hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fc8e259de934fd2bba8d8d85b352f2742268e755
2,214
cpp
C++
pure_pursuit_core/src/PathTracker.cpp
EricWang1hitsz/se2_navigation
081ef6700d58a2fcb81164013bf8ee309f7e202b
[ "BSD-3-Clause" ]
null
null
null
pure_pursuit_core/src/PathTracker.cpp
EricWang1hitsz/se2_navigation
081ef6700d58a2fcb81164013bf8ee309f7e202b
[ "BSD-3-Clause" ]
null
null
null
pure_pursuit_core/src/PathTracker.cpp
EricWang1hitsz/se2_navigation
081ef6700d58a2fcb81164013bf8ee309f7e202b
[ "BSD-3-Clause" ]
null
null
null
/* * PathTracker.cpp * * Created on: Mar 20, 2020 * Author: jelavice */ #include "pure_pursuit_core/path_tracking/PathTracker.hpp" #include <iostream> #include "pure_pursuit_core/heading_control/HeadingController.hpp" #include "pure_pursuit_core/math.hpp" #include "pure_pursuit_core/path_tracking/PathPreprocessor.hpp" #include "pure_pursuit_core/path_tracking/ProgressValidator.hpp" #include "pure_pursuit_core/velocity_control/LongitudinalVelocityController.hpp" namespace pure_pursuit { void PathTracker::setHeadingController(std::shared_ptr<HeadingController> ctrl) { headingController_ = ctrl; } void PathTracker::setVelocityController(std::shared_ptr<LongitudinalVelocityController> ctrl) { velocityController_ = ctrl; } void PathTracker::setProgressValidator(std::shared_ptr<ProgressValidator> validator) { progressValidator_ = validator; } void PathTracker::setPathPreprocessor(std::shared_ptr<PathPreprocessor> pathPreprocessor) { pathPreprocessor_ = pathPreprocessor; } double PathTracker::getTurningRadius() const { return turningRadius_; } double PathTracker::getYawRate() const { return yawRate_; } double PathTracker::getSteeringAngle() const { return steeringAngle_; } double PathTracker::getLongitudinalVelocity() const { return longitudinalVelocity_; } void PathTracker::importCurrentPath(const Path& path) { if (path.segment_.empty()) { throw std::runtime_error("empty path"); } currentPath_ = path; } bool PathTracker::initialize() { return true; } bool PathTracker::advance() { if (currentPath_.segment_.empty()) { std::cerr << "PathTracker:: trying to track empty path" << std::endl; return false; } advanceStateMachine(); // std::cout << "Advanced state machine" << std::endl; bool result = advanceControllers(); // std::cout << "Advanced controllers, status: " << std::boolalpha << result << std::endl; return result; } void PathTracker::updateRobotState(const RobotState& robotState) { currentRobotState_ = robotState; } bool PathTracker::isTrackingFinished() const { return progressValidator_->isPathTrackingFinished(currentPath_, currentRobotState_, currentPathSegmentId_); } } /* namespace pure_pursuit */
28.025316
109
0.765583
EricWang1hitsz
fc92983a4fbc4cadfe22630b95519c852898c683
2,125
cpp
C++
trunk/ProjectFootball/src/audio/CPlayListSystem.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
trunk/ProjectFootball/src/audio/CPlayListSystem.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
trunk/ProjectFootball/src/audio/CPlayListSystem.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
/****************************************************************************** * Copyright (C) 2007 - Ikaro Games www.ikarogames.com * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * * ******************************************************************************/ #include "CPlayListSystem.h" CPlayListSystem::CPlayListSystem() { } CPlayListSystem::~CPlayListSystem() { } void CPlayListSystem::addTrack(IAudioFile * audioFile) { } void CPlayListSystem::deleteTrack(int pos) { } CPlayListSystem * CPlayListSystem::getInstance() { return 0; } void CPlayListSystem::nextTrack() { } void CPlayListSystem::pausePlayback() { } void CPlayListSystem::previousTrack() { } void CPlayListSystem::startPlayback(int pos) { } void CPlayListSystem::stopPlayback() { }
25.60241
80
0.448
dividio
fc975fd192fac032affddf4be65010af4b7edcbf
1,369
cpp
C++
gstreaming/source/server/src/rtsp_server_util.cpp
hofbi/telecarla
020704a3b7087bc426f5ff97655c7e676c8b01bf
[ "MIT" ]
26
2020-06-09T18:28:07.000Z
2022-03-19T01:27:40.000Z
gstreaming/source/server/src/rtsp_server_util.cpp
hofbi/telecarla
020704a3b7087bc426f5ff97655c7e676c8b01bf
[ "MIT" ]
15
2020-06-21T21:04:44.000Z
2022-02-20T17:24:58.000Z
gstreaming/source/server/src/rtsp_server_util.cpp
hofbi/telecarla
020704a3b7087bc426f5ff97655c7e676c8b01bf
[ "MIT" ]
7
2020-06-21T11:55:53.000Z
2021-12-18T09:16:06.000Z
#include "rtsp_server_util.h" #include <glib.h> #include <ros/console.h> #include <sensor_msgs/image_encodings.h> #include "gst_server_context.h" namespace lmt { namespace server { void needData(GstElement* appSrc, guint /*unused*/, GstServerContext* context) { context->app->bufferNewData(appSrc); } void mediaConfigure(GstRTSPMediaFactory* /*factory*/, GstRTSPMedia* media, GstServerContext* context) { auto element = std::unique_ptr<GstElement, decltype(&gst_object_unref)>(gst_rtsp_media_get_element(media), gst_object_unref); GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(element.get()), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-rtsp-server"); auto appSrc = std::unique_ptr<GstElement, decltype(&gst_object_unref)>( gst_bin_get_by_name_recurse_up(GST_BIN(element.get()), context->app->getName().c_str()), gst_object_unref); context->encoder->configureEncoderElement(std::unique_ptr<GstElement>( gst_bin_get_by_name_recurse_up(GST_BIN(element.get()), context->encoder->getName().c_str()))); gst_util_set_object_arg(G_OBJECT(appSrc.get()), "format", "time"); g_object_set_data_full(G_OBJECT(media), "my-extra-data", context->app.get(), (GDestroyNotify)g_free); g_signal_connect(appSrc.get(), "need-data", (GCallback)needData, context); ROS_INFO("Media configured done"); } } // namespace server } // namespace lmt
37
118
0.745069
hofbi
fc981c53fabc0c784fc498dab6ff4051d4f55b06
28,217
cpp
C++
dist/wcjukebox/src/main.cpp
Bekenn/wcdx
148bda0c17b9a977e2ef90f27d48b206f89498da
[ "MIT" ]
14
2015-01-13T18:33:37.000Z
2022-01-10T22:17:41.000Z
dist/wcjukebox/src/main.cpp
Bekenn/wcdx
148bda0c17b9a977e2ef90f27d48b206f89498da
[ "MIT" ]
5
2020-07-12T22:54:11.000Z
2022-01-30T12:18:56.000Z
dist/wcjukebox/src/main.cpp
Bekenn/wcdx
148bda0c17b9a977e2ef90f27d48b206f89498da
[ "MIT" ]
1
2019-05-24T22:18:10.000Z
2019-05-24T22:18:10.000Z
#include "wcaudio_stream.h" #include "wave.h" #include <stdext/array_view.h> #include <stdext/file.h> #include <stdext/scope_guard.h> #include <stdext/string.h> #include <stdext/utility.h> #include <filesystem> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> #include <string_view> #include <unordered_map> #include <utility> #include <cstdlib> #include <cstddef> using namespace std::literals; namespace { enum : uint32_t { mode_none = 0x000, mode_track = 0x001, mode_wc2 = 0x002, mode_trigger = 0x004, mode_intensity = 0x008, mode_stream = 0x010, mode_show_tracks = 0x020, mode_show_triggers = 0x040, mode_wav = 0x080, mode_loop = 0x100, mode_single = 0x200, mode_debug_info = 0x400 }; struct program_options { uint32_t program_mode = mode_none; int track = -1; const wchar_t* stream_path = nullptr; const wchar_t* wav_path = nullptr; uint8_t trigger = no_trigger; uint8_t intensity = 15; // default for WC1 (selects patrol music) int loops = -1; }; class usage_error : public std::runtime_error { using runtime_error::runtime_error; }; void show_usage(const wchar_t* invocation); void diagnose_mode(uint32_t mode); void diagnose_unrecognized(const wchar_t* str); void show_tracks(program_options& options); void select_track(program_options& options); int parse_int(const wchar_t* str); } int wmain(int argc, wchar_t* argv[]) { std::wstring invocation = argc > 0 ? std::filesystem::path(argv[0]).filename() : "wcjukebox"; try { if (argc < 2) { show_usage(invocation.c_str()); return EXIT_SUCCESS; } program_options options; for (const wchar_t* const* arg = &argv[1]; *arg != nullptr; ++arg) { if ((*arg)[0] == L'-' || (*arg)[0] == L'/') { if (*arg + 1 == L"track"sv) { if ((options.program_mode & mode_track) != 0) throw usage_error("The -track option can only be used once."); options.program_mode |= mode_track; diagnose_mode(options.program_mode); auto game = *++arg; if (game == L"wc2"sv) options.program_mode |= mode_wc2; else if (game != L"wc1"sv) throw usage_error("The -track option must be followed by 'wc1' or 'wc2'."); options.track = parse_int(*++arg); } else if (*arg + 1 == L"trigger"sv) { if ((options.program_mode & mode_trigger) != 0) throw usage_error("The -trigger option can only be used once."); options.program_mode |= mode_trigger; diagnose_mode(options.program_mode); auto value = parse_int(*++arg); if (value < 0 || unsigned(value) > 0xFF) throw usage_error("Trigger must be between 0 and 255."); options.trigger = uint8_t(value); } else if (*arg + 1 == L"show-tracks"sv) { if ((options.program_mode & mode_show_tracks) != 0) throw usage_error("The -show-tracks option can only be used once."); options.program_mode |= mode_show_tracks; diagnose_mode(options.program_mode); auto game = *++arg; if (game == L"wc2"sv) options.program_mode |= mode_wc2; else if (game != L"wc1"sv) throw usage_error("The -show-tracks option must be followed by 'wc1' or 'wc2'."); } else if (*arg + 1 == L"show-triggers"sv) { if ((options.program_mode & mode_show_triggers) != 0) throw usage_error("The -show-triggers option can only be used once."); options.program_mode |= mode_show_triggers; diagnose_mode(options.program_mode); options.stream_path = *++arg; if (options.stream_path == nullptr) throw usage_error("Expected STR file path."); } else if (*arg + 1 == L"o"sv) { if ((options.program_mode & mode_wav) != 0) throw usage_error("The -o option can only be used once."); options.program_mode |= mode_wav; diagnose_mode(options.program_mode); options.wav_path = *++arg; if (options.wav_path == nullptr) throw usage_error("Expected WAV file path."); } else if (*arg + 1 == L"intensity"sv) { if ((options.program_mode & mode_intensity) != 0) throw usage_error("The -intensity option can only be used once."); options.program_mode |= mode_intensity; diagnose_mode(options.program_mode); auto value = parse_int(*++arg); if (value < 0 || unsigned(value) > 100) throw usage_error("Intensity must be between 0 and 100."); options.intensity = uint8_t(value); } else if (*arg + 1 == L"loop"sv) { if ((options.program_mode & mode_loop) != 0) throw usage_error("The -loop option can only be used once."); options.program_mode |= mode_loop; diagnose_mode(options.program_mode); options.loops = parse_int(*++arg); if (options.loops < 0) throw usage_error("The -loop option cannot be negative."); } else if (*arg + 1 == L"single"sv) { if ((options.program_mode & mode_single) != 0) throw usage_error("The -single option can only be used once."); options.program_mode |= mode_single; diagnose_mode(options.program_mode); } else if (*arg + 1 == L"debug-info"sv) { if ((options.program_mode & mode_debug_info) != 0) throw usage_error("The debug-info option can only be used once."); options.program_mode |= mode_debug_info; diagnose_mode(options.program_mode); } else diagnose_unrecognized(*arg); } else { if ((options.program_mode & mode_stream) != 0) diagnose_unrecognized(*arg); options.program_mode |= mode_stream; diagnose_mode(options.program_mode); options.stream_path = *arg; } } if ((options.program_mode & (mode_track | mode_stream | mode_show_tracks | mode_show_triggers)) == 0) throw usage_error("Missing required options."); if ((options.program_mode & mode_show_tracks) != 0) { show_tracks(options); return EXIT_SUCCESS; } if ((options.program_mode & mode_track) != 0) select_track(options); stdext::file_input_stream file(options.stream_path); wcaudio_stream stream(file); if ((options.program_mode & mode_show_triggers) != 0) { std::cout << "Available triggers:"; for (auto trigger : stream.triggers()) std::cout << ' ' << unsigned(trigger); std::cout << "\nAvailable intensities:"; for (auto intensity : stream.intensities()) std::cout << ' ' << unsigned(intensity); std::cout << '\n'; return EXIT_SUCCESS; } std::unordered_map<uint32_t, unsigned> chunk_frame_map; chunk_frame_map.reserve(128); stream.on_next_chunk([&](uint32_t chunk_index, unsigned frame_count) { chunk_frame_map.insert({ chunk_index, frame_count }); }); stream.on_loop([&](uint32_t chunk_index, unsigned frame_count) { stdext::discard(frame_count); if ((options.program_mode & mode_debug_info) != 0) { std::cout << "Loop to chunk " << chunk_index << " (frame index " << chunk_frame_map[chunk_index] << ')' << std::endl; } return options.loops < 0 || options.loops-- != 0; }); stream.on_start_track([&](uint32_t chunk_index) { if ((options.program_mode & mode_debug_info) != 0) std::cout << "Start track at chunk " << chunk_index << std::endl; chunk_frame_map.insert({ chunk_index, 0 }); }); stream.on_next_track([&](uint32_t chunk_index, unsigned frame_count) { chunk_frame_map.insert({ chunk_index, frame_count }); if ((options.program_mode & mode_debug_info) != 0) std::cout << "Switch to track at chunk " << chunk_index << std::endl; return (options.program_mode & mode_single) == 0; }); stream.on_prev_track([&](unsigned frame_count) { stdext::discard(frame_count); if ((options.program_mode & mode_debug_info) != 0) std::cout << "Return to previous track" << std::endl; }); stream.on_end_of_stream([&](unsigned frame_count) { stdext::discard(frame_count); if ((options.program_mode & mode_debug_info) != 0) std::cout << "End of stream" << std::endl; }); if ((options.program_mode & mode_wav) == 0) std::cout << "Press Ctrl-C to end playback." << std::endl; stream.select(options.trigger, options.intensity); if ((options.program_mode & mode_wav) != 0) { if (options.loops < 0) options.loops = 0; stdext::file_output_stream out(options.wav_path); write_wave(out, stream, stream.channels(), stream.sample_rate(), stream.bits_per_sample(), stream.buffer_size()); } else play_wave(stream, stream.channels(), stream.sample_rate(), stream.bits_per_sample(), stream.buffer_size()); return EXIT_SUCCESS; } catch (const usage_error& e) { std::cerr << "Error: " << e.what() << '\n'; show_usage(invocation.c_str()); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << '\n'; } catch (...) { std::cerr << "Unknown error\n"; } return EXIT_FAILURE; } namespace { enum stream_archive { invalid = -1, wc1_preflight, wc1_postflight, wc1_mission, wc2_gameflow, wc2_gametwo, wc2_spaceflight }; struct track_desc { stream_archive archive; uint8_t trigger; }; constexpr const wchar_t* stream_filenames[] { L"STREAMS\\PREFLITE.STR", L"STREAMS\\POSFLITE.STR", L"STREAMS\\MISSION.STR", L"STREAMS\\GAMEFLOW.STR", L"STREAMS\\GAMETWO.STR", L"STREAMS\\SPACEFLT.STR" }; // Maps from a track number to a stream archive and trigger number // See StreamLoadTrack and GetStreamTrack in Wing1.i64 constexpr track_desc wc1_track_map[] = { { stream_archive::wc1_mission, no_trigger }, // 0 - Regular Combat { stream_archive::wc1_mission, no_trigger }, // 1 - Being Tailed { stream_archive::wc1_mission, no_trigger }, // 2 - Tailing An Enemy { stream_archive::wc1_mission, no_trigger }, // 3 - Missile Tracking You { stream_archive::wc1_mission, no_trigger }, // 4 - You're Severely Damaged - Floundering { stream_archive::wc1_mission, no_trigger }, // 5 - Intense Combat { stream_archive::wc1_mission, 6 }, // 6 - Target Hit { stream_archive::wc1_mission, 7 }, // 7 - Ally Killed { stream_archive::wc1_mission, 8 }, // 8 - Your Wingman's been hit { stream_archive::wc1_mission, 9 }, // 9 - Enemy Ace Killed { stream_archive::wc1_mission, 10 }, // 10 - Overall Victory { stream_archive::wc1_mission, 11 }, // 11 - Overall Defeat { stream_archive::wc1_mission, no_trigger }, // 12 - Returning Defeated { stream_archive::wc1_mission, no_trigger }, // 13 - Returning Normal { stream_archive::wc1_mission, no_trigger }, // 14 - Returning Triumphant { stream_archive::wc1_mission, no_trigger }, // 15 - Flying to Dogfight { stream_archive::wc1_mission, no_trigger }, // 16 - Goal Line - Defending the Claw { stream_archive::wc1_mission, no_trigger }, // 17 - Strike Mission - Go Get 'Em { stream_archive::wc1_mission, no_trigger }, // 18 - Grim or Escort Mission { stream_archive::wc1_preflight, no_trigger }, // 19 - OriginFX (actually, fanfare) { stream_archive::wc1_preflight, 1 }, // 20 - Arcade Theme { stream_archive::wc1_preflight, 4 }, // 21 - Arcade Victory { stream_archive::wc1_preflight, 3 }, // 22 - Arcade Death { stream_archive::wc1_preflight, no_trigger }, // 23 - Fanfare { stream_archive::wc1_preflight, 5 }, // 24 - Briefing intro { stream_archive::wc1_preflight, 6 }, // 25 - Briefing middle { stream_archive::wc1_preflight, 7 }, // 26 - Briefing end { stream_archive::wc1_mission, 27 }, // 27 - Scramble through launch { stream_archive::wc1_postflight, no_trigger }, // 28 - Landing { stream_archive::wc1_postflight, 0, }, // 29 - Medium Damage Assessment { stream_archive::wc1_preflight, 0 }, // 30 - Rec Room { stream_archive::wc1_mission, 31 }, // 31 - Eject - Imminent Rescue { stream_archive::wc1_mission, 32 }, // 32 - Funeral { stream_archive::wc1_postflight, 2 }, // 33 - Debriefing - Successful { stream_archive::wc1_postflight, 1 }, // 34 - Debriefing - Unsuccessful { stream_archive::wc1_preflight, 2 }, // 35 - Barracks - Go To Sleep You Pilots { stream_archive::wc1_postflight, 3 }, // 36 - Commander's Office { stream_archive::wc1_postflight, 4 }, // 37 - Medel Ceremony - General { stream_archive::wc1_postflight, 5 }, // 38 - Medal Ceremony - Purple Heart { stream_archive::wc1_postflight, 7 }, // 39 - Minor Bravery { stream_archive::wc1_postflight, 6 }, // 40 - Major Bravery }; constexpr track_desc wc2_track_map[] = { { stream_archive::wc2_spaceflight, no_trigger }, // 0 - Combat 1 { stream_archive::wc2_spaceflight, no_trigger }, // 1 - Combat 2 { stream_archive::wc2_spaceflight, no_trigger }, // 2 - Combat 3 { stream_archive::wc2_spaceflight, no_trigger }, // 3 - Combat 4 { stream_archive::wc2_spaceflight, no_trigger }, // 4 - Combat 5 { stream_archive::wc2_spaceflight, no_trigger }, // 5 - Combat 6 { stream_archive::wc2_spaceflight, 6 }, // 6 - Victorious Combat { stream_archive::wc2_spaceflight, 7 }, // 7 - Tragedy { stream_archive::wc2_spaceflight, 8 }, // 8 - Dire straits { stream_archive::wc2_spaceflight, 9 }, // 9 - Scratch one fighter { stream_archive::wc2_spaceflight, 10 }, // 10 - Defeated fleeing enemy { stream_archive::wc2_spaceflight, 11 }, // 11 - Wingman death { stream_archive::wc2_spaceflight, no_trigger }, // 12 - Returning defeated { stream_archive::wc2_spaceflight, no_trigger }, // 13 - Returning successful { stream_archive::wc2_spaceflight, no_trigger }, // 14 - Returning jubilant { stream_archive::wc2_spaceflight, no_trigger }, // 15 - Mission 1 { stream_archive::wc2_spaceflight, no_trigger }, // 16 - Mission 2 { stream_archive::wc2_spaceflight, no_trigger }, // 17 - Mission 3 { stream_archive::wc2_spaceflight, no_trigger }, // 18 - Mission 4 { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::invalid, no_trigger }, { stream_archive::wc2_spaceflight, no_trigger }, // 27 - Scramble { stream_archive::wc2_gametwo, 28 }, // 28 - Landing { stream_archive::wc2_gametwo, 29 }, // 29 - Damage Assessment { stream_archive::invalid, no_trigger }, { stream_archive::wc2_spaceflight, no_trigger }, // 31 - Eject { stream_archive::wc2_spaceflight, no_trigger }, // 32 - Death { stream_archive::wc2_gametwo, 33 }, // 33 - debriefing (successful) { stream_archive::wc2_gametwo, 34 }, // 34 - debriefing (failed) { stream_archive::invalid, no_trigger }, { stream_archive::wc2_gametwo, 36 }, // 36 - Briefing 2 { stream_archive::wc2_gametwo, 37 }, // 37 - medal (valor?) { stream_archive::wc2_gametwo, 38 }, // 38 - medal (golden sun?) { stream_archive::wc2_gametwo, 39 }, // 39 - another medal { stream_archive::wc2_gametwo, 40 }, // 40 - big medal { stream_archive::wc2_spaceflight, no_trigger }, // 41 - Prologue { stream_archive::wc2_spaceflight, 42 }, // 42 - Torpedo lock { stream_archive::wc2_gameflow, 43 }, // 43 - Flight deck 1 { stream_archive::wc2_gameflow, 44 }, // 44 - Angel { stream_archive::wc2_gameflow, 45 }, // 45 - Jazz 1 { stream_archive::wc2_gameflow, 46 }, // 46 - Briefing { stream_archive::wc2_gameflow, 47 }, // 47 - Jump { stream_archive::wc2_gameflow, 48 }, // 48 - Prologue (quieter) { stream_archive::wc2_gameflow, 49 }, // 49 - Lounge 1 { stream_archive::wc2_gameflow, 50 }, // 50 - Jazz 2 { stream_archive::wc2_gameflow, 51 }, // 51 - Jazz 3 { stream_archive::wc2_gameflow, 52 }, // 52 - Jazz 4 { stream_archive::wc2_gameflow, 53 }, // 53 - Interlude 1 { stream_archive::wc2_gameflow, 54 }, // 54 - Theme { stream_archive::wc2_spaceflight, no_trigger }, // 55 - Bombing run { stream_archive::wc2_spaceflight, no_trigger }, // 56 - Final Mission { stream_archive::wc2_spaceflight, no_trigger }, // 57 - Fighting Thrakhath { stream_archive::wc2_gameflow, 58 }, // 58 - Kilrathi Theme { stream_archive::wc2_gametwo, 59 }, // 59 - Good Ending { stream_archive::wc2_gametwo, 60 }, // 60 - Lounge 2 { stream_archive::wc2_gameflow, 61 }, // 61 - End Credits { stream_archive::wc2_gameflow, 62 }, // 62 - Interlude 2 { stream_archive::wc2_gametwo, 63 }, // 63 - Jazz 5 { stream_archive::wc2_gametwo, 20 }, // 64 - Flight Deck 2 { stream_archive::wc2_gametwo, 21 }, // 65 - Sabotage // Bonus tracks { stream_archive::wc2_gameflow, 59 }, // 66 - Defeated fleeing enemy (alternate) { stream_archive::wc2_gameflow, 60 }, // 67 - Wingman death (alternate) { stream_archive::wc2_gameflow, 63 }, // 68 - Unknown { stream_archive::wc2_spaceflight, no_trigger }, // 69 - Jump (looping) }; void show_usage(const wchar_t* invocation) { std::wcout << L"Usage:\n" L" " << invocation << L" [<options>...] -track (wc1|wc2) <num>\n" L" " << invocation << L" [<options>...] -trigger <num> <filename>\n" L" " << invocation << L" -show-tracks (wc1|wc2)\n" L" " << invocation << L" -show-triggers <filename>\n" L"\n" L"The first form selects a music track to play. The command must be invoked from\n" L"the game directory (the same directory containing the STREAMS directory). The\n" L"correct stream file will be loaded automatically based on an internal mapping\n" L"from track number to stream file, trigger, and intensity values. To view the\n" L"mapping, use the -show-tracks option.\n" L"\n" L"The second form selects a track using the provided trigger value for the given\n" L"stream file. If the trigger is not provided, " << invocation << L" will play from the\n" L"first piece of audio data contained in the stream. If the intensity value is\n" L"not provided, a default value will be used. To view the list of triggers and\n" L"intensities supported by a given stream file, use the -show-triggers option.\n" L"This form may be used with any stream file.\n" L"\n" L"Options:\n" L" -o <filename>\n" L" Instead of playing music, write it to a WAV file.\n" L"\n" L" -intensity <num>\n" L" This value is used by the playback engine to handle transitions between\n" L" tracks. Some tracks are designed to transition to other specific tracks\n" L" upon completion, and this value determines which one that is. For example,\n" L" the scramble music from WC1 will transition to a track appropriate to a\n" L" given mission type based on the intensity value. If this value is not\n" L" provided, a default value will be used. For a list of supported triggers\n" L" and intensity values, use the -show-triggers option.\n" L"\n" L" -loop <num>\n" L" Continue playback until <num> loops have been completed. For instance,\n" L" -loop 0 will disable looping (causing a track to be played only once), and\n" L" -loop 1 will cause the track to repeat once (provided it has a loop point).\n" L" If the track does not have a loop point, this option is ignored. If this\n" L" option is not specified, the track will loop indefinitely.\n" L"\n" L" -single\n" L" Stop playback at transition points instead of following the transition to\n" L" the next track.\n" L"\n" L" -debug-info\n" L" Display information related to playback. The stream contains embedded\n" L" information that tells the player how to loop a track or how to progress\n" L" from one track to another. This information will be printed out as it is\n" L" encountered. If the -o option is being used, this option will also print\n" L" corresponding frame numbers in the output file.\n"; } void diagnose_mode(uint32_t mode) { if ((mode & (mode_track | mode_trigger)) == (mode_track | mode_trigger)) throw usage_error("The -trigger option cannot be used with -track."); if ((mode & (mode_track | mode_stream)) == (mode_track | mode_stream)) throw usage_error("Cannot specify a stream file with -track."); if ((mode & mode_show_tracks) != 0 && mode != mode_show_tracks) throw usage_error("The -show-tracks option cannot be used with other options."); if ((mode & mode_show_triggers) != 0 && (mode & ~mode_stream) != mode_show_triggers) throw usage_error("The -show-triggers option cannot be used with other options."); } void diagnose_unrecognized(const wchar_t* str) { std::ostringstream message; message << "Unexpected option: " << str; throw usage_error(std::move(message).str()); } void show_tracks(program_options& options) { stdext::array_view<const track_desc> track_map; if ((options.program_mode & mode_wc2) == 0) track_map = wc1_track_map; else track_map = wc2_track_map; std::wcout << L"Track | File | Trigger | Intensity\n" L"------|----------------------|---------|----------\n"; unsigned track_number = 0; for (auto entry : track_map) { at_scope_exit([&]{ ++track_number; }); if (entry.archive == stream_archive::invalid) continue; std::wcout << std::setw(5) << track_number << L" | "; std::wcout << std::setw(20) << std::setiosflags(std::ios_base::left) << stream_filenames[entry.archive] << L" | "; std::wcout.unsetf(std::ios_base::adjustfield); std::wcout.width(7); if (entry.trigger == no_trigger) std::wcout << L""; else std::wcout << entry.trigger; std::wcout << L" | "; std::wcout.width(9); if (entry.trigger == no_trigger) std::wcout << (track_number == 69 ? 47 : track_number); else std::wcout << L""; std::wcout << L'\n'; } } void select_track(program_options& options) { stdext::array_view<const track_desc> track_map; if ((options.program_mode & mode_wc2) == 0) track_map = wc1_track_map; else track_map = wc2_track_map; if (options.track < 0 || unsigned(options.track) >= track_map.size()) { std::ostringstream message; message << "Track must be between 0 and " << track_map.size() - 1 << '.'; throw usage_error(std::move(message).str()); } if (track_map[options.track].archive == stream_archive::invalid) { std::ostringstream message; message << "There is no track " << options.track << '.'; throw std::runtime_error(std::move(message).str()); } options.stream_path = stream_filenames[track_map[options.track].archive]; options.trigger = track_map[options.track].trigger; if (options.trigger == no_trigger) { // There's no easy way to map this one, so hard-code it instead. if (options.track == 69) options.intensity = 47; else options.intensity = uint8_t(options.track); } } int parse_int(const wchar_t* str) { if (str == nullptr) throw usage_error("Expected number."); wchar_t* end; auto value = int(wcstol(str, &end, 10)); if (*end != '\0') { std::ostringstream message; message << "Unexpected argument: " << stdext::to_mbstring(str) << " (Expected number.)\n"; throw usage_error(std::move(message).str()); } return value; } }
45.806818
126
0.543077
Bekenn
fc9e4fa4dc39218ba8c4752be64df8309dee6445
1,604
cc
C++
Codeforces/731-DIV3/B.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Codeforces/731-DIV3/B.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Codeforces/731-DIV3/B.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned long long uInt; typedef unsigned uint; bool has_right_chars(string S) { sort(S.begin(), S.end()); const char start = 'a'; bool valid = true; for (int i = 0; i < S.size(); i++) { if (S[i] != char(start + i)) { valid = false; } } return valid; } int main(void) { int T; cin >> T; for (int t = 0; t < T; t++) { string S; cin >> S; bool valid = true; if (!has_right_chars(S)) { valid = false; } const char start = 'a'; vector<int> pos; for (int i = 0; i < S.size(); i++) { pos.push_back(S.find(char(start + i))); } for (int i = 0; i < pos.size(); i++) { bool fine = false; for (int j = 0; j < i; j++) { if (abs(pos[i] - pos[j]) == 1) { fine = true; } } if (i > 0 && !fine) { valid = false; break; } } if (valid) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; }
20.05
67
0.413342
aajjbb
fc9eaf83c17806a7332ea13b23900f0c24b80566
1,396
hpp
C++
include/builtins.hpp
samcoppini/Glass-Interpreter
373d1bf9d5fbed144b7198da1b065ded533f99cd
[ "BSL-1.0" ]
null
null
null
include/builtins.hpp
samcoppini/Glass-Interpreter
373d1bf9d5fbed144b7198da1b065ded533f99cd
[ "BSL-1.0" ]
null
null
null
include/builtins.hpp
samcoppini/Glass-Interpreter
373d1bf9d5fbed144b7198da1b065ded533f99cd
[ "BSL-1.0" ]
null
null
null
#ifndef BUILTINS_HPP #define BUILTINS_HPP #include "class.hpp" #include "variable.hpp" #include <map> #include <string> // An enumeration of all of the built-in functions enum class Builtin: int { // Functions in the built-in I class InputLine, // I.l InputChar, // I.c InputEof, // I.e // Functions in the built-in A class MathAdd, // A.a MathSub, // A.s MathMult, // A.m MathDiv, // A.d MathMod, // A.mod MathFloor, // A.f MathEqual, // A.e MathNotEqual, // A.ne MathLessThan, // A.lt MathLessOrEqual, // A.le MathGreaterThan, // A.gt MathGreaterOrEqual, // A.ge // Functions in the built-in O class OutputStr, // O.o OutputNumber, // O.on // Functions in the built-in S class StrLength, // S.l StrIndex, // S.i StrReplace, // S.si StrConcatenate, // S.a StrSplit, // S.d StrEqual, // S.e StrNumtoChar, // S.ns StrChartoNum, // S.sn // Functions in the built-in V class VarNew, // V.n VarDelete // V.d }; ClassMap get_builtins(); void remove_builtins(ClassMap &classes); bool handle_builtin(Builtin type, std::vector<Variable> &stack, VarMap &globals); std::string builtin_text(Builtin type, const std::string &temp_name); #endif
24.928571
81
0.570917
samcoppini
fc9fd6a682038a09ad1ff2cb82ae7c7ffeb9e855
2,192
cpp
C++
examples/RpgDemo/fireball.cpp
RonenNess/ness-engine
5e6ea6c2fb59c2ccaef8cebcd133e717aec7d739
[ "Zlib" ]
30
2015-05-03T21:30:59.000Z
2022-01-12T04:25:06.000Z
examples/RpgDemo/fireball.cpp
RonenNess/ness-engine
5e6ea6c2fb59c2ccaef8cebcd133e717aec7d739
[ "Zlib" ]
1
2015-08-20T14:35:06.000Z
2015-08-20T21:17:21.000Z
examples/RpgDemo/fireball.cpp
RonenNess/ness-engine
5e6ea6c2fb59c2ccaef8cebcd133e717aec7d739
[ "Zlib" ]
5
2015-02-05T11:53:51.000Z
2020-03-08T10:57:24.000Z
#include "fireball.h" #include "character.h" #define FIREBALL_ANIM_STEPS 3 #define FIREBALL_DIRECTIONS_COUNT 4 Fireball::Fireball(Ness::LightNodePtr& lightNode, Ness::NodePtr& parent, const Ness::Point& position, const int direction) { // create sprite and animator m_direction = direction; m_parent = parent; m_sprite = parent->create_animated_sprite("gfx/fireball.png"); m_sprite->set_anchor(Ness::Point(0.5f, 0.5f)); m_sprite->set_blend_mode(Ness::BLEND_MODE_BLEND); m_sprite->set_position(position - Ness::Point(0, 50)); m_sprite->set_source_from_sprite_sheet(Ness::Pointi(0, 0), Ness::Pointi(3, 4), true); m_sprite->register_animator(ness_make_ptr<Ness::Animators::AnimatorSprite>(m_sprite, Ness::Sizei(FIREBALL_ANIM_STEPS, FIREBALL_DIRECTIONS_COUNT), Ness::Pointi(0, direction), FIREBALL_ANIM_STEPS, 10.0f, Ness::Animators::SPRITE_ANIM_END_REPEAT)); // distance left before self-terminate m_distance_left = 1000.0f; // create light m_light_node = lightNode; m_light = lightNode->create_light("../ness-engine/resources/gfx/light_round.jpg", Ness::Color::RED); } Fireball::~Fireball() { m_sprite->parent()->remove(m_sprite); m_light_node->remove(m_light); } void Fireball::do_animation(Ness::Renderer* renderer) { // move fireball float factor = 350.0f; switch (m_direction) { case DIRECTION_DOWN: m_sprite->set_position(m_sprite->get_position() + Ness::Point(0, renderer->time_factor() * factor)); break; case DIRECTION_UP: m_sprite->set_position(m_sprite->get_position() - Ness::Point(0, renderer->time_factor() * factor)); break; case DIRECTION_LEFT: m_sprite->set_position(m_sprite->get_position() - Ness::Point(renderer->time_factor() * factor, 0)); break; case DIRECTION_RIGHT: m_sprite->set_position(m_sprite->get_position() + Ness::Point(renderer->time_factor() * factor, 0)); break; } // reduce distance left to go m_distance_left -= renderer->time_factor() * factor; if (m_distance_left < 0.0f) remove_from_animation_queue(); // fix zindex m_sprite->set_zindex(m_sprite->get_position().y + 50); // fix light position m_light->set_position(m_sprite->get_position()); m_light->set_zindex(m_sprite->get_zindex()); }
32.716418
147
0.74635
RonenNess
fca225d128299273e9c10512d3605b9a118b9324
129
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/bench/btl/libs/BLAS/main.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/bench/btl/libs/BLAS/main.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/bench/btl/libs/BLAS/main.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:cd4a0e77cbc83e004385d988fa1135793c26b4f6a51cb6be3764696a721e007d size 2963
32.25
75
0.883721
initialz
fca29685edccd4fc21a8a33358f81729eab0c509
8,845
cpp
C++
obelus/client/math/math.cpp
monthyx1337/obelus-hack
8e83eb89ef56788c1b9c5af66b815824d17f309d
[ "MIT" ]
36
2021-07-08T01:30:44.000Z
2022-03-25T13:16:59.000Z
obelus/client/math/math.cpp
monthyx1337/obelus-hack
8e83eb89ef56788c1b9c5af66b815824d17f309d
[ "MIT" ]
2
2021-09-11T05:11:55.000Z
2022-01-28T07:49:39.000Z
obelus/client/math/math.cpp
monthyx1337/obelus-hack
8e83eb89ef56788c1b9c5af66b815824d17f309d
[ "MIT" ]
14
2021-07-08T00:11:12.000Z
2022-03-20T11:10:17.000Z
#include "../utilities/csgo.hpp" #include "../../hack/features/visuals/esp.h" bool math::GetBoundingBox(BaseEntity* entity, bbox_t& box) { const auto collideable = entity->Collideables(); if (collideable == nullptr) return false; vec3_t top, down, air, s[2]; vec3_t adjust = vec3_t(0, 0, -15) * entity->DuckAmount(); if (!(entity->Flags() & FL_ONGROUND) && (entity->MoveType() != MOVETYPE_LADDER)) air = vec3_t(0, 0, 10); else air = vec3_t(0, 0, 0); down = entity->AbsOrigin() + air; top = down + vec3_t(0, 0, 72) + adjust; if (visuals::WorldToScreen(top, s[1]) && visuals::WorldToScreen(down, s[0])) { vec3_t delta = s[1] - s[0]; box.h = fabsf(delta.y) + 6; box.w = box.h / 2 + 5; box.x = s[1].x - (box.w / 2) + 2; box.y = s[1].y - 1; return true; } return false; } vec3_t math::calculate_angle(const vec3_t& source, const vec3_t& destination, const vec3_t& viewAngles) { vec3_t delta = source - destination; auto radians_to_degrees = [](float radians) { return radians * 180 / static_cast<float>(M_PI); }; vec3_t angles; angles.x = radians_to_degrees(atanf(delta.z / std::hypotf(delta.x, delta.y))) - viewAngles.x; angles.y = radians_to_degrees(atanf(delta.y / delta.x)) - viewAngles.y; angles.z = 0.0f; if (delta.x >= 0.0) angles.y += 180.0f; angles.normalize_aimbot(); return angles; } void math::FixMove(UserCmd* m_pcmd, vec3_t wish_angle) { vec3_t view_fwd, view_right, view_up, cmd_fwd, cmd_right, cmd_up; auto viewangles = m_pcmd->viewangles; viewangles.normalized(); math::angle_vectors(wish_angle, &view_fwd, &view_right, &view_up); math::angle_vectors(viewangles, &cmd_fwd, &cmd_right, &cmd_up); float v8 = sqrtf((view_fwd.x * view_fwd.x) + (view_fwd.y * view_fwd.y)); float v10 = sqrtf((view_right.x * view_right.x) + (view_right.y * view_right.y)); float v12 = sqrtf(view_up.z * view_up.z); vec3_t norm_view_fwd((1.f / v8) * view_fwd.x, (1.f / v8) * view_fwd.y, 0.f); vec3_t norm_view_right((1.f / v10) * view_right.x, (1.f / v10) * view_right.y, 0.f); vec3_t norm_view_up(0.f, 0.f, (1.f / v12) * view_up.z); float v14 = sqrtf((cmd_fwd.x * cmd_fwd.x) + (cmd_fwd.y * cmd_fwd.y)); float v16 = sqrtf((cmd_right.x * cmd_right.x) + (cmd_right.y * cmd_right.y)); float v18 = sqrtf(cmd_up.z * cmd_up.z); vec3_t norm_cmd_fwd((1.f / v14) * cmd_fwd.x, (1.f / v14) * cmd_fwd.y, 0.f); vec3_t norm_cmd_right((1.f / v16) * cmd_right.x, (1.f / v16) * cmd_right.y, 0.f); vec3_t norm_cmd_up(0.f, 0.f, (1.f / v18) * cmd_up.z); float v22 = norm_view_fwd.x * m_pcmd->forwardmove; float v26 = norm_view_fwd.y * m_pcmd->forwardmove; float v28 = norm_view_fwd.z * m_pcmd->forwardmove; float v24 = norm_view_right.x * m_pcmd->sidemove; float v23 = norm_view_right.y * m_pcmd->sidemove; float v25 = norm_view_right.z * m_pcmd->sidemove; float v30 = norm_view_up.x * m_pcmd->upmove; float v27 = norm_view_up.z * m_pcmd->upmove; float v29 = norm_view_up.y * m_pcmd->upmove; m_pcmd->forwardmove = ((((norm_cmd_fwd.x * v24) + (norm_cmd_fwd.y * v23)) + (norm_cmd_fwd.z * v25)) + (((norm_cmd_fwd.x * v22) + (norm_cmd_fwd.y * v26)) + (norm_cmd_fwd.z * v28))) + (((norm_cmd_fwd.y * v30) + (norm_cmd_fwd.x * v29)) + (norm_cmd_fwd.z * v27)); m_pcmd->sidemove = ((((norm_cmd_right.x * v24) + (norm_cmd_right.y * v23)) + (norm_cmd_right.z * v25)) + (((norm_cmd_right.x * v22) + (norm_cmd_right.y * v26)) + (norm_cmd_right.z * v28))) + (((norm_cmd_right.x * v29) + (norm_cmd_right.y * v30)) + (norm_cmd_right.z * v27)); m_pcmd->upmove = ((((norm_cmd_up.x * v23) + (norm_cmd_up.y * v24)) + (norm_cmd_up.z * v25)) + (((norm_cmd_up.x * v26) + (norm_cmd_up.y * v22)) + (norm_cmd_up.z * v28))) + (((norm_cmd_up.x * v30) + (norm_cmd_up.y * v29)) + (norm_cmd_up.z * v27)); static auto cl_forwardspeed = interfaces::console->FindVar(XOR("cl_forwardspeed")); static auto cl_sidespeed = interfaces::console->FindVar(XOR("cl_sidespeed")); static auto cl_upspeed = interfaces::console->FindVar(XOR("cl_upspeed")); m_pcmd->forwardmove = std::clamp(m_pcmd->forwardmove, -cl_forwardspeed->GetFloat(), cl_forwardspeed->GetFloat()); m_pcmd->sidemove = std::clamp(m_pcmd->sidemove, -cl_sidespeed->GetFloat(), cl_sidespeed->GetFloat()); m_pcmd->upmove = std::clamp(m_pcmd->upmove, -cl_upspeed->GetFloat(), cl_upspeed->GetFloat()); } vec3_t math::calculate_angle(vec3_t& a, vec3_t& b) { vec3_t angles; vec3_t delta; delta.x = (a.x - b.x); delta.y = (a.y - b.y); delta.z = (a.z - b.z); double hyp = sqrt(delta.x * delta.x + delta.y * delta.y); angles.x = (float)(atanf(delta.z / hyp) * 57.295779513082f); angles.y = (float)(atanf(delta.y / delta.x) * 57.295779513082f); angles.z = 0.0f; if (delta.x >= 0.0) { angles.y += 180.0f; } return angles; } void math::sin_cos(float r, float* s, float* c) { *s = sin(r); *c = cos(r); } vec3_t math::angle_vector(vec3_t angle) { auto sy = sin(angle.y / 180.f * static_cast<float>(M_PI)); auto cy = cos(angle.y / 180.f * static_cast<float>(M_PI)); auto sp = sin(angle.x / 180.f * static_cast<float>(M_PI)); auto cp = cos(angle.x / 180.f * static_cast<float>(M_PI)); return vec3_t(cp * cy, cp * sy, -sp); } void math::transform_vector(vec3_t & a, matrix_t & b, vec3_t & out) { out.x = a.dot(b.mat_val[0]) + b.mat_val[0][3]; out.y = a.dot(b.mat_val[1]) + b.mat_val[1][3]; out.z = a.dot(b.mat_val[2]) + b.mat_val[2][3]; } void math::vector_angles(vec3_t & forward, vec3_t & angles) { vec3_t view; if (!forward[0] && !forward[1]) { view[0] = 0.0f; view[1] = 0.0f; } else { view[1] = atan2(forward[1], forward[0]) * 180.0f / M_PI; if (view[1] < 0.0f) view[1] += 360.0f; view[2] = sqrt(forward[0] * forward[0] + forward[1] * forward[1]); view[0] = atan2(forward[2], view[2]) * 180.0f / M_PI; } angles[0] = -view[0]; angles[1] = view[1]; angles[2] = 0.f; } void math::angle_vectors(const vec3_t& angles, vec3_t& forward) { float sp, sy, cp, cy; sy = sin(DEG2RAD(angles[1])); cy = cos(DEG2RAD(angles[1])); sp = sin(DEG2RAD(angles[0])); cp = cos(DEG2RAD(angles[0])); forward.x = cp * cy; forward.y = cp * sy; forward.z = -sp; } void math::angle_vectors(vec3_t & angles, vec3_t * forward, vec3_t * right, vec3_t * up) { float sp, sy, sr, cp, cy, cr; sin_cos(DEG2RAD(angles.x), &sp, &cp); sin_cos(DEG2RAD(angles.y), &sy, &cy); sin_cos(DEG2RAD(angles.z), &sr, &cr); if (forward) { forward->x = cp * cy; forward->y = cp * sy; forward->z = -sp; } if (right) { right->x = -1 * sr * sp * cy + -1 * cr * -sy; right->y = -1 * sr * sp * sy + -1 * cr * cy; right->z = -1 * sr * cp; } if (up) { up->x = cr * sp * cy + -sr * -sy; up->y = cr * sp * sy + -sr * cy; up->z = cr * cp; } } vec3_t math::vector_add(vec3_t & a, vec3_t & b) { return vec3_t(a.x + b.x, a.y + b.y, a.z + b.z); } void math::angle_matrix(const vec3_t& ang, const vec3_t& pos, matrix_t& out) { g::AngleMatrix(ang, out); out.set_origin(pos); } vec3_t math::vector_subtract(vec3_t & a, vec3_t & b) { return vec3_t(a.x - b.x, a.y - b.y, a.z - b.z); } vec3_t math::vector_multiply(vec3_t & a, vec3_t & b) { return vec3_t(a.x * b.x, a.y * b.y, a.z * b.z); } vec3_t math::vector_divide(vec3_t & a, vec3_t & b) { return vec3_t(a.x / b.x, a.y / b.y, a.z / b.z); } bool math::screen_transform(const vec3_t & point, vec3_t & screen) { auto matrix = interfaces::engine->world_to_screen_matrix(); float w = matrix[3][0] * point.x + matrix[3][1] * point.y + matrix[3][2] * point.z + matrix[3][3]; screen.x = matrix[0][0] * point.x + matrix[0][1] * point.y + matrix[0][2] * point.z + matrix[0][3]; screen.y = matrix[1][0] * point.x + matrix[1][1] * point.y + matrix[1][2] * point.z + matrix[1][3]; screen.z = 0.0f; int inverse_width = static_cast<int>((w < 0.001f) ? -1.0f / w : 1.0f / w); screen.x *= inverse_width; screen.y *= inverse_width; return (w < 0.001f); } bool math::world_to_screen(const vec3_t & origin, vec2_t & screen) { static std::uintptr_t view_matrix; if ( !view_matrix ) view_matrix = *reinterpret_cast< std::uintptr_t* >( reinterpret_cast< std::uintptr_t >( pattern::Scan( XOR("client.dll"), XOR("0F 10 05 ? ? ? ? 8D 85 ? ? ? ? B9") ) ) + 3 ) + 176; const auto& matrix = *reinterpret_cast< view_matrix_t* >( view_matrix ); const auto w = matrix.m[ 3 ][ 0 ] * origin.x + matrix.m[ 3 ][ 1 ] * origin.y + matrix.m[ 3 ][ 2 ] * origin.z + matrix.m[ 3 ][ 3 ]; if ( w < 0.001f ) return false; int x, y; interfaces::engine->GetScreenSize( x, y ); screen.x = static_cast<float>(x) / 2.0f; screen.y = static_cast<float>(y) / 2.0f; screen.x *= 1.0f + ( matrix.m[ 0 ][ 0 ] * origin.x + matrix.m[ 0 ][ 1 ] * origin.y + matrix.m[ 0 ][ 2 ] * origin.z + matrix.m[ 0 ][ 3 ] ) / w; screen.y *= 1.0f - ( matrix.m[ 1 ][ 0 ] * origin.x + matrix.m[ 1 ][ 1 ] * origin.y + matrix.m[ 1 ][ 2 ] * origin.z + matrix.m[ 1 ][ 3 ] ) / w; return true; }
32.638376
181
0.625438
monthyx1337
fca2dcab8b0d5d7d76124ae2a81cb36384774487
12,242
cc
C++
chrome/credential_provider/extension/task_manager_unittests.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/credential_provider/extension/task_manager_unittests.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/credential_provider/extension/task_manager_unittests.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <atlcomcli.h> #include <windows.h> #include "base/bind.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/task_environment.h" #include "chrome/credential_provider/extension/extension_utils.h" #include "chrome/credential_provider/extension/task.h" #include "chrome/credential_provider/extension/task_manager.h" #include "chrome/credential_provider/gaiacp/gcp_utils.h" #include "chrome/credential_provider/gaiacp/reg_utils.h" #include "chrome/credential_provider/test/gcp_fakes.h" #include "testing/gtest/include/gtest/gtest.h" namespace credential_provider { namespace testing { class TaskManagerTest : public ::testing::Test { public: TaskManagerTest() {} void RunTasks() { fake_task_manager_.RunTasks(task_environment_.GetMainThreadTaskRunner()); } void SetUp() override { ScopedLsaPolicy::SetCreatorForTesting( fake_scoped_lsa_factory_.GetCreatorCallback()); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); } FakeTaskManager* fake_task_manager() { return &fake_task_manager_; } FakeOSUserManager* fake_os_user_manager() { return &fake_os_user_manager_; } base::test::SingleThreadTaskEnvironment* task_environment() { return &task_environment_; } private: FakeTaskManager fake_task_manager_; FakeOSUserManager fake_os_user_manager_; FakeScopedLsaPolicyFactory fake_scoped_lsa_factory_; registry_util::RegistryOverrideManager registry_override; base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::TimeSource::MOCK_TIME}; }; class FakeTask : public extension::Task { public: explicit FakeTask(base::TimeDelta period); ~FakeTask() override; extension::Config GetConfig() override; HRESULT SetContext( const std::vector<extension::UserDeviceContext>& c) override; HRESULT Execute() override; static std::vector<extension::UserDeviceContext> user_device_context_; static int num_fails_; private: base::TimeDelta period_; }; std::vector<extension::UserDeviceContext> FakeTask::user_device_context_; int FakeTask::num_fails_ = 0; FakeTask::FakeTask(base::TimeDelta period) : period_(period) {} FakeTask::~FakeTask() {} extension::Config FakeTask::GetConfig() { extension::Config config; config.execution_period = period_; return config; } HRESULT FakeTask::SetContext( const std::vector<extension::UserDeviceContext>& c) { user_device_context_ = c; return S_OK; } HRESULT FakeTask::Execute() { if (num_fails_ != 0) { num_fails_--; return E_FAIL; } return S_OK; } std::unique_ptr<extension::Task> AuxTaskCreator(base::TimeDelta period) { auto task = std::make_unique<FakeTask>(period); return std::move(task); } extension::TaskCreator GenerateTaskCreator(base::TimeDelta period) { return base::BindRepeating(&AuxTaskCreator, period); } TEST_F(TaskManagerTest, PeriodicDelay) { std::string fake_task_name = "fake_task"; // Registers a task which has a config to run every 3 hours. fake_task_manager()->RegisterTask( fake_task_name, GenerateTaskCreator(base::TimeDelta::FromHours(3))); // Starts running registered tasks for all associated GCPW users. RunTasks(); task_environment()->FastForwardBy(base::TimeDelta::FromHours(5)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 2); std::wstring fake_task_reg_name = extension::GetLastSyncRegNameForTask(base::UTF8ToWide(fake_task_name)); ASSERT_NE(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); task_environment()->FastForwardBy(base::TimeDelta::FromHours(2)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 3); } TEST_F(TaskManagerTest, PreviouslyExecuted) { std::string fake_task_name = "fake_task"; std::wstring fake_task_reg_name = extension::GetLastSyncRegNameForTask(base::UTF8ToWide(fake_task_name)); const base::Time sync_time = base::Time::Now(); const std::wstring sync_time_millis = base::NumberToWString( (sync_time.ToDeltaSinceWindowsEpoch() - base::TimeDelta::FromHours(1)) .InMilliseconds()); SetGlobalFlag(fake_task_reg_name, sync_time_millis); // Registers a task which has a config to run every 3 hours. fake_task_manager()->RegisterTask( fake_task_name, GenerateTaskCreator(base::TimeDelta::FromHours(5))); // Starts running registered tasks for all associated GCPW users. RunTasks(); // First execution should happen after 4 hours as the registry says it was // executed an hour ago. task_environment()->FastForwardBy(base::TimeDelta::FromHours(3) + base::TimeDelta::FromMinutes(59)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 0); task_environment()->FastForwardBy(base::TimeDelta::FromMinutes(1)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 1); ASSERT_NE(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); task_environment()->FastForwardBy(base::TimeDelta::FromHours(5)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 2); } TEST_F(TaskManagerTest, TaskExecuted) { std::wstring serial_number = L"1234"; GoogleRegistrationDataForTesting g_registration_data(serial_number); std::wstring machine_guid = L"machine_guid"; SetMachineGuidForTesting(machine_guid); // Create a fake user associated to a gaia id. CComBSTR sid1; ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( L"foo@gmail.com", L"password", L"Full Name", L"comment", L"test-gaia-id", std::wstring(), L"domain", &sid1)); std::wstring device_resource_id1 = L"foo_resource_id"; ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid1), L"device_resource_id", device_resource_id1)); FakeTokenGenerator fake_token_generator; fake_token_generator.SetTokensForTesting( {base::GenerateGUID(), base::GenerateGUID()}); ASSERT_EQ(S_OK, GenerateGCPWDmToken((BSTR)sid1)); std::wstring dm_token1; ASSERT_EQ(S_OK, GetGCPWDmToken((BSTR)sid1, &dm_token1)); std::string fake_task_name = "fake_task"; fake_task_manager()->RegisterTask( fake_task_name, GenerateTaskCreator(base::TimeDelta::FromHours(3))); RunTasks(); task_environment()->FastForwardBy(base::TimeDelta::FromHours(5)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 2); ASSERT_EQ(FakeTask::user_device_context_.size(), (size_t)1); extension::UserDeviceContext c1 = {device_resource_id1, serial_number, machine_guid, OLE2W(sid1), dm_token1}; ASSERT_TRUE(FakeTask::user_device_context_[0] == c1); std::wstring fake_task_reg_name = extension::GetLastSyncRegNameForTask(base::UTF8ToWide(fake_task_name)); ASSERT_NE(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); // Create another user associated to a gaia id. CComBSTR sid2; ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( L"bar@gmail.com", L"password", L"Full Name", L"comment", L"test-gaia-id2", std::wstring(), L"domain", &sid2)); std::wstring device_resource_id2 = L"foo_resource_id"; ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid2), L"device_resource_id", device_resource_id2)); ASSERT_EQ(S_OK, GenerateGCPWDmToken((BSTR)sid2)); std::wstring dm_token2; ASSERT_EQ(S_OK, GetGCPWDmToken((BSTR)sid2, &dm_token2)); task_environment()->FastForwardBy(base::TimeDelta::FromHours(2)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 3); ASSERT_EQ(FakeTask::user_device_context_.size(), (size_t)2); extension::UserDeviceContext c2 = {device_resource_id2, serial_number, machine_guid, OLE2W(sid2), dm_token2}; ASSERT_TRUE(FakeTask::user_device_context_[0] == c1); ASSERT_TRUE(FakeTask::user_device_context_[1] == c2); } TEST_F(TaskManagerTest, TasksWithDifferentPeriods) { std::string fake_task_name = "fake_task"; std::string another_fake_task_name = "another_fake_task"; fake_task_manager()->RegisterTask( fake_task_name, GenerateTaskCreator(base::TimeDelta::FromHours(3))); fake_task_manager()->RegisterTask( another_fake_task_name, GenerateTaskCreator(base::TimeDelta::FromHours(1))); // Starts running registered tasks for all associated GCPW users. RunTasks(); task_environment()->FastForwardBy(base::TimeDelta::FromHours(5)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 2); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(another_fake_task_name), 5); std::wstring fake_task_reg_name = extension::GetLastSyncRegNameForTask(base::UTF8ToWide(fake_task_name)); ASSERT_NE(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); std::wstring another_fake_task_reg_name = extension::GetLastSyncRegNameForTask( base::UTF8ToWide(another_fake_task_name)); ASSERT_NE(GetGlobalFlagOrDefault(another_fake_task_reg_name, L""), L""); task_environment()->FastForwardBy(base::TimeDelta::FromHours(2)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 3); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(another_fake_task_name), 7); } TEST_F(TaskManagerTest, BackOff) { std::wstring serial_number = L"1234"; GoogleRegistrationDataForTesting g_registration_data(serial_number); std::wstring machine_guid = L"machine_guid"; SetMachineGuidForTesting(machine_guid); // Create a fake user associated to a gaia id. CComBSTR sid1; ASSERT_EQ(S_OK, fake_os_user_manager()->CreateTestOSUser( L"foo@gmail.com", L"password", L"Full Name", L"comment", L"test-gaia-id", std::wstring(), L"domain", &sid1)); std::wstring device_resource_id1 = L"foo_resource_id"; ASSERT_EQ(S_OK, SetUserProperty(OLE2W(sid1), L"device_resource_id", device_resource_id1)); FakeTokenGenerator fake_token_generator; fake_token_generator.SetTokensForTesting( {base::GenerateGUID(), base::GenerateGUID()}); ASSERT_EQ(S_OK, GenerateGCPWDmToken((BSTR)sid1)); std::string fake_task_name = "fake_task"; // Task::Execute returns failure 3 times and backoff mechanism kicks in. // 1st backoff is 1 min. 2nd backoff ins 3 mins. 3rd backoff is 6 mins. FakeTask::num_fails_ = 3; fake_task_manager()->RegisterTask( fake_task_name, GenerateTaskCreator(base::TimeDelta::FromMinutes(30))); // Starts running registered tasks for all associated GCPW users. RunTasks(); std::wstring fake_task_reg_name = extension::GetLastSyncRegNameForTask(base::UTF8ToWide(fake_task_name)); // Seconds 10 - 1st execution failure task_environment()->FastForwardBy(base::TimeDelta::FromSeconds(10)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 1); ASSERT_EQ(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); // Minutes 2:10 - 2nd execution failure task_environment()->FastForwardBy(base::TimeDelta::FromMinutes(2)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 2); ASSERT_EQ(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); // Minutes 6:10 - 3rd execution failure task_environment()->FastForwardBy(base::TimeDelta::FromMinutes(4)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 3); ASSERT_EQ(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); // Minutes 14:10 - success task_environment()->FastForwardBy(base::TimeDelta::FromMinutes(8)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 4); ASSERT_NE(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); // Minutes 13:10 - 3 more success task_environment()->FastForwardBy(base::TimeDelta::FromHours(2)); ASSERT_EQ(fake_task_manager()->NumOfTimesExecuted(fake_task_name), 8); ASSERT_NE(GetGlobalFlagOrDefault(fake_task_reg_name, L""), L""); } } // namespace testing } // namespace credential_provider
36.434524
80
0.740974
iridium-browser
fca51743d38453ae21af19365b6a2abe635f8d6d
2,655
cpp
C++
DungeonScene.cpp
kaitokidi/ChamanClickerBattle
248ca07c80a2ab3ee6376c8262e6c120e4650051
[ "MIT" ]
1
2016-01-27T17:02:03.000Z
2016-01-27T17:02:03.000Z
DungeonScene.cpp
kaitokidi/ChamanClickerBattle
248ca07c80a2ab3ee6376c8262e6c120e4650051
[ "MIT" ]
null
null
null
DungeonScene.cpp
kaitokidi/ChamanClickerBattle
248ca07c80a2ab3ee6376c8262e6c120e4650051
[ "MIT" ]
null
null
null
#include "DungeonScene.hpp" #include "Game.hpp" DungeonScene::DungeonScene(Game* g, sf::RenderWindow* w, sceneTypes sT, std::string name, std::string description) : ScenePlayable(g,w,sT,name,description), _topDoor(0,sf::Vector2f(120,16),directions::up), _botDoor(0,sf::Vector2f(120,144),directions::down), _leftDoor(0,sf::Vector2f(16,80),directions::left), _rightDoor(0,sf::Vector2f(224,80),directions::right) { _sceneIniCoord = sf::Vector2f(FLT_MAX,FLT_MAX); } DungeonScene::~DungeonScene() { } void DungeonScene::init(sf::Vector2f sceneIniCoord = sf::Vector2f(0,0)) { sf::Vector2f aux = _sceneIniCoord; ScenePlayable::init(sceneIniCoord); if (sceneIniCoord == aux) return; if (aux == sf::Vector2f(FLT_MAX,FLT_MAX)) { auto mapDoors = _map.getDungeonDoors(); for (auto it = mapDoors.begin(); it != mapDoors.end(); ++it) addDoor(*(*it).first,(*it).second); addProp(&_topDoor); addProp(&_botDoor); addProp(&_leftDoor); addProp(&_rightDoor); } _topDoor.setIniCoord(_sceneIniCoord); _botDoor.setIniCoord(_sceneIniCoord); _leftDoor.setIniCoord(_sceneIniCoord); _rightDoor.setIniCoord(_sceneIniCoord); _topDoor.setScene(this); _botDoor.setScene(this); _leftDoor.setScene(this); _rightDoor.setScene(this); if (DataManager::getBool(_sceneName+std::to_string(directions::up ), false)) _topDoor.openWithKey(); if (DataManager::getBool(_sceneName+std::to_string(directions::down ), false)) _botDoor.openWithKey(); if (DataManager::getBool(_sceneName+std::to_string(directions::left ), false)) _leftDoor.openWithKey(); if (DataManager::getBool(_sceneName+std::to_string(directions::right), false)) _rightDoor.openWithKey(); } void DungeonScene::update(float deltaTime) { ScenePlayable::update(deltaTime); if (_enemies.empty()) openDoors(); else closeDoors(); } void DungeonScene::render(sf::RenderTarget* target) { ScenePlayable::render(target); } sceneTypes DungeonScene::getType(){ return sceneTypes::dungeon; } void DungeonScene::addDoor(DungeonDoor door,directions dir) { if (dir == directions::up) _topDoor = door; else if (dir == directions::down) _botDoor = door; else if (dir == directions::left) _leftDoor = door; else if (dir == directions::right) _rightDoor = door; else { std::cout << "Wrong direction adding a door " << std::endl; exit(EXIT_FAILURE); } } void DungeonScene::openDoors() { _topDoor.open(); _botDoor.open(); _leftDoor.open(); _rightDoor.open(); } void DungeonScene::closeDoors() { _topDoor.close(); _botDoor.close(); _leftDoor.close(); _rightDoor.close(); }
31.987952
116
0.699435
kaitokidi
fca760afd3e25385bd40abc1797bfb0dfacc7e7b
11,996
cpp
C++
raptor/external/hypre_wrapper.cpp
lukeolson/raptor
526c88d0801634e6fb41375ae077f2d4aa3241a4
[ "BSD-2-Clause" ]
25
2017-11-20T21:45:43.000Z
2019-01-27T15:03:25.000Z
raptor/external/hypre_wrapper.cpp
lukeolson/raptor
526c88d0801634e6fb41375ae077f2d4aa3241a4
[ "BSD-2-Clause" ]
3
2017-11-21T01:20:20.000Z
2018-11-16T17:33:06.000Z
raptor/external/hypre_wrapper.cpp
lukeolson/raptor
526c88d0801634e6fb41375ae077f2d4aa3241a4
[ "BSD-2-Clause" ]
5
2017-11-20T22:03:57.000Z
2018-12-05T10:30:22.000Z
// Copyright (c) 2015-2017, RAPtor Developer Team // License: Simplified BSD, http://opensource.org/licenses/BSD-2-Clause #include "hypre_wrapper.hpp" HYPRE_IJVector convert(raptor::ParVector& x_rap, RAPtor_MPI_Comm comm_mat) { int num_procs, rank; RAPtor_MPI_Comm_rank(comm_mat, &rank); RAPtor_MPI_Comm_size(comm_mat, &num_procs); HYPRE_IJVector x; HYPRE_Int local_n = x_rap.local_n; std::vector<int> first_n(num_procs); RAPtor_MPI_Allgather(&local_n, 1, RAPtor_MPI_INT, first_n.data(), 1, RAPtor_MPI_INT, comm_mat); HYPRE_Int first_local = 0; for (int i = 0; i < rank; i++) { first_local += first_n[i]; } HYPRE_Int last_local = first_local + local_n - 1; HYPRE_IJVectorCreate(comm_mat, first_local, last_local, &x); HYPRE_IJVectorSetObjectType(x, HYPRE_PARCSR); HYPRE_IJVectorInitialize(x); HYPRE_Int* rows = new HYPRE_Int[local_n]; for (HYPRE_Int i = 0; i < local_n; i++) { rows[i] = i+first_local; } HYPRE_Real* x_data = x_rap.local.data(); HYPRE_IJVectorSetValues(x, local_n, rows, x_data); HYPRE_IJVectorAssemble(x); delete[] rows; return x; } HYPRE_IJMatrix convert(raptor::ParCSRMatrix* A_rap, RAPtor_MPI_Comm comm_mat) { HYPRE_IJMatrix A; HYPRE_Int n_rows = 0; HYPRE_Int n_cols = 0; HYPRE_Int local_row_start = 0; HYPRE_Int local_col_start = 0; HYPRE_Int rank, num_procs; HYPRE_Int one = 1; RAPtor_MPI_Comm_rank(comm_mat, &rank); RAPtor_MPI_Comm_size(comm_mat, &num_procs); std::vector<int> row_sizes(num_procs); std::vector<int> col_sizes(num_procs); RAPtor_MPI_Allgather(&(A_rap->local_num_rows), 1, RAPtor_MPI_INT, row_sizes.data(), 1, RAPtor_MPI_INT, RAPtor_MPI_COMM_WORLD); RAPtor_MPI_Allgather(&(A_rap->on_proc_num_cols), 1, RAPtor_MPI_INT, col_sizes.data(), 1, RAPtor_MPI_INT, RAPtor_MPI_COMM_WORLD); for (int i = 0; i < rank; i++) { local_row_start += row_sizes[i]; local_col_start += col_sizes[i]; } // Send new global cols (to update off_proc_col_map) std::vector<int> new_cols(A_rap->on_proc_num_cols); for (int i = 0; i < A_rap->on_proc_num_cols; i++) { new_cols[i] = i + local_col_start; } if (!A_rap->comm) A_rap->comm = new ParComm(A_rap->partition, A_rap->off_proc_column_map, A_rap->on_proc_column_map); std::vector<int>& recvbuf = A_rap->comm->communicate(new_cols); std::vector<int> off_proc_cols(A_rap->off_proc_num_cols); std::copy(recvbuf.begin(), recvbuf.begin() + A_rap->off_proc_num_cols, off_proc_cols.begin()); n_rows = A_rap->local_num_rows; if (n_rows) { n_cols = A_rap->on_proc_num_cols; } /********************************** ****** CREATE HYPRE MATRIX ************************************/ HYPRE_IJMatrixCreate(comm_mat, local_row_start, local_row_start + n_rows - 1, local_col_start, local_col_start + n_cols - 1, &A); HYPRE_IJMatrixSetObjectType(A, HYPRE_PARCSR); HYPRE_IJMatrixInitialize(A); HYPRE_Int row_start, row_end; HYPRE_Int global_row, global_col; HYPRE_Real value; for (int i = 0; i < A_rap->on_proc->n_rows; i++) { row_start = A_rap->on_proc->idx1[i]; row_end = A_rap->on_proc->idx1[i+1]; global_row = i + local_row_start; for (int j = row_start; j < row_end; j++) { global_col = A_rap->on_proc->idx2[j] + local_col_start; value = A_rap->on_proc->vals[j]; HYPRE_IJMatrixSetValues(A, 1, &one, &global_row, &global_col, &value); } } for (int i = 0; i < A_rap->off_proc->n_rows; i++) { row_start = A_rap->off_proc->idx1[i]; row_end = A_rap->off_proc->idx1[i+1]; global_row = i + local_row_start; for (int j = row_start; j < row_end; j++) { global_col = off_proc_cols[A_rap->off_proc->idx2[j]]; value = A_rap->off_proc->vals[j]; HYPRE_IJMatrixSetValues(A, 1, &one, &global_row, &global_col, &value); } } HYPRE_IJMatrixAssemble(A); return A; } raptor::ParCSRMatrix* convert(hypre_ParCSRMatrix* A_hypre, RAPtor_MPI_Comm comm_mat) { int num_procs; int rank; RAPtor_MPI_Comm_size(comm_mat, &num_procs); RAPtor_MPI_Comm_rank(comm_mat, &rank); hypre_CSRMatrix* A_hypre_diag = hypre_ParCSRMatrixDiag(A_hypre); HYPRE_Real* diag_data = hypre_CSRMatrixData(A_hypre_diag); HYPRE_Int* diag_i = hypre_CSRMatrixI(A_hypre_diag); HYPRE_Int* diag_j = hypre_CSRMatrixJ(A_hypre_diag); HYPRE_Int diag_nnz = hypre_CSRMatrixNumNonzeros(A_hypre_diag); HYPRE_Int diag_rows = hypre_CSRMatrixNumRows(A_hypre_diag); HYPRE_Int diag_cols = hypre_CSRMatrixNumCols(A_hypre_diag); hypre_CSRMatrix* A_hypre_offd = hypre_ParCSRMatrixOffd(A_hypre); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_hypre_offd); HYPRE_Int* offd_i = hypre_CSRMatrixI(A_hypre_offd); HYPRE_Int* offd_j = hypre_CSRMatrixJ(A_hypre_offd); HYPRE_Real* offd_data; if (num_cols_offd) { offd_data = hypre_CSRMatrixData(A_hypre_offd); } HYPRE_Int first_local_row = hypre_ParCSRMatrixFirstRowIndex(A_hypre); HYPRE_Int first_local_col = hypre_ParCSRMatrixFirstColDiag(A_hypre); HYPRE_Int* col_map_offd = hypre_ParCSRMatrixColMapOffd(A_hypre); HYPRE_Int global_rows = hypre_ParCSRMatrixGlobalNumRows(A_hypre); HYPRE_Int global_cols = hypre_ParCSRMatrixGlobalNumCols(A_hypre); ParCSRMatrix* A = new ParCSRMatrix(global_rows, global_cols, diag_rows, diag_cols, first_local_row, first_local_col); A->on_proc->idx1[0] = 0; for (int i = 0; i < diag_rows; i++) { int row_start = diag_i[i]; int row_end = diag_i[i+1]; for (int j = row_start; j < row_end; j++) { A->on_proc->idx2.emplace_back(diag_j[j]); A->on_proc->vals.emplace_back(diag_data[j]); } A->on_proc->idx1[i+1] = A->on_proc->idx2.size(); } A->on_proc->nnz = A->on_proc->idx2.size(); A->off_proc->idx1[0] = 0; for (int i = 0; i < diag_rows; i++) { if (num_cols_offd) { int row_start = offd_i[i]; int row_end = offd_i[i+1]; for (int j = row_start; j < row_end; j++) { int global_col = col_map_offd[offd_j[j]]; A->off_proc->idx2.emplace_back(global_col); A->off_proc->vals.emplace_back(offd_data[j]); } } A->off_proc->idx1[i+1] = A->off_proc->idx2.size(); } A->off_proc->nnz = A->off_proc->idx2.size(); A->finalize(); return A; } HYPRE_Solver hypre_create_hierarchy(hypre_ParCSRMatrix* A, hypre_ParVector* b, hypre_ParVector* x, HYPRE_Int coarsen_type, HYPRE_Int interp_type, HYPRE_Int p_max_elmts, HYPRE_Int agg_num_levels, HYPRE_Real strong_threshold, HYPRE_Real filter_threshold, HYPRE_Int num_functions) { // Create AMG solver struct HYPRE_Solver amg_data; HYPRE_BoomerAMGCreate(&amg_data); // Set Boomer AMG Parameters HYPRE_BoomerAMGSetMaxRowSum(amg_data, 1); HYPRE_BoomerAMGSetCoarsenType(amg_data, coarsen_type); HYPRE_BoomerAMGSetInterpType(amg_data, interp_type); HYPRE_BoomerAMGSetPMaxElmts(amg_data, p_max_elmts); HYPRE_BoomerAMGSetAggNumLevels(amg_data, agg_num_levels); HYPRE_BoomerAMGSetStrongThreshold(amg_data, strong_threshold); HYPRE_BoomerAMGSetMaxCoarseSize(amg_data, 50); HYPRE_BoomerAMGSetRelaxType(amg_data, 3); HYPRE_BoomerAMGSetRelaxOrder(amg_data, 0); // HYPRE_BoomerAMGSetRelaxWt(amg_data, 3.0/4); // set omega for SOR HYPRE_BoomerAMGSetNumFunctions(amg_data, num_functions); //HYPRE_BoomerAMGSetRAP2(amg_data, 1); HYPRE_BoomerAMGSetTruncFactor(amg_data, filter_threshold); HYPRE_BoomerAMGSetPrintLevel(amg_data, 0); HYPRE_BoomerAMGSetMaxIter(amg_data, 1000); // Setup AMG HYPRE_BoomerAMGSetup(amg_data, A, b, x); return amg_data; } HYPRE_Solver hypre_create_GMRES(hypre_ParCSRMatrix* A, hypre_ParVector* b, hypre_ParVector* x, HYPRE_Solver* precond_ptr, HYPRE_Int coarsen_type, HYPRE_Int interp_type, HYPRE_Int p_max_elmts, HYPRE_Int agg_num_levels, HYPRE_Real strong_threshold, HYPRE_Int num_functions) { // Create AMG solver struct HYPRE_Solver gmres_data; HYPRE_ParCSRGMRESCreate(RAPtor_MPI_COMM_WORLD, &gmres_data); HYPRE_Solver amg_data; HYPRE_BoomerAMGCreate(&amg_data); // Set Boomer AMG Parameters HYPRE_BoomerAMGSetMaxRowSum(amg_data, 1); HYPRE_BoomerAMGSetCoarsenType(amg_data, coarsen_type); HYPRE_BoomerAMGSetInterpType(amg_data, interp_type); HYPRE_BoomerAMGSetPMaxElmts(amg_data, p_max_elmts); HYPRE_BoomerAMGSetAggNumLevels(amg_data, agg_num_levels); HYPRE_BoomerAMGSetStrongThreshold(amg_data, strong_threshold); HYPRE_BoomerAMGSetMaxCoarseSize(amg_data, 50); HYPRE_BoomerAMGSetRelaxType(amg_data, 3); HYPRE_BoomerAMGSetNumFunctions(amg_data, num_functions); HYPRE_BoomerAMGSetPrintLevel(amg_data, 0); HYPRE_BoomerAMGSetMaxIter(amg_data, 1); HYPRE_BoomerAMGSetRelaxOrder(amg_data, 1); HYPRE_BoomerAMGSetTruncFactor(amg_data, 0.3); // Set GMRES Parameters HYPRE_GMRESSetMaxIter(gmres_data, 100); HYPRE_GMRESSetTol(gmres_data, 1e-6); HYPRE_GMRESSetPrintLevel(gmres_data, 2); // Setup AMG HYPRE_ParCSRGMRESSetPrecond(gmres_data, HYPRE_BoomerAMGSolve, HYPRE_BoomerAMGSetup, amg_data); HYPRE_ParCSRGMRESSetup(gmres_data, A, b, x); *precond_ptr = amg_data; return gmres_data; } HYPRE_Solver hypre_create_BiCGSTAB(hypre_ParCSRMatrix* A, hypre_ParVector* b, hypre_ParVector* x, HYPRE_Solver* precond_ptr, HYPRE_Int coarsen_type, HYPRE_Int interp_type, HYPRE_Int p_max_elmts, HYPRE_Int agg_num_levels, HYPRE_Real strong_threshold, HYPRE_Int num_functions) { // Create AMG solver struct HYPRE_Solver bicgstab_data; HYPRE_ParCSRBiCGSTABCreate(RAPtor_MPI_COMM_WORLD, &bicgstab_data); HYPRE_Solver amg_data; HYPRE_BoomerAMGCreate(&amg_data); // Set Boomer AMG Parameters HYPRE_BoomerAMGSetMaxRowSum(amg_data, 1); HYPRE_BoomerAMGSetCoarsenType(amg_data, coarsen_type); HYPRE_BoomerAMGSetInterpType(amg_data, interp_type); HYPRE_BoomerAMGSetPMaxElmts(amg_data, p_max_elmts); HYPRE_BoomerAMGSetAggNumLevels(amg_data, agg_num_levels); HYPRE_BoomerAMGSetStrongThreshold(amg_data, strong_threshold); HYPRE_BoomerAMGSetMaxCoarseSize(amg_data, 50); HYPRE_BoomerAMGSetRelaxType(amg_data, 3); HYPRE_BoomerAMGSetNumFunctions(amg_data, num_functions); HYPRE_BoomerAMGSetPrintLevel(amg_data, 0); HYPRE_BoomerAMGSetMaxIter(amg_data, 1); // Set GMRES Parameters HYPRE_BiCGSTABSetMaxIter(bicgstab_data, 100); HYPRE_BiCGSTABSetTol(bicgstab_data, 1e-6); HYPRE_BiCGSTABSetPrintLevel(bicgstab_data, 2); // Setup AMG HYPRE_ParCSRBiCGSTABSetPrecond(bicgstab_data, HYPRE_BoomerAMGSolve, HYPRE_BoomerAMGSetup, amg_data); HYPRE_ParCSRBiCGSTABSetup(bicgstab_data, A, b, x); *precond_ptr = amg_data; return bicgstab_data; }
35.808955
133
0.652634
lukeolson
fca76201a8f28c73583fc244019de92973547be7
221
cpp
C++
chapter 2/2.cpp
lyhlyhl/cpp_Primer_Plus_tasks
0b966ec8216ac9bb8baffe462e15317c2d98c5de
[ "MIT" ]
null
null
null
chapter 2/2.cpp
lyhlyhl/cpp_Primer_Plus_tasks
0b966ec8216ac9bb8baffe462e15317c2d98c5de
[ "MIT" ]
null
null
null
chapter 2/2.cpp
lyhlyhl/cpp_Primer_Plus_tasks
0b966ec8216ac9bb8baffe462e15317c2d98c5de
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int distance; cout << "please input the distance(long):"; cin >> distance; cout << distance * 220 << " yard" << endl; cin.get(); cin.get(); }
17
47
0.570136
lyhlyhl
fca99119511fb7fafa00f4c442f6614a3b157465
1,553
cpp
C++
private/shell/shell32/unicpp/admover.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/shell32/unicpp/admover.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/shell32/unicpp/admover.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
// ADMover.cpp : Implementation of DLL Exports. // Note: Proxy/Stub Information // To build a separate proxy/stub DLL, // run nmake -f ADMoverps.mk in the project directory. #include "stdafx.h" #pragma hdrstop #include "deskmovr.h" #ifdef POSTSPLIT CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_DeskMovr, CDeskMovr) END_OBJECT_MAP() ///////////////////////////////////////////////////////////////////////////// // DLL Entry Point // BUGBUG/TODO: Rename this to "atlcreate.cpp" or something more descriptive. STDAPI_(BOOL) DeskMovr_DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) { if (dwReason == DLL_PROCESS_ATTACH) { _Module.Init(ObjectMap, hInstance); } else if (dwReason == DLL_PROCESS_DETACH) { _Module.Term(); } return TRUE; // ok } STDAPI CDeskMovr_CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, void **ppunk) { return CComCreator< CComPolyObject< CDeskMovr > >::CreateInstance( (LPVOID)pUnkOuter, IID_IUnknown, (LPVOID*)ppunk ); } STDAPI CWebViewFolderContents_CreateInstance(LPUNKNOWN punkOuter, REFIID riid, LPVOID * ppvOut) { return CComCreator< CComPolyObject< CWebViewFolderContents > >::CreateInstance((LPVOID) punkOuter, riid, ppvOut); } STDAPI CShellFolderViewOC_CreateInstance(LPUNKNOWN punkOuter, REFIID riid, LPVOID * ppvOut) { return CComCreator< CComPolyObject< CShellFolderViewOC > >::CreateInstance((LPVOID) punkOuter, riid, ppvOut); } #endif
27.732143
122
0.670959
King0987654
fcaecfedb90217f34201526356e1650d389b8c20
952
cpp
C++
engine/src/common/clock.cpp
justinvh/raptr
b6f8c9badbf2731f555ec05d54d5865627af6022
[ "MIT" ]
3
2018-07-03T16:08:26.000Z
2018-07-15T01:18:15.000Z
engine/src/common/clock.cpp
justinvh/raptr
b6f8c9badbf2731f555ec05d54d5865627af6022
[ "MIT" ]
null
null
null
engine/src/common/clock.cpp
justinvh/raptr
b6f8c9badbf2731f555ec05d54d5865627af6022
[ "MIT" ]
null
null
null
#include <chrono> #include <raptr/common/clock.hpp> #include <raptr/common/logging.hpp> namespace { auto logger = raptr::_get_logger(__FILE__); }; namespace raptr::clock { namespace { auto clock_last = Time::now(); auto paused_time = Time::now(); int64_t offset_us = 0; bool paused = false; using us = std::chrono::microseconds; } int64_t ticks() { auto now = Time::now(); if (paused) { now = paused_time; } return std::chrono::duration_cast<us>(now - clock_last - us(offset_us)).count(); } void start() { if (paused) { toggle(); } } void stop() { if (!paused) { toggle(); } } bool toggle() { paused = !paused; if (!paused) { auto now = Time::now(); offset_us += std::chrono::duration_cast<us>(now - paused_time).count(); logger->debug("Clock is now offset by {}us", offset_us); } else { paused_time = Time::now(); } return paused; } }
17
84
0.591387
justinvh
fcb27c2e5c398e88e00d3d801cf7b69940818caa
6,942
hpp
C++
src/restio_api_mapper.hpp
Ri0n/restio
20e0324645fece1cbef43a740e52023c9e255c15
[ "BSD-2-Clause" ]
null
null
null
src/restio_api_mapper.hpp
Ri0n/restio
20e0324645fece1cbef43a740e52023c9e255c15
[ "BSD-2-Clause" ]
null
null
null
src/restio_api_mapper.hpp
Ri0n/restio
20e0324645fece1cbef43a740e52023c9e255c15
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2021, Sergei Ilinykh <rion4ik@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <boost/algorithm/string.hpp> #include <boost/asio/awaitable.hpp> #include <nlohmann/json.hpp> #include <span> #include "restio_common.hpp" #include "restio_properties.hpp" #include <type_traits> namespace restio::api { using namespace ::nlohmann; namespace http = ::boost::beast::http; // from <boost/beast/http.hpp> using ::boost::asio::awaitable; struct API { struct Method { using Handler = std::function<awaitable<void>(Request &request, Response &response, const Properties &properties)>; // using SyncHandler = std::function<void(Request &request, Response &response, const Properties &properties)>; http::verb method; std::string uri; std::string comment; json inputExample; json outputExample; std::string responseStatus; Handler handler; // Wrapping hardler to an async func if it's synchronous template <typename HandlerType> inline static Handler wrapHandler( HandlerType &&handler, typename std::enable_if< std::is_same<typename std::invoke_result<HandlerType, Request &, Response &, const Properties &>::type, awaitable<void>>::value>::type * = 0) { return handler; } template <typename HandlerType> inline static Handler wrapHandler( HandlerType &&handler, typename std::enable_if< std::is_same<typename std::invoke_result<HandlerType, Request &, Response &, const Properties &>::type, void>::value>::type * = 0) { return [handler = std::move(handler)]( Request &request, Response &response, const Properties &properties) -> awaitable<void> { handler(request, response, properties); co_return; }; } template <typename RequestMessage, typename ResponseMessage, typename HandlerType> inline static Method sample(http::verb method, std::string &&uri, std::string &&desc, std::string &&responseStatus, HandlerType &&handler) { return Method { method, std::move(uri), std::move(desc), RequestMessage::docSample(), ResponseMessage::docSample(), std::move(responseStatus), std::move(wrapHandler(std::move(handler))), }; } struct Dummy { static json docSample() { return nullptr; } }; template <typename ResponseMessage, typename... Args> inline static Method get(Args &&...args) { return sample<Dummy, ResponseMessage>(http::verb::get, std::forward<Args>(args)...); } template <typename RequestMessage, typename ResponseMessage, typename... Args> inline static Method post(Args &&...args) { return sample<RequestMessage, ResponseMessage>(http::verb::post, std::forward<Args>(args)...); } template <typename RequestMessage, typename ResponseMessage = Dummy, typename... Args> inline static Method put(Args &&...args) { return sample<RequestMessage, ResponseMessage>(http::verb::put, std::forward<Args>(args)...); } template <typename... Args> inline static Method delete_(Args &&...args) { return sample<Dummy, Dummy>(http::verb::delete_, std::forward<Args>(args)...); } }; struct ParsedNode { enum class Type : std::uint8_t { ConstString, VarString, Integer }; Type type; std::string id; // var name or const string value std::vector<std::reference_wrapper<const Method>> methods; std::vector<ParsedNode> children; bool operator==(const ParsedNode &other) const { return type == other.type && id == other.id; } }; struct LookupResult { Properties properties; std::reference_wrapper<const Method> method; }; inline API(int version = 1) : version(version) { } template <typename ResponseMessage, typename... Args> inline API &get(Args &&...args) { methods.push_back(Method::get<ResponseMessage>(std::forward<Args>(args)...)); return *this; } template <typename RequestMessage, typename ResponseMessage, typename... Args> inline API &post(Args &&...args) { methods.push_back(Method::post<RequestMessage, ResponseMessage>(std::forward<Args>(args)...)); return *this; } template <typename RequestMessage, typename ResponseMessage = Method::Dummy, typename... Args> inline API &put(Args &&...args) { methods.push_back(Method::put<RequestMessage, ResponseMessage>(std::forward<Args>(args)...)); return *this; } template <typename... Args> inline API &delete_(Args &&...args) { methods.push_back(Method::delete_(std::forward<Args>(args)...)); return *this; } void buildParser(); std::optional<LookupResult> lookup(http::verb method, std::string_view target) const; int version = 1; std::vector<Method> methods; std::vector<ParsedNode> roots; }; } // namespace restio::api
39
119
0.612215
Ri0n
fcb4b834718298760214e85fa27f2830f9835767
1,823
hpp
C++
includes/eeros/control/SignalChecker.hpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
includes/eeros/control/SignalChecker.hpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
includes/eeros/control/SignalChecker.hpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
#ifndef ORG_EEROS_SIGNAL_CHECKER_HPP_ #define ORG_EEROS_SIGNAL_CHECKER_HPP_ #include <eeros/control/Block1i.hpp> #include <eeros/safety/SafetyLevel.hpp> #include <eeros/safety/SafetySystem.hpp> #include <eeros/logger/Logger.hpp> namespace eeros { namespace control { using namespace safety; template <typename T = double> class SignalChecker : public Block1i<T> { public: SignalChecker(T lowerLimit, T upperLimit) : lowerLimit(lowerLimit), upperLimit(upperLimit), fired(false), safetySystem(nullptr), safetyEvent(nullptr), activeLevel(nullptr) { } virtual void run() override { auto val = this->in.getSignal().getValue(); if (!fired) { if (!((val > lowerLimit) && (val < upperLimit))) { if (safetySystem != nullptr && safetyEvent != nullptr) { if (activeLevel == nullptr || (activeLevel != nullptr && safetySystem->getCurrentLevel() >= *activeLevel)) { log.warn() << "Signal checker \'" + this->getName() + "\' fires!"; safetySystem->triggerEvent(*safetyEvent); fired = true; } } } } } virtual void setLimits(T lowerLimit, T upperLimit) { this->lowerLimit = lowerLimit; this->upperLimit = upperLimit; } virtual void reset() { fired = false; } virtual void registerSafetyEvent(SafetySystem& ss, SafetyEvent& e) { safetySystem = &ss; safetyEvent = &e; } virtual void setActiveLevel(SafetyLevel& level) { activeLevel = &level; } protected: T lowerLimit, upperLimit; bool fired; SafetySystem* safetySystem; SafetyEvent* safetyEvent; SafetyLevel* activeLevel; eeros::logger::Logger log; }; }; }; #endif /* ORG_EEROS_SIGNAL_CHECKER_HPP_ */
25.319444
116
0.625343
RicoPauli
fcb8ea4db8b19c244bd8788132101f9b0777f038
2,385
cpp
C++
Sethi/DivisionWithSubraction.cpp
przet/CppProgramming
042aff253988b74db47659d36806912ce84dd8bc
[ "MIT" ]
null
null
null
Sethi/DivisionWithSubraction.cpp
przet/CppProgramming
042aff253988b74db47659d36806912ce84dd8bc
[ "MIT" ]
null
null
null
Sethi/DivisionWithSubraction.cpp
przet/CppProgramming
042aff253988b74db47659d36806912ce84dd8bc
[ "MIT" ]
null
null
null
// m div n #include <iostream> int main() { // initialise the two integers to be stored from input int m = 0, n = 0; std::cout << "Please enter two integers \n"; // read in two inputs std::cin >> m; std::cin >> n; // store m - n. Will be useful for the loop later on, and some preliminary checks int store = (m - n); // check if store > n. If it is continue, if not we return m div n = 1 if (n > store && m > n) std::cout << "m div n = " << 1 << "\n"; // check if m == n and return m div n = 1 else if (m == n) std::cout << "m div n = " << 1 << "\n"; // I am assuming it is safe just to return "1" without any declaration before hand? Or should I store it first? // check if m < n and return m div n = 0 else if (m < n) std::cout << "m div n = " << 0 << "\n"; // same comment applies for returnin "0" direct. We do so in a main funciton (return(0)) so should be fine....? //otherwise, execute the (integer) division else if (m > n) // STRANGE. I just did else before, and if m == n, this else loop is still entered. But if m < n then 0 is returned correctly and program terminates. { // setting a counter and store variable for use in a loop int count = 1; int i = 1; // the loop with the logic of division via subtraction for (store, i = 1; store >= n; ++i) // Thanks for tutorial point for firming up the basics for me - the condition gets evaluated second and if it is true, the loop executes, otherwise the next statement after the loop (so no looping) occurs. // I had store == 0 - this was false! store != 0 is the right way. However I need to change this to not equal to less than zero. I had it the wrong way around, and this just firms up my fundamentals, my concepts :) { // the count until store equals zero or less is the div result (after we add one to it after the loop as we are starting at (m-n) instead of m. Yes we could of started the for loop at i =2, but we didn't) count = i; // n is subrtacted from (m-n) until store = 0 or less store -= n; } // output the div result to screen std::cout << "m div n = " << count + 1; } }
41.842105
258
0.568134
przet
fcbf95c0792d9a2c75c07942340771c0d80af552
24,990
cpp
C++
src/contours.cpp
jvo203/FITSWebQL
59a98bc1916ce5b5d88ec1ee1986009f47a76e8b
[ "MIT" ]
1
2022-03-09T07:21:48.000Z
2022-03-09T07:21:48.000Z
src/contours.cpp
jvo203/FITSWebQL
59a98bc1916ce5b5d88ec1ee1986009f47a76e8b
[ "MIT" ]
1
2020-06-04T08:12:36.000Z
2020-06-08T06:20:06.000Z
src/contours.cpp
jvo203/FITSWebQL
59a98bc1916ce5b5d88ec1ee1986009f47a76e8b
[ "MIT" ]
null
null
null
/*************************************************************************** * Copyright (C) 2007 by Bjorn Harpe,,, * * bjorn@ouelong.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ // based on the work of Paul Bourke and Nicholas Yue #include <stdio.h> #include <math.h> #include "contours.h" //bool operator <(SPoint p1,SPoint p2){return((p1.x<p2.x));} bool operator <(SPoint p1, SPoint p2){return(((p1.x*(unsigned int)0xFFFFFFFF)+p1.y)<((p2.x*(unsigned int)0xFFFFFFFF)+p2.y));} bool operator <(SPair p1,SPair p2){return(p1.p1<p2.p1);} bool operator ==(SPoint p1,SPoint p2){return((EQ(p1.x,p2.x))&&(EQ(p1.y,p2.y)));} bool operator !=(SPoint p1,SPoint p2){return(!(EQ(p1.x,p2.x)&&!(EQ(p1.y,p2.y))));} SPoint operator +=(SPoint p, SVector v){return(SPoint(p.x+=v.dx,p.y+=v.dy));} int CContourMap::contour(CRaster *r) { /* this routine is coppied almost verbatim form Nicholas Yue's C++ implememtation of Paul bourkes CONREC routine. for deatails on the theory and implementation of this routine visit http://local.wasp.uwa.edu.au/~pbourke/papers/conrec/ quick summary of the changes made - all the data passed in to the function is in a CRaster object and accessed thru a method (double value(double x, double y)). This class can be subclassed to calculate values based on a formula or retrieve values from a table. - as retrieval of values is now in the class supplied by the user we don't care if the data is regularly spaced or not, we assume that the class takes care of these details. - upper and lower bounds are similarly provided but the upper_bound and lower_bound methods in the class. - it is not assumed that this data is being immediatly output, rather it is all stored in a structure for later processing/display. yet to be done - realisticly we should replace the i and j indices with iterators, decouple this function from any sort of assumption entirely. this would require being able to retrieve x and y values from the iterator as well as the value. something like returning a pointer to a structure that contains the x and y values of the given point as well as the value. As this is not really required in my application it may or may not be done. //============================================================================= // // CONREC is a contouring subroutine for rectangularily spaced data. // // It emits calls to a line drawing subroutine supplied by the user // which draws a contour map corresponding to real*4data on a randomly // spaced rectangular grid. The coordinates emitted are in the same // units given in the x() and y() arrays. // // Any number of contour levels may be specified but they must be // in order of increasing value. // // As this code is ported from FORTRAN-77, please be very careful of the // various indices like ilb,iub,jlb and jub, remeber that C/C++ indices // starts from zero (0) // //===========================================================================*/ int m1,m2,m3,case_value; double dmin,dmax,x1,x2,y1,y2; register int i,j,k,m; double h[5]; int sh[5]; double xh[5],yh[5]; //=========================================================================== // The indexing of im and jm should be noted as it has to start from zero // unlike the fortran counter part //=========================================================================== int im[4] = {0,1,1,0},jm[4]={0,0,1,1}; //=========================================================================== // Note that castab is arranged differently from the FORTRAN code because // Fortran and C/C++ arrays are transposed of each other, in this case // it is more tricky as castab is in 3 dimension //=========================================================================== int castab[3][3][3] = { { {0,0,8},{0,2,5},{7,6,9} }, { {0,3,4},{1,3,1},{4,3,0} }, { {9,6,7},{5,2,0},{8,0,0} } }; for (j=((int)r->upper_bound().x-1);j>=(int)r->lower_bound().x;j--) { for (i=(int)r->lower_bound().y;i<=(int)r->upper_bound().y-1;i++) { double temp1,temp2; temp1 = min(r->value(i,j),r->value(i,j+1)); temp2 = min(r->value(i+1,j),r->value(i+1,j+1)); dmin = min(temp1,temp2); temp1 = max(r->value(i,j),r->value(i,j+1)); temp2 = max(r->value(i+1,j),r->value(i+1,j+1)); dmax = max(temp1,temp2); if (dmax>=levels[0]&&dmin<=levels[n_levels-1]) { for (k=0;k<n_levels;k++) { if (levels[k]>=dmin&&levels[k]<=dmax) { for (m=4;m>=0;m--) { if (m>0) { //============================================================= // The indexing of im and jm should be noted as it has to // start from zero //============================================================= h[m] = r->value(i+im[m-1],j+jm[m-1])-levels[k]; xh[m] = i+im[m-1]; yh[m] = j+jm[m-1]; } else { h[0] = 0.25*(h[1]+h[2]+h[3]+h[4]); xh[0]=0.5*(i+i+1); yh[0]=0.5*(j+j+1); } if (h[m]>0.0) { sh[m] = 1; } else if (h[m]<0.0) { sh[m] = -1; } else sh[m] = 0; } //================================================================= // // Note: at this stage the relative heights of the corners and the // centre are in the h array, and the corresponding coordinates are // in the xh and yh arrays. The centre of the box is indexed by 0 // and the 4 corners by 1 to 4 as shown below. // Each triangle is then indexed by the parameter m, and the 3 // vertices of each triangle are indexed by parameters m1,m2,and // m3. // It is assumed that the centre of the box is always vertex 2 // though this isimportant only when all 3 vertices lie exactly on // the same contour level, in which case only the side of the box // is drawn. // // // vertex 4 +-------------------+ vertex 3 // | \ / | // | \ m-3 / | // | \ / | // | \ / | // | m=2 X m=2 | the centre is vertex 0 // | / \ | // | / \ | // | / m=1 \ | // | / \ | // vertex 1 +-------------------+ vertex 2 // // // // Scan each triangle in the box // //================================================================= for (m=1;m<=4;m++) { m1 = m; m2 = 0; if (m!=4) m3 = m+1; else m3 = 1; case_value = castab[sh[m1]+1][sh[m2]+1][sh[m3]+1]; if (case_value!=0) { switch (case_value) { //=========================================================== // Case 1 - Line between vertices 1 and 2 //=========================================================== case 1: x1=xh[m1]; y1=yh[m1]; x2=xh[m2]; y2=yh[m2]; break; //=========================================================== // Case 2 - Line between vertices 2 and 3 //=========================================================== case 2: x1=xh[m2]; y1=yh[m2]; x2=xh[m3]; y2=yh[m3]; break; //=========================================================== // Case 3 - Line between vertices 3 and 1 //=========================================================== case 3: x1=xh[m3]; y1=yh[m3]; x2=xh[m1]; y2=yh[m1]; break; //=========================================================== // Case 4 - Line between vertex 1 and side 2-3 //=========================================================== case 4: x1=xh[m1]; y1=yh[m1]; x2=xsect(m2,m3); y2=ysect(m2,m3); break; //=========================================================== // Case 5 - Line between vertex 2 and side 3-1 //=========================================================== case 5: x1=xh[m2]; y1=yh[m2]; x2=xsect(m3,m1); y2=ysect(m3,m1); break; //=========================================================== // Case 6 - Line between vertex 3 and side 1-2 //=========================================================== case 6: x1=xh[m3]; y1=yh[m3]; x2=xsect(m1,m2); y2=ysect(m1,m2); break; //=========================================================== // Case 7 - Line between sides 1-2 and 2-3 //=========================================================== case 7: x1=xsect(m1,m2); y1=ysect(m1,m2); x2=xsect(m2,m3); y2=ysect(m2,m3); break; //=========================================================== // Case 8 - Line between sides 2-3 and 3-1 //=========================================================== case 8: x1=xsect(m2,m3); y1=ysect(m2,m3); x2=xsect(m3,m1); y2=ysect(m3,m1); break; //=========================================================== // Case 9 - Line between sides 3-1 and 1-2 //=========================================================== case 9: x1=xsect(m3,m1); y1=ysect(m3,m1); x2=xsect(m1,m2); y2=ysect(m1,m2); break; default: break; } //============================================================= // Put your processing code here and comment out the printf //============================================================= add_segment(SPair(SPoint(x1,y1),SPoint(x2,y2)),k); } } } } } } } return 0; } int CContourMap::generate_levels(double min, double max, int num) { double step=(max-min)/(num-1); if(levels) delete levels; levels=new double[num]; n_levels=num; for(int i=0;i<num;i++) { levels[i]=min+step*i; } return num; } CContourMap::CContourMap() { levels=NULL; n_levels=0; contour_level=NULL; } int CContourMap::add_segment(SPair t, int level) { // ensure that the object hierarchy has been allocated if(!contour_level) contour_level=new vector<CContourLevel*>(n_levels); if(!(*contour_level)[level]) (*contour_level)[level]=new CContourLevel; if(!(*contour_level)[level]->raw) (*contour_level)[level]->raw=new vector<SPair>; // push the value onto the end of the vector (*contour_level)[level]->raw->push_back(t); return(0); } int CContourMap::dump() { //sort the raw vectors if they exist vector<CContourLevel*>::iterator it=contour_level->begin(); int l=0; while(it!=contour_level->end()) { printf("Contour data at level %d [%f]\n",l,levels[l]); if(*it) (*it)->dump(); it++;l++; } fflush(NULL); return(0); } int CContourMap::consolidate() { //sort the raw vectors if they exist vector<CContourLevel*>::iterator it=contour_level->begin(); while(it!=contour_level->end()) { if(*it) (*it)->consolidate(); it++; } return(0); } CContourMap::~CContourMap() { if(levels) delete levels; if(contour_level) { vector<CContourLevel*>::iterator it=contour_level->begin(); while(it!=contour_level->end()) { delete(*it); it=contour_level->erase(it); } contour_level->clear(); delete contour_level; } } /* =============================================================================== the CContourLevel class contains all the contour data for any given contour level. initially this data is storred in point to point format in the raw vector, however functions exist to combine these vectors into groups (CContour) representing lines. */ int CContourLevel::dump() { // iterate thru the vector dumping values to STDOUT as we go // this function is intended for debugging purposes only printf("======================================================================\n"); if(raw) { printf("Raw vector data\n\n"); vector<SPair>::iterator it; it=raw->begin(); while(it!=raw->end()) { SPair t=*it; printf("\t(%f, %f)\t(%f, %f)\n",t.p1.x,t.p1.y,t.p2.x,t.p2.y); it++; } } if(contour_lines) { printf("Processed contour lines\n\n"); vector<CContour*>::iterator it=contour_lines->begin(); int c=1; while(it!=contour_lines->end()) { printf("Contour line %d:\n",c); (*it)->dump(); c++;it++; } } printf("======================================================================\n"); return(0); } int CContourLevel::consolidate() { vector<SPair>::iterator it; CContour *contour; int c=0; if(!raw) return(0); if (!contour_lines) contour_lines=new vector<CContour*>; std::sort(raw->begin(),raw->end()); while(!raw->empty()) { c++; it=raw->begin(); contour=new CContour(); contour->add_vector((*it).p1,(*it).p2); it=raw->erase(it); while(it!=raw->end()) { if((*it).p1==contour->end()) { contour->add_vector((*it).p1,(*it).p2); raw->erase(it); it=raw->begin(); } else it++; } contour_lines->push_back(contour); } delete raw;raw=NULL; fflush(NULL); c-=merge(); vector<CContour*>::iterator cit=contour_lines->begin(); while(cit!=contour_lines->end()) { (*cit)->condense(); cit++; } return(c); } int CContourLevel::merge() { vector<CContour*>::iterator it,jt; int c=0; if(contour_lines->size()<2) return(0); it=contour_lines->begin(); /* using two iterators we walk through the entire vector testing to see if some combination of the start and end points match. If we find matching points the two vectorsrs are merged. since when we go thru the vector once we are garanteed that all vectors that can connect to that oone have been merged we only have to merge the vector less the processed nodes at the begining. every merge does force jt back to the beginning of the search tho since a merge will change either the start or the end of the vector */ while(it!=contour_lines->end()) { jt=it+1; while(jt!=contour_lines->end()) { /* if the end of *it matches the start ot *jt we can copy *jt to the end of *it and remove jt, the erase funtion does us a favour and increments the iterator to the next element so we continue to test the next element */ if((*it)->end()==(*jt)->start()) { (*it)->merge(*jt); delete(*jt); contour_lines->erase(jt); jt=it+1; c++; } /* similarily if the end of *jt matches the start ot *it we can copy *it to the end of *jt and remove it,replacing it with jt, we then neet to update it to point at the just inserted record. */ else if((*jt)->end()==(*it)->start()) { (*jt)->merge(*it); delete(*it); (*it)=(*jt); contour_lines->erase(jt); jt=it+1; c++; } /* if both segments end at the same point we reverse one and merge it to the other, then remove the one we merged. */ else if((*it)->end()==((*jt)->end())) { (*jt)->reverse(); (*it)->merge(*jt); delete(*jt); contour_lines->erase(jt); jt=it+1; c++; } /* if both segments start at the same point reverse it, then merge it with jt, removing jt and reseting jt to the start of the search sequence */ else if((*it)->start()==((*jt)->start())) { (*it)->reverse(); (*it)->merge(*jt); delete(*jt); jt=contour_lines->erase(jt); c++; } else { jt++; } } it++; } return(c); } CContourLevel::~CContourLevel() { if(raw) { raw->clear(); delete raw; } if(contour_lines) { vector<CContour*>::iterator it=contour_lines->begin(); while(it!=contour_lines->end()) { delete (*it); it=contour_lines->erase(it); } contour_lines->clear(); delete contour_lines; } } /* =============================================================================== the CContour class stores actual individual contour lines in a vector,addition to the vector is handled by the add_vector function for individual vector components. in the case that one contour needs to be coppied to the end of another contour there is a merge function that will copy the second onto the end of the first. individual accessors are provided for the start and end points and the actual vector is publicly available. */ int CContour::add_vector(SPoint p1, SPoint p2) { // move the vector to the orgin SVector v; v.dx=p2.x-p1.x; v.dy=p2.y-p1.y; // if the contour vector does not exist create it // and set the starting point for this contour if(!contour) { contour=new vector<SVector>; _start=p1; } // insert the new vector to the end of the contour // and update the end point for this contour contour->push_back(v); _end=p2; return(0); } int CContour::reverse() { // swap the start and end points SPoint t=_end; _end=_start; _start=t; // iterate thru the entire vector and reverse each individual element // inserting them into a new vector as we go vector<SVector> *tmp=new vector<SVector>; vector<SVector>::iterator it=contour->begin(); while(it!=contour->end()) { (*it).dx*=-1; (*it).dy*=-1; tmp->insert(tmp->begin(),(*it)); it++; } // swap the old contour vector with the new reversed one we just generated delete contour; contour=tmp; return (0); } int CContour::merge(CContour *c) { this->contour->insert(this->contour->end(),c->contour->begin(),c->contour->end()); this->_end=c->_end; return(0); } int CContour::dump() { printf("\tStart: [%f, %f]\n\tEnd: [%f, %f]\n\tComponents>\n", _start.x,_start.y,_end.x,_end.y); vector<SVector>::iterator cit=contour->begin(); int c=1; SPoint p=_start; while(cit!=contour->end()) { p.x+=(*cit).dx; p.y+=(*cit).dy; printf("\t\t{%f, %f}\t[%f,%f]\n",(*cit).dx,(*cit).dy,p.x,p.y); c++,cit++; } return(0); } int CContour::condense(double difference) { /* at this time we potentially have multiple SVectors in the contour vector that are colinear and could be condensed into one SVector with, to determine if two successive vectors are colinear we take each vector and divide the y component of the vector by the x component, giving us the slope. we pass in a difference if the difference between th two slopes is less than the difference that we pass in and since we already know that both segments share a common point they can obviously be condensed. in the sample code on this page this is evident it the bounding rectangle. another possibility is modifying the code to allow point intersections on the plane. In this instance we may have multiple identical vectors with no magnitude that can be reduced to a single data point. */ vector<SVector>::iterator it,jt; double m1,m2; it=contour->begin(); jt=it+1; while(jt!=contour->end()) { if(((*jt).dx)&&((*it).dx)) { m1=(*jt).dy/(*jt).dx; m2=(*it).dy/(*jt).dx; } else if(((*jt).dy)&&((*it).dy)) { m1=(*jt).dx/(*jt).dy; m2=(*it).dx/(*jt).dy; } else { it++;jt++; continue; } if ((m1-m2<difference)&&(m2-m1<difference)) { (*it).dy+=(*jt).dy; (*it).dx+=(*jt).dx; jt=contour->erase(jt); } else { it++;jt++; } } return(0); } CContour::~CContour() { this->contour->clear(); delete this->contour; } #ifdef STANDALONE /* ============================================================================= the following is just test code to try to test that everything works together alright, we need to create an object that inherits from CRaster (ToMap in this case) that defines three functions, two returning each the lower and upper bounds respectively, and a third that returns the value at a given point. As we are assuming that data is regularly spaced we do not need to determine the x or y coordinate at this point as the original code did, rather we leave that for the rendering step to do by scaling the values as needed. ============================================================================= */ class ToMap:public CRaster { public: double value(double x,double y); SPoint upper_bound(); SPoint lower_bound(); }; double ToMap::value(double x, double y) { if(((int)x==1)&&((int)y==1)) return 1; else return 0; } SPoint ToMap::lower_bound() { return SPoint(0,0); } SPoint ToMap::upper_bound() { return SPoint(2,2); } int main(int argc, char *argv[]) { ToMap *m=new ToMap; CContourMap *map=new CContourMap; map->generate_levels(0,1,3); printf("Attempting to contour \n"); map->contour(m); map->dump(); printf("Consolidating Vectors\n"); map->consolidate(); printf("\n\n\n\t\tDumping Contour Map\n"); map->dump(); } #endif
34.326923
125
0.461024
jvo203
fcbfffa36fef185d08542e75b888b743f179cb7c
562
hpp
C++
LeetCode/C++/1150._Check_If_a_Number_Is_Majority_Element_in_a_Sorted_Array/solution.hpp
icgw/LeetCode
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
4
2018-09-12T09:32:17.000Z
2018-12-06T03:17:38.000Z
LeetCode/C++/1150._Check_If_a_Number_Is_Majority_Element_in_a_Sorted_Array/solution.hpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
LeetCode/C++/1150._Check_If_a_Number_Is_Majority_Element_in_a_Sorted_Array/solution.hpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
/* * solution.hpp * Copyright (C) 2019 Guowei Chen <icgw@outlook.com> * * Distributed under terms of the GPL license. */ #ifndef _SOLUTION_HPP_ #define _SOLUTION_HPP_ #include <vector> using std::vector; #include <algorithm> using std::equal_range; #include <iterator> using std::distance; class Solution { public: bool isMajorityElement(vector<int>& nums, int target) { auto eqrange = equal_range(nums.begin(), nums.end(), target); return distance(eqrange.first, eqrange.second) > (nums.size() >> 1); } }; #endif // ifndef _SOLUTION_HPP_
19.37931
72
0.706406
icgw
fcc8ff13d2044831c93f6a11cd4f8cf07c051dc0
752
hpp
C++
include/ParseEntry.hpp
astrowar/Cinform
f7fb7fcc3c3f83e1ee2691d968086e37faed038b
[ "MIT" ]
null
null
null
include/ParseEntry.hpp
astrowar/Cinform
f7fb7fcc3c3f83e1ee2691d968086e37faed038b
[ "MIT" ]
null
null
null
include/ParseEntry.hpp
astrowar/Cinform
f7fb7fcc3c3f83e1ee2691d968086e37faed038b
[ "MIT" ]
null
null
null
#ifndef PARSEENTRY_HPP #define PARSEENTRY_HPP #include <preprocess.hpp> #include <pmatch_baseClass.hpp> #include <list> using namespace std; namespace CInform { using namespace Match; namespace CodeParser { class MatchedParagraph { public: SParagraph* paragraph; list< MatchResult > mList; MatchedParagraph(SParagraph* _paragraph, list< MatchResult > _mList); }; class ParserEntry { public: HMatchExpended patten; string entryName; ParserEntry(string _entryName, HMatchExpended _patten); }; class ParserEntryGroup { public: std::list< std::pair< std::string, HMatch > > entryName_patten; ParserEntryGroup(list< ParserEntry> parserentries); void Add(ParserEntry p); }; } } #endif
14.745098
74
0.712766
astrowar
fcc95daaf86110f91a6d4456599568060fc64b4d
1,242
cpp
C++
Game/Source/ThroneAngel.cpp
aNnAm2606/PROJECT-II-BAKARA-SAN
84bbc8cc9f7ea9f5b1b3ece4ea4053c74e7ece7f
[ "MIT" ]
null
null
null
Game/Source/ThroneAngel.cpp
aNnAm2606/PROJECT-II-BAKARA-SAN
84bbc8cc9f7ea9f5b1b3ece4ea4053c74e7ece7f
[ "MIT" ]
7
2022-03-19T21:14:34.000Z
2022-03-19T21:53:13.000Z
Game/Source/ThroneAngel.cpp
aNnAm2606/PROJECT-II-BAKARA-SAN
84bbc8cc9f7ea9f5b1b3ece4ea4053c74e7ece7f
[ "MIT" ]
1
2022-03-08T12:25:02.000Z
2022-03-08T12:25:02.000Z
#include "ThroneAngel.h" #include "App.h" #include "Textures.h" #include "Render.h" #include "ATearsInHeaven.h" #include "AAngeleyes.h" #include "Audio.h" ThroneAngel::ThroneAngel(iPoint g_pos) : Enemy(g_pos) { p_CharacterName = "throne angel"; p_CharacterId = ECharacterType::ECHARACTER_MIPHARESH; p_Stats.health = 120; p_Stats.maxHealth = 120; p_Stats.damage = 15; p_Stats.speed = 10; p_CharacterFX = app->audio->LoadFx("Assets/Audio/Fx/dead2.wav"); p_CharacterSpriteSheet = app->tex->Load("Assets/Art/Enemies/final_boss_battle.png"); p_CharacterRect = { 0, 0, 128, 128 }; p_Abilities.push_back(new ATearsInHeaven(this)); p_Abilities.push_back(new AAngeleyes(this)); p_AttackAnimations.emplace_back(); p_AttackAnimations[0].PushBack({ 0, 0, 128, 128 }); p_AttackAnimations[0].speed = 0.2f; p_AttackAnimations[0].loop = false; p_AttackAnimations.emplace_back(); p_AttackAnimations[1].PushBack({ 0, 0, 128, 128 }); p_AttackAnimations[1].speed = 0.2f; p_AttackAnimations[1].loop = false; SDL_Rect rect = { 0, 256, 128, 128 }; for (int i = 0; i < 6; i++) { rect.x = i * 128; p_DeadAnimation.PushBack(rect); } p_DeadAnimation.speed = 0.2f; p_DeadAnimation.loop = false; } ThroneAngel::~ThroneAngel() { }
24.352941
85
0.714976
aNnAm2606
fccfe36132cf37ca81ba1440cf3ce6cc63e27f79
12,137
cpp
C++
tools/manager/src/user_config_descriptions.cpp
SleepKiller/swbfii-shaderpatch
b49ce3349d4dd09b19237ff4766652166ba1ffd4
[ "MIT" ]
5
2018-03-02T04:02:39.000Z
2018-08-07T19:36:50.000Z
tools/manager/src/user_config_descriptions.cpp
SleepKiller/swbfii-shaderpatch
b49ce3349d4dd09b19237ff4766652166ba1ffd4
[ "MIT" ]
27
2018-03-10T20:37:38.000Z
2018-10-08T11:10:34.000Z
tools/manager/src/user_config_descriptions.cpp
SleepKiller/swbfii-shaderpatch
b49ce3349d4dd09b19237ff4766652166ba1ffd4
[ "MIT" ]
null
null
null
#include "framework.hpp" #include "user_config_descriptions.hpp" using namespace std::literals; auto load_user_config_descriptions() -> std::unordered_map<std::wstring_view, std::wstring_view> { return { // clang-format off { L"Display"sv, LR"(Settings for controlling the display of the game.)"sv }, { L"Screen Percent"sv, LR"(Precentage of the sceen the game's window will take up. Value from 10 to 100.)"sv }, { L"Resolution Scale"sv, LR"(Render resolution scale, as a percentage. This controls the resolution the game will be rendered at but does not affect window size. For instance if your desktop resolution is 3840 x 2160 (4K) setting this to 50 will render the game at 1920 x 1080. The game will be upscaled back to 3840 x 2160 by the GPU when it is sent to the display. Lowering this can boost perforomance. Usage of an Anti-Aliasing Method with this option is highly reccomended.)"sv }, { L"Scale UI with Resolution Scale"sv, LR"(Keeps the game's UI and HUD from becoming illegible when Resolution Scale is used. This only has an effect if Display Scaling is 'yes'.)"sv }, { L"Allow Tearing"sv, LR"(Allow tearing when displaying frames. This can allow lower latency and is also required for variable refresh rate technologies to work.)"sv }, { L"Centred"sv, LR"(Whether to centre the window or not. If `ScreenPercent` is 100 there will be no difference between a centred and uncentred window.)"sv }, { L"Treat 800x600 As Interface"sv, LR"(Whether 800x600 will be treated as the resolution used by the game's main menu interface. When enabled causes Shader Patch to override the game's resolution without informing the game it has done so. Doing this keeps the interface usable while still letting you enjoy fullscreen ingame.)"sv }, { L"Windowed Interface"sv, LR"(When `Treat 800x600 As Interface` is `yes` controls whether the game's interface will be rendered fullscreen (which can lead to stretching on the UI) or if it'll be kept in a 800x600 window.)"sv }, { L"Display Scaling Aware"sv, LR"(Whether to mark the game DPI aware or not. When your display scaling is not at 100% having this be `yes` keeps the game being drawn at native resolution and stops Windows' upscaling it after the fact.)"sv }, { L"Display Scaling"sv, LR"(When `Display Scaling Aware` is `yes` controls if the game's perceived resolution will be scaled based on the display scaling factor. This effectively adjusts the scale UI and HUD elements are positioned and drawn with to match the display's scale.)"sv }, { L"Scalable Fonts"sv, LR"(Whether to replace the game's core fonts with ones that can be scaled. If you have any mods installed that also replace the game's fonts when this setting is enabled then they will be superseded by Shader Patch's fonts.)"sv }, { L"Enable Game Perceived Resolution Override"sv, LR"(Enables the overriding the resolution the game thinks it is rendering at, without changing the resolution it is actually rendered at. This can have the affect of altering the aspect ratio of the game and the scaling and position of UI/HUD elements. When set to `yes` causes `Display Scaling` to be ignored. If you're unsure what this is useful for then **leave** it set to "no".)"sv }, { L"Game Perceived Resolution Override"sv, LR"(The override for the game's perceived resolution, for use with `Enable Game Perceived Resolution Override`.)"sv }, { L"User Interface"sv, LR"(Settings affecting the user interface/HUD of the game. Note that Friend-Foe color changes do not work when a unit flashes on the minimap. They do work for everything else.)"sv }, { L"Extra UI Scaling"sv, LR"(Extra scaling for the UI/HUD on top of normal display scaling. As a percentage. This can be used to make text larger if it is too small but only has effect when Display Scaling is enabled. Note that the trick Shader Patch uses to scale the game's UI (lowering the resolution the game thinks it's rendering at) can't scale indefinitely, if changing this has to effect and you're on a high DPI screen it's possible you've hit the limit for how much scaling Shader Patch can allow.)"sv }, { L"Friend Color"sv, LR"(Color to use for Friend HUD and world elemenets. (Command Posts, crosshair, etc))"sv }, { L"Foe Color"sv, LR"(Color to use for Foe HUD and world elemenets. (Command Posts, crosshair, etc))"sv }, { L"Graphics"sv, LR"(Settings directly affecting the rendering of the game.)"sv }, { L"GPU Selection Method"sv, LR"(How to select the GPU to use. Can be "Highest Performance", "Lowest Power Usage", "Highest Feature Level", "Most Memory" or "Use CPU".)"sv }, { L"Anti-Aliasing Method"sv, LR"(Anti-Aliasing method to use, can be "none", "CMAA2", "MSAAx4" or "MSAAx8".)"sv }, { L"Supersample Alpha Test"sv, LR"(Enables supersampling the alpha test for hardedged transparency/alpha cutouts when Multisampling Anti-Aliasing is enabled. This provides excellent anti-aliasing for alpha cutouts (foliage, flat fences, etc) and should be much cheaper than general supersampling. It however does raise the number of texture samples that need to be taken by however many rendertarget samples there are - fast high end GPUs may not even notice this, low power mobile GPUs may struggle more. If enabling this causes performance issues but you'd still really like it then lowering the level of Anisotropic Filtering may help make reduce the performance cost of this option.)"sv }, { L"Anisotropic Filtering"sv, LR"(Anisotropic Filtering level for textures, can be "off", "x2", "x4", "x8" or "x16".)"sv }, { L"Enable 16-Bit Color Channel Rendering"sv, LR"(Controls whether R1G16B16A16 rendertargets will be used or not. Due to the way SWBFII is drawn using them can cut down significantly on banding. Additionally when they are enabled dithering will be applied when they are copied into R8G8B8A8 textures for display to further reduce banding. If Effects are enabled and HDR rendering is enabled by a map then this setting has no effect.)"sv }, { L"Enable Order-Independent Transparency"sv, LR"(Enables the use of an Order-Independent Transparency approximation. It should go without saying that this increases the cost of rendering. Requires a GPU with support for Rasterizer Ordered Views and typed Unordered Access View loads. When this is enabled transparent objects will no longer be affected by Multisample Anti-Aliasing (MSAA), this can be especially noticeable when using resolution scaling - although it does depend on the map. Postprocessing Anti-Aliasing options like CMAA2 are unaffected. Known to be buggy on old NVIDIA drivers. Try updating your GPU driver if you encounter issues.)"sv }, { L"Enable Alternative Post Processing"sv, LR"(Enables the use of an alternative post processing path for some of the game's post processing effects. The benefit to this is the alternative path is designed to be independent of the game's resolution and is unaffected by bugs the vanilla path suffers from relating to high resolutions. In some cases the alternative path may produce results that do not exactly match the intended look of a map.)"sv }, { L"Enable Scene Blur"sv, LR"(Enables maps to make use of the game's scene blur effect. Has a performance cost but using it will keep the map's artwork more inline with the creators vision. Note this is **unrelated** to the Effects system and also only takes effect when `Enable Alternative Post Processing` is `yes`.)"sv }, { L"Refraction Quality"sv, LR"(Quality level of refractions. Can be "Low", "Medium", "High" or "Ultra". "Low" sets the resolution of the refractions to 1/4 screen resolution, Medium 1/2, High 1/2 and Ultra matches screen resolution. On "High" or "Ultra" refractions will also be masked using the depth buffer.)"sv }, { L"Disable Light Brightness Rescaling"sv, LR"(In the vanilla shaders for most surfaces after calculating incoming light for a surface the brightness of the light is rescaled to keep it from being too dark or too bright. (Or at least that is what I *assume* the reason to be.) Disabling this can increase the realism and correctness of lighting for objects lit by the affected shaders. But for maps/mods that have had their lighting carefully balanced by the author it could do more harm than good. It is also likely to increase the amount of surfaces that are bright enough to cause light bloom in a scene. This setting has no affect on custom materials or when Effects are enabled. (Effects have an equivalent setting however.))"sv }, { L"Enable User Effects Config"sv, LR"(When a map or mod has not loaded an Effects Config Shader Patch can use a user specified config.)"sv }, { L"User Effects Config"sv, LR"(The name of the Effects Config to load when `Enable User Effects Config` is true. The config should be in the same directory as the game's executable.)"sv }, { L"Effects"sv, LR"(Settings for the Effects system, which allows modders to apply various effects to their mods at their discretion and configuration. Below are options provided to tweak the performance of this system for low-end/older GPUs.)"sv }, { L"Bloom"sv, LR"(Enable or disable a mod using the Bloom effect. This effect is can have a slight performance impact.)"sv }, { L"Vignette"sv, LR"(Enable or disable a mod using the Vignette effect. This effect is really cheap.)"sv }, { L"Film Grain"sv, LR"(Enable or disable a mod using the Film Grain effect. This effect is fairly cheap.)"sv }, { L"Allow Colored Film Grain"sv, LR"(Enable or disable a mod using being allowed to use Colored Film Grain. Slightly more expensive than just regular Film Grain, if a mod is using it.)"sv }, { L"SSAO"sv, LR"(Enable or disable a mod using Screen Space Ambient Occlusion. (Not actually true Ambient Occlusion as it is applied indiscriminately to opaque surfaces.) Has anywhere from a slight performance impact to significant performance impact depending on the quality setting.)"sv }, { L"SSAO Quality"sv, LR"(Quality of SSAO when enabled. Can be "Fastest", "Fast", Medium", "High" or "Highest". Each step up is usually 1.5x-2.0x more expensive than the last setting.)"sv }, { L"Developer"sv, LR"(Settings for both mod makers and Shader Patch developers. If you don't fall into those groups these settings likely aren't useful.)"sv }, { L"Screen Toggle"sv, LR"(Toggle key for the developer screen. Giving access to useful things for mod makers and Shader Patch developers alike. The value identifies the virtual key that activates the debug screen, below are some common values for you to choose from. (Copy and paste the value on the right of your desired key.) '~': 0xC0 '\': 0xDC 'Backspace': 0x08 'F12': 0x7B)"sv }, { L"Monitor BFront2.log"sv, LR"(Enables the monitoring, filtering and display of "BFront2.log" ingame. Can not be changed ingame. Only useful to modders.)"sv }, { L"Allow Event Queries"sv, LR"(Controls whether or not Shader Patch will allow the game to use GPU event queries.)"sv }, { L"Use D3D11 Debug Layer"sv, LR"(Enable the D3D11 debug layer, typically requires the Windows SDK to be installed to work. Even if this flag is true the debug layer will only be enabled if a debugger is attached to the game.)"sv }, { L"Use DXGI 1.2 Factory"sv, LR"(Limit Shader Patch to using a DXGI 1.2 factory to work around a crash in the Visual Studio Graphics Debugger. This also bypasses all GPU selection logic.)"sv }, { L"Shader Cache Path"sv, LR"(Path for shader cache file.)"sv }, { L"Shader Definitions Path"sv, LR"(Path to shader definitions. (.json files describing shader entrypoints and variations within a file))"sv }, { L"Shader Source Path"sv, LR"(Path to shader HLSL source files.)"sv }, { L"Material Scripts Path"sv, LR"(Path to material types Lua scripts.)"sv }, { L"Scalable Font Name"sv, LR"(Name of the font to use when Scalable Fonts are enabled.)"sv }, // clang-format on }; }
40.456667
347
0.7445
SleepKiller
fcd2cf26083ee49eefd2636c16d5414e6467837c
2,089
hpp
C++
include/ezdxf/acdb/object.hpp
mozman/ezdxf.cpp
09295f7dafe2a76253807fccd92560fd45eb97a5
[ "MIT" ]
2
2021-02-10T08:14:59.000Z
2021-12-09T08:55:01.000Z
include/ezdxf/acdb/object.hpp
mozman/ezdxf.cpp
09295f7dafe2a76253807fccd92560fd45eb97a5
[ "MIT" ]
null
null
null
include/ezdxf/acdb/object.hpp
mozman/ezdxf.cpp
09295f7dafe2a76253807fccd92560fd45eb97a5
[ "MIT" ]
1
2021-02-10T08:25:20.000Z
2021-02-10T08:25:20.000Z
// Copyright (c) 2021, Manfred Moitzi // License: MIT License // #ifndef EZDXF_OBJECT_HPP #define EZDXF_OBJECT_HPP #include <stdexcept> #include "ezdxf/type.hpp" namespace ezdxf::acdb { using ezdxf::Handle; // acdb::Object is the base class for all DXF entities in a DXF Document // which have a handle. // The handle can only be assigned once! class Object { private: unsigned int status_{0}; // status flags Handle handle_{0}; // 0 represents an unassigned handle Handle owner_{0}; // 0 represents no owner public: enum class Status { kErased = 1 }; Object() = default; explicit Object(Handle handle, Handle owner = 0) : Object{} { set_handle(handle); if (owner) set_owner(owner); } virtual ~Object() = default; // Returns the DXF type as specified in the DXF file: // Object is not a real DXF object, it is the base class for all // DXF entities. virtual DXFType dxf_type() { return DXFType::None; } // Returns the corresponding ObjectARX® type: virtual ARXType arx_type() { return ARXType::AcDbObject; } [[nodiscard]] bool is_erased() const { return status_ & static_cast<unsigned int>(Status::kErased); } [[nodiscard]] bool is_alive() const { return !is_erased(); } [[nodiscard]] Handle get_handle() const { return handle_; } void set_handle(Handle h) { if (handle_) // handle is immutable if != 0 throw std::invalid_argument("assigned handle is immutable"); handle_ = h; } [[nodiscard]] Handle get_owner() const { return owner_; } void set_owner(Handle o) { owner_ = o; } virtual void erase() { // Set object status to erased, DXF objects will not be destroyed at // the lifetime of a DXF document! status_ |= static_cast<unsigned int>(Status::kErased); } }; } #endif //EZDXF_OBJECT_HPP
28.616438
80
0.589756
mozman
fcd35c88697a8f366574654be0f2823e1a878233
8,815
cc
C++
misc/slowlink/slowlink.cc
flipk/pfkutils
d8f6c22720b6fcc44a882927c745a822282d1f69
[ "Unlicense" ]
4
2015-06-12T05:08:56.000Z
2017-11-13T11:34:27.000Z
misc/slowlink/slowlink.cc
flipk/pfkutils
d8f6c22720b6fcc44a882927c745a822282d1f69
[ "Unlicense" ]
null
null
null
misc/slowlink/slowlink.cc
flipk/pfkutils
d8f6c22720b6fcc44a882927c745a822282d1f69
[ "Unlicense" ]
1
2021-10-20T02:04:53.000Z
2021-10-20T02:04:53.000Z
#include "LockWait.h" #include "thread_slinger.h" #include "pfkposix.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <inttypes.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #define BAIL(condition,what) \ if (condition) { \ int e = errno; \ fprintf(stderr, what ": %d:%s\n", e, strerror(e)); \ return 1; \ } //#define PRINTF(x...) #define PRINTF(x...) printf(x) #define PRINTF2(x...) //#define PRINTF2(x...) printf(x) struct fdBuffer : public ThreadSlinger::thread_slinger_message { fdBuffer(void) { buffer = NULL; } ~fdBuffer(void) { if (buffer != NULL) delete[] buffer; } static int BUFFERSIZE; pfk_timeval stamp; // the time at which this should be sent. int length; char * buffer; void init(void) { if (buffer == NULL) buffer = new char[BUFFERSIZE]; } }; int fdBuffer::BUFFERSIZE = 0; // must be initialized typedef ThreadSlinger::thread_slinger_pool<fdBuffer> fdBufPool; typedef ThreadSlinger::thread_slinger_queue<fdBuffer> fdBufQ; struct connection_config { uint32_t latency; int server_fd; int client_fd; bool reader0_running; bool reader1_running; bool writer0_running; bool writer1_running; bool die; bool doServer; WaitUtil::Semaphore thread_init_sem; WaitUtil::Semaphore client_tokens; WaitUtil::Semaphore server_tokens; fdBufPool ctsPool; fdBufPool stcPool; fdBufQ ctsQ; fdBufQ stcQ; }; #define TICKS_PER_SECOND 20 void * reader_thread_routine( void * ); void * writer_thread_routine( void * ); int main(int argc, char ** argv) { if (argc != 6) { fprintf(stderr, "usage: slowlink bytes_per_second latency_in_mS " "listen_port remote_ip remote_port\n"); return 1; } try { connection_config cfg; fdBuffer::BUFFERSIZE = atoi(argv[1]) / TICKS_PER_SECOND; cfg.latency = atoi(argv[2]); uint16_t listen_port = atoi(argv[3]); char * remote_ip = argv[4]; uint16_t remote_port = atoi(argv[5]); int v = 1, listen_fd = -1; struct sockaddr_in sa; struct in_addr remote_inaddr; pthread_t id; pthread_attr_t pthattr; if (!inet_aton(remote_ip, &remote_inaddr)) { fprintf(stderr, "unable to parse ip address '%s'\n", remote_ip); return 1; } listen_fd = socket(AF_INET, SOCK_STREAM, 0); BAIL(listen_fd < 0, "socket"); cfg.client_fd = socket(AF_INET, SOCK_STREAM, 0); BAIL(cfg.client_fd < 0, "socket"); v = 1; setsockopt( listen_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &v, sizeof( v )); sa.sin_family = AF_INET; sa.sin_port = htons(listen_port); sa.sin_addr.s_addr = htonl(INADDR_ANY); v = bind( listen_fd, (struct sockaddr *) &sa, sizeof(sa)); BAIL(v < 0, "bind"); listen( listen_fd, 1 ); socklen_t salen = sizeof(sa); cfg.server_fd = accept( listen_fd, (struct sockaddr *) &sa, &salen ); BAIL( cfg.server_fd < 0, "accept" ); close( listen_fd ); sa.sin_port = htons(remote_port); sa.sin_addr = remote_inaddr; v = connect(cfg.client_fd, (struct sockaddr *) &sa, sizeof(sa)); BAIL(v < 0, "connect"); cfg.thread_init_sem.init(0); cfg.ctsPool.add(100); cfg.stcPool.add(100); cfg.reader0_running = false; cfg.reader1_running = false; cfg.writer0_running = false; cfg.writer1_running = false; cfg.die = false; pthread_attr_init( &pthattr ); pthread_attr_setdetachstate( &pthattr, PTHREAD_CREATE_DETACHED ); cfg.doServer = true; pthread_create(&id, &pthattr, reader_thread_routine, &cfg); cfg.thread_init_sem.take(); cfg.doServer = false; pthread_create(&id, &pthattr, reader_thread_routine, &cfg); cfg.thread_init_sem.take(); cfg.doServer = true; pthread_create(&id, &pthattr, writer_thread_routine, &cfg); cfg.thread_init_sem.take(); cfg.doServer = false; pthread_create(&id, &pthattr, writer_thread_routine, &cfg); cfg.thread_init_sem.take(); pthread_attr_destroy( &pthattr ); while (cfg.reader0_running == true && cfg.reader1_running == true && cfg.writer0_running == true && cfg.writer1_running == true) { usleep(1000000 / TICKS_PER_SECOND); // issue tokens cfg.client_tokens.give(); cfg.server_tokens.give(); PRINTF2("%d %d %d %d\n", cfg.reader0_running, cfg.reader1_running, cfg.writer0_running, cfg.writer1_running); }; // we got here because one of the connections // apparently died. attempt to clean up. // note: this part doesn't seem to work worth a damn. cfg.die = true; if (cfg.client_fd != -1) close(cfg.client_fd); if (cfg.server_fd != -1) close(cfg.server_fd); cfg.client_tokens.give(); cfg.server_tokens.give(); while (cfg.reader0_running == true || cfg.reader1_running == true || cfg.writer0_running == true || cfg.writer1_running == true) { usleep(1); } } catch (WaitUtil::LockableError e) { fprintf(stderr, "LockableError: %s\n", e.Format().c_str()); } catch (DLL3::ListError e) { fprintf(stderr, "DLL3 error: %s\n", e.Format().c_str()); } return 0; } void * reader_thread_routine( void * _cfg ) { connection_config * cfg = (connection_config *) _cfg; bool doServer = cfg->doServer; bool *myRunning = doServer ? &cfg->reader0_running : &cfg->reader1_running; int myfd = doServer ? cfg->server_fd : cfg->client_fd; fdBufPool *myPool = doServer ? &cfg->stcPool : &cfg->ctsPool; fdBufQ *myQ = doServer ? &cfg->stcQ : &cfg->ctsQ; fdBuffer * buf; pfk_timeval latency; latency.tv_sec = cfg->latency / 1000; // ms to sec latency.tv_usec = (cfg->latency % 1000) * 1000; // ms to us *myRunning = true; cfg->thread_init_sem.give(); while (cfg->die == false) { PRINTF("reader %d trying to alloc\n", doServer); buf = myPool->alloc(-1); buf->init(); PRINTF("reader %d got a buffer, attempting read\n", doServer); buf->length = read(myfd, buf->buffer, fdBuffer::BUFFERSIZE); PRINTF("reader %d got read of %d\n", doServer, buf->length); if (buf->length <= 0) { fprintf(stderr, "got read of %d on fd %d\n", buf->length, myfd); break; } gettimeofday(&buf->stamp, NULL); buf->stamp += latency; myQ->enqueue(buf); } *myRunning = false; return NULL; } void * writer_thread_routine( void * _cfg ) { connection_config * cfg = (connection_config *) _cfg; bool doServer = cfg->doServer; bool *myRunning = doServer ? &cfg->writer0_running : &cfg->writer1_running; pfk_timeval now; WaitUtil::Semaphore *myTokens = doServer ? &cfg->server_tokens : &cfg->client_tokens; fdBufQ *myQ = doServer ? &cfg->stcQ : &cfg->ctsQ; fdBufPool *myPool = doServer ? &cfg->stcPool : &cfg->ctsPool; int myfd = doServer ? cfg->client_fd : cfg->server_fd; fdBuffer * buf; *myRunning = true; cfg->thread_init_sem.give(); while (cfg->die == false && myTokens->take()) { gettimeofday(&now, NULL); buf = myQ->get_head(); if (buf == NULL) // queue empty, nothing to do. continue; if (buf->stamp > now) { // packet not old enough, let it age. PRINTF2("writer %d now %d.%06d < stamp %d.%06d\n", doServer, (int)now.tv_sec, (int)now.tv_usec, (int)buf->stamp.tv_sec, (int)buf->stamp.tv_usec); continue; } buf = myQ->dequeue(); PRINTF("writer %d attempting %d\n", doServer, buf->length); int cc = write(myfd, buf->buffer, buf->length); PRINTF("writer %d attempt %d returns %d\n", doServer, buf->length, cc); if (cc != buf->length) { fprintf(stderr, "write attempt %d returns %d on fd %d\n", buf->length, cc, myfd); cfg->die = true; break; } myPool->release(buf); } *myRunning = false; return NULL; }
32.054545
79
0.5789
flipk
fcd423355edaa0699203c38ccaf8674ee876b34d
3,699
cpp
C++
src/bullet.cpp
hanss314/PyDanmaku
4c6c27d1fa1c687bfa1f356f66f0ee006d6911f3
[ "MIT" ]
null
null
null
src/bullet.cpp
hanss314/PyDanmaku
4c6c27d1fa1c687bfa1f356f66f0ee006d6911f3
[ "MIT" ]
13
2018-01-29T02:00:26.000Z
2018-11-05T05:36:27.000Z
src/bullet.cpp
hanss314/PyDanmaku
4c6c27d1fa1c687bfa1f356f66f0ee006d6911f3
[ "MIT" ]
8
2018-01-29T04:47:55.000Z
2018-10-15T11:49:11.000Z
#include <stdbool.h> #include <math.h> #include <cstdio> #include <iostream> #include "../include/bullet.h" bool Bullet::run(double timestep, Bullet ref){ lx = x; ly = y; la = angle; lc = c; ls = s; //leave old reference frame double nx, ny; if (_ref_applied){ x -= ref.lx; y -= ref.ly; angle -= ref.la; nx = x*ref.lc + y*ref.ls; ny = y*ref.lc - x*ref.ls; x = nx; y = ny; } else { _ref_applied = true; } //apply movement speed += acceleration * timestep; angle += angular_momentum * timestep; x += cosf(angle) * speed * timestep; y += sinf(angle) * speed * timestep; //enter new reference frame nx = x*ref.c - y*ref.s; ny = y*ref.c + x*ref.s; x = nx; y = ny; x += ref.x; y += ref.y; angle += ref.angle; // set angle stuff angle = fmod(angle, (double) M_PI * 2); this->s = sinf(angle); this->c = cosf(angle); life++; return x < -10 || x > 650 || y < -10 || y > 490; } bool Bullet::run(double timestep){ lx = x; ly = y; la = angle; lc = c; ls = s; this->s = sinf(angle); this->c = cosf(angle); speed += acceleration * timestep; angle += angular_momentum * timestep; x += c * speed * timestep; y += s * speed * timestep; angle = fmod(angle, (double) M_PI * 2); life++; return x < -10 || x > 650 || y < -10 || y > 490; } bool Bullet::broad_search(double x, double y, double radius){ double dx = x - this->x, dy = y - this->y; return sqrt(dx*dx + dy*dy) <= radius + this->radius; } bool Bullet::collides(double x, double y, double radius){ if (!this->broad_search(x, y, radius)) return false; // transform to 0,0 x -= this->x; y -= this->y; // transform so rotation is 0 // normal equation is x = xcos - ysin; y = xsin + ycos // we're reversing the rotation, cos(-a) = cos(a), sin(-a) = -sin(a) // equation becomes x = xcos + ysin; y = ycos-xsin double tx = x*this->c + y*this->s; double ty = y*this->c - x*this->s; // move into one quadrant if (tx < 0) tx = -tx; if (ty < 0) ty = -ty; // extents in quadrant double w = this->width/2, h = this->height/2; if (this->is_rect) { // is it intersecting the top or right? if ((tx + radius <= w && ty <= h) || (ty + radius <= h && tx <= w)) return true; // find distance from corner and test if intersecting corner double dx = tx - h, dy = tx - w; return sqrt(dx * dx + dy * dy) <= radius; } else { // extend ellipse by radius of circle // will test if the centre of the circle is within the bigger ellipse w += radius; h += radius; // transform to a unit circle x /= w; y /= h; // if we're within the unit circle, we were within the bigger ellipse return sqrt(x*x + y*y) <= 1; } } Bullet::Bullet(){ Bullet(0.0, 0.0, true, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); this->c = this->lc = 1.0; } Bullet::Bullet( double x, double y, bool is_rect, double width, double height, double speed, double angle, double accel, double ang_m ){ this->x = lx = x; this->y = ly = y; this->width = width; this->height = height; if (is_rect) { this->radius = sqrt(width * width + height * height); } else if (width > height){ this->radius = width; } else { this->radius = height; } this->is_rect = is_rect; this->speed = speed; this->angle = la = fmod(angle, 2*M_PI); this->acceleration = accel; this->angular_momentum = ang_m; this->s = this->ls = sinf(angle); this->c = this->lc = cosf(angle); this->_is_curvy = false; }
28.236641
88
0.546364
hanss314
fcd47b2b032bd3c6cb3ff077f8124968c2d8b4a5
5,206
hpp
C++
src/include/duckdb/function/table/arrow.hpp
taniabogatsch/duckdb
dbb043b1149bdd70feec5cce131222d7897a3b91
[ "MIT" ]
null
null
null
src/include/duckdb/function/table/arrow.hpp
taniabogatsch/duckdb
dbb043b1149bdd70feec5cce131222d7897a3b91
[ "MIT" ]
null
null
null
src/include/duckdb/function/table/arrow.hpp
taniabogatsch/duckdb
dbb043b1149bdd70feec5cce131222d7897a3b91
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/function/table/arrow.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/function/table_function.hpp" #include "duckdb/common/arrow_wrapper.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/pair.hpp" #include "duckdb/common/thread.hpp" #include "duckdb/common/unordered_map.hpp" namespace duckdb { //===--------------------------------------------------------------------===// // Arrow Variable Size Types //===--------------------------------------------------------------------===// enum class ArrowVariableSizeType : uint8_t { FIXED_SIZE = 0, NORMAL = 1, SUPER_SIZE = 2 }; //===--------------------------------------------------------------------===// // Arrow Time/Date Types //===--------------------------------------------------------------------===// enum class ArrowDateTimeType : uint8_t { MILLISECONDS = 0, MICROSECONDS = 1, NANOSECONDS = 2, SECONDS = 3, DAYS = 4, MONTHS = 5 }; struct ArrowConvertData { ArrowConvertData(LogicalType type) : dictionary_type(type) {}; ArrowConvertData() {}; //! Hold type of dictionary LogicalType dictionary_type; //! If its a variable size type (e.g., strings, blobs, lists) holds which type it is vector<pair<ArrowVariableSizeType, idx_t>> variable_sz_type; //! If this is a date/time holds its precision vector<ArrowDateTimeType> date_time_precision; }; typedef unique_ptr<ArrowArrayStreamWrapper> (*stream_factory_produce_t)( uintptr_t stream_factory_ptr, pair<unordered_map<idx_t, string>, vector<string>> &project_columns, TableFilterSet *filters); typedef void (*stream_factory_get_schema_t)(uintptr_t stream_factory_ptr, ArrowSchemaWrapper &schema); struct ArrowScanFunctionData : public TableFunctionData { ArrowScanFunctionData(idx_t rows_per_thread_p, stream_factory_produce_t scanner_producer_p, uintptr_t stream_factory_ptr_p) : lines_read(0), rows_per_thread(rows_per_thread_p), stream_factory_ptr(stream_factory_ptr_p), scanner_producer(scanner_producer_p), number_of_rows(0) { } //! This holds the original list type (col_idx, [ArrowListType,size]) unordered_map<idx_t, unique_ptr<ArrowConvertData>> arrow_convert_data; atomic<idx_t> lines_read; ArrowSchemaWrapper schema_root; idx_t rows_per_thread; //! Pointer to the scanner factory uintptr_t stream_factory_ptr; //! Pointer to the scanner factory produce stream_factory_produce_t scanner_producer; //! Number of rows (Used in cardinality and progress bar) int64_t number_of_rows; }; struct ArrowScanLocalState : public LocalTableFunctionState { explicit ArrowScanLocalState(unique_ptr<ArrowArrayWrapper> current_chunk) : chunk(move(current_chunk)) { } unique_ptr<ArrowArrayStreamWrapper> stream; shared_ptr<ArrowArrayWrapper> chunk; idx_t chunk_offset = 0; vector<column_t> column_ids; //! Store child vectors for Arrow Dictionary Vectors (col-idx,vector) unordered_map<idx_t, unique_ptr<Vector>> arrow_dictionary_vectors; TableFilterSet *filters = nullptr; }; struct ArrowScanGlobalState : public GlobalTableFunctionState { unique_ptr<ArrowArrayStreamWrapper> stream; mutex main_mutex; bool ready = false; idx_t max_threads = 1; idx_t MaxThreads() const override { return max_threads; } }; struct ArrowTableFunction { public: static void RegisterFunction(BuiltinFunctions &set); private: //! Binds an arrow table static unique_ptr<FunctionData> ArrowScanBind(ClientContext &context, TableFunctionBindInput &input, vector<LogicalType> &return_types, vector<string> &names); //! Actual conversion from Arrow to DuckDB static void ArrowToDuckDB(ArrowScanLocalState &scan_state, std::unordered_map<idx_t, unique_ptr<ArrowConvertData>> &arrow_convert_data, DataChunk &output, idx_t start); //! Initialize Global State static unique_ptr<GlobalTableFunctionState> ArrowScanInitGlobal(ClientContext &context, TableFunctionInitInput &input); //! Initialize Local State static unique_ptr<LocalTableFunctionState> ArrowScanInitLocal(ClientContext &context, TableFunctionInitInput &input, GlobalTableFunctionState *global_state); //! Scan Function static void ArrowScanFunction(ClientContext &context, TableFunctionInput &data, DataChunk &output); //! Defines Maximum Number of Threads static idx_t ArrowScanMaxThreads(ClientContext &context, const FunctionData *bind_data); //! -----Utility Functions:----- //! Gets Arrow Table's Cardinality static unique_ptr<NodeStatistics> ArrowScanCardinality(ClientContext &context, const FunctionData *bind_data); //! Gets the progress on the table scan, used for Progress Bars static double ArrowProgress(ClientContext &context, const FunctionData *bind_data, const GlobalTableFunctionState *global_state); }; } // namespace duckdb
39.439394
117
0.673838
taniabogatsch
fcd918f9674ae48735def26586888e3eac1c701a
3,018
cpp
C++
Source/AsteroidShooter/Laser.cpp
goatryder/asteroidShooter
501b181ab7ccfe98f77b2426e858f3d68aba0b8b
[ "MIT" ]
null
null
null
Source/AsteroidShooter/Laser.cpp
goatryder/asteroidShooter
501b181ab7ccfe98f77b2426e858f3d68aba0b8b
[ "MIT" ]
null
null
null
Source/AsteroidShooter/Laser.cpp
goatryder/asteroidShooter
501b181ab7ccfe98f77b2426e858f3d68aba0b8b
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Laser.h" #include "UObject/ConstructorHelpers.h" #include "Components/StaticMeshComponent.h" #include "Components/AudioComponent.h" // Sets default values ALaser::ALaser() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; struct FConstructorStatics { ConstructorHelpers::FObjectFinderOptional<UStaticMesh> LaserMesh; ConstructorHelpers::FObjectFinderOptional<USoundBase> LaserSound; FConstructorStatics() : LaserMesh(TEXT("/Game/Geometry/Meshes/Laser.Laser")), LaserSound(TEXT("/Game/Sound/Laser.Laser")) {} }; static FConstructorStatics ConstructorStatics; LaserMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Laser Mesh")); LaserMesh->SetStaticMesh(ConstructorStatics.LaserMesh.Get()); LaserMesh->SetWorldScale3D(FVector(0.5f)); RootComponent = LaserMesh; // add material to mesh UMaterial* TempMaterial = CreateDefaultSubobject<UMaterial>(TEXT("Laser Material")); TempMaterial = ConstructorHelpers::FObjectFinderOptional<UMaterial>( TEXT("/Game/Geometry/Materials/LaserMaterial.LaserMaterial")).Get(); LaserMesh->SetMaterial(int32(), TempMaterial); Sound = CreateDefaultSubobject<UAudioComponent>(TEXT("Laser Sound")); Sound->SetSound(ConstructorStatics.LaserSound.Get()); Sound->Play(); // Use this component to drive this projectile's movement. ProjectileMovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovementComponent")); ProjectileMovementComponent->SetUpdatedComponent(RootComponent); ProjectileMovementComponent->InitialSpeed = 3000.0f; ProjectileMovementComponent->MaxSpeed = 3000.0f; ProjectileMovementComponent->bRotationFollowsVelocity = true; ProjectileMovementComponent->bShouldBounce = true; ProjectileMovementComponent->Bounciness = 0.3f; // Initial values Direction = FVector(1.0f, 0.0f, 0.0f); LaunchSpeed = 10000.0f; SurvivalTime = 5.0f; TimeElapsed = 0.0f; Tags.Add(TEXT("Laser")); } // constructor // Called when the game starts or when spawned void ALaser::BeginPlay() { Super::BeginPlay(); } // Called every frame void ALaser::Tick(float DeltaTime) { Super::Tick(DeltaTime); TimeElapsed += DeltaTime; if (TimeElapsed > SurvivalTime) Destroy(); const FVector LocalMove = Direction * DeltaTime * LaunchSpeed; AddActorLocalOffset(LocalMove, true); } // tick void ALaser::NotifyHit(UPrimitiveComponent* MyComp, AActor* Other, UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit) { // if (!Other->ActorHasTag("Player")) // Destroy(); // else // AddActorLocalOffset(FVector(10.0f, 0.0f, 0.0f), false); if (Other->ActorHasTag("Player")) AddActorLocalOffset(FVector(10.0f, 0.0f, 0.0f), false); } void ALaser::OnBeginOverlap(AActor* ProjectileActor, AActor* OtherActor) { }
27.944444
121
0.765408
goatryder
fcd97e4cf10acbe5abf8b388a2c35d5f4e63d5f2
8,818
cpp
C++
src/nyx/features/caliper_feret.cpp
sameeul/nyxus
46210ac218b456f822139e884dfed4bd2fdbbfce
[ "MIT" ]
null
null
null
src/nyx/features/caliper_feret.cpp
sameeul/nyxus
46210ac218b456f822139e884dfed4bd2fdbbfce
[ "MIT" ]
6
2022-02-09T20:42:43.000Z
2022-03-24T20:14:47.000Z
src/nyx/features/caliper_feret.cpp
sameeul/nyxus
46210ac218b456f822139e884dfed4bd2fdbbfce
[ "MIT" ]
4
2022-02-03T20:26:23.000Z
2022-02-17T02:59:27.000Z
#include "caliper.h" #include "../parallel.h" #include "rotation.h" CaliperFeretFeature::CaliperFeretFeature() : FeatureMethod("CaliperFeretFeature") { // Letting the feature dependency manager know provide_features({ MIN_FERET_DIAMETER, MAX_FERET_DIAMETER, MIN_FERET_ANGLE, MAX_FERET_ANGLE, STAT_FERET_DIAM_MIN, STAT_FERET_DIAM_MAX, STAT_FERET_DIAM_MEAN, STAT_FERET_DIAM_MEDIAN, STAT_FERET_DIAM_STDDEV, STAT_FERET_DIAM_MODE}); } void CaliperFeretFeature::calculate(LR& r) { if (r.has_bad_data()) return; std::vector<double> allD; // Diameters at 0-180 degrees rotation calculate_imp(r.convHull_CH, allD); // Calculate statistics of diameters auto s = ComputeCommonStatistics2(allD); _min = (double)s.min; _max = (double)s.max; _mean = s.mean; _median = s.median; _stdev = s.stdev; _mode = (double)s.mode; // Calculate angles at min- and max- diameter if (allD.size() > 0) { // Min and max auto itr_min_d = std::min_element(allD.begin(), allD.end()); auto itr_max_d = std::max_element(allD.begin(), allD.end()); minFeretDiameter = *itr_min_d; maxFeretDiameter = *itr_max_d; // Angles auto idxMin = std::distance(allD.begin(), itr_min_d); minFeretAngle = (double)idxMin / 2.0; auto idxMax = std::distance(allD.begin(), itr_max_d); maxFeretAngle = (double)idxMax / 2.0; } else { // Degenerate case minFeretDiameter = maxFeretDiameter = minFeretAngle = maxFeretAngle = 0.0; } } void CaliperFeretFeature::save_value(std::vector<std::vector<double>>& fvals) { fvals[MIN_FERET_DIAMETER][0] = minFeretDiameter; fvals[MAX_FERET_DIAMETER][0] = maxFeretDiameter; fvals[MIN_FERET_ANGLE][0] = minFeretAngle; fvals[MAX_FERET_ANGLE][0] = maxFeretAngle; fvals[STAT_FERET_DIAM_MIN][0] = _min; fvals[STAT_FERET_DIAM_MAX][0] = _max; fvals[STAT_FERET_DIAM_MEAN][0] = _mean; fvals[STAT_FERET_DIAM_MEDIAN][0] = _median; fvals[STAT_FERET_DIAM_STDDEV][0] = _stdev; fvals[STAT_FERET_DIAM_MODE][0] = _mode; } void CaliperFeretFeature::calculate_imp(const std::vector<Pixel2>& convex_hull, std::vector<double>& all_D) { // Rotated convex hull std::vector<Pixel2> CH_rot; CH_rot.reserve(convex_hull.size()); // Rotate and calculate the diameter all_D.clear(); for (float theta = 0.f; theta < 180.f; theta += rot_angle_increment) { Rotation::rotate_around_center(convex_hull, theta, CH_rot); auto [minX, minY, maxX, maxY] = AABB::from_pixelcloud(CH_rot); // Diameters at this angle std::vector<float> DA; // Iterate the y-grid float stepY = (maxY - minY) / float(n_steps); for (int iy = 1; iy <= n_steps; iy++) { float chord_y = minY + iy * stepY; // Find convex hull segments intersecting 'y' std::vector<std::pair<float, float>> X; // intersection points for (int iH = 1; iH < CH_rot.size(); iH++) { // The convex hull points are guaranteed to be consecutive auto& a = CH_rot[iH - 1], & b = CH_rot[iH]; // Chord's Y is between segment AB's Ys ? if ((a.y >= chord_y && b.y <= chord_y) || (b.y >= chord_y && a.y <= chord_y)) { auto chord_x = b.y != a.y ? (b.x - a.x) * (chord_y - a.y) / (b.y - a.y) + a.x : (b.y + a.y) / 2; auto tup = std::make_pair(chord_x, chord_y); X.push_back(tup); } } // Save the length of this chord. There must be 2 items in 'chordEnds' because we don't allow uniformative chords of zero length if (X.size() >= 2) { // for N segments auto compareFunc = [](const std::pair<float, float>& p1, const std::pair<float, float>& p2) { return p1.first < p2.first; }; auto idx_minX = std::distance(X.begin(), std::min_element(X.begin(), X.end(), compareFunc)); auto idx_maxX = std::distance(X.begin(), std::max_element(X.begin(), X.end(), compareFunc)); // left X and right X segments auto& e1 = X[idx_minX], & e2 = X[idx_maxX]; auto x1 = e1.first, y1 = e1.second, x2 = e2.first, y2 = e2.second; // save this chord auto dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Squared distance DA.push_back(dist); } } if (DA.size() > 0) { // Find the shortest and longest chords (diameters) double minD2 = *std::min_element(DA.begin(), DA.end()), maxD2 = *std::max_element(DA.begin(), DA.end()), min_ = sqrt(minD2), max_ = sqrt(maxD2); // Save them all_D.push_back(min_); all_D.push_back(max_); } } } void CaliperFeretFeature::osized_calculate(LR& r, ImageLoader&) { // Rotated convex hull std::vector<Pixel2> CH_rot; CH_rot.reserve(r.convHull_CH.size()); // Rotate and calculate the diameter std::vector<double> all_D; for (float theta = 0.f; theta < 180.f; theta += rot_angle_increment) { Rotation::rotate_around_center(r.convHull_CH, theta, CH_rot); auto [minX, minY, maxX, maxY] = AABB::from_pixelcloud(CH_rot); std::vector<float> DA; // Diameters at this angle // Iterate y-grid float stepY = (maxY - minY) / float(n_steps); for (int iy = 1; iy <= n_steps; iy++) { float chord_y = minY + iy * stepY; // Find convex hull segments intersecting 'y' std::vector<std::pair<float, float>> X; // intersection points for (int iH = 1; iH < CH_rot.size(); iH++) { // The convex hull points are guaranteed to be consecutive auto& a = CH_rot[iH - 1], & b = CH_rot[iH]; // Chord's Y is between segment AB's Ys ? if ((a.y >= chord_y && b.y <= chord_y) || (b.y >= chord_y && a.y <= chord_y)) { auto chord_x = b.y != a.y ? (b.x - a.x) * (chord_y - a.y) / (b.y - a.y) + a.x : (b.y + a.y) / 2; auto tup = std::make_pair(chord_x, chord_y); X.push_back(tup); } } // Save the length of this chord. There must be 2 items in 'chordEnds' because we don't allow uniformative chords of zero length if (X.size() >= 2) { // for N segments auto compareFunc = [](const std::pair<float, float>& p1, const std::pair<float, float>& p2) { return p1.first < p2.first; }; auto idx_minX = std::distance(X.begin(), std::min_element(X.begin(), X.end(), compareFunc)); auto idx_maxX = std::distance(X.begin(), std::max_element(X.begin(), X.end(), compareFunc)); // left X and right X segments auto& e1 = X[idx_minX], & e2 = X[idx_maxX]; auto x1 = e1.first, y1 = e1.second, x2 = e2.first, y2 = e2.second; // save this chord auto dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Squared distance DA.push_back(dist); } } if (DA.size() > 0) { // Find the shortest and longest chords (diameters) double minD2 = *std::min_element(DA.begin(), DA.end()), maxD2 = *std::max_element(DA.begin(), DA.end()), min_ = sqrt(minD2), max_ = sqrt(maxD2); // Save them all_D.push_back(min_); all_D.push_back(max_); } } // Calculate statistics of diameters auto s = ComputeCommonStatistics2(all_D); _min = (double)s.min; _max = (double)s.max; _mean = s.mean; _median = s.median; _stdev = s.stdev; _mode = (double)s.mode; // Calculate angles at min- and max- diameter if (all_D.size() > 0) { // Min and max auto itr_min_d = std::min_element(all_D.begin(), all_D.end()); auto itr_max_d = std::max_element(all_D.begin(), all_D.end()); minFeretDiameter = *itr_min_d; maxFeretDiameter = *itr_max_d; // Angles auto idxMin = std::distance(all_D.begin(), itr_min_d); minFeretAngle = (double)idxMin / 2.0; auto idxMax = std::distance(all_D.begin(), itr_max_d); maxFeretAngle = (double)idxMax / 2.0; } else { // Degenerate case minFeretDiameter = maxFeretDiameter = minFeretAngle = maxFeretAngle = 0.0; } } void CaliperFeretFeature::parallel_process(std::vector<int>& roi_labels, std::unordered_map <int, LR>& roiData, int n_threads) { size_t jobSize = roi_labels.size(), workPerThread = jobSize / n_threads; runParallel(CaliperFeretFeature::parallel_process_1_batch, n_threads, workPerThread, jobSize, &roi_labels, &roiData); } void CaliperFeretFeature::parallel_process_1_batch(size_t firstitem, size_t lastitem, std::vector<int>* ptrLabels, std::unordered_map <int, LR>* ptrLabelData) { // Calculate the feature for each batch ROI item for (auto i = firstitem; i < lastitem; i++) { // Get ahold of ROI's label and cache int roiLabel = (*ptrLabels)[i]; LR& r = (*ptrLabelData)[roiLabel]; // Skip the ROI if its data is invalid to prevent nans and infs in the output if (r.has_bad_data()) continue; // Calculate the feature and save it in ROI's csv-friendly buffer 'fvals' CaliperFeretFeature f; f.calculate(r); f.save_value(r.fvals); } }
31.492857
159
0.634838
sameeul
fcd9ec6cbf5478073b2597d02abc03fea35aff22
973
hpp
C++
inc/shader_program.hpp
tuxerr/lvr
16555daf7c52d10c16243b0e1b30cccee4e306a5
[ "MIT" ]
null
null
null
inc/shader_program.hpp
tuxerr/lvr
16555daf7c52d10c16243b0e1b30cccee4e306a5
[ "MIT" ]
null
null
null
inc/shader_program.hpp
tuxerr/lvr
16555daf7c52d10c16243b0e1b30cccee4e306a5
[ "MIT" ]
null
null
null
#ifndef DEF_SHADER_PROGRAM #define DEF_SHADER_PROGRAM #include <iostream> #include <map> #include <list> #include <string> #define GLFW_INCLUDE_GLCOREARB //#include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include "matrix4.hpp" #include "uniform.hpp" #include "uniformblock.hpp" class Program { public: Program(); ~Program(); void load_shaders(const char *vertex_shader_path,const char *fragment_shader_path,const char *tessellation_control_shader_path,const char *tessellation_evaluator_shader_path,const char *geometry_shader_path); GLuint compile_shader(const char *path,GLenum shader_type); void subscribe_to_uniform(Uniform *uni); void subscribe_to_uniformblock(UniformBlock *uni); void use(); void bind_texture(Texture* tex); void unuse(); GLuint id(); bool isBinded(); private: GLuint program_id; std::map<Uniform*,bool> uniforms; std::list<Texture*> textures; bool binded; }; #endif
25.605263
212
0.736896
tuxerr
fcdc43ad4ea14d6e37156ec1f8d3f2ba83726154
1,231
hpp
C++
third_party/boost/simd/function/ceil.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/function/ceil.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/ceil.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_CEIL_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_CEIL_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-arithmetic This function object computes the smallest integral representable value of its parameter type which is greater or equal to it. @par Header <boost/simd/function/ceil.hpp> @par Notes - @c ceil is also used as parameter to pass to @ref div or @ref rem @par Decorators - std_ for floating entries call std::ceil @see floor, round, nearbyint, trunc, iceil @par Example: @snippet ceil.cpp ceil @par Possible output: @snippet ceil.txt ceil **/ Value ceil(Value const& x); } } #endif #include <boost/simd/function/scalar/ceil.hpp> #include <boost/simd/function/simd/ceil.hpp> #endif
23.673077
100
0.594639
SylvainCorlay
fcdf07281d87a6fb2dbc66af290b8c63a6d78166
340
cpp
C++
codeforces/helpmaths.cpp
dhwanisanmukhani/competitive-coding
5392dea65b6ac370ac641c993120d7f252f5b1ac
[ "MIT" ]
null
null
null
codeforces/helpmaths.cpp
dhwanisanmukhani/competitive-coding
5392dea65b6ac370ac641c993120d7f252f5b1ac
[ "MIT" ]
null
null
null
codeforces/helpmaths.cpp
dhwanisanmukhani/competitive-coding
5392dea65b6ac370ac641c993120d7f252f5b1ac
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { string s; cin>>s; int f=0; int n=s.length(); std::vector<char> v(0); for(int i=0;i<n;i=i+2) { v.push_back(s[i]); } sort(v.begin(),v.end()); for(int k=0;k<((n+1)/2-1);k++) cout<<v[k]<<"+"; cout<<v[(n+1)/2-1]<<endl; return 0; }
14.782609
32
0.555882
dhwanisanmukhani
fcdf9b78850292ca27b80d06b170c601df129373
7,773
cpp
C++
libs/renderer/src/pass.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/renderer/src/pass.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/renderer/src/pass.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include "pass.h" #include <yttrium/base/buffer_appender.h> #include <yttrium/base/string.h> #include <yttrium/geometry/line.h> #include <yttrium/geometry/matrix.h> #include <yttrium/geometry/quad.h> #include <yttrium/renderer/metrics.h> #include <yttrium/renderer/program.h> #include "backend/backend.h" #include "builtin.h" #include "texture.h" #include <cassert> #ifndef NDEBUG # include <algorithm> #endif namespace { // Makes Y point forward and Z point up. const Yt::Matrix4 _3d_directions{ 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1 }; } namespace Yt { RenderPassData::RenderPassData() = default; RenderPassData::~RenderPassData() noexcept = default; RenderPassImpl::RenderPassImpl(RenderBackend& backend, RenderBuiltin& builtin, RenderPassData& data, const Size& viewport_size, RenderMetrics& metrics) : _backend{ backend } , _builtin{ builtin } , _data{ data } , _viewport_size{ viewport_size } , _metrics{ metrics } { _backend.clear(); } RenderPassImpl::~RenderPassImpl() noexcept { #ifndef NDEBUG _data._seen_textures.clear(); _data._seen_programs.clear(); #endif } void RenderPassImpl::draw_mesh(const Mesh& mesh) { update_state(); _metrics._triangles += _backend.draw_mesh(mesh); ++_metrics._draw_calls; } Matrix4 RenderPassImpl::full_matrix() const { const auto current_projection = std::find_if(_data._matrix_stack.rbegin(), _data._matrix_stack.rend(), [](const auto& m) { return m.second == RenderMatrixType::Projection; }); assert(current_projection != _data._matrix_stack.rend()); const auto current_view = current_projection.base(); assert(current_view != _data._matrix_stack.end()); assert(current_view->second == RenderMatrixType::View); return current_projection->first * current_view->first * model_matrix(); } Matrix4 RenderPassImpl::model_matrix() const { assert(!_data._matrix_stack.empty()); assert(_data._matrix_stack.back().second == RenderMatrixType::Model); return _data._matrix_stack.back().first; } Line3 RenderPassImpl::pixel_ray(const Vector2& v) const { // Move each coordinate to the center of the pixel (by adding 0.5), then normalize from [0, D] to [-1, 1]. const auto xn = (2 * v.x + 1) / static_cast<float>(_viewport_size._width) - 1; const auto yn = 1 - (2 * v.y + 1) / static_cast<float>(_viewport_size._height); const auto m = inverse(full_matrix()); return { m * Vector3{ xn, yn, 0 }, m * Vector3{ xn, yn, 1 } }; } RectF RenderPassImpl::viewport_rect() const { return RectF{ _viewport_size }; } void RenderPassImpl::pop_program() noexcept { assert(_data._program_stack.size() > 1 || (_data._program_stack.size() == 1 && _data._program_stack.back().second > 1)); if (_data._program_stack.back().second > 1) { --_data._program_stack.back().second; return; } _data._program_stack.pop_back(); _reset_program = true; } void RenderPassImpl::pop_projection() noexcept { assert(_data._matrix_stack.size() >= 3); assert(_data._matrix_stack.back().second == RenderMatrixType::Model); _data._matrix_stack.pop_back(); assert(_data._matrix_stack.back().second == RenderMatrixType::View); _data._matrix_stack.pop_back(); assert(_data._matrix_stack.back().second == RenderMatrixType::Projection); _data._matrix_stack.pop_back(); if (_data._matrix_stack.empty()) return; assert(_data._matrix_stack.back().second == RenderMatrixType::Model); #ifndef NDEBUG const auto last_view = std::find_if(_data._matrix_stack.rbegin(), _data._matrix_stack.rend(), [](const auto& m) { return m.second == RenderMatrixType::View; }); assert(last_view != _data._matrix_stack.rend()); const auto last_projection = std::next(last_view); assert(last_projection != _data._matrix_stack.rend()); assert(last_projection->second == RenderMatrixType::Projection); #endif } void RenderPassImpl::pop_texture(Flags<Texture2D::Filter> filter) noexcept { assert(_data._texture_stack.size() > 1 || (_data._texture_stack.size() == 1 && _data._texture_stack.back().second > 1)); if (_data._texture_stack.back().second == 1) { _data._texture_stack.pop_back(); _reset_texture = true; } else --_data._texture_stack.back().second; _current_texture_filter = filter; } void RenderPassImpl::pop_transformation() noexcept { assert(_data._matrix_stack.size() > 3); assert(_data._matrix_stack.back().second == RenderMatrixType::Model); _data._matrix_stack.pop_back(); assert(_data._matrix_stack.back().second == RenderMatrixType::Model); } void RenderPassImpl::push_program(const RenderProgram* program) { assert(!_data._program_stack.empty()); if (_data._program_stack.back().first == program) { ++_data._program_stack.back().second; return; } _data._program_stack.emplace_back(program, 1); _reset_program = true; } void RenderPassImpl::push_projection_2d(const Matrix4& matrix) { _data._matrix_stack.emplace_back(matrix, RenderMatrixType::Projection); _data._matrix_stack.emplace_back(Matrix4::identity(), RenderMatrixType::View); _data._matrix_stack.emplace_back(Matrix4::identity(), RenderMatrixType::Model); } void RenderPassImpl::push_projection_3d(const Matrix4& projection, const Matrix4& view) { _data._matrix_stack.emplace_back(projection, RenderMatrixType::Projection); _data._matrix_stack.emplace_back(::_3d_directions * view, RenderMatrixType::View); _data._matrix_stack.emplace_back(Matrix4::identity(), RenderMatrixType::Model); } Flags<Texture2D::Filter> RenderPassImpl::push_texture(const Texture2D* texture, Flags<Texture2D::Filter> filter) { if (!texture) { texture = _builtin._white_texture.get(); filter = Texture2D::NearestFilter; } assert(!_data._texture_stack.empty()); if (_data._texture_stack.back().first != texture) { _data._texture_stack.emplace_back(texture, 1); _reset_texture = true; } else ++_data._texture_stack.back().second; return std::exchange(_current_texture_filter, filter); } void RenderPassImpl::push_transformation(const Matrix4& matrix) { assert(!_data._matrix_stack.empty()); assert(_data._matrix_stack.back().second == RenderMatrixType::Model); _data._matrix_stack.emplace_back(_data._matrix_stack.back().first * matrix, RenderMatrixType::Model); } void RenderPassImpl::flush_2d(const Buffer& vertices, const Buffer& indices) noexcept { update_state(); _backend.flush_2d(vertices, indices); _metrics._triangles += indices.size() / sizeof(uint16_t) - 2; ++_metrics._draw_calls; } void RenderPassImpl::update_state() { if (_reset_program) { _reset_program = false; const auto program = _data._program_stack.back().first; if (program != _current_program) { _current_program = program; _backend.set_program(program); ++_metrics._shader_switches; #ifndef NDEBUG if (std::none_of(_data._seen_programs.begin(), _data._seen_programs.end(), [program](const auto seen_program) { return program == seen_program; })) _data._seen_programs.emplace_back(program); else ++_metrics._extra_shader_switches; #endif } } if (_reset_texture) { _reset_texture = false; const auto texture = _data._texture_stack.back().first; if (texture != _current_texture) { _current_texture = texture; _backend.set_texture(*texture, _current_texture_filter); ++_metrics._texture_switches; #ifndef NDEBUG if (std::none_of(_data._seen_textures.begin(), _data._seen_textures.end(), [texture](const auto seen_texture) { return texture == seen_texture; })) _data._seen_textures.emplace_back(texture); else ++_metrics._extra_texture_switches; #endif } } } }
31.216867
177
0.726875
blagodarin
fcdfe4d385d44b2bce4f9af8b28af515c744ae9f
3,672
hpp
C++
source/application/plugins/qcan-peak/qcan_plugin_peak.hpp
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
36
2016-08-23T13:05:02.000Z
2022-02-13T07:11:05.000Z
source/application/plugins/qcan-peak/qcan_plugin_peak.hpp
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
19
2017-01-30T08:59:40.000Z
2018-10-30T07:55:33.000Z
source/application/plugins/qcan-peak/qcan_plugin_peak.hpp
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
16
2016-06-02T11:15:02.000Z
2020-07-10T11:49:12.000Z
//============================================================================// // File: qcan_plugin_peak.hpp // // Description: CAN plugin for PEAK devices // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53842 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // 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, the following disclaimer and // // the referenced file 'COPYING'. // // 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 MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Provided that this notice is retained in full, this software may be // // distributed under the terms of the GNU Lesser General Public License // // ("LGPL") version 3 as distributed in the 'COPYING' file. // // // //============================================================================// #ifndef QCAN_PLUGIN_PEAK_H_ #define QCAN_PLUGIN_PEAK_H_ #include <QtCore/QLibrary> #include <QtCore/QObject> #include <QtCore/QtPlugin> #include <QtWidgets/QWidget> #include "qcan_plugin.hpp" #include "qcan_pcan_basic.hpp" #include "qcan_interface_peak.hpp" //----------------------------------------------------------------------------- /*! ** \class QCanPluginPeak ** \brief Peak PCAN ** */ class QCanPluginPeak : public QCanPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID QCanPlugin_iid FILE "plugin.json") Q_INTERFACES(QCanPlugin) private: /*! * \brief auwPCanChannelP * Contains all PCAN Channels that should be handled * by this plugin. */ QList<uint16_t> auwPCanChannelP; /*! * \brief Paramter to indentify an interface */ typedef struct { uint16_t uwPCanChannel; QCanInterfacePeak * pclQCanInterfacePeak; } QCanIf_ts; /*! * \brief atsQCanIfPeakP * Contains list of available QCAN Interfaces */ QList<QCanIf_ts> atsQCanIfPeakP; /*! * \brief pclPcanBasicP * Reference to the static PCAN Basic lib */ QCanPcanBasic &pclPcanBasicP = QCanPcanBasic::getInstance(); public: QCanPluginPeak(); ~QCanPluginPeak(); QIcon icon(void) Q_DECL_OVERRIDE; uint8_t interfaceCount(void) Q_DECL_OVERRIDE; QCanInterface * getInterface(uint8_t ubInterfaceV) Q_DECL_OVERRIDE; QString name(void) Q_DECL_OVERRIDE; }; #endif /*QCAN_PLUGIN_PEAK_H_*/
37.85567
80
0.498911
canpie
fce26744053549d6ee11415c3e2d63ff64ac9fac
19,171
cpp
C++
libnaucrates/src/statistics/CJoinStatsProcessor.cpp
acmnu/gporca
22e0442576c7e9c578a2a7d6182007ca045baedd
[ "ECL-2.0", "Apache-2.0" ]
1
2019-03-05T10:08:56.000Z
2019-03-05T10:08:56.000Z
libnaucrates/src/statistics/CJoinStatsProcessor.cpp
ppmht/gporca
7131e3e134e6e608f7e9fef9152a8b5d71e6a59e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libnaucrates/src/statistics/CJoinStatsProcessor.cpp
ppmht/gporca
7131e3e134e6e608f7e9fef9152a8b5d71e6a59e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright 2018 Pivotal, Inc. // // @filename: // CJoinStatsProcessor.cpp // // @doc: // Statistics helper routines for processing all join types //--------------------------------------------------------------------------- #include "gpopt/operators/ops.h" #include "gpopt/optimizer/COptimizerConfig.h" #include "naucrates/statistics/CStatisticsUtils.h" #include "naucrates/statistics/CJoinStatsProcessor.h" #include "naucrates/statistics/CLeftAntiSemiJoinStatsProcessor.h" #include "naucrates/statistics/CFilterStatsProcessor.h" #include "naucrates/statistics/CScaleFactorUtils.h" using namespace gpopt; // helper for joining histograms void CJoinStatsProcessor::JoinHistograms ( IMemoryPool *pmp, const CHistogram *phist1, const CHistogram *phist2, CStatsPredJoin *pstatsjoin, CDouble dRows1, CDouble dRows2, CHistogram **pphist1, // output: histogram 1 after join CHistogram **pphist2, // output: histogram 2 after join CDouble *pdScaleFactor, // output: scale factor based on the join BOOL fEmptyInput, IStatistics::EStatsJoinType eStatsJoinType, BOOL fIgnoreLasjHistComputation ) { GPOS_ASSERT(NULL != phist1); GPOS_ASSERT(NULL != phist2); GPOS_ASSERT(NULL != pstatsjoin); GPOS_ASSERT(NULL != pphist1); GPOS_ASSERT(NULL != pphist2); GPOS_ASSERT(NULL != pdScaleFactor); if (IStatistics::EsjtLeftAntiSemiJoin == eStatsJoinType) { CLeftAntiSemiJoinStatsProcessor::JoinHistogramsLASJ ( pmp, phist1, phist2, pstatsjoin, dRows1, dRows2, pphist1, pphist2, pdScaleFactor, fEmptyInput, eStatsJoinType, fIgnoreLasjHistComputation ); return; } if (fEmptyInput) { // use Cartesian product as scale factor *pdScaleFactor = dRows1 * dRows2; *pphist1 = GPOS_NEW(pmp) CHistogram(GPOS_NEW(pmp) DrgPbucket(pmp)); *pphist2 = GPOS_NEW(pmp) CHistogram(GPOS_NEW(pmp) DrgPbucket(pmp)); return; } *pdScaleFactor = CScaleFactorUtils::DDefaultScaleFactorJoin; CStatsPred::EStatsCmpType escmpt = pstatsjoin->Escmpt(); BOOL fEmptyHistograms = phist1->FEmpty() || phist2->FEmpty(); if (fEmptyHistograms) { // if one more input has no histograms (due to lack of statistics // for table columns or computed columns), we estimate // the join cardinality to be the max of the two rows. // In other words, the scale factor is equivalent to the // min of the two rows. *pdScaleFactor = std::min(dRows1, dRows2); } else if (CHistogram::FSupportsJoinPred(escmpt)) { CHistogram *phistJoin = phist1->PhistJoinNormalized ( pmp, escmpt, dRows1, phist2, dRows2, pdScaleFactor ); if (CStatsPred::EstatscmptEq == escmpt || CStatsPred::EstatscmptINDF == escmpt || CStatsPred::EstatscmptEqNDV == escmpt) { if (phist1->FScaledNDV()) { phistJoin->SetNDVScaled(); } *pphist1 = phistJoin; *pphist2 = (*pphist1)->PhistCopy(pmp); if (phist2->FScaledNDV()) { (*pphist2)->SetNDVScaled(); } return; } // note that for IDF and Not Equality predicate, we do not generate histograms but // just the scale factors. GPOS_ASSERT(phistJoin->FEmpty()); GPOS_DELETE(phistJoin); // TODO: Feb 21 2014, for all join condition except for "=" join predicate // we currently do not compute new histograms for the join columns } // for an unsupported join predicate operator or in the case of // missing histograms, copy input histograms and use default scale factor *pphist1 = phist1->PhistCopy(pmp); *pphist2 = phist2->PhistCopy(pmp); } // derive statistics for the given join's predicate(s) IStatistics * CJoinStatsProcessor::PstatsJoinArray ( IMemoryPool *pmp, DrgPstat *pdrgpstat, CExpression *pexprScalar, IStatistics::EStatsJoinType eStatsJoinType ) { GPOS_ASSERT(NULL != pexprScalar); GPOS_ASSERT(NULL != pdrgpstat); GPOS_ASSERT(0 < pdrgpstat->UlLength()); BOOL fLeftOuterJoin = IStatistics::EsjtLeftOuterJoin == eStatsJoinType; GPOS_ASSERT_IMP(fLeftOuterJoin, 2 == pdrgpstat->UlLength()); // create an empty set of outer references for statistics derivation CColRefSet *pcrsOuterRefs = GPOS_NEW(pmp) CColRefSet(pmp); // join statistics objects one by one using relevant predicates in given scalar expression const ULONG ulStats = pdrgpstat->UlLength(); IStatistics *pstats = (*pdrgpstat)[0]->PstatsCopy(pmp); CDouble dRowsOuter = pstats->DRows(); for (ULONG ul = 1; ul < ulStats; ul++) { IStatistics *pstatsCurrent = (*pdrgpstat)[ul]; DrgPcrs *pdrgpcrsOutput= GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrsOutput->Append(pstats->Pcrs(pmp)); pdrgpcrsOutput->Append(pstatsCurrent->Pcrs(pmp)); CStatsPred *pstatspredUnsupported = NULL; DrgPstatspredjoin *pdrgpstatspredjoin = CStatsPredUtils::PdrgpstatspredjoinExtract ( pmp, pexprScalar, pdrgpcrsOutput, pcrsOuterRefs, &pstatspredUnsupported ); IStatistics *pstatsNew = NULL; if (fLeftOuterJoin) { pstatsNew = pstats->PstatsLOJ(pmp, pstatsCurrent, pdrgpstatspredjoin); } else { pstatsNew = pstats->PstatsInnerJoin(pmp, pstatsCurrent, pdrgpstatspredjoin); } pstats->Release(); pstats = pstatsNew; if (NULL != pstatspredUnsupported) { // apply the unsupported join filters as a filter on top of the join results. // TODO, June 13 2014 we currently only cap NDVs for filters // immediately on top of tables. IStatistics *pstatsAfterJoinFilter = CFilterStatsProcessor::PstatsFilter(pmp, dynamic_cast<CStatistics *>(pstats), pstatspredUnsupported, false /* fCapNdvs */); // If it is outer join and the cardinality after applying the unsupported join // filters is less than the cardinality of outer child, we don't use this stats. // Because we need to make sure that Card(LOJ) >= Card(Outer child of LOJ). if (fLeftOuterJoin && pstatsAfterJoinFilter->DRows() < dRowsOuter) { pstatsAfterJoinFilter->Release(); } else { pstats->Release(); pstats = pstatsAfterJoinFilter; } pstatspredUnsupported->Release(); } pdrgpstatspredjoin->Release(); pdrgpcrsOutput->Release(); } // clean up pcrsOuterRefs->Release(); return pstats; } // main driver to generate join stats CStatistics * CJoinStatsProcessor::PstatsJoinDriver ( IMemoryPool *pmp, CStatisticsConfig *pstatsconf, const IStatistics *pistatsOuter, const IStatistics *pistatsInner, DrgPstatspredjoin *pdrgppredInfo, IStatistics::EStatsJoinType eStatsJoinType, BOOL fIgnoreLasjHistComputation ) { GPOS_ASSERT(NULL != pmp); GPOS_ASSERT(NULL != pistatsInner); GPOS_ASSERT(NULL != pistatsOuter); GPOS_ASSERT(NULL != pdrgppredInfo); BOOL fLASJ = (IStatistics::EsjtLeftAntiSemiJoin == eStatsJoinType); BOOL fSemiJoin = IStatistics::FSemiJoin(eStatsJoinType); // Extract stat objects for inner and outer child. // Historically, IStatistics was meant to have multiple derived classes // However, currently only CStatistics implements IStatistics // Until this changes, the interfaces have been designed to take IStatistics as parameters // In the future, IStatistics should be removed, as it is not being utilized as designed const CStatistics *pstatsOuter = dynamic_cast<const CStatistics *> (pistatsOuter); const CStatistics *pstatsInner = dynamic_cast<const CStatistics *> (pistatsInner); // create hash map from colid -> histogram for resultant structure HMUlHist *phmulhistJoin = GPOS_NEW(pmp) HMUlHist(pmp); // build a bitset with all join columns CBitSet *pbsJoinColIds = GPOS_NEW(pmp) CBitSet(pmp); for (ULONG ul = 0; ul < pdrgppredInfo->UlLength(); ul++) { CStatsPredJoin *pstatsjoin = (*pdrgppredInfo)[ul]; (void) pbsJoinColIds->FExchangeSet(pstatsjoin->UlColId1()); if (!fSemiJoin) { (void) pbsJoinColIds->FExchangeSet(pstatsjoin->UlColId2()); } } // histograms on columns that do not appear in join condition will // be copied over to the result structure pstatsOuter->AddNotExcludedHistograms(pmp, pbsJoinColIds, phmulhistJoin); if (!fSemiJoin) { pstatsInner->AddNotExcludedHistograms(pmp, pbsJoinColIds, phmulhistJoin); } DrgPdouble *pdrgpd = GPOS_NEW(pmp) DrgPdouble(pmp); const ULONG ulJoinConds = pdrgppredInfo->UlLength(); BOOL fEmptyOutput = false; CDouble dRowsJoin = 0; // iterate over join's predicate(s) for (ULONG ul = 0; ul < ulJoinConds; ul++) { CStatsPredJoin *ppredInfo = (*pdrgppredInfo)[ul]; ULONG ulColId1 = ppredInfo->UlColId1(); ULONG ulColId2 = ppredInfo->UlColId2(); GPOS_ASSERT(ulColId1 != ulColId2); // find the histograms corresponding to the two columns const CHistogram *phistOuter = pstatsOuter->Phist(ulColId1); // are column id1 and 2 always in the order of outer inner? const CHistogram *phistInner = pstatsInner->Phist(ulColId2); GPOS_ASSERT(NULL != phistOuter); GPOS_ASSERT(NULL != phistInner); BOOL fEmptyInput = CStatistics::FEmptyJoinInput(pstatsOuter, pstatsInner, fLASJ); CDouble dScaleFactorLocal(1.0); CHistogram *phistOuterAfter = NULL; CHistogram *phistInnerAfter = NULL; JoinHistograms ( pmp, phistOuter, phistInner, ppredInfo, pstatsOuter->DRows(), pstatsInner->DRows(), &phistOuterAfter, &phistInnerAfter, &dScaleFactorLocal, fEmptyInput, eStatsJoinType, fIgnoreLasjHistComputation ); fEmptyOutput = FEmptyJoinStats(pstatsOuter->FEmpty(), fEmptyOutput, phistOuter, phistInner, phistOuterAfter, eStatsJoinType); CStatisticsUtils::AddHistogram(pmp, ulColId1, phistOuterAfter, phmulhistJoin); if (!fSemiJoin) { CStatisticsUtils::AddHistogram(pmp, ulColId2, phistInnerAfter, phmulhistJoin); } GPOS_DELETE(phistOuterAfter); GPOS_DELETE(phistInnerAfter); pdrgpd->Append(GPOS_NEW(pmp) CDouble(dScaleFactorLocal)); } dRowsJoin = CStatistics::DMinRows; if (!fEmptyOutput) { dRowsJoin = DJoinCardinality(pstatsconf, pstatsOuter->DRows(), pstatsInner->DRows(), pdrgpd, eStatsJoinType); } // clean up pdrgpd->Release(); pbsJoinColIds->Release(); HMUlDouble *phmuldoubleWidthResult = pstatsOuter->CopyWidths(pmp); if (!fSemiJoin) { pstatsInner->CopyWidthsInto(pmp, phmuldoubleWidthResult); } // create an output stats object CStatistics *pstatsJoin = GPOS_NEW(pmp) CStatistics ( pmp, phmulhistJoin, phmuldoubleWidthResult, dRowsJoin, fEmptyOutput, pstatsOuter->UlNumberOfPredicates() ); // In the output statistics object, the upper bound source cardinality of the join column // cannot be greater than the upper bound source cardinality information maintained in the input // statistics object. Therefore we choose CStatistics::EcbmMin the bounding method which takes // the minimum of the cardinality upper bound of the source column (in the input hash map) // and estimated join cardinality. CStatisticsUtils::ComputeCardUpperBounds(pmp, pstatsOuter, pstatsJoin, dRowsJoin, CStatistics::EcbmMin /* ecbm */); if (!fSemiJoin) { CStatisticsUtils::ComputeCardUpperBounds(pmp, pstatsInner, pstatsJoin, dRowsJoin, CStatistics::EcbmMin /* ecbm */); } return pstatsJoin; } // return join cardinality based on scaling factor and join type CDouble CJoinStatsProcessor::DJoinCardinality ( CStatisticsConfig *pstatsconf, CDouble dRowsLeft, CDouble dRowsRight, DrgPdouble *pdrgpd, IStatistics::EStatsJoinType eStatsJoinType ) { GPOS_ASSERT(NULL != pstatsconf); GPOS_ASSERT(NULL != pdrgpd); CDouble dScaleFactor = CScaleFactorUtils::DCumulativeJoinScaleFactor(pstatsconf, pdrgpd); CDouble dCartesianProduct = dRowsLeft * dRowsRight; if (IStatistics::EsjtLeftAntiSemiJoin == eStatsJoinType || IStatistics::EsjtLeftSemiJoin == eStatsJoinType) { CDouble dRows = dRowsLeft; if (IStatistics::EsjtLeftAntiSemiJoin == eStatsJoinType) { dRows = dRowsLeft / dScaleFactor; } else { // semi join results cannot exceed size of outer side dRows = std::min(dRowsLeft.DVal(), (dCartesianProduct / dScaleFactor).DVal()); } return std::max(DOUBLE(1.0), dRows.DVal()); } GPOS_ASSERT(CStatistics::DMinRows <= dScaleFactor); return std::max(CStatistics::DMinRows.DVal(), (dCartesianProduct / dScaleFactor).DVal()); } // check if the join statistics object is empty output based on the input // histograms and the join histograms BOOL CJoinStatsProcessor::FEmptyJoinStats ( BOOL fEmptyOuter, BOOL fEmptyOutput, const CHistogram *phistOuter, const CHistogram *phistInner, CHistogram *phistJoin, IStatistics::EStatsJoinType eStatsJoinType ) { GPOS_ASSERT(NULL != phistOuter); GPOS_ASSERT(NULL != phistInner); GPOS_ASSERT(NULL != phistJoin); BOOL fLASJ = IStatistics::EsjtLeftAntiSemiJoin == eStatsJoinType; return fEmptyOutput || (!fLASJ && fEmptyOuter) || (!phistOuter->FEmpty() && !phistInner->FEmpty() && phistJoin->FEmpty()); } // Derive statistics for join operation given array of statistics object IStatistics * CJoinStatsProcessor::PstatsJoin ( IMemoryPool *pmp, CExpressionHandle &exprhdl, DrgPstat *pdrgpstatCtxt ) { GPOS_ASSERT(CLogical::EspNone < CLogical::PopConvert(exprhdl.Pop())->Esp(exprhdl)); DrgPstat *pdrgpstat = GPOS_NEW(pmp) DrgPstat(pmp); const ULONG ulArity = exprhdl.UlArity(); for (ULONG ul = 0; ul < ulArity - 1; ul++) { IStatistics *pstatsChild = exprhdl.Pstats(ul); pstatsChild->AddRef(); pdrgpstat->Append(pstatsChild); } CExpression *pexprJoinPred = NULL; if (exprhdl.Pdpscalar(ulArity - 1)->FHasSubquery()) { // in case of subquery in join predicate, assume join condition is True pexprJoinPred = CUtils::PexprScalarConstBool(pmp, true /*fVal*/); } else { // remove implied predicates from join condition to avoid cardinality under-estimation pexprJoinPred = CPredicateUtils::PexprRemoveImpliedConjuncts(pmp, exprhdl.PexprScalarChild(ulArity - 1), exprhdl); } // split join predicate into local predicate and predicate involving outer references CExpression *pexprLocal = NULL; CExpression *pexprOuterRefs = NULL; // get outer references from expression handle CColRefSet *pcrsOuter = exprhdl.Pdprel()->PcrsOuter(); CPredicateUtils::SeparateOuterRefs(pmp, pexprJoinPred, pcrsOuter, &pexprLocal, &pexprOuterRefs); pexprJoinPred->Release(); COperator::EOperatorId eopid = exprhdl.Pop()->Eopid(); GPOS_ASSERT(COperator::EopLogicalLeftOuterJoin == eopid || COperator::EopLogicalInnerJoin == eopid || COperator::EopLogicalNAryJoin == eopid); // we use Inner Join semantics here except in the case of Left Outer Join IStatistics::EStatsJoinType eStatsJoinType = IStatistics::EsjtInnerJoin; if (COperator::EopLogicalLeftOuterJoin == eopid) { eStatsJoinType = IStatistics::EsjtLeftOuterJoin; } // derive stats based on local join condition IStatistics *pstatsJoin = CJoinStatsProcessor::PstatsJoinArray(pmp, pdrgpstat, pexprLocal, eStatsJoinType); if (exprhdl.FHasOuterRefs() && 0 < pdrgpstatCtxt->UlLength()) { // derive stats based on outer references IStatistics *pstats = PstatsDeriveWithOuterRefs(pmp, exprhdl, pexprOuterRefs, pstatsJoin, pdrgpstatCtxt, eStatsJoinType); pstatsJoin->Release(); pstatsJoin = pstats; } pexprLocal->Release(); pexprOuterRefs->Release(); pdrgpstat->Release(); return pstatsJoin; } // Derives statistics when the scalar expression contains one or more outer references. // This stats derivation mechanism passes around a context array onto which // operators append their stats objects as they get derived. The context array is // filled as we derive stats on the children of a given operator. This gives each // operator access to the stats objects of its previous siblings as well as to the outer // operators in higher levels. // For example, in this expression: // // JOIN // |--Get(R) // +--Select(R.r=S.s) // +-- Get(S) // // We start by deriving stats on JOIN's left child (Get(R)) and append its // stats to the context. Then, we call stats derivation on JOIN's right child // (SELECT), passing it the current context. This gives SELECT access to the // histogram on column R.r--which is an outer reference in this example. After // JOIN's children's stats are computed, JOIN combines them into a parent stats // object, which is passed upwards to JOIN's parent. This mechanism gives any // operator access to the histograms of outer references defined anywhere in // the logical tree. For example, we also support the case where outer // reference R.r is defined two levels upwards: // // JOIN // |---Get(R) // +--JOIN // |--Get(T) // +--Select(R.r=S.s) // +--Get(S) // // // // The next step is to combine the statistics objects of the outer references // with those of the local columns. You can think of this as a correlated // expression, where for each outer tuple, we need to extract the outer ref // value and re-execute the inner expression using the current outer ref value. // This has the same semantics as a Join from a statistics perspective. // // We pull statistics for outer references from the passed statistics context, // using Join statistics derivation in this case. // // For example: // // Join // |--Get(R) // +--Join // |--Get(S) // +--Select(T.t=R.r) // +--Get(T) // // when deriving statistics on 'Select(T.t=R.r)', we join T with the cross // product (R x S) based on the condition (T.t=R.r) IStatistics * CJoinStatsProcessor::PstatsDeriveWithOuterRefs ( IMemoryPool *pmp, CExpressionHandle & #ifdef GPOS_DEBUG exprhdl // handle attached to the logical expression we want to derive stats for #endif // GPOS_DEBUG , CExpression *pexprScalar, // scalar condition to be used for stats derivation IStatistics *pstats, // statistics object of the attached expression DrgPstat *pdrgpstatOuter, // array of stats objects where outer references are defined IStatistics::EStatsJoinType eStatsJoinType ) { GPOS_ASSERT(exprhdl.FHasOuterRefs() && "attached expression does not have outer references"); GPOS_ASSERT(NULL != pexprScalar); GPOS_ASSERT(NULL != pstats); GPOS_ASSERT(NULL != pdrgpstatOuter); GPOS_ASSERT(0 < pdrgpstatOuter->UlLength()); GPOS_ASSERT(IStatistics::EstiSentinel != eStatsJoinType); // join outer stats object based on given scalar expression, // we use inner join semantics here to consider all relevant combinations of outer tuples IStatistics *pstatsOuter = CJoinStatsProcessor::PstatsJoinArray(pmp, pdrgpstatOuter, pexprScalar, IStatistics::EsjtInnerJoin); CDouble dRowsOuter = pstatsOuter->DRows(); // join passed stats object and outer stats based on the passed join type DrgPstat *pdrgpstat = GPOS_NEW(pmp) DrgPstat(pmp); pdrgpstat->Append(pstatsOuter); pstats->AddRef(); pdrgpstat->Append(pstats); IStatistics *pstatsJoined = CJoinStatsProcessor::PstatsJoinArray(pmp, pdrgpstat, pexprScalar, eStatsJoinType); pdrgpstat->Release(); // scale result using cardinality of outer stats and set number of rebinds of returned stats IStatistics *pstatsResult = pstatsJoined->PstatsScale(pmp, CDouble(1.0/dRowsOuter)); pstatsResult->SetRebinds(dRowsOuter); pstatsJoined->Release(); return pstatsResult; } // EOF
31.583196
163
0.728496
acmnu
fce55c2356000aeaf2a0e541199038c14ec5ffd6
4,268
cpp
C++
src/othello/stats/StatisticsManager.cpp
Orfby/Othello-MMP
72be0ee38a329eff536b17d1e5334353cfd58c6f
[ "MIT" ]
null
null
null
src/othello/stats/StatisticsManager.cpp
Orfby/Othello-MMP
72be0ee38a329eff536b17d1e5334353cfd58c6f
[ "MIT" ]
null
null
null
src/othello/stats/StatisticsManager.cpp
Orfby/Othello-MMP
72be0ee38a329eff536b17d1e5334353cfd58c6f
[ "MIT" ]
null
null
null
//Standard C++: #include <iostream> #include <iomanip> //Othello headers: #include <othello/stats/StatisticsManager.hpp> namespace othello { namespace stats { //////////////////////////////////////////////////////////////// StatisticsManager::StatisticsManager(const std::string& outFilePath, const std::string& infoString) { //Open the file and delete anything that's already there outFile.open(outFilePath, std::ios::trunc); //Output the header outFile << infoString << std::endl; outFile << "CSV START" << std::endl; outFile << "batch,p1AvgWins,p1AvgScore,p2AvgWins,p2AvgScore,avgGameLen,elapsed" << std::endl; } //////////////////////////////////////////////////////////////// void StatisticsManager::gameEnd(const std::pair<uint8_t, uint8_t>& score, const unsigned int& gameLength) { //Increase the number of games ++numGames; //Increase the game length totalGameLength += gameLength; //Increase the score totalScore.first += score.first; totalScore.second += score.second; //Increase the number of wins for the winner if (score.first > score.second) {++numWins.first;} else if (score.second > score.first) {++numWins.second;} } //////////////////////////////////////////////////////////////// void StatisticsManager::output() { //Get the time now auto end = std::chrono::system_clock::now(); //Calculate the elapsed time std::chrono::duration<double> elapsed = end - start; //Calculate the average wins std::pair<double, double> avgWins = { (double)numWins.first / numGames, (double)numWins.second / numGames }; //Calculate the average score std::pair<double, double> avgScore = { (double)totalScore.first / numGames, (double)totalScore.second / numGames }; //Calculate the average game length double avgGameLen = (double)totalGameLength / numGames; //Output to the csv outFile << batchCounter << ","; outFile << avgWins.first << "," << avgScore.first << ","; outFile << avgWins.second << "," << avgScore.second << ","; outFile << avgGameLen << "," << elapsed.count() << std::endl; //Output to stdout std::cout << "======================" << std::endl; std::cout << "Statistics of " << numGames << " games:" << std::endl; std::cout << "Win Rate: "; std::cout << std::setprecision(6) << avgWins.first * 100 << " vs "; std::cout << std::setprecision(6) << avgWins.second * 100 << std::endl; std::cout << "Avg Score: "; std::cout << std::setprecision(6) << avgScore.first << " vs "; std::cout << std::setprecision(6) << avgScore.second << std::endl; std::cout << "Avg Game Length: "; std::cout << std::setprecision(6) << avgGameLen << std::endl; std::cout << "Elapsed Time: "; std::cout << std::setprecision(6) << elapsed.count() << std::endl; std::cout << "======================" << std::endl; } //////////////////////////////////////////////////////////////// void StatisticsManager::reset() { //Reset the stats numGames = 0; numWins = {0, 0}; totalScore = {0, 0}; totalGameLength = 0; start = std::chrono::system_clock::now(); } //////////////////////////////////////////////////////////////// void StatisticsManager::nextBatch() { //Reset the stats reset(); //Increase the batch counter ++batchCounter; } } }
36.793103
113
0.446579
Orfby
fce9b6716cd99f2f7391f9b784c3db6ec681a619
52,617
cpp
C++
blades/xbmc/xbmc/utils/test/TestDatabaseUtils.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/utils/test/TestDatabaseUtils.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/utils/test/TestDatabaseUtils.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "utils/DatabaseUtils.h" #include "video/VideoDatabase.h" #include "music/MusicDatabase.h" #include "dbwrappers/qry_dat.h" #include "utils/Variant.h" #include "utils/StringUtils.h" #include "gtest/gtest.h" class TestDatabaseUtilsHelper { public: TestDatabaseUtilsHelper() { album_idAlbum = CMusicDatabase::album_idAlbum; album_strAlbum = CMusicDatabase::album_strAlbum; album_strArtists = CMusicDatabase::album_strArtists; album_strGenres = CMusicDatabase::album_strGenres; album_iYear = CMusicDatabase::album_iYear; album_strMoods = CMusicDatabase::album_strMoods; album_strStyles = CMusicDatabase::album_strStyles; album_strThemes = CMusicDatabase::album_strThemes; album_strReview = CMusicDatabase::album_strReview; album_strLabel = CMusicDatabase::album_strLabel; album_strType = CMusicDatabase::album_strType; album_iRating = CMusicDatabase::album_iRating; album_dtDateAdded = CMusicDatabase::album_dtDateAdded; song_idSong = CMusicDatabase::song_idSong; song_strTitle = CMusicDatabase::song_strTitle; song_iTrack = CMusicDatabase::song_iTrack; song_iDuration = CMusicDatabase::song_iDuration; song_iYear = CMusicDatabase::song_iYear; song_strFileName = CMusicDatabase::song_strFileName; song_iTimesPlayed = CMusicDatabase::song_iTimesPlayed; song_iStartOffset = CMusicDatabase::song_iStartOffset; song_iEndOffset = CMusicDatabase::song_iEndOffset; song_lastplayed = CMusicDatabase::song_lastplayed; song_userrating = CMusicDatabase::song_userrating; song_comment = CMusicDatabase::song_comment; song_strAlbum = CMusicDatabase::song_strAlbum; song_strPath = CMusicDatabase::song_strPath; song_strGenres = CMusicDatabase::song_strGenres; song_strArtists = CMusicDatabase::song_strArtists; } int album_idAlbum; int album_strAlbum; int album_strArtists; int album_strGenres; int album_iYear; int album_strMoods; int album_strStyles; int album_strThemes; int album_strReview; int album_strLabel; int album_strType; int album_iRating; int album_dtDateAdded; int song_idSong; int song_strTitle; int song_iTrack; int song_iDuration; int song_iYear; int song_strFileName; int song_iTimesPlayed; int song_iStartOffset; int song_iEndOffset; int song_lastplayed; int song_userrating; int song_comment; int song_strAlbum; int song_strPath; int song_strGenres; int song_strArtists; }; TEST(TestDatabaseUtils, GetField_None) { std::string refstr, varstr; refstr = ""; varstr = DatabaseUtils::GetField(FieldNone, MediaTypeNone, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); varstr = DatabaseUtils::GetField(FieldNone, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_MediaTypeAlbum) { std::string refstr, varstr; refstr = "albumview.idAlbum"; varstr = DatabaseUtils::GetField(FieldId, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strAlbum"; varstr = DatabaseUtils::GetField(FieldAlbum, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strArtists"; varstr = DatabaseUtils::GetField(FieldArtist, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strArtists"; varstr = DatabaseUtils::GetField(FieldAlbumArtist, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strGenre"; varstr = DatabaseUtils::GetField(FieldGenre, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.iYear"; varstr = DatabaseUtils::GetField(FieldYear, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strMoods"; varstr = DatabaseUtils::GetField(FieldMoods, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strStyles"; varstr = DatabaseUtils::GetField(FieldStyles, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strThemes"; varstr = DatabaseUtils::GetField(FieldThemes, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strReview"; varstr = DatabaseUtils::GetField(FieldReview, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strLabel"; varstr = DatabaseUtils::GetField(FieldMusicLabel, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strType"; varstr = DatabaseUtils::GetField(FieldAlbumType, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.iRating"; varstr = DatabaseUtils::GetField(FieldRating, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.dateAdded"; varstr = DatabaseUtils::GetField(FieldDateAdded, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = ""; varstr = DatabaseUtils::GetField(FieldNone, MediaTypeAlbum, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "albumview.strAlbum"; varstr = DatabaseUtils::GetField(FieldAlbum, MediaTypeAlbum, DatabaseQueryPartWhere); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); varstr = DatabaseUtils::GetField(FieldAlbum, MediaTypeAlbum, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_MediaTypeSong) { std::string refstr, varstr; refstr = "songview.idSong"; varstr = DatabaseUtils::GetField(FieldId, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strTitle"; varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.iTrack"; varstr = DatabaseUtils::GetField(FieldTrackNumber, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.iDuration"; varstr = DatabaseUtils::GetField(FieldTime, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.iYear"; varstr = DatabaseUtils::GetField(FieldYear, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strFilename"; varstr = DatabaseUtils::GetField(FieldFilename, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.iTimesPlayed"; varstr = DatabaseUtils::GetField(FieldPlaycount, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.iStartOffset"; varstr = DatabaseUtils::GetField(FieldStartOffset, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.iEndOffset"; varstr = DatabaseUtils::GetField(FieldEndOffset, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.lastPlayed"; varstr = DatabaseUtils::GetField(FieldLastPlayed, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.rating"; varstr = DatabaseUtils::GetField(FieldRating, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.comment"; varstr = DatabaseUtils::GetField(FieldComment, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strAlbum"; varstr = DatabaseUtils::GetField(FieldAlbum, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strArtists"; varstr = DatabaseUtils::GetField(FieldArtist, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strArtists"; varstr = DatabaseUtils::GetField(FieldAlbumArtist, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strGenre"; varstr = DatabaseUtils::GetField(FieldGenre, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.dateAdded"; varstr = DatabaseUtils::GetField(FieldDateAdded, MediaTypeSong, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "songview.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeSong, DatabaseQueryPartWhere); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); varstr = DatabaseUtils::GetField(FieldPath, MediaTypeSong, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_MediaTypeMusicVideo) { std::string refstr, varstr; refstr = "musicvideo_view.idMVideo"; varstr = DatabaseUtils::GetField(FieldId, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_TITLE); varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_RUNTIME); varstr = DatabaseUtils::GetField(FieldTime, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_DIRECTOR); varstr = DatabaseUtils::GetField(FieldDirector, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_STUDIOS); varstr = DatabaseUtils::GetField(FieldStudio, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_YEAR); varstr = DatabaseUtils::GetField(FieldYear, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_PLOT); varstr = DatabaseUtils::GetField(FieldPlot, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_ALBUM); varstr = DatabaseUtils::GetField(FieldAlbum, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_ARTIST); varstr = DatabaseUtils::GetField(FieldArtist, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_GENRE); varstr = DatabaseUtils::GetField(FieldGenre, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("musicvideo_view.c%02d",VIDEODB_ID_MUSICVIDEO_TRACK); varstr = DatabaseUtils::GetField(FieldTrackNumber, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.strFilename"; varstr = DatabaseUtils::GetField(FieldFilename, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.playCount"; varstr = DatabaseUtils::GetField(FieldPlaycount, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.lastPlayed"; varstr = DatabaseUtils::GetField(FieldLastPlayed, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.dateAdded"; varstr = DatabaseUtils::GetField(FieldDateAdded, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = ""; varstr = DatabaseUtils::GetField(FieldVideoResolution, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeMusicVideo, DatabaseQueryPartWhere); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeMusicVideo, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "musicvideo_view.userrating"; varstr = DatabaseUtils::GetField(FieldUserRating, MediaTypeMusicVideo, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_MediaTypeMovie) { std::string refstr, varstr; refstr = "movie_view.idMovie"; varstr = DatabaseUtils::GetField(FieldId, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_TITLE); varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("CASE WHEN length(movie_view.c%02d) > 0 THEN movie_view.c%02d " "ELSE movie_view.c%02d END", VIDEODB_ID_SORTTITLE, VIDEODB_ID_SORTTITLE, VIDEODB_ID_TITLE); varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeMovie, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_PLOT); varstr = DatabaseUtils::GetField(FieldPlot, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_PLOTOUTLINE); varstr = DatabaseUtils::GetField(FieldPlotOutline, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_TAGLINE); varstr = DatabaseUtils::GetField(FieldTagline, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_VOTES); varstr = DatabaseUtils::GetField(FieldVotes, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_RATING); varstr = DatabaseUtils::GetField(FieldRating, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("CAST(movie_view.c%02d as DECIMAL(5,3))", VIDEODB_ID_RATING); varstr = DatabaseUtils::GetField(FieldRating, MediaTypeMovie, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_CREDITS); varstr = DatabaseUtils::GetField(FieldWriter, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_YEAR); varstr = DatabaseUtils::GetField(FieldYear, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_SORTTITLE); varstr = DatabaseUtils::GetField(FieldSortTitle, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_RUNTIME); varstr = DatabaseUtils::GetField(FieldTime, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_MPAA); varstr = DatabaseUtils::GetField(FieldMPAA, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_TOP250); varstr = DatabaseUtils::GetField(FieldTop250, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_GENRE); varstr = DatabaseUtils::GetField(FieldGenre, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_DIRECTOR); varstr = DatabaseUtils::GetField(FieldDirector, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_STUDIOS); varstr = DatabaseUtils::GetField(FieldStudio, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_TRAILER); varstr = DatabaseUtils::GetField(FieldTrailer, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("movie_view.c%02d", VIDEODB_ID_COUNTRY); varstr = DatabaseUtils::GetField(FieldCountry, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "movie_view.strFilename"; varstr = DatabaseUtils::GetField(FieldFilename, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "movie_view.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "movie_view.playCount"; varstr = DatabaseUtils::GetField(FieldPlaycount, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "movie_view.lastPlayed"; varstr = DatabaseUtils::GetField(FieldLastPlayed, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "movie_view.dateAdded"; varstr = DatabaseUtils::GetField(FieldDateAdded, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "movie_view.userrating"; varstr = DatabaseUtils::GetField(FieldUserRating, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = ""; varstr = DatabaseUtils::GetField(FieldRandom, MediaTypeMovie, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_MediaTypeTvShow) { std::string refstr, varstr; refstr = "tvshow_view.idShow"; varstr = DatabaseUtils::GetField(FieldId, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("CASE WHEN length(tvshow_view.c%02d) > 0 THEN tvshow_view.c%02d " "ELSE tvshow_view.c%02d END", VIDEODB_ID_TV_SORTTITLE, VIDEODB_ID_TV_SORTTITLE, VIDEODB_ID_TV_TITLE); varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeTvShow, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_TITLE); varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_PLOT); varstr = DatabaseUtils::GetField(FieldPlot, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_STATUS); varstr = DatabaseUtils::GetField(FieldTvShowStatus, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_VOTES); varstr = DatabaseUtils::GetField(FieldVotes, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_RATING); varstr = DatabaseUtils::GetField(FieldRating, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_PREMIERED); varstr = DatabaseUtils::GetField(FieldYear, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_GENRE); varstr = DatabaseUtils::GetField(FieldGenre, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_MPAA); varstr = DatabaseUtils::GetField(FieldMPAA, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_STUDIOS); varstr = DatabaseUtils::GetField(FieldStudio, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("tvshow_view.c%02d", VIDEODB_ID_TV_SORTTITLE); varstr = DatabaseUtils::GetField(FieldSortTitle, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "tvshow_view.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "tvshow_view.dateAdded"; varstr = DatabaseUtils::GetField(FieldDateAdded, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "tvshow_view.totalSeasons"; varstr = DatabaseUtils::GetField(FieldSeason, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "tvshow_view.totalCount"; varstr = DatabaseUtils::GetField(FieldNumberOfEpisodes, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "tvshow_view.watchedcount"; varstr = DatabaseUtils::GetField(FieldNumberOfWatchedEpisodes, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "tvshow_view.userrating"; varstr = DatabaseUtils::GetField(FieldUserRating, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = ""; varstr = DatabaseUtils::GetField(FieldRandom, MediaTypeTvShow, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_MediaTypeEpisode) { std::string refstr, varstr; refstr = "episode_view.idEpisode"; varstr = DatabaseUtils::GetField(FieldId, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_TITLE); varstr = DatabaseUtils::GetField(FieldTitle, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_PLOT); varstr = DatabaseUtils::GetField(FieldPlot, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_VOTES); varstr = DatabaseUtils::GetField(FieldVotes, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_RATING); varstr = DatabaseUtils::GetField(FieldRating, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_CREDITS); varstr = DatabaseUtils::GetField(FieldWriter, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_AIRED); varstr = DatabaseUtils::GetField(FieldAirDate, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_RUNTIME); varstr = DatabaseUtils::GetField(FieldTime, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_DIRECTOR); varstr = DatabaseUtils::GetField(FieldDirector, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_SEASON); varstr = DatabaseUtils::GetField(FieldSeason, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = StringUtils::Format("episode_view.c%02d", VIDEODB_ID_EPISODE_EPISODE); varstr = DatabaseUtils::GetField(FieldEpisodeNumber, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.strFilename"; varstr = DatabaseUtils::GetField(FieldFilename, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.strPath"; varstr = DatabaseUtils::GetField(FieldPath, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.playCount"; varstr = DatabaseUtils::GetField(FieldPlaycount, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.lastPlayed"; varstr = DatabaseUtils::GetField(FieldLastPlayed, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.dateAdded"; varstr = DatabaseUtils::GetField(FieldDateAdded, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.strTitle"; varstr = DatabaseUtils::GetField(FieldTvShowTitle, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.premiered"; varstr = DatabaseUtils::GetField(FieldYear, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.mpaa"; varstr = DatabaseUtils::GetField(FieldMPAA, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.strStudio"; varstr = DatabaseUtils::GetField(FieldStudio, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "episode_view.userrating"; varstr = DatabaseUtils::GetField(FieldUserRating, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = ""; varstr = DatabaseUtils::GetField(FieldRandom, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetField_FieldRandom) { std::string refstr, varstr; refstr = ""; varstr = DatabaseUtils::GetField(FieldRandom, MediaTypeEpisode, DatabaseQueryPartSelect); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = ""; varstr = DatabaseUtils::GetField(FieldRandom, MediaTypeEpisode, DatabaseQueryPartWhere); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); refstr = "RANDOM()"; varstr = DatabaseUtils::GetField(FieldRandom, MediaTypeEpisode, DatabaseQueryPartOrderBy); EXPECT_STREQ(refstr.c_str(), varstr.c_str()); } TEST(TestDatabaseUtils, GetFieldIndex_None) { int refindex, varindex; refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeNone); EXPECT_EQ(refindex, varindex); varindex = DatabaseUtils::GetFieldIndex(FieldNone, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); } /* TODO: Should enums in CMusicDatabase be made public instead? */ TEST(TestDatabaseUtils, GetFieldIndex_MediaTypeAlbum) { int refindex, varindex; TestDatabaseUtilsHelper a; refindex = a.album_idAlbum; varindex = DatabaseUtils::GetFieldIndex(FieldId, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strAlbum; varindex = DatabaseUtils::GetFieldIndex(FieldAlbum, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strArtists; varindex = DatabaseUtils::GetFieldIndex(FieldArtist, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strArtists; varindex = DatabaseUtils::GetFieldIndex(FieldAlbumArtist, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strGenres; varindex = DatabaseUtils::GetFieldIndex(FieldGenre, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_iYear; varindex = DatabaseUtils::GetFieldIndex(FieldYear, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strMoods; varindex = DatabaseUtils::GetFieldIndex(FieldMoods, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strStyles; varindex = DatabaseUtils::GetFieldIndex(FieldStyles, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strThemes; varindex = DatabaseUtils::GetFieldIndex(FieldThemes, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strReview; varindex = DatabaseUtils::GetFieldIndex(FieldReview, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strLabel; varindex = DatabaseUtils::GetFieldIndex(FieldMusicLabel, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_strType; varindex = DatabaseUtils::GetFieldIndex(FieldAlbumType, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_iRating; varindex = DatabaseUtils::GetFieldIndex(FieldRating, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = a.album_dtDateAdded; varindex = DatabaseUtils::GetFieldIndex(FieldDateAdded, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeAlbum); EXPECT_EQ(refindex, varindex); } TEST(TestDatabaseUtils, GetFieldIndex_MediaTypeSong) { int refindex, varindex; TestDatabaseUtilsHelper a; refindex = a.song_idSong; varindex = DatabaseUtils::GetFieldIndex(FieldId, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_strTitle; varindex = DatabaseUtils::GetFieldIndex(FieldTitle, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_iTrack; varindex = DatabaseUtils::GetFieldIndex(FieldTrackNumber, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_iDuration; varindex = DatabaseUtils::GetFieldIndex(FieldTime, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_iYear; varindex = DatabaseUtils::GetFieldIndex(FieldYear, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_strFileName; varindex = DatabaseUtils::GetFieldIndex(FieldFilename, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_iTimesPlayed; varindex = DatabaseUtils::GetFieldIndex(FieldPlaycount, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_iStartOffset; varindex = DatabaseUtils::GetFieldIndex(FieldStartOffset, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_iEndOffset; varindex = DatabaseUtils::GetFieldIndex(FieldEndOffset, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_lastplayed; varindex = DatabaseUtils::GetFieldIndex(FieldLastPlayed, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_userrating; varindex = DatabaseUtils::GetFieldIndex(FieldRating, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_comment; varindex = DatabaseUtils::GetFieldIndex(FieldComment, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_strAlbum; varindex = DatabaseUtils::GetFieldIndex(FieldAlbum, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_strPath; varindex = DatabaseUtils::GetFieldIndex(FieldPath, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_strArtists; varindex = DatabaseUtils::GetFieldIndex(FieldArtist, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = a.song_strGenres; varindex = DatabaseUtils::GetFieldIndex(FieldGenre, MediaTypeSong); EXPECT_EQ(refindex, varindex); refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeSong); EXPECT_EQ(refindex, varindex); } TEST(TestDatabaseUtils, GetFieldIndex_MediaTypeMusicVideo) { int refindex, varindex; refindex = 0; varindex = DatabaseUtils::GetFieldIndex(FieldId, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_TITLE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTitle, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_RUNTIME + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTime, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_DIRECTOR + 2; varindex = DatabaseUtils::GetFieldIndex(FieldDirector, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_STUDIOS + 2; varindex = DatabaseUtils::GetFieldIndex(FieldStudio, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_YEAR + 2; varindex = DatabaseUtils::GetFieldIndex(FieldYear, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_PLOT + 2; varindex = DatabaseUtils::GetFieldIndex(FieldPlot, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_ALBUM + 2; varindex = DatabaseUtils::GetFieldIndex(FieldAlbum, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_ARTIST + 2; varindex = DatabaseUtils::GetFieldIndex(FieldArtist, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_GENRE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldGenre, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MUSICVIDEO_TRACK + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTrackNumber, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MUSICVIDEO_FILE; varindex = DatabaseUtils::GetFieldIndex(FieldFilename, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MUSICVIDEO_PATH; varindex = DatabaseUtils::GetFieldIndex(FieldPath, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MUSICVIDEO_PLAYCOUNT; varindex = DatabaseUtils::GetFieldIndex(FieldPlaycount, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MUSICVIDEO_LASTPLAYED; varindex = DatabaseUtils::GetFieldIndex(FieldLastPlayed, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MUSICVIDEO_DATEADDED; varindex = DatabaseUtils::GetFieldIndex(FieldDateAdded, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MUSICVIDEO_USER_RATING; varindex = DatabaseUtils::GetFieldIndex(FieldUserRating, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeMusicVideo); EXPECT_EQ(refindex, varindex); } TEST(TestDatabaseUtils, GetFieldIndex_MediaTypeMovie) { int refindex, varindex; refindex = 0; varindex = DatabaseUtils::GetFieldIndex(FieldId, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TITLE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTitle, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_SORTTITLE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldSortTitle, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_PLOT + 2; varindex = DatabaseUtils::GetFieldIndex(FieldPlot, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_PLOTOUTLINE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldPlotOutline, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TAGLINE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTagline, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_VOTES + 2; varindex = DatabaseUtils::GetFieldIndex(FieldVotes, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_RATING + 2; varindex = DatabaseUtils::GetFieldIndex(FieldRating, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_CREDITS + 2; varindex = DatabaseUtils::GetFieldIndex(FieldWriter, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_YEAR + 2; varindex = DatabaseUtils::GetFieldIndex(FieldYear, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_RUNTIME + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTime, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_MPAA + 2; varindex = DatabaseUtils::GetFieldIndex(FieldMPAA, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TOP250 + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTop250, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_GENRE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldGenre, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_DIRECTOR + 2; varindex = DatabaseUtils::GetFieldIndex(FieldDirector, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_STUDIOS + 2; varindex = DatabaseUtils::GetFieldIndex(FieldStudio, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TRAILER + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTrailer, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_COUNTRY + 2; varindex = DatabaseUtils::GetFieldIndex(FieldCountry, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MOVIE_FILE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldFilename, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MOVIE_PATH; varindex = DatabaseUtils::GetFieldIndex(FieldPath, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MOVIE_PLAYCOUNT; varindex = DatabaseUtils::GetFieldIndex(FieldPlaycount, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MOVIE_LASTPLAYED; varindex = DatabaseUtils::GetFieldIndex(FieldLastPlayed, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MOVIE_DATEADDED; varindex = DatabaseUtils::GetFieldIndex(FieldDateAdded, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_MOVIE_USER_RATING; varindex = DatabaseUtils::GetFieldIndex(FieldUserRating, MediaTypeMovie); EXPECT_EQ(refindex, varindex); refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeMovie); EXPECT_EQ(refindex, varindex); } TEST(TestDatabaseUtils, GetFieldIndex_MediaTypeTvShow) { int refindex, varindex; refindex = 0; varindex = DatabaseUtils::GetFieldIndex(FieldId, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_TITLE + 1; varindex = DatabaseUtils::GetFieldIndex(FieldTitle, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_SORTTITLE + 1; varindex = DatabaseUtils::GetFieldIndex(FieldSortTitle, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_PLOT + 1; varindex = DatabaseUtils::GetFieldIndex(FieldPlot, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_STATUS + 1; varindex = DatabaseUtils::GetFieldIndex(FieldTvShowStatus, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_VOTES + 1; varindex = DatabaseUtils::GetFieldIndex(FieldVotes, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_RATING + 1; varindex = DatabaseUtils::GetFieldIndex(FieldRating, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_PREMIERED + 1; varindex = DatabaseUtils::GetFieldIndex(FieldYear, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_GENRE + 1; varindex = DatabaseUtils::GetFieldIndex(FieldGenre, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_MPAA + 1; varindex = DatabaseUtils::GetFieldIndex(FieldMPAA, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_TV_STUDIOS + 1; varindex = DatabaseUtils::GetFieldIndex(FieldStudio, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_TVSHOW_PATH; varindex = DatabaseUtils::GetFieldIndex(FieldPath, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_TVSHOW_DATEADDED; varindex = DatabaseUtils::GetFieldIndex(FieldDateAdded, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_TVSHOW_NUM_EPISODES; varindex = DatabaseUtils::GetFieldIndex(FieldNumberOfEpisodes, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_TVSHOW_NUM_WATCHED; varindex = DatabaseUtils::GetFieldIndex(FieldNumberOfWatchedEpisodes, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_TVSHOW_NUM_SEASONS; varindex = DatabaseUtils::GetFieldIndex(FieldSeason, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_TVSHOW_USER_RATING; varindex = DatabaseUtils::GetFieldIndex(FieldUserRating, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeTvShow); EXPECT_EQ(refindex, varindex); } TEST(TestDatabaseUtils, GetFieldIndex_MediaTypeEpisode) { int refindex, varindex; refindex = 0; varindex = DatabaseUtils::GetFieldIndex(FieldId, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_TITLE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTitle, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_PLOT + 2; varindex = DatabaseUtils::GetFieldIndex(FieldPlot, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_VOTES + 2; varindex = DatabaseUtils::GetFieldIndex(FieldVotes, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_RATING + 2; varindex = DatabaseUtils::GetFieldIndex(FieldRating, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_CREDITS + 2; varindex = DatabaseUtils::GetFieldIndex(FieldWriter, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_AIRED + 2; varindex = DatabaseUtils::GetFieldIndex(FieldAirDate, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_RUNTIME + 2; varindex = DatabaseUtils::GetFieldIndex(FieldTime, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_DIRECTOR + 2; varindex = DatabaseUtils::GetFieldIndex(FieldDirector, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_SEASON + 2; varindex = DatabaseUtils::GetFieldIndex(FieldSeason, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_ID_EPISODE_EPISODE + 2; varindex = DatabaseUtils::GetFieldIndex(FieldEpisodeNumber, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_FILE; varindex = DatabaseUtils::GetFieldIndex(FieldFilename, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_PATH; varindex = DatabaseUtils::GetFieldIndex(FieldPath, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_PLAYCOUNT; varindex = DatabaseUtils::GetFieldIndex(FieldPlaycount, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_LASTPLAYED; varindex = DatabaseUtils::GetFieldIndex(FieldLastPlayed, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_DATEADDED; varindex = DatabaseUtils::GetFieldIndex(FieldDateAdded, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_TVSHOW_NAME; varindex = DatabaseUtils::GetFieldIndex(FieldTvShowTitle, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_TVSHOW_STUDIO; varindex = DatabaseUtils::GetFieldIndex(FieldStudio, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_TVSHOW_AIRED; varindex = DatabaseUtils::GetFieldIndex(FieldYear, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_TVSHOW_MPAA; varindex = DatabaseUtils::GetFieldIndex(FieldMPAA, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = VIDEODB_DETAILS_EPISODE_USER_RATING; varindex = DatabaseUtils::GetFieldIndex(FieldUserRating, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); refindex = -1; varindex = DatabaseUtils::GetFieldIndex(FieldRandom, MediaTypeEpisode); EXPECT_EQ(refindex, varindex); } TEST(TestDatabaseUtils, GetSelectFields) { Fields fields; FieldList fieldlist; EXPECT_FALSE(DatabaseUtils::GetSelectFields(fields, MediaTypeAlbum, fieldlist)); fields.insert(FieldId); fields.insert(FieldGenre); fields.insert(FieldAlbum); fields.insert(FieldArtist); fields.insert(FieldTitle); EXPECT_FALSE(DatabaseUtils::GetSelectFields(fields, MediaTypeNone, fieldlist)); EXPECT_TRUE(DatabaseUtils::GetSelectFields(fields, MediaTypeAlbum, fieldlist)); EXPECT_FALSE(fieldlist.empty()); } TEST(TestDatabaseUtils, GetFieldValue) { CVariant v_null, v_string; dbiplus::field_value f_null, f_string("test"); f_null.set_isNull(); EXPECT_TRUE(DatabaseUtils::GetFieldValue(f_null, v_null)); EXPECT_TRUE(v_null.isNull()); EXPECT_TRUE(DatabaseUtils::GetFieldValue(f_string, v_string)); EXPECT_FALSE(v_string.isNull()); EXPECT_TRUE(v_string.isString()); } /* TODO: Need some way to test this function */ // TEST(TestDatabaseUtils, GetDatabaseResults) // { // static bool GetDatabaseResults(MediaType mediaType, const FieldList &fields, // const std::unique_ptr<dbiplus::Dataset> &dataset, // DatabaseResults &results); // } TEST(TestDatabaseUtils, BuildLimitClause) { std::string a = DatabaseUtils::BuildLimitClause(100); EXPECT_STREQ(" LIMIT 100", a.c_str()); } // class DatabaseUtils // { // public: // // // static std::string BuildLimitClause(int end, int start = 0); // };
38.975556
96
0.71055
krattai
fcefdd9ebef6a8c97be2492bdc4d718aaabff697
8,847
hpp
C++
test/io/rgba_test_pixels.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
test/io/rgba_test_pixels.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
test/io/rgba_test_pixels.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODLEIC_TESELA_TEST_IO_RGBA_TEST_PIXELS_HPP #define CYNODLEIC_TESELA_TEST_IO_RGBA_TEST_PIXELS_HPP std::uint8_t png_rgba_test_pixels[16][16][4] = { {{211,126,54,133},{186,17,154,60},{157,30,158,61},{132,99,179,91},{137,126,124,133},{152,181,139,206},{172,200,209,172},{186,141,198,70},{196,126,56,133},{201,150,104,201},{191,129,82,214},{191,96,25,172},{196,126,24,133},{186,149,49,179},{142,143,151,70},{83,170,225,71}}, {{255,184,28,255},{226,123,142,206},{177,106,212,45},{132,109,229,9},{118,103,214,14},{128,135,210,74},{152,124,199,107},{186,83,161,39},{216,47,102,57},{226,61,4,163},{216,59,31,180},{211,44,35,203},{206,53,94,201},{196,77,166,187},{157,159,246,140},{103,202,255,208}}, {{255,176,30,248},{245,181,126,249},{196,147,184,176},{142,153,182,26},{103,178,190,29},{98,181,205,24},{118,141,171,7},{162,105,108,0},{206,30,138,16},{230,24,120,157},{226,30,46,193},{211,36,21,233},{206,32,73,236},{191,2,173,223},{152,97,224,232},{103,152,249,230}}, {{245,141,33,223},{240,140,133,249},{211,152,218,241},{162,162,203,172},{113,179,117,60},{88,200,55,2},{93,147,71,0},{128,112,89,7},{177,73,136,68},{206,64,157,144},{201,71,105,171},{186,74,42,236},{172,61,71,234},{157,33,138,225},{123,65,123,225},{78,102,110,196}}, {{196,126,79,133},{216,108,119,198},{216,161,211,214},{196,143,213,225},{157,126,85,133},{118,175,63,21},{98,126,37,31},{103,118,25,66},{128,126,45,133},{147,111,114,133},{142,120,118,180},{128,137,76,219},{118,126,10,133},{108,114,102,136},{78,94,107,133},{39,96,23,60}}, {{142,115,127,82},{181,97,176,186},{216,102,203,220},{226,74,195,233},{211,106,114,205},{172,165,19,103},{128,149,24,87},{93,144,25,111},{83,129,78,87},{78,131,29,68},{74,138,10,63},{64,135,59,52},{64,167,70,41},{59,143,42,48},{34,99,56,43},{0,114,29,39}}, {{108,90,179,118},{157,71,213,205},{206,47,172,230},{240,0,152,235},{240,70,125,236},{211,129,47,225},{152,114,41,198},{93,140,41,210},{54,147,38,161},{34,181,60,66},{29,197,32,36},{34,138,26,1},{44,162,60,16},{44,141,71,41},{20,111,146,50},{0,138,164,70}}, {{118,68,184,71},{157,56,132,153},{196,30,67,215},{226,24,40,237},{230,97,60,249},{211,126,86,239},{162,91,81,220},{108,90,61,206},{69,146,12,100},{49,219,71,53},{44,235,43,24},{54,178,2,0},{69,131,84,15},{69,120,188,54},{49,126,246,167},{20,112,255,147}}, {{162,126,40,133},{177,91,24,111},{186,26,60,172},{186,56,65,171},{181,126,35,133},{172,150,147,172},{152,134,138,214},{128,67,97,208},{108,126,26,133},{98,219,110,85},{93,217,143,31},{98,199,84,39},{113,126,51,133},{113,108,174,100},{103,126,255,140},{88,114,251,187}}, {{226,187,35,96},{211,93,103,124},{181,24,155,147},{147,46,123,74},{123,88,34,54},{118,115,74,190},{123,115,147,224},{137,85,157,217},{152,150,99,172},{157,216,46,91},{147,199,145,43},{142,197,126,74},{152,175,21,220},{167,165,167,203},{167,143,199,161},{162,167,151,124}}, {{255,159,70,129},{230,83,54,192},{181,93,45,179},{123,109,26,100},{83,120,17,136},{74,112,4,219},{93,106,79,153},{132,109,113,129},{172,178,55,103},{186,252,14,61},{172,255,95,60},{162,216,97,39},{172,182,62,118},{196,213,190,161},{206,182,126,111},{206,187,19,74}}, {{235,123,30,163},{221,100,67,183},{177,135,115,195},{128,146,82,196},{88,131,22,179},{74,71,12,176},{88,83,46,61},{128,128,54,63},{167,179,19,85},{186,255,81,68},{177,255,128,140},{167,217,74,82},{177,181,88,45},{196,226,152,68},{206,214,88,66},{196,187,7,70}}, {{167,126,62,133},{172,111,149,118},{172,131,155,183},{152,146,98,215},{128,126,26,133},{108,15,41,96},{103,30,3,87},{123,102,32,100},{152,126,4,133},{177,176,77,68},{172,194,99,161},{167,137,69,210},{172,126,28,133},{181,159,69,136},{172,147,52,100},{147,158,45,70}}, {{88,99,128,39},{118,68,153,32},{152,126,113,63},{177,181,54,129},{177,168,24,53},{157,82,71,78},{132,52,101,203},{123,83,44,236},{137,99,48,230},{162,114,95,200},{172,150,69,198},{177,105,46,215},{181,73,7,190},{172,115,58,100},{137,97,49,66},{88,115,64,41}}, {{25,76,168,16},{74,0,171,11},{132,61,125,43},{186,138,16,147},{206,134,83,113},{191,143,53,96},{147,131,12,205},{118,138,4,255},{118,147,41,245},{147,114,128,245},{177,172,113,240},{201,158,38,217},{211,123,30,172},{186,161,82,39},{123,120,48,41},{49,109,67,36}}, {{0,85,122,39},{44,0,152,26},{113,18,95,61},{181,102,8,195},{216,129,85,221},{196,191,8,203},{147,220,139,171},{103,191,151,195},{103,178,48,205},{137,167,98,242},{186,181,94,255},{226,161,1,220},{240,162,57,151},{211,168,76,71},{128,115,2,43},{39,121,32,39}} }; std::uint8_t tiff_rgba_test_pixels[16][16][4] = { {{110,66,28,133},{44,4,36,60},{38,7,38,61},{47,35,64,91},{71,66,65,133},{123,146,112,206},{116,135,141,172},{51,39,54,70},{102,66,29,133},{158,118,82,201},{160,108,69,214},{129,65,17,172},{102,66,13,133},{131,105,34,179},{39,39,41,70},{23,47,63,71}}, {{255,184,28,255},{183,99,115,206},{31,19,37,45},{5,4,8,9},{6,6,12,14},{37,39,61,74},{64,52,84,107},{28,13,25,39},{48,11,23,57},{144,39,3,163},{152,42,22,180},{168,35,28,203},{162,42,74,201},{144,56,122,187},{86,87,135,140},{84,165,208,208}}, {{248,171,29,248},{239,177,123,249},{135,101,127,176},{14,16,19,26},{12,20,22,29},{9,17,19,24},{3,4,5,7},{0,0,0,0},{13,2,9,16},{142,15,74,157},{171,23,35,193},{193,33,19,233},{191,30,68,236},{167,2,151,223},{138,88,204,232},{93,137,225,230}}, {{214,123,29,223},{234,137,130,249},{199,144,206,241},{109,109,137,172},{27,42,28,60},{1,2,0,2},{0,0,0,0},{4,3,2,7},{47,19,36,68},{116,36,89,144},{135,48,70,171},{172,68,39,236},{158,56,65,234},{139,29,122,225},{109,57,109,225},{60,78,85,196}}, {{102,66,41,133},{168,84,92,198},{181,135,177,214},{173,126,188,225},{82,66,44,133},{10,14,5,21},{12,15,4,31},{27,31,6,66},{67,66,23,133},{77,58,59,133},{100,85,83,180},{110,118,65,219},{62,66,5,133},{58,61,54,136},{41,49,56,133},{9,23,5,60}}, {{46,37,41,82},{132,71,128,186},{186,88,175,220},{207,68,178,233},{170,85,92,205},{69,67,8,103},{44,51,8,87},{40,63,11,111},{28,44,27,87},{21,35,8,68},{18,34,2,63},{13,28,12,52},{10,27,11,41},{11,27,8,48},{6,17,9,43},{0,17,4,39}}, {{50,42,83,118},{126,57,171,205},{186,42,155,230},{221,0,140,235},{222,65,116,236},{186,114,41,225},{118,89,32,198},{77,115,34,210},{34,93,24,161},{9,47,16,66},{4,28,5,36},{0,1,0,1},{3,10,4,16},{7,23,11,41},{4,22,29,50},{0,38,45,70}}, {{33,19,51,71},{94,34,79,153},{165,25,56,215},{210,22,37,237},{225,95,59,249},{198,118,81,239},{140,79,70,220},{87,73,49,206},{27,57,5,100},{10,46,15,53},{4,22,4,24},{0,0,0,0},{4,8,5,15},{15,25,40,54},{32,83,161,167},{12,65,147,147}}, {{84,66,21,133},{77,40,10,111},{125,18,40,172},{125,38,44,171},{94,66,18,133},{116,101,99,172},{128,112,116,214},{104,55,79,208},{56,66,14,133},{33,73,37,85},{11,26,17,31},{15,30,13,39},{59,66,27,133},{44,42,68,100},{57,69,140,140},{65,84,184,187}}, {{85,70,13,96},{103,45,50,124},{104,14,89,147},{43,13,36,74},{26,19,7,54},{88,86,55,190},{108,101,129,224},{117,72,134,217},{103,101,67,172},{56,77,16,91},{25,34,24,43},{41,57,37,74},{131,151,18,220},{133,131,133,203},{105,90,126,161},{79,81,73,124}}, {{129,80,35,129},{173,62,41,192},{127,65,32,179},{48,43,10,100},{44,64,9,136},{64,96,3,219},{56,64,47,153},{67,55,57,129},{69,72,22,103},{44,60,3,61},{40,60,22,60},{25,33,15,39},{80,84,29,118},{124,134,120,161},{90,79,55,111},{60,54,6,74}}, {{150,79,19,163},{159,72,48,183},{135,103,88,195},{98,112,63,196},{62,92,15,179},{51,49,8,176},{21,20,11,61},{32,32,13,63},{56,60,6,85},{50,68,22,68},{97,140,70,140},{54,70,24,82},{31,32,16,45},{52,60,41,68},{53,55,23,66},{54,51,2,70}}, {{87,66,32,133},{80,51,69,118},{123,94,111,183},{128,123,83,215},{67,66,14,133},{41,6,15,96},{35,10,1,87},{48,40,13,100},{79,66,2,133},{47,47,21,68},{109,122,63,161},{138,113,57,210},{90,66,15,133},{97,85,37,136},{67,58,20,100},{40,43,12,70}}, {{13,15,20,39},{15,9,19,32},{38,31,28,63},{90,92,27,129},{37,35,5,53},{48,25,22,78},{105,41,80,203},{114,77,41,236},{124,89,43,230},{127,89,75,200},{134,116,54,198},{149,89,39,215},{135,54,5,190},{67,45,23,100},{35,25,13,66},{14,18,10,41}}, {{2,5,11,16},{3,0,7,11},{22,10,21,43},{107,80,9,147},{91,59,37,113},{72,54,20,96},{118,105,10,205},{118,138,4,255},{113,141,39,245},{141,110,123,245},{167,162,106,240},{171,134,32,217},{142,83,20,172},{28,25,13,39},{20,19,8,41},{7,15,9,36}}, {{0,13,19,39},{4,0,15,26},{27,4,23,61},{138,78,6,195},{187,112,74,221},{156,152,6,203},{99,148,93,171},{79,146,115,195},{83,143,39,205},{130,158,93,242},{186,181,94,255},{195,139,1,220},{142,96,34,151},{59,47,21,71},{22,19,0,43},{6,19,5,39}} }; #endif // CYNODLEIC_TESELA_TEST_IO_RGBA_TEST_PIXELS_HPP
176.94
281
0.602464
cynodelic
fcf04f7ac5bb72d29befbcdf4528f6127e1387be
29,879
cc
C++
Grpc/serverfeatures.pb.cc
tomasruizr/EventStoreDb
645fefe9fa5be274e6f61abe59708458620b8047
[ "MIT" ]
null
null
null
Grpc/serverfeatures.pb.cc
tomasruizr/EventStoreDb
645fefe9fa5be274e6f61abe59708458620b8047
[ "MIT" ]
null
null
null
Grpc/serverfeatures.pb.cc
tomasruizr/EventStoreDb
645fefe9fa5be274e6f61abe59708458620b8047
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: serverfeatures.proto #include "serverfeatures.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_serverfeatures_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SupportedMethod_serverfeatures_2eproto; namespace event_store { namespace client { namespace server_features { class SupportedMethodsDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SupportedMethods> _instance; } _SupportedMethods_default_instance_; class SupportedMethodDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SupportedMethod> _instance; } _SupportedMethod_default_instance_; } // namespace server_features } // namespace client } // namespace event_store static void InitDefaultsscc_info_SupportedMethod_serverfeatures_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::event_store::client::server_features::_SupportedMethod_default_instance_; new (ptr) ::event_store::client::server_features::SupportedMethod(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::event_store::client::server_features::SupportedMethod::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SupportedMethod_serverfeatures_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_SupportedMethod_serverfeatures_2eproto}, {}}; static void InitDefaultsscc_info_SupportedMethods_serverfeatures_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::event_store::client::server_features::_SupportedMethods_default_instance_; new (ptr) ::event_store::client::server_features::SupportedMethods(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::event_store::client::server_features::SupportedMethods::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SupportedMethods_serverfeatures_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_SupportedMethods_serverfeatures_2eproto}, { &scc_info_SupportedMethod_serverfeatures_2eproto.base,}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_serverfeatures_2eproto[2]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_serverfeatures_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_serverfeatures_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_serverfeatures_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethods, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethods, methods_), PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethods, event_store_server_version_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethod, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethod, method_name_), PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethod, service_name_), PROTOBUF_FIELD_OFFSET(::event_store::client::server_features::SupportedMethod, features_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::event_store::client::server_features::SupportedMethods)}, { 7, -1, sizeof(::event_store::client::server_features::SupportedMethod)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::event_store::client::server_features::_SupportedMethods_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::event_store::client::server_features::_SupportedMethod_default_instance_), }; const char descriptor_table_protodef_serverfeatures_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\024serverfeatures.proto\022\"event_store.clie" "nt.server_features\032\014shared.proto\"|\n\020Supp" "ortedMethods\022D\n\007methods\030\001 \003(\01323.event_st" "ore.client.server_features.SupportedMeth" "od\022\"\n\032event_store_server_version\030\002 \001(\t\"N" "\n\017SupportedMethod\022\023\n\013method_name\030\001 \001(\t\022\024" "\n\014service_name\030\002 \001(\t\022\020\n\010features\030\003 \003(\t2x" "\n\016ServerFeatures\022f\n\023GetSupportedMethods\022" "\031.event_store.client.Empty\0324.event_store" ".client.server_features.SupportedMethods" "B.\n,com.eventstore.dbclient.proto.server" "featuresb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_serverfeatures_2eproto_deps[1] = { &::descriptor_table_shared_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_serverfeatures_2eproto_sccs[2] = { &scc_info_SupportedMethod_serverfeatures_2eproto.base, &scc_info_SupportedMethods_serverfeatures_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_serverfeatures_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_serverfeatures_2eproto = { false, false, descriptor_table_protodef_serverfeatures_2eproto, "serverfeatures.proto", 456, &descriptor_table_serverfeatures_2eproto_once, descriptor_table_serverfeatures_2eproto_sccs, descriptor_table_serverfeatures_2eproto_deps, 2, 1, schemas, file_default_instances, TableStruct_serverfeatures_2eproto::offsets, file_level_metadata_serverfeatures_2eproto, 2, file_level_enum_descriptors_serverfeatures_2eproto, file_level_service_descriptors_serverfeatures_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_serverfeatures_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_serverfeatures_2eproto)), true); namespace event_store { namespace client { namespace server_features { // =================================================================== void SupportedMethods::InitAsDefaultInstance() { } class SupportedMethods::_Internal { public: }; SupportedMethods::SupportedMethods(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), methods_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:event_store.client.server_features.SupportedMethods) } SupportedMethods::SupportedMethods(const SupportedMethods& from) : ::PROTOBUF_NAMESPACE_ID::Message(), methods_(from.methods_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); event_store_server_version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_event_store_server_version().empty()) { event_store_server_version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_event_store_server_version(), GetArena()); } // @@protoc_insertion_point(copy_constructor:event_store.client.server_features.SupportedMethods) } void SupportedMethods::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SupportedMethods_serverfeatures_2eproto.base); event_store_server_version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } SupportedMethods::~SupportedMethods() { // @@protoc_insertion_point(destructor:event_store.client.server_features.SupportedMethods) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void SupportedMethods::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); event_store_server_version_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void SupportedMethods::ArenaDtor(void* object) { SupportedMethods* _this = reinterpret_cast< SupportedMethods* >(object); (void)_this; } void SupportedMethods::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void SupportedMethods::SetCachedSize(int size) const { _cached_size_.Set(size); } const SupportedMethods& SupportedMethods::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SupportedMethods_serverfeatures_2eproto.base); return *internal_default_instance(); } void SupportedMethods::Clear() { // @@protoc_insertion_point(message_clear_start:event_store.client.server_features.SupportedMethods) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; methods_.Clear(); event_store_server_version_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* SupportedMethods::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // repeated .event_store.client.server_features.SupportedMethod methods = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_methods(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); } else goto handle_unusual; continue; // string event_store_server_version = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_event_store_server_version(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "event_store.client.server_features.SupportedMethods.event_store_server_version")); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* SupportedMethods::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:event_store.client.server_features.SupportedMethods) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .event_store.client.server_features.SupportedMethod methods = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_methods_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(1, this->_internal_methods(i), target, stream); } // string event_store_server_version = 2; if (this->event_store_server_version().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_event_store_server_version().data(), static_cast<int>(this->_internal_event_store_server_version().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "event_store.client.server_features.SupportedMethods.event_store_server_version"); target = stream->WriteStringMaybeAliased( 2, this->_internal_event_store_server_version(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:event_store.client.server_features.SupportedMethods) return target; } size_t SupportedMethods::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:event_store.client.server_features.SupportedMethods) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .event_store.client.server_features.SupportedMethod methods = 1; total_size += 1UL * this->_internal_methods_size(); for (const auto& msg : this->methods_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // string event_store_server_version = 2; if (this->event_store_server_version().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_event_store_server_version()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void SupportedMethods::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:event_store.client.server_features.SupportedMethods) GOOGLE_DCHECK_NE(&from, this); const SupportedMethods* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SupportedMethods>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:event_store.client.server_features.SupportedMethods) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:event_store.client.server_features.SupportedMethods) MergeFrom(*source); } } void SupportedMethods::MergeFrom(const SupportedMethods& from) { // @@protoc_insertion_point(class_specific_merge_from_start:event_store.client.server_features.SupportedMethods) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; methods_.MergeFrom(from.methods_); if (from.event_store_server_version().size() > 0) { _internal_set_event_store_server_version(from._internal_event_store_server_version()); } } void SupportedMethods::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:event_store.client.server_features.SupportedMethods) if (&from == this) return; Clear(); MergeFrom(from); } void SupportedMethods::CopyFrom(const SupportedMethods& from) { // @@protoc_insertion_point(class_specific_copy_from_start:event_store.client.server_features.SupportedMethods) if (&from == this) return; Clear(); MergeFrom(from); } bool SupportedMethods::IsInitialized() const { return true; } void SupportedMethods::InternalSwap(SupportedMethods* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); methods_.InternalSwap(&other->methods_); event_store_server_version_.Swap(&other->event_store_server_version_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } ::PROTOBUF_NAMESPACE_ID::Metadata SupportedMethods::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void SupportedMethod::InitAsDefaultInstance() { } class SupportedMethod::_Internal { public: }; SupportedMethod::SupportedMethod(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), features_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:event_store.client.server_features.SupportedMethod) } SupportedMethod::SupportedMethod(const SupportedMethod& from) : ::PROTOBUF_NAMESPACE_ID::Message(), features_(from.features_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); method_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_method_name().empty()) { method_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_method_name(), GetArena()); } service_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_service_name().empty()) { service_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_service_name(), GetArena()); } // @@protoc_insertion_point(copy_constructor:event_store.client.server_features.SupportedMethod) } void SupportedMethod::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SupportedMethod_serverfeatures_2eproto.base); method_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); service_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } SupportedMethod::~SupportedMethod() { // @@protoc_insertion_point(destructor:event_store.client.server_features.SupportedMethod) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void SupportedMethod::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); method_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); service_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void SupportedMethod::ArenaDtor(void* object) { SupportedMethod* _this = reinterpret_cast< SupportedMethod* >(object); (void)_this; } void SupportedMethod::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void SupportedMethod::SetCachedSize(int size) const { _cached_size_.Set(size); } const SupportedMethod& SupportedMethod::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SupportedMethod_serverfeatures_2eproto.base); return *internal_default_instance(); } void SupportedMethod::Clear() { // @@protoc_insertion_point(message_clear_start:event_store.client.server_features.SupportedMethod) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; features_.Clear(); method_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); service_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* SupportedMethod::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // string method_name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_method_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "event_store.client.server_features.SupportedMethod.method_name")); CHK_(ptr); } else goto handle_unusual; continue; // string service_name = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_service_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "event_store.client.server_features.SupportedMethod.service_name")); CHK_(ptr); } else goto handle_unusual; continue; // repeated string features = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_features(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "event_store.client.server_features.SupportedMethod.features")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<26>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* SupportedMethod::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:event_store.client.server_features.SupportedMethod) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string method_name = 1; if (this->method_name().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_method_name().data(), static_cast<int>(this->_internal_method_name().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "event_store.client.server_features.SupportedMethod.method_name"); target = stream->WriteStringMaybeAliased( 1, this->_internal_method_name(), target); } // string service_name = 2; if (this->service_name().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_service_name().data(), static_cast<int>(this->_internal_service_name().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "event_store.client.server_features.SupportedMethod.service_name"); target = stream->WriteStringMaybeAliased( 2, this->_internal_service_name(), target); } // repeated string features = 3; for (int i = 0, n = this->_internal_features_size(); i < n; i++) { const auto& s = this->_internal_features(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "event_store.client.server_features.SupportedMethod.features"); target = stream->WriteString(3, s, target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:event_store.client.server_features.SupportedMethod) return target; } size_t SupportedMethod::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:event_store.client.server_features.SupportedMethod) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string features = 3; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(features_.size()); for (int i = 0, n = features_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( features_.Get(i)); } // string method_name = 1; if (this->method_name().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_method_name()); } // string service_name = 2; if (this->service_name().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_service_name()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void SupportedMethod::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:event_store.client.server_features.SupportedMethod) GOOGLE_DCHECK_NE(&from, this); const SupportedMethod* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SupportedMethod>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:event_store.client.server_features.SupportedMethod) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:event_store.client.server_features.SupportedMethod) MergeFrom(*source); } } void SupportedMethod::MergeFrom(const SupportedMethod& from) { // @@protoc_insertion_point(class_specific_merge_from_start:event_store.client.server_features.SupportedMethod) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; features_.MergeFrom(from.features_); if (from.method_name().size() > 0) { _internal_set_method_name(from._internal_method_name()); } if (from.service_name().size() > 0) { _internal_set_service_name(from._internal_service_name()); } } void SupportedMethod::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:event_store.client.server_features.SupportedMethod) if (&from == this) return; Clear(); MergeFrom(from); } void SupportedMethod::CopyFrom(const SupportedMethod& from) { // @@protoc_insertion_point(class_specific_copy_from_start:event_store.client.server_features.SupportedMethod) if (&from == this) return; Clear(); MergeFrom(from); } bool SupportedMethod::IsInitialized() const { return true; } void SupportedMethod::InternalSwap(SupportedMethod* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); features_.InternalSwap(&other->features_); method_name_.Swap(&other->method_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); service_name_.Swap(&other->service_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } ::PROTOBUF_NAMESPACE_ID::Metadata SupportedMethod::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace server_features } // namespace client } // namespace event_store PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::event_store::client::server_features::SupportedMethods* Arena::CreateMaybeMessage< ::event_store::client::server_features::SupportedMethods >(Arena* arena) { return Arena::CreateMessageInternal< ::event_store::client::server_features::SupportedMethods >(arena); } template<> PROTOBUF_NOINLINE ::event_store::client::server_features::SupportedMethod* Arena::CreateMaybeMessage< ::event_store::client::server_features::SupportedMethod >(Arena* arena) { return Arena::CreateMessageInternal< ::event_store::client::server_features::SupportedMethod >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
44.796102
188
0.762174
tomasruizr
fcf1f2c2bed21bae8cdb17c1e2ba7079cc585529
381
cpp
C++
problems/283.Move_Zeroes/AC_stl_n.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/283.Move_Zeroes/AC_stl_n.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/283.Move_Zeroes/AC_stl_n.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
/* * Author: illuz <iilluzen[at]gmail.com> * File: AC_stl_n.cpp * Create Date: 2015-09-24 11:13:56 * Descripton: */ #include <bits/stdc++.h> using namespace std; const int N = 0; class Solution { public: void moveZeroes(vector<int>& nums) { return fill(remove(nums.begin(), nums.end(), 0), nums.end(), 0); } }; int main() { return 0; }
15.24
72
0.582677
subramp-prep
fcf2817896184b8d46c955b637352d3b4478438f
3,357
cpp
C++
ace/tao/orbsvcs/tests/Event/lib/Counting_Consumer.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/orbsvcs/tests/Event/lib/Counting_Consumer.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/orbsvcs/tests/Event/lib/Counting_Consumer.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// Counting_Consumer.cpp,v 1.4 2000/03/24 05:20:21 coryan Exp #include "Counting_Consumer.h" ACE_RCSID(EC_Tests, EC_Count_Consumer, "Counting_Consumer.cpp,v 1.4 2000/03/24 05:20:21 coryan Exp") EC_Counting_Consumer::EC_Counting_Consumer (const char* name) : event_count (0), disconnect_count (0), name_ (name) { } void EC_Counting_Consumer::connect (RtecEventChannelAdmin::ConsumerAdmin_ptr consumer_admin, const RtecEventChannelAdmin::ConsumerQOS &qos, CORBA::Environment &ACE_TRY_ENV) { // The canonical protocol to connect to the EC RtecEventComm::PushConsumer_var consumer = this->_this (ACE_TRY_ENV); ACE_CHECK; if (CORBA::is_nil (this->supplier_proxy_.in ())) { this->supplier_proxy_ = consumer_admin->obtain_push_supplier (ACE_TRY_ENV); ACE_CHECK; } this->supplier_proxy_->connect_push_consumer (consumer.in (), qos, ACE_TRY_ENV); ACE_CHECK; } void EC_Counting_Consumer::disconnect (CORBA::Environment &ACE_TRY_ENV) { if (!CORBA::is_nil (this->supplier_proxy_.in ())) { this->supplier_proxy_->disconnect_push_supplier (ACE_TRY_ENV); ACE_CHECK; this->supplier_proxy_ = RtecEventChannelAdmin::ProxyPushSupplier::_nil (); } this->deactivate (ACE_TRY_ENV); } void EC_Counting_Consumer::deactivate (CORBA::Environment &ACE_TRY_ENV) { PortableServer::POA_var consumer_poa = this->_default_POA (ACE_TRY_ENV); ACE_CHECK; PortableServer::ObjectId_var consumer_id = consumer_poa->servant_to_id (this, ACE_TRY_ENV); ACE_CHECK; consumer_poa->deactivate_object (consumer_id.in (), ACE_TRY_ENV); ACE_CHECK; } void EC_Counting_Consumer::dump_results (int expected_count, int tolerance) { int diff = this->event_count - expected_count; if (diff > tolerance || diff < -tolerance) { ACE_DEBUG ((LM_DEBUG, "ERROR - %s unexpected number of events <%d>\n", this->name_, this->event_count)); } else { ACE_DEBUG ((LM_DEBUG, "%s - number of events <%d> within margins\n", this->name_, this->event_count)); } } void EC_Counting_Consumer::push (const RtecEventComm::EventSet& events, CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { if (events.length () == 0) { ACE_DEBUG ((LM_DEBUG, "%s (%P|%t) no events\n", this->name_)); return; } this->event_count ++; #if 0 if (this->event_count % 10 == 0) { ACE_DEBUG ((LM_DEBUG, "%s (%P|%t): %d events received\n", this->name_, this->event_count)); } #endif /* 0 */ } void EC_Counting_Consumer::disconnect_push_consumer (CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { this->disconnect_count++; this->supplier_proxy_ = RtecEventChannelAdmin::ProxyPushSupplier::_nil (); } #if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION) #elif defined(ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA) #endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */
27.743802
101
0.615133
tharindusathis
fcf3782388b4ce54e3dc0a01cb1de31eac9b64e8
13,861
cpp
C++
src/Samples/src/samples/animations/pump_jack_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/Samples/src/samples/animations/pump_jack_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/Samples/src/samples/animations/pump_jack_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/animations/animation.h> #include <babylon/animations/easing/bezier_curve_ease.h> #include <babylon/animations/easing/easing_function.h> #include <babylon/animations/ianimation_key.h> #include <babylon/cameras/free_camera.h> #include <babylon/engines/scene.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/lights/hemispheric_light.h> #include <babylon/meshes/mesh.h> #include <babylon/samples/babylon_register_sample.h> namespace BABYLON { namespace Samples { class FunnyEase : public EasingFunction { public: FunnyEase(float distanceOfStick, float lengthOfStick); ~FunnyEase() override; [[nodiscard]] float easeInCore(float gradient) const override; private: float _distanceOfStick; float _lengthOfStick; }; // end of class FunnyEase /** * @brief Pump Jack Scene. * @see https://www.babylonjs-playground.com/#1XA6UQ#50 * @see https://doc.babylonjs.com/babylon101/animations */ struct PumpJackScene : public IRenderableScene { public: PumpJackScene(ICanvas* iCanvas) : IRenderableScene(iCanvas) { } ~PumpJackScene() override = default; const char* getName() override { return "Pump Jack Scene"; } void initializeScene(ICanvas* canvas, Scene* scene) override { // Configuration float animationFrames = 200.f; float lengthOfStick = 6.f; float lengthOfTopStick = 10.f; float lengthOfPumpStick = lengthOfStick + 5.f; float distanceOfStick = 1.f; unsigned int moveDirection = 1; // Create custom easing function auto myEase = std::make_shared<FunnyEase>(distanceOfStick, lengthOfStick); // Initialization auto camera = FreeCamera::New("camera1", Vector3(0.f, 10.f, -25.f), scene); camera->setTarget(Vector3::Zero()); camera->position = Vector3(-5.f, 10.f, -25.f); camera->attachControl(canvas, true); auto light = HemisphericLight::New("Hemi0", Vector3(0.f, 1.f, 0.f), scene); light->diffuse = Color3(1.f, 1.f, 1.f); light->specular = Color3(1.f, 1.f, 1.f); light->groundColor = Color3(0.f, 0.f, 0.f); light->intensity = 0.7f; //#################// // Main motor axis // //#################// auto parentObject = Mesh::CreateBox("parent", 0.1f, scene); auto motorAxis = Mesh::CreateCylinder("motorAxis", 5, 0.5f, 0.5f, 24, 1, scene, true, 0); motorAxis->rotation().x = Math::PI_2; motorAxis->parent = parentObject.get(); auto motorAnimation = Animation::New("anim", "rotation.z", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys std::vector<IAnimationKey> motorIAnimationKeys{ IAnimationKey(0.f, AnimationValue(0.f)), IAnimationKey(animationFrames, AnimationValue(Math::PI2 * (moveDirection ? -1.f : 1.f))), }; motorAnimation->setKeys(motorIAnimationKeys); parentObject->animations.emplace_back(motorAnimation); scene->beginAnimation(parentObject, 0.f, animationFrames, true); //###########// // Front Arm // //###########// auto frontArmPaddle = Mesh::CreateBox("frontArmPaddle", 2.f, scene); frontArmPaddle->parent = parentObject.get(); frontArmPaddle->scaling().y = 2.f; frontArmPaddle->scaling().z = 0.1f; frontArmPaddle->scaling().x = 0.5f; frontArmPaddle->position().y = 1.5f; frontArmPaddle->position().z = -2.3f; auto frontWeight = Mesh::CreateBox("frontWeight", 1.f, scene); frontWeight->parent = parentObject.get(); frontWeight->position().y = 3.f; frontWeight->position().z = -2.3f; frontWeight->scaling = Vector3(3.f, 1.6f, 0.3f); auto frontPivot = Mesh::CreateBox("frontPivot", 0.5f, scene); frontPivot->parent = parentObject.get(); frontPivot->position().y = distanceOfStick; frontPivot->position().z = -2.3f; auto frontStick = Mesh::CreateBox("frontStick", 1.f, scene); frontStick->parent = frontPivot.get(); frontStick->position().x = -(lengthOfStick / 2.f); frontStick->position().z = -0.3f; frontStick->scaling = Vector3(lengthOfStick, 0.2f, 0.2f); auto frontStickAnimation = Animation::New( "anim", "rotation.z", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys std::vector<IAnimationKey> frontStickIAnimationKeys{ IAnimationKey(0, AnimationValue(moveDirection ? -2.5f * Math::PI : -Math::PI_2)), IAnimationKey(animationFrames, AnimationValue(moveDirection ? -Math::PI_2 : -2.5f * Math::PI)), }; frontStickAnimation->setKeys(frontStickIAnimationKeys); frontStickAnimation->setEasingFunction(myEase); frontPivot->animations.emplace_back(frontStickAnimation); scene->beginAnimation(frontPivot, 0.f, animationFrames, true); //###########// // Back Arm // //###########// auto backArmPaddle = Mesh::CreateBox("backArmPaddle", 2.f, scene); backArmPaddle->parent = parentObject.get(); backArmPaddle->scaling().y = 2.f; backArmPaddle->scaling().z = 0.1f; backArmPaddle->scaling().x = 0.5f; backArmPaddle->position().y = 1.5f; backArmPaddle->position().z = 2.3f; auto backWeight = Mesh::CreateBox("backWeight", 1.f, scene); backWeight->parent = parentObject.get(); backWeight->position().y = 3.f; backWeight->position().z = 2.3f; backWeight->scaling = Vector3(3.f, 1.6f, 0.3f); auto backPivot = Mesh::CreateBox("backPivot", 0.5f, scene); backPivot->parent = parentObject.get(); backPivot->position().y = distanceOfStick; backPivot->position().z = 2.3f; auto backStick = Mesh::CreateBox("backStick", 1.f, scene); backStick->parent = backPivot.get(); backStick->position().x = -(lengthOfStick / 2.f); backStick->position().z = 0.3f; backStick->scaling = Vector3(lengthOfStick, 0.2f, 0.2f); auto backStickAnimation = Animation::New( "anim", "rotation.z", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys std::vector<IAnimationKey> backStickIAnimationKeys{ IAnimationKey(0, AnimationValue(moveDirection ? -2.5f * Math::PI : -Math::PI_2)), IAnimationKey(animationFrames, AnimationValue(moveDirection ? -Math::PI_2 : -2.5f * Math::PI)), }; backStickAnimation->setKeys(backStickIAnimationKeys); backStickAnimation->setEasingFunction(myEase); backPivot->animations.emplace_back(backStickAnimation); scene->beginAnimation(backPivot, 0.f, animationFrames, true); //############// // Top Pieces // //############// auto topStick = Mesh::CreateBox("topStick", 1, scene); topStick->scaling = Vector3(lengthOfTopStick, 0.2f, 0.2f); topStick->position().x = -lengthOfTopStick / 2.f; topStick->position().y = lengthOfStick; auto topStickAnimation = Animation::New( "anim", "rotation.z", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); float moveAngle = std::asin((2.f * distanceOfStick) / lengthOfTopStick); // Animation keys std::vector<IAnimationKey> topStickIAnimationKeys{ IAnimationKey(0, AnimationValue(moveAngle)), IAnimationKey(animationFrames / 2, AnimationValue(-moveAngle)), IAnimationKey(animationFrames, AnimationValue(moveAngle)), }; topStickAnimation->setKeys(topStickIAnimationKeys); topStickAnimation->setEasingFunction(BezierCurveEase::New(0.35f, 0.1f, 0.65f, 0.9f)); topStick->animations.emplace_back(topStickAnimation); scene->beginAnimation(topStick, 0.f, animationFrames, true); auto topBar = Mesh::CreateCylinder("topBar", 5.5f, 0.7f, 0.7f, 24, 1, scene, true, 0); topBar->parent = topStick.get(); topBar->position().x = 0.5f; topBar->scaling = Vector3(1.f / lengthOfTopStick, 5.f, 5.f); topBar->rotation().x = Math::PI_2; auto topBall = Mesh::CreateSphere("topBall", 12, 1, scene, true, 0); topBall->parent = topStick.get(); topBall->position().x = -0.5f; topBall->scaling = Vector3(1.f / lengthOfTopStick, 5.f, 5.f); //############// // Pump Stick // //############// auto pumpStick = Mesh::CreateBox("pumpStick", 1.f, scene); pumpStick->position().x = -lengthOfTopStick; pumpStick->scaling = Vector3(0.2f, lengthOfPumpStick, 0.2f); auto pumpStickAnimation = Animation::New( "anim", "position.y", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys std::vector<IAnimationKey> pumpStickIAnimationKeys{ IAnimationKey(0, AnimationValue(lengthOfStick - (lengthOfPumpStick / 2.f) - distanceOfStick)), IAnimationKey(animationFrames / 2, AnimationValue(lengthOfStick - (lengthOfPumpStick / 2.f) + distanceOfStick)), IAnimationKey(animationFrames, AnimationValue(lengthOfStick - (lengthOfPumpStick / 2.f) - distanceOfStick)), }; pumpStickAnimation->setKeys(pumpStickIAnimationKeys); pumpStickAnimation->setEasingFunction(BezierCurveEase::New(0.35f, 0.1f, 0.65f, 0.9f)); pumpStick->animations.emplace_back(pumpStickAnimation); scene->beginAnimation(pumpStick, 0.f, animationFrames, true); //####################// // Visual Complements // //####################// auto ground = Mesh::CreateBox("ground", 1.f, scene); ground->position().x = -5.f; ground->position().y = -5.f; ground->scaling().x = 20.f; ground->scaling().z = 10.f; auto groundEntrance = Mesh::CreateCylinder("groundEntrance", 3, 1, 1, 12, 1, scene, true, 0); groundEntrance->position().x = -lengthOfTopStick; groundEntrance->position().y = ground->position().y + 1.5f; auto centerPillarFront = Mesh::CreateBox("centerPillarFront", 1.f, scene); centerPillarFront->position().x = -lengthOfTopStick / 2.f; centerPillarFront->position().z = -1.f; centerPillarFront->scaling().y = 11.f; centerPillarFront->rotation().x = 0.16f; auto centerPillarBack = Mesh::CreateBox("centerPillarBack", 1.f, scene); centerPillarBack->position().x = -lengthOfTopStick / 2.f; centerPillarBack->position().z = 1.f; centerPillarBack->scaling().y = 11.f; centerPillarBack->rotation().x = -0.16f; auto topAxis = Mesh::CreateCylinder("topAxis", 2, 1, 1, 12, 1, scene, true, 0); topAxis->position().x = -lengthOfTopStick / 2.f; topAxis->position().y = lengthOfStick - 0.6f; topAxis->rotation().x = Math::PI_2; auto engine2 = Mesh::CreateBox("engine2", 1.f, scene); engine2->scaling().x = 3.f; engine2->scaling().y = 2.f; engine2->scaling().z = 2.f; auto support = Mesh::CreateBox("support", 1.f, scene); support->scaling().y = -ground->position().x; support->scaling().x = 0.7f; support->scaling().z = 0.7f; support->position().y = ground->position().x / 2.f; support->position().z = -1.f; auto support2 = Mesh::CreateBox("support2", 1.f, scene); support2->scaling().y = -ground->position().x; support2->scaling().x = 0.7f; support2->scaling().z = 0.7f; support2->position().y = ground->position().x / 2.f; support2->position().z = 1.f; auto support3 = Mesh::CreateBox("support3", 1.f, scene); support3->scaling().y = -ground->position().x + 1.f; support3->scaling().x = 0.7f; support3->scaling().z = 0.7f; support3->position().x = 2.f; support3->position().y = ground->position().x / 2.f; support3->position().z = 1.f; support3->rotation().z = 0.7f; auto support4 = Mesh::CreateBox("support4", 1.f, scene); support4->scaling().y = -ground->position().x + 1.f; support4->scaling().x = 0.7f; support4->scaling().z = 0.7f; support4->position().x = 2.f; support4->position().y = ground->position().x / 2.f; support4->position().z = -1.f; support4->rotation().z = 0.7f; auto support5 = Mesh::CreateBox("support5", 1.f, scene); support5->scaling().y = -ground->position().x + 1.f; support5->scaling().x = 0.7f; support5->scaling().z = 0.7f; support5->position().x = -2.f; support5->position().y = ground->position().x / 2.f; support5->position().z = 1.f; support5->rotation().z = -0.7f; auto support6 = Mesh::CreateBox("support6", 1.f, scene); support6->scaling().y = -ground->position().x + 1.f; support6->scaling().x = 0.7f; support6->scaling().z = 0.7f; support6->position().x = -2.f; support6->position().y = ground->position().x / 2.f; support6->position().z = -1.f; support6->rotation().z = -0.7f; auto support7 = Mesh::CreateBox("support7", 1.f, scene); support7->position().x = -lengthOfTopStick / 4.f - 0.5f; support7->position().y = 2.f; support7->scaling().y = 8.f; support7->scaling().x = 0.7f; support7->scaling().z = 0.7f; support7->rotation().z = 0.5f; } }; // end of struct PumpJackScene } // end of namespace Samples } // end of namespace BABYLON namespace BABYLON { namespace Samples { FunnyEase::FunnyEase(float distanceOfStick, float lengthOfStick) : _distanceOfStick{distanceOfStick}, _lengthOfStick{lengthOfStick} { } FunnyEase::~FunnyEase() = default; float FunnyEase::easeInCore(float gradient) const { float angle = gradient * Math::PI2; angle += std::asin(std::sin(angle) * _distanceOfStick / _lengthOfStick); gradient = angle / Math::PI2; return gradient; } BABYLON_REGISTER_SAMPLE("Animations", PumpJackScene) } // end of namespace Samples } // end of namespace BABYLON
37.665761
100
0.635236
sacceus
fcf57ec8a6e88185c93dc3f764ba1e14a4140ece
5,242
cpp
C++
src/editor/graph_ed.cpp
geoo89/Lix
47dfd2317509ed5cb39b7b230b2de138dc613a6d
[ "CC0-1.0" ]
1
2015-08-29T05:22:40.000Z
2015-08-29T05:22:40.000Z
src/editor/graph_ed.cpp
carvalhomb/AdaptiveLix
d7054c5f96fae54dccef23e48760851b4981a109
[ "CC0-1.0" ]
null
null
null
src/editor/graph_ed.cpp
carvalhomb/AdaptiveLix
d7054c5f96fae54dccef23e48760851b4981a109
[ "CC0-1.0" ]
null
null
null
/* * editor/graph_ed.cpp * * Hatches are always drawn with a rotation of 0. Instead, rotation means * if lixes should walk to the left (!= 0) instead of the right (== 0). * Thus, some functions must override those in Graphic:: to implement this. * */ #include "graph_ed.h" #include "../gameplay/lookup.h" #include "../graphic/gra_lib.h" #include "../other/globals.h" #include "../other/help.h" // proper modulo via Help::mod EdGraphic::EdGraphic(Torbit& tb, const Object* o, int x, int y) : Graphic (o->cb, tb, x, y), object (o), draw_info(false) { } EdGraphic::~EdGraphic() { } void EdGraphic::animate() { if (is_last_frame()) { if (object->type != Object::HATCH) set_x_frame(0); // do nothing for hatches here. } else set_x_frame(get_x_frame() + 1); // Traps won't be animated all the time by Gameplay, so we don't have // to check for anything here. } int EdGraphic::get_xl() const { // see top comment if (object->type == Object::HATCH) return get_cutbit()->get_xl(); else return Graphic:: get_xl(); } int EdGraphic::get_yl() const { // see top comment if (object->type == Object::HATCH) return get_cutbit()->get_yl(); else return Graphic:: get_yl(); } int EdGraphic::get_selbox_x() const { if (object->type == Object::HATCH) return object->selbox_x; int edge = (int) get_rotation(); if (get_mirror()) edge = edge == 1 ? 3 : edge == 3 ? 1 : edge; switch (edge) { case 0: return object->selbox_x; // rotation is clockwise case 1: return object->cb.get_yl() - object->selbox_y - object->selbox_yl; case 2: return object->cb.get_xl() - object->selbox_x - object->selbox_xl; case 3: return object->selbox_y; } return object->selbox_x; // against compiler warning } int EdGraphic::get_selbox_y() const { if (object->type == Object::HATCH) return object->selbox_y; int edge = (int) get_rotation(); if (get_mirror()) edge = edge == 0 ? 2 : edge == 2 ? 0 : edge; switch (edge) { case 0: return object->selbox_y; case 1: return object->selbox_x; case 2: return object->cb.get_yl() - object->selbox_y - object->selbox_yl; case 3: return object->cb.get_xl() - object->selbox_x - object->selbox_xl; } return object->selbox_y; // against compiler warning } int EdGraphic::get_selbox_xl() const { if (object->type == Object::HATCH) return object->selbox_xl; if ((int) get_rotation() % 2 == 1) return object->selbox_yl; else return object->selbox_xl; } int EdGraphic::get_selbox_yl() const { if (object->type == Object::HATCH) return object->selbox_yl; if ((int) get_rotation() % 2 == 1) return object->selbox_xl; else return object->selbox_yl; } int EdGraphic::get_pixel(int x, int y) const { // see top comment if (object->type == Object::HATCH) { const int use_y = !get_mirror() ? y : get_yl() - y; return get_cutbit()->get_pixel(get_x_frame(), get_y_frame(), x, use_y); } else return Graphic::get_pixel(x, y); } void EdGraphic::draw() { // see top comment if (object->type == Object::HATCH && get_rotation()) { set_rotation(false); Graphic::draw(); set_rotation(true); } else Graphic::draw(); if (draw_info) { if (object->type == Object::HATCH) { // draw arrow pointing into the hatch's direction static const Cutbit& cb = GraLib::get(gloB->file_bitmap_edit_hatch); cb.draw(get_ground(), get_x() + get_xl()/2 - cb.get_xl()/2, get_y() + ::text_height(font_med), get_rotation() ? 1 : 0, 0); } } } void EdGraphic::draw_with_trigger_area() { // do the regular drawing draw(); // now draw trigger area on top if (object->type == Object::GOAL || object->type == Object::HATCH || object->type == Object::TRAP || object->type == Object::WATER || object->type == Object::FLING || object->type == Object::TRAMPOLINE) { get_ground().draw_rectangle( get_x() + object->get_trigger_x(), get_y() + object->get_trigger_y(), object->trigger_xl, object->trigger_yl, makecol(0x40, 0xFF, 0xFF) ); } } void EdGraphic::draw_lookup(Lookup& lk) { if (!object) return; Lookup::LoNr nr = 0; switch (object->type) { case Object::GOAL: nr = Lookup::bit_goal; break; case Object::TRAP: nr = Lookup::bit_trap; break; case Object::WATER: nr = object->subtype == 0 ? Lookup::bit_water : Lookup::bit_fire; break; case Object::FLING: nr = Lookup::bit_fling; break; case Object::TRAMPOLINE: nr = Lookup::bit_trampoline; break; default: break; } lk.add_rectangle(get_x() + object->get_trigger_x(), get_y() + object->get_trigger_y(), object->trigger_xl, object->trigger_yl, nr); }
28.48913
79
0.57459
geoo89
fcf641ad6349c31321ed91a8b6f670f1547414e2
546
hpp
C++
include/termui/window_resize.hpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
1
2020-07-31T01:34:47.000Z
2020-07-31T01:34:47.000Z
include/termui/window_resize.hpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
null
null
null
include/termui/window_resize.hpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
null
null
null
#ifndef WINDOW_RESIZE_H #define WINDOW_RESIZE_H #include "dimensions.hpp" namespace bandwit { namespace termui { class WindowResizeReceiver { public: WindowResizeReceiver() = default; virtual ~WindowResizeReceiver() = default; CLASS_DISABLE_COPIES(WindowResizeReceiver) CLASS_DISABLE_MOVES(WindowResizeReceiver) virtual void on_window_resize(const Dimensions &win_dim_old, const Dimensions &win_dim_new) = 0; }; } // namespace termui } // namespace bandwit #endif // WINDOW_RESIZE_H
21.84
69
0.723443
numerodix
fcf71d6ac87384ad228ec4341fc7cf4cd88174f9
792
cpp
C++
awesome/c_cpp/cpp-cheat/cpp/cast_operator.cpp
liujiamingustc/phd
4f815a738abad43531d02ac66f5bd0d9a1def52a
[ "Apache-2.0" ]
3
2021-01-06T03:01:18.000Z
2022-03-21T03:02:55.000Z
awesome/c_cpp/cpp-cheat/cpp/cast_operator.cpp
liujiamingustc/phd
4f815a738abad43531d02ac66f5bd0d9a1def52a
[ "Apache-2.0" ]
null
null
null
awesome/c_cpp/cpp-cheat/cpp/cast_operator.cpp
liujiamingustc/phd
4f815a738abad43531d02ac66f5bd0d9a1def52a
[ "Apache-2.0" ]
null
null
null
/* Allows to convert objects to primitives and other objects. http://en.cppreference.com/w/cpp/language/cast_operator */ #include "common.hpp" class ToInt { public: int i; ToInt(int i) : i(i) {} operator int() { return this->i; } }; class ToToInt { public: int i; ToToInt(int i) : i(i) {} operator ToInt() { return ToInt(this->i); } }; int main() { // Explicit cast. assert((int)ToInt(0) == 0); // Implicit conversion. assert(ToInt(0) == 0); // ERROR: Only a single implicit cast is possible at a time. //assert(ToToInt(0) == 0); // OK, on implicit cast. assert((ToInt)ToToInt(0) == 0); // OK, all explicit. assert((int)(ToInt)ToToInt(0) == 0); }
18.418605
64
0.537879
liujiamingustc
fcf760b3897709d7b29603449f5a87cbabfcc694
117
cpp
C++
lang/Library.cpp
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
lang/Library.cpp
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
lang/Library.cpp
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
#include <lang/Library.h> #ifdef LINUX #include <lang/Library.Linux> #elif WIN32 #include <lang/Library.W32> #endif
14.625
29
0.74359
gizmomogwai
1e02cb66d96eafdf12b13d7df22a6c3997f42770
23,078
cpp
C++
rw_ray_tracing_lib/bvh_builder.cpp
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
rw_ray_tracing_lib/bvh_builder.cpp
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
rw_ray_tracing_lib/bvh_builder.cpp
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
#include "bvh_builder.h" #include <DebugUtils/DebugLogger.h> #include <Engine/Common/IRenderingContext.h> #include <Engine/IRenderer.h> #include <algorithm> #include <chrono> #include <limits> #include <sstream> #include <ray_tracing_texture_cache.h> #include <rw_engine/global_definitions.h> #include <rw_engine/rw_rh_pipeline.h> using namespace rw_raytracing_lib; // Expands a 10-bit integer into 30 bits // by inserting 2 zeros after each bit. uint32_t expandBits( uint32_t v ) { v = ( v * 0x00010001u ) & 0xFF0000FFu; v = ( v * 0x00000101u ) & 0x0F00F00Fu; v = ( v * 0x00000011u ) & 0xC30C30C3u; v = ( v * 0x00000005u ) & 0x49249249u; return v; } // Generates uint32_t morton3D( float x, float y, float z ) { x = min( max( x * 1024.0f, 0.0f ), 1023.0f ); y = min( max( y * 1024.0f, 0.0f ), 1023.0f ); z = min( max( z * 1024.0f, 0.0f ), 1023.0f ); uint32_t xx = expandBits( static_cast<uint32_t>( x ) ); uint32_t yy = expandBits( static_cast<uint32_t>( y ) ); uint32_t zz = expandBits( static_cast<uint32_t>( z ) ); return ( ( zz << 2 ) | ( yy << 1 ) | xx ); } constexpr auto MORTON_CODE_START = 29; BVHBuilder::BVHBuilder() {} static inline uint32_t getDimForMorton3D( uint32_t idx ) { return idx % 3; } constexpr auto AAC_DELTA = 20; constexpr auto AAC_EPSILON = 0.1f; // 0.1f for HQ, 0.2 for fast constexpr auto AAC_ALPHA = ( 0.5f - AAC_EPSILON ); static inline float AAC_C() { return ( 0.5f * powf( AAC_DELTA, 0.5f + AAC_EPSILON ) ); } static inline uint32_t AAC_F( uint32_t x ) { return static_cast<uint32_t>( ceil( AAC_C() * powf( x, AAC_ALPHA ) ) ); } // Searches for the best candidate to merge i-th cluster with, // using surface area heuristic // O(n) uint32_t GetClosestCluster( std::vector<BVHBuildNode *> &clusters, uint32_t i ) { float closestDist = INFINITY; uint32_t idx = i; for ( uint32_t j = 0; j < clusters.size(); ++j ) { if ( i == j ) continue; BBox combined = BBox::Merge( clusters[i]->bounds, clusters[j]->bounds ); float d = combined.SurfaceArea(); // search for minimal surface area of combined bboxes if ( d < closestDist ) { closestDist = d; idx = j; } } return idx; } std::vector<BVHBuildNode *> combineCluster( std::vector<BVHBuildNode *> &clusters, uint32_t n, uint32_t &totalNodes, uint32_t dim ) { std::vector<uint32_t> closest( clusters.size(), 0 ); // O(n^2) // Build closest clusters lookup table for ( uint32_t i = 0; i < clusters.size(); ++i ) { closest[i] = GetClosestCluster( clusters, i ); } while ( clusters.size() > n ) { float bestDist = INFINITY; uint32_t leftIdx = 0; uint32_t rightIdx = 0; // Search for 2 closest clusters to merge for ( uint32_t i = 0; i < clusters.size(); ++i ) { BBox combined = BBox::Merge( clusters[i]->bounds, clusters[closest[i]]->bounds ); float d = combined.SurfaceArea(); if ( d < bestDist ) { bestDist = d; leftIdx = i; rightIdx = closest[i]; } } totalNodes++; // Create new cluster node BVHBuildNode *node = new BVHBuildNode(); node->InitInterior( dim, clusters[leftIdx], clusters[rightIdx] ); clusters[leftIdx] = node; clusters[rightIdx] = clusters.back(); closest[rightIdx] = closest.back(); clusters.pop_back(); closest.pop_back(); closest[leftIdx] = GetClosestCluster( clusters, leftIdx ); for ( uint32_t i = 0; i < clusters.size(); ++i ) { if ( closest[i] == leftIdx || closest[i] == rightIdx ) closest[i] = GetClosestCluster( clusters, i ); else if ( closest[i] == closest.size() ) { closest[i] = rightIdx; } } } return clusters; } uint32_t makePartition( std::vector<std::pair<uint32_t, uint32_t>> sortedMC, uint32_t start, uint32_t end, uint32_t partitionbit ) { uint32_t curFind = ( 1 << partitionbit ); if ( ( sortedMC[start].first & curFind ) == ( sortedMC[end - 1].first & curFind ) ) { return start + ( end - start ) / 2; } uint32_t lower = start; uint32_t upper = end; while ( lower < upper ) { uint32_t mid = lower + ( upper - lower ) / 2; if ( ( sortedMC[mid].first & curFind ) == 0 ) { lower = mid + 1; } else { upper = mid; } } return lower; } void BVHBuilder::RecursiveBuildAAC( std::vector<BVHPrimitive> &buildData, std::vector<std::pair<uint32_t, uint32_t>> mortonCodes, uint32_t start, uint32_t end, uint32_t &totalNodes, uint32_t partitionBit, std::vector<BVHBuildNode *> *clusterData ) { if ( end - start == 0 ) { return; } uint32_t dim = getDimForMorton3D( partitionBit ); if ( end - start < AAC_DELTA ) { std::vector<BVHBuildNode *> clusters; totalNodes += ( end - start ); for ( uint32_t i = start; i < end; ++i ) { // Create leaf _BVHBuildNode_ BVHBuildNode *node = new BVHBuildNode(); uint32_t primIdx = mortonCodes[i].second; node->InitLeaf( primIdx, 1, buildData[primIdx].boundBox ); // deal with firstPrimOffset later with DFS clusters.push_back( node ); } *clusterData = combineCluster( clusters, AAC_F( AAC_DELTA ), totalNodes, dim ); return; } uint32_t splitIdx = makePartition( mortonCodes, start, end, partitionBit ); uint32_t newPartionBit = partitionBit - 1; std::vector<BVHBuildNode *> leftC; std::vector<BVHBuildNode *> rightC; uint32_t rightTotalnodes = 0; RecursiveBuildAAC( buildData, mortonCodes, start, splitIdx, totalNodes, newPartionBit, &leftC ); RecursiveBuildAAC( buildData, mortonCodes, splitIdx, end, rightTotalnodes, newPartionBit, &rightC ); totalNodes += rightTotalnodes; leftC.insert( leftC.end(), rightC.begin(), rightC.end() ); *clusterData = combineCluster( leftC, AAC_F( end - start ), totalNodes, dim ); } std::vector<BVHPrimitive> BVHBuilder::GenerateBVHPrimitiveList( rh::rw::engine::RpGeometryInterface *geometry ) { std::vector<BVHPrimitive> result; result.reserve( static_cast<size_t>( geometry->GetTriangleCount() ) ); for ( size_t i = 0; i < static_cast<size_t>( geometry->GetTriangleCount() ); i++ ) { auto triangle_ids = geometry->GetTrianglePtr()[i].vertIndex; RwV3d v1 = geometry->GetMorphTarget( 0 )->verts[triangle_ids[0]]; RwV3d v2 = geometry->GetMorphTarget( 0 )->verts[triangle_ids[1]]; RwV3d v3 = geometry->GetMorphTarget( 0 )->verts[triangle_ids[2]]; BBox bbox( v1, v2, v3 ); DirectX::XMVECTOR centroid = bbox.GetCenter(); result.push_back( {bbox, centroid, static_cast<uint32_t>( i ), {0, 0, 0}} ); } return result; } BBox::BBox( const RwV3d &a, const RwV3d &b, const RwV3d &c ) { const float min_f = -( std::numeric_limits<float>::max )(); const float max_f = ( std::numeric_limits<float>::max )(); DirectX::XMVECTOR max_xm = {min_f, min_f, min_f, 1.0f}; DirectX::XMVECTOR min_xm = {max_f, max_f, max_f, 1.0f}; min_xm = DirectX::XMVectorMin( min_xm, {a.x, a.y, a.z, 1.0f} ); min_xm = DirectX::XMVectorMin( min_xm, {b.x, b.y, b.z, 1.0f} ); min_xm = DirectX::XMVectorMin( min_xm, {c.x, c.y, c.z, 1.0f} ); max_xm = DirectX::XMVectorMax( max_xm, {a.x, a.y, a.z, 1.0f} ); max_xm = DirectX::XMVectorMax( max_xm, {b.x, b.y, b.z, 1.0f} ); max_xm = DirectX::XMVectorMax( max_xm, {c.x, c.y, c.z, 1.0f} ); DirectX::XMStoreFloat4( &max, max_xm ); DirectX::XMStoreFloat4( &min, min_xm ); } BBox::BBox() { const float min_f = -( std::numeric_limits<float>::max )(); const float max_f = ( std::numeric_limits<float>::max )(); max = {min_f, min_f, min_f, 0}; min = {max_f, max_f, max_f, 0}; } void BBox::Merge( const DirectX::XMVECTOR &vec ) { DirectX::XMVECTOR max_xm = DirectX::XMLoadFloat4( &max ); DirectX::XMVECTOR min_xm = DirectX::XMLoadFloat4( &min ); min_xm = DirectX::XMVectorMin( min_xm, vec ); max_xm = DirectX::XMVectorMax( max_xm, vec ); DirectX::XMStoreFloat4( &max, max_xm ); DirectX::XMStoreFloat4( &min, min_xm ); } BBox BBox::Merge( const BBox &a, const BBox &b ) { BBox c; DirectX::XMStoreFloat4( &c.min, DirectX::XMVectorMin( DirectX::XMVectorMin( a.GetMinXm(), b.GetMinXm() ), c.GetMinXm() ) ); DirectX::XMStoreFloat4( &c.max, DirectX::XMVectorMax( DirectX::XMVectorMax( a.GetMaxXm(), b.GetMaxXm() ), c.GetMaxXm() ) ); return c; } uint32_t bvhDfs( std::vector<LinearBVHNode> &flat_tree, RpTriangle *&primitives, std::vector<RpTriangle> &orderedPrims, BVHBuildNode *node, std::vector<BVHPrimitive> &buildData, uint32_t &offset ) { LinearBVHNode &linearNode = flat_tree[offset]; linearNode.bounds = node->bounds; uint32_t myOffset = offset++; if ( node->nPrimitives > 0 ) { assert( !node->children[0] && !node->children[1] ); uint32_t firstPrimOffset = orderedPrims.size(); uint32_t primNum = buildData[node->firstPrimOffset].triangleId; orderedPrims.push_back( primitives[primNum] ); node->firstPrimOffset = firstPrimOffset; linearNode.primitivesOffset = node->firstPrimOffset; linearNode.nPrimitives = node->nPrimitives; } else { linearNode.nPrimitives = 0; linearNode.axis = node->splitAxis; bvhDfs( flat_tree, primitives, orderedPrims, node->children[0], buildData, offset ); linearNode.secondChildOffset = bvhDfs( flat_tree, primitives, orderedPrims, node->children[1], buildData, offset ); } delete node; return myOffset; } uint32_t bvhDfsTlas( std::vector<LinearBVHNodeTLAS> &flat_tree, const std::vector<BLAS_Instance> &instances, uint32_t &inst_offset, BVHBuildNode *node, std::vector<BVHPrimitive> &buildData, uint32_t &offset ) { LinearBVHNodeTLAS &linearNode = flat_tree[offset]; linearNode.bounds = node->bounds; uint32_t myOffset = offset++; if ( node->nPrimitives > 0 ) { assert( !node->children[0] && !node->children[1] ); uint32_t firstPrimOffset = inst_offset; uint32_t primNum = buildData[node->firstPrimOffset].triangleId; inst_offset++; node->firstPrimOffset = firstPrimOffset; linearNode.blasBVHOffset = primNum; linearNode.lowLevel_a = 1; } else { linearNode.lowLevel_a = 0; linearNode.axis = node->splitAxis; bvhDfsTlas( flat_tree, instances, inst_offset, node->children[0], buildData, offset ); linearNode.secondChildOffset = bvhDfsTlas( flat_tree, instances, inst_offset, node->children[1], buildData, offset ); } delete node; return myOffset; } BLAS_BVH BVHBuilder::BuildBVH( rh::rw::engine::RpGeometryInterface *geometry, RayTracingTextureCache *texture_cache ) { RpTriangle *tri_list = geometry->GetTrianglePtr(); auto s = std::chrono::high_resolution_clock::now(); auto bvh_prim_list = GenerateBVHPrimitiveList( geometry ); BBox centerBBox; for ( uint32_t i = 0; i < bvh_prim_list.size(); ++i ) centerBBox.Merge( bvh_prim_list[i].centroid ); std::vector<std::pair<uint32_t, uint32_t>> mortonCodes; mortonCodes.reserve( bvh_prim_list.size() ); for ( uint32_t i = 0; i < bvh_prim_list.size(); ++i ) { auto c = bvh_prim_list[i].centroid; float newX = ( DirectX::XMVectorGetX( c ) - centerBBox.min.x ) / ( centerBBox.max.x - centerBBox.min.x ); float newY = ( DirectX::XMVectorGetY( c ) - centerBBox.min.y ) / ( centerBBox.max.y - centerBBox.min.y ); float newZ = ( DirectX::XMVectorGetZ( c ) - centerBBox.min.z ) / ( centerBBox.max.z - centerBBox.min.z ); uint32_t mc = morton3D( newX, newY, newZ ); mortonCodes.push_back( std::make_pair( mc, i ) ); } std::sort( mortonCodes.begin(), mortonCodes.end() ); auto bv_bs = std::chrono::high_resolution_clock::now(); std::vector<BVHBuildNode *> clusters; uint32_t totalNodes = 0; RecursiveBuildAAC( bvh_prim_list, mortonCodes, 0, bvh_prim_list.size(), totalNodes, MORTON_CODE_START, &clusters ); BVHBuildNode *root = combineCluster( clusters, 1, totalNodes, 2 )[0]; auto bv_be = std::chrono::high_resolution_clock::now(); std::vector<LinearBVHNode> bvh_tree_flat; bvh_tree_flat.reserve( totalNodes ); for ( uint32_t i = 0; i < totalNodes; ++i ) bvh_tree_flat.push_back( {} ); std::vector<RpTriangle> ordered_tri_list; uint32_t offset = 0; bvhDfs( bvh_tree_flat, tri_list, ordered_tri_list, root, bvh_prim_list, offset ); auto e = std::chrono::high_resolution_clock::now(); std::stringstream ss; ss << "bvh build time without morton codes: " << std::chrono::duration_cast<std::chrono::milliseconds>( e - bv_bs ).count() << " ms.\n" << "bvh build time: " << std::chrono::duration_cast<std::chrono::milliseconds>( e - s ).count() << " ms.\n" << "bvh recursive aac build time: " << std::chrono::duration_cast<std::chrono::milliseconds>( bv_be - bv_bs ).count() << " ms.\n"; rh::debug::DebugLogger::Log( ss.str() ); std::vector<RTVertex> verts; verts.reserve( static_cast<uint32_t>( geometry->GetVertexCount() ) ); for ( auto i = 0; i < geometry->GetVertexCount(); i++ ) { uint32_t color = geometry->GetVertexColorPtr() != nullptr ? *reinterpret_cast<uint32_t *>( &geometry->GetVertexColorPtr()[i] ) : 0xFF000000; RwTexCoords texcoords = geometry->GetTexCoordSetPtr( 0 ) != nullptr ? geometry->GetTexCoordSetPtr( 0 )[i] : RwTexCoords{0, 0}; verts.push_back( {{geometry->GetMorphTarget( 0 )->verts[i].x, geometry->GetMorphTarget( 0 )->verts[i].y, geometry->GetMorphTarget( 0 )->verts[i].z}, color, {texcoords.u, texcoords.v, 0, 0}} ); } std::vector<MaterialInfo> materials; RpMeshHeader *header = geometry->GetMeshHeader(); RpMesh *mesh_array = reinterpret_cast<RpMesh *>( reinterpret_cast<uint8_t *>( header ) + sizeof( RpMeshHeader ) ); materials.reserve( header->numMeshes ); for ( auto i = 0; i < header->numMeshes; i++ ) { const RpMesh &mesh = mesh_array[i]; MaterialInfo info{}; info.textureId = -1; if ( mesh.material && mesh.material->texture && mesh.material->texture->raster ) { info.transparency = mesh.material->color.alpha; auto address = texture_cache->GetTextureAddress( rh::rw::engine::GetInternalRaster( mesh.material->texture->raster ) ); if ( address != nullptr ) { info.textureId = address->id; info.mipLevel = address->mip_level; info.xScale = address->scaleX; info.yScale = address->scaleY; } } materials.push_back( info ); } return {bvh_tree_flat, ordered_tri_list, verts, materials}; } void BVHBuilder::PackBLASBVH( PackedBLAS_BVH &result, const std::vector<BLAS_BVH *> &new_blas, uint32_t last_id_offset ) { auto s = std::chrono::high_resolution_clock::now(); uint32_t blas_bvh_nodes_size = result.blas.nodes.size(); uint32_t blas_triangle_lists_size = result.blas.ordered_triangles.size(); uint32_t blas_vertex_lists_size = result.blas.vertices.size(); uint32_t blas_material_lists_size = result.blas.materials.size(); for ( size_t i = 0; i < new_blas.size(); i++ ) { result.blas_offsets_map[last_id_offset + i].blasBVHOffset = blas_bvh_nodes_size; result.blas_offsets_map[last_id_offset + i].primitiveOffset = blas_triangle_lists_size; result.blas_offsets_map[last_id_offset + i].vertexOffset = blas_vertex_lists_size; result.blas_offsets_map[last_id_offset + i].materialOffset = blas_material_lists_size; blas_bvh_nodes_size += new_blas[i]->nodes.size(); blas_triangle_lists_size += new_blas[i]->ordered_triangles.size(); blas_vertex_lists_size += new_blas[i]->vertices.size(); blas_material_lists_size += new_blas[i]->materials.size(); } // res.blas.ordered_triangles.reserve( blas_triangle_lists_size ); // res.blas.nodes.reserve( blas_bvh_nodes_size ); // res.blas.vertices.reserve( blas_vertex_lists_size ); for ( size_t i = 0; i < new_blas.size(); i++ ) { result.blas.vertices.insert( result.blas.vertices.end(), new_blas[i]->vertices.begin(), new_blas[i]->vertices.end() ); result.blas.ordered_triangles.insert( result.blas.ordered_triangles.end(), new_blas[i]->ordered_triangles.begin(), new_blas[i]->ordered_triangles.end() ); result.blas.nodes.insert( result.blas.nodes.end(), new_blas[i]->nodes.begin(), new_blas[i]->nodes.end() ); result.blas.materials.insert( result.blas.materials.end(), new_blas[i]->materials.begin(), new_blas[i]->materials.end() ); } auto e = std::chrono::high_resolution_clock::now(); std::stringstream ss; ss << "bvh pack time : " << std::chrono::duration_cast<std::chrono::milliseconds>( e - s ).count() << " ms.\n" << "bvh new node count : " << new_blas.size() << "\nbvh packed blas size: " << ( result.blas.materials.size() * sizeof( MaterialInfo ) + result.blas.ordered_triangles.size() * sizeof( RpTriangle ) + result.blas.vertices.size() * sizeof( RTVertex ) + result.blas.nodes.size() * sizeof( LinearBVHNode ) ) << " bytes.\n"; rh::debug::DebugLogger::Log( ss.str() ); } TLAS_BVH BVHBuilder::BuildTLASBVH( PackedBLAS_BVH &packed_blas, const std::vector<BLAS_BVH> &blas, const std::vector<BLAS_Instance> &instances ) { auto s = std::chrono::high_resolution_clock::now(); std::vector<BVHPrimitive> bvh_prim_list; bvh_prim_list.reserve( instances.size() ); for ( size_t i = 0; i < instances.size(); i++ ) { DirectX::XMMATRIX ws = DirectX::XMLoadFloat4x4( &instances[i].world_transform ); BBox ws_bbox = blas[instances[i].blas_id].nodes[0].bounds.Transform( ws ); DirectX::XMVECTOR centroid = ws_bbox.GetCenter(); bvh_prim_list.push_back( {ws_bbox, centroid, static_cast<uint32_t>( i ), {0, 0, 0}} ); } BBox centerBBox; for ( uint32_t i = 0; i < bvh_prim_list.size(); ++i ) centerBBox = BBox::Merge( bvh_prim_list[i].boundBox, centerBBox ); std::vector<std::pair<uint32_t, uint32_t>> mortonCodes; mortonCodes.reserve( bvh_prim_list.size() ); for ( uint32_t i = 0; i < bvh_prim_list.size(); ++i ) { auto c = bvh_prim_list[i].centroid; float newX = ( DirectX::XMVectorGetX( c ) - centerBBox.min.x ) / ( centerBBox.max.x - centerBBox.min.x ); float newY = ( DirectX::XMVectorGetY( c ) - centerBBox.min.y ) / ( centerBBox.max.y - centerBBox.min.y ); float newZ = ( DirectX::XMVectorGetZ( c ) - centerBBox.min.z ) / ( centerBBox.max.z - centerBBox.min.z ); uint32_t mc = morton3D( newX, newY, newZ ); mortonCodes.push_back( std::make_pair( mc, i ) ); } std::sort( mortonCodes.begin(), mortonCodes.end() ); std::vector<BVHBuildNode *> clusters; uint32_t totalNodes = 0; RecursiveBuildAAC( bvh_prim_list, mortonCodes, 0, bvh_prim_list.size(), totalNodes, MORTON_CODE_START, &clusters ); BVHBuildNode *root = combineCluster( clusters, 1, totalNodes, 2 )[0]; TLAS_BVH tlas; tlas.tlas.reserve( totalNodes ); for ( uint32_t i = 0; i < totalNodes; ++i ) tlas.tlas.push_back( {} ); std::vector<BLAS_Instance> ordered_blas_list; uint32_t offset = 0; uint32_t inst_offset = 0; bvhDfsTlas( tlas.tlas, instances, inst_offset, root, bvh_prim_list, offset ); for ( size_t i = 0; i < tlas.tlas.size(); i++ ) { if ( tlas.tlas[i].lowLevel_a > 0 ) { uint32_t blas_id = instances[tlas.tlas[i].blasBVHOffset].blas_id; DirectX::XMMATRIX ws = DirectX::XMLoadFloat4x4( &instances[tlas.tlas[i].blasBVHOffset].world_transform ); DirectX::XMStoreFloat4x4( &tlas.tlas[i].world_transform, DirectX::XMMatrixInverse( nullptr, ws ) ); tlas.tlas[i].blasBVHOffset = packed_blas.blas_offsets_map[blas_id].blasBVHOffset; tlas.tlas[i].primitiveOffset = packed_blas.blas_offsets_map[blas_id].primitiveOffset; tlas.tlas[i].vertexOffset = packed_blas.blas_offsets_map[blas_id].vertexOffset; tlas.tlas[i].materialOffset = packed_blas.blas_offsets_map[blas_id].materialOffset; } } auto e = std::chrono::high_resolution_clock::now(); std::stringstream ss; ss << "tlas build time : " << std::chrono::duration_cast<std::chrono::milliseconds>( e - s ).count() << " ms.\n" << "tlas node count : " << tlas.tlas.size() << ".\n"; rh::debug::DebugLogger::Log( ss.str() ); return tlas; }
39.858377
101
0.580943
HermanLederer
1e042b146202b0bb3b0b41544c871b7995b30b11
679
hpp
C++
src/sdk/data/LimitedTupleDatabase.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
1
2020-10-11T06:54:04.000Z
2020-10-11T06:54:04.000Z
src/sdk/data/LimitedTupleDatabase.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
null
null
null
src/sdk/data/LimitedTupleDatabase.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
null
null
null
/** * LimitedTupleDatabase.hpp - Limit Tuple Database * * Collection of limited tuples that have been identified */ #ifndef _SDK_LIMITEDTUPLEDATABASE #define _SDK_LIMITEDTUPLEDATABASE #include <memory> #include <vector> #include "sdk/data/LimitedTuple.hpp" namespace sdk { namespace data { class LimitedTupleDatabase { public: LimitedTupleDatabase(); bool Add(LimitedTuple* limited_tuple); void Remove(std::unique_ptr<LimitedTuple> const& tuple); std::vector<std::unique_ptr<LimitedTuple>> const& GetTuples() const; private: std::vector<std::unique_ptr<LimitedTuple>> tuples_; }; } // namespace data } // namespace sdk #endif /* _SDK_LIMITEDTUPLEDATABASE */
24.25
70
0.756996
psettle
1e0553cd57ddb4ac7a88abd158009dae1bea4015
6,495
cc
C++
src/cross_point_detect/cross_points_detector.cc
FlyAlCode/RCLGeolocalization-2.0
2325fd11b23789630b6c12ecd0258c9dec84644a
[ "MIT" ]
4
2021-02-06T07:59:14.000Z
2022-02-22T10:58:27.000Z
src/cross_point_detect/cross_points_detector.cc
FlyAlCode/RCLGeolocalization-2.0
2325fd11b23789630b6c12ecd0258c9dec84644a
[ "MIT" ]
null
null
null
src/cross_point_detect/cross_points_detector.cc
FlyAlCode/RCLGeolocalization-2.0
2325fd11b23789630b6c12ecd0258c9dec84644a
[ "MIT" ]
1
2021-09-15T13:48:00.000Z
2021-09-15T13:48:00.000Z
#include "cross_points_detector.h" // debug #include <iostream> namespace rcll{ CrossPointDetector::CrossPointDetector(int min_cross_point_distance){ min_cross_point_distance_ = min_cross_point_distance; } CrossPointDetector::~CrossPointDetector(){ } int CrossPointDetector::CountDisconnectPoints(const cv::Mat& local_image){ int w = local_image.cols; int h = local_image.rows; std::vector<uchar> around_pixel; for(int i = 0; i<w; i++) around_pixel.push_back(local_image.at<uchar>(0,i)); for(int i=1; i<h; i++) around_pixel.push_back(local_image.at<uchar>(i,w-1)); for(int i=w-2; i>=0; i--) around_pixel.push_back(local_image.at<uchar>(h-1, i)); for(int i=h-2; i>0; i--) around_pixel.push_back(local_image.at<uchar>(i,0)); const int max_step = 1; // max number of points to skip to avoid adjacent point int num = 0; int connected_points_num = 0; int points_num = around_pixel.size(); for(int i=0; i<points_num-1; i++){ if(around_pixel[i]==1){ if(connected_points_num == 0){ ++num; } ++connected_points_num; if(connected_points_num > max_step) connected_points_num = 0; } else{ connected_points_num = 0; } } if(around_pixel[points_num-1]==1){ // deal with the last which is special for adjance with first point if(connected_points_num==0 && around_pixel[0]==0) ++num; } return num; } void CrossPointDetector::CountDisconnectPointsForAllPoints(const cv::Mat &input_img, cv::Mat &output_img){ cv::Mat tmp = cv::Mat::zeros(input_img.size(), input_img.type()); for(int i=1; i<tmp.rows-1; i++){ for(int j=1; j<tmp.cols-1; j++){ if(input_img.at<uchar>(i,j)==1) tmp.at<uchar>(i,j) = CountDisconnectPoints(input_img(cv::Rect(j-1,i-1,3,3))); else tmp.at<uchar>(i,j) = 0; } } tmp.copyTo(output_img); } /* @ 1. When encountering a point with value larger than 2, a neighbor area with radius r(3) * @ is search to find all points with value larger than 2; after than, the max/min in x/y * @ are calculated to find the boundary, and a rect area is formed, which is treated as the keypoint. * @ 2. Then a new search around the area is performed,to find the how many lines connected to the keypoint. */ void CrossPointDetector::MergeCrossPoints(const cv::Mat &src, const cv::Mat &neighbor_img, cv::Mat &output_img, std::vector<cv::Rect> &keypoint_area){ const int max_keypoint_radius = min_cross_point_distance_; // the radius to search to form a keypoint neighbor_img.copyTo(output_img); keypoint_area.clear(); cv::Mat point_visited_map = cv::Mat::zeros(neighbor_img.size(), neighbor_img.type()); for(int i=0; i<neighbor_img.rows; i++){ for(int j=0; j<neighbor_img.cols; j++){ if(point_visited_map.at<uchar>(i,j)==0 && neighbor_img.at<uchar>(i,j)>2){ // unvisited cross points int max_i = i; int min_i = i; int max_j = j; int min_j = j; for(int di=0; di<=max_keypoint_radius; di++){ // points above the current are all visited, thus are not need to search for(int dj=-max_keypoint_radius; dj<=max_keypoint_radius; dj++){ int search_i = i+di; int search_j = j+dj; if(search_i<0 || search_i>neighbor_img.rows-1 || search_j<0 ||search_j >neighbor_img.cols-1) continue; if(neighbor_img.at<uchar>(search_i, search_j)>2){ if(search_i>max_i) max_i = search_i; if(search_j>max_j) max_j = search_j; if(search_j<min_j) min_j = search_j; } } } // record the cross point keypoint_area.push_back(cv::Rect(min_j, min_i, max_j-min_j+1, max_i-min_i+1)); // redefine the type of the point int type = CountDisconnectPoints(src(cv::Rect(min_j-1, min_i-1, max_j-min_j+1+2, max_i-min_i+1+2))); for(int di=min_i; di<=max_i; di++){ for(int dj=min_j; dj<=max_j; dj++){ point_visited_map.at<uchar>(di, dj) = 1; // mark all points belong the keypoint as visited to avoid forming more than once output_img.at<uchar>(di, dj) = type; // refine the type for the point } } } } } } void CrossPointDetector::Run(const cv::Mat &input_img, cv::Mat &cross_points_img, std::vector<cv::Rect> &keypoint_area){ cv::Mat tmp; CountDisconnectPointsForAllPoints(input_img, tmp); MergeCrossPoints(input_img, tmp, cross_points_img, keypoint_area); } /* @Used just for debug */ void CrossPointDetector::ColorNeighborImage(const cv::Mat &neighbor_img, cv::Mat &colored_neighbor_img){ cv::Mat show_img(neighbor_img.size(), CV_8UC3); for(int i=0; i<neighbor_img.rows; i++){ for(int j=0; j<neighbor_img.cols; j++){ switch(neighbor_img.at<uchar>(i,j)){ case 0: show_img.at<cv::Vec3b>(i,j) = cv::Vec3b(0, 0, 0); break; case 1: show_img.at<cv::Vec3b>(i,j) = cv::Vec3b(255, 0, 0); break; case 2: show_img.at<cv::Vec3b>(i,j) = cv::Vec3b(0, 255, 0); break; case 3: show_img.at<cv::Vec3b>(i,j) = cv::Vec3b(0, 0, 255); break; case 4: show_img.at<cv::Vec3b>(i,j) = cv::Vec3b(255,255,0); break; default: show_img.at<cv::Vec3b>(i,j) = cv::Vec3b(255,255,255); } } } show_img.copyTo(colored_neighbor_img); } } // road_match
40.092593
165
0.529484
FlyAlCode
1e08a1480140ffd104e047a84a24dea75d5ebaa7
1,110
cpp
C++
codes/HDU/hdu4462.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4462.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4462.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cstdlib> #include <set> #include <bitset> #include <algorithm> using namespace std; const int maxn = 55; const int maxm = 15; const int inf = 0x3f3f3f3f; bitset<maxn * maxn> s, p[maxm]; int N, K, R[maxm], C[maxm], D[maxm]; int g[maxn][maxn]; void init () { memset(g, 0, sizeof(g)); scanf("%d", &K); for (int i = 0; i < K; i++) { scanf("%d%d", &R[i], &C[i]); g[R[i]][C[i]] = 1; } for (int i = 0; i < K; i++) scanf("%d", &D[i]); for (int i = 0; i < K; i++) { p[i].reset(); for (int x = 1; x <= N; x++) { for (int y = 1; y <= N; y++) { if (g[x][y]) continue; if (abs(x - R[i]) + abs(y - C[i]) <= D[i]) p[i].set( (x-1) * N + y-1); } } } } int solve() { int ans = inf; for (int i = 0; i < (1<<K); i++) { int cnt = 0; s.reset(); for (int j = 0; j < K; j++) { if (i&(1<<j)) { cnt++; s |= p[j]; } } if (s.count() == N * N - K) ans = min(ans, cnt); } return ans == inf ? -1 : ans; } int main () { while (scanf("%d", &N) == 1 && N) { init(); printf("%d\n", solve()); } return 0; }
16.086957
46
0.452252
JeraKrs
1e0b264189a1521697792d610ec30c1f37317b0f
2,369
cpp
C++
HackerEarth/Graph/Just shortest distance problem.cpp
Gmaurya/data-structure-and-algorithms
9f9790140719d24d15ee401e0d11a99dedde4235
[ "MIT" ]
3
2017-12-27T04:58:16.000Z
2018-02-05T14:11:06.000Z
HackerEarth/Graph/Just shortest distance problem.cpp
Gmaurya/data-structure-and-algorithms
9f9790140719d24d15ee401e0d11a99dedde4235
[ "MIT" ]
4
2018-10-04T07:45:07.000Z
2018-11-23T17:36:20.000Z
HackerEarth/Graph/Just shortest distance problem.cpp
Gmaurya/data-structure-and-algorithms
9f9790140719d24d15ee401e0d11a99dedde4235
[ "MIT" ]
8
2018-10-02T20:34:58.000Z
2018-10-07T14:27:53.000Z
/* You are given an empty graph of N vertices and M queries of two types: Given a number X answer what is the shortest distance from the vertex 1 to the vertex X. Given two integers X, Y add the new oriented edge from X to Y. Input The first line contains two integers N and M. The following M lines describe queries in the format mentioned above Output For each query of the first type output one integer on a separate line - answer for the corresponding query. Output -1 if it's impossible to get to the vertex in this query from the vertex 1. Constraints 1 <= N <= 1000 1 <= M <= 500 000 1 <= X, Y <= N Subtasks N <= 500, M <= 5 000 in 50 % of test data SAMPLE INPUT 4 7 1 4 2 1 2 2 2 3 2 3 4 1 4 2 2 4 1 4 SAMPLE OUTPUT -1 3 2 */ /*************************************************************************/ #include<bits/stdc++.h> #define ll long long #define FOR(i,s,n) for(ll i = s; i < (n); i++) #define FORD(i,s,n) for(ll i=(n)-1;i>=s;i--) #define mp(x,y) make_pair(x,y) #define scan(n) scanf("%d",&n) #define print(n) printf("%d",n) #define println(n) printf("%d\n",n) #define printsp(n) printf("%d ",n) using namespace std; vector<ll> adj[1005]; ll height[1005]; ll visited[1005] = {0}; void BFS(ll s); int main() { FOR(i,0,1005) height[i] = 10000; height[1] = 0; ll n,m,x,y,type; cin>>n>>m; FOR(i,0,m) { cin>>type; if(type == 2) { cin>>x>>y; adj[x].push_back(y); if((height[x]+1)<=height[y]) { height[y] = height[x]+1; BFS(y); } } else { cin>>x; if(height[x] == 10000) cout<<-1<<endl; else cout<<height[x]<<endl; } } return 0; } void BFS(ll s) { ll v; queue <ll> q; q.push(s); visited[s] = 1; while(!q.empty()) { v = q.front(); q.pop(); FOR(i,0,adj[v].size()) { if(visited[adj[v][i]]) continue; visited[adj[v][i]] = 1; ll p = height[adj[v][i]]; height[adj[v][i]] = min(height[adj[v][i]],height[v]+1); if(p != height[adj[v][i]]) q.push(adj[v][i]); } } memset(visited,0,sizeof(visited)); }
18.952
191
0.493879
Gmaurya
1f6122f5bc91ab037013e19755482a73b47ef2d8
7,034
hpp
C++
src/Matrices/SPointArray.hpp
ahbarnett/RLCM
63ff05112ae18f189599bbb2eb3b375febb7edf2
[ "Apache-2.0" ]
7
2019-01-16T06:35:10.000Z
2022-03-21T16:55:25.000Z
src/Matrices/SPointArray.hpp
ahbarnett/RLCM
63ff05112ae18f189599bbb2eb3b375febb7edf2
[ "Apache-2.0" ]
1
2022-03-18T21:05:13.000Z
2022-03-18T21:05:13.000Z
src/Matrices/SPointArray.hpp
ahbarnett/RLCM
63ff05112ae18f189599bbb2eb3b375febb7edf2
[ "Apache-2.0" ]
5
2019-01-16T04:17:12.000Z
2022-03-21T22:01:30.000Z
// The SPointArray class implements a set of sparse data points; see // the SPoint class for an individual sparse data point. The point set // is treated as a sparse matrix, which is represented by three // numbers and three arrays. Let the matrix have a size N*d with nnz // nonzero elements, where N is the number of points and d is the // dimension of the points. The three arrays are start, idx, and X, // which means respectively, the starting location of a new point, the // index of the nonzero elements, and the values of the nonzero // elements. Such a storage format is consistent with the compressed // sparse row (CSR) matrix format. For more details, see the class // definition below. // // Note that the sparse matrix is effectively in row-major order. This // is different from the storage of a dense point array (see // DPointArray). // // The implementation of some methods in this class is parallelized // whereas others not. The general rule of thumb is that if the // computation is w.r.t. one point (e.g., GetPoint), then it is not // parallelized, because such computation can possibly be iterated // through all points (where parallelism better takes place). If the // computation is w.r.t. the whole point array (e.g., // RandomBipartition), then it is parallelized. The computation // w.r.t. a subset of points (e.g., GetSubset) lies between the above // two cases; for the moment this computation is parallelized. #ifndef _SPOINT_ARRAY_ #define _SPOINT_ARRAY_ #include "SPoint.hpp" #include "DPointArray.hpp" class SPointArray { public: SPointArray(); SPointArray(INTEGER N_, INTEGER d_, INTEGER nnz_); SPointArray(const SPointArray& G); SPointArray& operator= (const SPointArray& G); SPointArray& operator= (const DPointArray& G); // Convert from dense to sparse ~SPointArray(); void Init(void); void Init(INTEGER N_, INTEGER d_, INTEGER nnz_); // This is NOT a zero matrix void ReleaseAllMemory(void); void DeepCopy(const SPointArray &G); //-------------------- Utilities -------------------- // // X is the self data matrix. // Get dimension INTEGER GetD(void) const; // Get number of points INTEGER GetN(void) const; // Get nnz INTEGER GetNNZ(void) const; // Get the i-th point x void GetPoint(INTEGER i, SPoint &x) const; void GetPoint(INTEGER i, DPoint &x) const; // Get a consecutive chunk Y. Note that SPointArray is in row-major // order whereas DPointArray is in column-major order. void GetSubset(INTEGER istart, INTEGER n, SPointArray &Y) const; void GetSubset(INTEGER istart, INTEGER n, DPointArray &Y) const; // Get a subset Y. Note that SPointArray is in row-major order // whereas DPointArray is in column-major order. void GetSubset(INTEGER *iidx, INTEGER n, SPointArray &Y) const; void GetSubset(INTEGER *iidx, INTEGER n, DPointArray &Y) const; // Get the pointer to start INTEGER* GetPointerStart(void) const; // Get the pointer to idx INTEGER* GetPointerIdx(void) const; // Get the pointer to X double* GetPointerX(void) const; // Get the data matrix (stored in dense format) void AsDMatrix(DMatrix &A) const; // Print the point set void PrintPointArray(const char *name) const; //-------------------- Computations -------------------- // // X is the self data matrix. // Center of the point set void Center(DPoint &c) const; // Root mean squared distances between the center and the points double StdvDist(void) const; // max_i x_i'*x_i double MaxPointNorm2(void) const; // y = mode(X) * b (size of X is N*d) void MatVec(const DVector &b, DVector &y, MatrixMode ModeX) const; void MatVec(const DPoint &b, DVector &y, MatrixMode ModeX) const; // Y = mode(X) * mode(B) (size of X is N*d) void MatMat(const DMatrix &B, DMatrix &Y, MatrixMode ModeX, MatrixMode ModeB) const; void MatMat(const SPointArray &B, DMatrix &Y, MatrixMode ModeX, MatrixMode ModeB) const; // Bipartition and permute the points by using a hyperplane with // random orientation. // // This routine randomly partitions the data points (indexed from // istart to istart+n-1) into two equal halves, if n >= 2*N0. Let // the dividing hyperplane have a normal direction 'normal'. All the // points are projected along this direction and a median (named // 'offset') of the projected values is computed. The hyperplane // equation is thus h(x) = normal'*x - offset = 0. In the // nondegenerate case, there are m1 = floor(n/2) points x satisfying // h(x) < 0 and the rest satisfying h(x) > 0. The routine permutes // the points so that those indexed from istart to istart+m1-1 // correspond to h(x) < 0 and the rest corresponds to h(x) > 0. The // return value of the routine is m1. Additionally, if the // permutation array perm is not NULL and is filled with ordering // information, then on exit it records the new order of the points. INTEGER RandomBipartition(INTEGER istart, INTEGER n, INTEGER N0, INTEGER *perm, DPoint &normal, double &offset); // Similar to RandomBipartition, except that the orientation of the // hyperplane is the principal direction of the points. INTEGER PCABipartition(INTEGER istart, INTEGER n, INTEGER N0, INTEGER *perm, DPoint &normal, double &offset); // Partitioning the points along the longest dimension of the // bounding box. // // This functionality is not implemented, because for sparse points, // such a partitioning may be highly imbalanced due to the excessive // number of zeros. One should not use this a partitioning // method. These functions are declared only as a placeholder. void ComputeBBox(double **bbox, INTEGER &dim); INTEGER BBoxBipartition(INTEGER start, INTEGER n, INTEGER N0, INTEGER *perm, DPoint &normal, double &offset, const double *bbox, INTEGER &which_dim); protected: private: INTEGER N; // Number of points INTEGER d; // Dimension INTEGER nnz; // Total number of nonzeros INTEGER *start; // INTEGER *idx; // double *X; // // The three arrays 'start', 'idx', and 'X', altogether, are used to // represent points in a manner consistent with the CSR format of a // sparse matrix. // // 'start' has a length N+1, where start[i] means the location of // idx (and of X) where the i-th point begins, for i = 0:N-1. For // convenience, start[N] = nnz. // // 'idx' has a length nnz, where the segment idx[start[i]] to // idx[start[i+1]-1] stores the coordinates of the nonzero elements // of the i-th point. All 'idx' entries must be < d. // // 'X' has a length nnz, where the segment X[start[i]] to // X[start[i+1]-1] stores the values of the nonzero elements of the // i-th point. // Called by RandomBipartition() and PCABipartition() INTEGER Bipartition(INTEGER istart, INTEGER n, INTEGER *perm, DPoint &normal, double &offset); }; #endif
38.437158
80
0.688797
ahbarnett
1f63afd604f068b46005bd634af66015ac2795ba
3,904
cpp
C++
cli/src/sync_dat.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
cli/src/sync_dat.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
cli/src/sync_dat.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
#include <exodus/program.h> programinit() var last_sync_date; var last_sync_time; function main() { var datpath = COMMAND.a(2); if (not datpath) { //datpath = osgetenv("EXO_HOME") ^ "/dat"; if (not datpath.osgetenv("EXO_HOME")) datpath = osgetenv("HOME"); datpath ^= "/dat"; } var force = index(OPTIONS, "F"); var verbose = index(OPTIONS, "V"); // Skip if no definitions file var definitions; if (not open("DEFINITIONS",definitions)) { //abort("Error: sync_dat - No DEFINITIONS file"); definitions = ""; } // Get the date and time of last sync var last_sync; var definitions_key = "LAST_SYNC_DATE_TIME*DAT"; if (not definitions or not read(last_sync,definitions, definitions_key)) last_sync = ""; last_sync_date = last_sync.a(1); last_sync_time = last_sync.a(2); // Skip if nothing new var datinfo = osdir(datpath); var dirtext = "sync_dat: " ^ datpath ^ " " ^ datinfo.a(2).oconv("D-Y") ^ " " ^ datinfo.a(3).oconv("MTS"); if (not force and not is_newer(datinfo)) { if (verbose) printl(dirtext, "No change."); return 0; } printl(dirtext,"Scanning ..."); begintrans(); // Process each subdir in turn. each one represents a db file. var dirnames = oslistd(datpath ^ "/*"); for (var dirname : dirnames) { var dirpath = datpath ^ "/" ^ dirname ^ "/"; // // Skip dirs which are not newer i.e. have no newer records // if (not force) { // var dirinfo = osdir(dirpath); // if (not is_newer(dirinfo)) { // if (verbose) // printl("Nothing new in", dirpath, dirinfo.a(2).oconv("D-Y"), dirinfo.a(3).oconv("MTS")); // continue; // } // } // Open or create the target db file var dbfile; var dbfilename = dirname; if (not open(dbfilename, dbfile)) { createfile(dbfilename); if (not open(dbfilename, dbfile)) { errputl("Error: sync_dat cannot create " ^ dbfilename); continue; } } // Process each file/record in the subdir var osfilenames = oslistf(dirpath ^ "*"); for (var osfilename : osfilenames) { ID = osfilename; if (not ID) continue; if (ID.starts(".") or ID.ends(".swp")) continue; // Skip files/records which are not newer var filepath = dirpath ^ ID; if (not force and not is_newer(osfile(filepath))) { if (verbose) printl("Not newer", dbfilename, ID); continue; } if (not osread(RECORD from filepath)) { errputl("Error: sync_dat cannot read " ^ ID ^ " from " ^ filepath); continue; } gosub unescape_text(RECORD); //get any existing record var oldrecord; if (not read(oldrecord from dbfile, ID)) { oldrecord = ""; } if (RECORD eq oldrecord) { if (verbose) printl("Not changed", dbfilename, ID); } else { // Write the RECORD write(RECORD on dbfile, ID); printl("sync_dat:", dbfilename, ID, "WRITTEN"); } // Create pgsql using dict2sql // DONT SKIP SINCE PGSQL FUNCTIONS MUST BE IN EVERY DATABASE if (dbfilename.starts("dict.") and RECORD.index("/" "*pgsql")) { var cmd = "dict2sql " ^ dbfilename ^ " " ^ ID; //cmd ^= " {V}"; if (not osshell(cmd)) errputl("Error: sync_dat: In dict2sql for " ^ ID ^ " in " ^ dbfilename); } } } // Record the current sync date and time if (definitions) write(date() ^ FM ^ time() on definitions, definitions_key); committrans(); return 0; } function is_newer(in fsinfo) { int fsinfo_date = fsinfo.a(2); if (fsinfo_date > last_sync_date) return true; if (fsinfo_date < last_sync_date) return false; return fsinfo.a(3) > last_sync_time; } //WARNING: KEEP AS REVERSE OF escape_text() IN COPYFILE //identical code in copyfile and sync_dat subroutine unescape_text(io record) { //replace new lines with FM record.converter("\n", FM); //unescape new lines record.swapper("\\n", "\n"); //unescape backslashes record.swapper("\\\\", "\\"); return; } programexit()
23.238095
106
0.633453
BOBBYWY
1f65131beb18d615a01ac1fa1c699cb7042bee92
533
hpp
C++
sgreader/exception/RuntimeException.hpp
Vinorcola/citybuilding-tools
df91d8106987af45f1d11a34470acadb3873a91a
[ "MIT" ]
null
null
null
sgreader/exception/RuntimeException.hpp
Vinorcola/citybuilding-tools
df91d8106987af45f1d11a34470acadb3873a91a
[ "MIT" ]
null
null
null
sgreader/exception/RuntimeException.hpp
Vinorcola/citybuilding-tools
df91d8106987af45f1d11a34470acadb3873a91a
[ "MIT" ]
null
null
null
#ifndef RUNTIMEEXCEPTION_HPP #define RUNTIMEEXCEPTION_HPP #include <QtCore/QException> class RuntimeException : public QException { private: const QString message; const std::string standardFormatMessage; public: RuntimeException(const QString& message); const QString& getMessage() const; virtual void raise() const override; virtual RuntimeException* clone() const override; virtual const char* what() const noexcept override; }; #endif // RUNTIMEEXCEPTION_HPP
23.173913
59
0.707317
Vinorcola
1f66dc48db47223011f4cdfb964f8fd0c97c0073
32,836
cpp
C++
SimTKcommon/tests/TestScalar.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
1,916
2015-01-01T09:35:21.000Z
2022-03-30T11:38:43.000Z
SimTKcommon/tests/TestScalar.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
389
2015-01-01T01:13:51.000Z
2022-03-16T15:30:58.000Z
SimTKcommon/tests/TestScalar.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
486
2015-01-02T10:25:49.000Z
2022-03-16T15:31:40.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2008-12 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: * * * * 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 "SimTKcommon.h" #include "SimTKcommon/Testing.h" #include <iostream> using std::cout; using std::endl; using namespace SimTK; void testIsNaN() { const float fltRegular = -12.34f; const double dblRegular = -12.34; const float fltNaN = NTraits<float>::getNaN(); const double dblNaN = NTraits<double>::getNaN(); const float nfltNaN = -fltNaN; const double ndblNaN = -dblNaN; SimTK_TEST(isNaN(fltNaN) && isNaN(dblNaN)); SimTK_TEST(isNaN(nfltNaN) && isNaN(ndblNaN)); SimTK_TEST(!isNaN(fltRegular) && !isNaN(dblRegular)); std::complex<float> cflt(fltRegular, -2*fltRegular); std::complex<double> cdbl(dblRegular, -2*dblRegular); conjugate<float> cjflt(fltRegular, -2*fltRegular); conjugate<double> cjdbl(dblRegular, -2*dblRegular); SimTK_TEST(!isNaN(cflt) && !isNaN(cdbl)); SimTK_TEST(!isNaN(cjflt) && !isNaN(cjdbl)); // Reference the same memory as a negator of its contents. const negator<float>& nflt = reinterpret_cast<const negator<float>&>(fltRegular); const negator<double>& ndbl = reinterpret_cast<const negator<double>&>(dblRegular); negator<std::complex<float> >& ncflt = reinterpret_cast<negator<std::complex<float> >&> (cflt); negator<std::complex<double> >& ncdbl = reinterpret_cast<negator<std::complex<double> >&>(cdbl); negator<conjugate<float> >& ncjflt = reinterpret_cast<negator<conjugate<float> >&> (cjflt); negator<conjugate<double> >& ncjdbl = reinterpret_cast<negator<conjugate<double> >&> (cjdbl); // Test that negators are working properly. SimTK_TEST_EQ(nflt, -fltRegular); SimTK_TEST_EQ(ndbl, -dblRegular); SimTK_TEST_EQ(ncflt, -cflt); SimTK_TEST_EQ(-ncflt, cflt); SimTK_TEST_EQ(ncjflt, -cjflt); SimTK_TEST_EQ(-ncjflt, cjflt); SimTK_TEST(!isNaN(nflt) && !isNaN(ndbl)); SimTK_TEST(!isNaN(ncflt) && !isNaN(ncdbl)); SimTK_TEST(!isNaN(ncjflt) && !isNaN(ncjdbl)); // Should be NaN if either or both parts are NaN. cflt = std::complex<float>(cflt.real(), fltNaN); cdbl = std::complex<double>(cdbl.real(), dblNaN); cjflt = conjugate<float>(cjflt.real(), fltNaN); cjdbl = conjugate<double>(cjdbl.real(), dblNaN); // Imaginary only is NaN. SimTK_TEST(isNaN(cflt) && isNaN(cdbl)); SimTK_TEST(isNaN(cjflt) && isNaN(cjdbl)); SimTK_TEST(isNaN(ncflt) && isNaN(ncdbl)); SimTK_TEST(isNaN(ncjflt) && isNaN(ncjdbl)); cflt = std::complex<float>(fltNaN, cflt.imag()); cdbl = std::complex<double>(dblNaN, cdbl.imag()); cjflt = conjugate<float>(fltNaN, cjflt.imag()); cjdbl = conjugate<double>(dblNaN, cjdbl.imag()); // Both parts are NaN. SimTK_TEST(isNaN(cflt) && isNaN(cdbl)); SimTK_TEST(isNaN(cjflt) && isNaN(cjdbl)); SimTK_TEST(isNaN(ncflt) && isNaN(ncdbl)); SimTK_TEST(isNaN(ncjflt) && isNaN(ncjdbl)); // Restore imaginary part to normal. cflt = std::complex<float>(cflt.real(), fltRegular); cdbl = std::complex<double>(cdbl.real(), dblRegular); cjflt = conjugate<float>(cjflt.real(), fltRegular); cjdbl = conjugate<double>(cjdbl.real(), dblRegular); // Real part only is NaN; SimTK_TEST(isNaN(cflt) && isNaN(cdbl)); SimTK_TEST(isNaN(cjflt) && isNaN(cjdbl)); SimTK_TEST(isNaN(ncflt) && isNaN(ncdbl)); SimTK_TEST(isNaN(ncjflt) && isNaN(ncjdbl)); } void testIsInf() { const float fltRegular = -12.34f; const double dblRegular = -12.34; const float fltInf = NTraits<float>::getInfinity(); const double dblInf = NTraits<double>::getInfinity(); const float mfltInf = -fltInf; const double mdblInf = -dblInf; const negator<float>& nfltInf = reinterpret_cast<const negator<float>&>(fltInf); const negator<double>& ndblInf = reinterpret_cast<const negator<double>&>(dblInf); SimTK_TEST(nfltInf == -fltInf); SimTK_TEST(ndblInf == -dblInf); SimTK_TEST(isInf(fltInf) && isInf(dblInf)); SimTK_TEST(isInf(mfltInf) && isInf(mdblInf)); SimTK_TEST(isInf(nfltInf) && isInf(ndblInf)); SimTK_TEST(!isInf(fltRegular) && !isInf(dblRegular)); std::complex<float> cflt(fltRegular, -2*fltRegular); std::complex<double> cdbl(dblRegular, -2*dblRegular); conjugate<float> cjflt(fltRegular, -2*fltRegular); conjugate<double> cjdbl(dblRegular, -2*dblRegular); SimTK_TEST(!isInf(cflt) && !isInf(cdbl)); SimTK_TEST(!isInf(cjflt) && !isInf(cjdbl)); // Reference the same memory as a negator of its contents. const negator<float>& nflt = reinterpret_cast<const negator<float>&>(fltRegular); const negator<double>& ndbl = reinterpret_cast<const negator<double>&>(dblRegular); negator<std::complex<float> >& ncflt = reinterpret_cast<negator<std::complex<float> >&> (cflt); negator<std::complex<double> >& ncdbl = reinterpret_cast<negator<std::complex<double> >&>(cdbl); negator<conjugate<float> >& ncjflt = reinterpret_cast<negator<conjugate<float> >&> (cjflt); negator<conjugate<double> >& ncjdbl = reinterpret_cast<negator<conjugate<double> >&> (cjdbl); // Test that negators are working properly. SimTK_TEST_EQ(nflt, -fltRegular); SimTK_TEST_EQ(ndbl, -dblRegular); SimTK_TEST_EQ(ncflt, -cflt); SimTK_TEST_EQ(-ncflt, cflt); SimTK_TEST_EQ(ncjflt, -cjflt); SimTK_TEST_EQ(-ncjflt, cjflt); SimTK_TEST(!isInf(nflt) && !isInf(ndbl)); SimTK_TEST(!isInf(ncflt) && !isInf(ncdbl)); SimTK_TEST(!isInf(ncjflt) && !isInf(ncjdbl)); // Should be Inf if either or both parts are Inf, as long as neither // part is NaN. cflt = std::complex<float>(cflt.real(), fltInf); cdbl = std::complex<double>(cdbl.real(), dblInf); cjflt = conjugate<float>(cjflt.real(), fltInf); cjdbl = conjugate<double>(cjdbl.real(), dblInf); // Imaginary only is Inf. SimTK_TEST(isInf(cflt) && isInf(cdbl)); SimTK_TEST(isInf(cjflt) && isInf(cjdbl)); SimTK_TEST(isInf(ncflt) && isInf(ncdbl)); SimTK_TEST(isInf(ncjflt) && isInf(ncjdbl)); cflt = std::complex<float>(fltInf, cflt.imag()); cdbl = std::complex<double>(dblInf, cdbl.imag()); cjflt = conjugate<float>(fltInf, cjflt.imag()); cjdbl = conjugate<double>(dblInf, cjdbl.imag()); // Both parts are Inf. SimTK_TEST(isInf(cflt) && isInf(cdbl)); SimTK_TEST(isInf(cjflt) && isInf(cjdbl)); SimTK_TEST(isInf(ncflt) && isInf(ncdbl)); SimTK_TEST(isInf(ncjflt) && isInf(ncjdbl)); // Restore imaginary part to normal. cflt = std::complex<float>(cflt.real(), fltRegular); cdbl = std::complex<double>(cdbl.real(), dblRegular); cjflt = conjugate<float>(cjflt.real(), fltRegular); cjdbl = conjugate<double>(cjdbl.real(), dblRegular); // Real part only is Inf; SimTK_TEST(isInf(cflt) && isInf(cdbl)); SimTK_TEST(isInf(cjflt) && isInf(cjdbl)); SimTK_TEST(isInf(ncflt) && isInf(ncdbl)); SimTK_TEST(isInf(ncjflt) && isInf(ncjdbl)); // Set real part to minus infinity. cflt = std::complex<float>(mfltInf, cflt.imag()); cdbl = std::complex<double>(mdblInf, cdbl.imag()); cjflt = conjugate<float>(mfltInf, cjflt.imag()); cjdbl = conjugate<double>(mdblInf, cjdbl.imag()); SimTK_TEST(isInf(cflt) && isInf(cdbl)); SimTK_TEST(isInf(cjflt) && isInf(cjdbl)); SimTK_TEST(isInf(ncflt) && isInf(ncdbl)); SimTK_TEST(isInf(ncjflt) && isInf(ncjdbl)); // Set real part to NaN. const float fltNaN = NTraits<float>::getNaN(); const double dblNaN = NTraits<double>::getNaN(); cflt = std::complex<float>(fltNaN, cflt.imag()); cdbl = std::complex<double>(dblNaN, cdbl.imag()); cjflt = conjugate<float>(fltNaN, cjflt.imag()); cjdbl = conjugate<double>(dblNaN, cjdbl.imag()); SimTK_TEST(!isInf(cflt) && !isInf(cdbl)); SimTK_TEST(!isInf(cjflt) && !isInf(cjdbl)); SimTK_TEST(!isInf(ncflt) && !isInf(ncdbl)); SimTK_TEST(!isInf(ncjflt) && !isInf(ncjdbl)); } void testIsFinite() { const float fltRegular = -12.34f; const double dblRegular = -12.34; const float fltNaN = NTraits<float>::getNaN(); const double dblNaN = NTraits<double>::getNaN(); const float nfltNaN = -fltNaN; const double ndblNaN = -dblNaN; const float fltInf = NTraits<float>::getInfinity(); const double dblInf = NTraits<double>::getInfinity(); const float mfltInf = -fltInf; const double mdblInf = -dblInf; SimTK_TEST(isFinite(fltRegular) && isFinite(dblRegular)); SimTK_TEST(!isFinite(fltNaN) && !isFinite(dblNaN)); SimTK_TEST(!isFinite(fltInf) && !isFinite(dblInf)); SimTK_TEST(!isFinite(mfltInf) && !isFinite(mdblInf)); std::complex<float> cflt(fltRegular, -2*fltRegular); std::complex<double> cdbl(dblRegular, -2*dblRegular); conjugate<float> cjflt(fltRegular, -2*fltRegular); conjugate<double> cjdbl(dblRegular, -2*dblRegular); SimTK_TEST(isFinite(cflt) && isFinite(cdbl)); SimTK_TEST(isFinite(cjflt) && isFinite(cjdbl)); // Reference the same memory as a negator of its contents. const negator<float>& nflt = reinterpret_cast<const negator<float>&>(fltRegular); const negator<double>& ndbl = reinterpret_cast<const negator<double>&>(dblRegular); negator<std::complex<float> >& ncflt = reinterpret_cast<negator<std::complex<float> >&> (cflt); negator<std::complex<double> >& ncdbl = reinterpret_cast<negator<std::complex<double> >&>(cdbl); negator<conjugate<float> >& ncjflt = reinterpret_cast<negator<conjugate<float> >&> (cjflt); negator<conjugate<double> >& ncjdbl = reinterpret_cast<negator<conjugate<double> >&> (cjdbl); // Test that negators are working properly. SimTK_TEST_EQ(nflt, -fltRegular); SimTK_TEST_EQ(ndbl, -dblRegular); SimTK_TEST_EQ(ncflt, -cflt); SimTK_TEST_EQ(-ncflt, cflt); SimTK_TEST_EQ(ncjflt, -cjflt); SimTK_TEST_EQ(-ncjflt, cjflt); SimTK_TEST(isFinite(nflt) && isFinite(ndbl)); SimTK_TEST(isFinite(ncflt) && isFinite(ncdbl)); SimTK_TEST(isFinite(ncjflt) && isFinite(ncjdbl)); // Should be finite only if both parts are finite. cflt = std::complex<float>(cflt.real(), fltInf); cdbl = std::complex<double>(cdbl.real(), mdblInf); cjflt = conjugate<float>(cjflt.real(), fltNaN); cjdbl = conjugate<double>(cjdbl.real(), dblInf); // Imaginary only is NaN. SimTK_TEST(!isFinite(cflt) && !isFinite(cdbl)); SimTK_TEST(!isFinite(cjflt) && !isFinite(cjdbl)); SimTK_TEST(!isFinite(ncflt) && !isFinite(ncdbl)); SimTK_TEST(!isFinite(ncjflt) && !isFinite(ncjdbl)); cflt = std::complex<float> (fltInf, cflt.imag()); cdbl = std::complex<double>(mdblInf, cdbl.imag()); cjflt = conjugate<float> (fltNaN, cjflt.imag()); cjdbl = conjugate<double> (dblInf, cjdbl.imag()); // Both parts are non-finite. SimTK_TEST(!isFinite(cflt) && !isFinite(cdbl)); SimTK_TEST(!isFinite(cjflt) && !isFinite(cjdbl)); SimTK_TEST(!isFinite(ncflt) && !isFinite(ncdbl)); SimTK_TEST(!isFinite(ncjflt) && !isFinite(ncjdbl)); // Restore imaginary part to normal. cflt = std::complex<float>(cflt.real(), fltRegular); cdbl = std::complex<double>(cdbl.real(), dblRegular); cjflt = conjugate<float>(cjflt.real(), fltRegular); cjdbl = conjugate<double>(cjdbl.real(), dblRegular); // Real part only is non-finite; SimTK_TEST(!isFinite(cflt) && !isFinite(cdbl)); SimTK_TEST(!isFinite(cjflt) && !isFinite(cjdbl)); SimTK_TEST(!isFinite(ncflt) && !isFinite(ncdbl)); SimTK_TEST(!isFinite(ncjflt) && !isFinite(ncjdbl)); } void testSignBit() { const unsigned char ucm=0xff, ucz=0, ucp=27; const unsigned short usm=0xffff, usz=0, usp=2342; const unsigned int uim=0xffffffff, uiz=0, uip=2342344; const unsigned long ulm=(unsigned long)-23423L, ulz=0, ulp=234234UL; const unsigned long long ullm=(unsigned long long)-234234234LL, ullz=0, ullp=234234234ULL; SimTK_TEST(!(signBit(ucm)||signBit(ucz)||signBit(ucp))); SimTK_TEST(!(signBit(usm)||signBit(usz)||signBit(usp))); SimTK_TEST(!(signBit(uim)||signBit(uiz)||signBit(uip))); SimTK_TEST(!(signBit(ulm)||signBit(ulz)||signBit(ulp))); SimTK_TEST(!(signBit(ullm)||signBit(ullz)||signBit(ullp))); // Note that signBit(char) doesn't exist. const signed char cm=-23, cz=0, cp=99; const short sm=-1234, sz=0, sp=23423; const int im=-2342343, iz=0, ip=29472383; const long lm=-43488, lz=0, lp=3454545; const long long llm=-2342342343433LL, llz=0, llp=874578478478574LL; SimTK_TEST(signBit(cm) && !(signBit(cz)||signBit(cp))); SimTK_TEST(signBit(sm) && !(signBit(sz)||signBit(sp))); SimTK_TEST(signBit(im) && !(signBit(iz)||signBit(ip))); SimTK_TEST(signBit(lm) && !(signBit(lz)||signBit(lp))); SimTK_TEST(signBit(llm) && !(signBit(llz)||signBit(llp))); const float fm=-12398.34f, fz=0, fp=4354.331f; const double dm=-234234.454, dz=0, dp=345345.2342; float mfz=-fz; double mdz=-dz;// -0 for some compilers SimTK_TEST(signBit(fm) && !(signBit(fz)||signBit(fp))); SimTK_TEST(signBit(dm) && !(signBit(dz)||signBit(dp))); // Can't be sure whether the compiler will actually have produced // a minus zero here. // SimTK_TEST(signBit(mfz) && signBit(mdz)); // Note: signBit of negated float or double should be the // *same* as the underlying float or double; it is the // interpretation of that bit that is supposed to be // different. const negator<float>& nfm=reinterpret_cast<const negator<float>&>(fm); const negator<float>& nfz=reinterpret_cast<const negator<float>&>(fz); const negator<float>& nfp=reinterpret_cast<const negator<float>&>(fp); const negator<float>& nmfz=reinterpret_cast<const negator<float>&>(mfz); const negator<double>& ndm=reinterpret_cast<const negator<double>&>(dm); const negator<double>& ndz=reinterpret_cast<const negator<double>&>(dz); const negator<double>& ndp=reinterpret_cast<const negator<double>&>(dp); const negator<double>& nmdz=reinterpret_cast<const negator<double>&>(mdz); SimTK_TEST(signBit(nfm) && !(signBit(nfz)||signBit(nfp))); SimTK_TEST(signBit(ndm) && !(signBit(ndz)||signBit(ndp))); SimTK_TEST(signBit(nmfz)==signBit(mfz) && signBit(nmdz)==signBit(mdz)); const float fltInf = NTraits<float>::getInfinity(); const double dblInf = NTraits<double>::getInfinity(); const float mfltInf = -fltInf; const double mdblInf = -dblInf; SimTK_TEST(!signBit(fltInf) && !signBit(dblInf)); SimTK_TEST(signBit(mfltInf) && signBit(mdblInf)); } void testSign() { const unsigned char ucm=0xff, ucz=0, ucp=27; const unsigned short usm=0xffff, usz=0, usp=2342; const unsigned int uim=0xffffffff, uiz=0, uip=2342344; const unsigned long ulm=(unsigned long)-23423L, ulz=0, ulp=234234UL; const unsigned long long ullm=(unsigned long long)-234234234LL, ullz=0, ullp=234234234ULL; SimTK_TEST(sign(ucm)==1 && sign(ucz)==0 && sign(ucp)==1); SimTK_TEST(sign(usm)==1 && sign(usz)==0 && sign(usp)==1); SimTK_TEST(sign(uim)==1 && sign(uiz)==0 && sign(uip)==1); SimTK_TEST(sign(ulm)==1 && sign(ulz)==0 && sign(ulp)==1); SimTK_TEST(sign(ullm)==1 && sign(ullz)==0 && sign(ullp)==1); // Note that sign(char) doesn't exist. const signed char cm=-23, cz=0, cp=99; const short sm=-1234, sz=0, sp=23423; const int im=-2342343, iz=0, ip=29472383; const long lm=-43488, lz=0, lp=3454545; const long long llm=-2342342343433LL, llz=0, llp=874578478478574LL; SimTK_TEST(sign(cm)==-1 && sign(cz)==0 && sign(cp)==1); SimTK_TEST(sign(sm)==-1 && sign(sz)==0 && sign(sp)==1); SimTK_TEST(sign(im)==-1 && sign(iz)==0 && sign(ip)==1); SimTK_TEST(sign(lm)==-1 && sign(lz)==0 && sign(lp)==1); SimTK_TEST(sign(llm)==-1 && sign(llz)==0 && sign(llp)==1); const float fm=-12398.34f, fz=0, fp=4354.331f; const double dm=-234234.454, dz=0, dp=345345.2342; float mfz=-fz; double mdz=-dz;// -0 SimTK_TEST(sign(fm)==-1 && sign(fz)==0 && sign(fp)==1); SimTK_TEST(sign(dm)==-1 && sign(dz)==0 && sign(dp)==1); SimTK_TEST(sign(mfz)==0 && sign(mdz)==0); // doesn't matter if it's -0 // Note: sign of negated float or double should be the // *opposite* as the underlying float or double. const negator<float>& nfm=reinterpret_cast<const negator<float>&>(fm); const negator<float>& nfz=reinterpret_cast<const negator<float>&>(fz); const negator<float>& nfp=reinterpret_cast<const negator<float>&>(fp); const negator<float>& nmfz=reinterpret_cast<const negator<float>&>(mfz); const negator<double>& ndm=reinterpret_cast<const negator<double>&>(dm); const negator<double>& ndz=reinterpret_cast<const negator<double>&>(dz); const negator<double>& ndp=reinterpret_cast<const negator<double>&>(dp); const negator<double>& nmdz=reinterpret_cast<const negator<double>&>(mdz); SimTK_TEST(sign(nfm)==1 && sign(nfz)==0 && sign(nfp)==-1); SimTK_TEST(sign(ndm)==1 && sign(ndz)==0 && sign(ndp)==-1); SimTK_TEST(sign(nmfz)==0 && sign(nmdz)==0); // doesn't matter if it's -0 const float fltInf = NTraits<float>::getInfinity(); const double dblInf = NTraits<double>::getInfinity(); const float mfltInf = -fltInf; const double mdblInf = -dblInf; const negator<float>& nfltInf = reinterpret_cast<const negator<float>&>(fltInf); const negator<double>& ndblInf = reinterpret_cast<const negator<double>&>(dblInf); SimTK_TEST(sign(fltInf)==1 && sign(dblInf)==1); SimTK_TEST(sign(mfltInf)==-1 && sign(mdblInf)==-1); SimTK_TEST(sign(nfltInf)==-1 && sign(ndblInf)==-1); } void testSquareAndCube() { const float fval = -23.33f; const double dval = -234443.441; const negator<float>& nfval = reinterpret_cast<const negator<float>&>(fval); const negator<double>& ndval = reinterpret_cast<const negator<double>&>(dval); // Basic test. SimTK_TEST_EQ(square(fval), fval*fval); SimTK_TEST_EQ(square(dval), dval*dval); SimTK_TEST_EQ(cube(fval), fval*fval*fval); SimTK_TEST_EQ(cube(dval), dval*dval*dval); // Test scalar negators. SimTK_TEST_EQ(square(nfval), nfval*nfval); SimTK_TEST_EQ(square(nfval), fval*fval); SimTK_TEST_EQ(square(ndval), ndval*ndval); SimTK_TEST_EQ(square(ndval), dval*dval); SimTK_TEST_EQ(cube(nfval), nfval*nfval*nfval); SimTK_TEST_EQ(cube(nfval), -fval*fval*fval); SimTK_TEST_EQ(cube(ndval), ndval*ndval*ndval); SimTK_TEST_EQ(cube(ndval), -dval*dval*dval); // Create complex and conjugate values. std::complex<float> fc(-234.343f, 45345e7f); std::complex<double> dc(-234.343, 45345e7); conjugate<float> fcj(-19.1e3f, -454.234f); conjugate<double> dcj(-19.1e3, -454.234); // Manual conjugates std::complex<float> fcmj(fcj.real(), fcj.imag()); std::complex<double> dcmj(dcj.real(), dcj.imag()); SimTK_TEST(fcj == fcmj); // sign change only; should be exact SimTK_TEST(dcj == dcmj); SimTK_TEST_EQ(fcj*fcj, fcmj*fcmj); SimTK_TEST_EQ(dcj*dcj, dcmj*dcmj); SimTK_TEST_EQ(fcj*fcj*fcj, fcmj*fcmj*fcmj); SimTK_TEST_EQ(dcj*dcj*dcj, dcmj*dcmj*dcmj); // Negators of complex an conjugate. negator<std::complex<float> >& nfc = reinterpret_cast<negator<std::complex<float> >&> (fc); negator<std::complex<double> >& ndc = reinterpret_cast<negator<std::complex<double> >&>(dc); negator<conjugate<float> >& nfcj = reinterpret_cast<negator<conjugate<float> >&> (fcj); negator<conjugate<double> >& ndcj = reinterpret_cast<negator<conjugate<double> >&> (dcj); // Change of sign should be exact. SimTK_TEST(nfc == -fc); SimTK_TEST(ndc == -dc); SimTK_TEST(nfcj == -fcj); SimTK_TEST(ndcj == -dcj); // Basic complex and conjugate tests. SimTK_TEST_EQ(square(fc), fc*fc); SimTK_TEST_EQ(cube(fc), fc*fc*fc); SimTK_TEST_EQ(square(dc), dc*dc); SimTK_TEST_EQ(cube(dc), dc*dc*dc); SimTK_TEST_EQ(square(fcj), fcj*fcj); SimTK_TEST_EQ(cube(fcj), fcj*fcj*fcj); SimTK_TEST_EQ(square(dcj), dcj*dcj); SimTK_TEST_EQ(cube(dcj), dcj*dcj*dcj); // Tests involving negators of complex and conjugate. SimTK_TEST_EQ(square(nfc), nfc*nfc); SimTK_TEST_EQ(square(nfc), fc*fc); SimTK_TEST_EQ(square(ndc), ndc*ndc); SimTK_TEST_EQ(square(ndc), dc*dc); SimTK_TEST_EQ(cube(nfc), nfc*nfc*nfc); SimTK_TEST_EQ(cube(nfc), -fc*fc*fc); SimTK_TEST_EQ(cube(ndc), ndc*ndc*ndc); SimTK_TEST_EQ(cube(ndc), -dc*dc*dc); SimTK_TEST_EQ(square(nfcj), nfcj*nfcj); SimTK_TEST_EQ(square(nfcj), fcj*fcj); SimTK_TEST_EQ(square(ndcj), ndcj*ndcj); SimTK_TEST_EQ(square(ndcj), dcj*dcj); SimTK_TEST_EQ(cube(nfcj), nfcj*nfcj*nfcj); SimTK_TEST_EQ(cube(nfcj), -fcj*fcj*fcj); SimTK_TEST_EQ(cube(ndcj), ndcj*ndcj*ndcj); SimTK_TEST_EQ(cube(ndcj), -dcj*dcj*dcj); } void testIsNumericallyEqual() { const float f=1.234f, fn=1.234f+1e-5f, fe=1.234f+1e-9f; const double d=1.234, dn=1.234 +1e-12, de=1.234 +1e-15; const negator<float>& nf=negator<float>::recast(f); const negator<float>& nfn=negator<float>::recast(fn); const negator<float>& nfe=negator<float>::recast(fe); SimTK_TEST(isNumericallyEqual(f,f)) SimTK_TEST(isNumericallyEqual(f,fe)); SimTK_TEST(!isNumericallyEqual(f,fn)); SimTK_TEST(isNumericallyEqual(f,fn,1e-4f)); SimTK_TEST(!isNumericallyEqual(f,fn,1e-6f)); SimTK_TEST(CNT<float>::isNumericallyEqual(f,f)); SimTK_TEST(CNT<float>::isNumericallyEqual(f,fe)); SimTK_TEST(!CNT<float>::isNumericallyEqual(f,fn)); SimTK_TEST(CNT<float>::isNumericallyEqual(f,fn,1e-4f)); SimTK_TEST(!CNT<float>::isNumericallyEqual(f,fn,1e-6f)); SimTK_TEST(nf.isNumericallyEqual(nf)); SimTK_TEST(nf.isNumericallyEqual(-f)); SimTK_TEST(!nf.isNumericallyEqual(f)); SimTK_TEST(isNumericallyEqual(1000*f,1234)); SimTK_TEST(isNumericallyEqual(1234,1000*f)); SimTK_TEST(isNumericallyEqual(1000*fe,1234)); SimTK_TEST(isNumericallyEqual(1234,1000*fe)); SimTK_TEST(!isNumericallyEqual(1000*fn,1234)); SimTK_TEST(!isNumericallyEqual(1234,1000*fn)); SimTK_TEST(isNumericallyEqual(d,d)); SimTK_TEST(isNumericallyEqual(d,de)); SimTK_TEST(!isNumericallyEqual(d,dn)); SimTK_TEST(isNumericallyEqual(1000*d,1234)); SimTK_TEST(isNumericallyEqual(1234,1000*d)); SimTK_TEST(isNumericallyEqual(1000*de,1234)); SimTK_TEST(isNumericallyEqual(1234,1000*de)); SimTK_TEST(!isNumericallyEqual(1000*dn,1234)); SimTK_TEST(!isNumericallyEqual(1234,1000*dn)); // Mixed should use float tolerance SimTK_TEST(isNumericallyEqual(fe,de)); SimTK_TEST(!isNumericallyEqual((double)fe,de)); } void testClamp() { const int i4=4; const double d325=3.25; const float fn325=-3.25; // int SimTK_TEST(clamp(4,i4,4)==4); SimTK_TEST(clamp(0,i4,9)==4); SimTK_TEST(clamp(5,i4,9)==5); SimTK_TEST(clamp(-7,i4,-5)==-5); // double SimTK_TEST(clamp(3.25,d325,3.25)==3.25); SimTK_TEST(clamp(0.,d325,9.)==3.25); SimTK_TEST(clamp(5.,d325,9.)==5); SimTK_TEST(clamp(-7.,d325,-5.)==-5); // float SimTK_TEST(clamp(-3.25f,fn325,-3.25f)==-3.25); SimTK_TEST(clamp(-9.f,fn325,0.f)==-3.25f); SimTK_TEST(clamp(-9.f,fn325,-5.f)==-5); SimTK_TEST(clamp(5.f,fn325,7.f)==5); // Test methods that take integer bounds. SimTK_TEST(clamp(0,d325,9)==3.25); SimTK_TEST(clamp(5,d325,9)==5); SimTK_TEST(clamp(-7,d325,-5)==-5); SimTK_TEST(clamp(-9,fn325,0)==-3.25); SimTK_TEST(clamp(-9,fn325,-5)==-5); SimTK_TEST(clamp(5,fn325,7)==5); SimTK_TEST(clamp(0.,d325,9)==3.25); SimTK_TEST(clamp(5.,d325,9)==5); SimTK_TEST(clamp(-7.,d325,-5)==-5); SimTK_TEST(clamp(-9.f,fn325,0)==-3.25); SimTK_TEST(clamp(-9.f,fn325,-5)==-5); SimTK_TEST(clamp(5.f,fn325,7)==5); SimTK_TEST(clamp(0,d325,9.)==3.25); SimTK_TEST(clamp(5,d325,9.)==5); SimTK_TEST(clamp(-7,d325,-5.)==-5); SimTK_TEST(clamp(-9,fn325,0.f)==-3.25); SimTK_TEST(clamp(-9,fn325,-5.f)==-5); SimTK_TEST(clamp(5,fn325,7.f)==5); int i; double d; float f; i=i4; SimTK_TEST(clampInPlace(-2,i,3)==3 && i==3); d=d325; SimTK_TEST(clampInPlace(-2.,d,3.)==3 && d==3); f=fn325; SimTK_TEST(clampInPlace(-2,f,3)==-2 && f==-2); // Do a test for each of the less-common supported types. char c='j'; unsigned char uc=3; signed char sc=-2; SimTK_TEST(clamp('a',c,'e')=='e'); SimTK_TEST(clamp('a',c,'z')=='j'); SimTK_TEST(clamp((unsigned char)4,uc,(unsigned char)5)==4); SimTK_TEST(clamp((signed char)-7,sc,(signed char)-1)==-2); short s=-32000; unsigned short us=17; unsigned ui=4023456789U; SimTK_TEST(clamp((short)-29000,s,(short)400)==-29000); SimTK_TEST(clamp((unsigned short)4,us,(unsigned short)15)==15); SimTK_TEST(clamp(100000000U,ui,4010000000U)==4010000000U); long l=-234234L; unsigned long ul=293493849UL; long long ll=-123456789123LL; unsigned long long ull=123456789123ULL; SimTK_TEST(clamp(-1000000L,l,-200000L)==-234234); SimTK_TEST(clamp(1000000UL,ul,4000000000UL)==293493849); SimTK_TEST(clamp(-100000000000LL,ll,27LL)==-100000000000LL); SimTK_TEST(clamp(-1000000000000LL,ll,27LL)==-123456789123LL); } void testStep() { // double SimTK_TEST(stepUp(0.)==0 && stepUp(.5)==.5 && stepUp(1.)==1); SimTK_TEST(0 < stepUp(.3) && stepUp(.3) < .5); SimTK_TEST(.5 < stepUp(.7) && stepUp(.7) < 1); SimTK_TEST(stepDown(0.)==1 && stepDown(.5)==.5 && stepDown(1.)==0); SimTK_TEST(.5 < stepDown(.3) && stepDown(.3) < 1); SimTK_TEST(0 < stepDown(.7) && stepDown(.7) < .5); SimTK_TEST(dstepUp(0.)==0 && dstepUp(.5)>0 && dstepUp(1.)==0); SimTK_TEST(dstepDown(0.)==0 && dstepDown(.5)<0 && dstepDown(1.)==0); SimTK_TEST(d2stepUp(0.)==0 && d2stepUp(1.)==0); SimTK_TEST(d2stepDown(0.)==0 && d2stepDown(1.)==0); // float SimTK_TEST(stepUp(0.f)==0 && stepUp(.5f)==.5f && stepUp(1.f)==1); SimTK_TEST(0 < stepUp(.3f) && stepUp(.3f) < .5f); SimTK_TEST(.5f < stepUp(.7f) && stepUp(.7f) < 1); SimTK_TEST(stepDown(0.f)==1 && stepDown(.5f)==.5f && stepDown(1.f)==0); SimTK_TEST(.5f < stepDown(.3f) && stepDown(.3f) < 1); SimTK_TEST(0 < stepDown(.7f) && stepDown(.7f) < .5f); SimTK_TEST(dstepUp(0.f)==0 && dstepUp(.5f)>0 && dstepUp(1.f)==0); SimTK_TEST(dstepDown(0.f)==0 && dstepDown(.5f)<0 && dstepDown(1.f)==0); SimTK_TEST(d2stepUp(0.f)==0 && d2stepUp(1.f)==0); SimTK_TEST(d2stepDown(0.f)==0 && d2stepDown(1.f)==0); // int is treated as a double, but only for stepUp()/stepDown() SimTK_TEST(stepUp(0)==0 && stepUp(1)==1); SimTK_TEST(stepDown(0)==1 && stepDown(1)==0); // Don't know anything analytic about d3 but can test with finite // differencing below. // Central difference estimates should give around 10 // decimal places in double, 4 in float. const double dupEst = (stepUp(.799+1e-6)-stepUp(.799-1e-6))/2e-6; const double ddnEst = (stepDown(.799+1e-6)-stepDown(.799-1e-6))/2e-6; const double d2upEst = (dstepUp(.723+1e-6)-dstepUp(.723-1e-6))/2e-6; const double d2dnEst = (dstepDown(.723+1e-6)-dstepDown(.723-1e-6))/2e-6; const double d3upEst = (d2stepUp(.123+1e-6)-d2stepUp(.123-1e-6))/2e-6; const double d3dnEst = (d2stepDown(.123+1e-6)-d2stepDown(.123-1e-6))/2e-6; SimTK_TEST_EQ_TOL(dstepUp(.799), dupEst, 1e-8); SimTK_TEST_EQ_TOL(dstepDown(.799), ddnEst, 1e-8); SimTK_TEST_EQ_TOL(d2stepUp(.723), d2upEst, 1e-8); SimTK_TEST_EQ_TOL(d2stepDown(.723), d2dnEst, 1e-8); SimTK_TEST_EQ_TOL(d3stepUp(.123), d3upEst, 1e-8); SimTK_TEST_EQ_TOL(d3stepDown(.123), d3dnEst, 1e-8); const float fdupEst = (stepUp(.699f+1e-3f)-stepUp(.699f-1e-3f))/2e-3f; const float fddnEst = (stepDown(.699f+1e-3f)-stepDown(.699f-1e-3f))/2e-3f; const float fd2upEst = (dstepUp(.623f+1e-3f)-dstepUp(.623f-1e-3f))/2e-3f; const float fd2dnEst = (dstepDown(.623f+1e-3f)-dstepDown(.623f-1e-3f))/2e-3f; const float fd3upEst = (d2stepUp(.211f+1e-3f)-d2stepUp(.211f-1e-3f))/2e-3f; const float fd3dnEst = (d2stepDown(.211f+1e-3f)-d2stepDown(.211f-1e-3f))/2e-3f; SimTK_TEST_EQ_TOL(dstepUp(.699f), fdupEst, 1e-3); SimTK_TEST_EQ_TOL(dstepDown(.699f), fddnEst, 1e-3); SimTK_TEST_EQ_TOL(d2stepUp(.623f), fd2upEst, 1e-3); SimTK_TEST_EQ_TOL(d2stepDown(.623f), fd2dnEst, 1e-3); SimTK_TEST_EQ_TOL(d3stepUp(.211f), fd3upEst, 1e-3); SimTK_TEST_EQ_TOL(d3stepDown(.211f), fd3dnEst, 1e-3); // y = stepAny(y0,yrange,x0,1/xrange, x) // y goes from -1 to 1 as x goes from 0 to 1, exact arithmetic. SimTK_TEST(stepAny(-1,2,0,1,0.) == -1); SimTK_TEST(stepAny(-1,2,0,1,.5) == 0); SimTK_TEST(stepAny(-1,2,0,1,1.) == 1); SimTK_TEST(stepAny(-1,2,0,1,0.f) == -1); SimTK_TEST(stepAny(-1,2,0,1,.5f) == 0); SimTK_TEST(stepAny(-1,2,0,1,1.f) == 1); // y goes from -7 down to -14 as x goes from -3.1 up to +429.3. const double x0=-3.1, x1=429.3, y0=-7., y1=-14.; const double xr=(x1-x0), ooxr=1/xr, yr=(y1-y0); SimTK_TEST_EQ(stepAny(y0,yr,x0,ooxr,-3.1), y0); SimTK_TEST_EQ(stepAny(y0,yr,x0,ooxr,429.3), y1); SimTK_TEST_EQ(stepAny(y0,yr,x0,ooxr,x0+xr/2), y0+yr/2); const float fx0=-3.1f, fx1=429.3f, fy0=-7.f, fy1=-14.f; const float fxr=(fx1-fx0), fooxr=1/fxr, fyr=(fy1-fy0); SimTK_TEST_EQ(stepAny(fy0,fyr,fx0,fooxr,-3.1f),fy0); SimTK_TEST_EQ(stepAny(fy0,fyr,fx0,fooxr,429.3f),fy1); SimTK_TEST_EQ(stepAny(fy0,fyr,fx0,fooxr,fx0+fxr/2),fy0+fyr/2); // Check derivatives const double danyEst = (stepAny(y0,yr,x0,ooxr,.799+1e-6)-stepAny(y0,yr,x0,ooxr,.799-1e-6))/2e-6; const double d2anyEst = (dstepAny(yr,x0,ooxr,.723+1e-6)-dstepAny(yr,x0,ooxr,.723-1e-6))/2e-6; const double d3anyEst = (d2stepAny(yr,x0,ooxr,.123+1e-6)-d2stepAny(yr,x0,ooxr,.123-1e-6))/2e-6; SimTK_TEST_EQ_TOL(dstepAny(yr,x0,ooxr,.799), danyEst, 1e-8); SimTK_TEST_EQ_TOL(d2stepAny(yr,x0,ooxr,.723), d2anyEst, 1e-8); SimTK_TEST_EQ_TOL(d3stepAny(yr,x0,ooxr,.123), d3anyEst, 1e-8); const float fdanyEst = (stepAny(fy0,fyr,fx0,fooxr,.799f+1e-3f) -stepAny(fy0,fyr,fx0,fooxr,.799f-1e-3f))/2e-3f; const float fd2anyEst = (dstepAny(fyr,fx0,fooxr,.723f+1e-3f) -dstepAny(fyr,fx0,fooxr,.723f-1e-3f))/2e-3f; const float fd3anyEst = (d2stepAny(fyr,fx0,fooxr,.123f+1e-3f) -d2stepAny(fyr,fx0,fooxr,.123f-1e-3f))/2e-3f; SimTK_TEST_EQ_TOL(dstepAny(fyr,fx0,fooxr,.799f), fdanyEst, 1e-3); SimTK_TEST_EQ_TOL(d2stepAny(fyr,fx0,fooxr,.723f), fd2anyEst, 1e-3); SimTK_TEST_EQ_TOL(d3stepAny(fyr,fx0,fooxr,.123f), fd3anyEst, 1e-3); } int main() { SimTK_START_TEST("TestScalar"); SimTK_SUBTEST(testIsNaN); SimTK_SUBTEST(testIsInf); SimTK_SUBTEST(testIsFinite); SimTK_SUBTEST(testSignBit); SimTK_SUBTEST(testSign); SimTK_SUBTEST(testSquareAndCube); SimTK_SUBTEST(testIsNumericallyEqual); SimTK_SUBTEST(testClamp); SimTK_SUBTEST(testStep); SimTK_END_TEST(); }
43.606906
103
0.644811
e-schumann
1f670fa59096390aa78f4f05c0360763b39347a4
25,751
cpp
C++
src/libs/plugins/pokey/pokeyDevice.cpp
mteichtahl/simhub
4c409c61e38bb5deeb58a09c6cb89730d38280e1
[ "MIT" ]
3
2018-03-19T18:09:12.000Z
2021-06-17T03:56:05.000Z
src/libs/plugins/pokey/pokeyDevice.cpp
mteichtahl/simhub
4c409c61e38bb5deeb58a09c6cb89730d38280e1
[ "MIT" ]
19
2017-04-29T11:25:52.000Z
2021-05-07T14:48:59.000Z
src/libs/plugins/pokey/pokeyDevice.cpp
mteichtahl/simhub
4c409c61e38bb5deeb58a09c6cb89730d38280e1
[ "MIT" ]
9
2017-04-26T22:45:06.000Z
2022-02-27T01:08:54.000Z
#include <string.h> #include "elements/attributes/attribute.h" #include "main.h" #include "pokeyDevice.h" using namespace std::chrono_literals; PokeyDevice::PokeyDevice(PokeyDevicePluginStateManager *owner, sPoKeysNetworkDeviceSummary deviceSummary, uint8_t index) { _callbackArg = NULL; _enqueueCallback = NULL; _owner = owner; _pokey = PK_ConnectToNetworkDevice(&deviceSummary); if (!_pokey) { throw std::exception(); } _index = index; _userId = deviceSummary.UserID; _serialNumber = std::to_string(deviceSummary.SerialNumber); _firwareVersionMajorMajor = (deviceSummary.FirmwareVersionMajor >> 4) + 1; _firwareVersionMajor = deviceSummary.FirmwareVersionMajor & 0x0F; _firwareVersionMinor = deviceSummary.FirmwareVersionMinor; memcpy(&_ipAddress, &deviceSummary.IPaddress, 4); _hardwareType = deviceSummary.HWtype; _dhcp = deviceSummary.DHCP; _intToDisplayRow[0] = 0b11111100; _intToDisplayRow[1] = 0b01100000; _intToDisplayRow[2] = 0b11011010; _intToDisplayRow[3] = 0b11110010; _intToDisplayRow[4] = 0b01100110; _intToDisplayRow[5] = 0b10110110; _intToDisplayRow[6] = 0b10111110; _intToDisplayRow[7] = 0b11100000; _intToDisplayRow[8] = 0b11111110; _intToDisplayRow[9] = 0b11100110; _switchMatrixManager = std::make_shared<PokeySwitchMatrixManager>(_pokey); loadPinConfiguration(); if (makeAllPinsInactive()) { _pollTimer.data = this; _pollLoop = uv_loop_new(); uv_timer_init(_pollLoop, &_pollTimer); int ret = uv_timer_start(&_pollTimer, (uv_timer_cb)&PokeyDevice::DigitalIOTimerCallback, DEVICE_START_DELAY, DEVICE_READ_INTERVAL); if (ret == 0) { _pollThread = std::make_shared<std::thread>([=] { uv_run(_pollLoop, UV_RUN_DEFAULT); }); } } else { printf("Failed to make all pins inactive - pokey polling loop inactive"); } } bool PokeyDevice::ownsPin(std::string pinName) { for (int i = 0; i < _pokey->info.iPinCount; i++) { if (_pins[i].pinName == pinName) { return true; } } return false; } bool PokeyDevice::makeAllPinsInactive() { bool retVal = true; for (int i = 0; i < _pokey->info.iPinCount; i++) { int ret = inactivePin(i); if (ret != PK_OK) { retVal = false; break; } } return retVal; } void PokeyDevice::setCallbackInfo(EnqueueEventHandler enqueueCallback, void *callbackArg, SPHANDLE pluginInstance) { _enqueueCallback = enqueueCallback; _callbackArg = callbackArg; _pluginInstance = pluginInstance; } void PokeyDevice::DigitalIOTimerCallback(uv_timer_t *timer, int status) { PokeyDevice *self = static_cast<PokeyDevice *>(timer->data); assert(self); // only run if we have complete our preflight if (!self->_owner->successfulPreflightCompleted()) { return; } // Process the encoders int encoderRetValue = PK_EncoderValuesGet(self->_pokey); if (encoderRetValue == PK_OK) { GenericTLV *el = NULL; for (int i = 0; i < self->_encoderMap.size(); i++) { uint32_t step = self->_encoders[i].step; uint32_t newEncoderValue = self->_pokey->Encoders[i].encoderValue; uint32_t previousEncoderValue = self->_encoders[i].previousEncoderValue; uint32_t currentValue = self->_encoders[i].value; uint32_t min = self->_encoders[i].min; uint32_t max = self->_encoders[i].max; if (previousEncoderValue != newEncoderValue) { if (newEncoderValue < previousEncoderValue) { // values are decreasing // absolute encoders send 1 or -1 if (self->_encoders[i].type == "absolute") { self->_encoders[i].value = 1; } else { if (currentValue <= min) { self->_encoders[i].previousValue = min; self->_encoders[i].value = min; } else { self->_encoders[i].value = currentValue - step; } } } else { // values are increasing if (self->_encoders[i].type == "absolute") { // absolute encoders send 1 or -1 self->_encoders[i].value = -1; } else { if (currentValue >= max) { self->_encoders[i].previousValue = max; self->_encoders[i].value = max; } else { self->_encoders[i].value = currentValue + step; } } } el = make_generic(self->_encoders[i].name.c_str(), self->_encoders[i].description.c_str()); el->ownerPlugin = self->_owner; el->type = CONFIG_INT; el->value.int_value = (int)self->_encoders[i].value; el->length = sizeof(uint32_t); dupe_string(&(el->units), self->_encoders[i].units.c_str()); // enqueue the element self->_enqueueCallback(self, (void *)el, self->_callbackArg); // set previous to equal new self->_encoders[i].previousEncoderValue = newEncoderValue; } } } // Finish processing the encoders int retVal = PK_DigitalIOGet(self->_pokey); if (retVal == PK_OK) { self->_owner->pinRemappingMutex().lock(); for (int i = 0; i < self->_pokey->info.iPinCount; i++) { GenericTLV *el = make_generic((const char *)"-", (const char *)"-"); if (self->_pins[i].type == "DIGITAL_INPUT") { int sourcePinNumber = self->_pins[i].pinNumber; if (self->_pins[i].value != self->_pokey->Pins[sourcePinNumber - 1].DigitalValueGet && !self->_pins[i].skipNext) { // data has changed so send it off for processing printf("DIN pin-index %i - %i\n", sourcePinNumber - 1, self->_pokey->Pins[sourcePinNumber - 1].DigitalValueGet); el->ownerPlugin = self->_owner; el->type = CONFIG_BOOL; bool hackSkip = false; el->length = sizeof(uint8_t); if (self->_owner->pinRemapped(self->_pins[i].pinName)) { // KLUDGE: as each device has its own polling // thread, the logic below is a // critical section because it can // touch the state of multiple device // pins std::pair<std::shared_ptr<PokeyDevice>, std::string> remappedPinInfo = self->_owner->remappedPinDetails(self->_pins[i].pinName); int remappedPinIndex = remappedPinInfo.first->pinIndexFromName(remappedPinInfo.second); // remappedPinInfo.first->pins()[remappedPinIndex].previousValue = self->_pins[self->_pins[i].pinNumber - 1].value; self->_pins[i].previousValue = self->_pins[self->_pins[i].pinNumber - 1].value; remappedPinInfo.first->_pins[remappedPinIndex].previousValue = self->_pokey->Pins[sourcePinNumber - 1].DigitalValueGet; remappedPinInfo.first->_pins[remappedPinIndex].value = self->_pokey->Pins[sourcePinNumber - 1].DigitalValueGet; self->_pins[i].value = self->_pokey->Pins[sourcePinNumber - 1].DigitalValueGet; dupe_string(&(el->name), remappedPinInfo.second.c_str()); el->value.bool_value = self->_pokey->Pins[sourcePinNumber - 1].DigitalValueGet; if (el->value.bool_value == 0) { remappedPinInfo.first->_pins[remappedPinIndex].skipNext = true; } else { if (!remappedPinInfo.first->_pins[remappedPinIndex].skipNext) { self->_owner->pinRemappingMutex().unlock(); std::this_thread::sleep_for(250ms); // give any other remapped polling // threads a chance to send a state // change if (remappedPinInfo.first->_pins[remappedPinIndex].skipNext) { hackSkip = true; } } remappedPinInfo.first->_pins[remappedPinIndex].skipNext = false; } printf("--> remapping %s to %s\n", self->_pins[i].pinName.c_str(), remappedPinInfo.first->pins()[remappedPinIndex].pinName.c_str()); } else { dupe_string(&(el->name), self->_pins[i].pinName.c_str()); el->value.bool_value = self->_pins[i].value; self->_pins[i].previousValue = self->_pins[i].value; self->_pins[i].value = self->_pokey->Pins[self->_pins[i].pinNumber - 1].DigitalValueGet; } if (hackSkip) { printf("HACKSKIP, %s, %i\n", self->_pins[i].pinName.c_str(), self->_pins[i].value); release_generic(el); self->_owner->pinRemappingMutex().unlock(); return; } if (self->_pins[i].description.size() > 0) { dupe_string(&(el->description), self->_pins[i].description.c_str()); } if (self->_pins[i].units.size() > 0) { dupe_string(&(el->units), self->_pins[i].units.c_str()); } std::shared_ptr<Attribute> attribute = AttributeFromCGeneric(el); TransformFunction transformer = self->_owner->transformForPinName(self->_pins[i].pinName); if (transformer) { std::string transformedValue = transformer(attribute->valueToString(), "NULL", "NULL"); attribute->setType(STRING_ATTRIBUTE); attribute->setValue(transformedValue); GenericTLV *transformedGeneric = AttributeToCGeneric(attribute); printf("---> %s: %s\n", (char *)self->_pins[i].pinName.c_str(), transformedValue.c_str()); self->_enqueueCallback(self, (void *)transformedGeneric, self->_callbackArg); } else { printf("---> %s\n", (char *)self->_pins[i].pinName.c_str()); self->_enqueueCallback(self, (void *)el, self->_callbackArg); } } } } // -- process all switch matrix std::vector<GenericTLV *> matrixResult = self->_switchMatrixManager->readAll(); for (auto &res : matrixResult) { res->ownerPlugin = self->_owner; self->_enqueueCallback(self, (void *)res, self->_callbackArg); } // -- end process all switch matrix self->_owner->pinRemappingMutex().unlock(); } else { if (retVal == PK_ERR_TRANSFER) { printf("----> PK_ERR_TRANSFER %i\n\n", retVal); } else if (retVal == PK_ERR_GENERIC) { printf("----> PK_ERR_GENERIC %i\n\n", retVal); } else if (retVal == PK_ERR_PARAMETER) { printf("----> PK_ERR_PARAMETER %i\n\n", retVal); } } } void PokeyDevice::addPin(int pinIndex, std::string pinName, int pinNumber, std::string pinType, int defaultValue, std::string description, bool invert) { if (pinType == "DIGITAL_OUTPUT") outputPin(pinNumber); if (pinType == "DIGITAL_INPUT") inputPin(pinNumber, invert); mapNameToPin(pinName.c_str(), pinNumber); _pins[pinIndex].pinName = pinName; _pins[pinIndex].pinIndex = pinIndex; _pins[pinIndex].type = pinType.c_str(); _pins[pinIndex].pinNumber = pinNumber; _pins[pinIndex].defaultValue = defaultValue; _pins[pinIndex].value = defaultValue; _pins[pinIndex].description = description; } void PokeyDevice::startPolling() { uv_run(uv_default_loop(), UV_RUN_DEFAULT); } void PokeyDevice::stopPolling() { assert(_pollLoop); uv_stop(_pollLoop); if (_pollThread->joinable()) _pollThread->join(); } /** * @brief Default destructor for PokeyDevice * * @return nothing */ PokeyDevice::~PokeyDevice() { stopPolling(); if (_pollThread) { if (_pollThread->joinable()) { _pollThread->join(); } } PK_DisconnectDevice(_pokey); } std::string PokeyDevice::name() { std::string tmp((char *)deviceData().DeviceName); return tmp; } std::string PokeyDevice::hardwareTypeString() { if (_hardwareType == 31) { return "Pokey 57E"; } return "Unknown"; } bool PokeyDevice::validatePinCapability(int pin, std::string type) { assert(_pokey); bool retVal = false; if (type == "DIGITAL_OUTPUT") { retVal = isPinDigitalOutput(pin - 1); } else if (type == "DIGITAL_INPUT") { retVal = isPinDigitalInput(pin - 1); } return retVal; } bool PokeyDevice::validateEncoder(int encoderNumber) { assert(_pokey); bool retVal = false; if (encoderNumber == ENCODER_1) { //! TODO: Check pins 1 and 2 are not allocated already retVal = isEncoderCapable(1) && isEncoderCapable(2); } else if (encoderNumber == ENCODER_2) { //! TODO: Check pins 5 and 6 are not allocated already retVal = isEncoderCapable(5) && isEncoderCapable(6); } else if (encoderNumber == ENCODER_3) { //! TODO: Check pins 15 and 16 are not allocated already retVal = isEncoderCapable(15) && isEncoderCapable(16); } return retVal; } bool PokeyDevice::isEncoderCapable(int pin) { switch (pin) { case 1: return (bool)PK_CheckPinCapability(_pokey, 0, PK_AllPinCap_fastEncoder1A); case 2: return (bool)PK_CheckPinCapability(_pokey, 1, PK_AllPinCap_fastEncoder1B); case 5: return true; //! this is here because the pokeys library is broken return (bool)PK_CheckPinCapability(_pokey, 5, PK_AllPinCap_fastEncoder2A); case 6: return true; // this is here because the pokeys library is broken return (bool)PK_CheckPinCapability(_pokey, 6, PK_AllPinCap_fastEncoder2B); case 15: return (bool)PK_CheckPinCapability(_pokey, 14, PK_AllPinCap_fastEncoder3A); case 16: return (bool)PK_CheckPinCapability(_pokey, 15, PK_AllPinCap_fastEncoder3B); default: return false; } return false; } void PokeyDevice::addEncoder( int encoderNumber, uint32_t defaultValue, std::string name, std::string description, int min, int max, int step, int invertDirection, std::string units, std::string type) { assert(encoderNumber >= 1); PK_EncoderConfigurationGet(_pokey); int encoderIndex = encoderNumber - 1; _pokey->Encoders[encoderIndex].encoderValue = defaultValue; _pokey->Encoders[encoderIndex].encoderOptions = 0b11; if (encoderNumber == 1) { if (invertDirection) { _pokey->Encoders[encoderIndex].channelApin = 1; _pokey->Encoders[encoderIndex].channelBpin = 0; } else { _pokey->Encoders[encoderIndex].channelApin = 1; _pokey->Encoders[encoderIndex].channelBpin = 0; } } else if (encoderNumber == 2) { if (invertDirection) { _pokey->Encoders[encoderIndex].channelApin = 5; _pokey->Encoders[encoderIndex].channelBpin = 4; } else { _pokey->Encoders[encoderIndex].channelApin = 4; _pokey->Encoders[encoderIndex].channelBpin = 5; } } else if (encoderNumber == 3) { if (invertDirection) { _pokey->Encoders[encoderIndex].channelApin = 15; _pokey->Encoders[encoderIndex].channelBpin = 14; } else { _pokey->Encoders[encoderIndex].channelApin = 14; _pokey->Encoders[encoderIndex].channelBpin = 15; } } _encoders[encoderIndex].name = name; _encoders[encoderIndex].number = encoderNumber; _encoders[encoderIndex].defaultValue = defaultValue; _encoders[encoderIndex].value = defaultValue; _encoders[encoderIndex].previousValue = defaultValue; _encoders[encoderIndex].previousEncoderValue = defaultValue; _encoders[encoderIndex].min = min; _encoders[encoderIndex].max = max; _encoders[encoderIndex].step = step; _encoders[encoderIndex].units = units; _encoders[encoderIndex].description = description; _encoders[encoderIndex].type = type; int val = PK_EncoderConfigurationSet(_pokey); if (val == PK_OK) { PK_EncoderValuesSet(_pokey); mapNameToEncoder(name.c_str(), encoderNumber); } else { // throw exception } } void PokeyDevice::addMatrixLED(int id, std::string name, std::string type) { PK_MatrixLEDConfigurationGet(_pokey); _matrixLED[id].name = name; _matrixLED[id].type = type; mapNameToMatrixLED(name, id); } void PokeyDevice::addGroupToMatrixLED(int id, int displayId, std::string name, int digits, int position) { _matrixLED[displayId].group[position].name = name; _matrixLED[displayId].group[position].position = position; _matrixLED[displayId].group[position].length = digits; _matrixLED[displayId].group[position].value = 0; } void PokeyDevice::configMatrixLED(int id, int rows, int cols, int enabled) { _pokey->MatrixLED[id].rows = rows; _pokey->MatrixLED[id].columns = cols; _pokey->MatrixLED[id].displayEnabled = enabled; _pokey->MatrixLED[id].RefreshFlag = 1; _pokey->MatrixLED[id].data[0] = 0; _pokey->MatrixLED[id].data[1] = 0; _pokey->MatrixLED[id].data[2] = 0; _pokey->MatrixLED[id].data[3] = 0; _pokey->MatrixLED[id].data[4] = 0; _pokey->MatrixLED[id].data[5] = 0; _pokey->MatrixLED[id].data[6] = 0; _pokey->MatrixLED[id].data[7] = 0; int32_t ret = PK_MatrixLEDConfigurationSet(_pokey); PK_MatrixLEDUpdate(_pokey); } void PokeyDevice::configMatrix(int id, uint8_t chipSelect, std::string type, uint8_t enabled, std::string name, std::string description) { _pokeyMax7219Manager = std::make_shared<PokeyMAX7219Manager>(_pokey); if (enabled) { _pokeyMax7219Manager->addMatrix(id, chipSelect, type, enabled, name, description); } } void PokeyDevice::addLedToLedMatrix(int ledMatrixIndex, uint8_t ledIndex, std::string name, std::string description, uint8_t enabled, uint8_t row, uint8_t col) { assert(_pokeyMax7219Manager); _pokeyMax7219Manager->addLedToMatrix(ledMatrixIndex, ledIndex, name, description, enabled, row, col); } uint32_t PokeyDevice::targetValue(std::string targetName, int value) { uint8_t displayNum = displayFromName(targetName); displayNumber(displayNum, targetName, value); return 0; } uint32_t PokeyDevice::targetValue(std::string targetName, bool value) { uint32_t retValue = PK_OK; uint32_t result = PK_OK; uint8_t pin = pinFromName(targetName) - 1; if (pin >= 0 && pin <= 55) { result = PK_DigitalIOSetSingle(_pokey, pin, value); } else { // we have output matrix - so deliver there _pokeyMax7219Manager->setLedByName(targetName, value); } if (result == PK_ERR_TRANSFER) { printf("----> PK_ERR_TRANSFER pin %d --> %d %d (pokey: %s)\n\n", pin, (uint8_t)value, result, name().c_str()); } else if (result == PK_ERR_GENERIC) { printf("----> PK_ERR_GENERIC pin %d --> %d %d (pokey: %s)\n\n", pin, (uint8_t)value, result, name().c_str()); } else if (result == PK_ERR_PARAMETER) { printf("----> PK_ERR_PARAMETER pin %d --> %d %d (pokey: %s)\n\n", pin, (uint8_t)value, result, name().c_str()); } // for now always return succes as we don't want to terminate // eveinting on setsingle error return retValue; } uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName, int value) { int groupIndex = 0; for (int i = 0; i < MAX_MATRIX_LED_GROUPS; i++) { if (_matrixLED[displayNumber].group[i].name == targetName) { groupIndex = i; } } // we should only display +ve values if (value < -1) { value = value * -1; } std::string charString = std::to_string(value); int numberOfChars = charString.length(); int groupLength = _matrixLED[displayNumber].group[groupIndex].length; if (value == 0) { int position = _matrixLED[displayNumber].group[groupIndex].position; for (int i = position; i < (groupLength + position); i++) { _pokey->MatrixLED[displayNumber].data[i] = 0b00000000; } _pokey->MatrixLED[displayNumber].data[(position + groupLength) - 1] = _intToDisplayRow[0]; } if (numberOfChars <= groupLength) { for (int i = 0; i < numberOfChars; i++) { int displayOffset = (int)charString.at(i) - 48; int convertedValue = _intToDisplayRow[displayOffset]; int position = groupIndex + i; if (value > 0) { _matrixLED[displayNumber].group[groupIndex].value = convertedValue; _pokey->MatrixLED[displayNumber].data[position] = convertedValue; } else if (value == -1) { for (int i = groupIndex; i < groupLength + groupIndex; i++) { _pokey->MatrixLED[displayNumber].data[i] = 0b00000000; } } } } _pokey->MatrixLED[displayNumber].RefreshFlag = 1; int retValue = PK_MatrixLEDUpdate(_pokey); if (retValue == PK_ERR_TRANSFER) { printf("----> PK_ERR_TRANSFER %i\n\n", retValue); } else if (retValue == PK_ERR_GENERIC) { printf("----> PK_ERR_GENERIC %i\n\n", retValue); } else if (retValue == PK_ERR_PARAMETER) { printf("----> PK_ERR_PARAMETER pin %i\n\n", retValue); } return retValue; } int PokeyDevice::configSwitchMatrix(int id, std::string name, std::string type, bool enabled) { int retVal = -1; _switchMatrixManager->addMatrix(id, name, type, enabled); return retVal; } int PokeyDevice::configSwitchMatrixSwitch(int switchMatrixId, int switchId, std::string name, int pin, int enablePin, bool invert, bool invertEnablePin) { std::shared_ptr<PokeySwitchMatrix> matrix = _switchMatrixManager->matrix(switchMatrixId); matrix->addSwitch(switchId, name, pin, enablePin, invert, invertEnablePin); return 0; } int PokeyDevice::configSwitchMatrixVirtualPin(int switchMatrixId, std::string name, bool invert, PinMaskMap &virtualPinMask, std::map<int, std::string> &valueTransforms) { std::shared_ptr<PokeySwitchMatrix> matrix = _switchMatrixManager->matrix(switchMatrixId); matrix->addVirtualPin(name, invert, virtualPinMask, valueTransforms); return 0; } uint32_t PokeyDevice::outputPin(uint8_t pin) { _pokey->Pins[--pin].PinFunction = PK_PinCap_digitalOutput | PK_PinCap_invertPin; return PK_PinConfigurationSet(_pokey); } uint32_t PokeyDevice::inputPin(uint8_t pin, bool invert) { int pinSetting = PK_PinCap_digitalInput; if (invert) { pinSetting = pinSetting | PK_PinCap_invertPin; } _pokey->Pins[--pin].PinFunction = pinSetting; return PK_PinConfigurationSet(_pokey); } uint32_t PokeyDevice::inactivePin(uint8_t pin) { int pinSetting = PK_PinCap_pinRestricted; return PK_PinConfigurationSet(_pokey); } int32_t PokeyDevice::name(std::string name) { strncpy((char *)_pokey->DeviceData.DeviceName, name.c_str(), 30); return PK_DeviceNameSet(_pokey); } uint8_t PokeyDevice::displayFromName(std::string targetName) { std::map<std::string, int>::iterator it; it = _displayMap.find(targetName); if (it != _displayMap.end()) { return it->second; } else { printf("---> cant find display\n"); return -1; } } int PokeyDevice::pinIndexFromName(std::string targetName) { for (size_t i = 0; i < MAX_PINS; i++) { if (_pins[i].pinName == targetName) { return _pins[i].pinIndex; } } return -1; } int PokeyDevice::pinFromName(std::string targetName) { std::map<std::string, int>::iterator it; it = _pinMap.find(targetName); if (it != _pinMap.end()) { return it->second; } else return -1; } void PokeyDevice::mapNameToPin(std::string name, int pin) { _pinMap.emplace(name, pin); } void PokeyDevice::mapNameToEncoder(std::string name, int encoderNumber) { _encoderMap.emplace(name, encoderNumber); } void PokeyDevice::mapNameToMatrixLED(std::string name, int id) { _displayMap.emplace(name, id); } bool PokeyDevice::isPinDigitalOutput(uint8_t pin) { return (bool)PK_CheckPinCapability(_pokey, pin, PK_AllPinCap_digitalOutput); } bool PokeyDevice::isPinDigitalInput(uint8_t pin) { return (bool)PK_CheckPinCapability(_pokey, pin, PK_AllPinCap_digitalInput); }
33.972296
174
0.597841
mteichtahl
1f685bfe9060adfa2833fb81f48d6f6b2ca4fb54
421
hpp
C++
src/serialization/spatial.hpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
716
2015-03-30T16:26:45.000Z
2022-03-30T12:26:58.000Z
src/serialization/spatial.hpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
1,130
2015-02-21T17:30:44.000Z
2022-03-30T09:06:22.000Z
src/serialization/spatial.hpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
239
2015-02-05T14:15:14.000Z
2022-03-14T23:51:47.000Z
// // Copyright (c) 2019 INRIA // #ifndef __pinocchio_serialization_spatial_hpp__ #define __pinocchio_serialization_spatial_hpp__ #include "pinocchio/serialization/se3.hpp" #include "pinocchio/serialization/motion.hpp" #include "pinocchio/serialization/force.hpp" #include "pinocchio/serialization/symmetric3.hpp" #include "pinocchio/serialization/inertia.hpp" #endif // ifndef __pinocchio_serialization_spatial_hpp__
28.066667
56
0.831354
thanhndv212
1f6ad8649c57098ed589225627b04f177fad1348
12,610
cc
C++
wrappers/7.0.0/vtkUniformGridAMRDataIteratorWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkUniformGridAMRDataIteratorWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkUniformGridAMRDataIteratorWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkCompositeDataIteratorWrap.h" #include "vtkUniformGridAMRDataIteratorWrap.h" #include "vtkObjectWrap.h" #include "vtkInformationWrap.h" #include "vtkDataObjectWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkUniformGridAMRDataIteratorWrap::ptpl; VtkUniformGridAMRDataIteratorWrap::VtkUniformGridAMRDataIteratorWrap() { } VtkUniformGridAMRDataIteratorWrap::VtkUniformGridAMRDataIteratorWrap(vtkSmartPointer<vtkUniformGridAMRDataIterator> _native) { native = _native; } VtkUniformGridAMRDataIteratorWrap::~VtkUniformGridAMRDataIteratorWrap() { } void VtkUniformGridAMRDataIteratorWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkUniformGridAMRDataIterator").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("UniformGridAMRDataIterator").ToLocalChecked(), ConstructorGetter); } void VtkUniformGridAMRDataIteratorWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkUniformGridAMRDataIteratorWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkCompositeDataIteratorWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkCompositeDataIteratorWrap::ptpl)); tpl->SetClassName(Nan::New("VtkUniformGridAMRDataIteratorWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetCurrentDataObject", GetCurrentDataObject); Nan::SetPrototypeMethod(tpl, "getCurrentDataObject", GetCurrentDataObject); Nan::SetPrototypeMethod(tpl, "GetCurrentFlatIndex", GetCurrentFlatIndex); Nan::SetPrototypeMethod(tpl, "getCurrentFlatIndex", GetCurrentFlatIndex); Nan::SetPrototypeMethod(tpl, "GetCurrentIndex", GetCurrentIndex); Nan::SetPrototypeMethod(tpl, "getCurrentIndex", GetCurrentIndex); Nan::SetPrototypeMethod(tpl, "GetCurrentLevel", GetCurrentLevel); Nan::SetPrototypeMethod(tpl, "getCurrentLevel", GetCurrentLevel); Nan::SetPrototypeMethod(tpl, "GetCurrentMetaData", GetCurrentMetaData); Nan::SetPrototypeMethod(tpl, "getCurrentMetaData", GetCurrentMetaData); Nan::SetPrototypeMethod(tpl, "GoToFirstItem", GoToFirstItem); Nan::SetPrototypeMethod(tpl, "goToFirstItem", GoToFirstItem); Nan::SetPrototypeMethod(tpl, "GoToNextItem", GoToNextItem); Nan::SetPrototypeMethod(tpl, "goToNextItem", GoToNextItem); Nan::SetPrototypeMethod(tpl, "HasCurrentMetaData", HasCurrentMetaData); Nan::SetPrototypeMethod(tpl, "hasCurrentMetaData", HasCurrentMetaData); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "IsDoneWithTraversal", IsDoneWithTraversal); Nan::SetPrototypeMethod(tpl, "isDoneWithTraversal", IsDoneWithTraversal); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); #ifdef VTK_NODE_PLUS_VTKUNIFORMGRIDAMRDATAITERATORWRAP_INITPTPL VTK_NODE_PLUS_VTKUNIFORMGRIDAMRDATAITERATORWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkUniformGridAMRDataIteratorWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkUniformGridAMRDataIterator> native = vtkSmartPointer<vtkUniformGridAMRDataIterator>::New(); VtkUniformGridAMRDataIteratorWrap* obj = new VtkUniformGridAMRDataIteratorWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkUniformGridAMRDataIteratorWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkUniformGridAMRDataIteratorWrap::GetCurrentDataObject(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); vtkDataObject * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCurrentDataObject(); VtkDataObjectWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataObjectWrap *w = new VtkDataObjectWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkUniformGridAMRDataIteratorWrap::GetCurrentFlatIndex(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); unsigned int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCurrentFlatIndex(); info.GetReturnValue().Set(Nan::New(r)); } void VtkUniformGridAMRDataIteratorWrap::GetCurrentIndex(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); unsigned int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCurrentIndex(); info.GetReturnValue().Set(Nan::New(r)); } void VtkUniformGridAMRDataIteratorWrap::GetCurrentLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); unsigned int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCurrentLevel(); info.GetReturnValue().Set(Nan::New(r)); } void VtkUniformGridAMRDataIteratorWrap::GetCurrentMetaData(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); vtkInformation * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCurrentMetaData(); VtkInformationWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkInformationWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkInformationWrap *w = new VtkInformationWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkUniformGridAMRDataIteratorWrap::GoToFirstItem(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->GoToFirstItem(); } void VtkUniformGridAMRDataIteratorWrap::GoToNextItem(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->GoToNextItem(); } void VtkUniformGridAMRDataIteratorWrap::HasCurrentMetaData(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->HasCurrentMetaData(); info.GetReturnValue().Set(Nan::New(r)); } void VtkUniformGridAMRDataIteratorWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkUniformGridAMRDataIteratorWrap::IsDoneWithTraversal(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->IsDoneWithTraversal(); info.GetReturnValue().Set(Nan::New(r)); } void VtkUniformGridAMRDataIteratorWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); vtkUniformGridAMRDataIterator * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkUniformGridAMRDataIteratorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkUniformGridAMRDataIteratorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkUniformGridAMRDataIteratorWrap *w = new VtkUniformGridAMRDataIteratorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkUniformGridAMRDataIteratorWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUniformGridAMRDataIteratorWrap *wrapper = ObjectWrap::Unwrap<VtkUniformGridAMRDataIteratorWrap>(info.Holder()); vtkUniformGridAMRDataIterator *native = (vtkUniformGridAMRDataIterator *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkUniformGridAMRDataIterator * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkUniformGridAMRDataIteratorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkUniformGridAMRDataIteratorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkUniformGridAMRDataIteratorWrap *w = new VtkUniformGridAMRDataIteratorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); }
35.72238
124
0.765583
axkibe
1f6d1c213f0ae2f58da5b768a4b9c8c9b8aeab83
1,204
cpp
C++
Greed-is-Good.cpp
EdvinAlvarado/Code-Wars
a3a06a44cda004052b5c0930f3693678c5c92e21
[ "BSD-2-Clause" ]
null
null
null
Greed-is-Good.cpp
EdvinAlvarado/Code-Wars
a3a06a44cda004052b5c0930f3693678c5c92e21
[ "BSD-2-Clause" ]
null
null
null
Greed-is-Good.cpp
EdvinAlvarado/Code-Wars
a3a06a44cda004052b5c0930f3693678c5c92e21
[ "BSD-2-Clause" ]
null
null
null
#include <vector> #include <map> #include <iostream> int score(const std::vector<int>& dice) { std::map<int,int> dvalue_counter; int result = 0; for (const int& dvalue: dice) { std::cout << dvalue << " "; dvalue_counter[dvalue]++; } for (auto it = dvalue_counter.begin(); it != dvalue_counter.end(); it++) { // std::cout << it->first << "\t" << it->second << std::endl; if (it->second == 3) { if (it->first == 1) { result += 1000; dvalue_counter[it->first] -= 3; } else if (it->first == 6) { result += 600; // dvalue_counter[it->first] -= 3; } else if (it->first == 5) { result += 500; dvalue_counter[it->first] -= 3; } else if (it->first == 4) { result += 400; // dvalue_counter[it->first] -= 3; } else if (it->first == 3) { result += 300; // dvalue_counter[it->first] -= 3; } else if (it->first == 2) { result += 200; // dvalue_counter[it->first] -= 3; } } if (it->first == 1) { result += it->second * 100; } else if (it->first == 5) { result += it->second * 50; } } return result; } int main() { const std::vector<int> dice_throws = {3, 3, 3, 3, 3}; std::cout << score(dice_throws) << std::endl; }
25.083333
75
0.542359
EdvinAlvarado
1f718d971c81e0fdf3cf645269132c27308f8042
20,284
cpp
C++
silkopter/fc/src/simulator/Multirotor_Simulator.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
silkopter/fc/src/simulator/Multirotor_Simulator.cpp
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
silkopter/fc/src/simulator/Multirotor_Simulator.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
#include "FCStdAfx.h" #include "Multirotor_Simulator.h" #include "uav_properties/IMultirotor_Properties.h" #include "hal.def.h" #include "messages.def.h" //#include "sz_Multirotor_Simulator.hpp" //#include "sz_Multirotor_Simulator_Structs.hpp" namespace silk { namespace node { Multirotor_Simulator::Multirotor_Simulator(HAL& hal) : m_hal(hal) , m_descriptor(new hal::Multirotor_Simulator_Descriptor()) , m_config(new hal::Multirotor_Simulator_Config()) { m_angular_velocity_stream = std::make_shared<Angular_Velocity>(); m_acceleration_stream = std::make_shared<Acceleration>(); m_magnetic_field_stream = std::make_shared<Magnetic_Field>(); m_pressure_stream = std::make_shared<Pressure>(); m_temperature_stream = std::make_shared<Temperature>(); m_distance_stream = std::make_shared<Distance>(); m_gps_info_stream = std::make_shared<GPS_Info>(); m_ecef_position_stream = std::make_shared<ECEF_Position>(); m_ecef_velocity_stream = std::make_shared<ECEF_Velocity>(); m_simulator_state_stream = std::make_shared<Simulator_State_Stream>(); } ts::Result<void> Multirotor_Simulator::init(hal::INode_Descriptor const& descriptor) { QLOG_TOPIC("multirotor_simulator::init"); auto specialized = dynamic_cast<hal::Multirotor_Simulator_Descriptor const*>(&descriptor); if (!specialized) { return make_error("Wrong descriptor type"); } *m_descriptor = *specialized; return init(); } ts::Result<void> Multirotor_Simulator::init() { std::shared_ptr<const IMultirotor_Properties> multirotor_properties = m_hal.get_specialized_uav_properties<IMultirotor_Properties>(); if (!multirotor_properties) { return make_error("No multi properties found"); } if (!m_simulation.init(1000)) { return make_error("Cannot initialize simulator world"); } if (!m_simulation.init_uav(multirotor_properties)) { return make_error("Cannot initialize UAV simulator"); } m_input_throttle_streams.resize(multirotor_properties->get_motors().size()); m_input_throttle_stream_paths.resize(multirotor_properties->get_motors().size()); m_angular_velocity_stream->rate = m_descriptor->get_angular_velocity_rate(); m_angular_velocity_stream->dt = std::chrono::microseconds(1000000 / m_angular_velocity_stream->rate); m_acceleration_stream->rate = m_descriptor->get_acceleration_rate(); m_acceleration_stream->dt = std::chrono::microseconds(1000000 / m_acceleration_stream->rate); m_magnetic_field_stream->rate = m_descriptor->get_magnetic_field_rate(); m_magnetic_field_stream->dt = std::chrono::microseconds(1000000 / m_magnetic_field_stream->rate); m_pressure_stream->rate = m_descriptor->get_pressure_rate(); m_pressure_stream->dt = std::chrono::microseconds(1000000 / m_pressure_stream->rate); m_temperature_stream->rate = m_descriptor->get_temperature_rate(); m_temperature_stream->dt = std::chrono::microseconds(1000000 / m_temperature_stream->rate); m_distance_stream->rate = m_descriptor->get_distance_rate(); m_distance_stream->dt = std::chrono::microseconds(1000000 / m_distance_stream->rate); m_gps_info_stream->rate = m_descriptor->get_gps_rate(); m_gps_info_stream->dt = std::chrono::microseconds(1000000 / m_gps_info_stream->rate); m_ecef_position_stream->rate = m_descriptor->get_gps_rate(); m_ecef_position_stream->dt = std::chrono::microseconds(1000000 / m_ecef_position_stream->rate); m_ecef_velocity_stream->rate = m_descriptor->get_gps_rate(); m_ecef_velocity_stream->dt = std::chrono::microseconds(1000000 / m_ecef_velocity_stream->rate); m_simulator_state_stream->set_rate(30); return ts::success; } ts::Result<void> Multirotor_Simulator::start(Clock::time_point tp) { m_last_tp = tp; m_simulator_state_stream->set_tp(tp); return ts::success; } std::vector<INode::Input> Multirotor_Simulator::get_inputs() const { std::vector<Input> inputs(m_input_throttle_streams.size() + 1); for (size_t i = 0; i < m_input_throttle_streams.size(); i++) { inputs[i].type = stream::IThrottle::TYPE; inputs[i].rate = m_descriptor->get_throttle_rate(); inputs[i].name = q::util::format<std::string>("throttle_{}", i); inputs[i].stream_path = m_input_throttle_stream_paths[i]; } inputs.back().type = stream::IMultirotor_State::TYPE; inputs.back().rate = m_descriptor->get_state_rate(); inputs.back().name = "state"; inputs.back().stream_path = m_input_state_stream_path; return inputs; } std::vector<INode::Output> Multirotor_Simulator::get_outputs() const { std::vector<Output> outputs = { {"angular_velocity", m_angular_velocity_stream}, {"acceleration", m_acceleration_stream}, {"magnetic_field", m_magnetic_field_stream}, {"pressure", m_pressure_stream}, {"temperature", m_temperature_stream}, {"sonar_distance", m_distance_stream}, {"gps_info", m_gps_info_stream}, {"gps_position", m_ecef_position_stream}, {"gps_velocity", m_ecef_velocity_stream}, {"simulator_state", m_simulator_state_stream}, }; return outputs; } void Multirotor_Simulator::process() { QLOG_TOPIC("multirotor_simulator::process"); m_angular_velocity_stream->samples.clear(); m_acceleration_stream->samples.clear(); m_magnetic_field_stream->samples.clear(); m_pressure_stream->samples.clear(); m_temperature_stream->samples.clear(); m_distance_stream->samples.clear(); m_gps_info_stream->samples.clear(); m_ecef_position_stream->samples.clear(); m_ecef_velocity_stream->samples.clear(); m_simulator_state_stream->clear(); for (size_t i = 0; i < m_input_throttle_streams.size(); i++) { std::shared_ptr<stream::IThrottle> stream = m_input_throttle_streams[i].lock(); if (stream) { std::vector<stream::IThrottle::Sample> const& samples = stream->get_samples(); if (!samples.empty()) { m_simulation.set_motor_throttle(i, samples.back().value); } } } { std::shared_ptr<stream::IMultirotor_State> stream = m_input_state_stream.lock(); if (stream) { std::vector<stream::IMultirotor_State::Sample> const& samples = stream->get_samples(); if (!samples.empty()) { m_multirotor_state = samples.back().value; } } } Clock::time_point now = Clock::now(); Clock::duration dt = now - m_last_tp; if (dt < std::chrono::milliseconds(1)) { return; } m_last_tp = now; static const util::coordinates::LLA origin_lla(math::radians(41.390205), math::radians(2.154007), 37.5); math::trans3dd enu_to_ecef_trans = util::coordinates::enu_to_ecef_transform(origin_lla); math::mat3d enu_to_ecef_rotation = util::coordinates::enu_to_ecef_rotation(origin_lla); m_simulation.process(dt, [this, &enu_to_ecef_trans, &enu_to_ecef_rotation](Multirotor_Simulation& simulation, Clock::duration simulation_dt) { Multirotor_Simulation::State const& uav_state = simulation.get_state(); { Angular_Velocity& stream = *m_angular_velocity_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { math::vec3f noise(m_noise.angular_velocity(m_noise.generator), m_noise.angular_velocity(m_noise.generator), m_noise.angular_velocity(m_noise.generator)); stream.accumulated_dt -= stream.dt; stream.last_sample.value = uav_state.angular_velocity + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { Acceleration& stream = *m_acceleration_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { math::vec3f noise(m_noise.acceleration(m_noise.generator), m_noise.acceleration(m_noise.generator), m_noise.acceleration(m_noise.generator)); stream.accumulated_dt -= stream.dt; stream.last_sample.value = uav_state.acceleration + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { Magnetic_Field& stream = *m_magnetic_field_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { math::vec3f noise(m_noise.magnetic_field(m_noise.generator), m_noise.magnetic_field(m_noise.generator), m_noise.magnetic_field(m_noise.generator)); stream.accumulated_dt -= stream.dt; QASSERT(math::is_finite(uav_state.magnetic_field)); QASSERT(!math::is_zero(uav_state.magnetic_field, math::epsilon<float>())); stream.last_sample.value = uav_state.magnetic_field + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { Pressure& stream = *m_pressure_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { double noise = m_noise.pressure(m_noise.generator); stream.accumulated_dt -= stream.dt; stream.last_sample.value = uav_state.pressure + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { Temperature& stream = *m_temperature_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { float noise = m_noise.temperature(m_noise.generator); stream.accumulated_dt -= stream.dt; stream.last_sample.value = uav_state.temperature + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { Distance& stream = *m_distance_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { float noise = m_noise.ground_distance(m_noise.generator); stream.accumulated_dt -= stream.dt; stream.last_sample.value = uav_state.proximity_distance + noise; stream.last_sample.is_healthy = !math::is_zero(uav_state.proximity_distance, std::numeric_limits<float>::epsilon()); stream.samples.push_back(stream.last_sample); } } { GPS_Info& stream = *m_gps_info_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { stream.accumulated_dt -= stream.dt; stream.last_sample.value.fix = stream::IGPS_Info::Value::Fix::FIX_3D; stream.last_sample.value.visible_satellites = 4; stream.last_sample.value.fix_satellites = 4; stream.last_sample.value.pacc = m_noise.gps_pacc(m_noise.generator); stream.last_sample.value.vacc = m_noise.gps_vacc(m_noise.generator); stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { ECEF_Position& stream = *m_ecef_position_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { math::vec3d noise(m_noise.gps_position(m_noise.generator), m_noise.gps_position(m_noise.generator), m_noise.gps_position(m_noise.generator)); stream.accumulated_dt -= stream.dt; stream.last_sample.value = math::transform(enu_to_ecef_trans, math::vec3d(uav_state.enu_position)) + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } { ECEF_Velocity& stream = *m_ecef_velocity_stream; stream.accumulated_dt += simulation_dt; while (stream.accumulated_dt >= stream.dt) { math::vec3f noise(m_noise.gps_velocity(m_noise.generator), m_noise.gps_velocity(m_noise.generator), m_noise.gps_velocity(m_noise.generator)); stream.accumulated_dt -= stream.dt; stream.last_sample.value = math::vec3f(math::transform(enu_to_ecef_rotation, math::vec3d(uav_state.enu_velocity))) + noise; stream.last_sample.is_healthy = true; stream.samples.push_back(stream.last_sample); } } }); { size_t samples_needed = m_simulator_state_stream->compute_samples_needed(); Multirotor_Simulation::State simulation_state = m_simulation.get_state(); simulation_state.multirotor_state = m_multirotor_state; for (size_t i = 0; i < samples_needed; i++) { m_simulator_state_stream->push_sample(simulation_state, true); } } } ts::Result<void> Multirotor_Simulator::set_input_stream_path(size_t idx, std::string const& path) { if (idx < m_input_throttle_streams.size()) { m_input_throttle_streams[idx].reset(); m_input_throttle_stream_paths[idx].clear(); if (!path.empty()) { std::shared_ptr<stream::IThrottle> input_stream = m_hal.get_stream_registry().find_by_name<stream::IThrottle>(path); if (input_stream) { uint32_t rate = input_stream->get_rate(); if (rate != m_descriptor->get_throttle_rate()) { return make_error("Bad input stream '{}'. Expected rate {}Hz, got {}Hz", path, m_descriptor->get_throttle_rate(), rate); } else { m_input_throttle_streams[idx] = input_stream; m_input_throttle_stream_paths[idx] = path; } } else { return make_error("Cannot find stream '{}'", path); } } } else { m_input_state_stream.reset(); m_input_state_stream_path.clear(); if (!path.empty()) { std::shared_ptr<stream::IMultirotor_State> input_stream = m_hal.get_stream_registry().find_by_name<stream::IMultirotor_State>(path); if (input_stream) { uint32_t rate = input_stream->get_rate(); if (rate != m_descriptor->get_state_rate()) { return make_error("Bad input stream '{}'. Expected rate {}Hz, got {}Hz", path, m_descriptor->get_state_rate(), rate); } else { m_input_state_stream = input_stream; m_input_state_stream_path = path; } } else { return make_error("Cannot find stream '{}'", path); } } } return ts::success; } ts::Result<void> Multirotor_Simulator::set_config(hal::INode_Config const& config) { QLOG_TOPIC("multirotor_simulator::set_config"); auto specialized = dynamic_cast<hal::Multirotor_Simulator_Config const*>(&config); if (!specialized) { return make_error("Wrong config type"); } // Simulation::UAV_Config uav_config; // uav_config.mass = sz.uav.mass; // uav_config.radius = sz.uav.radius; // uav_config.height = sz.uav.height; // uav_config.motors.resize(sz.motors.size()); // for (size_t i = 0; i < uav_config.motors.size(); i++) // { // uav_config.motors[i].position = sz.motors[i].position; // uav_config.motors[i].clockwise = sz.motors[i].clockwise; // uav_config.motors[i].max_thrust = sz.motors[i].max_thrust; // uav_config.motors[i].max_rpm = sz.motors[i].max_rpm; // uav_config.motors[i].acceleration = sz.motors[i].acceleration; // uav_config.motors[i].deceleration = sz.motors[i].deceleration; // } std::shared_ptr<const IMultirotor_Properties> multirotor_properties = m_hal.get_specialized_uav_properties<IMultirotor_Properties>(); if (!multirotor_properties) { return make_error("No multi properties found"); } if (!m_simulation.init_uav(multirotor_properties)) { return make_error("Cannot configure UAV simulator"); } *m_config = *specialized; m_simulation.set_gravity_enabled(m_config->get_gravity_enabled()); m_simulation.set_ground_enabled(m_config->get_ground_enabled()); m_simulation.set_drag_enabled(m_config->get_drag_enabled()); m_simulation.set_simulation_enabled(m_config->get_simulation_enabled()); auto const& noise = m_config->get_noise(); m_noise.gps_position = Noise::Distribution<float>(-noise.get_gps_position()*0.5f, noise.get_gps_position()*0.5f); m_noise.gps_velocity = Noise::Distribution<float>(-noise.get_gps_velocity()*0.5f, noise.get_gps_velocity()*0.5f); m_noise.gps_pacc = Noise::Distribution<float>(-noise.get_gps_pacc()*0.5f, noise.get_gps_pacc()*0.5f); m_noise.gps_vacc = Noise::Distribution<float>(-noise.get_gps_vacc()*0.5f, noise.get_gps_vacc()*0.5f); m_noise.acceleration = Noise::Distribution<float>(-noise.get_acceleration()*0.5f, noise.get_acceleration()*0.5f); m_noise.angular_velocity = Noise::Distribution<float>(-noise.get_angular_velocity()*0.5f, noise.get_angular_velocity()*0.5f); m_noise.magnetic_field = Noise::Distribution<float>(-noise.get_magnetic_field()*0.5f, noise.get_magnetic_field()*0.5f); m_noise.pressure = Noise::Distribution<float>(-noise.get_pressure()*0.5f, noise.get_pressure()*0.5f); m_noise.temperature = Noise::Distribution<float>(-noise.get_temperature()*0.5f, noise.get_temperature()*0.5f); m_noise.ground_distance = Noise::Distribution<float>(-noise.get_ground_distance()*0.5f, noise.get_ground_distance()*0.5f); return ts::success; } std::shared_ptr<const hal::INode_Config> Multirotor_Simulator::get_config() const { return m_config; } std::shared_ptr<const hal::INode_Descriptor> Multirotor_Simulator::get_descriptor() const { return m_descriptor; } ts::Result<std::shared_ptr<messages::INode_Message>> Multirotor_Simulator::send_message(messages::INode_Message const& _message) { if (dynamic_cast<messages::Multirotor_Simulator_Reset_Message const*>(&_message)) { m_simulation.reset(); return nullptr; } else if (dynamic_cast<messages::Multirotor_Simulator_Stop_Motion_Message const*>(&_message)) { m_simulation.stop_motion(); return nullptr; } else if (messages::Multirotor_Simulator_Set_Gravity_Enabled_Message const* message = dynamic_cast<messages::Multirotor_Simulator_Set_Gravity_Enabled_Message const*>(&_message)) { m_simulation.set_gravity_enabled(message->get_enabled()); return nullptr; } else if (messages::Multirotor_Simulator_Set_Ground_Enabled_Message const* message = dynamic_cast<messages::Multirotor_Simulator_Set_Ground_Enabled_Message const*>(&_message)) { m_simulation.set_ground_enabled(message->get_enabled()); return nullptr; } else if (messages::Multirotor_Simulator_Set_Simulation_Enabled_Message const* message = dynamic_cast<messages::Multirotor_Simulator_Set_Simulation_Enabled_Message const*>(&_message)) { m_simulation.set_simulation_enabled(message->get_enabled()); return nullptr; } else if (messages::Multirotor_Simulator_Set_Drag_Enabled_Message const* message = dynamic_cast<messages::Multirotor_Simulator_Set_Drag_Enabled_Message const*>(&_message)) { m_simulation.set_drag_enabled(message->get_enabled()); return nullptr; } else { return make_error("Unknown message"); } } } }
41.650924
186
0.659288
jeanleflambeur
1f724206e509b40fb4649375e29fdf9d04580c76
836
cpp
C++
example/thread_pool_example.cpp
yksz/cpp-concurrent-library
c8943b21d9e578673199f29ff8316109445fe93d
[ "MIT" ]
null
null
null
example/thread_pool_example.cpp
yksz/cpp-concurrent-library
c8943b21d9e578673199f29ff8316109445fe93d
[ "MIT" ]
null
null
null
example/thread_pool_example.cpp
yksz/cpp-concurrent-library
c8943b21d9e578673199f29ff8316109445fe93d
[ "MIT" ]
null
null
null
#include <iostream> #include <mutex> #include "ccl/thread_pool.h" static const int kNthreads = 2; static const int kDispatchCount = 5; int main(void) { std::mutex mutex; int count = 0; { ccl::ThreadPool pool(kNthreads); for (int i = 0; i < kDispatchCount; i++) { pool.Dispatch([&]() { { std::lock_guard<std::mutex> lock(mutex); std::cout << "Thread_" << std::this_thread::get_id() << ": count=" << count << std::endl; count++; } }); } } // wait for all tasks to complete // Output: // Thread_<ID>: count=0 // Thread_<ID>: count=1 // Thread_<ID>: count=2 // Thread_<ID>: count=3 // Thread_<ID>: count=4 return 0; }
23.885714
72
0.473684
yksz
1f73b02e82ecf6ec931d8604e11cc837e47ace7d
6,897
hh
C++
core/include/milan/core/Histogram.hh
matt-komm/milan-alpha
b6affa5541ca6b01384ab57256983a9fe7e1689c
[ "MIT" ]
null
null
null
core/include/milan/core/Histogram.hh
matt-komm/milan-alpha
b6affa5541ca6b01384ab57256983a9fe7e1689c
[ "MIT" ]
null
null
null
core/include/milan/core/Histogram.hh
matt-komm/milan-alpha
b6affa5541ca6b01384ab57256983a9fe7e1689c
[ "MIT" ]
null
null
null
#ifndef __MILAN_CORE_HISTOGRAM_H__ #define __MILAN_CORE_HISTOGRAM_H__ #include "milan/core/Types.hh" #include "milan/core/Binning.hh" #include "milan/core/Exception.hh" #include "milan/core/HistogramInterface.hh" #include "milan/core/Parameter.hh" #include "milan/core/Ptr.hh" #include "milan/core/HistogramFunction.hh" #include <array> #include <cmath> #include <vector> namespace milan { class Histogram: public HistogramInterface, public PtrInterface<HistogramInterface,Histogram> { protected: std::vector<Binning> _binning; std::vector<double> _content; std::vector<double> _error2; public: Histogram(const std::vector<Binning>& binning): _binning(binning) { sizetype N = 1; for (sizetype idim = 0; idim < _binning.size(); ++idim) { //add 2 to account for over- & underflow N*=_binning[idim].size()+2; } _content = std::vector<double>(N,0); _error2 = std::vector<double>(N,0); } Histogram(const Histogram& histogram): _binning(histogram._binning), _content(histogram._content), _error2(histogram._error2) { } Histogram& operator=(const Histogram& histogram) { _binning = histogram._binning; _content = histogram._content; _error2 = histogram._error2; return *this; } Histogram(Histogram&& histogram): _binning(std::move(histogram._binning)), _content(std::move(histogram._content)), _error2(std::move(histogram._error2)) { } Histogram& operator=(Histogram&& histogram) { _binning = std::move(histogram._binning); _content = std::move(histogram._content); _error2 = std::move(histogram._error2); return *this; } virtual sizetype size() const { return _content.size(); } inline double getContent(const std::vector<sizetype>& index) const { return _content[getGlobalBinFromIndex(index)]; } inline void setContent(const std::vector<sizetype>& index, const double& value) { _content[getGlobalBinFromIndex(index)] = value; } inline void setContent(const sizetype& globalIndex, const double& value) { _content[globalIndex] = value; } inline double getError(const std::vector<sizetype>& index) const { return std::sqrt(getError2(index)); } inline double getError2(const std::vector<sizetype>& index) const { return _error2[getGlobalBinFromIndex(index)]; } inline void setError(const std::vector<sizetype>& index, const double& error) { setError2(index,error*error); } inline void setError2(const std::vector<sizetype>& index, const double& error2) { if (error2<0.0) { milan_throw("Error2 of a histogram needs to be positive - not ",error2,"!"); } _error2[getGlobalBinFromIndex(index)] = error2; } inline void setError2(sizetype index, double error2) { if (error2<0.0) { milan_throw("Error2 of a histogram needs to be positive - not ",error2,"!"); } _error2[index]=error2; } inline const Binning& getBinning(const sizetype& idim) const { return _binning[idim]; } virtual const std::vector<Binning>& getBinningVector() const { return _binning; } sizetype getGlobalBinFromIndex(const std::vector<sizetype>& index) const { sizetype globalIndex = 0; sizetype offset = 1; for (sizetype idim = 0; idim < _binning.size(); ++idim) { globalIndex+=index[idim]*offset; offset*=_binning[idim].size()+2; } return globalIndex; } inline std::vector<sizetype> findIndexFromValue(const std::vector<double>& value) const { std::vector<sizetype> index(_binning.size(),0); for (sizetype idim = 0; idim < _binning.size(); ++idim) { index[idim]=_binning[idim].findBin(value[idim]); } return index; } inline sizetype findGlobalBinFromValue(const std::vector<double>& value) const { return getGlobalBinFromIndex(findIndexFromValue(value)); } virtual double getContent(sizetype index) const { return _content[index]; } virtual double getDerivative(sizetype, const Ptr<Parameter>&) const { return 0.0; } virtual double getError2(sizetype index) const { return std::max(0.0,_error2[index]); } Histogram operator+(const Histogram& rhs) const { Histogram result(*this); //copy for (sizetype ibin = 0; ibin < result._content.size(); ++ibin) { result._content[ibin]+=rhs._content[ibin]; result._error2[ibin]+=rhs._error2[ibin]; } return result; } Histogram operator-(const Histogram& rhs) const { Histogram result(*this); //copy for (sizetype ibin = 0; ibin < result._content.size(); ++ibin) { result._content[ibin]-=rhs._content[ibin]; result._error2[ibin]+=rhs._error2[ibin]; } return result; } Histogram operator*(double factor) const { Histogram result(*this); //copy for (sizetype ibin = 0; ibin < result._content.size(); ++ibin) { result._content[ibin]*=factor; result._error2[ibin]*=factor; } return result; } Histogram operator/(double factor) const { Histogram result(*this); //copy for (sizetype ibin = 0; ibin < result._content.size(); ++ibin) { result._content[ibin]/=factor; result._error2[ibin]/=factor; } return result; } inline operator HistogramFunction() const { return copy(); } virtual ~Histogram() { } }; } #endif
29.348936
95
0.521676
matt-komm
1f76750029ddeb8f5cbc496a2c559c72fafceb3d
452
hpp
C++
cpp-projects/nodes/nodes/ConnectionPainter.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/nodes/nodes/ConnectionPainter.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/nodes/nodes/ConnectionPainter.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
1
2021-07-06T14:47:41.000Z
2021-07-06T14:47:41.000Z
#pragma once // Qt #include <QtGui/QPainter> #include <QIcon> namespace QtNodes{ class ConnectionGeometry; class ConnectionState; class Connection; class ConnectionPainter{ public: static void paint(QPainter* painter, Connection const& connection); static QPainterPath getPainterStroke(ConnectionGeometry const& geom); static inline QIcon icon = QIcon(":convert.png"); static inline std::unique_ptr<QPixmap> pixmap = nullptr; }; }
20.545455
73
0.75885
FlorianLance
1f7774d46f44223449aabf9c5a31c523abc5ae16
27,947
cpp
C++
EncodePNG/main.cpp
cdyk/debris
cb820b54f5d541d18fb9c3058afbe0dd7670da8b
[ "MIT" ]
null
null
null
EncodePNG/main.cpp
cdyk/debris
cb820b54f5d541d18fb9c3058afbe0dd7670da8b
[ "MIT" ]
null
null
null
EncodePNG/main.cpp
cdyk/debris
cb820b54f5d541d18fb9c3058afbe0dd7670da8b
[ "MIT" ]
null
null
null
#if 0 // FIXME: add zlib dependency. #include <vector> #include <zlib.h> #include <fstream> #include <iostream> #include <cstdlib> #include <cmath> #include <stdexcept> #include <time.h> #include <xmmintrin.h> #include <smmintrin.h> #define WIDTH 1024 //6 #define HEIGHT 768 class TimeStamp { public: TimeStamp() { clock_gettime(CLOCK_MONOTONIC, &m_time); } static double delta(const TimeStamp& start, const TimeStamp& stop) { timespec delta; if ((stop.m_time.tv_nsec - start.m_time.tv_nsec) < 0) { delta.tv_sec = stop.m_time.tv_sec - start.m_time.tv_sec - 1; delta.tv_nsec = 1000000000 + stop.m_time.tv_nsec - start.m_time.tv_nsec; } else { delta.tv_sec = stop.m_time.tv_sec - start.m_time.tv_sec; delta.tv_nsec = stop.m_time.tv_nsec - start.m_time.tv_nsec; } return delta.tv_sec + 1e-9*delta.tv_nsec; } protected: timespec m_time; }; class BitPusher { public: BitPusher(std::vector<unsigned char>& data) : m_data(data), m_pending_data(0u), m_pending_count(0u) {} ~BitPusher() { while (m_pending_count >= 8u) { m_data.push_back(m_pending_data); m_pending_data = m_pending_data >> 8u; m_pending_count -= 8u; } if (m_pending_count) { m_data.push_back(m_pending_data); } } void pushBits(unsigned long long int bits, unsigned int count) { m_pending_data = m_pending_data | (bits << m_pending_count); m_pending_count += count; while (m_pending_count >= 8u) { m_data.push_back(m_pending_data); m_pending_data = m_pending_data >> 8u; m_pending_count -= 8u; } } void pushBitsReverse(unsigned long long int bits, unsigned int count) { //std::cerr << "pushing " << count << " bits:\t"; //for(int i=0; i<count; i++) { // std::cerr << ((bits>>(count-i-1))&1); //} //std::cerr << "\n"; bits = bits << (64 - count); bits = ((bits & 0x5555555555555555ull) << 1) | ((bits >> 1) & 0x5555555555555555ull); bits = ((bits & 0x3333333333333333ull) << 2) | ((bits >> 2) & 0x3333333333333333ull); bits = ((bits & 0x0F0F0F0F0F0F0F0Full) << 4) | ((bits >> 4) & 0x0F0F0F0F0F0F0F0Full); bits = ((bits & 0x00FF00FF00FF00FFull) << 8) | ((bits >> 8) & 0x00FF00FF00FF00FFull); bits = ((bits & 0x0000FFFF0000FFFFull) << 16) | ((bits >> 16) & 0x0000FFFF0000FFFFull); bits = ((bits & 0x00000000FFFFFFFFull) << 32) | ((bits >> 32) & 0x00000000FFFFFFFFull); pushBits(bits, count); } protected: std::vector<unsigned char>& m_data; unsigned long long int m_pending_data; unsigned int m_pending_count; }; void encodeCount(unsigned int& bits, unsigned int& bits_n, unsigned int count) { //std::cerr << "count=" << count << " "; uint q = 0; if (count < 3) { abort(); // no copies, 1 or 2 never occurs. } else if (count < 11) { unsigned int t = count - 3; t = (t & 0x07u) + ((257 - 256) << 0); bits = (bits << 7) | t; // 7-bit count code bits_n += 7; } else if (count < 19) { // count=11..18, code=265..268, 1 extra bit int t = count - 11; q = (t & 0x01u) << (8 - 1); t = (t & 0x06u) + ((265 - 256) << 1); bits = (bits << 8) | t; bits_n += 8; } else if (count < 35) { // count=19..34, code=269..272, 2 extra bits int t = count - 19; q = (t & 0x03u) << (8 - 2); t = (t & 0x0Cu) + ((269 - 256) << 2); bits = (bits << 9) | t; bits_n += 9; } else if (count < 67) { // c=35..66, code=273..276, 3 extra bits int t = count - 35; q = (t & 0x07u) << (8 - 3); t = (t & 0x18u) + ((273 - 256) << 3); bits = (bits << 10) | t; bits_n += 10; } else if (count < 115) { // c=67..114, 7-bit code=277..279, 4 extra bits int t = count - 67; q = (t & 0x0Fu) << (8 - 4); t = (t & 0x30u) + ((277 - 256) << 4); bits = (bits << 11) | t; bits_n += 11; } else if (count < 131) { // c=115..130, 8-bit code=280, 4 extra bits int t = count - 115; q = (t & 0x0Fu) << (8 - 4); t = (t & 0x30u) + ((280 - 280 + 0xc0) << 4); bits = (bits << 12) | t; bits_n += 12; } else if (count < 258) { // c=131..257, code=281..284, 5 extra bits int t = count - 131; bits = (bits << 12) | ((t&(0xff << 5)) + ((281 - 280 + 0xc0) << 5)); q = (t & 0x1Fu) << (8 - 5); bits_n += 13; } else if (count < 259) { bits = (bits << 8) | (285 - 280 + 0xc0); bits_n += 8; } else { std::cerr << "unsupported count " << count << "\n"; abort(); } q = ((q & 0x55u) << 1) | ((q >> 1) & 0x55u); q = ((q & 0x33u) << 2) | ((q >> 2) & 0x33u); q = ((q & 0x0Fu) << 4) | ((q >> 4) & 0x0Fu); bits = bits | q; } void encodeDistance(unsigned int& bits, unsigned int& bits_n, unsigned int distance) { //std::cerr << "distance=" << distance << " "; uint q = 0; if (distance < 1) { std::cerr << "unsupported distance " << distance << "\n"; abort(); } else if (distance < 5) { // d=1..4, code=0..3, 0 extra bits bits = (bits << 5) | (distance - 1); bits_n += 5; } else if (distance < 9) { // d=5..8, code=4..5, 1 extra bit unsigned int t = distance - 5; bits = (bits << 6) | ((t&(0x1f << 1)) + (4 << 1)); q = (t & 1u) << (32 - 1); bits_n += 6; } else if (distance < 17) { // d=9..16, code=6..7, 2 extra bits unsigned int t = distance - 9; bits = (bits << 7) | ((t&(0x1 << 2)) + (6 << 2)); q = (t & 3u) << (32 - 2); bits_n += 7; } else if (distance < 33) { // d=17..32, code=8..9, 3 extra bits unsigned int t = distance - 17; bits = (bits << 8) | ((t&(0x1 << 3)) + (8 << 3)); q = (t & 7u) << (32 - 3); bits_n += 8; } else if (distance < 65) { // d=33..64, code=10..11, 4 extra bits unsigned int t = distance - 33; bits = (bits << 9) | ((t&(0x1 << 4)) + (10 << 4)); q = (t & 0xFu) << (32 - 4); bits_n += 9; } else if (distance < 129) { // d=65..128, code=12..13, 5 extra bits unsigned int t = distance - 65; bits = (bits << 10) | ((t&(0x1 << 5)) + (12 << 5)); q = (t & 0x1Fu) << (32 - 5); bits_n += 10; } else if (distance < 257) { // d=129..256, code=14,15, 6 extra bits unsigned int t = distance - 129; q = (t & 0x3Fu) << (32 - 6); t = (t & 0x40u) + (14 << 6); bits = (bits << 11) | t; bits_n += 11; } else if (distance < 513) { // d=257..512, code 16..17, 7 extra bits unsigned int t = distance - 257; q = (t & 0x7Fu) << (32 - 7); t = (t & 0x80u) + (16 << 7); bits = (bits << 12) | t; bits_n += 12; } else if (distance < 1025) { // d=257..512, code 18..19, 8 extra bits unsigned int t = distance - 513; q = (t & 0x0FFu) << (32 - 8); t = (t & 0x100u) + (18 << 8); bits = (bits << 13) | t; bits_n += 13; } else if (distance < 2049) { // d=1025..2048, code 20..21, 9 extra bits unsigned int t = distance - 1025; q = (t & 0x1FFu) << (32 - 9); t = (t & 0x200u) + (20 << 9); bits = (bits << 14) | t; bits_n += 14; } else if (distance < 4097) { // d=2049..4096, code 22..23, 10 extra bits unsigned int t = distance - 2049; q = (t & 0x3FFu) << (32 - 10); t = (t & 0x400u) + (22 << 10); bits = (bits << 15) | t; bits_n += 15; } else if (distance < 8193) { // d=4097..8192, code 24..25, 11 extra bits unsigned int t = distance - 4097; q = (t & 0x7FFu) << (32 - 11); t = (t & 0x800u) + (24 << 11); bits = (bits << 16) | t; bits_n += 16; } else if (distance < 16385) { // d=8193..16384, code 26..27, 12 extra bits unsigned int t = distance - 8193; q = (t & 0x0FFFu) << (32 - 12); t = (t & 0x1000u) + (26 << 12); bits = (bits << 17) | t; bits_n += 17; } else if (distance < 32769) { // d=16385..32768, code 28..29, 13 extra bits unsigned int t = distance - 16385; q = (t & 0x1FFFu) << (32 - 13); t = (t & 0x2000u) + (28 << 13); bits = (bits << 18) | t; bits_n += 18; } else { std::cerr << "Illegal " << distance << "\n"; abort(); } q = ((q & 0x55555555u) << 1) | ((q >> 1) & 0x55555555u); q = ((q & 0x33333333u) << 2) | ((q >> 2) & 0x33333333u); q = ((q & 0x0F0F0F0Fu) << 4) | ((q >> 4) & 0x0F0F0F0Fu); q = ((q & 0x00FF00FFu) << 8) | ((q >> 8) & 0x00FF00FFu); q = ((q & 0x0000FFFFu) << 16) | ((q >> 16) & 0x0000FFFFu); bits = bits | q; } void encodeLiteralTriplet(unsigned int& bits, unsigned int& bits_n, unsigned int rgb) { //std::cerr << "literal=" << rgb << " "; unsigned int t = (rgb >> 16) & 0xffu; if (t < 144) { bits = (t + 48); bits_n = 8; } else { bits = (t + 256); bits_n = 9; } t = (rgb >> 8) & 0xffu; if (t < 144) { bits = (bits << 8) | (t + 48); bits_n += 8; } else { bits = (bits << 9) | (t + 256); bits_n += 9; } t = (rgb) & 0xffu; if (t < 144) { bits = (bits << 8) | (t + 48); bits_n += 8; } else { bits = (bits << 9) | (t + 256); bits_n += 9; } } unsigned long int CRC(const std::vector<unsigned long>& crc_table, const unsigned char* p, size_t length) { size_t i; unsigned long int crc = 0xffffffffl; for (i = 0; i < length; i++) { unsigned int ix = (p[i] ^ crc) & 0xff; crc = crc_table[ix] ^ ((crc >> 8)); } return ~crc; } void writeIDAT3(std::ofstream& file, const std::vector<unsigned char>& img, const std::vector<unsigned long>& crc_table) { TimeStamp start; std::vector<unsigned char> IDAT(8); // IDAT chunk header IDAT[4] = 'I'; IDAT[5] = 'D'; IDAT[6] = 'A'; IDAT[7] = 'T'; // --- create deflate chunk ------------------------------------------------ IDAT.push_back(8 + (7 << 4)); // CM=8=deflate, CINFO=7=32K window size = 112 IDAT.push_back(94 /* 28*/); // FLG unsigned int dat_size; unsigned int s1 = 1; unsigned int s2 = 0; { BitPusher pusher(IDAT); pusher.pushBitsReverse(6, 3); // 5 = 101 std::vector<unsigned int> buffer(WIDTH * 5, ~0u); unsigned int* zrows[4] = { buffer.data(), buffer.data() + WIDTH, buffer.data() + 2 * WIDTH, buffer.data() + 3 * WIDTH, }; unsigned int o = 0; for (int j = 0; j < HEIGHT; j++) { unsigned int* rows[4] = { zrows[(j + 3) & 1], zrows[(j + 2) & 1], zrows[(j + 1) & 1], zrows[j & 1] }; // unsigned int* p_row = rows[ j&1 ]; //unsigned int* c_row = rows[ (j+1)&1 ]; pusher.pushBitsReverse(0 + 48, 8); // Push png scanline filter s1 += 0; // update adler 1 & 2 s2 += s1; int match_src_i = 0; int match_src_j = 0; int match_dst_i = 0; int match_dst_o = 0; // used for debugging int match_length = 0; //std::cerr << o << "---\n"; o++; for (int i = 0; i < WIDTH; i++) { unsigned int R = img[3 * (WIDTH*j + i) + 0]; unsigned int G = img[3 * (WIDTH*j + i) + 1]; unsigned int B = img[3 * (WIDTH*j + i) + 2]; unsigned int RGB = (R << 16) | (G << 8) | B; s1 = (s1 + R); s2 = (s2 + s1); s1 = (s1 + G); s2 = (s2 + s1); s1 = (s1 + B); s2 = (s2 + s1); //std::cerr << o << ":\t" << RGB << "\t"; rows[0][i] = RGB; bool redo; do { redo = false; bool emit_match = false; bool emit_verbatim = false; if (match_length == 0) { // We have no running matching, try to find candidate int k; match_src_j = 0; for (k = i - 1; (k >= 0) && (rows[0][k] != RGB); k--) {} if (k < 0) { match_src_j = 1; for (k = WIDTH - 1; (k >= 0) && (rows[1][k] != RGB); k--) {} } if (k >= 0) { // Found match, match_src_i = k; match_dst_i = i; match_dst_o = o; match_length = 1; if (i == WIDTH - 1) { emit_match = true; } } else { emit_verbatim = true; } } else { // We are matching if (match_length >= 86) { // Max matchlength is 86*3=258, flush and continue emit_match = true; redo = true; } else if ((match_src_i + match_length < WIDTH) && // don't match outside scanline (rows[match_src_j][match_src_i + match_length] == RGB)) // check if matching { match_length = match_length + 1; if (i == WIDTH - 1) { emit_match = true; } } else { emit_match = true; redo = true; // try to find new match source int k = match_src_i - 1; for (int m = match_src_j; (emit_match) && (m < 2); m++) { for (; (emit_match) && (k >= 0); k--) { bool fail = false; for (int l = 0; l <= match_length; l++) { if (rows[0][match_dst_i + l] != rows[m][k + l]) { fail = true; break; } } if (!fail) { match_src_j = m; match_src_i = k; match_length = match_length + 1; emit_match = false; redo = false; break; } } k = WIDTH - 1; } } } if (((i == WIDTH - 1) && (match_length)) || emit_match) { unsigned int bits = 0; unsigned int bits_n = 0; unsigned int count = 3 * match_length; encodeCount(bits, bits_n, count); pusher.pushBitsReverse(bits, bits_n); bits = 0; bits_n = 0; unsigned int distance = 3 * (match_dst_i - match_src_i); if (match_src_j > 0) { distance += 3 * WIDTH + 1; } encodeDistance(bits, bits_n, distance); pusher.pushBitsReverse(bits, bits_n); match_length = 0; } if (emit_verbatim) { unsigned int bits = 0; unsigned int bits_n = 0; encodeLiteralTriplet(bits, bits_n, RGB); pusher.pushBitsReverse(bits, bits_n); } } while (redo); o += 3; } s1 = s1 % 65521; s2 = s2 % 65521; } pusher.pushBits(0, 7); // EOB } unsigned int adler = (s2 << 16) + s1; IDAT.push_back(((adler) >> 24) & 0xffu); // Adler32 IDAT.push_back(((adler) >> 16) & 0xffu); IDAT.push_back(((adler) >> 8) & 0xffu); IDAT.push_back(((adler) >> 0) & 0xffu); // --- end deflate chunk -------------------------------------------------- // Update PNG chunk content size for IDAT dat_size = IDAT.size() - 8u; IDAT[0] = ((dat_size) >> 24) & 0xffu; IDAT[1] = ((dat_size) >> 16) & 0xffu; IDAT[2] = ((dat_size) >> 8) & 0xffu; IDAT[3] = ((dat_size) >> 0) & 0xffu; unsigned long crc = CRC(crc_table, IDAT.data() + 4, dat_size + 4); IDAT.resize(IDAT.size() + 4u); // make room for CRC IDAT[dat_size + 8] = ((crc) >> 24) & 0xffu; IDAT[dat_size + 9] = ((crc) >> 16) & 0xffu; IDAT[dat_size + 10] = ((crc) >> 8) & 0xffu; IDAT[dat_size + 11] = ((crc) >> 0) & 0xffu; TimeStamp stop; std::cerr << "IDAT3 used " << TimeStamp::delta(start, stop) << "\n"; if (1) { std::vector<unsigned char> quux(10 * 1024 * 1024); z_stream stream; int err; stream.next_in = (z_const Bytef *)IDAT.data() + 8; stream.avail_in = (uInt)IDAT.size() - 8; stream.next_out = quux.data(); stream.avail_out = quux.size(); stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) { std::cerr << "inflateInit failed: " << err << "\n"; abort(); } err = inflate(&stream, Z_FINISH); if (stream.msg != NULL) { std::cerr << stream.msg << "\n"; } uLongf quux_size = quux.size(); err = uncompress(quux.data(), &quux_size, IDAT.data() + 8, IDAT.size() - 8); if (err != Z_OK) { std::cerr << "uncompress=" << err << "\n"; } if (quux_size != ((3 * WIDTH + 1)*HEIGHT)) { std::cerr << "uncompress_size=" << quux_size << ", should be=" << ((3 * WIDTH + 1)*HEIGHT) << "\n"; } } file.write(reinterpret_cast<char*>(IDAT.data()), dat_size + 12); } void createCRCTable(std::vector<unsigned long>& crc_table) { crc_table.resize(256); for (int j = 0; j < 256; j++) { unsigned long int c = j; for (int i = 0; i < 8; i++) { if (c & 0x1) { c = 0xedb88320ul ^ (c >> 1); } else { c = c >> 1; } } crc_table[j] = c; } } void createDummyImage(std::vector<unsigned char>& img) { img.resize(3 * WIDTH*HEIGHT); for (int j = 0; j < HEIGHT; j++) { for (int i = 0; i < WIDTH; i++) { float x = i / (WIDTH / 2.f) - 1.f; float y = j / (HEIGHT / 2.f) - 1.f; float r = sqrt(x*x + y * y); if (r < 0.9f) { img[3 * (WIDTH*j + i) + 0] = 255; img[3 * (WIDTH*j + i) + 1] = 255 * 0.5f*(sinf(30 * r) + 1.f);; img[3 * (WIDTH*j + i) + 2] = 255 * 0.5f*(sinf(40 * r) + 1.f); } else if (r < 1.f) { int q = (int)(200 * r); if (q & 1) { img[3 * (WIDTH*j + i) + 0] = q; img[3 * (WIDTH*j + i) + 1] = 255; img[3 * (WIDTH*j + i) + 2] = 255; } else { img[3 * (WIDTH*j + i) + 0] = 0; img[3 * (WIDTH*j + i) + 1] = q; img[3 * (WIDTH*j + i) + 2] = 0; } } else { img[3 * (WIDTH*j + i) + 0] = 255; img[3 * (WIDTH*j + i) + 1] = 255; img[3 * (WIDTH*j + i) + 2] = 0; } } } } void writeSignature(std::ofstream& file) { unsigned char signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 }; file.write(reinterpret_cast<char*>(signature), sizeof(signature)); } void writeIHDR(std::ofstream& file, const std::vector<unsigned long>& crc_table) { // IHDR chunk, 13 + 12 (length, type, crc) = 25 bytes unsigned char IHDR[25] = { // Chunk length (4 bytes) ((13) >> 24) & 0xffu,((13) >> 16) & 0xffu, ((13) >> 8) & 0xffu, ((13) >> 0) & 0xffu, // Chunk type (4 bytes) 'I', 'H', 'D', 'R', // Image width (4 bytes) ((WIDTH) >> 24) & 0xffu,((WIDTH) >> 16) & 0xffu, ((WIDTH) >> 8) & 0xffu, ((WIDTH) >> 0) & 0xffu, // Image height ((HEIGHT) >> 24) & 0xffu,((HEIGHT) >> 16) & 0xffu, ((HEIGHT) >> 8) & 0xffu, ((HEIGHT) >> 0) & 0xffu, // bits per channel, RGB triple, ..., .., image not interlaced (5 bytes) 8, 2, 0, 0, 0, // CRC of 13+4 bytes 0, 0, 0, 0 }; unsigned long crc = CRC(crc_table, IHDR + 4, 13 + 4); IHDR[21] = ((crc) >> 24) & 0xffu; // image width IHDR[22] = ((crc) >> 16) & 0xffu; IHDR[23] = ((crc) >> 8) & 0xffu; IHDR[24] = ((crc) >> 0) & 0xffu; file.write(reinterpret_cast<char*>(IHDR), sizeof(IHDR)); } void writeIDAT(std::ofstream& file, const std::vector<unsigned char>& img, const std::vector<unsigned long>& crc_table) { TimeStamp start; std::vector<unsigned char> filtered((3 * WIDTH + 1)*HEIGHT); for (int j = 0; j < HEIGHT; j++) { filtered[(3 * WIDTH + 1)*j + 0] = 0; for (int i = 0; i < WIDTH; i++) { filtered[(3 * WIDTH + 1)*j + 1 + 3 * i + 0] = img[3 * WIDTH*j + 3 * i + 0]; filtered[(3 * WIDTH + 1)*j + 1 + 3 * i + 1] = img[3 * WIDTH*j + 3 * i + 1]; filtered[(3 * WIDTH + 1)*j + 1 + 3 * i + 2] = img[3 * WIDTH*j + 3 * i + 2]; } } std::vector<unsigned char> IDAT(16 * 1024 * 1024); uLongf dat_size = IDAT.size() - 12; TimeStamp c_start; int c = compress((Bytef*)(IDAT.data() + 8), &dat_size, (Bytef*)filtered.data(), filtered.size()); TimeStamp c_stop; if (c == Z_MEM_ERROR) { std::cerr << "Z_MEM_ERROR\n"; exit(EXIT_FAILURE); } else if (c == Z_BUF_ERROR) { std::cerr << "Z_BUF_ERROR\n"; exit(EXIT_FAILURE); } IDAT[0] = ((dat_size) >> 24) & 0xffu; IDAT[1] = ((dat_size) >> 16) & 0xffu; IDAT[2] = ((dat_size) >> 8) & 0xffu; IDAT[3] = ((dat_size) >> 0) & 0xffu; IDAT[4] = 'I'; IDAT[5] = 'D'; IDAT[6] = 'A'; IDAT[7] = 'T'; unsigned long crc = CRC(crc_table, IDAT.data() + 4, dat_size + 4); IDAT[dat_size + 8] = ((crc) >> 24) & 0xffu; // image width IDAT[dat_size + 9] = ((crc) >> 16) & 0xffu; IDAT[dat_size + 10] = ((crc) >> 8) & 0xffu; IDAT[dat_size + 11] = ((crc) >> 0) & 0xffu; TimeStamp stop; std::cerr << "IDAT used " << TimeStamp::delta(start, stop) << ", compress used " << TimeStamp::delta(c_start, c_stop) << "\n"; file.write(reinterpret_cast<char*>(IDAT.data()), dat_size + 12); } void writeIDAT2(std::ofstream& file, const std::vector<unsigned char>& img, const std::vector<unsigned long>& crc_table) { TimeStamp start; std::vector<unsigned char> IDAT(8); // IDAT chunk header IDAT[4] = 'I'; IDAT[5] = 'D'; IDAT[6] = 'A'; IDAT[7] = 'T'; // --- create deflate chunk ------------------------------------------------ IDAT.push_back(8 + (7 << 4)); // CM=8=deflate, CINFO=7=32K window size = 112 IDAT.push_back(94 /* 28*/); // FLG unsigned int dat_size; unsigned int s1 = 1; unsigned int s2 = 0; { BitPusher pusher(IDAT); pusher.pushBitsReverse(6, 3); // 5 = 101 for (int j = 0; j < HEIGHT; j++) { // push scan-line filter type pusher.pushBitsReverse(1 + 48, 8); // Push a 1 (diff with left) s1 += 1; // update adler 1 & 2 s2 += s1; #if 1 unsigned int trgb_p = 0xffffffff; unsigned int c = 0; for (int i = 0; i < WIDTH; i++) { unsigned int trgb_l = 0; for (int k = 0; k < 3; k++) { unsigned int t = (img[3 * WIDTH*j + 3 * i + k] - (i == 0 ? 0 : img[3 * WIDTH*j + 3 * (i - 1) + k])) & 0xffu; s1 = (s1 + t); // update adler 1 & 2 s2 = (s2 + s1); trgb_l = (trgb_l << 8) | t; } if ((i == 0) || (i == WIDTH - 1) || (trgb_l != trgb_p) || (c >= 66)) { // flush copies if (c == 0) { // no copies, 1 or 2 never occurs. } else if (c < 11) { pusher.pushBitsReverse(c - 2, 7); pusher.pushBitsReverse(2, 5); } else if (c < 19) { int t = c - 11; pusher.pushBitsReverse((t >> 1) + 9, 7); pusher.pushBitsReverse((t & 1), 1); pusher.pushBitsReverse(2, 5); } else if (c < 35) { int t = c - 19; pusher.pushBitsReverse((t >> 2) + 13, 7); pusher.pushBits((t & 3), 2); pusher.pushBitsReverse(2, 5); } else if (c < 67) { int t = c - 35; pusher.pushBitsReverse((t >> 3) + 17, 7); pusher.pushBits((t & 7), 3); pusher.pushBitsReverse(2, 5); } c = 0; // need to write literal int r = (trgb_l >> 16) & 0xffu; if (r < 144) { pusher.pushBitsReverse(r + 48, 8); } else { pusher.pushBitsReverse(r + (400 - 144), 9); } int g = (trgb_l >> 8) & 0xffu; if (g < 144) { pusher.pushBitsReverse(g + 48, 8); } else { pusher.pushBitsReverse(g + (400 - 144), 9); } int b = (trgb_l >> 0) & 0xffu; if (b < 144) { pusher.pushBitsReverse(b + 48, 8); } else { pusher.pushBitsReverse(b + (400 - 144), 9); } trgb_p = trgb_l; } else { c += 3; } } #else for (int i = 0; i < WIDTH; i++) { for (int k = 0; k < 3; k++) { int q = img[3 * WIDTH*j + 3 * i + k]; s1 = (s1 + q); // update adler 1 & 2 s2 = (s2 + s1); if (q < 144) { pusher.pushBitsReverse(q + 48, 8); // 48 = 00110000 } else { pusher.pushBitsReverse(q + (400 - 144), 9); // 400 = 110010000 } } } #endif // We can do up to 5552 iterations before we need to run the modulo, // see comment on NMAX adler32.c in zlib. s1 = s1 % 65521; s2 = s2 % 65521; } pusher.pushBits(0, 7); // EOB } unsigned int adler = (s2 << 16) + s1; IDAT.push_back(((adler) >> 24) & 0xffu); // Adler32 IDAT.push_back(((adler) >> 16) & 0xffu); IDAT.push_back(((adler) >> 8) & 0xffu); IDAT.push_back(((adler) >> 0) & 0xffu); // --- end deflate chunk -------------------------------------------------- // Update PNG chunk content size for IDAT dat_size = IDAT.size() - 8u; IDAT[0] = ((dat_size) >> 24) & 0xffu; IDAT[1] = ((dat_size) >> 16) & 0xffu; IDAT[2] = ((dat_size) >> 8) & 0xffu; IDAT[3] = ((dat_size) >> 0) & 0xffu; unsigned long crc = CRC(crc_table, IDAT.data() + 4, dat_size + 4); IDAT.resize(IDAT.size() + 4u); // make room for CRC IDAT[dat_size + 8] = ((crc) >> 24) & 0xffu; IDAT[dat_size + 9] = ((crc) >> 16) & 0xffu; IDAT[dat_size + 10] = ((crc) >> 8) & 0xffu; IDAT[dat_size + 11] = ((crc) >> 0) & 0xffu; TimeStamp stop; std::cerr << "IDAT2 used " << TimeStamp::delta(start, stop) << "\n"; if (1) { std::vector<unsigned char> quux(10 * 1024 * 1024); z_stream stream; int err; stream.next_in = (z_const Bytef *)IDAT.data() + 8; stream.avail_in = (uInt)IDAT.size() - 8; stream.next_out = quux.data(); stream.avail_out = quux.size(); stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) { std::cerr << "inflateInit failed: " << err << "\n"; abort(); } err = inflate(&stream, Z_FINISH); if (stream.msg != NULL) { std::cerr << stream.msg << "\n"; } uLongf quux_size = quux.size(); err = uncompress(quux.data(), &quux_size, IDAT.data() + 8, IDAT.size() - 8); if (err != Z_OK) { std::cerr << "uncompress=" << err << "\n"; } if (quux_size != ((3 * WIDTH + 1)*HEIGHT)) { std::cerr << "uncompress_size=" << quux_size << ", should be=" << ((3 * WIDTH + 1)*HEIGHT) << "\n"; } } file.write(reinterpret_cast<char*>(IDAT.data()), dat_size + 12); } void writeIEND(std::ofstream& file, const std::vector<unsigned long>& crc_table) { unsigned char IEND[12] = { 0, 0, 0, 0, // payload size 'I', 'E', 'N', 'D', // chunk id 174, 66, 96, 130 // chunk crc }; file.write(reinterpret_cast<char*>(IEND), 12); } #endif int main(int argc, char **argv) { #if 0 std::vector<unsigned long> crc_table; createCRCTable(crc_table); std::vector<unsigned char> img; createDummyImage(img); std::ofstream png("img.png"); writeSignature(png); writeIHDR(png, crc_table); writeIDAT(png, img, crc_table); writeIEND(png, crc_table); png.close(); std::ofstream png2("img2.png"); writeSignature(png2); writeIHDR(png2, crc_table); writeIDAT2(png2, img, crc_table); writeIEND(png2, crc_table); png2.close(); std::ofstream png3("img3.png"); writeSignature(png3); writeIHDR(png3, crc_table); writeIDAT3(png3, img, crc_table); writeIEND(png3, crc_table); png3.close(); { std::ofstream png2("img2.png"); writeSignature(png2); writeIHDR(png2, crc_table); writeIDAT2(png2, img, crc_table); writeIEND(png2, crc_table); png2.close(); } #endif return 0; }
26.872115
115
0.482198
cdyk
1f78534c6ac29c1c1f4ff42b8aa284c7e0d7c508
8,886
cpp
C++
miniapps/mhd/imScale.cpp
fanronghong/mfem
5bc8d5ea1b7e3a0b377423773e78428bf7160612
[ "BSD-3-Clause" ]
1
2020-04-28T05:08:24.000Z
2020-04-28T05:08:24.000Z
miniapps/mhd/imScale.cpp
fanronghong/mfem
5bc8d5ea1b7e3a0b377423773e78428bf7160612
[ "BSD-3-Clause" ]
null
null
null
miniapps/mhd/imScale.cpp
fanronghong/mfem
5bc8d5ea1b7e3a0b377423773e78428bf7160612
[ "BSD-3-Clause" ]
null
null
null
// MFEM modified from Example 10 and 16 // // Compile with: make imMHDp // // Description: It solves a time dependent resistive MHD problem // There three versions: // 1. explicit scheme // 2. implicit scheme using a very simple linear preconditioner // 3. implicit scheme using physcis-based preconditioner // Author: QT #include "mfem.hpp" #include "myCoefficient.hpp" #include "myIntegrator.hpp" #include "imScale.hpp" #include "PCSolver.hpp" #include "InitialConditions.hpp" #include <memory> #include <iostream> #include <fstream> #ifndef MFEM_USE_PETSC #error This example requires that MFEM is built with MFEM_USE_PETSC=YES #endif int main(int argc, char *argv[]) { int num_procs, myid; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); //++++Parse command-line options. const char *mesh_file = "./Meshes/xperiodic-square.mesh"; int ser_ref_levels = 2; int par_ref_levels = 0; int order = 2; int ode_solver_type = 3; double t_final = 5.0; double dt = 0.0001; double visc = 1e-3; double resi = 1e-3; bool visit = false; bool use_petsc = false; bool use_factory = false; const char *petscrc_file = ""; beta = 0.001; Lx=3.0; lambda=5.0; int vis_steps = 1; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&ser_ref_levels, "-rs", "--refine", "Number of times to refine the mesh uniformly in serial."); args.AddOption(&par_ref_levels, "-rp", "--refineP", "Number of times to refine the mesh uniformly in parallel."); args.AddOption(&order, "-o", "--order", "Order (degree) of the finite elements."); args.AddOption(&ode_solver_type, "-s", "--ode-solver", "ODE solver: 1 - Backward Euler, 2 - Brailovskaya,\n\t" " 3 - L-stable SDIRK23, 4 - L-stable SDIRK33,\n\t" " 22 - Implicit Midpoint, 23 - SDIRK23, 24 - SDIRK34."); args.AddOption(&t_final, "-tf", "--t-final", "Final time; start time is 0."); args.AddOption(&dt, "-dt", "--time-step", "Time step."); args.AddOption(&visc, "-visc", "--viscosity", "Viscosity coefficient."); args.AddOption(&resi, "-resi", "--resistivity", "Resistivity coefficient."); args.AddOption(&vis_steps, "-vs", "--visualization-steps", "Visualize every n-th timestep."); args.AddOption(&use_petsc, "-usepetsc", "--usepetsc", "-no-petsc", "--no-petsc", "Use or not PETSc to solve the nonlinear system."); args.AddOption(&use_factory, "-shell", "--shell", "-no-shell", "--no-shell", "Use user-defined preconditioner factory (PCSHELL)."); args.AddOption(&petscrc_file, "-petscopts", "--petscopts", "PetscOptions file to use."); args.Parse(); if (!args.Good()) { if (myid == 0) { args.PrintUsage(cout); } MPI_Finalize(); return 1; } lambda=.5/M_PI; resiG=resi; if (myid == 0) args.PrintOptions(cout); if (use_petsc) { MFEMInitializePetsc(NULL,NULL,petscrc_file,NULL); } //+++++Read the mesh from the given mesh file. Mesh *mesh = new Mesh(mesh_file, 1, 1); int dim = mesh->Dimension(); //++++Define the ODE solver used for time integration. Several implicit // singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as // backward Euler methods are available. PCSolver *ode_solver=NULL; ODESolver *ode_solver2=NULL; bool explicitSolve=false; switch (ode_solver_type) { //Explicit methods (first-order Predictor-Corrector) case 2: ode_solver = new PCSolver; explicitSolve = true; break; //Implict L-stable methods case 1: ode_solver2 = new BackwardEulerSolver; break; case 3: ode_solver2 = new SDIRK23Solver(2); break; case 4: ode_solver2 = new SDIRK33Solver; break; // Implicit A-stable methods (not L-stable) case 12: ode_solver2 = new ImplicitMidpointSolver; break; case 13: ode_solver2 = new SDIRK23Solver; break; case 14: ode_solver2 = new SDIRK34Solver; break; default: if (myid == 0) cout << "Unknown ODE solver type: " << ode_solver_type << '\n'; delete mesh; MPI_Finalize(); return 3; } //++++++Refine the mesh to increase the resolution. for (int lev = 0; lev < ser_ref_levels; lev++) { mesh->UniformRefinement(); } ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; for (int lev = 0; lev < par_ref_levels; lev++) { pmesh->UniformRefinement(); } //+++++Define the vector finite element spaces representing [Psi, Phi, w] // in block vector bv, with offsets given by the fe_offset array. // All my fespace is 1D but the problem is multi-dimensional H1_FECollection fe_coll(order, dim); ParFiniteElementSpace fespace(pmesh, &fe_coll); HYPRE_Int global_size = fespace.GlobalTrueVSize(); if (myid == 0) { cout << "Number of total scalar unknowns: " << global_size << endl; } int fe_size = fespace.TrueVSize(); Array<int> fe_offset(4); fe_offset[0] = 0; fe_offset[1] = fe_size; fe_offset[2] = 2*fe_size; fe_offset[3] = 3*fe_size; BlockVector vx(fe_offset); ParGridFunction psi, phi, w; phi.MakeTRef(&fespace, vx, fe_offset[0]); psi.MakeTRef(&fespace, vx, fe_offset[1]); w.MakeTRef(&fespace, vx, fe_offset[2]); //+++++Set the initial conditions, and the boundary conditions FunctionCoefficient phiInit(InitialPhi); phi.ProjectCoefficient(phiInit); phi.SetTrueVector(); FunctionCoefficient psiInit3(InitialPsi3); psi.ProjectCoefficient(psiInit3); psi.SetTrueVector(); FunctionCoefficient wInit(InitialW); w.ProjectCoefficient(wInit); w.SetTrueVector(); //this step is necessary to make sure unknows are updated! phi.SetFromTrueVector(); psi.SetFromTrueVector(); w.SetFromTrueVector(); //++++++this is a periodic boundary condition in x and Direchlet in y Array<int> ess_bdr(fespace.GetMesh()->bdr_attributes.Max()); ess_bdr = 0; ess_bdr[0] = 1; //set attribute 1 to Direchlet boundary fixed if(ess_bdr.Size()!=1 || false) { if (myid==0) cout <<"ess_bdr size should be 1 but it is "<<ess_bdr.Size()<<endl; delete ode_solver; delete ode_solver2; delete mesh; delete pmesh; MPI_Finalize(); return 2; } //++++Initialize the MHD operator, the GLVis visualization ResistiveMHDOperator oper(fespace, ess_bdr, visc, resi, use_petsc, use_factory); FunctionCoefficient e0(E0rhs3); oper.SetRHSEfield(e0); //set initial J FunctionCoefficient jInit3(InitialJ3); oper.SetInitialJ(jInit3); double t = 0.0; oper.SetTime(t); ode_solver2->Init(oper); MPI_Barrier(MPI_COMM_WORLD); double start = MPI_Wtime(); //++++Perform time-integration (looping over the time iterations, ti, with a // time-step dt). bool last_step = false; for (int ti = 1; !last_step; ti++) { //ignore the first time step if (ti==2) { MPI_Barrier(MPI_COMM_WORLD); start = MPI_Wtime(); } ode_solver2->Step(vx, t, dt); last_step = (t >= t_final - 1e-8*dt); if (last_step || (ti % vis_steps) == 0) { if (myid==0) cout << "step " << ti << ", t = " << t <<endl; } } MPI_Barrier(MPI_COMM_WORLD); double end = MPI_Wtime(); if (myid == 0) cout <<"######Runtime = "<<end-start<<" ######"<<endl; //++++++Save the solutions. { phi.SetFromTrueVector(); psi.SetFromTrueVector(); w.SetFromTrueVector(); ostringstream mesh_name, phi_name, psi_name, w_name,j_name; mesh_name << "mesh." << setfill('0') << setw(6) << myid; phi_name << "sol_phi." << setfill('0') << setw(6) << myid; psi_name << "sol_psi." << setfill('0') << setw(6) << myid; w_name << "sol_omega." << setfill('0') << setw(6) << myid; ofstream omesh(mesh_name.str().c_str()); omesh.precision(8); pmesh->Print(omesh); ofstream osol(phi_name.str().c_str()); osol.precision(8); phi.Save(osol); ofstream osol3(psi_name.str().c_str()); osol3.precision(8); psi.Save(osol3); ofstream osol4(w_name.str().c_str()); osol4.precision(8); w.Save(osol4); } //+++++Free the used memory. delete ode_solver; delete ode_solver2; delete pmesh; oper.DestroyHypre(); if (use_petsc) { MFEMFinalizePetsc(); } MPI_Finalize(); return 0; }
30.641379
87
0.609498
fanronghong
1f7a6452665d1c909389e6c7dee21c9904679c9c
595
cpp
C++
src/UnitTest/TUTTest.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
src/UnitTest/TUTTest.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
src/UnitTest/TUTTest.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
// ***************************************************************************** /*! \file src/UnitTest/TUTTest.cpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Template Unit Test unit test class definition \details Template Unit Test unit test class definition. */ // ***************************************************************************** #include "TUTTest.hpp" #include "NoWarning/tuttest.def.h"
37.1875
80
0.489076
franjgonzalez
1f7bae902416c708bb6939558da5541394e3c1ac
403
cpp
C++
advance/structWithCpp.cpp
slowy07/c-lesson
89f3b90c75301d59f64a6659eb8da8a3f8be1582
[ "MIT" ]
2
2020-06-02T17:32:09.000Z
2020-11-29T01:24:52.000Z
advance/structWithCpp.cpp
slowy07/c-lesson
89f3b90c75301d59f64a6659eb8da8a3f8be1582
[ "MIT" ]
null
null
null
advance/structWithCpp.cpp
slowy07/c-lesson
89f3b90c75301d59f64a6659eb8da8a3f8be1582
[ "MIT" ]
2
2020-09-23T14:40:28.000Z
2020-11-26T12:32:44.000Z
#include <iostream> using namespace std; struct Rumah { int houseCode; char houseName[100]; //length }; int main() { Rumah rumah; //declaration struct Rumah cout<<"houseCode :"; cin>>rumah.houseCode; cout<<"houseName :"; cin>>rumah.houseName; //create ouput cout<<"data created "<<endl; cout<<"house Name : "<<rumah.houseName<<endl; cout<<"house Code : "<<rumah.houseCode<<endl; }
20.15
47
0.665012
slowy07
1f7f12a6ffe15a419b2ba405037cef94db2ad0de
383
cpp
C++
0049 - Product of consecutive Fib numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
0049 - Product of consecutive Fib numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
0049 - Product of consecutive Fib numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
#include <vector> typedef unsigned long long ull; class ProdFib { public: static std::vector<ull> productFib(ull prod) { ull t1 = 0, t2 = 1, nextTerm = t1 + t2; while(t1*t2 <= prod) { if (t1 * t2 == prod) return {t1, t2, true}; t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; } if (t1 * t2 > prod) return {t1, t2, false}; } };
22.529412
51
0.524804
dimitri-dev
1f80a338bc0065be2bd8d75ceae76182a17c9c92
2,360
cpp
C++
scratch/projects/basics/xReciprocalFrames.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
scratch/projects/basics/xReciprocalFrames.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
scratch/projects/basics/xReciprocalFrames.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
/* * ===================================================================================== * * Filename: xReciprocalFrames.cpp * * Description: some calculus tests * * Version: 1.0 * Created: 02/05/2014 12:39:59 * Revision: none * Compiler: gcc * * Author: PC * Organization: * * ===================================================================================== */ #include "vsr_cga3D.h" #include "vsr_GLVimpl.h" using namespace vsr; using namespace vsr::cga3D; struct MyApp : App { Pnt mouse; Lin ray; float time; float amt; MyApp(Window * win ) : App(win){ scene.camera.pos( 0,0,10 ); time = 0; } void initGui(){ gui(amt,"amt",-100,100); } void getMouse(){ auto tv = interface.vd().ray; Vec z (tv[0], tv[1], tv[2] ); auto tm = interface.mouse.projectMid; ray = Round::point( tm[0], tm[1], tm[2] ) ^ z ^ Inf(1); mouse = Round::point( ray, Ori(1) ); } virtual void onDraw(){ getMouse(); // Circle ca = CXZ(1).trs(0,-2,0); // Circle cb = CXZ(1).trs(0,2,0); auto ca = Ro::dls(0.0,0,-3,0); auto cb = Ro::dls(0.0,0,3,0); Drv drv = Vec(ca-cb).unit().copy<Drv>(); Dlp da = ca <= drv; Dlp db = cb <= -drv; auto intersect = ( ray.dual() ^ Dlp(0,0,1) ).dual().unit().null(); VT sqd = Ro::sqd( ca, cb ); ( intersect <= da / sqd ).print(); ( intersect <= db / sqd ).print(); auto pss = ca ^ cb ^ Inf(1); VT norm = pss.rnorm(); auto rca = ( (cb ^ Inf(1) )<= pss ) / (norm*norm); auto rcb = ( (ca ^ Inf(1) )<= pss ) / (norm*norm); // cout << "r" << endl; // rca.print(); intersect.print(); auto sa = intersect <= rca; auto sb = intersect <= rcb; Draw (ca); Draw(cb); // cout << "and ... " << endl; // sa.print(); sb.print(); // cout << "or ... " << endl; auto ss = intersect <= (ca ^ cb); // ss.print(); // cout << ss.wt() << endl; } }; MyApp * app; int main(){ GLV glv(0,0); Window * win = new Window(500,500,"Versor",&glv); app = new MyApp( win ); app -> initGui(); glv << *app; Application::run(); return 0; }
18.015267
88
0.425847
tingelst
1f8208304eb52691a62fd8f33e1ea34ad00b43a4
2,634
cpp
C++
src/posix/time.cpp
abdes/asap_filesystem
44b8ab19900db6ce58a8802817a5b42d6ab6a4b3
[ "BSD-3-Clause" ]
3
2019-05-20T14:21:11.000Z
2019-05-21T19:09:13.000Z
src/posix/time.cpp
abdes/asap_filesystem
44b8ab19900db6ce58a8802817a5b42d6ab6a4b3
[ "BSD-3-Clause" ]
null
null
null
src/posix/time.cpp
abdes/asap_filesystem
44b8ab19900db6ce58a8802817a5b42d6ab6a4b3
[ "BSD-3-Clause" ]
null
null
null
// Copyright The Authors 2018. // Distributed under the 3-Clause BSD License. // (See accompanying file LICENSE or copy at // https://opensource.org/licenses/BSD-3-Clause) #include "../fs_portability.h" #if defined(ASAP_POSIX) // ----------------------------------------------------------------------------- // detail: file time utils // ----------------------------------------------------------------------------- namespace asap { namespace filesystem { namespace detail { namespace posix_port { namespace { // We know this may create an overflow and also that the tests may always be // true. This is here for cases where the representation of // std::chrono::duration is smaller than the TimeSpec representation. HEDLEY_DIAGNOSTIC_PUSH #if defined(HEDLEY_GCC_VERSION) HEDLEY_PRAGMA(GCC diagnostic ignored "-Woverflow") #endif // HEDLEY_GCC_VERSION #if defined(__clang__) HEDLEY_PRAGMA(clang diagnostic ignored "-Wtautological-type-limit-compare") #endif // __clang__ auto FileTimeIsRepresentable(TimeSpec tm) -> bool { using std::chrono::nanoseconds; using std::chrono::seconds; if (tm.tv_sec >= 0) { return tm.tv_sec <= seconds::max().count(); } if (tm.tv_sec == (seconds::min().count() - 1)) { return tm.tv_nsec >= nanoseconds::min().count(); } return tm.tv_sec >= seconds::min().count(); } HEDLEY_DIAGNOSTIC_POP } // namespace auto FileTimeTypeFromPosixTimeSpec(TimeSpec tm) -> file_time_type { using std::chrono::duration; using std::chrono::duration_cast; using rep = typename file_time_type::rep; using fs_duration = typename file_time_type::duration; using fs_seconds = duration<rep>; using fs_nanoseconds = duration<rep, std::nano>; if (tm.tv_sec >= 0 || tm.tv_nsec == 0) { return file_time_type( fs_seconds(tm.tv_sec) + duration_cast<fs_duration>(fs_nanoseconds(tm.tv_nsec))); } // tm.tv_sec < 0 auto adj_subsec = duration_cast<fs_duration>(fs_seconds(1) - fs_nanoseconds(tm.tv_nsec)); auto Dur = fs_seconds(tm.tv_sec + 1) - adj_subsec; return file_time_type(Dur); } auto ExtractLastWriteTime(const path &p, const StatT &st, std::error_code *ec) -> file_time_type { ErrorHandler<file_time_type> err("last_write_time", ec, &p); auto ts = detail::posix_port::ExtractModificationTime(st); if (!detail::posix_port::FileTimeIsRepresentable(ts)) { return err.report(std::errc::value_too_large); } return detail::posix_port::FileTimeTypeFromPosixTimeSpec(ts); } } // namespace posix_port } // namespace detail } // namespace filesystem } // namespace asap #endif // ASAP_POSIX
32.518519
80
0.667046
abdes
1f84070f51d4c926b76df27f24cee448ed1ce071
917
cpp
C++
sorting/quick-sort/quick-sort-tcgen.cpp
zakee94/algorithms
abacc85bf8bda06796b283bae3452f6dbd1897d1
[ "MIT" ]
3
2017-12-14T14:21:37.000Z
2019-07-01T05:51:32.000Z
sorting/quick-sort/quick-sort-tcgen.cpp
zakee94/algorithms
abacc85bf8bda06796b283bae3452f6dbd1897d1
[ "MIT" ]
null
null
null
sorting/quick-sort/quick-sort-tcgen.cpp
zakee94/algorithms
abacc85bf8bda06796b283bae3452f6dbd1897d1
[ "MIT" ]
1
2019-03-04T22:38:49.000Z
2019-03-04T22:38:49.000Z
#include <iostream> #include <fstream> #include <stdlib.h> #include <time.h> using namespace std; #define SIZE 100000000 void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void printArray(int arr[], int size) { int i; ofstream outFile; outFile.open("input.txt"); for (i = 0; i < size; i++) outFile << arr[i] << "\n"; outFile.close(); } void initArray(int arr[], int size) { int i; for (i = 0; i < size; i++) { arr[i] = i + 1; } } void shuffle(int arr[], int size) { int rand_index, j = size - 1, i; for (i = 0; i < j; i++) { rand_index = rand() % j; swap(&arr[rand_index], &arr[j]); j--; } } int main() { int* arr = (int*)malloc(sizeof(int)*SIZE); srand(time(NULL)); initArray(arr, SIZE); shuffle(arr, SIZE); printArray(arr, SIZE); free(arr); return 0; }
15.810345
46
0.513631
zakee94
1f875975a55ca02fc65efe05f5900c797901f749
3,355
cpp
C++
Engine/source/util/catmullRom.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
46
2015-01-05T17:34:43.000Z
2022-01-04T04:03:09.000Z
Engine/source/util/catmullRom.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/source/util/catmullRom.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
9
2015-08-08T18:46:06.000Z
2021-02-01T13:53:20.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "platform/platform.h" #include "util/catmullRom.h" #include "math/mMathFn.h" const F32 CatmullRomBase::smX[] = { 0.0000000000f, 0.5384693101f, -0.5384693101f, 0.9061798459f, -0.9061798459f }; const F32 CatmullRomBase::smC[] = { 0.5688888889f, 0.4786286705f, 0.4786286705f, 0.2369268850f, 0.2369268850f }; CatmullRomBase::CatmullRomBase() : mTimes( NULL ), mLengths( NULL ), mTotalLength( 0.0f ), mCount( 0 ) { } void CatmullRomBase::_initialize( U32 count, const F32 *times ) { //AssertFatal( times, "CatmullRomBase::_initialize() - Got null position!" ) AssertFatal( count > 1, "CatmullRomBase::_initialize() - Must have more than 2 points!" ) // set up arrays mTimes = new F32[count]; mCount = count; // set up curve segment lengths mLengths = new F32[count-1]; mTotalLength = 0.0f; for ( U32 i = 0; i < count-1; ++i ) { mLengths[i] = segmentArcLength(i, 0.0f, 1.0f); mTotalLength += mLengths[i]; } // copy the times if we have them. F32 l = 0.0f; for ( U32 i = 0; i < count; ++i ) { if ( times ) mTimes[i] = times[i]; else { if ( mIsZero( mTotalLength ) ) mTimes[i] = 0.0f; else mTimes[i] = l / mTotalLength; if ( i < count-1 ) l += mLengths[i]; } } } void CatmullRomBase::clear() { delete [] mTimes; mTimes = NULL; delete [] mLengths; mLengths = NULL; mTotalLength = 0.0f; mCount = 0; } F32 CatmullRomBase::arcLength( F32 t1, F32 t2 ) { if ( t2 <= t1 ) return 0.0f; if ( t1 < mTimes[0] ) t1 = mTimes[0]; if ( t2 > mTimes[mCount-1] ) t2 = mTimes[mCount-1]; // find segment and parameter U32 seg1; for ( seg1 = 0; seg1 < mCount-1; ++seg1 ) { if ( t1 <= mTimes[seg1+1] ) { break; } } F32 u1 = (t1 - mTimes[seg1])/(mTimes[seg1+1] - mTimes[seg1]); // find segment and parameter U32 seg2; for ( seg2 = 0; seg2 < mCount-1; ++seg2 ) { if ( t2 <= mTimes[seg2+1] ) { break; } } F32 u2 = (t2 - mTimes[seg2])/(mTimes[seg2+1] - mTimes[seg2]); F32 result; // both parameters lie in one segment if ( seg1 == seg2 ) { result = segmentArcLength( seg1, u1, u2 ); } // parameters cross segments else { result = segmentArcLength( seg1, u1, 1.0f ); for ( U32 i = seg1+1; i < seg2; ++i ) result += mLengths[i]; result += segmentArcLength( seg2, 0.0f, u2 ); } return result; } U32 CatmullRomBase::getPrevNode( F32 t ) { AssertFatal( mCount >= 2, "CatmullRomBase::getPrevNode - Bad point count!" ); // handle boundary conditions if ( t <= mTimes[0] ) return 0; else if ( t >= mTimes[mCount-1] ) return mCount-1; // find segment and parameter U32 i; // segment # for ( i = 0; i < mCount-1; ++i ) { if ( t <= mTimes[i+1] ) break; } AssertFatal( i >= 0 && i < mCount, "CatmullRomBase::getPrevNode - Got bad output index!" ); return i; } F32 CatmullRomBase::getTime( U32 idx ) { AssertFatal( idx >= 0 && idx < mCount, "CatmullRomBase::getTime - Got bad index!" ); return mTimes[idx]; }
21.645161
94
0.569001
fr1tz
1f8989f008bd2186682b99ccb5577861cd3c9cc3
1,637
hpp
C++
include/StateInGame.hpp
nqbinh47/Maze-Runner
f8bd2ad1c39154676f9b49d0285464396adbcf80
[ "MIT" ]
4
2022-01-18T02:47:11.000Z
2022-01-19T13:04:59.000Z
include/StateInGame.hpp
phphuc62/Maze-Runner
f8bd2ad1c39154676f9b49d0285464396adbcf80
[ "MIT" ]
null
null
null
include/StateInGame.hpp
phphuc62/Maze-Runner
f8bd2ad1c39154676f9b49d0285464396adbcf80
[ "MIT" ]
1
2022-01-18T02:52:53.000Z
2022-01-18T02:52:53.000Z
#pragma once #include "StateGame.hpp" #define SCREEN_TITLE_WIDTH (SCREEN_WIDTH - 2 * SPACE) #define SCREEN_TITLE_HEIGHT (OFFSET_MAZE_Y - 2 * SPACE) #define OFFSET_TITLE_X (SPACE + SCREEN_TITLE_WIDTH / 2) #define OFFSET_TITLE_Y (SPACE + SCREEN_TITLE_HEIGHT / 2) #define NUMBER_OF_BOXES 3 #define NUMBER_OF_BUTTONS 3 #define SCREEN_INFO_HEIGHT (SCREEN_MAZE_Y / NUMBER_OF_BOXES) #define SCREEN_INFO_WIDTH (SCREEN_WIDTH - SCREEN_MAZE_X - 2 * SPACE) #define OFFSET_LEVEL_X (OFFSET_MAZE_X + SCREEN_MAZE_X + 5 + SCREEN_INFO_WIDTH / 2) #define OFFSET_LEVEL_Y (OFFSET_MAZE_Y + SCREEN_INFO_HEIGHT / 2) #define OFFSET_TIME_X (OFFSET_LEVEL_X - SCREEN_INFO_WIDTH / 4) #define OFFSET_TIME_Y (OFFSET_LEVEL_Y + SCREEN_INFO_HEIGHT / 4 * 3) #define OFFSET_TIME_INFO_X OFFSET_TIME_X #define OFFSET_TIME_INFO_Y (OFFSET_TIME_Y + SCREEN_INFO_HEIGHT / 2) #define OFFSET_COINS_X (OFFSET_LEVEL_X + SCREEN_INFO_WIDTH / 4) #define OFFSET_COINS_Y OFFSET_TIME_Y #define OFFSET_COINS_INFO_X OFFSET_COINS_X #define OFFSET_COINS_INFO_Y (OFFSET_COINS_Y + SCREEN_INFO_HEIGHT / 2) #define BUTTON_HEIGHT (SCREEN_INFO_HEIGHT / 2) #define BUTTON_WIDTH (SCREEN_INFO_WIDTH / (NUMBER_OF_BUTTONS + 1)) #define BUTTON_SPACE (BUTTON_WIDTH / (NUMBER_OF_BUTTONS + 1)) #define OFFSET_HELP_X (OFFSET_LEVEL_X - SCREEN_INFO_WIDTH / 2 + BUTTON_SPACE + BUTTON_WIDTH / 2) #define OFFSET_HELP_Y (OFFSET_TIME_INFO_Y + SCREEN_INFO_HEIGHT / 4 * 3) #define OFFSET_RESTART_X (OFFSET_HELP_X + BUTTON_WIDTH + BUTTON_SPACE) #define OFFSET_RESTART_Y OFFSET_HELP_Y #define OFFSET_RETURN_MENU_X (OFFSET_RESTART_X + BUTTON_WIDTH + BUTTON_SPACE) #define OFFSET_RETURN_MENU_Y OFFSET_HELP_Y
40.925
96
0.808186
nqbinh47
1f8b36183b039cad25ae480f4b2be6b17518b860
2,048
cpp
C++
BasiliskII/src/uae_cpu/fpu/rounding.cpp
jvernet/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
940
2015-01-04T12:20:10.000Z
2022-03-29T12:35:27.000Z
BasiliskII/src/uae_cpu/fpu/rounding.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
163
2015-02-10T09:08:10.000Z
2022-03-13T05:48:10.000Z
BasiliskII/src/uae_cpu/fpu/rounding.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
188
2015-01-07T19:46:11.000Z
2022-03-26T19:06:00.000Z
/* * fpu/rounding.cpp - system-dependant FPU rounding mode and precision * * Basilisk II (C) 1997-2008 Christian Bauer * * MC68881/68040 fpu emulation * * Original UAE FPU, copyright 1996 Herman ten Brugge * Rewrite for x86, copyright 1999-2000 Lauri Pesonen * New framework, copyright 2000 Gwenole Beauchesne * Adapted for JIT compilation (c) Bernd Meyer, 2000 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #undef PRIVATE #define PRIVATE /**/ #undef PUBLIC #define PUBLIC /**/ #undef FFPU #define FFPU /**/ #undef FPU #define FPU fpu. /* -------------------------------------------------------------------------- */ /* --- Native X86 Rounding Mode --- */ /* -------------------------------------------------------------------------- */ #ifdef FPU_USE_X86_ROUNDING_MODE const uae_u32 FFPU x86_control_word_rm_mac2host[] = { CW_RC_NEAR, CW_RC_ZERO, CW_RC_DOWN, CW_RC_UP }; #endif /* -------------------------------------------------------------------------- */ /* --- Native X86 Rounding Precision --- */ /* -------------------------------------------------------------------------- */ #ifdef FPU_USE_X86_ROUNDING_PRECISION const uae_u32 FFPU x86_control_word_rp_mac2host[] = { CW_PC_EXTENDED, CW_PC_SINGLE, CW_PC_DOUBLE, CW_PC_RESERVED }; #endif
31.507692
80
0.587402
jvernet
1f8cda7fa9d89777f6f1368265cfe2be5fd45d95
27,457
cpp
C++
DryadVertex/VertexHost/system/channel/src/recorditem.cpp
TheWhiteEagle/Dryad
ad28579dd8303925befc6502633949850b7ca550
[ "Apache-2.0" ]
242
2015-01-04T08:08:04.000Z
2022-03-31T02:00:14.000Z
DryadVertex/VertexHost/system/channel/src/recorditem.cpp
TheWhiteEagle/Dryad
ad28579dd8303925befc6502633949850b7ca550
[ "Apache-2.0" ]
2
2015-04-30T07:44:42.000Z
2015-05-19T06:24:31.000Z
DryadVertex/VertexHost/system/channel/src/recorditem.cpp
TheWhiteEagle/Dryad
ad28579dd8303925befc6502633949850b7ca550
[ "Apache-2.0" ]
50
2015-01-13T20:39:53.000Z
2022-01-09T20:42:34.000Z
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ #include "recorditem.h" #pragma unmanaged RecordArrayBase::RecordArrayBase() { m_recordArray = NULL; m_recordArraySize = 0; m_numberOfRecords = 0; m_nextRecord = 0; m_serializedAny = 0; } RecordArrayBase::~RecordArrayBase() { LogAssert(m_buffer == NULL); LogAssert(m_recordArray == NULL); } void RecordArrayBase::FreeStorage() { m_buffer = NULL; if (m_recordArraySize > 0) { FreeTypedArray(m_recordArray); } m_recordArray = NULL; m_recordArraySize = 0; m_numberOfRecords = 0; m_nextRecord = 0; } void RecordArrayBase::PopRecord() { LogAssert(m_nextRecord > 0); --m_nextRecord; } UInt32 RecordArrayBase::GetNumberOfRecords() const { return m_numberOfRecords; } UInt64 RecordArrayBase::GetNumberOfSubItems() const { return GetNumberOfRecords(); } void RecordArrayBase::TruncateSubItems(UInt64 numberOfSubItems) { LogAssert(numberOfSubItems < (UInt64) m_numberOfRecords); SetRecordIndex((UInt32) numberOfSubItems); Truncate(); ResetRecordPointer(); } UInt64 RecordArrayBase::GetItemSize() const { return (UInt64) GetRecordSize() * (UInt64) GetNumberOfRecords(); } void* RecordArrayBase::GetRecordArrayUntyped() { return m_recordArray; } void RecordArrayBase::SetNumberOfRecords(UInt32 numberOfRecords) { if (m_recordArraySize < numberOfRecords) { if (m_recordArraySize > 0) { LogAssert(m_buffer == NULL); FreeTypedArray(m_recordArray); } m_recordArraySize = numberOfRecords; if (m_recordArraySize > 0) { m_recordArray = MakeTypedArray(m_recordArraySize); } else { m_recordArray = NULL; } } else if (m_recordArraySize == 0) { LogAssert(m_buffer != NULL); LogAssert(m_recordArray != NULL); m_recordArray = NULL; } m_buffer = NULL; m_numberOfRecords = numberOfRecords; ResetRecordPointer(); } void RecordArrayBase::ResetRecordPointer() { m_nextRecord = 0; } void* RecordArrayBase::GetRecordUntyped(UInt32 index) { LogAssert(index < m_numberOfRecords); char* cPtr = (char *) m_recordArray; return &(cPtr[GetRecordSize() * index]); } // // Return pointer to next record in array // void* RecordArrayBase::NextRecordUntyped() { if (m_nextRecord == m_numberOfRecords) { // // If no more records, return null // return NULL; } else { // // If valid record index, set return value to correct // offset from array start and increment "next record" index // LogAssert(m_nextRecord < m_numberOfRecords); char* cPtr = (char *) m_recordArray; void* r = &(cPtr[GetRecordSize() * m_nextRecord]); ++m_nextRecord; return r; } } // // Return the next record index // UInt32 RecordArrayBase::GetRecordIndex() const { return m_nextRecord; } void RecordArrayBase::SetRecordIndex(UInt32 index) { LogAssert(index <= m_numberOfRecords); m_nextRecord = index; } // // Return whether there are any additional records available // bool RecordArrayBase::AtEnd() { return (m_nextRecord == m_numberOfRecords); } void RecordArrayBase::Truncate() { if (m_nextRecord*2 < m_recordArraySize) { void* newArray = TransferTruncatedArray(m_recordArray, m_nextRecord); FreeTypedArray(m_recordArray); m_recordArray = newArray; m_recordArraySize = m_nextRecord; } m_numberOfRecords = m_nextRecord; } void RecordArrayBase::TransferRecord(void* dstRecord, void* srcRecord) { TransferRecord(NULL, dstRecord, NULL, srcRecord); } void* RecordArrayBase::TransferTruncatedArray(void* srcArrayUntyped, UInt32 numberOfRecords) { if (numberOfRecords == 0) { return NULL; } void* dstArrayUntyped = MakeTypedArray(numberOfRecords); LogAssert(dstArrayUntyped != NULL); char* srcPtr = (char *) srcArrayUntyped; char* dstPtr = (char *) dstArrayUntyped; UInt32 i; for (i=0; i<numberOfRecords; ++i, srcPtr += GetRecordSize(), dstPtr += GetRecordSize()) { TransferRecord(this, dstPtr, this, srcPtr); } return dstArrayUntyped; } UInt32 RecordArrayBase::ReadArray(DrMemoryBuffer* buffer, Size_t startOffset, UInt32 nRecords) { Size_t neededSize = nRecords * GetRecordSize(); Size_t availableSize = buffer->GetAvailableSize(); LogAssert(availableSize >= startOffset); Size_t remainingSize = buffer->GetAvailableSize() - startOffset; if (remainingSize < neededSize) { SetNumberOfRecords(0); return 0; } else { SetNumberOfRecords(nRecords); buffer->Read(startOffset, m_recordArray, neededSize); return (UInt32) neededSize; } } DrError RecordArrayBase::ReadFinalArray(DrMemoryBuffer* buffer) { LogAssert(buffer->GetAvailableSize() < GetRecordSize()); return DrError_EndOfStream; } UInt32 RecordArrayBase::AttachArray(DryadLockedMemoryBuffer* buffer, Size_t startOffset) { Size_t remainingSize; void* recordArray = (void *) buffer->GetReadAddress(startOffset, &remainingSize); LogAssert(remainingSize == buffer->GetAvailableSize() - startOffset); UInt32 numberOfRecords = (UInt32) (remainingSize / GetRecordSize()); if (numberOfRecords == 0) { SetNumberOfRecords(0); return 0; } else { FreeStorage(); m_buffer = buffer; m_recordArray = recordArray; m_numberOfRecords = numberOfRecords; return (UInt32) (m_numberOfRecords * GetRecordSize()); } } DrError RecordArrayBase::DeSerialize(DrResettableMemoryReader* reader, Size_t availableSize) { UInt32 numberOfRecords = (UInt32) (availableSize / GetRecordSize()); if (numberOfRecords < 1) { return DrError_EndOfStream; } if (GetNumberOfRecords() == 0) { SetNumberOfRecords(numberOfRecords); } if (numberOfRecords >= GetNumberOfRecords()) { numberOfRecords = GetNumberOfRecords(); } else { SetNumberOfRecords(numberOfRecords); } Size_t dataLength = (Size_t) (numberOfRecords * GetRecordSize()); DrError err = reader->ReadBytes((BYTE *) GetRecordArrayUntyped(), dataLength); LogAssert(err == DrError_OK); return DrError_OK; } void RecordArrayBase::StartSerializing() { if (m_serializedAny == false) { ResetRecordPointer(); m_serializedAny = true; } } DrError RecordArrayBase::Serialize(ChannelMemoryBufferWriter* writer) { StartSerializing(); void* nextRecord; bool filledBuffer = writer->MarkRecordBoundary(); LogAssert(filledBuffer == false); while (filledBuffer == false && (nextRecord = NextRecordUntyped()) != NULL) { writer->WriteBytes((BYTE *) nextRecord, GetRecordSize()); filledBuffer = writer->MarkRecordBoundary(); } if (filledBuffer) { return DrError_IncompleteOperation; } else { return DrError_OK; } } PackedRecordArrayParserBase:: PackedRecordArrayParserBase(DObjFactoryBase* factory) { m_factory = factory; } PackedRecordArrayParserBase::~PackedRecordArrayParserBase() { } RChannelItem* PackedRecordArrayParserBase:: ParseNextItem(ChannelDataBufferList* bufferList, Size_t startOffset, Size_t* pOutLength) { LogAssert(bufferList->IsEmpty() == false); RecordArrayBase *item = (RecordArrayBase *) m_factory->AllocateObjectUntyped(); RChannelBufferData* headBuffer = bufferList->CastOut(bufferList->GetHead()); if (bufferList->GetHead() != bufferList->GetTail()) { RChannelBufferData* tailBuffer = bufferList->CastOut(bufferList->GetTail()); Size_t tailBufferSize = tailBuffer->GetData()->GetAvailableSize(); DrRef<RChannelReaderBuffer> combinedBuffer; combinedBuffer.Attach(new RChannelReaderBuffer(bufferList, startOffset, tailBufferSize)); *pOutLength = item->ReadArray(combinedBuffer, 0, 1); } else { *pOutLength = item->AttachArray(headBuffer->GetData(), startOffset); } if (*pOutLength == 0) { m_factory->FreeObjectUntyped(item); item = NULL; } return item; } RChannelItem* PackedRecordArrayParserBase:: ParsePartialItem(ChannelDataBufferList* bufferList, Size_t startOffset, RChannelBufferMarker* markerBuffer) { if (bufferList->IsEmpty()) { return NULL; } RChannelBufferData* tailBuffer = bufferList->CastOut(bufferList->GetTail()); Size_t tailBufferSize = tailBuffer->GetData()->GetAvailableSize(); DrRef<RChannelReaderBuffer> combinedBuffer; combinedBuffer.Attach(new RChannelReaderBuffer(bufferList, startOffset, tailBufferSize)); RecordArrayBase *item = (RecordArrayBase *) m_factory->AllocateObjectUntyped(); DrError err = item->ReadFinalArray(combinedBuffer); if (err == DrError_OK) { return item; } m_factory->FreeObjectUntyped(item); if (err == DrError_EndOfStream) { return NULL; } else { return RChannelMarkerItem::CreateErrorItem(RChannelItem_ParseError, err); } } PackedRecordArrayParser::PackedRecordArrayParser(DObjFactoryBase* factory) : PackedRecordArrayParserBase(factory) { } PackedRecordArrayParser::~PackedRecordArrayParser() { } RecordArrayReaderBase::RecordArrayReaderBase() { } RecordArrayReaderBase::RecordArrayReaderBase(SyncItemReaderBase* reader) { Initialize(reader); } RecordArrayReaderBase::~RecordArrayReaderBase() { delete [] m_currentRecord; delete [] m_itemCache; } void RecordArrayReaderBase::Initialize(SyncItemReaderBase* reader) { m_reader = reader; m_arrayItem = NULL; m_cacheSize = 32; m_currentRecord = new void* [m_cacheSize]; m_itemCache = new RChannelItemRef [m_cacheSize]; m_valid = 0; m_cachedItemCount = 0; } void RecordArrayReaderBase::DiscardCachedItems() { UInt32 i; for (i=0; i<m_cachedItemCount; ++i) { m_itemCache[i] = NULL; } m_cachedItemCount = 0; } bool RecordArrayReaderBase::AdvanceInternal(UInt32 slotNumber) { while (m_item == NULL) { LogAssert(m_arrayItem == NULL); DrError status = m_reader->ReadItemSync(&m_item); LogAssert(status == DrError_OK); LogAssert(m_item != NULL); RChannelItemType itemType = m_item->GetType(); if (itemType == RChannelItem_Data) { m_arrayItem = (RecordArrayBase *) (m_item.Ptr()); } else if (RChannelItem::IsTerminationItem(itemType) == false) { /* this is a marker; skip it and fetch the next one */ m_item = NULL; } } if (m_arrayItem != NULL) { m_currentRecord[slotNumber] = m_arrayItem->NextRecordUntyped(); LogAssert(m_currentRecord[slotNumber] != NULL); if (m_arrayItem->AtEnd()) { m_itemCache[m_cachedItemCount].TransferFrom(m_item); LogAssert(m_item == NULL); m_arrayItem = NULL; ++m_cachedItemCount; } return true; } else { return false; } } void RecordArrayReaderBase::PushBack() { PushBack(true); } void RecordArrayReaderBase::PushBack(bool pushValid) { if (pushValid) { LogAssert(m_valid > 0); } if (m_arrayItem == NULL) { LogAssert(m_item == NULL); LogAssert(m_cachedItemCount > 0); --m_cachedItemCount; m_item.TransferFrom(m_itemCache[m_cachedItemCount]); m_arrayItem = (RecordArrayBase *) (m_item.Ptr()); } if (m_arrayItem->GetRecordIndex() == 0) { DrLogA("Can't push back more than one record"); } m_arrayItem->PopRecord(); if (pushValid) { --m_valid; } } bool RecordArrayReaderBase::Advance() { DiscardCachedItems(); if (AdvanceInternal(0)) { m_valid = 1; return true; } else { m_valid = 0; return false; } } UInt32 RecordArrayReaderBase::AdvanceBlock(UInt32 validEntriesRequested) { DiscardCachedItems(); if (validEntriesRequested > m_cacheSize) { delete [] m_currentRecord; delete [] m_itemCache; m_cacheSize = validEntriesRequested; m_currentRecord = new void* [m_cacheSize]; m_itemCache = new RChannelItemRef [m_cacheSize]; } UInt32 i; for (i=0; i<validEntriesRequested; ++i) { if (AdvanceInternal(i) == false) { break; } } m_valid = i; return i; } DrError RecordArrayReaderBase::GetStatus() { RChannelItem* item = GetTerminationItem(); if (item == NULL) { return DrError_OK; } else { return item->GetErrorFromItem(); } } RChannelItem* RecordArrayReaderBase::GetTerminationItem() { if (m_item == NULL || RChannelItem::IsTerminationItem(m_item->GetType()) == false) { return NULL; } else { return m_item; } } UInt32 RecordArrayReaderBase::GetValidCount() const { return m_valid; } RecordArrayWriterBase::RecordArrayWriterBase() { m_currentRecord = NULL; m_itemCache = NULL; m_cachedItemCount = 0; } RecordArrayWriterBase::RecordArrayWriterBase(SyncItemWriterBase* writer, DObjFactoryBase* factory) { m_currentRecord = NULL; m_itemCache = NULL; m_cachedItemCount = 0; Initialize(writer, factory); } RecordArrayWriterBase::~RecordArrayWriterBase() { Destroy(); } void RecordArrayWriterBase::Destroy() { Flush(); delete [] m_currentRecord; delete [] m_itemCache; } void RecordArrayWriterBase::Initialize(SyncItemWriterBase* writer, DObjFactoryBase* factory) { Destroy(); m_factory = factory; m_writer = writer; m_cacheSize = 32; m_currentRecord = new void* [m_cacheSize]; m_itemCache = new DrRef<RecordArrayBase> [m_cacheSize]; m_valid = 0; m_pushBackIndex = 0; m_cachedItemCount = 0; } void RecordArrayWriterBase::SetWriter(SyncItemWriterBase* writer) { m_writer = writer; } DrError RecordArrayWriterBase::GetWriterStatus() { return m_writer->GetWriterStatus(); } // // Write out any cached items // void RecordArrayWriterBase::SendCachedItems() { UInt32 i; for (i=0; i<m_cachedItemCount; ++i) { // // ensure the record pointer is rewound in case we are sending // this down a FIFO // m_itemCache[i]->ResetRecordPointer(); m_writer->WriteItemSync(m_itemCache[i]); m_itemCache[i] = NULL; } m_cachedItemCount = 0; } // // Move to next available object if one is available. // void RecordArrayWriterBase::AdvanceInternal(UInt32 slotNumber) { if (m_item == NULL) { // // If no current record array, generate one // RecordArrayBase *item = (RecordArrayBase *) m_factory->AllocateObjectUntyped(); m_item.Attach(item); } // // Set current record to the next available record // m_currentRecord[slotNumber] = m_item->NextRecordUntyped(); LogAssert(m_currentRecord[slotNumber] != NULL); // // If there are no more records in this record array, transfer the // record array into the item cache to remember that all items are cached. // if (m_item->AtEnd()) { m_itemCache[m_cachedItemCount].TransferFrom(m_item); LogAssert(m_item == NULL); ++m_cachedItemCount; } } // // // void RecordArrayWriterBase::MakeValid() { // // Clear out any cached items to reset // SendCachedItems(); // // Get the index of the next available record // if (m_item == NULL) { m_pushBackIndex = 0; } else { m_pushBackIndex = m_item->GetRecordIndex(); } // // Move to next available object if one is available and mark as valid // AdvanceInternal(0); m_valid = 1; } void RecordArrayWriterBase::MakeValidBlock(UInt32 validEntriesRequested) { SendCachedItems(); if (m_item == NULL) { m_pushBackIndex = 0; } else { m_pushBackIndex = m_item->GetRecordIndex(); } if (validEntriesRequested > m_cacheSize) { delete [] m_currentRecord; delete [] m_itemCache; m_cacheSize = validEntriesRequested; m_currentRecord = new void* [m_cacheSize]; m_itemCache = new DrRef<RecordArrayBase> [m_cacheSize]; } UInt32 i; for (i=0; i<validEntriesRequested; ++i) { AdvanceInternal(i); } m_valid = validEntriesRequested; } UInt32 RecordArrayWriterBase::GetValidCount() const { return m_valid; } void RecordArrayWriterBase::PushBack() { LogAssert(m_valid > 0); if (m_cachedItemCount > 0) { /* throw away back to the item we were using when we started */ m_item.TransferFrom(m_itemCache[0]); UInt32 i; for (i=1; i<m_cachedItemCount; ++i) { m_itemCache[i] = NULL; } m_cachedItemCount = 0; } LogAssert(m_item != NULL); m_item->SetRecordIndex(m_pushBackIndex); m_pushBackIndex = 0; m_valid = 0; } void* RecordArrayWriterBase::ReadValidUntyped(UInt32 index) { LogAssert(index < m_valid); return m_currentRecord[index]; } void RecordArrayWriterBase::Flush() { if (m_item != NULL) { m_item->Truncate(); m_itemCache[m_cachedItemCount].TransferFrom(m_item); LogAssert(m_item == NULL); ++m_cachedItemCount; } SendCachedItems(); m_valid = 0; } void RecordArrayWriterBase::Terminate() { Flush(); RChannelItemRef item; item.Attach(RChannelMarkerItem::Create(RChannelItem_EndOfStream, false)); m_writer->WriteItemSync(item); } AlternativeRecordParserBase:: AlternativeRecordParserBase(DObjFactoryBase* factory) { m_factory = factory; m_function = NULL; } AlternativeRecordParserBase:: AlternativeRecordParserBase(DObjFactoryBase* factory, RecordDeSerializerFunction* function) { m_factory = factory; m_function = function; } AlternativeRecordParserBase::~AlternativeRecordParserBase() { } void AlternativeRecordParserBase::ResetParser() { m_pendingErrorItem = NULL; } DrError AlternativeRecordParserBase:: DeSerializeArray(RecordArrayBase* array, DrResettableMemoryReader* reader, Size_t availableSize) { if (array->GetNumberOfRecords() == 0) { array->SetNumberOfRecords(RChannelItem::s_defaultRecordBatchSize); } Size_t sizeUsed = 0; Size_t remainingSize = availableSize; DrError err = DrError_OK; array->ResetRecordPointer(); void* nextRecord; while (remainingSize > 0 && (nextRecord = array->NextRecordUntyped()) != NULL) { err = DeSerializeUntyped(nextRecord, reader, remainingSize, false); if (err != DrError_OK) { array->PopRecord(); reader->ResetToBufferOffset(sizeUsed); break; } sizeUsed = reader->GetBufferOffset(); LogAssert(sizeUsed <= availableSize); remainingSize = availableSize - sizeUsed; } array->Truncate(); array->ResetRecordPointer(); if (err == DrError_EndOfStream && array->AtEnd() == false) { /* AtEnd() == false after Truncate+Reset means there's at least one item */ err = DrError_OK; } return err; } RChannelItem* AlternativeRecordParserBase:: ParseNextItem(ChannelDataBufferList* bufferList, Size_t startOffset, Size_t* pOutLength) { if (m_pendingErrorItem != NULL) { return m_pendingErrorItem.Detach(); } LogAssert(bufferList->IsEmpty() == false); RChannelBufferData* tailBuffer = bufferList->CastOut(bufferList->GetTail()); Size_t tailBufferSize = tailBuffer->GetData()->GetAvailableSize(); DrRef<DrMemoryBuffer> buffer; buffer.Attach(new RChannelReaderBuffer(bufferList, startOffset, tailBufferSize)); DrResettableMemoryReader reader(buffer); RecordArrayBase* recordArray = (RecordArrayBase *) m_factory->AllocateObjectUntyped(); DrError err = DeSerializeArray(recordArray, &reader, buffer->GetAvailableSize()); if (err == DrError_OK) { *pOutLength = reader.GetBufferOffset(); return recordArray; } m_factory->FreeObjectUntyped(recordArray); if (err == DrError_EndOfStream) { return NULL; } else { return RChannelMarkerItem::CreateErrorItem(RChannelItem_ParseError, err); } } RChannelItem* AlternativeRecordParserBase:: ParsePartialItem(ChannelDataBufferList* bufferList, Size_t startOffset, RChannelBufferMarker* markerBuffer) { if (m_pendingErrorItem != NULL) { return m_pendingErrorItem.Detach(); } if (bufferList->IsEmpty()) { return NULL; } RChannelBufferData* tailBuffer = bufferList->CastOut(bufferList->GetTail()); Size_t tailBufferSize = tailBuffer->GetData()->GetAvailableSize(); DrRef<DrMemoryBuffer> buffer; buffer.Attach(new RChannelReaderBuffer(bufferList, startOffset, tailBufferSize)); DrResettableMemoryReader reader(buffer); RecordArrayBase* recordArray = (RecordArrayBase *) m_factory->AllocateObjectUntyped(); recordArray->SetNumberOfRecords(1); void* nextRecord = recordArray->NextRecordUntyped(); DrError err = DeSerializeUntyped(nextRecord, &reader, buffer->GetAvailableSize(), true); if (err == DrError_OK) { recordArray->ResetRecordPointer(); return recordArray; } m_factory->FreeObjectUntyped(recordArray); if (err == DrError_EndOfStream) { return NULL; } else { return RChannelMarkerItem::CreateErrorItem(RChannelItem_ParseError, err); } } DrError AlternativeRecordParserBase:: DeSerializeUntyped(void* record, DrMemoryBufferReader* reader, Size_t availableSize, bool lastRecordInStream) { return (*m_function)(record, reader, availableSize, lastRecordInStream); } UntypedAlternativeRecordParser:: UntypedAlternativeRecordParser(DObjFactoryBase* factory, RecordDeSerializerFunction* function) : AlternativeRecordParserBase(factory, function) { } StdAlternativeRecordParserFactory:: StdAlternativeRecordParserFactory(DObjFactoryBase* factory, RecordDeSerializerFunction* function) { m_factory = factory; m_function = function; } void StdAlternativeRecordParserFactory:: MakeParser(RChannelItemParserRef* pParser, DVErrorReporter* errorReporter) { pParser->Attach(new UntypedAlternativeRecordParser(m_factory, m_function)); } AlternativeRecordMarshalerBase::AlternativeRecordMarshalerBase() { m_function = NULL; } AlternativeRecordMarshalerBase:: AlternativeRecordMarshalerBase(RecordSerializerFunction* function) { m_function = function; } AlternativeRecordMarshalerBase::~AlternativeRecordMarshalerBase() { } void AlternativeRecordMarshalerBase:: SetFunction(RecordSerializerFunction* function) { m_function = function; } DrError AlternativeRecordMarshalerBase:: MarshalItem(ChannelMemoryBufferWriter* writer, RChannelItem* item, bool flush, RChannelItemRef* pFailureItem) { DrError err = DrError_OK; if (item->GetType() != RChannelItem_Data) { return err; } RecordArrayBase* arrayItem = (RecordArrayBase *) item; arrayItem->StartSerializing(); Size_t currentPosition = 0; void* nextRecord; bool filledBuffer = writer->MarkRecordBoundary(); LogAssert(filledBuffer == false); while (err == DrError_OK && filledBuffer == false && (nextRecord = arrayItem->NextRecordUntyped()) != NULL) { currentPosition = writer->GetBufferOffset(); err = SerializeUntyped(nextRecord, writer); if (err == DrError_OK) { filledBuffer = writer->MarkRecordBoundary(); } } if (err != DrError_OK) { LogAssert(writer->GetStatus() == DrError_OK); writer->SetBufferOffset(currentPosition); pFailureItem->Attach(RChannelMarkerItem:: CreateErrorItem(RChannelItem_MarshalError, err)); return DryadError_ChannelAbort; } if (filledBuffer) { return DrError_IncompleteOperation; } return DrError_OK; } DrError AlternativeRecordMarshalerBase:: SerializeUntyped(void* record, DrMemoryBufferWriter* writer) { return (*m_function)(record, writer); } UntypedAlternativeRecordMarshaler:: UntypedAlternativeRecordMarshaler(RecordSerializerFunction* function) : AlternativeRecordMarshalerBase(function) { } StdAlternativeRecordMarshalerFactory:: StdAlternativeRecordMarshalerFactory(RecordSerializerFunction* function) { m_function = function; } void StdAlternativeRecordMarshalerFactory:: MakeMarshaler(RChannelItemMarshalerRef* pMarshaler, DVErrorReporter* errorReporter) { pMarshaler->Attach(new UntypedAlternativeRecordMarshaler(m_function)); }
24.063979
100
0.62953
TheWhiteEagle
1f912a21fa0f0ff1efadb3bd28be31f267a9c009
1,802
cpp
C++
components/arduino/libraries/UC20/call.cpp
pornpol/enres_logger_idf
b3024594e94d70e9c83f7738261fb70696521188
[ "Apache-2.0" ]
null
null
null
components/arduino/libraries/UC20/call.cpp
pornpol/enres_logger_idf
b3024594e94d70e9c83f7738261fb70696521188
[ "Apache-2.0" ]
null
null
null
components/arduino/libraries/UC20/call.cpp
pornpol/enres_logger_idf
b3024594e94d70e9c83f7738261fb70696521188
[ "Apache-2.0" ]
null
null
null
#include "call.h" #include "TEE_UC20.h" CALL:: CALL(){} unsigned char CALL:: Call(String call_number) /* return 0 = Timeout return 1 = OK return 2 = NO CARRIER return 3 = BUSY */ { gsm.print(F("ATD")); gsm.print(call_number); gsm.println(F(";")); while(!gsm.available()) {} gsm.start_time_out(); while(1) { String req = gsm.readStringUntil('\n'); if(req.indexOf(F("OK")) != -1) { gsm.debug(F("OK")); return(1); } if(req.indexOf(F("NO CARRIER")) != -1) { gsm.debug(F("NO CARRIER")); return(2); } if(req.indexOf(F("BUSY")) != -1) { gsm.debug(F("BUSY")); return(2); } if(gsm.time_out(10000)) { gsm.debug(F("Error")); return(0); } } return(0); } bool CALL:: Answer() { gsm.println(F("ATA")); return(gsm.wait_ok(3000)); } bool CALL:: DisconnectExisting() { gsm.println(F("ATH")); return(gsm.wait_ok(3000)); } bool CALL:: HangUp() { gsm.println(F("AT+CHUP")); return(gsm.wait_ok(3000)); } String CALL:: CurrentCallsMe() { gsm.println(F("AT+CLCC")); while(!gsm.available()) {} gsm.start_time_out(); while(1) { String req = gsm.readStringUntil('\n'); if(req.indexOf(F("+CLCC")) != -1) { char index1 = req.indexOf(F("\"")); char index2 = req.indexOf(F("\""),index1+1); return(req.substring(index1+1,index2)); //Serial.println("req"); return(req); } if(gsm.time_out(20000)) { return(F("CurrentCallsMe Timeout")); } } return(F(" ")); } bool CALL::WaitRing() { while(gsm.available()) { String req = gsm.readStringUntil('\n'); if(req.indexOf(F("RING")) != -1) { return(true); } } return(false); }
16.381818
70
0.523307
pornpol
1f94657cfbb6f826615438c0587ea187ddfb0a8c
695
cpp
C++
codeforces/1185c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1185c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1185c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve() { int n, M; cin >> n >> M; vector<int> cnt(101, 0); auto remain = [&](int lim){ int r = 0; int have = 0; for (int i = 1; i <= 100; i++) { if (have + i*cnt[i] <= lim) { have += i*cnt[i]; r += cnt[i]; } else { r += (lim - have) / i; break; } } return r; }; for (int i = 1; i <= n; i++) { int x; cin >> x; cout << i-1 - remain(M-x) << ' '; cnt[x]++; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
18.289474
45
0.371223
sogapalag
1f9539cd13ceae2303e02e48b7735be4cf82c190
7,190
cpp
C++
src/atta/graphicsSystem/renderers/phongRenderer.cpp
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-06-18T00:48:13.000Z
2021-06-18T00:48:13.000Z
src/atta/graphicsSystem/renderers/phongRenderer.cpp
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
6
2021-03-11T21:01:27.000Z
2021-09-06T19:41:46.000Z
src/atta/graphicsSystem/renderers/phongRenderer.cpp
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-09-04T19:54:41.000Z
2021-09-04T19:54:41.000Z
//-------------------------------------------------- // Atta Graphics System // phongRenderer.cpp // Date: 2021-09-18 // By Breno Cunha Queiroz //-------------------------------------------------- #include <atta/graphicsSystem/renderers/phongRenderer.h> #include <atta/graphicsSystem/graphicsManager.h> #include <atta/graphicsSystem/framebuffer.h> #include <atta/graphicsSystem/renderPass.h> #include <atta/resourceSystem/resourceManager.h> #include <atta/resourceSystem/resources/mesh.h> #include <atta/componentSystem/componentManager.h> #include <atta/componentSystem/components/meshComponent.h> #include <atta/componentSystem/components/transformComponent.h> #include <atta/componentSystem/components/materialComponent.h> #include <atta/componentSystem/components/pointLightComponent.h> #include <atta/componentSystem/components/directionalLightComponent.h> #include <atta/componentSystem/factory.h> namespace atta { PhongRenderer::PhongRenderer(): Renderer("PhongRenderer") { //---------- Create geometry pipeline ----------// // Framebuffer Framebuffer::CreateInfo framebufferInfo {}; framebufferInfo.attachments.push_back({Image::Format::RGB}); framebufferInfo.attachments.push_back({Image::Format::DEPTH32F}); framebufferInfo.width = 500; framebufferInfo.height = 500; framebufferInfo.debugName = StringId("PhongRenderer Framebuffer"); std::shared_ptr<Framebuffer> framebuffer = GraphicsManager::create<Framebuffer>(framebufferInfo); // Shader Group ShaderGroup::CreateInfo shaderGroupInfo {}; shaderGroupInfo.shaderPaths = {"shaders/phongRenderer/shader.vert", "shaders/phongRenderer/shader.frag"}; shaderGroupInfo.debugName = StringId("PhongRenderer Shader Group"); std::shared_ptr<ShaderGroup> shaderGroup = GraphicsManager::create<ShaderGroup>(shaderGroupInfo); // Render Pass RenderPass::CreateInfo renderPassInfo {}; renderPassInfo.framebuffer = framebuffer; renderPassInfo.debugName = StringId("PhongRenderer Render Pass"); std::shared_ptr<RenderPass> renderPass = GraphicsManager::create<RenderPass>(renderPassInfo); Pipeline::CreateInfo pipelineInfo {}; // Vertex input layout pipelineInfo.shaderGroup = shaderGroup; pipelineInfo.layout = { { "inPosition", VertexBufferElement::Type::VEC3 }, { "inNormal", VertexBufferElement::Type::VEC3 }, { "inTexCoord", VertexBufferElement::Type::VEC2 } }; pipelineInfo.renderPass = renderPass; _geometryPipeline = GraphicsManager::create<Pipeline>(pipelineInfo); } PhongRenderer::~PhongRenderer() { } void PhongRenderer::render(std::shared_ptr<Camera> camera) { std::vector<EntityId> entities = ComponentManager::getEntities(); _geometryPipeline->begin(); { // Camera std::shared_ptr<ShaderGroup> shader = _geometryPipeline->getShaderGroup(); shader->setMat4("projection", transpose(camera->getProj())); shader->setMat4("view", transpose(camera->getView())); shader->setVec3("viewPos", camera->getPosition()); //----- Lighting -----// int numPointLights = 0; for(auto entity : entities) { TransformComponent* transform = ComponentManager::getEntityComponent<TransformComponent>(entity); PointLightComponent* pl = ComponentManager::getEntityComponent<PointLightComponent>(entity); DirectionalLightComponent* dl = ComponentManager::getEntityComponent<DirectionalLightComponent>(entity); if(transform && (pl || dl)) { if(pl && numPointLights < 10) { int i = numPointLights++; shader->setVec3(("pointLights["+std::to_string(i)+"].position").c_str(), transform->position); shader->setVec3(("pointLights["+std::to_string(i)+"].intensity").c_str(), pl->intensity); } if(dl) { vec3 before = { 0.0f, -1.0f, 0.0f }; //vec3 direction; //transform->orientation.transformVector(before, direction); shader->setVec3("directionalLight.direction", before); shader->setVec3("directionalLight.intensity", dl->intensity); } if(numPointLights++ == 10) LOG_WARN("PhongRenderer", "Maximum number of point lights reached, 10 lights"); } } shader->setInt("numPointLights", numPointLights); // Ambient shader->setVec3("ambientColor", {0.2f, 0.2f, 0.2f}); shader->setFloat("ambientStrength", 1.0f); // Diffuse shader->setFloat("diffuseStrength", 1.0f); // Specular shader->setFloat("specularStrength", 1.0f); for(auto entity : entities) { MeshComponent* mesh = ComponentManager::getEntityComponent<MeshComponent>(entity); TransformComponent* transform = ComponentManager::getEntityComponent<TransformComponent>(entity); MaterialComponent* material = ComponentManager::getEntityComponent<MaterialComponent>(entity); if(mesh && transform) { mat4 model; model.setPosOriScale(transform->position, transform->orientation, transform->scale); model.transpose(); mat4 invModel = inverse(model); shader->setMat4("model", model); shader->setMat4("invModel", invModel); if(material) { shader->setVec3("material.albedo", material->albedo); shader->setFloat("material.metallic", material->metallic); shader->setFloat("material.roughness", material->roughness); shader->setFloat("material.ao", material->ao); } else { MaterialComponent material {}; shader->setVec3("material.albedo", material.albedo); shader->setFloat("material.metallic", material.metallic); shader->setFloat("material.roughness", material.roughness); shader->setFloat("material.ao", material.ao); } GraphicsManager::getRendererAPI()->renderMesh(mesh->sid); } } } _geometryPipeline->end(); } void PhongRenderer::resize(uint32_t width, uint32_t height) { if(width != _width || height != _height) { _geometryPipeline->getRenderPass()->getFramebuffer()->resize(width, height); _width = width; _height = height; } } }
43.841463
120
0.581224
Brenocq
1f962f82b1838e00f1496520f9adc39e5113eb16
830
cpp
C++
AIC/AIC'20 - Level 1 Training/Week #9/P.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 1 Training/Week #9/P.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 1 Training/Week #9/P.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://codeforces.com/group/Rv2Qzg0DgK/contest/287283/problem/P #include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; ll mod = 1e9 + 7; int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); int x = 2, i = 1; string s; vector<string> v; while (cin >> s) { x = 2, i = 1; v.push_back ("*"); for (auto& elem : s) { if (elem == '[') x = 1, i = 1; else if (elem == ']') x = 2; else if (x == 1) { v.back ().insert (v.back ().begin () + i, elem); i++; } else v.back ().push_back (elem); } } for (auto& elem : v) cout << elem.substr (1, elem.size () - 1) << "\n"; }
23.714286
75
0.459036
MaGnsio
1f98a5a6eabe784a86ee75b9401b51f7c8434f21
307
cpp
C++
test/ControlTest.cpp
lipk/hadamer-cpp
e2905d0a11ea89ed9991dbb4293ed203ae003a26
[ "MIT" ]
1
2020-11-08T02:29:13.000Z
2020-11-08T02:29:13.000Z
test/ControlTest.cpp
lipk/hadamer-cpp
e2905d0a11ea89ed9991dbb4293ed203ae003a26
[ "MIT" ]
null
null
null
test/ControlTest.cpp
lipk/hadamer-cpp
e2905d0a11ea89ed9991dbb4293ed203ae003a26
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <Control.hpp> #include <iostream> #include <limits> TEST_CASE("mapTuple", "[control]") { auto y = mapTuple(std::make_tuple(1, 2.0), [](auto x) { return x+1;}); CHECK(std::get<0>(y) == 2); CHECK(std::get<1>(y) == 3.0); } TEST_CASE("Loop::simple", "[control]") { }
19.1875
74
0.589577
lipk
1f9cd668d29757d4bfd08fd128d8589975358c4a
120
hpp
C++
lib/thing/include/ge/thing.hpp
snailbaron/ge
a3859d944c1d2534caaf2e9c52b90181e181aef3
[ "MIT" ]
null
null
null
lib/thing/include/ge/thing.hpp
snailbaron/ge
a3859d944c1d2534caaf2e9c52b90181e181aef3
[ "MIT" ]
null
null
null
lib/thing/include/ge/thing.hpp
snailbaron/ge
a3859d944c1d2534caaf2e9c52b90181e181aef3
[ "MIT" ]
null
null
null
#pragma once #include "ge/thing/entity.hpp" #include "ge/thing/entity_manager.hpp" #include "ge/thing/entity_pool.hpp"
20
38
0.766667
snailbaron
1f9e78bcc4ce09c6837b9ebcb0fc1bcc349ce947
939
hpp
C++
include/awl/backends/x11/window/original_class_hint.hpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
include/awl/backends/x11/window/original_class_hint.hpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
include/awl/backends/x11/window/original_class_hint.hpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#ifndef AWL_BACKENDS_X11_WINDOW_ORIGINAL_CLASS_HINT_HPP_INCLUDED #define AWL_BACKENDS_X11_WINDOW_ORIGINAL_CLASS_HINT_HPP_INCLUDED #include <awl/backends/x11/window/class_hint.hpp> #include <awl/detail/symbol.hpp> #include <fcppt/nonmovable.hpp> #include <fcppt/unique_ptr_impl.hpp> #include <fcppt/config/external_begin.hpp> #include <X11/Xutil.h> #include <fcppt/config/external_end.hpp> namespace awl::backends::x11::window { class original_class_hint { FCPPT_NONMOVABLE(original_class_hint); public: AWL_DETAIL_SYMBOL explicit original_class_hint(awl::backends::x11::window::class_hint &&); AWL_DETAIL_SYMBOL ~original_class_hint(); [[nodiscard]] AWL_DETAIL_SYMBOL XClassHint *get() const; [[nodiscard]] AWL_DETAIL_SYMBOL awl::backends::x11::window::class_hint const &hint() const; private: class impl; fcppt::unique_ptr<impl> const impl_; awl::backends::x11::window::class_hint const hint_; }; } #endif
22.902439
93
0.783813
freundlich
1f9fd45b0ceda7f28f2186de522daa432e9a94e1
6,850
cc
C++
online_belief_propagation/side_info_ssbm.cc
xxdreck/google-research
dac724bc2b9362d65c26747a8754504fe4c615f8
[ "Apache-2.0" ]
2
2022-01-21T18:15:34.000Z
2022-01-25T15:21:34.000Z
online_belief_propagation/side_info_ssbm.cc
xxdreck/google-research
dac724bc2b9362d65c26747a8754504fe4c615f8
[ "Apache-2.0" ]
110
2021-10-01T18:22:38.000Z
2021-12-27T22:08:31.000Z
online_belief_propagation/side_info_ssbm.cc
admariner/google-research
7cee4b22b925581d912e8d993625c180da2a5a4f
[ "Apache-2.0" ]
1
2022-02-10T10:43:10.000Z
2022-02-10T10:43:10.000Z
// Copyright 2021 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "side_info_ssbm.h" #include <assert.h> #include <cmath> #include <iostream> #include "belief_propagation_utils.h" SideInfoSSBM::SideInfoSSBM(double a, double b, double label_confidence, int num_clusters, int radius, int num_vertices) : a_(a), b_(b), label_confidence_(label_confidence), num_clusters_(num_clusters), num_vertices_(num_vertices), radius_(radius) { assert(a_ > 0); assert(b_ >= 0); assert(label_confidence_ >= 0.0); assert(label_confidence_ <= 1.0); assert(num_clusters_ > 0); assert(radius_ > 0); assert(num_vertices_ > 0); assert(a_ <= num_vertices_); assert(b_ <= num_vertices_); } std::vector<int> SideInfoSSBM::GenerateClusters() const { return vertex_labels_; } void SideInfoSSBM::Initialize() { side_infos_.clear(); edge_labels_.clear(); vertex_labels_.clear(); } void SideInfoSSBM::UpdateLabels(int source, const GraphStream* input, const int* side_information) { // Update side information side_infos_.push_back(*side_information); const auto& neighbors = input->GetCurrentNeighborhood(source); // First step: compute the label distribution of all the new edges.. // Mapping of the names here to the names in the paper: // source -> v(t) // nei -> v // lvl2 -> v' for (auto& nei : neighbors) { const auto& lvl2 = input->GetCurrentNeighborhood(nei); std::vector<double> current_edge_label(num_clusters_, 0); for (int j = 0; j < num_clusters_; j++) { for (int i = 0; i < lvl2.size(); i++) { if (lvl2[i] != source) { // Notice that the WeightFunction is applyed to edge_label_ already. current_edge_label[j] += edge_labels_[std::pair<int, int>(lvl2[i], nei)][j]; } } if (j == side_infos_[nei]) { current_edge_label[j] += log(label_confidence_); } else { current_edge_label[j] += log((1 - label_confidence_) / (num_clusters_ - 1)); } } double g_value = 0; for (int i = 0; i < num_clusters_; i++) { g_value += exp(current_edge_label[i]); } double log_g_value = log(g_value); for (int j = 0; j < num_clusters_; j++) { current_edge_label[j] -= log_g_value; } edge_labels_[std::pair<int, int>(nei, source)] = WeightFunction(current_edge_label, num_clusters_, a_, b_); } // Second step: Compute the tree structure of height 'r' around source. // multi_neighbors[i] contains the neighbors of source in distance 'r-i'. std::vector<std::vector<double>> multi_neighbors(radius_ + 1); // The parent to a vertex on the path to source. std::map<int, int> parents; BFS(input, &multi_neighbors, &parents, source, radius_, -1); // Edge weight for a radius of 'r'. for (int r = radius_ - 1; r >= 0; r--) { // Mapping of the names here to the names in the paper: // source -> v(t) // r_nei -> v // nei -> v' // lvl2 -> v'' for (const auto& r_nei : multi_neighbors[r]) { int nei = parents[r_nei]; const auto& lvl2 = input->GetCurrentNeighborhood(nei); std::vector<double> current_edge_label(num_clusters_, 0); for (int j = 0; j < num_clusters_; j++) { for (int i = 0; i < lvl2.size(); i++) { if (lvl2[i] != r_nei) { // Notice that the WeightFunction is applied to edge_label_ already. current_edge_label[j] += edge_labels_[std::pair<int, int>(lvl2[i], nei)][j]; } } if (j == side_infos_[nei]) { current_edge_label[j] += log(label_confidence_); } else { current_edge_label[j] += log((1 - label_confidence_) / (num_clusters_ - 1)); } } double g_value = 0; for (int i = 0; i < num_clusters_; i++) { g_value += exp(current_edge_label[i]); } double log_g_value = log(g_value); for (int j = 0; j < num_clusters_; j++) { current_edge_label[j] -= log_g_value; } edge_labels_[std::pair<int, int>(nei, r_nei)] = WeightFunction(current_edge_label, num_clusters_, a_, b_); } } // We compute the weights of the node after all the nodes are inserted. if (source == num_vertices_ - 1) { // Mapping of the names here to the names in the paper: // i -> u // nei -> v for (int i = 0; i < num_vertices_; i++) { std::vector<double> label(num_clusters_, 0); const auto& neighbors = input->GetCurrentNeighborhood(i); for (int j = 0; j < num_clusters_; j++) { // Notice that the WeightFunction is applied to edge_label_ already. for (const auto& nei : neighbors) { if (edge_labels_.find(std::pair<int, int>(nei, i)) != edge_labels_.end()) label[j] += edge_labels_[std::pair<int, int>(nei, i)][j]; } if (j == side_infos_[i]) { label[j] += log(label_confidence_); } else { label[j] += log((1 - label_confidence_) / (num_clusters_ - 1)); } } int max_index = 0; for (int j = 0; j < num_clusters_; j++) { if (label[j] > label[max_index]) { max_index = j; } } vertex_labels_.push_back(max_index); } } } void SideInfoSSBM::BFS(const GraphStream* input, std::vector<std::vector<double>>* multi_neighbors, std::map<int, int>* parents, int vertex, int radius, int parent) { std::set<int> seen; seen.insert(vertex); // the pari represents (vertex id, radius) std::vector<std::pair<int, int>> queue; queue.push_back(std::pair<int, int>(vertex, radius)); int pointer = 0; while (pointer < queue.size()) { if (queue[pointer].second == 0) { break; } const auto& neighbors = input->GetCurrentNeighborhood(queue[pointer].first); for (const auto& nei : neighbors) { if (seen.find(nei) == seen.end()) { seen.insert(nei); (*parents)[nei] = queue[pointer].first; (*multi_neighbors)[queue[pointer].second - 1].push_back(nei); queue.push_back(std::pair<int, int>(nei, queue[pointer].second - 1)); } } pointer++; } }
34.59596
80
0.60365
xxdreck
1fa22d5bc9102f5063e86fbaa6bc1a06f6f6bf15
5,239
cc
C++
src/_Meddly/src/storage/ct_styles.cc
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
6
2018-05-30T23:02:14.000Z
2022-01-19T07:30:46.000Z
src/_Meddly/src/storage/ct_styles.cc
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
null
null
null
src/_Meddly/src/storage/ct_styles.cc
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
2
2018-07-13T18:53:27.000Z
2021-04-12T17:54:02.000Z
/* Meddly: Multi-terminal and Edge-valued Decision Diagram LibrarY. Copyright (C) 2009, Iowa State University Research Foundation, Inc. This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "ct_styles.h" // #define DEBUG_SLOW // #define DEBUG_CT_SEARCHES // #define DEBUG_CT_SLOTS // #define DEBUG_REHASH // #define DEBUG_TABLE2LIST // #define DEBUG_LIST2TABLE // #define DEBUG_CTALLOC // #define DEBUG_ISDEAD // #define DEBUG_ISSTALE // #define DEBUG_REMOVESTALES // #define DEBUG_REMOVESTALES_DETAILS // #define DEBUG_CT_SCAN // #define DEBUG_CT // #define DEBUG_VALIDATE_COUNTS #define INTEGRATED_MEMMAN #include "../hash_stream.h" #include <climits> #include "ct_typebased.h" #include "ct_none.h" // ********************************************************************** // * * // * monolithic_chained_style methods * // * * // ********************************************************************** MEDDLY::monolithic_chained_style::monolithic_chained_style() { } MEDDLY::compute_table* MEDDLY::monolithic_chained_style::create(const ct_initializer::settings &s) const { switch (s.compression) { case ct_initializer::None: return new ct_none<true, true>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<true, true>(s, 0, 0); default: return 0; } } bool MEDDLY::monolithic_chained_style::usesMonolithic() const { return true; } // ********************************************************************** // * * // * monolithic_unchained_style methods * // * * // ********************************************************************** MEDDLY::monolithic_unchained_style::monolithic_unchained_style() { } MEDDLY::compute_table* MEDDLY::monolithic_unchained_style::create(const ct_initializer::settings &s) const { switch (s.compression) { case ct_initializer::None: return new ct_none<true, false>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<true, false>(s, 0, 0); default: return 0; } } bool MEDDLY::monolithic_unchained_style::usesMonolithic() const { return true; } // ********************************************************************** // * * // * operation_chained_style methods * // * * // ********************************************************************** MEDDLY::operation_chained_style::operation_chained_style() { } MEDDLY::compute_table* MEDDLY::operation_chained_style::create(const ct_initializer::settings &s, operation* op, unsigned slot) const { switch (s.compression) { case ct_initializer::None: return new ct_none<false, true>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<false, true>(s, 0, 0); default: return 0; } } bool MEDDLY::operation_chained_style::usesMonolithic() const { return false; } // ********************************************************************** // * * // * operation_unchained_style methods * // * * // ********************************************************************** MEDDLY::operation_unchained_style::operation_unchained_style() { } MEDDLY::compute_table* MEDDLY::operation_unchained_style::create(const ct_initializer::settings &s, operation* op, unsigned slot) const { switch (s.compression) { case ct_initializer::None: return new ct_none<false, false>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<false, false>(s, 0, 0); default: return 0; } } bool MEDDLY::operation_unchained_style::usesMonolithic() const { return false; }
31
113
0.493033
asminer
1fa7dcb5c61b14ca782a826f60f4a615aa8757f8
3,504
cpp
C++
SGCore/sgwin.cpp
mohemam/SGL
8d2b76bb199b8745b4c58fc39ad48e6b443da5e9
[ "MIT" ]
null
null
null
SGCore/sgwin.cpp
mohemam/SGL
8d2b76bb199b8745b4c58fc39ad48e6b443da5e9
[ "MIT" ]
null
null
null
SGCore/sgwin.cpp
mohemam/SGL
8d2b76bb199b8745b4c58fc39ad48e6b443da5e9
[ "MIT" ]
null
null
null
#include "sgwin.h" #include <iostream> #include <Windows.h> namespace sgl { void SetConsoleWindowSize(int width, int height) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); if (h == INVALID_HANDLE_VALUE) throw std::runtime_error("Unable to get stdout handle."); // If either dimension is greater than the largest console window we can have, // there is no point in attempting the change. { COORD largestSize = GetLargestConsoleWindowSize(h); if (width > largestSize.X) throw std::invalid_argument("The width is too large."); if (height > largestSize.Y) throw std::invalid_argument("The height is too large."); } CONSOLE_SCREEN_BUFFER_INFO bufferInfo; if (!GetConsoleScreenBufferInfo(h, &bufferInfo)) throw std::runtime_error("Unable to retrieve screen buffer info."); SMALL_RECT& winInfo = bufferInfo.srWindow; COORD windowSize = { winInfo.Right - winInfo.Left + 1, winInfo.Bottom - winInfo.Top + 1 }; if (windowSize.X > width || windowSize.Y > height) { // window size needs to be adjusted before the buffer size can be reduced. SMALL_RECT info = { 0, 0, width < windowSize.X ? width - 1 : windowSize.X - 1, height < windowSize.Y ? height - 1 : windowSize.Y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) throw std::runtime_error("Unable to resize window before resizing buffer."); } COORD size = { width, height }; if (!SetConsoleScreenBufferSize(h, size)) throw std::runtime_error("Unable to resize screen buffer."); SMALL_RECT info = { 0, 0, width - 1, height - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) throw std::runtime_error("Unable to resize window after resizing buffer."); } void ClearScreen(char fill) { COORD tl = { 0,0 }; CONSOLE_SCREEN_BUFFER_INFO s; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(console, &s); DWORD written, cells = s.dwSize.X * s.dwSize.Y; FillConsoleOutputCharacter(console, fill, cells, tl, &written); FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written); SetConsoleCursorPosition(console, tl); } wchar_t* CreateScreenBuffer(int width, int height) { wchar_t* screen = new wchar_t[width * height]; HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL); SetConsoleActiveScreenBuffer(hConsole); DWORD dwBytesWritten = 0; return screen; } void SetConsoleColor(unsigned int fg_color, unsigned int bg_color) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, fg_color | (bg_color * 16)); } void CopyToClipboard(const std::string& s) { const size_t len = s.length() + 1; HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); memcpy(GlobalLock(hMem), s.c_str(), len); GlobalUnlock(hMem); OpenClipboard(0); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); } void ShowLastSystemError() { LPSTR messageBuffer; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, // source GetLastError(), 0, // lang (LPSTR)&messageBuffer, 0, NULL); std::cerr << messageBuffer << '\n'; LocalFree(messageBuffer); } void MoveWindow(unsigned int left, unsigned int top) { HWND console = GetConsoleWindow(); RECT r; GetWindowRect(console, &r); //stores the console's current dimensions MoveWindow(console, left, top, (r.right-r.left), (r.top - r.bottom), TRUE); } }
28.721311
116
0.704909
mohemam
1faa37a286d85e09b150c0ff75dc229e3fc5c739
496
cpp
C++
bucket_AE/tinyxml2/patches/patch-tinyxml2.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
17
2017-04-22T21:53:52.000Z
2021-01-21T16:57:55.000Z
bucket_AE/tinyxml2/patches/patch-tinyxml2.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
186
2017-09-12T20:46:52.000Z
2021-11-27T18:15:14.000Z
bucket_AE/tinyxml2/patches/patch-tinyxml2.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
74
2017-09-06T14:48:01.000Z
2021-08-28T02:48:27.000Z
--- tinyxml2.cpp.orig 2021-06-08 18:04:12.223152000 +0200 +++ tinyxml2.cpp 2021-06-08 18:04:35.876513000 +0200 @@ -103,7 +103,7 @@ #if defined(_WIN64) #define TIXML_FSEEK _fseeki64 #define TIXML_FTELL _ftelli64 -#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__ANDROID__) +#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__ANDROID__) #define TIXML_FSEEK fseeko #define TIXML_FTELL ftello #elif defined(__unix__) && defined(__x86_64__)
41.333333
99
0.743952
jrmarino
1fabee3e53ef182cee547c25c1f48a2f9050197d
128
cpp
C++
math/Trig.cpp
nfoste82/engine
9b64077778bf3548a8d1a53bddcaabada7a2957e
[ "MIT" ]
1
2017-02-17T07:15:49.000Z
2017-02-17T07:15:49.000Z
math/Trig.cpp
nfoste82/engine
9b64077778bf3548a8d1a53bddcaabada7a2957e
[ "MIT" ]
null
null
null
math/Trig.cpp
nfoste82/engine
9b64077778bf3548a8d1a53bddcaabada7a2957e
[ "MIT" ]
null
null
null
#include <math.h> #include "Trig.hpp" void Trig::SinCos(float x, float& sn, float& cs) { sn = sinf(x); cs = cosf(x); }
14.222222
48
0.578125
nfoste82
1fb0297c2a3e42e4d568c8d133d5badc83c02700
3,776
cpp
C++
sources/Panel/src/Hardware/HAL/HAL.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
sources/Panel/src/Hardware/HAL/HAL.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
sources/Panel/src/Hardware/HAL/HAL.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
// 2022/04/20 16:52:11 (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by #include "defines.h" #include "Hardware/HAL/HAL.h" #include "Hardware/HAL/HAL_PINS.h" namespace HAL { static void SystemClockConfig(); } void HAL::Init() { SystemClockConfig(); HAL_Init(); HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); /* System interrupt init*/ /* MemoryManagement_IRQn interrupt configuration */ HAL_NVIC_SetPriority(MemoryManagement_IRQn, 0, 0); /* BusFault_IRQn interrupt configuration */ HAL_NVIC_SetPriority(BusFault_IRQn, 0, 0); /* UsageFault_IRQn interrupt configuration */ HAL_NVIC_SetPriority(UsageFault_IRQn, 0, 0); /* SVCall_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SVCall_IRQn, 0, 0); /* DebugMonitor_IRQn interrupt configuration */ HAL_NVIC_SetPriority(DebugMonitor_IRQn, 0, 0); /* PendSV_IRQn interrupt configuration */ HAL_NVIC_SetPriority(PendSV_IRQn, 0, 0); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); __HAL_RCC_GPIOI_CLK_ENABLE(); __HAL_RCC_DMA2D_CLK_ENABLE(); __HAL_RCC_LTDC_CLK_ENABLE(); __HAL_RCC_TIM4_CLK_ENABLE(); HAL_PINS::Init(); HAL_BUS::Init(); HAL_LTDC::Init(); } void HAL::SystemClockConfig() { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; /**Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = 16; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 16; RCC_OscInitStruct.PLL.PLLN = 360; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 4; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { ERROR_HANDLER(); } /**Activate the Over-Drive mode */ if (HAL_PWREx_EnableOverDrive() != HAL_OK) { ERROR_HANDLER(); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) { ERROR_HANDLER(); } PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LTDC; PeriphClkInitStruct.PLLSAI.PLLSAIN = 100; PeriphClkInitStruct.PLLSAI.PLLSAIR = 2; PeriphClkInitStruct.PLLSAIDivR = RCC_PLLSAIDIVR_2; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { ERROR_HANDLER(); } /**Configure the Systick interrupt time */ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); } void HAL::ErrorHandler(const char *, int) { while (true) {}; }
27.97037
120
0.727225
Sasha7b9Work
1fb729683d50a1300d855f1baf5a597308eca89a
122
hh
C++
dead_pixel/gfx/graphics_context.hh
ErrorOnUsername/dead-pixel
a13dba2a5be60c1b0d4112fc3557639d6d5af29a
[ "BSD-2-Clause" ]
null
null
null
dead_pixel/gfx/graphics_context.hh
ErrorOnUsername/dead-pixel
a13dba2a5be60c1b0d4112fc3557639d6d5af29a
[ "BSD-2-Clause" ]
null
null
null
dead_pixel/gfx/graphics_context.hh
ErrorOnUsername/dead-pixel
a13dba2a5be60c1b0d4112fc3557639d6d5af29a
[ "BSD-2-Clause" ]
null
null
null
#pragma once namespace DP::GraphicsContext { void init(void* window_handle); void swap_buffers(void* window_handle); }
13.555556
39
0.770492
ErrorOnUsername
1fb9879d7534cbfebe84c694c658ef790d5a7510
1,161
cpp
C++
pysrc/enumer-test.cpp
CrackerCat/xed
428712c28e831573579b7f749db63d3a58dcdbd9
[ "Apache-2.0" ]
1,261
2016-12-16T14:29:30.000Z
2022-03-30T20:21:25.000Z
pysrc/enumer-test.cpp
CrackerCat/xed
428712c28e831573579b7f749db63d3a58dcdbd9
[ "Apache-2.0" ]
190
2016-12-17T13:44:09.000Z
2022-03-27T09:28:13.000Z
pysrc/enumer-test.cpp
CrackerCat/xed
428712c28e831573579b7f749db63d3a58dcdbd9
[ "Apache-2.0" ]
155
2016-12-16T22:17:20.000Z
2022-02-16T20:53:59.000Z
/// @file enumer-test.cpp // This file was automatically generated. // Do not edit this file. #include <string.h> #include <assert.h> #include "enumer-test.H" typedef struct { const char* name; test_type_t value; } name_table_test_type_t; static const name_table_test_type_t name_array_test_type_t[] = { {"aaa", TEST_TYPE_aaa}, {"bbb", TEST_TYPE_bbb}, {"ccc", TEST_TYPE_ccc}, {"LAST", TEST_TYPE_LAST}, {0, TEST_TYPE_LAST}, }; test_type_t str2test_type_t(const char* s) { const name_table_test_type_t* p = name_array_test_type_t; while( p->name ) { if (strcmp(p->name,s) == 0) { return p->value; } p++; } return TEST_TYPE_LAST; } const char* test_type_t2str(const test_type_t p) { test_type_t type_idx = p; if ( p > TEST_TYPE_LAST) type_idx = TEST_TYPE_LAST; return name_array_test_type_t[type_idx].name; } test_type_t test_type_t_last(void) { return TEST_TYPE_LAST; } /* Here is a skeleton switch statement embedded in a comment switch(p) { case TEST_TYPE_aaa: case TEST_TYPE_bbb: case TEST_TYPE_ccc: case TEST_TYPE_LAST: default: xed_assert(0); } */
18.428571
64
0.680448
CrackerCat
1fbb772427aa4066aea9fd2f1f85b9f133bea4ea
1,536
cpp
C++
unittests/VMRuntime/JSTypedArrayTest.cpp
ScriptBox99/microsoft-hermes-windows
c7eb49152bcb5fa6812c3413a80ffc5bb937bb0c
[ "MIT" ]
3
2022-01-03T20:57:16.000Z
2022-01-26T06:25:58.000Z
unittests/VMRuntime/JSTypedArrayTest.cpp
0xgpapad/hermes
903ca2b44ae0434a5d548af1ec1c10e34bc31836
[ "MIT" ]
null
null
null
unittests/VMRuntime/JSTypedArrayTest.cpp
0xgpapad/hermes
903ca2b44ae0434a5d548af1ec1c10e34bc31836
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/JSTypedArray.h" #include "TestHelpers.h" using namespace hermes::vm; namespace { using JSTypedArrayTest = RuntimeTestFixture; TEST_F(JSTypedArrayTest, BeginAndEndMatchesOnBaseAndSub) { // Make sure that the begin and end pointers match for both JSTypedArrayBase, // and JSTypedArray<T>. Do this for each T. #define TYPED_ARRAY(name, type) \ { \ auto result = name##Array::allocate(runtime, 10); \ ASSERT_FALSE(isException(result)); \ Handle<name##Array> array = Handle<name##Array>::vmcast(*result); \ EXPECT_EQ( \ reinterpret_cast<uintptr_t>(array->begin(runtime)), \ reinterpret_cast<uintptr_t>( \ Handle<JSTypedArrayBase>::vmcast(array)->begin(runtime))); \ EXPECT_EQ( \ reinterpret_cast<uintptr_t>(array->end(runtime)), \ reinterpret_cast<uintptr_t>( \ Handle<JSTypedArrayBase>::vmcast(array)->end(runtime))); \ } #include "hermes/VM/TypedArrays.def" } } // namespace
38.4
79
0.527344
ScriptBox99
1fbbf6cf2d744c821120b32717568211da71711a
2,820
cpp
C++
src/renderer/base/fontinfo.cpp
RifasM/terminal
a5f31f77bc77068ba1eb3e3deec56c5a2e9e4513
[ "MIT" ]
7
2021-02-18T01:15:39.000Z
2022-03-22T07:08:34.000Z
src/renderer/base/fontinfo.cpp
RifasM/terminal
a5f31f77bc77068ba1eb3e3deec56c5a2e9e4513
[ "MIT" ]
116
2019-07-08T21:28:45.000Z
2021-07-28T21:12:21.000Z
src/renderer/base/fontinfo.cpp
RifasM/terminal
a5f31f77bc77068ba1eb3e3deec56c5a2e9e4513
[ "MIT" ]
1
2019-11-25T00:13:17.000Z
2019-11-25T00:13:17.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include "..\inc\FontInfo.hpp" bool operator==(const FontInfo& a, const FontInfo& b) { return (static_cast<FontInfoBase>(a) == static_cast<FontInfoBase>(b) && a._coordSize == b._coordSize && a._coordSizeUnscaled == b._coordSizeUnscaled); } FontInfo::FontInfo(_In_ PCWSTR const pwszFaceName, const BYTE bFamily, const LONG lWeight, const COORD coordSize, const UINT uiCodePage, const bool fSetDefaultRasterFont /*= false*/) : FontInfoBase(pwszFaceName, bFamily, lWeight, fSetDefaultRasterFont, uiCodePage), _coordSize(coordSize), _coordSizeUnscaled(coordSize) { ValidateFont(); } FontInfo::FontInfo(const FontInfo& fiFont) : FontInfoBase(fiFont), _coordSize(fiFont.GetSize()), _coordSizeUnscaled(fiFont.GetUnscaledSize()) { } COORD FontInfo::GetUnscaledSize() const { return _coordSizeUnscaled; } COORD FontInfo::GetSize() const { return _coordSize; } void FontInfo::SetFromEngine(_In_ PCWSTR const pwszFaceName, const BYTE bFamily, const LONG lWeight, const bool fSetDefaultRasterFont, const COORD coordSize, const COORD coordSizeUnscaled) { FontInfoBase::SetFromEngine(pwszFaceName, bFamily, lWeight, fSetDefaultRasterFont); _coordSize = coordSize; _coordSizeUnscaled = coordSizeUnscaled; _ValidateCoordSize(); } void FontInfo::ValidateFont() { _ValidateCoordSize(); } void FontInfo::_ValidateCoordSize() { // a (0,0) font is okay for the default raster font, as we will eventually set the dimensions based on the font GDI // passes back to us. if (!IsDefaultRasterFontNoSize()) { // Initialize X to 1 so we don't divide by 0 if (_coordSize.X == 0) { _coordSize.X = 1; } // If we have no font size, we want to use 8x12 by default if (_coordSize.Y == 0) { _coordSize.X = 8; _coordSize.Y = 12; _coordSizeUnscaled = _coordSize; } } } #pragma warning(push) #pragma warning(suppress : 4356) Microsoft::Console::Render::IFontDefaultList* FontInfo::s_pFontDefaultList; #pragma warning(pop) void FontInfo::s_SetFontDefaultList(_In_ Microsoft::Console::Render::IFontDefaultList* const pFontDefaultList) { FontInfoBase::s_SetFontDefaultList(pFontDefaultList); }
28.2
120
0.591844
RifasM
1fbca0d907aacafaa7b89b23eebdfd582b681432
30,967
cpp
C++
dali-toolkit/internal/text/cursor-helper-functions.cpp
tizenorg/platform.core.uifw.dali-toolkit
146486a8c7410a2f2a20a6d670145fe855672b96
[ "Apache-2.0" ]
null
null
null
dali-toolkit/internal/text/cursor-helper-functions.cpp
tizenorg/platform.core.uifw.dali-toolkit
146486a8c7410a2f2a20a6d670145fe855672b96
[ "Apache-2.0" ]
null
null
null
dali-toolkit/internal/text/cursor-helper-functions.cpp
tizenorg/platform.core.uifw.dali-toolkit
146486a8c7410a2f2a20a6d670145fe855672b96
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2016 Samsung Electronics Co., 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. * */ // FILE HEADER #include <dali-toolkit/internal/text/cursor-helper-functions.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/text/glyph-metrics-helper.h> namespace { #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction. struct FindWordData { FindWordData( const Dali::Toolkit::Text::Character* const textBuffer, Dali::Toolkit::Text::Length totalNumberOfCharacters, Dali::Toolkit::Text::CharacterIndex hitCharacter, bool isWhiteSpace, bool isNewParagraph ) : textBuffer( textBuffer ), totalNumberOfCharacters( totalNumberOfCharacters ), hitCharacter( hitCharacter ), foundIndex( 0u ), isWhiteSpace( isWhiteSpace ), isNewParagraph( isNewParagraph ) {} ~FindWordData() {} const Dali::Toolkit::Text::Character* const textBuffer; Dali::Toolkit::Text::Length totalNumberOfCharacters; Dali::Toolkit::Text::CharacterIndex hitCharacter; Dali::Toolkit::Text::CharacterIndex foundIndex; bool isWhiteSpace : 1u; bool isNewParagraph : 1u; }; bool IsWhiteSpaceOrNewParagraph( Dali::Toolkit::Text::Character character, bool isHitWhiteSpace, bool isHitWhiteSpaceOrNewParagraph ) { bool isWhiteSpaceOrNewParagraph = false; if( isHitWhiteSpaceOrNewParagraph ) { if( isHitWhiteSpace ) { // Whether the current character is a white space. Note a new paragraph character is a white space as well but here is not wanted. isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character ) && !Dali::TextAbstraction::IsNewParagraph( character ); } else { // Whether the current character is a new paragraph character. isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsNewParagraph( character ); } } else { // Whether the current character is a white space or a new paragraph character (note the new paragraph character is a white space as well). isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character ); } return isWhiteSpaceOrNewParagraph; } void FindStartOfWord( FindWordData& data ) { const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph; for( data.foundIndex = data.hitCharacter; data.foundIndex > 0; --data.foundIndex ) { const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex - 1u ); const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character, data.isWhiteSpace, isHitWhiteSpaceOrNewParagraph ); if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph ) { break; } } } void FindEndOfWord( FindWordData& data ) { const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph; for( data.foundIndex = data.hitCharacter + 1u; data.foundIndex < data.totalNumberOfCharacters; ++data.foundIndex ) { const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex ); const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character, data.isWhiteSpace, isHitWhiteSpaceOrNewParagraph ); if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph ) { break; } } } } //namespace namespace Dali { namespace Toolkit { namespace Text { LineIndex GetClosestLine( VisualModelPtr visualModel, float visualY ) { float totalHeight = 0.f; LineIndex lineIndex = 0u; const Vector<LineRun>& lines = visualModel->mLines; for( Vector<LineRun>::ConstIterator it = lines.Begin(), endIt = lines.End(); it != endIt; ++it, ++lineIndex ) { const LineRun& lineRun = *it; // The line height is the addition of the line ascender and the line descender. // However, the line descender has a negative value, hence the subtraction. totalHeight += lineRun.ascender - lineRun.descender; if( visualY < totalHeight ) { return lineIndex; } } if( lineIndex == 0u ) { return 0; } return lineIndex-1; } float CalculateLineOffset( const Vector<LineRun>& lines, LineIndex lineIndex ) { float offset = 0.f; for( Vector<LineRun>::ConstIterator it = lines.Begin(), endIt = lines.Begin() + lineIndex; it != endIt; ++it ) { const LineRun& lineRun = *it; // The line height is the addition of the line ascender and the line descender. // However, the line descender has a negative value, hence the subtraction. offset += lineRun.ascender - lineRun.descender; } return offset; } CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, LogicalModelPtr logicalModel, MetricsPtr metrics, float visualX, float visualY ) { DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY ); CharacterIndex logicalIndex = 0u; const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count(); const Length totalNumberOfLines = visualModel->mLines.Count(); if( ( 0 == totalNumberOfGlyphs ) || ( 0 == totalNumberOfLines ) ) { return logicalIndex; } // Find which line is closest. const LineIndex lineIndex = Text::GetClosestLine( visualModel, visualY ); // Convert from text's coords to line's coords. const LineRun& line = *( visualModel->mLines.Begin() + lineIndex ); // Transform the tap point from text's coords to line's coords. visualX -= line.alignmentOffset; // Get the positions of the glyphs. const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin(); // Get the character to glyph conversion table. const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin(); // Get the glyphs per character table. const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin(); // Get the characters per glyph table. const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin(); // Get the glyph's info buffer. const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin(); const CharacterIndex startCharacter = line.characterRun.characterIndex; const CharacterIndex endCharacter = line.characterRun.characterIndex + line.characterRun.numberOfCharacters; DALI_ASSERT_DEBUG( endCharacter <= logicalModel->mText.Count() && "Invalid line info" ); // Whether this line is a bidirectional line. const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( startCharacter ); // The character's direction buffer. const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL; // Whether there is a hit on a glyph. bool matched = false; // Traverses glyphs in visual order. To do that use the visual to logical conversion table. CharacterIndex visualIndex = startCharacter; Length numberOfVisualCharacters = 0u; for( ; visualIndex < endCharacter; ++visualIndex ) { // The character in logical order. const CharacterIndex characterLogicalOrderIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( visualIndex ) : visualIndex ); const CharacterDirection direction = ( bidiLineFetched ? *( directionsBuffer + characterLogicalOrderIndex ) : LTR ); // The number of glyphs for that character const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterLogicalOrderIndex ); ++numberOfVisualCharacters; if( 0u != numberOfGlyphs ) { // Get the first character/glyph of the group of glyphs. const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfVisualCharacters; const CharacterIndex firstLogicalCharacterIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( firstVisualCharacterIndex ) : firstVisualCharacterIndex ); const GlyphIndex firstLogicalGlyphIndex = *( charactersToGlyphBuffer + firstLogicalCharacterIndex ); // Get the metrics for the group of glyphs. GlyphMetrics glyphMetrics; GetGlyphsMetrics( firstLogicalGlyphIndex, numberOfGlyphs, glyphMetrics, glyphInfoBuffer, metrics ); // Get the position of the first glyph. const Vector2& position = *( positionsBuffer + firstLogicalGlyphIndex ); // Whether the glyph can be split, like Latin ligatures fi, ff or Arabic (ل + ا). Length numberOfCharacters = *( charactersPerGlyphBuffer + firstLogicalGlyphIndex ); if( direction != LTR ) { // As characters are being traversed in visual order, // for right to left ligatures, the character which contains the // number of glyphs in the table is found first. // Jump the number of characters to the next glyph is needed. if( 0u == numberOfCharacters ) { // TODO: This is a workaround to fix an issue with complex characters in the arabic // script like i.e. رّ or الأَبْجَدِيَّة العَرَبِيَّة // There are characters that are not shaped in one glyph but in combination with // the next one generates two of them. // The visual to logical conversion table have characters in different order than // expected even if all of them are arabic. // The workaround doesn't fix the issue completely but it prevents the application // to hang in an infinite loop. // Find the number of characters. for( GlyphIndex index = firstLogicalGlyphIndex + 1u; ( 0u == numberOfCharacters ) && ( index < totalNumberOfGlyphs ) ; ++index ) { numberOfCharacters = *( charactersPerGlyphBuffer + index ); } if( 2u > numberOfCharacters ) { continue; } --numberOfCharacters; } visualIndex += numberOfCharacters - 1u; } // Get the script of the character. const Script script = logicalModel->GetScript( characterLogicalOrderIndex ); const bool isInterglyphIndex = ( numberOfCharacters > numberOfGlyphs ) && HasLigatureMustBreak( script ); const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u; const float glyphAdvance = glyphMetrics.advance / static_cast<float>( numberOfBlocks ); CharacterIndex index = 0u; for( ; index < numberOfBlocks; ++index ) { // Find the mid-point of the area containing the glyph const float glyphCenter = -glyphMetrics.xBearing + position.x + ( static_cast<float>( index ) + 0.5f ) * glyphAdvance; if( visualX < glyphCenter ) { matched = true; break; } } if( matched ) { // If the glyph is shaped from more than one character, it matches the character of the glyph. visualIndex = firstVisualCharacterIndex + index; break; } numberOfVisualCharacters = 0u; } } // The number of characters of the whole text. const Length totalNumberOfCharacters = logicalModel->mText.Count(); // Return the logical position of the cursor in characters. if( !matched ) { // If no character is matched, then the last character (in visual order) of the line is used. visualIndex = endCharacter; } // Get the paragraph direction. const CharacterDirection paragraphDirection = line.direction; if( totalNumberOfCharacters != visualIndex ) { // The visual index is not at the end of the text. if( LTR == paragraphDirection ) { // The paragraph direction is left to right. if( visualIndex == endCharacter ) { // It places the cursor just before the last character in visual order. // i.e. it places the cursor just before the '\n' or before the last character // if there is a long line with no word breaks which is wrapped. // It doesn't check if the closest line is the last one like the RTL branch below // because the total number of characters is different than the visual index and // the visual index is the last character of the line. --visualIndex; } } else { // The paragraph direction is right to left. if( ( lineIndex != totalNumberOfLines - 1u ) && // is not the last line. ( visualIndex == startCharacter ) ) { // It places the cursor just after the first character in visual order. // i.e. it places the cursor just after the '\n' or after the last character // if there is a long line with no word breaks which is wrapped. // If the last line doesn't end with '\n' it won't increase the visual index // placing the cursor at the beginning of the line (in visual order). ++visualIndex; } } } else { // The visual index is at the end of text. // If the text ends with a new paragraph character i.e. a '\n', an extra line with no characters is added at the end of the text. // This branch checks if the closest line is the one with the last '\n'. If it is, it decrements the visual index to place // the cursor just before the last '\n'. if( ( lineIndex != totalNumberOfLines - 1u ) && TextAbstraction::IsNewParagraph( *( logicalModel->mText.Begin() + visualIndex - 1u ) ) ) { --visualIndex; } } logicalIndex = ( bidiLineFetched ? logicalModel->GetLogicalCursorIndex( visualIndex ) : visualIndex ); DALI_LOG_INFO( gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex ); DALI_ASSERT_DEBUG( ( logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0 ) && "GetClosestCursorIndex - Out of bounds index" ); return logicalIndex; } void GetCursorPosition( VisualModelPtr visualModel, LogicalModelPtr logicalModel, MetricsPtr metrics, CharacterIndex logical, CursorInfo& cursorInfo ) { // Whether the logical cursor position is at the end of the whole text. const bool isLastPosition = logicalModel->mText.Count() == logical; // Get the line where the character is laid-out. const CharacterIndex characterOfLine = isLastPosition ? ( logical - 1u ) : logical; // Whether the cursor is in the last position and the last position is a new paragraph character. const bool isLastNewParagraph = isLastPosition && TextAbstraction::IsNewParagraph( *( logicalModel->mText.Begin() + characterOfLine ) ); const LineRun* const modelLines = visualModel->mLines.Begin(); const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterOfLine ); const LineRun& line = *( modelLines + lineIndex ); if( isLastNewParagraph ) { // The cursor is in a new line with no characters. Place the cursor in that line. const LineIndex newLineIndex = lineIndex + 1u; const LineRun& newLine = *( modelLines + newLineIndex ); cursorInfo.isSecondaryCursor = false; // Set the line offset and height. cursorInfo.lineOffset = CalculateLineOffset( visualModel->mLines, newLineIndex ); // The line height is the addition of the line ascender and the line descender. // However, the line descender has a negative value, hence the subtraction. cursorInfo.lineHeight = newLine.ascender - newLine.descender; // Set the primary cursor's height. cursorInfo.primaryCursorHeight = cursorInfo.lineHeight; // Set the primary cursor's position. cursorInfo.primaryPosition.x = 0.f; cursorInfo.primaryPosition.y = cursorInfo.lineOffset; // Transform the cursor info from line's coords to text's coords. cursorInfo.primaryPosition.x += ( LTR == line.direction ) ? 0.f : visualModel->mControlSize.width; } else { // Whether this line is a bidirectional line. const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( characterOfLine ); // Check if the logical position is the first or the last one of the line. const bool isFirstPositionOfLine = line.characterRun.characterIndex == logical; const bool isLastPositionOfLine = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == logical; // 'logical' is the logical 'cursor' index. // Get the next and current logical 'character' index. const CharacterIndex characterIndex = isFirstPositionOfLine ? logical : logical - 1u; const CharacterIndex nextCharacterIndex = isLastPositionOfLine ? characterIndex : logical; // The character's direction buffer. const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL; CharacterDirection isCurrentRightToLeft = false; CharacterDirection isNextRightToLeft = false; if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right. { isCurrentRightToLeft = *( directionsBuffer + characterIndex ); isNextRightToLeft = *( directionsBuffer + nextCharacterIndex ); } // Get the paragraph's direction. const CharacterDirection isRightToLeftParagraph = line.direction; // Check whether there is an alternative position: cursorInfo.isSecondaryCursor = ( ( !isLastPositionOfLine && ( isCurrentRightToLeft != isNextRightToLeft ) ) || ( isLastPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) || ( isFirstPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) ); // Set the line offset and height. cursorInfo.lineOffset = CalculateLineOffset( visualModel->mLines, lineIndex ); // The line height is the addition of the line ascender and the line descender. // However, the line descender has a negative value, hence the subtraction. cursorInfo.lineHeight = line.ascender - line.descender; // Calculate the primary cursor. CharacterIndex index = characterIndex; if( cursorInfo.isSecondaryCursor ) { // If there is a secondary position, the primary cursor may be in a different place than the logical index. if( isLastPositionOfLine ) { // The position of the cursor after the last character needs special // care depending on its direction and the direction of the paragraph. // Need to find the first character after the last character with the paragraph's direction. // i.e l0 l1 l2 r0 r1 should find r0. index = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u; if( bidiLineFetched ) { index = logicalModel->GetLogicalCharacterIndex( index ); } } else if( isFirstPositionOfLine ) { index = isRightToLeftParagraph ? line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u : line.characterRun.characterIndex; if( bidiLineFetched ) { index = logicalModel->GetLogicalCharacterIndex( index ); } } else { index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? characterIndex : nextCharacterIndex; } } const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin(); const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin(); const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin(); const CharacterIndex* const glyphsToCharactersBuffer = visualModel->mGlyphsToCharacters.Begin(); const Vector2* const glyphPositionsBuffer = visualModel->mGlyphPositions.Begin(); const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin(); // Convert the cursor position into the glyph position. const GlyphIndex primaryGlyphIndex = *( charactersToGlyphBuffer + index ); const Length primaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index ); const Length primaryNumberOfCharacters = *( charactersPerGlyphBuffer + primaryGlyphIndex ); // Get the metrics for the group of glyphs. GlyphMetrics glyphMetrics; GetGlyphsMetrics( primaryGlyphIndex, primaryNumberOfGlyphs, glyphMetrics, glyphInfoBuffer, metrics ); // Whether to add the glyph's advance to the cursor position. // i.e if the paragraph is left to right and the logical cursor is zero, the position is the position of the first glyph and the advance is not added, // if the logical cursor is one, the position is the position of the first glyph and the advance is added. // A 'truth table' was build and an online Karnaugh map tool was used to simplify the logic. // // FLCP A // ------ // 0000 1 // 0001 1 // 0010 0 // 0011 0 // 0100 1 // 0101 0 // 0110 1 // 0111 0 // 1000 0 // 1001 1 // 1010 0 // 1011 1 // 1100 x // 1101 x // 1110 x // 1111 x // // Where F -> isFirstPosition // L -> isLastPosition // C -> isCurrentRightToLeft // P -> isRightToLeftParagraph // A -> Whether to add the glyph's advance. const bool addGlyphAdvance = ( ( isLastPositionOfLine && !isRightToLeftParagraph ) || ( isFirstPositionOfLine && isRightToLeftParagraph ) || ( !isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft ) ); float glyphAdvance = addGlyphAdvance ? glyphMetrics.advance : 0.f; if( !isLastPositionOfLine && ( primaryNumberOfCharacters > 1u ) ) { const CharacterIndex firstIndex = *( glyphsToCharactersBuffer + primaryGlyphIndex ); bool isCurrentRightToLeft = false; if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right. { isCurrentRightToLeft = *( directionsBuffer + index ); } Length numberOfGlyphAdvance = ( isFirstPositionOfLine ? 0u : 1u ) + characterIndex - firstIndex; if( isCurrentRightToLeft ) { numberOfGlyphAdvance = primaryNumberOfCharacters - numberOfGlyphAdvance; } glyphAdvance = static_cast<float>( numberOfGlyphAdvance ) * glyphMetrics.advance / static_cast<float>( primaryNumberOfCharacters ); } // Get the glyph position and x bearing (in the line's coords). const Vector2& primaryPosition = *( glyphPositionsBuffer + primaryGlyphIndex ); // Set the primary cursor's height. cursorInfo.primaryCursorHeight = cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight; // Set the primary cursor's position. cursorInfo.primaryPosition.x = -glyphMetrics.xBearing + primaryPosition.x + glyphAdvance; cursorInfo.primaryPosition.y = cursorInfo.lineOffset + line.ascender - glyphMetrics.ascender; // Transform the cursor info from line's coords to text's coords. cursorInfo.primaryPosition.x += line.alignmentOffset; // Calculate the secondary cursor. if( cursorInfo.isSecondaryCursor ) { // Set the secondary cursor's height. cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight; CharacterIndex index = characterIndex; if( !isLastPositionOfLine ) { index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? nextCharacterIndex : characterIndex; } const GlyphIndex secondaryGlyphIndex = *( charactersToGlyphBuffer + index ); const Length secondaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index ); const Vector2& secondaryPosition = *( glyphPositionsBuffer + secondaryGlyphIndex ); GetGlyphsMetrics( secondaryGlyphIndex, secondaryNumberOfGlyphs, glyphMetrics, glyphInfoBuffer, metrics ); // Set the secondary cursor's position. // FCP A // ------ // 000 1 // 001 x // 010 0 // 011 0 // 100 x // 101 0 // 110 1 // 111 x // // Where F -> isFirstPosition // C -> isCurrentRightToLeft // P -> isRightToLeftParagraph // A -> Whether to add the glyph's advance. const bool addGlyphAdvance = ( ( !isFirstPositionOfLine && !isCurrentRightToLeft ) || ( isFirstPositionOfLine && !isRightToLeftParagraph ) ); cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + ( addGlyphAdvance ? glyphMetrics.advance : 0.f ); cursorInfo.secondaryPosition.y = cursorInfo.lineOffset + cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight; // Transform the cursor info from line's coords to text's coords. cursorInfo.secondaryPosition.x += line.alignmentOffset; } } } bool FindSelectionIndices( VisualModelPtr visualModel, LogicalModelPtr logicalModel, MetricsPtr metrics, float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex ) { /* Hit character Select |-------------------------------------------------------|------------------------------------------| | On a word | The word | | On a single white space between words | The word before or after the white space | | On one of the multiple contiguous white spaces | The white spaces | | On a single white space which is in the position zero | The white space and the next word | | On a new paragraph character | The word or group of white spaces before | |-------------------------------------------------------|------------------------------------------| */ CharacterIndex hitCharacter = Text::GetClosestCursorIndex( visualModel, logicalModel, metrics, visualX, visualY ); const Length totalNumberOfCharacters = logicalModel->mText.Count(); DALI_ASSERT_DEBUG( ( hitCharacter <= totalNumberOfCharacters ) && "GetClosestCursorIndex returned out of bounds index" ); if( 0u == totalNumberOfCharacters ) { // Nothing to do if the model is empty. return false; } if( hitCharacter >= totalNumberOfCharacters ) { // Closest hit character is the last character. if( hitCharacter == totalNumberOfCharacters ) { hitCharacter--; //Hit character index set to last character in logical model } else { // hitCharacter is out of bounds return false; } } const Character* const textBuffer = logicalModel->mText.Begin(); startIndex = hitCharacter; endIndex = hitCharacter; // Whether the hit character is a new paragraph character. const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + hitCharacter ) ); // Whether the hit character is a white space. Note a new paragraph character is a white space as well but here is not wanted. const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + hitCharacter ) ) && !isHitCharacterNewParagraph; FindWordData data( textBuffer, totalNumberOfCharacters, hitCharacter, isHitCharacterWhiteSpace, isHitCharacterNewParagraph ); if( isHitCharacterNewParagraph ) { // Find the first character before the hit one which is not a new paragraph character. if( hitCharacter > 0u ) { endIndex = hitCharacter - 1u; for( ; endIndex > 0; --endIndex ) { const Dali::Toolkit::Text::Character character = *( data.textBuffer + endIndex ); if( !Dali::TextAbstraction::IsNewParagraph( character ) ) { break; } } } data.hitCharacter = endIndex; data.isNewParagraph = false; data.isWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + data.hitCharacter ) ); } // Find the start of the word. FindStartOfWord( data ); startIndex = data.foundIndex; // Find the end of the word. FindEndOfWord( data ); endIndex = data.foundIndex; if( 1u == ( endIndex - startIndex ) ) { if( isHitCharacterWhiteSpace ) { // Select the word before or after the white space if( 0u == hitCharacter ) { data.isWhiteSpace = false; FindEndOfWord( data ); endIndex = data.foundIndex; } else if( hitCharacter > 0u ) { // Find the start of the word. data.hitCharacter = hitCharacter - 1u; data.isWhiteSpace = false; FindStartOfWord( data ); startIndex = data.foundIndex; --endIndex; } } } return true; } } // namespace Text } // namespace Toolkit } // namespace Dali
37.764634
174
0.646204
tizenorg
1fbde727811706eeb19098090723ce3acecdd2e1
2,827
cpp
C++
smolengine/src/ECS/Systems/AudioSystem.cpp
Floritte/Game-Engine-Samples
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
[ "Apache-2.0" ]
3
2021-05-18T00:01:06.000Z
2021-07-09T15:39:23.000Z
smolengine/src/ECS/Systems/AudioSystem.cpp
Floritte/Game-Engine-Samples
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
[ "Apache-2.0" ]
null
null
null
smolengine/src/ECS/Systems/AudioSystem.cpp
Floritte/Game-Engine-Samples
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "ECS/Systems/AudioSystem.h" #include "ECS/Components/Include/Components.h" #include "ECS/Components/Singletons/WorldAdminStateSComponent.h" #include "ECS/Components/Singletons/AudioEngineSComponent.h" #include "Audio/AudioSource.h" #include <soloud.h> #include <soloud_speech.h> #include <soloud_wav.h> #include <soloud_thread.h> #include <soloud_bus.h> #include <soloud_biquadresonantfilter.h> #include <soloud_echofilter.h> #include <soloud_dcremovalfilter.h> #include <soloud_bassboostfilter.h> #include <soloud_lofifilter.h> #include <soloud_freeverbfilter.h> #include <soloud_waveshaperfilter.h> namespace SmolEngine { float* AudioSystem::GetFFT() { return m_State->Core->calcFFT(); } float* AudioSystem::GetWave() { return m_State->Core->getWave(); } void AudioSystem::SetGlobalVolume(float value) { m_State->Core->setGlobalVolume(value); } void AudioSystem::StopAll() { m_State->Core->stopAll(); } void AudioSystem::RemoveHandle(uint32_t handle) { m_State->Handles.erase(std::remove_if(m_State->Handles.begin(), m_State->Handles.end(), [&](const Ref<AudioHandle>& another) { return *another == handle; }), m_State->Handles.end()); } void AudioSystem::OnBeginWorld() { entt::registry* registry = m_World->m_CurrentRegistry; const auto& view = registry->view<AudioSourceComponent>(); for (auto entity : view) { AudioSourceComponent& component = view.get<AudioSourceComponent>(entity); component.ClearFiltersEX(); component.CreateFiltersEX(); for (auto& info : component.Clips) { if (info.m_CreateInfo.bPlayOnAwake) { component.PlayClip(info.m_Clip, info.m_Handle); } } } } void AudioSystem::OnEndWorld() { entt::registry* registry = m_World->m_CurrentRegistry; const auto& view = registry->view<AudioSourceComponent>(); for (auto entity : view) { AudioSourceComponent& component = view.get<AudioSourceComponent>(entity); component.StopAll(); } } void AudioSystem::OnUpdate(const glm::vec3 camPos) { m_State->Core->set3dListenerPosition(camPos.x, camPos.y, camPos.z); { entt::registry* registry = m_World->m_CurrentRegistry; const auto& view = registry->view<AudioSourceComponent, TransformComponent>(); for (auto entity : view) { auto& [as, transform] = view.get<AudioSourceComponent, TransformComponent>(entity); for (auto& clip_info : as.Clips) { AudioClipCreateInfo& create_info = clip_info.m_CreateInfo; if (!create_info.bStatic && create_info.eType == ClipType::Sound_3D) { m_State->Core->set3dSourceParameters(*as.GroupHandle, transform.WorldPos.x, transform.WorldPos.y, transform.WorldPos.z, transform.Rotation.x, transform.Rotation.y, transform.Rotation.z); } } } } m_State->Core->update3dAudio(); } }
26.92381
104
0.719844
Floritte
1fbeb569a364140abc915a83425a610afe7bbed9
1,537
cc
C++
solutions/mrJudge/foodchain/main.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/mrJudge/foodchain/main.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/mrJudge/foodchain/main.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
// #include <bits/stdc++.h> #include <algorithm> #include <cmath> #include <deque> #include <iostream> #include <map> #include <queue> #include <set> #include <unordered_map> #include <vector> using namespace std; #define FOR(i, j, k, l) for (s32 i = j; i < k; i += l) #define RFOR(i, j, k, l) for (s32 i = j; i >= k; i -= l) #define REP(i, j) FOR(i, 0, j, 1) #define RREP(i, j) RFOR(i, j, 0, 1) #define ALL(x) x.begin(), x.end() #define MEAN(a, b) min(a, b) + (abs(b - a) / 2) #define FASTIO() \ cin.tie(nullptr); \ ios::sync_with_stdio(false); typedef int64_t s64; typedef uint64_t u64; typedef int32_t s32; typedef uint32_t u32; typedef float f32; typedef double f64; typedef pair<s32, s32> PII; typedef pair<s64, s64> PLLLL; typedef vector<s32> VI; typedef vector<PII> VPII; typedef priority_queue<s32> PQI; typedef priority_queue<s64> PQLL; typedef priority_queue<pair<s32, s32>> PQPI; typedef priority_queue<pair<s64, s64>> PQPLL; template <typename T, typename U> inline void amin(T &x, U y) { if (y < x) x = y; } template <typename T, typename U> inline void amax(T &x, U y) { if (x < y) x = y; } template <typename T> inline T ndigits(T x) { T y; while (x) { x /= 10; ++y; } return y; } int main() { // Don't collapse the block FASTIO(); u64 x; cin >> x; for (u64 i = 1; i < 5; ++i) { u64 a = 0; u64 y; cin >> y; for (y %= 1000000009; x; x >>= 1) { a += (x & 1) * y; a %= 1000000009; y <<= 1; y %= 1000000009; } x = a; } cout << x; }
20.223684
56
0.591412
zwliew
1fc140e0344d796bfb98ba148510cf2fc30e46df
5,960
cpp
C++
C-Plus-Plus/Circular_Queue_Cpp.cpp
MjCode01/DS-Algo-Point
79d826fa63090014dfaab281e5170c25b86c6bbf
[ "MIT" ]
1,148
2020-09-28T15:06:16.000Z
2022-03-17T16:30:08.000Z
C-Plus-Plus/Circular_Queue_Cpp.cpp
MjCode01/DS-Algo-Point
79d826fa63090014dfaab281e5170c25b86c6bbf
[ "MIT" ]
520
2020-09-28T18:34:26.000Z
2021-10-30T17:06:43.000Z
C-Plus-Plus/Circular_Queue_Cpp.cpp
MjCode01/DS-Algo-Point
79d826fa63090014dfaab281e5170c25b86c6bbf
[ "MIT" ]
491
2020-09-28T18:40:14.000Z
2022-03-20T13:41:44.000Z
//Implementation of Circular Queue in C++ #include <iostream> using namespace std; //Defined class CircularQueue class CircularQueue{ private: int * circular_queue; int front, rear, queue_size; public: // Parameterized constructor CircularQueue(int Qsize){ front = rear = -1; circular_queue = new int[Qsize]; queue_size = Qsize; } //Function to check whether the circular queue is full or not bool isFull(){ if((front==0 && rear==queue_size-1) || (front == rear+1)){ return true; }else{ return false; } } //Function to check whether the circular queue is empty or not bool isEmpty(){ if(front == -1){ return true; }else{ return false; } } //Function to insert an element in the circular queue void Enqueue(int val){ if(isFull()){ cout<<"Overflow:The Circular queue is full, can't add any more elements!"<<"\n"; }else{ if(isEmpty()){ front = rear = 0; }else{ if(rear == queue_size-1){ rear = 0; }else{ rear++; } } circular_queue[rear] = val; Display(); } } //Function to delete an element from the circular queue void Dequeue(){ if(isEmpty()){ cout<<"Underflow:The Circular queue is empty, can't remove any more elements!"<<"\n"; }else{ if(front==rear){ front = rear = -1; }else{ if(front == queue_size-1){ front = 0; }else{ front++; } } Display(); } } //Function to display the circular queue void Display(){ //Remove below comment to view working of trackers //cout<<"Front:"<<front<<" "<<"Rear:"<<rear<<"\n"; if(isEmpty()){ cout<<"Queue is empty."; }else{ if(rear>=front){ for(int i=front;i<=rear;i++){ cout<<circular_queue[i]<<"<--"; } }else{ for(int i=front;i<queue_size;i++){ cout<<circular_queue[i]<<"<--"; } for(int i=0;i<=rear;i++){ cout<<circular_queue[i]<<"<--"; } } } cout<<"\n"; } }; int main() { int Qsize; cout<<"Enter the size of your desired circular queue:"<<"\n"; cin>>Qsize; //Create an instance of Circular Queue CircularQueue myFirstCQueue(Qsize); int choice=1; do{ cout<<"Circular Queue functionalities:"<<"\n"; cout<<"1.Enqueue"<<"\n"; cout<<"2.Dequeue"<<"\n"; cout<<"3.Display"<<"\n"; cout<<"4.Is Empty"<<"\n"; cout<<"5.Is Full"<<"\n"; cout<<"6.Exit"<<"\n\n"; cout<<"Please enter your choice:"<<"\n"; cin>>choice; int temp; switch(choice){ case 1: cout<<"Enter value to be entered:"<<"\n"; cin >> temp; myFirstCQueue.Enqueue(temp); break; case 2: myFirstCQueue.Dequeue(); break; case 3: myFirstCQueue.Display(); break; case 4: if(myFirstCQueue.isEmpty()){ cout<<"Circular Queue is empty!"; }else{ cout<<"Circular Queue is not empty!"; } break; case 5: if(myFirstCQueue.isEmpty()){ cout<<"Circular Queue is full!"; }else{ cout<<"Circular Queue is not full!"; } myFirstCQueue.isFull(); break; default: break; } }while(choice!=6); return 0; } /* Circular Queue is a Data Structure similar to a linear Queue.It follows the FIFO (First in First Out) principle.In a linear queue there arises a condition where if the queue is full, even after deque operations more elements cannot be added to it.Circular queue overcomes these limitations of linear queue as it connects the rear end of the queue to the front end.Because of this it is also called a 'Ring Buffer'. Sample I/O : Enter the size of your desired circular queue:5 Circular Queue functionalities: 1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Is Full 6.Exit Please enter your choice:1 Enter value to be entered:10 10<-- Circular Queue functionalities: 1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Is Full 6.Exit Please enter your choice:1 Enter value to be entered:20 10<--20<-- Circular Queue functionalities: 1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Is Full 6.Exit Please enter your choice:1 Enter value to be entered:30 10<--20<--30<-- Circular Queue functionalities: 1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Is Full 6.Exit Please enter your choice:2 20<--30<-- Circular Queue functionalities: 1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Is Full 6.Exit Please enter your choice:1 Enter value to be entered:80 20<--30<--80<-- Circular Queue functionalities: 1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Is Full 6.Exit Please enter your choice:6 */
26.371681
106
0.478188
MjCode01
1fc6d6891fc73a425c1f17efc58be62205d79ce2
3,359
cpp
C++
grante/RBFNetwork.cpp
pantonante/grante-bazel
e3f22ec111463a7ae0686494422ab09f86b4d39a
[ "DOC" ]
null
null
null
grante/RBFNetwork.cpp
pantonante/grante-bazel
e3f22ec111463a7ae0686494422ab09f86b4d39a
[ "DOC" ]
null
null
null
grante/RBFNetwork.cpp
pantonante/grante-bazel
e3f22ec111463a7ae0686494422ab09f86b4d39a
[ "DOC" ]
null
null
null
#include <numeric> #include <iostream> #include <cmath> #include <cassert> #include "RBFNetwork.h" namespace Grante { RBFNetwork::RBFNetwork(unsigned int N, unsigned int d) : N(N), d(d), has_proto(false), has_beta(false) { } RBFNetwork::RBFNetwork(const std::vector<std::vector<double> >& prototypes) : prototypes(prototypes), has_proto(true), has_beta(false) { assert(prototypes.size() > 0); d = prototypes[0].size(); N = prototypes.size(); for (unsigned int pi = 0; pi < prototypes.size(); ++pi) { assert(prototypes[pi].size() == d); } } void RBFNetwork::FixBeta(double log_beta) { this->beta = log_beta; has_beta = true; } size_t RBFNetwork::ParameterDimension() const { return ((has_proto ? (N) : (N + N*d)) + (has_beta ? 0 : 1)); } bool RBFNetwork::HasFixedPrototypes() const { return (has_proto); } bool RBFNetwork::HasFixedBeta() const { return (has_beta); } double RBFNetwork::Evaluate(const std::vector<double>& x, const std::vector<double>& param, size_t param_base) const { double res = 0.0; for (unsigned int n = 0; n < N; ++n) { // += alpha_n * rbf(x) res += param[param_base+(has_beta ? 0 : 1)+n] * EvaluateRBFFunction(x, param, n, param_base); } return (res); } double RBFNetwork::EvaluateGradient(const std::vector<double>& x, const std::vector<double>& param, std::vector<double>& grad, size_t param_base, double scale) const { assert(param.size() == grad.size()); assert(param_base < param.size()); double res = 0.0; double exp_beta = has_beta ? std::exp(beta) : std::exp(param[param_base+0]); unsigned int b_base = has_beta ? 0 : 1; for (unsigned int n = 0; n < N; ++n) { double l2_resp = EvaluateL2(x, param, n, param_base); double cur_rbf_resp = std::exp(-exp_beta*l2_resp); double alpha_n = param[param_base+b_base+n]; // 0. RBF response res += alpha_n * cur_rbf_resp; // 1. \nabla_{alpha_n} f(x) = rbf_resp[n] grad[param_base+b_base+n] += scale * cur_rbf_resp; // 2. \nabla_beta if (has_beta == false) { grad[param_base+0] += scale * -alpha_n * cur_rbf_resp * l2_resp * exp_beta; } if (has_proto == false) { // 3. \nabla_{c_n} size_t c_n_start = param_base + b_base + N + n*d; for (size_t dp = 0; dp < d; ++dp) { grad[c_n_start+dp] += scale * -2.0 * exp_beta * alpha_n * cur_rbf_resp * (param[c_n_start+dp] - x[dp]); } } } return (res); } double RBFNetwork::EvaluateRBFFunction(const std::vector<double>& x, const std::vector<double>& param, unsigned int n, size_t param_base) const { double exp_beta = has_beta ? std::exp(beta) : std::exp(param[param_base+0]); double l2 = EvaluateL2(x, param, n, param_base); double res = std::exp(-exp_beta*l2); #if 0 std::cout << "res " << res << std::endl; std::cout << " exp_beta * L2 = " << exp_beta << " * " << l2 << std::endl; #endif return (res); } double RBFNetwork::EvaluateL2(const std::vector<double>& x, const std::vector<double>& param, unsigned int n, size_t param_base) const { double xcn_diff = 0.0; if (has_proto) { for (unsigned int dp = 0; dp < d; ++dp) xcn_diff += (x[dp]-prototypes[n][dp]) * (x[dp]-prototypes[n][dp]); } else { size_t c_n_start = (has_beta ? 0 : 1) + N + n*d; for (size_t dp = 0; dp < d; ++dp) { xcn_diff += (x[dp]-param[param_base+c_n_start+dp]) * (x[dp]-param[param_base+c_n_start+dp]); } } return (xcn_diff); } }
26.872
75
0.645132
pantonante
1fc70bd75f208da0095ccc98daaaf6136f1263ab
7,920
cpp
C++
src/global/LogHandler.cpp
misery/AusweisApp2
dab96eb2bdd8a132023964d4aeecc7069d12a244
[ "Apache-2.0" ]
null
null
null
src/global/LogHandler.cpp
misery/AusweisApp2
dab96eb2bdd8a132023964d4aeecc7069d12a244
[ "Apache-2.0" ]
null
null
null
src/global/LogHandler.cpp
misery/AusweisApp2
dab96eb2bdd8a132023964d4aeecc7069d12a244
[ "Apache-2.0" ]
null
null
null
/* * \copyright Copyright (c) 2014-2018 Governikus GmbH & Co. KG, Germany */ #include "LogHandler.h" #include "BreakPropertyBindingDiagnosticLogFilter.h" #include "SingletonHelper.h" #include <QDir> using namespace governikus; defineSingleton(LogHandler) #if !defined(Q_OS_ANDROID) && !defined(QT_USE_JOURNALD) #define ENABLE_MESSAGE_PATTERN #endif LogHandler::LogHandler() : QObject() , mEnvPattern(!qEnvironmentVariableIsEmpty("QT_MESSAGE_PATTERN")) , mFunctionFilenameSize(74) , mBacklogPosition(0) , mMessagePattern(QStringLiteral("%{category} %{time yyyy.MM.dd hh:mm:ss.zzz} %{if-debug} %{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif} %{function}(%{file}:%{line}) %{message}")) , mDefaultMessagePattern(QStringLiteral("%{if-category}%{category}: %{endif}%{message}")) // as defined in qlogging.cpp , mLogFileTemplate(QDir::tempPath() + QStringLiteral("/AusweisApp2.XXXXXX.log")) // if you change value you need to adjust getOtherLogfiles() , mLogFile(mLogFileTemplate) , mHandler(nullptr) , mFilePrefix("/src/") , mMutex() { #ifndef QT_NO_DEBUG new BreakPropertyBindingDiagnosticLogFilter(this); #endif } LogHandler::~LogHandler() { reset(); } LogHandler& LogHandler::getInstance() { return *Instance; } void LogHandler::reset() { const QMutexLocker mutexLocker(&mMutex); if (isInitialized()) { qInstallMessageHandler(nullptr); mHandler = nullptr; } } void LogHandler::init() { const QMutexLocker mutexLocker(&mMutex); if (!isInitialized()) { if (useLogfile()) { mLogFile.open(); } mHandler = qInstallMessageHandler(&LogHandler::messageHandler); } } bool LogHandler::isInitialized() const { return mHandler; } void LogHandler::setAutoRemove(bool pRemove) { mLogFile.setAutoRemove(pRemove); } void LogHandler::logToFile(const QString& pOutput) { if (mLogFile.isOpen() && mLogFile.isWritable()) { mLogFile.write(pOutput.toUtf8()); mLogFile.flush(); } } QByteArray LogHandler::getBacklog() { const QMutexLocker mutexLocker(&mMutex); if (mLogFile.isOpen() && mLogFile.isReadable()) { const auto currentPos = mLogFile.pos(); mLogFile.seek(mBacklogPosition); const auto backlog = mLogFile.readAll(); mLogFile.seek(currentPos); return backlog; } if (useLogfile()) { return tr("An error occurred in log handling: %1").arg(mLogFile.errorString()).toUtf8(); } return QByteArray(); } QDateTime LogHandler::getFileDate(const QFileInfo& pInfo) { const auto& dateTime = pInfo.birthTime(); if (dateTime.isValid()) { return dateTime; } return pInfo.metadataChangeTime(); } QDateTime LogHandler::getCurrentLogfileDate() const { return getFileDate(mLogFile); } void LogHandler::resetBacklog() { const QMutexLocker mutexLocker(&mMutex); mBacklogPosition = mLogFile.pos(); } void LogHandler::copyMessageLogContext(const QMessageLogContext& pSource, QMessageLogContext& pDestination, const QByteArray& pFilename, const QByteArray& pFunction, const QByteArray& pCategory) { pDestination.file = pFilename.isNull() ? pSource.file : pFilename.constData(); pDestination.function = pFunction.isNull() ? pSource.function : pFunction.constData(); pDestination.category = pCategory.isNull() ? pSource.category : pCategory.constData(); pDestination.line = pSource.line; pDestination.version = pSource.version; } QByteArray LogHandler::formatFilename(const char* pFilename) const { QByteArray filename(pFilename); // Normalize the file name filename.replace(QByteArrayLiteral("\\"), "/"); // Remove useless path return filename.mid(filename.lastIndexOf(mFilePrefix) + mFilePrefix.size()); } QByteArray LogHandler::formatFunction(const char* pFunction, const QByteArray& pFilename, int pLine) const { QByteArray function(pFunction); // Remove namespace governikus:: function.replace(QByteArrayLiteral("governikus::"), ""); // Remove the parameter list const auto start = function.indexOf('('); const auto end = function.indexOf(')'); function = function.left(start) + function.mid(end + 1); // Remove the return type (if any) if (function.indexOf(' ') != -1) { function = function.mid(function.lastIndexOf(' ') + 1); } // Trim function name const int size = mFunctionFilenameSize - 3 - pFilename.size() - QString::number(pLine).size(); if (size >= function.size()) { return function; } if (size < 3) { return QByteArray(); } if (size < 10) { return QByteArrayLiteral("..."); } return QByteArrayLiteral("...") + function.right(size - 3); } QByteArray LogHandler::formatCategory(const QByteArray& pCategory) const { const int MAX_CATEGORY_LENGTH = 10; if (pCategory.length() > MAX_CATEGORY_LENGTH) { return pCategory.left(MAX_CATEGORY_LENGTH - 3) + QByteArrayLiteral("..."); } return pCategory + QByteArray(MAX_CATEGORY_LENGTH - pCategory.size(), ' '); } QString LogHandler::getPaddedLogMsg(const QMessageLogContext& pContext, const QString& pMsg) { const int paddingSize = (pContext.function == nullptr && pContext.file == nullptr && pContext.line == 0) ? mFunctionFilenameSize - 18 : // padding for nullptr == "unknown(unknown:0)" mFunctionFilenameSize - 3 - static_cast<int>(qstrlen(pContext.function)) - static_cast<int>(qstrlen(pContext.file)) - QString::number(pContext.line).size(); QString padding; padding.reserve(paddingSize + pMsg.size() + 3); padding.fill(QLatin1Char(' '), paddingSize); padding += QStringLiteral(": "); padding += pMsg; return padding; } void LogHandler::handleMessage(QtMsgType pType, const QMessageLogContext& pContext, const QString& pMsg) { const QMutexLocker mutexLocker(&mMutex); const QByteArray& filename = formatFilename(pContext.file); const QByteArray& function = formatFunction(pContext.function, filename, pContext.line); const QByteArray& category = formatCategory(pContext.category); QMessageLogContext ctx; copyMessageLogContext(pContext, ctx, filename, function, category); const QString& message = mEnvPattern ? pMsg : getPaddedLogMsg(ctx, pMsg); qSetMessagePattern(mMessagePattern); #ifdef Q_OS_WIN const QLatin1String lineBreak("\r\n"); #else const QLatin1Char lineBreak('\n'); #endif QString logMsg = qFormatLogMessage(pType, ctx, message) + lineBreak; logToFile(logMsg); #ifdef ENABLE_MESSAGE_PATTERN mHandler(pType, ctx, message); #else qSetMessagePattern(mDefaultMessagePattern); mHandler(pType, ctx, pMsg); #endif Q_EMIT fireRawLog(pMsg, QString::fromLatin1(pContext.category)); Q_EMIT fireLog(logMsg); } bool LogHandler::copy(const QString& pDest) { if (pDest.trimmed().isEmpty()) { return false; } const QMutexLocker mutexLocker(&mMutex); return QFile::copy(mLogFile.fileName(), pDest); } QFileInfoList LogHandler::getOtherLogfiles() const { QDir tmpPath = QDir::temp(); tmpPath.setSorting(QDir::Time); tmpPath.setFilter(QDir::Files); tmpPath.setNameFilters(QStringList({QStringLiteral("AusweisApp2.*.log")})); QFileInfoList list = tmpPath.entryInfoList(); list.removeAll(mLogFile); return list; } bool LogHandler::removeOtherLogfiles() { const auto otherLogFiles = getOtherLogfiles(); for (const auto& entry : otherLogFiles) { qDebug() << "Remove old log file:" << entry.absoluteFilePath() << "|" << QFile::remove(entry.absoluteFilePath()); } return !otherLogFiles.isEmpty(); } void LogHandler::setLogfile(bool pEnable) { const QMutexLocker mutexLocker(&mMutex); if (pEnable) { if (!mLogFile.isOpen()) { mLogFile.setFileTemplate(mLogFileTemplate); mLogFile.open(); } } else { if (mLogFile.isOpen()) { mLogFile.close(); mLogFile.remove(); mBacklogPosition = 0; } mLogFile.setFileTemplate(QString()); } } bool LogHandler::useLogfile() const { return !mLogFile.fileTemplate().isNull(); } void LogHandler::messageHandler(QtMsgType pType, const QMessageLogContext& pContext, const QString& pMsg) { getInstance().handleMessage(pType, pContext, pMsg); }
22.890173
226
0.729293
misery
1fc7bc5ed907c5771ecf46d3bfaf2c743dfe094b
9,994
cpp
C++
src/map/StateMap.cpp
Streetwalrus/WalrusRPG
53d88ef36ca1b2c169b5755dd95ac2c5626b91f5
[ "MIT" ]
12
2015-06-30T19:38:06.000Z
2017-11-27T20:26:32.000Z
src/map/StateMap.cpp
Pokespire/pokespire
53d88ef36ca1b2c169b5755dd95ac2c5626b91f5
[ "MIT" ]
18
2015-06-26T01:44:48.000Z
2016-07-01T16:26:17.000Z
src/map/StateMap.cpp
Pokespire/pokespire
53d88ef36ca1b2c169b5755dd95ac2c5626b91f5
[ "MIT" ]
1
2016-12-12T05:15:46.000Z
2016-12-12T05:15:46.000Z
#include "StateMap.h" #include "DoorEntity.h" #include "Graphics.h" #include "Logger.h" #include "TalkEntity.h" #include "collision/Collision.h" #include "input/Input.h" #include "piaf/Archive.h" #include "render/Text.h" #include "render/TileRenderer.h" #include <cmath> using WalrusRPG::States::StateMap; using namespace WalrusRPG; using namespace WalrusRPG::Graphics; using WalrusRPG::Utils::Rect; using WalrusRPG::PIAF::Archive; using WalrusRPG::PIAF::File; using WalrusRPG::Graphics::Texture; using namespace WalrusRPG::Input; using WalrusRPG::Input::Key; using WalrusRPG::Graphics::Font; using WalrusRPG::Textbox; using WalrusRPG::Entity; using WalrusRPG::TileRenderer; using WalrusRPG::TalkEntity; using WalrusRPG::DoorEntity; using WalrusRPG::MAP_OBJECT_GRID_TILE_WIDTH; namespace { void print_debug_camera_data(const Camera &camera, const Font &fnt) { fnt.draw_format(240, 1, Black, "CAM : X : %d Y: %d", camera.get_x(), camera.get_y()); fnt.draw_format(240, 0, "CAM : X : %d Y: %d", camera.get_x(), camera.get_y()); } void print_debug_map_data(const Map &map, const Font &fnt) { fnt.draw_format(240, 9, Black, "MAP : W: %d, H:%d", map.get_width(), map.get_height()); fnt.draw_format(240, 8, "MAP : W: %d, H:%d", map.get_width(), map.get_height()); } } // TODO : We definitely need a Resource Manager StateMap::StateMap(int x, int y, Map &map) : started(false), camera(x, y), map(map), data("data/wip_data.wrf"), tex_haeccity((*data).get("t_haeccity")), txt(tex_haeccity, (*data).get("f_haeccity")), box(txt), p(*this, 32, 40, 10, 4, new TileRenderer(map.tmap.get_texture(), TILE_DIMENSION, TILE_DIMENSION), 128) { map.add_entity(&p); TileRenderer *tr = new TileRenderer(map.tmap.get_texture(), TILE_DIMENSION, TILE_DIMENSION); map.add_entity(new TalkEntity(*this, 128, 64, TILE_DIMENSION, TILE_DIMENSION, tr, 150, "Hello, I'm a skeleton.")); map.add_entity(new TalkEntity(*this, 128, 96, TILE_DIMENSION, TILE_DIMENSION, tr, 134, "Hello, I'm another skeleton.")); map.add_entity(new TalkEntity( *this, 138, 104, TILE_DIMENSION, TILE_DIMENSION, tr, 134, "Doot doot. Thanks \xFF\x02\xFF\x00\x00Mr. Skeltal\xFF\x02\xFF\xFF\xFF!")); map.add_entity(new TalkEntity( *this, 138, 104, TILE_DIMENSION, TILE_DIMENSION, tr, 134, "Doot doot. Thanks \xFF\x02\xFF\x00\x00Mr. Skeltal\xFF\x02\xFF\xFF\xFF!")); map.add_entity( new DoorEntity(*this, 48, 240, TILE_DIMENSION, TILE_DIMENSION, tr, 4, 7)); map.add_entity( new DoorEntity(*this, 352, 240, TILE_DIMENSION, TILE_DIMENSION, tr, 4, 7)); map.reset_entity_grid(); /* map.add_entity( new Entity(*this, 196, 112, TILE_DIMENSION, TILE_DIMENSION, tr, 134)); map.add_entity( new Entity(*this, 196, 104, TILE_DIMENSION, TILE_DIMENSION, tr, 134)); */ } StateMap::~StateMap() { } void StateMap::update() { camera.set_center_x(p.x + p.w / 2); camera.set_center_y(p.y + p.h / 2); unsigned t = (key_down(K_B) ? 16 : 1); map.update(); if (started) { for (unsigned i = 0; i < t; i++) box.update(); if (key_pressed(K_A) && box.state == Done) { started = false; p.controllable = true; } } else { if (key_pressed(K_A)) { // Check direction. Rect check_hitbox; switch (p.direction) { // up case 0: check_hitbox = {(int) p.x, (int) p.y - 4, p.w, 4}; break; // down case 1: check_hitbox = {(int) p.x, (int) p.y + (int) p.h, p.w, 4}; break; // left case 2: check_hitbox = {(int) p.x - (int) p.w - 4, (int) p.y, 4, p.h}; break; // down case 3: check_hitbox = {(int) p.x + (int) p.w, (int) p.y, 4, p.h}; break; } // Check for (auto ptr = map.entities.begin(); ptr < map.entities.end(); ptr++) { Entity *e = *ptr; if (e == &p) continue; if (WalrusRPG::AABBCheck(check_hitbox, {(int) e->x, (int) e->y, e->w, e->h})) { e->interact_with(p, InteractionType::CHECK); Logger::log("Interacted with %p", e); map.remove_entity_from_grid(e); map.add_entity_to_grid(e); } } // if (!started && box.state != Done) // started = true; // else if (box.state == Done) // { // } } } camera.update(); } void StateMap::render() { map.render(camera); print_debug_camera_data(camera, txt); #if !IMGUI print_debug_map_data(map, txt); #endif if (started) box.render(); } #if IMGUI void StateMap::debug_layer(uint16_t *layer, ImU32 color, ImDrawList *list, ImVec2 offset) { for (signed i = 0; i < map.get_height(); i++) { for (signed j = 0; j < map.get_width(); j++) { float x = offset.x + 4 * j; float y = offset.y + 4 * i; uint16_t tile = layer[i * map.get_width() + j]; { if (tile != 0) { list->AddRectFilled({x, y}, {x + 4, y + 4}, color); } } } } } void StateMap::debug() { if (!ImGui::Begin("Map state")) return; ImGui::BeginGroup(); ImGui::Text("Camera"); ImGui::Indent(); ImGui::Value("X", camera.get_x()); ImGui::SameLine(); ImGui::Value("Y", camera.get_y()); ImGui::EndGroup(); ImGui::Separator(); ImGui::Text("Map"); ImGui::Indent(); ImGui::Value("W", map.get_width()); ImGui::SameLine(); ImGui::Value("H", map.get_height()); ImGui::Value("Nb entities", (int) map.entities.size()); ImGui::Unindent(); ImGui::Text("Layers"); if (ImGui::Checkbox("Ground", &show_layer_ground)) ; ImGui::SameLine(); if (ImGui::Checkbox("Middle", &show_layer_middle)) ; ImGui::SameLine(); if (ImGui::Checkbox("Over", &show_layer_over)) ; if (ImGui::Checkbox("Entities", &show_entities)) ; if (show_entities) { ImGui::SameLine(); ImGui::Checkbox("Grid", &show_entity_grid); } if (ImGui::BeginChild("map_frame", {0, 0}, true)) { if (ImGui::IsWindowHovered() && !ImGui::IsAnyItemActive() && ImGui::IsMouseDragging(1, 0.0f)) scrolling = {scrolling.x - ImGui::GetIO().MouseDelta.x, scrolling.y - ImGui::GetIO().MouseDelta.y}; ImVec2 s = ImGui::GetCursorScreenPos(); s = {s.x - scrolling.x, s.y - scrolling.y}; ImDrawList *list = ImGui::GetWindowDrawList(); if (show_layer_ground && map.layer0 != nullptr) StateMap::debug_layer(map.layer0, 0x88888888, list, s); if (show_layer_middle && map.layer1 != nullptr) StateMap::debug_layer(map.layer1, 0xFF0000FF, list, s); if (show_entities) { for (auto ptr = map.entities.begin(); ptr != map.entities.end(); ptr++) { Entity *e = *ptr; float x = s.x + e->x / TILE_DIMENSION * 4; float x2 = s.x + (e->x + e->w) / TILE_DIMENSION * 4; float y = s.y + e->y / TILE_DIMENSION * 4; float y2 = s.y + (e->y + e->h) / TILE_DIMENSION * 4; list->AddRectFilled({x, y}, {x2, y2}, 0xFFFFFFFF); } // Entity Grid if (show_entity_grid) { for (int i = 0, max_i = map.get_height() / MAP_OBJECT_GRID_TILE_WIDTH + 1; i < max_i; ++i) { for (int j = 0, max_j = map.get_width() / MAP_OBJECT_GRID_TILE_WIDTH + 1; j < max_j; ++j) { list->AddRect( {std::floor(j * MAP_OBJECT_GRID_TILE_WIDTH * 4 + s.x), std::floor(i * MAP_OBJECT_GRID_TILE_WIDTH * 4 + s.y)}, {std::floor((j + 1) * MAP_OBJECT_GRID_TILE_WIDTH * 4 + s.x), std::floor((i + 1) * MAP_OBJECT_GRID_TILE_WIDTH * 4 + s.y)}, 0x80FFFFFF); } } } } if (show_layer_over && map.layer2 != nullptr) StateMap::debug_layer(map.layer2, 0x800000FF, list, s); float x = camera.get_x() / (float) TILE_DIMENSION; float x2 = (camera.get_x() + 320) / (float) TILE_DIMENSION; float y = camera.get_y() / (float) TILE_DIMENSION; float y2 = (camera.get_y() + 240) / (float) TILE_DIMENSION; list->AddRect({std::floor(x * 4 + s.x), std::floor(y * 4 + s.y)}, {std::floor(x2 * 4 + s.x), std::floor(y2 * 4 + s.y)}, 0xFFFFFF00); } ImGui::EndChild(); if (show_entity_grid) { ImGui::Text("Grid entity population"); for (int i = 0, max_i = map.get_height() / MAP_OBJECT_GRID_TILE_WIDTH + 1; i < max_i; ++i) { for (int j = 0, max_j = map.get_width() / MAP_OBJECT_GRID_TILE_WIDTH + 1; j < max_j; ++j) { ImGui::Text("%3d", map.entity_container[i][j].size()); ImGui::SameLine(); } ImGui::Text(""); } } ImGui::End(); } #endif
32.983498
90
0.510206
Streetwalrus
1fc89fece79685cbbc1f5e32122218216bc32778
7,498
cpp
C++
Opal Prospect/OpenGL/ArrayTexture.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
2
2018-06-06T02:01:08.000Z
2020-07-25T18:10:32.000Z
Opal Prospect/OpenGL/ArrayTexture.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
10
2018-07-27T01:56:45.000Z
2019-02-23T01:49:36.000Z
Opal Prospect/OpenGL/ArrayTexture.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
null
null
null
//class header #include "ArrayTexture.hpp" //std lib includes #include <iostream> #include <sstream> //other includes #include "glew.h" #include "OGLHelpers.hpp" /* MIT License Copyright (c) 2018 Scott Bengs 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. */ ArrayTexture::ArrayTexture() { id = 0; texture_name = ""; } void ArrayTexture::bind() const { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_ARRAY, getID()); } void ArrayTexture::unbind() const { glBindTexture(GL_TEXTURE_2D_ARRAY, 0); } void ArrayTexture::loadImages(std::vector<std::string> file_paths) { int good_width = 0; int good_height = 0; std::stringstream bad_stream; bad_stream << FilePath::getCWD() << "Textures" << FilePath::getOSSeperator() << "bad.png"; std::string fallback = bad_stream.str(); for (size_t i = 0; i < file_paths.size(); i++) { Image temp; temp.setFilePath(file_paths[i]); //temp.loadImage(); temp.loadImageFallback(temp.getPath(), fallback); //get the path we created and not the given file path images.push_back(std::move(temp)); } //std::cout << "second loop\n"; for (size_t i = 0; i < images.size(); i++) { if (images[i].getWidth() > 0) { good_width = images[i].getWidth(); good_height = images[i].getHeight(); break; } } //std::cout << "good_width: " << good_width << "\n"; //std::cout << "good_height: " << good_height << "\n"; //do sanity check that all array textures are the same size. Any that deviate from the first non 0 one must match that Image junk; junk.setSolidColor(255, 0, 255, good_width, good_height); //std::cout << "third loop\n"; for (size_t i = 0; i < images.size(); i++) { if (images[i].getWidth() != good_width || images[i].getHeight() != good_height) { //std::cout << "third loop if start\n"; junk.setFilePath(images[i].getFilename()); images[i] = junk; //std::cout << "third loop if done\n"; } //std::cout << "third loop running\n"; } //std::cout << "third loop end\n"; } void ArrayTexture::createTexture() { const int color_components = 4; const int id_count = 1; const int level = 0; //not using mipmaps so it's always 0 const int border = 0; //no border being used so set to 0 void* data = nullptr; std::vector<unsigned char> complete_texture; if (images.size() == 0) { std::cout << "No images have been loaded. Exiting\n"; return; //nothing to setup so just exit } if (id > 0) { destroy(); //make sure we clean up our current texture before we generate another } glGenTextures(id_count, &id); //create an id and bind it bind(); OGLHelpers::getOpenGLError("pre teximage3d", true); //void glTexImage3D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid * data); glTexImage3D(GL_TEXTURE_2D_ARRAY, level, GL_RGBA8, images[0].getWidth(), images[0].getHeight(), static_cast<int>(getImageCount()), border, GL_RGBA, GL_UNSIGNED_BYTE, data); //fill in the data on the graphics card OGLHelpers::getOpenGLError("post teximage3d", true); //GL_NEAREST, GL_LINEAR glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_MIRRORED_REPEAT, GL_REPEAT, or GL_MIRROR_CLAMP_TO_EDGE //glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); //glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT); OGLHelpers::getOpenGLError("post texparam", true); complete_texture.reserve(images[0].getSize() * getImageCount()); //holds the complete texture that is uploaded in one go. Only reserve them since we insert later for (size_t i = 0; i < images.size(); i++) { const std::vector<unsigned char>& ref = images[i].getImageData(); complete_texture.insert(complete_texture.end(), ref.begin(), ref.end()); texture_numbers[images[i].getFilename()] = i; } uploadCompleteTexture(static_cast<int>(getImageCount()), complete_texture.data()); OGLHelpers::getOpenGLError("post array texture uploads", true); unbind(); } void ArrayTexture::destroy() { const int count = 1; unbind(); if (id > 0) { glDeleteTextures(count, &id); } } unsigned int ArrayTexture::getID() const { return id; } int ArrayTexture::getImageWidth() const { if (images.size() == 0) //don't cause exception if there are no loaded images { return 0; } else { return images[0].getWidth(); } } int ArrayTexture::getImageHeight() const { if (images.size() == 0) { return 0; } else { return images[0].getWidth(); } } size_t ArrayTexture::getImageCount() const { return images.size(); } std::string ArrayTexture::getTextureName() const { return texture_name; } unsigned int ArrayTexture::getTextureNumberReference(std::string filename) const { auto it = texture_numbers.find(filename); if (it == texture_numbers.end()) { //std::cout << "name: " << filename << " was not found\n"; return 0; } else { return it->second + 1; } } void ArrayTexture::setTextureName(std::string name) { texture_name = name; } /* Sends the entire texture up in one go instead of individual layers */ void ArrayTexture::uploadCompleteTexture(int count, void* data) const { const int level = 0; const int x_offset = 0; const int y_offset = 0; const int z_offset = 0; //start at the beginning //z offset specifies what level you want to start on. 0 is base. You can upload it all from 0 or just do them idividually //void glTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid * pixels); glTexSubImage3D(GL_TEXTURE_2D_ARRAY, level, x_offset, y_offset, z_offset, images[0].getWidth(), images[0].getHeight(), count, GL_RGBA, GL_UNSIGNED_BYTE, data); }
31.241667
216
0.674713
swbengs