hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
805a8feb74fbb10cdec4830e3f48c8f810f690ba
11,466
cpp
C++
src/lib/operators/insert.cpp
cmfcmf/hyrise
d3465dfc83039876c1800bf245e73874947da114
[ "MIT" ]
2
2019-01-22T19:44:32.000Z
2019-01-22T19:52:33.000Z
src/lib/operators/insert.cpp
tom-lichtenstein/hyrise
a11b5bdf6be726fd88b16c6e6284a238f5ec7873
[ "MIT" ]
33
2019-02-02T09:52:50.000Z
2019-03-07T13:14:40.000Z
src/lib/operators/insert.cpp
tom-lichtenstein/hyrise
a11b5bdf6be726fd88b16c6e6284a238f5ec7873
[ "MIT" ]
null
null
null
#include "insert.hpp" #include <algorithm> #include <memory> #include <string> #include <vector> #include "concurrency/transaction_context.hpp" #include "resolve_type.hpp" #include "storage/base_encoded_segment.hpp" #include "storage/storage_manager.hpp" #include "storage/value_segment.hpp" #include "type_cast.hpp" #include "utils/assert.hpp" namespace opossum { // We need these classes to perform the dynamic cast into a templated ValueSegment class AbstractTypedSegmentProcessor : public Noncopyable { public: AbstractTypedSegmentProcessor() = default; AbstractTypedSegmentProcessor(const AbstractTypedSegmentProcessor&) = delete; AbstractTypedSegmentProcessor& operator=(const AbstractTypedSegmentProcessor&) = delete; AbstractTypedSegmentProcessor(AbstractTypedSegmentProcessor&&) = default; AbstractTypedSegmentProcessor& operator=(AbstractTypedSegmentProcessor&&) = default; virtual ~AbstractTypedSegmentProcessor() = default; virtual void resize_vector(std::shared_ptr<BaseSegment> segment, size_t new_size) = 0; virtual void copy_data(std::shared_ptr<const BaseSegment> source, ChunkOffset source_start_index, std::shared_ptr<BaseSegment> target, ChunkOffset target_start_index, ChunkOffset length) = 0; }; template <typename T> class TypedSegmentProcessor : public AbstractTypedSegmentProcessor { public: void resize_vector(std::shared_ptr<BaseSegment> segment, size_t new_size) override { auto value_segment = std::dynamic_pointer_cast<ValueSegment<T>>(segment); DebugAssert(value_segment, "Cannot insert into non-ValueColumns"); auto& values = value_segment->values(); values.resize(new_size); if (value_segment->is_nullable()) { value_segment->null_values().resize(new_size); } } // this copies void copy_data(std::shared_ptr<const BaseSegment> source, ChunkOffset source_start_index, std::shared_ptr<BaseSegment> target, ChunkOffset target_start_index, ChunkOffset length) override { auto casted_target = std::dynamic_pointer_cast<ValueSegment<T>>(target); DebugAssert(casted_target, "Cannot insert into non-ValueColumns"); auto& values = casted_target->values(); auto target_is_nullable = casted_target->is_nullable(); if (auto casted_source = std::dynamic_pointer_cast<const ValueSegment<T>>(source)) { std::copy_n(casted_source->values().begin() + source_start_index, length, values.begin() + target_start_index); if (casted_source->is_nullable()) { const auto nulls_begin_iter = casted_source->null_values().begin() + source_start_index; const auto nulls_end_iter = nulls_begin_iter + length; Assert( target_is_nullable || std::none_of(nulls_begin_iter, nulls_end_iter, [](const auto& null) { return null; }), "Trying to insert NULL into non-NULL segment"); std::copy(nulls_begin_iter, nulls_end_iter, casted_target->null_values().begin() + target_start_index); } } else if (auto casted_dummy_source = std::dynamic_pointer_cast<const ValueSegment<int32_t>>(source)) { // We use the segment type of the Dummy table used to insert a single null value. // A few asserts are needed to guarantee correct behaviour. // You may also end up here if the data types of the input and the target column mismatch. Usually, this gets // caught way earlier, but if you build your own tests, this might happen. Assert(length == 1, "Cannot insert multiple unknown null values at once."); Assert(casted_dummy_source->size() == 1, "Source segment is of wrong type."); Assert(casted_dummy_source->null_values().front() == true, "Only value in dummy table must be NULL!"); Assert(target_is_nullable, "Cannot insert NULL into NOT NULL target."); // Ignore source value and only set null to true casted_target->null_values()[target_start_index] = true; } else { // } else if(auto casted_source = std::dynamic_pointer_cast<ReferenceSegment>(source)){ // since we have no guarantee that a ReferenceSegment references only a single other segment, // this would require us to find out the referenced segment's type for each single row. // instead, we just use the slow path below. for (auto i = 0u; i < length; i++) { auto ref_value = (*source)[source_start_index + i]; if (variant_is_null(ref_value)) { Assert(target_is_nullable, "Cannot insert NULL into NOT NULL target"); values[target_start_index + i] = T{}; casted_target->null_values()[target_start_index + i] = true; } else { values[target_start_index + i] = type_cast_variant<T>(ref_value); } } } } }; Insert::Insert(const std::string& target_table_name, const std::shared_ptr<const AbstractOperator>& values_to_insert) : AbstractReadWriteOperator(OperatorType::Insert, values_to_insert), _target_table_name(target_table_name) {} const std::string Insert::name() const { return "Insert"; } std::shared_ptr<const Table> Insert::_on_execute(std::shared_ptr<TransactionContext> context) { context->register_read_write_operator(std::static_pointer_cast<AbstractReadWriteOperator>(shared_from_this())); _target_table = StorageManager::get().get_table(_target_table_name); // These TypedSegmentProcessors kind of retrieve the template parameter of the segments. auto typed_segment_processors = std::vector<std::unique_ptr<AbstractTypedSegmentProcessor>>(); for (const auto& column_type : _target_table->column_data_types()) { typed_segment_processors.emplace_back( make_unique_by_data_type<AbstractTypedSegmentProcessor, TypedSegmentProcessor>(column_type)); } auto total_rows_to_insert = static_cast<uint32_t>(input_table_left()->row_count()); // First, allocate space for all the rows to insert. Do so while locking the table to prevent multiple threads // modifying the table's size simultaneously. auto start_index = 0u; auto start_chunk_id = ChunkID{0}; auto end_chunk_id = 0u; { auto scoped_lock = _target_table->acquire_append_mutex(); if (_target_table->chunk_count() == 0) { _target_table->append_mutable_chunk(); } start_chunk_id = _target_table->chunk_count() - 1; end_chunk_id = start_chunk_id + 1; auto last_chunk = _target_table->get_chunk(start_chunk_id); start_index = last_chunk->size(); // If last chunk is compressed, add a new uncompressed chunk if (!last_chunk->is_mutable()) { _target_table->append_mutable_chunk(); end_chunk_id++; } auto remaining_rows = total_rows_to_insert; while (remaining_rows > 0) { auto current_chunk = _target_table->get_chunk(static_cast<ChunkID>(_target_table->chunk_count() - 1)); auto rows_to_insert_this_loop = std::min(_target_table->max_chunk_size() - current_chunk->size(), remaining_rows); // Resize MVCC vectors. current_chunk->get_scoped_mvcc_data_lock()->grow_by(rows_to_insert_this_loop, MvccData::MAX_COMMIT_ID); // Resize current chunk to full size. auto old_size = current_chunk->size(); for (ColumnID column_id{0}; column_id < current_chunk->column_count(); ++column_id) { typed_segment_processors[column_id]->resize_vector(current_chunk->get_segment(column_id), old_size + rows_to_insert_this_loop); } remaining_rows -= rows_to_insert_this_loop; // Create new chunk if necessary. if (remaining_rows > 0) { _target_table->append_mutable_chunk(); end_chunk_id++; } } } // TODO(all): make compress chunk thread-safe; if it gets called here by another thread, things will likely break. // Then, actually insert the data. auto input_offset = 0u; auto source_chunk_id = ChunkID{0}; auto source_chunk_start_index = 0u; for (auto target_chunk_id = start_chunk_id; target_chunk_id < end_chunk_id; target_chunk_id++) { auto target_chunk = _target_table->get_chunk(target_chunk_id); const auto current_num_rows_to_insert = std::min(target_chunk->size() - start_index, total_rows_to_insert - input_offset); auto target_start_index = start_index; auto still_to_insert = current_num_rows_to_insert; // while target chunk is not full while (target_start_index != target_chunk->size()) { const auto source_chunk = input_table_left()->get_chunk(source_chunk_id); auto num_to_insert = std::min(source_chunk->size() - source_chunk_start_index, still_to_insert); for (ColumnID column_id{0}; column_id < target_chunk->column_count(); ++column_id) { const auto& source_segment = source_chunk->get_segment(column_id); typed_segment_processors[column_id]->copy_data(source_segment, source_chunk_start_index, target_chunk->get_segment(column_id), target_start_index, num_to_insert); } still_to_insert -= num_to_insert; target_start_index += num_to_insert; source_chunk_start_index += num_to_insert; bool source_chunk_depleted = source_chunk_start_index == source_chunk->size(); if (source_chunk_depleted) { source_chunk_id++; source_chunk_start_index = 0u; } } for (auto i = start_index; i < start_index + current_num_rows_to_insert; i++) { // we do not need to check whether other operators have locked the rows, we have just created them // and they are not visible for other operators. // the transaction IDs are set here and not during the resize, because // tbb::concurrent_vector::grow_to_at_least(n, t)" does not work with atomics, since their copy constructor is // deleted. target_chunk->get_scoped_mvcc_data_lock()->tids[i] = context->transaction_id(); _inserted_rows.emplace_back(RowID{target_chunk_id, i}); } input_offset += current_num_rows_to_insert; start_index = 0u; } return nullptr; } void Insert::_on_commit_records(const CommitID cid) { for (auto row_id : _inserted_rows) { auto chunk = _target_table->get_chunk(row_id.chunk_id); auto mvcc_data = chunk->get_scoped_mvcc_data_lock(); mvcc_data->begin_cids[row_id.chunk_offset] = cid; mvcc_data->tids[row_id.chunk_offset] = 0u; } } void Insert::_on_rollback_records() { for (auto row_id : _inserted_rows) { auto chunk = _target_table->get_chunk(row_id.chunk_id); // We set the begin and end cids to 0 (effectively making it invisible for everyone) so that the ChunkCompression // does not think that this row is still incomplete. We need to make sure that the end is written before the begin. chunk->get_scoped_mvcc_data_lock()->end_cids[row_id.chunk_offset] = 0u; std::atomic_thread_fence(std::memory_order_release); chunk->get_scoped_mvcc_data_lock()->begin_cids[row_id.chunk_offset] = 0u; chunk->get_scoped_mvcc_data_lock()->tids[row_id.chunk_offset] = 0u; } } std::shared_ptr<AbstractOperator> Insert::_on_deep_copy( const std::shared_ptr<AbstractOperator>& copied_input_left, const std::shared_ptr<AbstractOperator>& copied_input_right) const { return std::make_shared<Insert>(_target_table_name, copied_input_left); } void Insert::_on_set_parameters(const std::unordered_map<ParameterID, AllTypeVariant>& parameters) {} } // namespace opossum
45.5
120
0.720129
cmfcmf
805ea71dabf146f76d987af60fe31fc1d9cb9102
11,863
hpp
C++
src/game_api/state.hpp
iojon/overlunky
096902bf8f0de28522ab140d900d64354ce536ac
[ "MIT" ]
null
null
null
src/game_api/state.hpp
iojon/overlunky
096902bf8f0de28522ab140d900d64354ce536ac
[ "MIT" ]
null
null
null
src/game_api/state.hpp
iojon/overlunky
096902bf8f0de28522ab140d900d64354ce536ac
[ "MIT" ]
1
2020-11-14T14:45:16.000Z
2020-11-14T14:45:16.000Z
#pragma once #include "items.hpp" #include "layer.hpp" #include "memory.hpp" #include "savedata.hpp" #include "screen.hpp" #include "screen_arena.hpp" #include "state_structs.hpp" #include "thread_utils.hpp" const float ZF = 0.737f; struct Layer; struct LevelGenSystem; struct StateMemory { size_t p00; uint32_t screen_last; uint32_t screen; uint32_t screen_next; uint32_t loading; Illumination* illumination; float fadevalue; // 0.0 = all visible; 1.0 = all black uint32_t fadeout; uint32_t fadein; uint32_t loading_black_screen_timer; // if state.loading is 1, this timer counts down to 0 while the screen is black (used after Ouroboros, in // credits, ...) uint8_t ingame; uint8_t playing; uint8_t pause; uint8_t b33; int32_t i34; uint32_t quest_flags; uint8_t correct_ushabti; // correct_ushabti = anim_frame - (2 * floor(anim_frame/12)) uint8_t i3cb; uint8_t i3cc; uint8_t i3cd; ENT_TYPE speedrun_character; // who administers the speedrun in base camp uint8_t speedrun_activation_trigger; // must transition from true to false to activate it uint8_t padding4; uint8_t padding5; uint8_t padding6; uint32_t w; uint32_t h; int8_t kali_favor; int8_t kali_status; int8_t kali_altars_destroyed; uint8_t b4f; int32_t i50; int32_t money_shop_total; // total $ spent at shops, persists between levels, number will be negative uint8_t world_start; uint8_t level_start; uint8_t theme_start; uint8_t b5f; uint32_t seed; uint32_t time_total; uint8_t world; uint8_t world_next; uint8_t level; uint8_t level_next; int32_t i6c; // i6c and i70 are a pointer to ThemeInfo (todo) int32_t i70; uint8_t theme; uint8_t theme_next; uint8_t win_state; // 0 = no win 1 = tiamat win 2 = hundun win 3 = CO win; set this and next doorway leads to victory scene uint8_t b73; ENT_TYPE end_spaceship_character; // who pops out the spaceship for a tiamat/hundun win uint8_t shoppie_aggro; uint8_t shoppie_aggro_levels; uint8_t merchant_aggro; uint8_t saved_dogs; uint8_t saved_cats; uint8_t saved_hamsters; uint8_t kills_npc; uint8_t level_count; uint8_t unknown1a; uint8_t unknown1b; bool world2_coffin_spawned; bool world4_coffin_spawned; bool world6_coffin_spawned; uint8_t unknown2b; uint8_t unknown2c; uint8_t unknown2d; ENT_TYPE waddler_storage[99]; int16_t waddler_storage_meta[99]; // to store mattock durability for example uint16_t journal_progression_count; JournalProgressionSlot journal_progression_slots[40]; uint8_t skip2[844]; ThemeProgression theme_progression; uint8_t unknown3; uint8_t unknown4; uint8_t unknown5a; uint8_t unknown5b; uint8_t unknown5c; uint8_t unknown5d; ArenaState arena; uint32_t journal_flags; ENT_TYPE first_damage_cause; // entity type that caused first damage, for the journal int8_t first_damage_world; int8_t first_damage_level; uint8_t i9f4c; uint8_t i9f4d; uint32_t time_last_level; uint32_t time_level; uint32_t time_speedrun; uint32_t money_last_levels; int32_t hud_flags; uint32_t presence_flags; ENT_TYPE coffin_contents; // entity type - the contents of the coffin that will be spawned (during levelgen) uint8_t cause_of_death; uint8_t padding10; uint8_t padding11; uint8_t padding12; ENT_TYPE cause_of_death_entity_type; int32_t waddler_floor_storage; // entity uid of the first floor_storage entity size_t toast; size_t speechbubble; uint32_t speechbubble_timer; uint32_t toast_timer; int32_t speechbubble_owner; Dialogue basecamp_dialogue; // screen pointers below are most likely in an array and indexed through the screen ID (-10), hence the nullptrs for // screens that are available in GameManager ScreenTeamSelect* screen_team_select; ScreenCamp* screen_camp; ScreenLevel* screen_level; ScreenTransition* screen_transition; ScreenDeath* screen_death; size_t unknown_screen_spaceship; // potentially ScreenSpaceship, but is nullptr (there is no UI rendering on spaceship anyway) ScreenWin* screen_win; ScreenCredits* screen_credits; ScreenScores* screen_scores; ScreenConstellation* screen_constellation; ScreenRecap* screen_recap; size_t unknown_screen_arena_menu; // potentially ScreenArenaMenu, available in GameManager ScreenArenaStagesSelect* screen_arena_stages_select1; size_t unknown_screen_arena_intro; // potentially ScreenArenaIntro, available in GameManager ScreenArenaStagesSelect* screen_arena_stages_select2; ScreenArenaIntro* screen_arena_intro; ScreenArenaLevel* screen_arena_level; ScreenArenaScore* screen_arena_score; size_t unknown_screen_online_loading; // potentially ScreenOnlineLoading, available in GameManager size_t unknown_screen_online_lobby; // potentially ScreenOnlineLobby, available in GameManager uint32_t next_entity_uid; uint16_t unknown20; uint16_t screen_change_counter; // increments every time screen changes; used in online sync together with next_entity_uid and unknown20 as a 64bit number PlayerInputs* player_inputs; Items* items; LevelGenSystem* level_gen; Layer* layers[2]; Logic* logic; QuestsInfo* quests; std::unordered_map<uint32_t, int32_t>* ai_targets; // e.g. hired hand uid -> snake uid LiquidPhysics* liquid_physics; PointerList* particle_emitters; // list of ParticleEmitterInfo* PointerList* lightsources; // list of Illumination* size_t unknown27; std::unordered_map<uint32_t, Entity*> instance_id_to_pointer; size_t unknown28; size_t unknown29; size_t unknown30; uint32_t layer_transition_effect_timer; uint8_t camera_layer; uint8_t unknowk31a; uint8_t unknowk31b; uint8_t unknowk31c; size_t unknown32; size_t unknown33; size_t unknown34; size_t unknown35; size_t unknown36; uint32_t time_startup; uint32_t special_visibility_flags; Camera* camera; /// Returns animation_frame of the correct ushabti uint16_t get_correct_ushabti(); void set_correct_ushabti(uint16_t animation_frame); }; struct State { size_t location; size_t addr_damage; size_t addr_insta; size_t addr_zoom; size_t addr_zoom_shop; size_t addr_dark; static void set_write_load_opt(bool allow); static State& get(); // Returns the main-thread version of StateMemory* StateMemory* ptr() const; // Returns the local-thread version of StateMemory* StateMemory* ptr_local() const; Layer* layer(uint8_t index) { return ptr()->layers[index]; } Layer* layer_local(uint8_t index) { return ptr_local()->layers[index]; } Items* items() { auto pointer = ptr()->items; return (Items*)(pointer); } void godmode(bool g) { // log::debug!("God {:?}" mode; g); if (g) { write_mem_prot(addr_damage, ("\xC3"s), true); write_mem_prot(addr_insta, ("\xC3"s), true); } else { write_mem_prot(addr_damage, ("\x48"s), true); write_mem_prot(addr_insta, ("\x40"s), true); } } void darkmode(bool g) { // log::debug!("God {:?}" mode; g); if (g) { write_mem_prot(addr_dark, ("\x90\x90"s), true); } else { write_mem_prot(addr_dark, ("\xEB\x2E"s), true); } } void zoom(float level) { // This technically sets camp zoom but not interactively :( // auto addr_zoom = find_inst(memory.exe(), &hex!("C7 80 E8 04 08 00"), // memory.after_bundle); write_mem_prot(memory.at_exe(addr_zoom + 6), // to_le_bytes(level), true); addr_zoom = memory.after_bundle; auto roomx = ptr()->w; if (level == 0.0) { switch (roomx) { case 1: level = 9.50f; break; case 2: level = 16.29f; break; case 3: level = 23.08f; break; case 4: level = 29.87f; break; case 5: level = 36.66f; break; case 6: level = 43.45f; break; case 7: level = 50.24f; break; case 8: level = 57.03f; break; default: level = 13.5f; } } static size_t offset[4] = {0}; // where the different hardcoded zoom levels are written if (offset[0] == 0) { auto memory = Memory::get(); auto _addr_zoom = memory.after_bundle; for (int i = 0; i < 4; i++) { _addr_zoom = find_inst(memory.exe(), "\x48\x8B\x48\x10\xC7\x81"s, _addr_zoom + 1); offset[i] = memory.at_exe(_addr_zoom) + 10; } } if (offset[0] != 0) write_mem_prot(offset[0], to_le_bytes(level), true); // I dunno :D if (offset[1] != 0) write_mem_prot(offset[1], to_le_bytes(level), true); // shop if (offset[2] != 0) write_mem_prot(offset[2], to_le_bytes(level), true); // level if (offset[3] != 0) write_mem_prot(offset[3], to_le_bytes(level), true); // default (camp, transition) static size_t real_offset = 0; // actual target zoom level if (real_offset == 0) { auto memory = Memory::get(); auto _offset = memory.at_exe(0x22334A00); //TODO: patterns or something. Also this pointer is kinda slow, it doesn't work before intro cutscene. _offset = read_u64(_offset); if (_offset != 0) { _offset += 0x804f0; real_offset = _offset; } } if (real_offset != 0) { write_mem_prot(real_offset, to_le_bytes(level), true); } } std::pair<float, float> click_position(float x, float y); std::pair<float, float> screen_position(float x, float y); float get_zoom_level(); uint32_t flags() { return ptr()->hud_flags; } void set_flags(uint32_t f) { ptr()->hud_flags = f; } void set_pause(uint8_t p) { ptr()->pause = p; } uint32_t get_frame_count() { return read_u32((size_t)ptr() - 0xd0); } std::vector<int64_t> read_prng() { std::vector<int64_t> prng; for (int i = 0; i < 20; ++i) { prng.push_back(read_i64((size_t)ptr() - 0xb0 + 8 * static_cast<size_t>(i))); } return prng; } Entity* find(uint32_t unique_id) { auto& map = ptr()->instance_id_to_pointer; auto it = map.find(unique_id); if (it == map.end()) return nullptr; return it->second; } std::pair<float, float> get_camera_position(); void set_camera_position(float cx, float cy); void warp(uint8_t w, uint8_t l, uint8_t t); void set_seed(uint32_t seed); SaveData* savedata(); };
31.634667
159
0.610975
iojon
80629117d2c79ecfb56e7211afef34ff974ecfd5
18,248
cpp
C++
tags/20090801_v0.2.0/src/singlePlayer/wh/CSelectTeamWindowHandler.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
tags/20090801_v0.2.0/src/singlePlayer/wh/CSelectTeamWindowHandler.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
tags/20090801_v0.2.0/src/singlePlayer/wh/CSelectTeamWindowHandler.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
/****************************************************************************** * Copyright (C) 2008 - 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 <libintl.h> #include "CSelectTeamWindowHandler.h" #include "../db/bean/CPfTeams.h" #include "../db/bean/CPfConfederations.h" #include "../db/bean/CPfCountries.h" #include "../db/bean/CPfCompetitions.h" #include "../db/dao/factory/IDAOFactory.h" #include "../option/CSinglePlayerOptionManager.h" #include "../CSinglePlayerGame.h" #include "../../engine/CGameEngine.h" #include "../../exceptions/PFException.h" #include "../../utils/CLog.h" #include "../../utils/gui/CImageListboxItem.h" CSelectTeamWindowHandler::CSelectTeamWindowHandler(CSinglePlayerGame &game) : CWindowHandler("selectTeam.layout"), m_game(game) { LOG_DEBUG("CSelectTeamWindowHandler()"); m_confederationsList = NULL; m_countriesList = NULL; m_competitionsList = NULL; m_teamsList = NULL; m_lastSeason = NULL; } CSelectTeamWindowHandler::~CSelectTeamWindowHandler() { LOG_DEBUG("~CSelectTeamWindowHandler()"); } void CSelectTeamWindowHandler::init() { CEGUI::WindowManager *windowMngr = CEGUI::WindowManager::getSingletonPtr(); m_selectButton = static_cast<CEGUI::PushButton*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/SelectButton")); m_backButton = static_cast<CEGUI::PushButton*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/BackButton")); m_guiTeamsList = static_cast<CEGUI::ItemListbox*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/TeamsList")); m_guiTeamName = static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/TeamName")); m_guiTeamBudget = static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/TeamBudget")); m_guiTeamShield = static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/TeamShield")); m_guiConfederationImage = static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/ConfederationImage")); m_guiCountryImage = static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/CountryImage")); m_guiTeamAverage = static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/TeamAverage")); m_confederationsCombobox = static_cast<CEGUI::Combobox*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/Confederation")); m_countriesCombobox = static_cast<CEGUI::Combobox*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/Country")); m_competitionsCombobox = static_cast<CEGUI::Combobox*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/Competition")); m_confederationsCombobox->getEditbox()->setEnabled(false); m_countriesCombobox ->getEditbox()->setEnabled(false); m_competitionsCombobox ->getEditbox()->setEnabled(false); m_guiTeamsList->setWantsMultiClickEvents(true); // i18n support m_backButton ->setText((CEGUI::utf8*)gettext("Back")); m_selectButton->setText((CEGUI::utf8*)gettext("Select Team")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/SelectTeamLabel"))->setText((CEGUI::utf8*)gettext("Please, select your team:")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/NameLabel"))->setText((CEGUI::utf8*)gettext("Name:")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/BudgetLabel"))->setText((CEGUI::utf8*)gettext("Budget:")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/AverageLabel"))->setText((CEGUI::utf8*)gettext("Average:")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/ConfederationLabel"))->setText((CEGUI::utf8*)gettext("Confederation:")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/CountryLabel"))->setText((CEGUI::utf8*)gettext("Country:")); static_cast<CEGUI::Window*>(windowMngr->getWindow((CEGUI::utf8*)"SelectTeam/CompetitionLabel"))->setText((CEGUI::utf8*)gettext("Competition:")); // Event handle registerEventConnection(m_confederationsCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::confederationsComboboxListSelectionChanged, this))); registerEventConnection(m_countriesCombobox ->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::countriesComboboxListSelectionChanged, this))); registerEventConnection(m_competitionsCombobox ->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::competitionsComboboxListSelectionChanged, this))); registerEventConnection(m_guiTeamsList ->subscribeEvent(CEGUI::ItemListbox::EventSelectionChanged, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::teamsListboxSelectionChanged, this))); registerEventConnection(m_guiTeamsList ->subscribeEvent(CEGUI::ItemListbox::EventMouseDoubleClick, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::teamsListboxMouseDoubleClick, this))); registerEventConnection(m_selectButton ->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::selectButtonClicked, this))); registerEventConnection(m_backButton ->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSelectTeamWindowHandler::backButtonClicked, this))); } void CSelectTeamWindowHandler::enter() { loadLastSeason(); int confederation = loadConfederationsList(); int country = loadCountriesList(confederation); int competition = loadCompetitionsList(country); loadTeamList(competition); m_selectButton->setEnabled(false); } void CSelectTeamWindowHandler::leave() { if(m_confederationsList!=NULL) { m_game.getIDAOFactory()->getIPfConfederationsDAO()->freeVector(m_confederationsList); m_confederationsList = NULL; } if(m_countriesList!=NULL) { m_game.getIDAOFactory()->getIPfCountriesDAO()->freeVector(m_countriesList); m_countriesList = NULL; } if(m_competitionsList!=NULL) { m_game.getIDAOFactory()->getIPfCompetitionsDAO()->freeVector(m_competitionsList); m_competitionsList = NULL; } if(m_teamsList!=NULL) { m_game.getIDAOFactory()->getIPfTeamsDAO()->freeVector(m_teamsList); m_teamsList = NULL; } if( m_lastSeason!=NULL ){ delete m_lastSeason; m_lastSeason = NULL; } m_confederationsCombobox->resetList(); m_countriesCombobox ->resetList(); m_competitionsCombobox ->resetList(); m_guiTeamsList ->resetList(); clearTeamInfo(); } void CSelectTeamWindowHandler::loadLastSeason() { if( m_lastSeason!=NULL ){ delete m_lastSeason; m_lastSeason = NULL; } IPfSeasonsDAO *seasonsDAO = m_game.getIDAOFactory()->getIPfSeasonsDAO(); m_lastSeason = seasonsDAO->findLastSeason(); if( m_lastSeason==NULL || m_lastSeason->getXSeason_str()=="" ){ throw PFEXCEPTION("[CSelectTeamWindowHandler::loadLastSeason] Last season not found"); } } int CSelectTeamWindowHandler::loadConfederationsList() { IPfConfederationsDAO *confederationsDAO = m_game.getIDAOFactory()->getIPfConfederationsDAO(); if(m_confederationsList!=NULL) { confederationsDAO->freeVector(m_confederationsList); } m_confederationsList = confederationsDAO->findByXFKSeasonWithLeague(m_lastSeason->getXSeason_str()); std::vector<CPfConfederations*>::iterator it; for(it = m_confederationsList->begin(); it != m_confederationsList->end(); it++) { CPfConfederations *confederation = (*it); m_confederationsCombobox->addItem(new CEGUI::ListboxTextItem ((CEGUI::utf8*)confederation->getSConfederation().c_str(), confederation->getXConfederation())); } CPfConfederations *conf = m_confederationsList->front(); m_confederationsCombobox->setText((CEGUI::utf8*)conf->getSConfederation().c_str()); m_guiConfederationImage->setProperty("Image", "set:"+ conf->getSLogo() +" image:"+conf->getSLogo()+"_map"); return m_confederationsList->front()->getXConfederation(); } int CSelectTeamWindowHandler::loadCountriesList(int XConfederation) { IPfCountriesDAO *countriesDAO = m_game.getIDAOFactory()->getIPfCountriesDAO(); if(m_countriesList!=NULL) { countriesDAO->freeVector(m_countriesList); } m_countriesList = countriesDAO->findByXFkConfederationAndXFKSeasonWithLeague(XConfederation, m_lastSeason->getXSeason()); int selectedCountry = -1; if(!m_countriesList->empty()) { std::vector<CPfCountries*>::iterator it; for(it = m_countriesList->begin(); it != m_countriesList->end(); it++) { CPfCountries *country = (*it); m_countriesCombobox->addItem(new CEGUI::ListboxTextItem ((CEGUI::utf8*)country->getSShortName().c_str(), country->getXCountry())); } CPfCountries *country = m_countriesList->front(); m_countriesCombobox->setText((CEGUI::utf8*)country->getSShortName().c_str()); m_guiCountryImage->setProperty("Image", "set:"+ country->getSFlag() +" image:"+country->getSFlag()+"_map"); selectedCountry = m_countriesList->front()->getXCountry(); } else { m_countriesCombobox->setText((CEGUI::utf8*)gettext("No countries")); } return selectedCountry; } int CSelectTeamWindowHandler::loadCompetitionsList(int XCountry) { IPfCompetitionsDAO *competitionsDAO = m_game.getIDAOFactory()->getIPfCompetitionsDAO(); if(m_competitionsList!=NULL) { competitionsDAO->freeVector(m_competitionsList); } m_competitionsList = competitionsDAO->findByXFkCountryAndXFKSeason(XCountry, m_lastSeason->getXSeason()); int selectedCompetition = -1; if(!m_competitionsList->empty()) { std::vector<CPfCompetitions*>::iterator it; for(it = m_competitionsList->begin(); it != m_competitionsList->end(); it++) { CPfCompetitions *competition = (*it); m_competitionsCombobox->addItem(new CEGUI::ListboxTextItem ((CEGUI::utf8*)competition->getSCompetition().c_str(), competition->getXCompetition())); } m_competitionsCombobox->setText((CEGUI::utf8*)m_competitionsList->front()->getSCompetition().c_str()); selectedCompetition = m_competitionsList->front()->getXCompetition(); } else { m_competitionsCombobox->setText((CEGUI::utf8*)gettext("No competitions")); } return selectedCompetition; } void CSelectTeamWindowHandler::loadTeamList(int XCompetition) { IPfTeamsDAO* teamsDAO = m_game.getIDAOFactory()->getIPfTeamsDAO(); if(m_teamsList!=NULL) { teamsDAO->freeVector(m_teamsList); } m_teamsList = teamsDAO->findByXFKCompetitionAndXFKSeason(XCompetition, m_lastSeason->getXSeason()); if(!m_teamsList->empty()) { CEGUI::WindowManager * m_WndMgr = CEGUI::WindowManager::getSingletonPtr(); std::vector<CPfTeams*>::iterator it; for( it=m_teamsList->begin(); it!=m_teamsList->end(); it++ ){ CPfTeams *team = (*it); CEGUI::CImageListboxItem *item = (CEGUI::CImageListboxItem*)m_WndMgr->createWindow("ArridiDesign/ImageListboxItem", (CEGUI::utf8*)team->getSTeam().c_str()); item->setID(team->getXTeam()); item->getChildAtIdx(0)->setProperty("Image", "set:"+ team->getSLogo() +" image:"+team->getSLogo()+"_s"); item->setText((CEGUI::utf8*)team->getSTeam().c_str()); m_guiTeamsList->addItem(item); } } } bool CSelectTeamWindowHandler::teamsListboxSelectionChanged(const CEGUI::EventArgs& e) { if(m_guiTeamsList->getFirstSelectedItem()!=0 && m_teamsList!=NULL) { m_selectButton->setEnabled(true); CEGUI::ItemEntry* item = m_guiTeamsList->getFirstSelectedItem(); int xTeam = item->getID(); std::vector<CPfTeams*>::iterator it; bool found=false; it=m_teamsList->begin(); while(it!=m_teamsList->end() && !found) { CPfTeams *team = (*it); if(team->getXTeam() == xTeam) { loadTeamInfo(team); found = true; } it++; } } else { m_selectButton->setEnabled(false); clearTeamInfo(); } return true; } bool CSelectTeamWindowHandler::confederationsComboboxListSelectionChanged(const CEGUI::EventArgs& e) { CEGUI::ListboxItem *item = m_confederationsCombobox->getSelectedItem(); if(item != NULL) { IPfConfederationsDAO *confederationsDAO = m_game.getIDAOFactory()->getIPfConfederationsDAO(); CPfConfederations *conf = confederationsDAO->findByXConfederation(item->getID()); m_confederationsCombobox->setText(item->getText()); m_guiConfederationImage->setProperty("Image", "set:"+ conf->getSLogo() +" image:"+conf->getSLogo()+"_map"); m_countriesCombobox->clearAllSelections(); m_countriesCombobox->resetList(); m_countriesCombobox->getEditbox()->setText(""); m_guiCountryImage->setProperty("Image", "set: image:full_image"); m_competitionsCombobox->clearAllSelections(); m_competitionsCombobox->resetList(); m_competitionsCombobox->getEditbox()->setText(""); m_guiTeamsList->resetList(); m_selectButton->setEnabled(false); clearTeamInfo(); int country = loadCountriesList(item->getID()); int competition = loadCompetitionsList(country); loadTeamList(competition); } return true; } bool CSelectTeamWindowHandler::countriesComboboxListSelectionChanged(const CEGUI::EventArgs& e) { CEGUI::ListboxItem *item = m_countriesCombobox->getSelectedItem(); if(item != NULL) { IPfCountriesDAO *countriesDAO = m_game.getIDAOFactory()->getIPfCountriesDAO(); CPfCountries *country = countriesDAO->findByXCountry(item->getID()); m_countriesCombobox->setText(item->getText()); m_guiCountryImage->setProperty("Image", "set:"+ country->getSFlag() +" image:"+country->getSFlag()+"_map"); m_competitionsCombobox->clearAllSelections(); m_competitionsCombobox->resetList(); m_competitionsCombobox->getEditbox()->setText(""); m_guiTeamsList->resetList(); m_selectButton->setEnabled(false); clearTeamInfo(); int competition = loadCompetitionsList(item->getID()); loadTeamList(competition); } return true; } bool CSelectTeamWindowHandler::competitionsComboboxListSelectionChanged(const CEGUI::EventArgs& e) { CEGUI::ListboxItem *item = m_competitionsCombobox->getSelectedItem(); if(item != NULL) { m_competitionsCombobox->setText(item->getText()); m_guiTeamsList->resetList(); m_selectButton->setEnabled(false); clearTeamInfo(); loadTeamList(item->getID()); } return true; } bool CSelectTeamWindowHandler::teamsListboxMouseDoubleClick(const CEGUI::EventArgs& e) { if(m_guiTeamsList->getFirstSelectedItem()!=0) { selectButtonClicked(e); } return true; } bool CSelectTeamWindowHandler::selectButtonClicked(const CEGUI::EventArgs& e) { CEGUI::ItemEntry* item = m_guiTeamsList->getFirstSelectedItem(); m_game.getOptionManager()->setGamePlayerTeam(item->getID()); m_game.getOptionManager()->setGameNew(false); CGameEngine::getInstance()->getWindowManager()->nextScreen("Game"); CGameEngine::getInstance()->getWindowManager()->clearHistory(); return true; } bool CSelectTeamWindowHandler::backButtonClicked(const CEGUI::EventArgs& e) { CGameEngine::getInstance()->getWindowManager()->previousScreen(); return true; } void CSelectTeamWindowHandler::loadTeamInfo(CPfTeams *team) { // TODO Add more team information m_guiTeamName->setText((CEGUI::utf8*)team->getSTeam().c_str()); std::ostringstream budget; budget << team->getNBudget(); m_guiTeamBudget->setText((CEGUI::utf8*)budget.str().c_str()); IPfTeamAveragesDAO *teamAveragesDAO = m_game.getIDAOFactory()->getIPfTeamAveragesDAO(); CPfTeamAverages *teamAverage = teamAveragesDAO->findByXTeam(team->getXTeam_str()); std::ostringstream average; average << teamAverage->getNTotal(); m_guiTeamAverage->setText((CEGUI::utf8*)average.str().c_str()); delete teamAverage; //Loading Shield m_guiTeamShield->setProperty("Image", "set:"+ team->getSLogo() +" image:"+team->getSLogo()+"_b"); } void CSelectTeamWindowHandler::clearTeamInfo() { // TODO Clear all team information m_guiTeamName ->setText(""); m_guiTeamBudget ->setText(""); m_guiTeamAverage->setText(""); m_guiTeamShield ->setProperty("Image", "set: image:full_image"); }
46.43257
218
0.678431
dividio
8063c264cbd2bfa952a1ee4fb10a3a7a290bac0b
1,171
cc
C++
patches/process-kill_posix.cc
bolthole/solaris-chromium-patches
5ed86010096ace6e50bfa97bb8ca0237b0f834ee
[ "Apache-2.0" ]
null
null
null
patches/process-kill_posix.cc
bolthole/solaris-chromium-patches
5ed86010096ace6e50bfa97bb8ca0237b0f834ee
[ "Apache-2.0" ]
null
null
null
patches/process-kill_posix.cc
bolthole/solaris-chromium-patches
5ed86010096ace6e50bfa97bb8ca0237b0f834ee
[ "Apache-2.0" ]
1
2018-11-12T09:01:36.000Z
2018-11-12T09:01:36.000Z
diff --git a/base/process/kill_posix.cc b/base/process/kill_posix.cc index bff7be4..544b9a3 100644 --- a/base/process/kill_posix.cc +++ b/base/process/kill_posix.cc @@ -248,6 +248,17 @@ bool WaitForExitCodeWithTimeout(ProcessHandle handle, bool WaitForProcessesToExit(const FilePath::StringType& executable_name, base::TimeDelta wait, const ProcessFilter* filter) { +#if defined(OS_SOLARIS) + // Okay, yes this is an ugly hack. But filling out all the + // process_iterator_BLAHBLAHBLAH garbage is even uglier, and + // the only purpose is to wait around for a named process to die. + // We dont need things that fancy. Just fake it for now, + // presume it will die eventually :) + + base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(400)); + return 0; + +#else bool result = false; // TODO(port): This is inefficient, but works if there are multiple procs. @@ -264,6 +275,7 @@ bool WaitForProcessesToExit(const FilePath::StringType& executable_name, } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta()); return result; +#endif } #if defined(OS_MACOSX)
37.774194
92
0.687447
bolthole
8067adad0aa629091a19ffd2ada16175fbdd5d4b
1,924
inl
C++
dependencies/2dmapping/UnitSquareToTriangle.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
dependencies/2dmapping/UnitSquareToTriangle.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
dependencies/2dmapping/UnitSquareToTriangle.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
/*! \file UnitSquareToTriangle.inl * \author Jared Hoberock * \brief Inline file for UnitSquareToTriangle.h. */ #include "UnitSquareToTriangle.h" #include "UnitSquareToIsoscelesRightTriangle.h" template<typename Real, typename Point> void UnitSquareToTriangle ::evaluate(const Real &u, const Real &v, const Point &v0, const Point &v1, const Point &v2, Point &p, Real *pdf) { Real b[2]; UnitSquareToIsoscelesRightTriangle::evaluate(u,v,b); p = b[0] * v0 + b[1] * v1 + (Real(1) - b[0] - b[1]) * v2; if(pdf) { *pdf = evaluatePdf<Real,Point>(p,v0,v1,v2); } // end if } // end UnitSquareToTriangle::evaluate() template<typename Real, typename Point, typename Point2> void UnitSquareToTriangle ::evaluate(const Real &u, const Real &v, const Point &v0, const Point &v1, const Point &v2, Point &p, Point2 &b, Real *pdf) { UnitSquareToIsoscelesRightTriangle::evaluate(u,v,b); p = b[0] * v0 + b[1] * v1 + (Real(1) - b[0] - b[1]) * v2; if(pdf) { *pdf = evaluatePdf<Real,Point>(p,v0,v1,v2); } // end if } // end UnitSquareToTriangle::evaluate() template<typename Point, typename Real> void UnitSquareToTriangle ::inverse(const Point &p, const Point &v0, const Point &v1, const Point &v2, Real &u, Real &v) { std::cerr << "UnitSquareToTriangle::inverse(): Unimplemented method called!" << std::endl; } // end UnitSquareToTriangle::inverse() template<typename Real, typename Point> Real UnitSquareToTriangle ::evaluatePdf(const Point &p, const Point &v0, const Point &v1, const Point &v2) { // compute the area of (v0,v1,v2) Real denom = Real(0.5) * (v1 - v0).cross(v2 - v0).norm(); return Real(1) / denom; } // end UnitSquareToTriangle::evaluatePdf()
30.0625
93
0.601871
jaredhoberock
806898e6e74ed2387d1eec075d58469555b53dc6
817
cpp
C++
LD20 - Acid/imagemgr.cpp
milo-brandt/milos-ludum-dare-entries
6b4907463395ee99720386bca48726a798af14d2
[ "MIT" ]
null
null
null
LD20 - Acid/imagemgr.cpp
milo-brandt/milos-ludum-dare-entries
6b4907463395ee99720386bca48726a798af14d2
[ "MIT" ]
null
null
null
LD20 - Acid/imagemgr.cpp
milo-brandt/milos-ludum-dare-entries
6b4907463395ee99720386bca48726a798af14d2
[ "MIT" ]
null
null
null
/* * imagemgr.cpp * Acid * * Created by Milo Brandt on 4/30/11. * Copyright 2011 Apple Inc. All rights reserved. * */ #include "imagemgr.h" imageManager::imageManager(){ x[plyr_sprite].LoadFromFile("player.png"); x[goal_sprite].LoadFromFile("Goal.png"); x[complete_sprite].LoadFromFile("complete.png"); x[title_sprite].LoadFromFile("Title.png"); x[help_sprite].LoadFromFile("instructions.png"); x[chat_sprite+1].LoadFromFile("Talk1.png"); x[chat_sprite+2].LoadFromFile("Talk2.png"); x[chat_sprite+3].LoadFromFile("Talk3.png"); x[chat_sprite+4].LoadFromFile("Talk4.png"); x[chat_sprite+5].LoadFromFile("Talk5.png"); x[chat_sprite+6].LoadFromFile("Talk6.png"); x[lvl1_sprite].LoadFromFile("instructionsA.png"); x[lvl2_sprite].LoadFromFile("lvl2.png"); x[win_sprite].LoadFromFile("win.png"); }
30.259259
50
0.724602
milo-brandt
8068ab1c95f7f3b86016674e48db57c8b904aa89
109
hpp
C++
include/rua/sched.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
include/rua/sched.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
include/rua/sched.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
#ifndef _RUA_SCHED_HPP #define _RUA_SCHED_HPP #include "sched/await.hpp" #include "sched/dozer.hpp" #endif
13.625
26
0.779817
yulon
8069c0f0f5b6082614643f71af872753d87ad731
1,008
cpp
C++
atcoder-dp/lcs.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
atcoder-dp/lcs.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
atcoder-dp/lcs.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { string X, Y; cin >> X; cin >> Y; int m = X.length(); int n = Y.length(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) dp[i][j] = 0; else { if (X[i] == t[j]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } } int i = m, j = n; string st = ""; while (i > 0 && j > 0) { if (X[i - 1] == t[j - 1]) { st.push_back(X[i-1]); i--; j--; } else { if (dp[i][j - 1] > dp[i - 1][j]) j--; else i--; } } reverse(st.begin(), st.end()); cout << st << "\n"; return 0; }
21
63
0.284722
rranjan14
80715f67f775881f9ab4b28a5ffd43db8f167f49
839
cpp
C++
main/PISupervisor/src/PIDiskSize.cpp
sim1st/endpointdlp
f5203f23e93b00c8242c45fa85c26d9b7419e50c
[ "Apache-2.0" ]
null
null
null
main/PISupervisor/src/PIDiskSize.cpp
sim1st/endpointdlp
f5203f23e93b00c8242c45fa85c26d9b7419e50c
[ "Apache-2.0" ]
null
null
null
main/PISupervisor/src/PIDiskSize.cpp
sim1st/endpointdlp
f5203f23e93b00c8242c45fa85c26d9b7419e50c
[ "Apache-2.0" ]
null
null
null
#ifndef _PIDISKSIZE_CPP #define _PIDISKSIZE_CPP #include "PIDiskSize.h" #include "include_system.h" #include <sys/statvfs.h> //////////////////////////////////////// // CPIDiskSize CPIDiskSize::CPIDiskSize() { clear(); } CPIDiskSize::~CPIDiskSize() { } void CPIDiskSize::clear(void) { totalBytes = 0.0; freeBytes = 0.0; usedBytes = 0.0; } bool CPIDiskSize::getSystemDiskSize(void) { clear(); struct statvfs sv; memset( &sv, 0, sizeof(sv) ); int result = statvfs( "/", &sv ); if(result != 0) { return false; } totalBytes = (double)(sv.f_blocks * sv.f_frsize); freeBytes = (double)(sv.f_bfree * sv.f_frsize); usedBytes = totalBytes - freeBytes; return true; } void CPIDiskSize::getUsedBytes(void) { usedBytes = totalBytes - freeBytes; } #endif // #ifndef _PIDISKSIZE_CPP
19.511628
51
0.622169
sim1st
807aa7f5dd3ef3255444c00cf2901498e3b89131
1,496
cc
C++
src/triangle.cc
interval1066/quetest
68958adaae845ce1132a21da3955af56f74228bb
[ "BSD-2-Clause" ]
null
null
null
src/triangle.cc
interval1066/quetest
68958adaae845ce1132a21da3955af56f74228bb
[ "BSD-2-Clause" ]
null
null
null
src/triangle.cc
interval1066/quetest
68958adaae845ce1132a21da3955af56f74228bb
[ "BSD-2-Clause" ]
null
null
null
#include <triangle.h> #include <segment.h> #include <algorithm> #include <iostream> using namespace std; using namespace slicer; Triangle::Triangle(Vertex v1, Vertex v2, Vertex v3) : v1(v1), v2(v2), v3(v3) {} float Triangle::x_min() const { return min(v1.x, min(v2.x, v3.x)); } float Triangle::x_max() const { return max(v1.x, max(v2.x, v3.x)); } float Triangle::y_min() const { return min(v1.y, min(v2.y, v3.y)); } float Triangle::y_max() const { return max(v1.y, max(v2.y, v3.y)); } float Triangle::z_min() const { return min(v1.z, min(v2.z, v3.z)); } float Triangle::z_max() const { return max(v1.z, max(v2.z, v3.z)); } bool Triangle::belong_to_plane_z() const { return (v1.z == v2.z) && (v2.z == v3.z); } Triangle& Triangle::operator+=(Vertex shift) { v1 += shift; v2 += shift; v3 += shift; return *this; } std::vector<Vertex> Triangle::intersect(float z) const { Segment l1(v1, v2), l2(v2, v3), l3(v3, v1); Vertex p1 = l1.intersect_with_plane(z); Vertex p2 = l2.intersect_with_plane(z); Vertex p3 = l3.intersect_with_plane(z); vector<Vertex> res; if (p1.between_with_e(v1, v2)) res.push_back(p1); if (p2.between_with_e(v2, v3) && find(res.begin(), res.end(), p2) == res.end()) res.push_back(p2); if (p3.between_with_e(v3, v1) && find(res.begin(), res.end(), p3) == res.end()) res.push_back(p3); return res; } std::ostream& operator << (std::ostream& stream, const Triangle& t) { stream << t.v1 << " " << t.v2 << " " << t.v3; return stream; }
16.622222
80
0.637032
interval1066
80842a0a5b8365f8e37d3b4c3514392abc363945
1,612
hpp
C++
code/jalog/Scope.hpp
iboB/jalog
d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9
[ "MIT" ]
3
2021-12-07T06:16:31.000Z
2021-12-22T14:12:36.000Z
code/jalog/Scope.hpp
iboB/jalog
d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9
[ "MIT" ]
null
null
null
code/jalog/Scope.hpp
iboB/jalog
d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9
[ "MIT" ]
null
null
null
// jalog // Copyright (c) 2021-2022 Borislav Stanimirov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #pragma once #include "API.h" #include "Level.hpp" #include "ScopeDesc.hpp" #include <atomic> #include <vector> #include <string_view> namespace jalog { class Logger; class Sink; class JALOG_API Scope { public: // creates a default logger scope explicit Scope(std::string_view label, uintptr_t id = 0, intptr_t userData = -1); // creates a scope for a given logger Scope(Logger& logger, std::string_view label, uintptr_t id = 0, intptr_t userData = -1); ~Scope(); Scope(const Scope&) = delete; Scope& operator=(const Scope&) = delete; Scope(Scope&&) = delete; Scope& operator=(Scope&&) = delete; const ScopeDesc& desc() const { return m_desc; } void setLevel(Level lvl) { m_level.store(lvl, std::memory_order_relaxed); } Level level() const { return m_level.load(std::memory_order_relaxed); } bool enabled(Level lvl) const { return lvl >= level(); } // add an entry but don't perform the enabled check // assume it's performed from the outside void addEntryUnchecked(Level lvl, std::string_view text); // add entry if the level is >= than our min level void addEntry(Level lvl, std::string_view text) { if (enabled(lvl)) addEntryUnchecked(lvl, text); } private: friend class Logger; std::atomic<Level> m_level = Level::Debug; protected: Logger& m_logger; ScopeDesc m_desc; std::vector<Sink*> m_sinks; }; }
23.705882
103
0.684243
iboB
808bc2b68f3917e36970e82b72836aa2f5d18f30
1,672
cpp
C++
RealityCore/Source/GUI/Login.cpp
Intro-Ventors/Re-Co-Desktop
8547cca9230069a36973ec836426d4610f30f8bb
[ "MIT" ]
null
null
null
RealityCore/Source/GUI/Login.cpp
Intro-Ventors/Re-Co-Desktop
8547cca9230069a36973ec836426d4610f30f8bb
[ "MIT" ]
null
null
null
RealityCore/Source/GUI/Login.cpp
Intro-Ventors/Re-Co-Desktop
8547cca9230069a36973ec836426d4610f30f8bb
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Intro-Ventors #include "Login.hpp" #include "../../ui_Login.h" #include <QMovie> #include <QCryptographicHash> namespace GUI { Login::Login(QWidget* pParent) : QDialog(pParent, Qt::FramelessWindowHint) , m_pLogin(new Ui::Login()) { // Setup the UI. m_pLogin->setupUi(this); // Create and assign the movie to the label. auto pMovie = new QMovie(":/Assets/2D/SplashScreen.gif"); m_pLogin->movie->setMovie(pMovie); // Set the size of the movie and start playing. pMovie->setScaledSize(QSize(480, 270)); pMovie->start(); //setAttribute(Qt::WA_TranslucentBackground); setStyleSheet("background-color: black;"); // Setup connections. connect(m_pLogin->signIn, &QPushButton::pressed, this, &Login::onSignIn); connect(m_pLogin->signUp, &QPushButton::pressed, this, &Login::onSignUp); } Login::~Login() { // Delete the allocated memory. delete m_pLogin; } QString Login::getUsername() const { return m_pLogin->username->text(); } QByteArray Login::getPassword() const { // Hash and return the hashed bytes. return QCryptographicHash::hash(m_pLogin->password->text().toLocal8Bit(), QCryptographicHash::Sha3_512); } void Login::clearInput() { m_pLogin->username->clear(); m_pLogin->password->clear(); } void Login::onSignIn() { const auto username = getUsername(); const auto password = getPassword(); // Clear the user inputs. clearInput(); // Whatever the log in logic. // Say that we accept the login. accept(); } void Login::onSignUp() { // Clear the user inputs. clearInput(); // Whatever the sign up logic. // Say that we rejected it. reject(); } }
20.641975
106
0.68122
Intro-Ventors
80926846273cfea668bdebae73a235d443533e22
1,150
cpp
C++
src/largest-divisible-subset.cpp
amoudgl/leetcode-solutions
dc6570bb06b82c2c70d6f387b3486897035cc995
[ "MIT" ]
null
null
null
src/largest-divisible-subset.cpp
amoudgl/leetcode-solutions
dc6570bb06b82c2c70d6f387b3486897035cc995
[ "MIT" ]
null
null
null
src/largest-divisible-subset.cpp
amoudgl/leetcode-solutions
dc6570bb06b82c2c70d6f387b3486897035cc995
[ "MIT" ]
null
null
null
// Author: Abhinav Moudgil [ https://leetcode.com/amoudgl/ ] class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { int i, j, n = nums.size(), prev, max = 0, ind, maxind, ans = 0; vector<int> largestSet; if (n == 0) return largestSet; sort(nums.begin(), nums.end()); vector<pair<int, int>> dp(n, pair<int, int> (0, -1)); for (i = 0; i < n; i++) { int temp = 0; ind = -1; for (j = 0; j < i; j++) { if (nums[i] % nums[j] == 0 && dp[j].first > temp) { temp = dp[j].first; ind = j; } } dp[i].first = temp + 1; dp[i].second = ind; if (dp[i].first > ans) { ans = dp[i].first; maxind = i; } } i = maxind; while (i != -1) { largestSet.push_back(nums[i]); i = dp[i].second; } reverse(largestSet.begin(), largestSet.end()); return largestSet; } };
28.75
73
0.395652
amoudgl
809a93ee2b6e537001737479389c09c46d51dc92
3,244
cpp
C++
main/controller.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
2
2019-01-08T12:51:04.000Z
2019-01-08T12:51:04.000Z
main/controller.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
null
null
null
main/controller.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2014 Lucas Nunes de Lima * * 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 "controller.hpp" #include "http/server.hpp" #include "logger.hpp" #include "settings.hpp" #include "manager.hpp" #include "modbus/handler.hpp" #include <memory> namespace controller { namespace Controller { using http::Server; Server* http_server = nullptr; Manager* manager = nullptr; void http_thread() { try { logger.write("Iniciando servidor HTTP."); Server sv("0.0.0.0", "80", "."); http_server = &sv; sv.run(); http_server = nullptr; } catch(std::exception e) { logger.write("Erro ao executar servidor HTTP: {}.", e.what()); } catch(...) { logger.write("Erro ao executar servidor HTTP."); } } void free_thread() { do { if(http_server != nullptr) { http_server->freeConnections(); } std::this_thread::sleep_for(std::chrono::milliseconds(250)); } while(true); } void manager_thread() { Manager mn; manager = &mn; mn.run(); manager = nullptr; mn.kickDog(); logger.write("Erro ao executar programa principal."); } void modbus_thread() { using namespace modbus; try { logger.write("Iniciando servidor modbus."); Modbus sv; sv.run(); } catch (std::exception& e) { logger.write("Erro ao executar servidor Modbus: {}.", e.what()); } catch(...) { logger.write("Erro ao executar servidor Modbus."); } } void kick() { if(manager != nullptr) manager->kickDog(); } void start() { system("cpufreq-set -f 1000MHz"); std::thread t1(http_thread); std::thread t2(manager_thread); std::thread t3(modbus_thread); std::thread t4(free_thread); t1.join(); kick(); t2.join(); kick(); t3.join(); kick(); t4.join(); kick(); } } }
25.543307
80
0.460543
lucasnunes
809c004dab8f2e13b058b94afeb1ddfa6c95b8e1
1,601
cpp
C++
fw/src/util.cpp
cednik/one-wire_sniffer
bfa8e38e6310c8a20ac48eaa711be53b3454806b
[ "MIT" ]
null
null
null
fw/src/util.cpp
cednik/one-wire_sniffer
bfa8e38e6310c8a20ac48eaa711be53b3454806b
[ "MIT" ]
null
null
null
fw/src/util.cpp
cednik/one-wire_sniffer
bfa8e38e6310c8a20ac48eaa711be53b3454806b
[ "MIT" ]
null
null
null
#include "util.hpp" #include "print.hpp" #include "esp_system.h" #include "FreeRTOS.h" void checkReset() { esp_reset_reason_t resetReason = esp_reset_reason(); switch (resetReason) { case ESP_RST_UNKNOWN: print("\tUnknown reset - strange\n"); break; case ESP_RST_POWERON: print("\tPoweron reset\n"); break; case ESP_RST_EXT: print("\tExternal reset\n"); break; case ESP_RST_SW: print("\tSoftware reset\n"); break; case ESP_RST_PANIC: print("\tReset due to core panic - stop program\n"); vTaskSuspend(nullptr); break; case ESP_RST_INT_WDT: print("\tReset due to interrupt watchdog - stop program\n"); vTaskSuspend(nullptr); break; case ESP_RST_TASK_WDT: print("\tReset due to task watchdog - stop program\n"); vTaskSuspend(nullptr); break; case ESP_RST_WDT: print("\tReset due to some watchdog - stop program\n"); vTaskSuspend(nullptr); break; case ESP_RST_DEEPSLEEP: print("\tWaked from deep sleep\n"); break; case ESP_RST_BROWNOUT: print("\tBrownout reset - please check power\n"); break; case ESP_RST_SDIO: print("\tSDIO reset - strange\n"); break; } } void notifyTaskFromISR(Callback::callback_arg_t args) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; vTaskNotifyGiveFromISR( reinterpret_cast<TaskHandle_t>(args), &xHigherPriorityTaskWoken); if (xHigherPriorityTaskWoken == pdTRUE) portYIELD_FROM_ISR(); }
27.603448
93
0.632105
cednik
809df21ef9969a171e4b2592b26fb7645d008cdc
32,988
tcc
C++
libraries/math/test/tcc/Tensor_test.tcc
siddu1998/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
1
2018-11-08T06:19:31.000Z
2018-11-08T06:19:31.000Z
libraries/math/test/tcc/Tensor_test.tcc
vishnoitanuj/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
null
null
null
libraries/math/test/tcc/Tensor_test.tcc
vishnoitanuj/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
1
2019-12-19T10:02:48.000Z
2019-12-19T10:02:48.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: Tensor_test.tcc (math_test) // Authors: Ofer Dekel, Kern Handa // //////////////////////////////////////////////////////////////////////////////////////////////////// // math #include "TensorOperations.h" // utilities #include "testing.h" // stl #include <cstdlib> // rand template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorIndexer() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto S = T.GetSubTensor({ 0,1,2 }, { 2,2,2 }); T(1, 2, 3) = 7; T(0, 1, 2) = 8; auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,8,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,7 } } }; auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 8, 4 },{ 3, 4 } }, { { 3, 4 },{ 3, 7 } } }; testing::ProcessTest("Tensor::operator()", T == R1 && S == R2); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorSize() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); auto S = T.GetSubTensor({ 0,1,2 }, { 2,2,2 }); testing::ProcessTest("Tensor::Size", T.Size() == 10*20*30 && S.Size() == 2*2*2); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorNumRows() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); testing::ProcessTest("Tensor::NumRows", T.NumRows() == 10); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorNumColumns() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); testing::ProcessTest("Tensor::NumColumns", T.NumColumns() == 20); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorNumChannels() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); testing::ProcessTest("Tensor::NumChannels", T.NumChannels() == 30); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetShape() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); auto shape = T.GetShape(); testing::ProcessTest("Tensor::GetShape", shape == math::TensorShape{10,20,30}); } template<typename ElementType> void TestTensorNumSlices() { math::ColumnRowChannelTensor<ElementType> T(10, 20, 30); math::ChannelColumnRowTensor<ElementType> S(10, 20, 30); testing::ProcessTest("Tensor::NumSlices", math::NumSlices<math::Dimension::column, math::Dimension::row>(T) == 30 && math::NumSlices<math::Dimension::row, math::Dimension::column>(T) == 30 && math::NumSlices<math::Dimension::column, math::Dimension::channel>(T) == 10 && math::NumSlices<math::Dimension::channel, math::Dimension::column>(T) == 10 && math::NumSlices<math::Dimension::channel, math::Dimension::row>(S) == 20 && math::NumSlices<math::Dimension::row, math::Dimension::channel>(S) == 20 && math::NumSlices<math::Dimension::column, math::Dimension::channel>(S) == 10 && math::NumSlices<math::Dimension::channel, math::Dimension::column>(S) == 10); auto test1DNumSlices = [](auto T) { testing::ProcessTest("Tensor::NumSlices", math::NumSlices<math::Dimension::channel>(T) == (10 * 20) && math::NumSlices<math::Dimension::column>(T) == (10 * 30) && math::NumSlices<math::Dimension::row>(T) == (20 * 30)); }; test1DNumSlices(T); test1DNumSlices(S); } template<typename ElementType> void TestTensorNumPrimarySlices() { math::ColumnRowChannelTensor<ElementType> T(10, 20, 30); math::ChannelColumnRowTensor<ElementType> S(10, 20, 30); testing::ProcessTest("Tensor::NumPrimarySlices", T.NumPrimarySlices() == 30 && S.NumPrimarySlices() == 10); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorIsEqual() { auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("Tensor::IsEqual", S.IsEqual(T) && T.GetSubTensor({ 0,1,2 }, { 2,2,2 }).IsEqual(S.GetSubTensor({ 0,1,2 }, { 2,2,2 }))); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorEqualityOperator() { auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("Tensor::operator==", T == S && T.GetSubTensor({ 0,1,2 }, {2,2,2}) == S.GetSubTensor({ 0,1,2 }, { 2,2,2 })); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorInequalityOoperator() { auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,8,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto U = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("Tensor::operator!=", T != S && T.GetSubTensor({ 0,1,2 }, { 2,2,2 }) != S.GetSubTensor({ 0,1,2 }, { 2,2,2 }) && T != U); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetConstReference() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto S = T.GetSubTensor({ 0,1,2 }, { 2,2,2 }); testing::ProcessTest("Tensor::operator==", T == T.GetConstReference() && S == S.GetConstReference()); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetSubTensor() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2>(4, 6, 8); auto subT = T.GetSubTensor({ 1,2,3 }, { 2,3,4 }); subT.Fill(1); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2>(4, 6, 8); for (size_t i = 1; i < 3; ++i) { for (size_t j = 2; j < 5; ++j) { for (size_t k = 3; k < 7; ++k) { S(i, j, k) = 1; } } } testing::ProcessTest("TestGetSubTensor()", T == S); } template <typename ElementType> void TestTensorGetSlice() { math::ColumnRowChannelTensor<ElementType> T1(3, 4, 5); T1(0, 0, 0) = 1; T1(1, 2, 3) = 2; T1(0, 3, 3) = 3; T1(2, 2, 4) = 3; auto T1Test2DSlice = [](auto T) { auto M1 = math::GetSlice<math::Dimension::column, math::Dimension::row>(T, 3); testing::ProcessTest("TensorReference::GetSlice()", M1(2, 1) == 2 && M1(3, 0) == 3); auto M2 = math::GetSlice<math::Dimension::row, math::Dimension::column>(T, 3); testing::ProcessTest("TensorReference::GetSlice()", M2(1, 2) == 2 && M2(0, 3) == 3); auto M3 = math::GetSlice<math::Dimension::column, math::Dimension::channel>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M3(0, 0) == 1 && M3(3, 3) == 3); auto M4 = math::GetSlice<math::Dimension::channel, math::Dimension::column>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M4(0, 0) == 1 && M4(3, 3) == 3); }; T1Test2DSlice(T1); T1Test2DSlice(T1.GetConstReference()); math::ChannelColumnRowTensor<ElementType> T2(3, 4, 5); T2(0, 0, 0) = 1; T2(1, 2, 3) = 2; T2(0, 3, 3) = 3; T2(2, 2, 4) = 4; auto T2Test2DSlice = [](auto T) { auto M1 = math::GetSlice<math::Dimension::column, math::Dimension::channel>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M1(0, 0) == 1 && M1(3, 3) == 3); auto M2 = math::GetSlice<math::Dimension::channel, math::Dimension::column>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M2(0, 0) == 1 && M2(3, 3) == 3); auto M3 = math::GetSlice<math::Dimension::row, math::Dimension::channel>(T, 2); testing::ProcessTest("TensorReference::GetSlice()", M3(1, 3) == 2 && M3(2, 4) == 4); auto M4 = math::GetSlice<math::Dimension::channel, math::Dimension::row>(T, 2); testing::ProcessTest("TensorReference::GetSlice()", M4(3, 1) == 2 && M4(4, 2) == 4); }; T2Test2DSlice(T2); T2Test2DSlice(T2.GetConstReference()); auto vectorSliceTest = [](auto _) { using TensorType = decltype(_); // T = numpy.arange(5 * 7 * 11).reshape(5, 7, 11) TensorType T(5, 7, 11); for (unsigned i = 0; i < 5; ++i) { for (unsigned j = 0; j < 7; ++j) { for (unsigned k = 0; k < 11; ++k) { T(i, j, k) = static_cast<typename TensorType::TensorElementType>(k + j * 11 + i * 77); } } } auto test1DGetSlice = [](auto T) { // equivalent of NumPy's T[4, 6, ...] auto V1 = math::GetSlice<math::Dimension::channel>(T, 4, 6); testing::ProcessTest("TensorReference::GetSlice()", V1 == math::ColumnVector<ElementType>({ 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384 })); // equivalent of NumPy's T[4, ..., 8] auto V2 = math::GetSlice<math::Dimension::column>(T, 4, 8); testing::ProcessTest("TensorReference::GetSlice()", V2 == math::ColumnVector<ElementType>({ 316, 327, 338, 349, 360, 371, 382 })); // equivalent of NumPy's T[..., 6, 8] auto V3 = math::GetSlice<math::Dimension::row>(T, 6, 8); testing::ProcessTest("TensorReference::GetSlice()", V3 == math::ColumnVector<ElementType>({ 74, 151, 228, 305, 382 })); }; test1DGetSlice(T); test1DGetSlice(T.GetConstReference()); typename TensorType::TensorElementType originalElementVal = 0; // T[..., 6, 8][0] = 0 auto V1 = math::GetSlice<math::Dimension::channel>(T, 4, 6); std::swap(originalElementVal, V1[0]); testing::ProcessTest("TensorReference::GetSlice() after modification", V1 == math::ColumnVector<ElementType>({ 0, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384 })); testing::ProcessTest("T(4, 6, 0) == 0", T(4, 6, 0) == 0); std::swap(originalElementVal, V1[0]); // T[4..., 8][0] = 0 auto V2 = math::GetSlice<math::Dimension::column>(T, 4, 8); std::swap(originalElementVal, V2[0]); testing::ProcessTest("TensorReference::GetSlice() after modification", V2 == math::ColumnVector<ElementType>({ 0, 327, 338, 349, 360, 371, 382 })); testing::ProcessTest("T(4, 0, 8) == 0", T(4, 0, 8) == 0); std::swap(originalElementVal, V2[0]); // T[4, 6, ...][0] = 0 auto V3 = math::GetSlice<math::Dimension::row>(T, 6, 8); std::swap(originalElementVal, V3[0]); testing::ProcessTest("TensorReference::GetSlice() after modification", V3 == math::ColumnVector<ElementType>({ 0, 151, 228, 305, 382 })); testing::ProcessTest("T(0, 6, 8) == 0", T(0, 6, 8) == 0); std::swap(originalElementVal, V3[0]); }; vectorSliceTest(math::ChannelColumnRowTensor<ElementType>{}); vectorSliceTest(math::ColumnRowChannelTensor<ElementType>{}); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetPrimarySlice(){} template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorReferenceAsVector() { math::ChannelColumnRowTensor<ElementType> T(3, 4, 2); T(0, 0, 0) = 1; T(0, 0, 1) = 2; T(0, 1, 0) = 3; T(0, 1, 1) = 4; math::ColumnRowChannelTensor<ElementType> S(T); auto u = T.ReferenceAsVector(); auto v = S.ReferenceAsVector(); math::RowVector<ElementType> r1{ 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; math::RowVector<ElementType> r2{ 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; testing::ProcessTest("TensorReference::ReferenceAsVector()", u == r1 && v == r2); } template<typename ElementType> void TestTensorReferenceAsMatrix() { math::ChannelColumnRowTensor<ElementType> T(3, 4, 2); T(0, 0, 0) = 1; T(0, 0, 1) = 2; T(0, 1, 0) = 3; T(0, 1, 1) = 4; math::ColumnRowChannelTensor<ElementType> S(T); auto M = T.ReferenceAsMatrix(); auto N = S.ReferenceAsMatrix(); math::RowMatrix<ElementType> R1 { { 1, 2, 3, 4, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 } }; math::RowMatrix<ElementType> R2 { { 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; testing::ProcessTest("TensorReference::ReferenceAsMatrix", M == R1 && N == R2); } template <typename ElementType> void TestTensorReferenceAsMatrixCopy() { math::ChannelColumnRowTensor<ElementType> T(2, 4, 1); float x = 1; for (size_t i = 0; i < 2; i++) { for (size_t j = 0; j < 4; j++) { T(i, j, 0) = x++; } } math::RowMatrix<ElementType> E{ { 1, 5 }, { 2, 6 }, { 3, 7 }, { 4, 8 } }; auto r = T.GetConstReference(); auto result = math::RowMatrix<ElementType>(r.ReferenceAsMatrix().Transpose()); testing::ProcessTest("TensorReference::ReferenceAsMatrix.Transpose and copy", result.IsEqual(E)); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorCopyFrom() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; math::Tensor<ElementType, dimension0, dimension1, dimension2> S(2, 3, 4); S.CopyFrom(T); math::Tensor<ElementType, math::Dimension::column, math::Dimension::row, math::Dimension::channel> S2(2, 3, 4); S2.CopyFrom(T); auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; auto N = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 5,6 },{ 9,0 } }, { { 4,5 },{ 7,8 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).CopyFrom(N); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,5,6 },{ 9,0,9,0 } }, { { 3,4,5,6 },{ 7,8,4,5 },{ 1,2,7,8 } } }; testing::ProcessTest("TensorReference::CopyFrom", S == T && S2 == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorReset() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Reset(); math::Tensor<ElementType, dimension0, dimension1, dimension2> S(2, 3, 4); auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Reset(); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,0,0 },{ 9,0,0,0 } }, { { 3,4,5,6 },{ 7,8,0,0 },{ 1,2,0,0 } } }; testing::ProcessTest("TensorReference::Reset", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorFill() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Fill (3); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } }, { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Fill(3); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,3,3 },{ 9,0,3,3 } }, { { 3,4,5,6 },{ 7,8,3,3 },{ 1,2,3,3 } } }; testing::ProcessTest("TensorReference::Fill", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGenerate() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Generate([]()->ElementType {return 3; }); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } }, { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Generate([]()->ElementType {return 3; }); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,3,3 },{ 9,0,3,3 } }, { { 3,4,5,6 },{ 7,8,3,3 },{ 1,2,3,3 } } }; testing::ProcessTest("TensorReference::Generate", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorTransform() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Transform([](ElementType x) {return 2*x; }); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 2,4,6,8 },{ 10,12,14,16 },{ 18,0,2,4 } }, { { 6,8,10,12 },{ 14,16,18,0 },{ 2,4,6,8 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Transform([](ElementType x) {return 2 * x; }); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,14,16 },{ 9,0,2,4 } }, { { 3,4,5,6 },{ 7,8,18,0 },{ 1,2,6,8 } } }; testing::ProcessTest("TensorReference::Transform", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorPlusEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T += 2; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,4,5,6 },{ 7,8,9,10 },{ 11,2,3,4 } }, { { 5,6,7,8 },{ 9,10,11,2 },{ 3,4,5,6 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) += 2; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,9,10 },{ 9,0,3,4 } }, { { 3,4,5,6 },{ 7,8,11,2 },{ 1,2,5,6 } } }; testing::ProcessTest("TensorReference::operator+=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorMinusEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T -= -2; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,4,5,6 },{ 7,8,9,10 },{ 11,2,3,4 } }, { { 5,6,7,8 },{ 9,10,11,2 },{ 3,4,5,6 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) -= -2; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,9,10 },{ 9,0,3,4 } }, { { 3,4,5,6 },{ 7,8,11,2 },{ 1,2,5,6 } } }; testing::ProcessTest("TensorReference::operator-=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorTimesEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T *= 2; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 2,4,6,8 },{ 10,12,14,16 },{ 18,0,2,4 } }, { { 6,8,10,12 },{ 14,16,18,0 },{ 2,4,6,8 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) *= 2; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,14,16 },{ 9,0,2,4 } }, { { 3,4,5,6 },{ 7,8,18,0 },{ 1,2,6,8 } } }; testing::ProcessTest("TensorReference::operator*=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorDivideEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T /=0.5; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 2,4,6,8 },{ 10,12,14,16 },{ 18,0,2,4 } }, { { 6,8,10,12 },{ 14,16,18,0 },{ 2,4,6,8 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) /= 0.5; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,14,16 },{ 9,0,2,4 } }, { { 3,4,5,6 },{ 7,8,18,0 },{ 1,2,6,8 } } }; testing::ProcessTest("TensorReference::operator/=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2, math::ImplementationType implementation> void TestTensorVectorAddUpdate() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); auto v1 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2 }; math::AddUpdate<math::Dimension::row, implementation>(v1, T); auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 }, { 1,1,1,1 }, { 1,1,1,1 } }, { { 2,2,2,2 }, { 2,2,2,2 }, { 2,2,2,2 } } }; testing::ProcessTest("void TestTensorVectorAddUpdate()", T == R1); T.Fill(0); auto v2 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3 }; math::AddUpdate<math::Dimension::column, implementation>(v2, T); auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } }, { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } } }; testing::ProcessTest("void TestTensorVectorAddUpdate()", T == R2); T.Fill(0); auto v3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3,4 }; math::AddUpdate<math::Dimension::channel, implementation>(v3, T); auto R3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("void TestTensorVectorAddUpdate()", T == R3); // subtensors auto TT = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto TR = TT.GetSubTensor({ 5,3,1 }, {2,3,4}); TR.Fill(0); math::AddUpdate<math::Dimension::row, implementation>(v1, TR); testing::ProcessTest("void TestTensorVectorAddUpdate() with subtensor", TR == R1); TR.Fill(0); math::AddUpdate<math::Dimension::column, implementation>(v2, TR); testing::ProcessTest("void TestTensorVectorAddUpdate() with subtensor", TR == R2); TR.Fill(0); math::AddUpdate<math::Dimension::channel, implementation>(v3, TR); testing::ProcessTest("void TestTensorVectorAddUpdate() with subtensor", TR == R3); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2, math::ImplementationType implementation> void TestTensorVectorMultiply() { auto implementationName = math::Internal::MatrixOperations<implementation>::GetImplementationName(); auto T1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T1.Fill(1); auto v1 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2 }; math::ScaleUpdate<math::Dimension::row, implementation>(v1, T1); auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 },{ 1,1,1,1 },{ 1,1,1,1 } }, { { 2,2,2,2 },{ 2,2,2,2 },{ 2,2,2,2 } } }; auto T2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T2.Fill(1); auto v2 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3 }; math::ScaleUpdate<math::Dimension::column, implementation>(v2, T2); auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } }, { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } } }; auto T3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T3.Fill(1); auto v3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3,4 }; math::ScaleUpdate<math::Dimension::channel, implementation>(v3, T3); auto R3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; // subtensors auto S1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto M1 = S1.GetSubTensor({ 5,3,1 }, { 2,3,4 }); M1.Fill(1); math::ScaleUpdate<math::Dimension::row, implementation>(v1, M1); auto S2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto M2 = S2.GetSubTensor({ 5,3,1 }, { 2,3,4 }); M2.Fill(1); math::ScaleUpdate<math::Dimension::column, implementation>(v2, M2); auto S3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto M3 = S3.GetSubTensor({ 5,3,1 }, { 2,3,4 }); M3.Fill(1); math::ScaleUpdate<math::Dimension::channel, implementation>(v3, M3); testing::ProcessTest(implementationName + "::Multiply(Vector, Tensor)", T1 == R1 && T2 == R2 && T3 == R3 && M1 == R1 && M2 == R2 && M3 == R3); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2, math::ImplementationType implementation> void TestTensorVectorScaleAddUpdate() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T.Fill(1); auto s1 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2 }; auto b1 = math::Vector<ElementType, math::VectorOrientation::row>{ 3,4 }; math::ScaleAddUpdate<math::Dimension::row, implementation>(s1, b1, T); auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 4,4,4,4 },{ 4,4,4,4 },{ 4,4,4,4 } }, { { 6,6,6,6 },{ 6,6,6,6 },{ 6,6,6,6 } } }; testing::ProcessTest("void TestTensorVectorScaleAddUpdate()", T == R1); T.Fill(1); auto s2 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3 }; auto b2 = math::Vector<ElementType, math::VectorOrientation::row>{ 4,5,6 }; math::ScaleAddUpdate<math::Dimension::column, implementation>(s2, b2, T); auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 5,5,5,5 },{ 7,7,7,7 },{ 9,9,9,9 } }, { { 5,5,5,5 },{ 7,7,7,7 },{ 9,9,9,9 } } }; testing::ProcessTest("void TestTensorVectorScaleAddUpdate()", T == R2); T.Fill(1); auto s3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3,4 }; auto b3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,1,2,2 }; math::ScaleAddUpdate<math::Dimension::channel, implementation>(s3, b3, T); auto R3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 2,3,5,6 },{ 2,3,5,6 },{ 2,3,5,6 } }, { { 2,3,5,6 },{ 2,3,5,6 },{ 2,3,5,6 } } }; testing::ProcessTest("void TestTensorVectorScaleAddUpdate()", T == R3); // subtensors auto TT = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto TR = TT.GetSubTensor({ 5,3,1 }, { 2,3,4 }); TR.Fill(1); math::ScaleAddUpdate<math::Dimension::row, implementation>(s1, b1, TR); testing::ProcessTest("void TestTensorVectorScaleAddUpdate() with subtensor", TR == R1); TR.Fill(1); math::ScaleAddUpdate<math::Dimension::column, implementation>(s2, b2, TR); testing::ProcessTest("void TestTensorVectorScaleAddUpdate() with subtensor", TR == R2); TR.Fill(1); math::ScaleAddUpdate<math::Dimension::channel, implementation>(s3, b3, TR); testing::ProcessTest("void TestTensorVectoScaleAddUpdate() with subtensor", TR == R3); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorArchiver() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); T(3, 2, 1) = 2.0; T(4, 3, 2) = 3.0; T(3, 3, 3) = 4.0; utilities::SerializationContext context; std::stringstream strstream; utilities::JsonArchiver archiver(strstream); math::TensorArchiver::Write(T, "test", archiver); utilities::JsonUnarchiver unarchiver(strstream, context); math::Tensor<ElementType, dimension0, dimension1, dimension2> Ta(0, 0, 0); math::TensorArchiver::Read(Ta, "test", unarchiver); testing::ProcessTest("void TestTensorArchiver(), write and read tensor", Ta == T); }
37.743707
175
0.563084
siddu1998
80a01ec5d4887398844160006ac6f8eb80bb30ce
18,036
cpp
C++
libraries/plugins/apis/sig_by_key_api/sig_by_key_api.cpp
sityck/steem_paper
9490b7ec929282a63d342a2364d03b268e51d756
[ "MIT" ]
null
null
null
libraries/plugins/apis/sig_by_key_api/sig_by_key_api.cpp
sityck/steem_paper
9490b7ec929282a63d342a2364d03b268e51d756
[ "MIT" ]
null
null
null
libraries/plugins/apis/sig_by_key_api/sig_by_key_api.cpp
sityck/steem_paper
9490b7ec929282a63d342a2364d03b268e51d756
[ "MIT" ]
null
null
null
#include <steem/plugins/sig_by_key_api/sig_by_key_api.hpp> #include <steem/plugins/sig_by_key_api/sig_by_key_api_plugin.hpp> #include <steem/plugins/sig_by_key_api/HibeGS.hpp> #include <iostream> using namespace relicxx; using namespace forwardsec; namespace steem { namespace plugins { namespace sig_by_key { namespace detail { class sig_by_key_api_impl { public: relicResourceHandle relic; PairingGroup group; MasterPublicKey mpk; relicxx::G2 msk; //如果需要新建多个群,则需要修改代码,改为获取对应群组的私钥 //目前的需求只存在一个群组,所以无需修改 //同一个群,提交论文和审稿对应的群公私钥是同一对 GroupSecretKey gsk; UserSecretKey usk; sig_by_key_api_impl() {} ~sig_by_key_api_impl() {} set_group_return set_group(const set_group_args &args) { set_up(); groupSetup(args.groupID, msk, gsk, mpk); //返回gsk给group manager,先假设只返回给一个人 set_group_return final; //此处需保存每个group的私钥 final.a0 = g2ToStr(gsk.a0); final.a2 = g2ToStr(gsk.a2); final.a3 = g2ToStr(gsk.a3); final.a4 = g2ToStr(gsk.a4); final.a5 = g1ToStr(gsk.a5); return final; } join_group_return join_group(const join_group_args &args) { set_up(); string groupID = args.groupID; string userID = args.userID; join(groupID, userID, gsk, usk, mpk); join_group_return final; final.b0 = g2ToStr(usk.b0); final.b3 = g2ToStr(usk.b3); final.b4 = g2ToStr(usk.b4); final.b5 = g1ToStr(usk.b5); return final; } // 返回用户签名 get_sig_return get_sig(const get_sig_args &args) { set_up(); get_sig_return final; UserSecretKey usk; usk.b0 = strToG2(args.b0); usk.b3 = strToG2(args.b3); usk.b4 = strToG2(args.b4); usk.b5 = strToG1(args.b5); Signature sig; relicxx::ZR m = group.hashListToZR(args.m); sign(args.groupID, args.userID, m, usk, sig, mpk); final.c0 = g2ToStr(sig.c0); final.c5 = g1ToStr(sig.c5); final.c6 = g2ToStr(sig.c6); final.e1 = g1ToStr(sig.e1); final.e2 = g2ToStr(sig.e2); final.e3 = gtToStr(sig.e3); final.x = zrToStr(sig.x); final.y = zrToStr(sig.y); final.z = zrToStr(sig.z); return final; } open_paper_return open_paper(const open_paper_args args) { set_up(); open_paper_return final; Signature sig; sig.c0 = strToG2(args.c0); sig.c5 = strToG1(args.c5); sig.c6 = strToG2(args.c6); sig.e1 = strToG1(args.e1); sig.e2 = strToG2(args.e2); sig.e3 = strToGT(args.e3); sig.x = strToZR(args.x); sig.y = strToZR(args.y); sig.z = strToZR(args.z); final.result = open(mpk, gsk, sig, args.userID); return final; } verify_user_return verify_user(const verify_user_args args) { set_up(); verify_user_return final; Signature sig; sig.c0 = strToG2(args.c0); sig.c5 = strToG1(args.c5); sig.c6 = strToG2(args.c6); sig.e1 = strToG1(args.e1); sig.e2 = strToG2(args.e2); sig.e3 = strToGT(args.e3); sig.x = strToZR(args.x); sig.y = strToZR(args.y); sig.z = strToZR(args.z); final.result = verify(group.hashListToZR(args.m), sig, args.groupID, mpk); return final; } test_return test(const test_args &args) { test_return final; setup(mpk, msk); string groupID = "science"; const set_group_args set_args{.groupID = groupID}; set_group_return sgr = set_group(set_args); GroupSecretKey gsk2; gsk2.a0 = strToG2(sgr.a0); gsk2.a2 = strToG2(sgr.a2); gsk2.a3 = strToG2(sgr.a3); gsk2.a4 = strToG2(sgr.a4); gsk2.a5 = strToG1(sgr.a5); const join_group_args join_args{.groupID = "science", .userID = "www"}; join_group_return jgr = join_group(join_args); UserSecretKey usk2; usk2.b0 = strToG2(jgr.b0); usk2.b3 = strToG2(jgr.b3); usk2.b4 = strToG2(jgr.b4); usk2.b5 = strToG1(jgr.b5); string str = "123"; get_sig_args sig_args{.groupID = "science", .userID = "www", .m = str, .b0 = jgr.b0, .b3 = jgr.b3, .b4 = jgr.b4, .b5 = jgr.b5}; get_sig_return gsr = get_sig(sig_args); Signature sig; sig.c0 = strToG2(gsr.c0); sig.c5 = strToG1(gsr.c5); sig.c6 = strToG2(gsr.c6); sig.e1 = strToG1(gsr.e1); sig.e2 = strToG2(gsr.e2); sig.e3 = strToGT(gsr.e3); sig.x = strToZR(gsr.x); sig.y = strToZR(gsr.y); sig.z = strToZR(gsr.z); open_paper_args open_args{.userID = "www", .c0 = gsr.c0, .c5 = gsr.c5, .c6 = gsr.c6, .e1 = gsr.e1, .e2 = gsr.e2, .e3 = gsr.e3, .x = gsr.x, .y = gsr.y, .z = gsr.z}; open_paper_return opr = open_paper(open_args); verify_user_args ver_args{.groupID = "science", .m = str, .c0 = gsr.c0, .c5 = gsr.c5, .c6 = gsr.c6, .e1 = gsr.e1, .e2 = gsr.e2, .e3 = gsr.e3, .x = gsr.x, .y = gsr.y, .z = gsr.z}; if (verify_user(ver_args).result == true && opr.result == true) final.result = "true"; else final.result = "false"; /* GroupSecretKey gsk; UserSecretKey usk; Signature sig; const relicxx::ZR m = group.randomZR(); groupSetup("science", msk, gsk, mpk); join("science", "www", gsk, usk, mpk); sign(m, usk, sig, mpk); verify(m, sig, "science", mpk); if (open(mpk, gsk, sig) && verify(m, sig, "science", mpk)) final.result = "true"; else { final.result = "false"; } */ return final; } private: void setup(MasterPublicKey &mpk, relicxx::G2 &msk) const { const unsigned int l = 4; ZR alpha = group.randomZR(); mpk.g = group.randomG1(); mpk.g2 = group.randomG2(); mpk.hibeg1 = group.exp(mpk.g, alpha); //we setup four level HIBE here,the first level is Group identity,the second level is user identity //the third level is the signed message,the last level is a random identity mpk.l = 4; for (unsigned int i = 0; i <= l; i++) { ZR h = group.randomZR(); mpk.hG2.push_back(group.exp(mpk.g2, h)); } mpk.n = group.randomGT(); msk = group.exp(mpk.g2, alpha); } void groupSetup(const std::string &groupID, const G2 &msk, GroupSecretKey &gsk, const MasterPublicKey &mpk) const { const ZR e = group.hashListToZR(groupID); const ZR r1 = group.randomZR(); gsk.a0 = group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), e)), r1); gsk.a0 = group.mul(msk, gsk.a0); gsk.a2 = group.exp(mpk.hG2.at(2), r1); gsk.a3 = group.exp(mpk.hG2.at(3), r1); ; gsk.a4 = group.exp(mpk.hG2.at(4), r1); gsk.a5 = group.exp(mpk.g, r1); } void join(const string &groupID, const string &userID, const GroupSecretKey &gsk, UserSecretKey &usk, const MasterPublicKey &mpk) const { const ZR gUserID = group.hashListToZR(userID); const ZR gGroupID = group.hashListToZR(groupID); const ZR r2 = group.randomZR(); relicxx::G2 res = group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)); res = group.exp(group.mul(res, group.exp(mpk.hG2.at(2), gUserID)), r2); usk.b0 = group.mul(gsk.a0, group.exp(gsk.a2, gUserID)); usk.b0 = group.mul(usk.b0, res); usk.b3 = group.mul(gsk.a3, group.exp(mpk.hG2.at(3), r2)); usk.b4 = group.mul(gsk.a4, group.exp(mpk.hG2.at(4), r2)); usk.b5 = group.mul(gsk.a5, group.exp(mpk.g, r2)); } void sign(string groupID, string userID, const ZR &m, const UserSecretKey &usk, Signature &sig, const MasterPublicKey &mpk) { const ZR gUserID = group.hashListToZR(userID); const ZR gGroupID = group.hashListToZR(groupID); //G(UserID),G(r4),k are public const ZR r3 = group.randomZR(); //r4 use to blind identity const ZR r4 = group.randomZR(); //user to encrypt identity to the group manager const ZR k = group.randomZR(); relicxx::G2 res = group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)); res = group.mul(res, group.exp(mpk.hG2.at(2), gUserID)); res = group.mul(res, group.exp(mpk.hG2.at(3), m)); res = group.exp(group.mul(res, group.exp(mpk.hG2.at(4), r4)), r3); sig.c0 = group.mul(usk.b0, group.exp(usk.b3, m)); sig.c0 = group.mul(group.mul(sig.c0, group.exp(usk.b4, r4)), res); sig.c5 = group.mul(usk.b5, group.exp(mpk.g, r3)); sig.c6 = group.mul(group.exp(mpk.hG2.at(2), gUserID), group.exp(mpk.hG2.at(4), r4)); sig.e1 = group.exp(mpk.g, k); sig.e2 = group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)), k); sig.e3 = group.exp(group.pair(mpk.g2, mpk.hibeg1), k); sig.e3 = group.mul(sig.e3, group.exp(mpk.n, gUserID)); sig.x = gUserID; sig.y = r4; sig.z = k; } bool verify(const ZR &m, const Signature &sig, const string &groupID, const MasterPublicKey &mpk) { const ZR gGroupID = group.hashListToZR(groupID); const ZR y = sig.y; const ZR t = group.randomZR(); const GT M = group.randomGT(); const ZR k = sig.z; relicxx::G1 d1 = group.exp(mpk.g, t); relicxx::G2 d2 = group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)); d2 = group.exp(group.mul(d2, group.mul(group.exp(mpk.hG2.at(3), m), sig.c6)), t); relicxx::GT delta3 = group.mul(M, group.exp(group.pair(mpk.hibeg1, mpk.g2), t)); relicxx::GT result = group.mul(delta3, group.div(group.pair(sig.c5, d2), group.pair(d1, sig.c0))); cout << (M == result) << (sig.c6 == group.mul(group.exp(mpk.hG2.at(2), sig.x), group.exp(mpk.hG2.at(4), y))) << (sig.e1 == group.exp(mpk.g, k)) << (sig.e2 == group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)), k)) << (sig.e3 == group.mul(group.exp(mpk.n, sig.x), group.exp(group.pair(mpk.hibeg1, mpk.g2), k))); return M == result && sig.c6 == group.mul(group.exp(mpk.hG2.at(2), sig.x), group.exp(mpk.hG2.at(4), y)) && sig.e1 == group.exp(mpk.g, k) && sig.e2 == group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)), k) && sig.e3 == group.mul(group.exp(mpk.n, sig.x), group.exp(group.pair(mpk.hibeg1, mpk.g2), k)); } bool open(const MasterPublicKey &mpk, const GroupSecretKey &gsk, const Signature &sig, string userID) { const ZR gUserID = group.hashListToZR(userID); relicxx::GT t = group.exp(group.pair(mpk.hibeg1, mpk.g2), sig.z); //goes through all user identifiers here if (sig.e3 == group.mul(group.exp(mpk.n, gUserID), t)) return true; else return false; } void set_up() { mpk.l = 4; string g = "021780706f0a7afbfc7e5c2fde178c4a0fa86ff9612c233743cadc96c2e85b99eb000000000000000a00000000000000736369656e636500207e580300000000f03b9904000000000384b2c61a7f00006077e8c61a7f0000e05429c61a7f00000a000000000000004b33b2c61a7f0000207e5803000000006077e8c61a7f0000a0"; string g2 = "02675cbaedec16f50d576a451f813e28d235f8176ab3c748c3e7071197c9c300e404674f3d853347d6f91532a2ca2d27697324275c63c8ed3b8931458e21c394753b9904000000000384b2c61a7f00006077e8c61a7f0000e05429c61a7f00000a000000000000004b33b2c61a7f0000207e5803000000000fab4dc81a7f000043"; string hibeg1 = "022fcc465af6de5155ecbe906c11a221e6c4ea065c94b64f9c128c69e45127a7f65429c61a7f00000700000000000000f03b9904000000007a5c55c71a7f000067687a020000000000000000000000006077e8c61a7f0000e05429c61a7f00000100000000000000207e580300000000207e580300000000000fbb96801eca69a0"; string u0 = "038c714d1457e3630c45d809b7a9db159a7d18d4a2e981f492b017a44d75082ede4d4e0d863b3e77731c85a74acb8c187be285a03d4b1cb79b5c8b099ea3ce656bd2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000038"; string u1 = "033f62f51761b537d105b9343871fe486b582e567bc0f9ee605de4f53f88639022a4cb9b83d85504632770869911cdb388b2b1082168fec8a244f80c44cf22560bd2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f0000a0"; string u2 = "0391aaf47f42654a1c1cac4267b0e3df1985da3e0c341d8ab12d29597af64bddcd6657d290c86175522cd2da1c7652e4fbd381445332d6b5977550abf320c0fb98d2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000060"; string u3 = "035a3ed74532bda53e84441f4571088468b458c4b83cf2294e4360b85468f6f6835a69507209cfbabbc105f1b8d4fdeecf06093d11c773e3bfa16df653a93fdb10d2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000065"; string u4 = "03023afaeeb25eb44de70edee8b47f24f681592f820c4e5874837fb09f2bdfb05c3661488e917ea489240c3f2b2f4c202ab314f4ad0281cd611e90e7568d584f25d2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f0000c3"; string n = "0066f837d6aaf4d69618917009d0b3c61dc670e614a50d98788cd22400f93c6f22fc9fd14feaff20528338278548c68b71f2a60caed5c8568a61301de0c3256997d26fcf602973721435f651bc6ca3d9230ad04d0b261ae18ca2ab9ae3de01097d518908191408010a85b1ef849579f68286da897c699f394fc48cfb8c1ce3e4a32fa6404a88d40b6d6f571434d7fff3a376c16f25848e8cc3a3cd09236dead65ad8203d97d42b68e76bd2dda61e4edebd1dac6ef620af540bb5a776720633537808a32b1f57b7427849becb1ad34577f089fa78e471fc273d9c6ed9b950aaec23f2be2d40fdb004b6ab3b16c7550eaebc585921acc0acf8eefc928356bdf553801800f40c7f0000207e580300000000287e580300000000b03a990400000000c05429c61a7f0000020000000000000010040000000000007a5c55c71a7f0000d59991020000000000000000000000006077e8c61a7f0000e05429c61a7f00000100000000000000207e580300000000207e580300000000000fbb96801eca69"; string smsk = "02852d3c40a12f7b1b1d930b0324d90c7a2bd28b4eda25e0210318d2c4d9b33eacb32c094e3b48c78cfaf99272b69c5004b072e725145d1624ed35177810e022d8687a020000000000000000000000006077e8c61a7f0000e05429c61a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000083"; mpk.g = strToG1(g); mpk.g2 = strToG2(g2); mpk.hibeg1 = strToG1(hibeg1); mpk.hG2.push_back(strToG2(u0)); mpk.hG2.push_back(strToG2(u1)); mpk.hG2.push_back(strToG2(u2)); mpk.hG2.push_back(strToG2(u3)); mpk.hG2.push_back(strToG2(u4)); mpk.n = strToGT(n); msk = strToG2(smsk); //setup(mpk, msk); } relicxx::G2 getGsk() const { //此处需读取数据库返回群私钥 return group.randomG2(); } string g1ToStr(relicxx::G1 g) const { int len = 4 * FP_BYTES + 1; uint8_t bin[len]; int l; l = g1_size_bin(g.g, 1); g1_write_bin(bin, l, g.g, 1); //bin to str string str = ""; for (int i = 0; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::G1 strToG1(string str) const { relicxx::G1 g; relicxx::G1 g2 = group.randomG1(); int len = 4 * FP_BYTES + 1; int l; l = g1_size_bin(g2.g, 1); uint8_t bin[len]; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin[i / 2] = ::strtol(pair.c_str(), 0, 16); } g1_read_bin(g.g, bin, l); return g; } string g2ToStr(relicxx::G2 g) const { int len = 4 * FP_BYTES + 1; uint8_t bin[len]; int l; l = g2_size_bin(g.g, 1); g2_write_bin(bin, l, g.g, 1); //bin to str string str = ""; for (int i = 0; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::G2 strToG2(string str) const { relicxx::G2 g; relicxx::G2 g2 = group.randomG2(); int len = 4 * FP_BYTES + 1; int l; l = g2_size_bin(g2.g, 1); uint8_t bin[len]; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin[i / 2] = ::strtol(pair.c_str(), 0, 16); } g2_read_bin(g.g, bin, l); return g; } string gtToStr(relicxx::GT g) const { int len = 12 * PC_BYTES; uint8_t bin[len]; int l; l = gt_size_bin(g.g, 1); gt_write_bin(bin, l, g.g, 1); //bin to str string str = ""; for (int i = 0; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::GT strToGT(string str) const { relicxx::GT g; relicxx::GT g2 = group.randomGT(); int len = 12 * PC_BYTES; int l; l = gt_size_bin(g2.g, 1); uint8_t bin[len]; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin[i / 2] = ::strtol(pair.c_str(), 0, 16); } gt_read_bin(g.g, bin, l); return g; } string zrToStr(relicxx::ZR zr) const { int len = CEIL(RELIC_BN_BITS, 8); uint8_t bin[RELIC_BN_BITS / 8 + 1]; bn_write_bin(bin, len, zr.z); //bin to str string str = ""; for (int i = 96; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::ZR strToZR(string str) const { int len = CEIL(RELIC_BN_BITS, 8); relicxx::ZR zr; uint8_t bin2[RELIC_BN_BITS / 8 + 1]; for (int i = 0; i < 96; i++) bin2[i] = '\0'; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin2[i / 2 + 96] = ::strtol(pair.c_str(), 0, 16); } bn_read_bin(zr.z, bin2, len); return zr; } char *inttohex(int a) const { char *buffer = new char[3]; if (a / 16 < 10) buffer[0] = a / 16 + '0'; else buffer[0] = a / 16 - 10 + 'a'; if (a % 16 < 10) buffer[1] = a % 16 + '0'; else buffer[1] = a % 16 - 10 + 'a'; buffer[2] = '\0'; return buffer; } }; } // namespace detail sig_by_key_api::sig_by_key_api() : my(new detail::sig_by_key_api_impl()) { JSON_RPC_REGISTER_API(STEEM_sig_by_key_api_plugin_NAME); } sig_by_key_api::~sig_by_key_api() {} // 需要注意创建sig_by_key的时机,因W为sig_by_key的构造函数中会调用JSON RPC插件去注册API,因此 // 需要等JSON RPC先初始化好,plugin_initialize被调用时,会先注册sig_by_key_api_plugin的依赖 // 模块,因此可以确保此时JSON RPC插件此时已经注册完毕。 void sig_by_key_api_plugin::plugin_initialize(const appbase::variables_map &options) { api = std::make_shared<sig_by_key_api>(); } DEFINE_LOCKLESS_APIS(sig_by_key_api, (set_group)(join_group)(get_sig)(open_paper)(test)(verify_user)) } // namespace sig_by_key } // namespace plugins } // namespace steem
36.144289
786
0.672599
sityck
80b0f3e0ba55bd103b47a0208fe1c079d70a15d7
19,155
cpp
C++
src/corehost/cli/deps_resolver.cpp
krytarowski/cli
e4d7fa5bc4841f55662804c6999ff29e2b7075b0
[ "MIT" ]
null
null
null
src/corehost/cli/deps_resolver.cpp
krytarowski/cli
e4d7fa5bc4841f55662804c6999ff29e2b7075b0
[ "MIT" ]
null
null
null
src/corehost/cli/deps_resolver.cpp
krytarowski/cli
e4d7fa5bc4841f55662804c6999ff29e2b7075b0
[ "MIT" ]
7
2017-04-11T14:01:50.000Z
2022-03-30T21:52:56.000Z
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <set> #include <functional> #include <cassert> #include "trace.h" #include "deps_entry.h" #include "deps_format.h" #include "deps_resolver.h" #include "utils.h" #include "fx_ver.h" #include "libhost.h" namespace { // ----------------------------------------------------------------------------- // A uniqifying append helper that doesn't let two entries with the same // "asset_name" be part of the "output" paths. // void add_tpa_asset( const pal::string_t& asset_name, const pal::string_t& asset_path, std::set<pal::string_t>* items, pal::string_t* output) { if (items->count(asset_name)) { return; } trace::verbose(_X("Adding tpa entry: %s"), asset_path.c_str()); // Workaround for CoreFX not being able to resolve sym links. pal::string_t real_asset_path = asset_path; pal::realpath(&real_asset_path); output->append(real_asset_path); output->push_back(PATH_SEPARATOR); items->insert(asset_name); } // ----------------------------------------------------------------------------- // A uniqifying append helper that doesn't let two "paths" to be identical in // the "output" string. // void add_unique_path( deps_entry_t::asset_types asset_type, const pal::string_t& path, std::set<pal::string_t>* existing, pal::string_t* output) { // Resolve sym links. pal::string_t real = path; pal::realpath(&real); if (existing->count(real)) { return; } trace::verbose(_X("Adding to %s path: %s"), deps_entry_t::s_known_asset_types[asset_type], real.c_str()); output->append(real); output->push_back(PATH_SEPARATOR); existing->insert(real); } } // end of anonymous namespace // ----------------------------------------------------------------------------- // Load local assemblies by priority order of their file extensions and // unique-fied by their simple name. // void deps_resolver_t::get_dir_assemblies( const pal::string_t& dir, const pal::string_t& dir_name, dir_assemblies_t* dir_assemblies) { trace::verbose(_X("Adding files from %s dir %s"), dir_name.c_str(), dir.c_str()); // Managed extensions in priority order, pick DLL over EXE and NI over IL. const pal::string_t managed_ext[] = { _X(".ni.dll"), _X(".dll"), _X(".ni.exe"), _X(".exe") }; // List of files in the dir std::vector<pal::string_t> files; pal::readdir(dir, &files); for (const auto& ext : managed_ext) { for (const auto& file : files) { // Nothing to do if file length is smaller than expected ext. if (file.length() <= ext.length()) { continue; } auto file_name = file.substr(0, file.length() - ext.length()); auto file_ext = file.substr(file_name.length()); // Ext did not match expected ext, skip this file. if (pal::strcasecmp(file_ext.c_str(), ext.c_str())) { continue; } // Already added entry for this asset, by priority order skip this ext if (dir_assemblies->count(file_name)) { trace::verbose(_X("Skipping %s because the %s already exists in %s assemblies"), file.c_str(), dir_assemblies->find(file_name)->second.c_str(), dir_name.c_str()); continue; } // Add entry for this asset pal::string_t file_path = dir + DIR_SEPARATOR + file; trace::verbose(_X("Adding %s to %s assembly set from %s"), file_name.c_str(), dir_name.c_str(), file_path.c_str()); dir_assemblies->emplace(file_name, file_path); } } } bool deps_resolver_t::try_roll_forward(const deps_entry_t& entry, const pal::string_t& probe_dir, pal::string_t* candidate) { trace::verbose(_X("Attempting a roll forward for [%s/%s/%s] in [%s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str(), probe_dir.c_str()); const pal::string_t& lib_ver = entry.library_version; fx_ver_t cur_ver(-1, -1, -1); if (!fx_ver_t::parse(lib_ver, &cur_ver, false)) { trace::verbose(_X("No roll forward as specified version [%s] could not be parsed"), lib_ver.c_str()); return false; } // Extract glob string of the form: 1.0.* from the version 1.0.0-prerelease-00001. size_t pat_start = lib_ver.find(_X('.'), lib_ver.find(_X('.')) + 1); pal::string_t maj_min_star = lib_ver.substr(0, pat_start + 1) + _X('*'); pal::string_t path = probe_dir; append_path(&path, entry.library_name.c_str()); pal::string_t cache_key = path; append_path(&cache_key, maj_min_star.c_str()); pal::string_t max_str; if (m_roll_forward_cache.count(cache_key)) { max_str = m_roll_forward_cache[cache_key]; trace::verbose(_X("Found cached roll forward version [%s] -> [%s]"), lib_ver.c_str(), max_str.c_str()); } else { try_patch_roll_forward_in_dir(path, cur_ver, &max_str, true); m_roll_forward_cache[cache_key] = max_str; } append_path(&path, max_str.c_str()); return entry.to_rel_path(path, candidate); } void deps_resolver_t::setup_probe_config( const corehost_init_t* init, const runtime_config_t& config, const arguments_t& args) { if (pal::directory_exists(args.dotnet_extensions)) { pal::string_t ext_ni = args.dotnet_extensions; append_path(&ext_ni, get_arch()); if (pal::directory_exists(ext_ni)) { // Servicing NI probe. m_probes.push_back(probe_config_t::svc_ni(ext_ni, config.get_fx_roll_fwd())); } // Servicing normal probe. m_probes.push_back(probe_config_t::svc(args.dotnet_extensions, config.get_fx_roll_fwd())); } if (pal::directory_exists(args.dotnet_packages_cache)) { pal::string_t ni_packages_cache = args.dotnet_packages_cache; append_path(&ni_packages_cache, get_arch()); if (pal::directory_exists(ni_packages_cache)) { // Packages cache NI probe m_probes.push_back(probe_config_t::cache_ni(ni_packages_cache)); } // Packages cache probe m_probes.push_back(probe_config_t::cache(args.dotnet_packages_cache)); } if (pal::directory_exists(m_fx_dir)) { // FX probe m_probes.push_back(probe_config_t::fx(m_fx_dir, m_fx_deps.get())); } for (const auto& probe : m_additional_probes) { // Additional paths bool roll_fwd = config.get_fx_roll_fwd(); m_probes.push_back(probe_config_t::additional(probe, roll_fwd)); } if (trace::is_enabled()) { trace::verbose(_X("-- Listing probe configurations...")); for (const auto& pc : m_probes) { pc.print(); } } } void deps_resolver_t::setup_additional_probes(const std::vector<pal::string_t>& probe_paths) { m_additional_probes.assign(probe_paths.begin(), probe_paths.end()); for (auto iter = m_additional_probes.begin(); iter != m_additional_probes.end(); ) { if (pal::directory_exists(*iter)) { ++iter; } else { iter = m_additional_probes.erase(iter); } } } bool deps_resolver_t::probe_entry_in_configs(const deps_entry_t& entry, pal::string_t* candidate) { candidate->clear(); for (const auto& config : m_probes) { trace::verbose(_X(" Considering entry [%s/%s/%s] and probe dir [%s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str(), config.probe_dir.c_str()); if (config.only_serviceable_assets && !entry.is_serviceable) { trace::verbose(_X(" Skipping... not serviceable asset")); continue; } if (config.only_runtime_assets && entry.asset_type != deps_entry_t::asset_types::runtime) { trace::verbose(_X(" Skipping... not runtime asset")); continue; } pal::string_t probe_dir = config.probe_dir; if (config.match_hash) { if (entry.to_hash_matched_path(probe_dir, candidate)) { assert(!config.roll_forward); trace::verbose(_X(" Matched hash for [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... match hash failed")); } else if (config.probe_deps_json) { // If the deps json has it then someone has already done rid selection and put the right stuff in the dir. // So checking just package name and version would suffice. No need to check further for the exact asset relative path. if (config.probe_deps_json->has_package(entry.library_name, entry.library_version) && entry.to_dir_path(probe_dir, candidate)) { trace::verbose(_X(" Probed deps json and matched [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... probe in deps json failed")); } else if (!config.roll_forward) { if (entry.to_full_path(probe_dir, candidate)) { trace::verbose(_X(" Specified no roll forward; matched [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... not found in probe dir")); } else if (config.roll_forward) { if (try_roll_forward(entry, probe_dir, candidate)) { trace::verbose(_X(" Specified roll forward; matched [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... could not roll forward and match in probe dir")); } // continue to try next probe config } return false; } // ----------------------------------------------------------------------------- // Resolve coreclr directory from the deps file. // // Description: // Look for CoreCLR from the dependency list in the package cache and then // the packages directory. // pal::string_t deps_resolver_t::resolve_coreclr_dir() { auto process_coreclr = [&] (bool is_portable, const pal::string_t& deps_dir, deps_json_t* deps) -> pal::string_t { pal::string_t candidate; if (deps->has_coreclr_entry()) { const deps_entry_t& entry = deps->get_coreclr_entry(); if (probe_entry_in_configs(entry, &candidate)) { return get_directory(candidate); } else if (entry.is_rid_specific && entry.to_rel_path(deps_dir, &candidate)) { return get_directory(candidate); } } else { trace::verbose(_X("Deps has no coreclr entry.")); } // App/FX main dir or standalone app dir. trace::verbose(_X("Probing for CoreCLR in deps directory=[%s]"), deps_dir.c_str()); if (coreclr_exists_in_dir(deps_dir)) { return deps_dir; } return pal::string_t(); }; trace::info(_X("-- Starting CoreCLR Probe from app deps.json")); pal::string_t clr_dir = process_coreclr(m_portable, m_app_dir, m_deps.get()); if (clr_dir.empty() && m_portable) { trace::info(_X("-- Starting CoreCLR Probe from FX deps.json")); clr_dir = process_coreclr(false, m_fx_dir, m_fx_deps.get()); } if (!clr_dir.empty()) { return clr_dir; } // Use platform-specific search algorithm pal::string_t install_dir; if (pal::find_coreclr(&install_dir)) { return install_dir; } return pal::string_t(); } void deps_resolver_t::resolve_tpa_list( const pal::string_t& clr_dir, pal::string_t* output) { const std::vector<deps_entry_t> empty(0); // Obtain the local assemblies in the app dir. get_dir_assemblies(m_app_dir, _X("local"), &m_local_assemblies); if (m_portable) { // For portable also obtain FX dir assemblies. get_dir_assemblies(m_fx_dir, _X("fx"), &m_fx_assemblies); } std::set<pal::string_t> items; auto process_entry = [&](const pal::string_t& deps_dir, deps_json_t* deps, const dir_assemblies_t& dir_assemblies, const deps_entry_t& entry) { if (items.count(entry.asset_name)) { return; } pal::string_t candidate; trace::info(_X("Processing TPA for deps entry [%s, %s, %s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str()); // Try to probe from the shared locations. if (probe_entry_in_configs(entry, &candidate)) { add_tpa_asset(entry.asset_name, candidate, &items, output); } // The rid asset should be picked up from app relative subpath. else if (entry.is_rid_specific && entry.to_rel_path(deps_dir, &candidate)) { add_tpa_asset(entry.asset_name, candidate, &items, output); } // The rid-less asset should be picked up from the app base. else if (dir_assemblies.count(entry.asset_name)) { add_tpa_asset(entry.asset_name, dir_assemblies.find(entry.asset_name)->second, &items, output); } else { // FIXME: Consider this error as a fail fast? trace::verbose(_X("Error: Could not resolve path to assembly: [%s, %s, %s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str()); } }; const auto& deps_entries = m_deps->get_entries(deps_entry_t::asset_types::runtime); std::for_each(deps_entries.begin(), deps_entries.end(), [&](const deps_entry_t& entry) { process_entry(m_app_dir, m_deps.get(), m_local_assemblies, entry); }); // Finally, if the deps file wasn't present or has missing entries, then // add the app local assemblies to the TPA. for (const auto& kv : m_local_assemblies) { add_tpa_asset(kv.first, kv.second, &items, output); } const auto& fx_entries = m_portable ? m_fx_deps->get_entries(deps_entry_t::asset_types::runtime) : empty; std::for_each(fx_entries.begin(), fx_entries.end(), [&](const deps_entry_t& entry) { process_entry(m_fx_dir, m_fx_deps.get(), m_fx_assemblies, entry); }); for (const auto& kv : m_fx_assemblies) { add_tpa_asset(kv.first, kv.second, &items, output); } } // ----------------------------------------------------------------------------- // Resolve the directories order for resources/native lookup // // Description: // This general purpose function specifies priority order of directory lookup // for both native images and resources specific resource images. Lookup for // resources assemblies is done by looking up two levels above from the file // path. Lookup for native images is done by looking up one level from the // file path. // // Parameters: // asset_type - The type of the asset that needs lookup, currently // supports "resources" and "native" // app_dir - The application local directory // package_dir - The directory path to where packages are restored // package_cache_dir - The directory path to secondary cache for packages // clr_dir - The directory where the host loads the CLR // // Returns: // output - Pointer to a string that will hold the resolved lookup dirs // void deps_resolver_t::resolve_probe_dirs( deps_entry_t::asset_types asset_type, const pal::string_t& clr_dir, pal::string_t* output) { bool is_resources = asset_type == deps_entry_t::asset_types::resources; assert(is_resources || asset_type == deps_entry_t::asset_types::native); // For resources assemblies, we need to provide the base directory of the resources path. // For example: .../Foo/en-US/Bar.dll, then, the resolved path is .../Foo std::function<pal::string_t(const pal::string_t&)> resources = [] (const pal::string_t& str) { return get_directory(get_directory(str)); }; // For native assemblies, obtain the directory path from the file path std::function<pal::string_t(const pal::string_t&)> native = [] (const pal::string_t& str) { return get_directory(str); }; std::function<pal::string_t(const pal::string_t&)>& action = is_resources ? resources : native; std::set<pal::string_t> items; std::vector<deps_entry_t> empty(0); const auto& entries = m_deps->get_entries(asset_type); const auto& fx_entries = m_portable ? m_fx_deps->get_entries(asset_type) : empty; pal::string_t candidate; auto add_package_cache_entry = [&](const deps_entry_t& entry) { if (probe_entry_in_configs(entry, &candidate)) { add_unique_path(asset_type, action(candidate), &items, output); } }; std::for_each(entries.begin(), entries.end(), add_package_cache_entry); std::for_each(fx_entries.begin(), fx_entries.end(), add_package_cache_entry); // For portable rid specific assets, the app relative directory must be used. if (m_portable) { std::for_each(entries.begin(), entries.end(), [&](const deps_entry_t& entry) { if (entry.is_rid_specific && entry.asset_type == asset_type && entry.to_rel_path(m_app_dir, &candidate)) { add_unique_path(asset_type, action(candidate), &items, output); } }); } // App local path add_unique_path(asset_type, m_app_dir, &items, output); // FX path if present if (!m_fx_dir.empty()) { add_unique_path(asset_type, m_fx_dir, &items, output); } // CLR path add_unique_path(asset_type, clr_dir, &items, output); } // ----------------------------------------------------------------------------- // Entrypoint to resolve TPA, native and resources path ordering to pass to CoreCLR. // // Parameters: // app_dir - The application local directory // package_dir - The directory path to where packages are restored // package_cache_dir - The directory path to secondary cache for packages // clr_dir - The directory where the host loads the CLR // probe_paths - Pointer to struct containing fields that will contain // resolved path ordering. // // bool deps_resolver_t::resolve_probe_paths(const pal::string_t& clr_dir, probe_paths_t* probe_paths) { resolve_tpa_list(clr_dir, &probe_paths->tpa); resolve_probe_dirs(deps_entry_t::asset_types::native, clr_dir, &probe_paths->native); resolve_probe_dirs(deps_entry_t::asset_types::resources, clr_dir, &probe_paths->resources); return true; }
35.472222
194
0.612895
krytarowski
80b2d3a6805b8fade32a858d5ffeec00f33b0fac
869
cpp
C++
Engine/Flora/Application/Window.cpp
chgalante/flora
17db42ce92925c5e9e5e3a9084747553a27cfa96
[ "MIT" ]
1
2021-07-09T03:32:51.000Z
2021-07-09T03:32:51.000Z
Engine/Flora/Application/Window.cpp
chgalante/flora
17db42ce92925c5e9e5e3a9084747553a27cfa96
[ "MIT" ]
1
2021-08-21T19:13:15.000Z
2021-08-21T19:13:15.000Z
Engine/Flora/Application/Window.cpp
chgalante/flora
17db42ce92925c5e9e5e3a9084747553a27cfa96
[ "MIT" ]
null
null
null
#include "Window.hpp" #include "Flora/Base.hpp" #include "Flora/Utilities/Log.hpp" namespace FloraEngine { Window::Window() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwInit(); pWindow = glfwCreateWindow(1280, 720, "FloraEngine", NULL, NULL); if (!pWindow) { FE_CORE_CRITICAL("GLFW failed to create window"); } glfwMakeContextCurrent(pWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { FE_CORE_CRITICAL("Failed to initialize OpenGL Context!"); } glViewport(0, 0, 640, 480); } bool Window::OnUpdate() { glfwPollEvents(); glfwSwapBuffers(pWindow); /* Returns false if the window should close to signal app termination */ return !glfwWindowShouldClose(pWindow); } } // namespace FloraEngine
24.828571
74
0.742232
chgalante
80b8280507d0875ee79783a046e73a5fcc256e4d
9,436
cpp
C++
Source/AllProjects/CQCDrvDev/CQCDrvDev_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCDrvDev/CQCDrvDev_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCDrvDev/CQCDrvDev_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCDrvDev_ThisFacility.cpp // // AUTHOR: Dean Roddey // // CREATED: 02/14/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CQCDrvDev.hpp" // --------------------------------------------------------------------------- // Do our RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TFacCQCDrvDev,TGUIFacility) // --------------------------------------------------------------------------- // CLASS: TFacCQCDrvDev // PREFIX: fac // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TFacCQCDrvDev: Constructors and operators // --------------------------------------------------------------------------- TFacCQCDrvDev::TFacCQCDrvDev() : TGUIFacility ( L"CQCDrvDev" , tCIDLib::EModTypes::Exe , kCIDLib::c4MajVersion , kCIDLib::c4MinVersion , kCIDLib::c4Revision , tCIDLib::EModFlags::HasMsgsAndRes ) { m_strTitleText = strMsg(kDrvDevMsgs::midMsg_Title); } TFacCQCDrvDev::~TFacCQCDrvDev() { } // --------------------------------------------------------------------------- // TFacCQCDrvDev: Public, non-virtual methods // --------------------------------------------------------------------------- const TCQCUserCtx& TFacCQCDrvDev::cuctxToUse() const { return m_cuctxToUse; } tCIDLib::EExitCodes TFacCQCDrvDev::eMainThread(TThread& thrThis, tCIDLib::TVoid*) { // Let our caller go thrThis.Sync(); // // Ask CQCKit to load core environment/parm stuff. If we can't do this, // then we are doomed and just have to exit. // TString strFailReason; if (!facCQCKit().bLoadEnvInfo(strFailReason, kCIDLib::True)) { TErrBox msgbTest(m_strTitleText, strMsg(kDrvDevMsgs::midStatus_BadEnv, strFailReason)); msgbTest.ShowIt(TWindow::wndDesktop()); return tCIDLib::EExitCodes::BadEnvironment; } TLogSrvLogger* plgrLogSrv = nullptr; try { // // First thing of all, check to see if there is already an instance // running. If so, activate it and just exit. // TResourceName rsnInstance(L"CQSL", L"CQCDrvDev", L"SingleInstanceInfo"); if (TProcess::bSetSingleInstanceInfo(rsnInstance, kCIDLib::True)) return tCIDLib::EExitCodes::Normal; // // Now we can initialize the client side ORB, which we have to // do, despite being mostly standalone, because of the need to // read/write macros from the data server. // facCIDOrb().InitClient(); // // The next thing we want to do is to install a log server logger. We // just use the standard one that's provided by CIDLib. It logs to // the standard CIDLib log server, and uses a local file for fallback // if it cannot connect. // plgrLogSrv = new TLogSrvLogger(facCQCKit().strLocalLogDir()); TModule::InstallLogger(plgrLogSrv, tCIDLib::EAdoptOpts::Adopt); // Parse the command line parms tCIDLib::TBoolean bNoState = kCIDLib::False; if (!bParseParms(bNoState)) return tCIDLib::EExitCodes::BadParameters; // Do a version check against the master server and exit if not valid if (!facCQCIGKit().bCheckCQCVersion(TWindow::wndDesktop(), m_strTitleText)) return tCIDLib::EExitCodes::InitFailed; // We have to log on before we can do anything. If that works if (!bDoLogon()) return tCIDLib::EExitCodes::Normal; // Initialize the local config store facCQCGKit().InitObjectStore ( kCQCDrvDev::strStoreKey, m_cuctxToUse.strUserName(), bNoState ); // // We have to install some class loaders on the macro engine // facility, so that the standard CQC runtime classes and driver // classes are available. // facCQCMEng().InitCMLRuntime(m_cuctxToUse.sectUser()); facCQCMedia().InitCMLRuntime(); facCQCGenDrvS().InitCMLRuntime(); // // Enable the sending out of events, so that any user action events // the driver might send out can be tested. // facCQCKit().StartEventProcessing(tCQCKit::EEvProcTypes::Send, m_cuctxToUse.sectUser()); // // Register any local serial port factories we want to make available. // facGC100Ser().bUpdateFactory(m_cuctxToUse.sectUser()); facJAPwrSer().bUpdateFactory(m_cuctxToUse.sectUser()); // // Load any previous config we might have had (assuming it wasn't // tossed via the 'no state' command line parm above. // TCQCFrameState fstMain; facCQCGKit().bReadFrameState(kCQCDrvDev::strCfgKey_Frame, fstMain, TSize(640, 480)); m_wndMainFrame.Create(fstMain); } catch(const TError& errToCatch) { TExceptDlg dlgErr ( TWindow::wndDesktop() , m_strTitleText , strMsg(kDrvDevMsgs::midMsg_Exception) , errToCatch ); return tCIDLib::EExitCodes::InitFailed; } catch(...) { TErrBox msgbErr(m_strTitleText, strMsg(kDrvDevMsgs::midMsg_UnknownExcept)); msgbErr.ShowIt(TWindow::wndDesktop()); return tCIDLib::EExitCodes::InitFailed; } // // Call the window processing loop. We won't come back until the // program exits. No exceptions will come out of here, so we don't // have to protect it. We use the MDI enabled loop here. // facCIDCtrls().uMainMsgLoop(m_wndMainFrame); try { m_wndMainFrame.Destroy(); } catch(TError& errToCatch) { if (bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); LogEventObj(errToCatch); } } // Terminate the local config store try { facCQCGKit().TermObjectStore(); } catch(TError& errToCatch) { if (bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); LogEventObj(errToCatch); } } // Force the log server logger to local logging, and terminate the orb try { if (plgrLogSrv) plgrLogSrv->bForceLocal(kCIDLib::True); facCIDOrb().Terminate(); } catch(TError& errToCatch) { if (bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); LogEventObj(errToCatch); } } // And finally make the logger stop logging try { if (plgrLogSrv) plgrLogSrv->Cleanup(); } catch(...) { } try { // Turn event processing back off facCQCKit().StopEventProcessing(); } catch(...) { } return tCIDLib::EExitCodes::Normal; } // --------------------------------------------------------------------------- // TFacCQCDrvDev: Private, non-virtual methods // --------------------------------------------------------------------------- // // This method runs the standard CQC logon dialog. If it succeeds, we get // back the security token for the user, which we set on CQCKit for subsequent // use by the app. // tCIDLib::TBoolean TFacCQCDrvDev::bDoLogon() { // // We'll get a temp security token, which we'll store on the CQCKit // facility if we succeed, and it'll fill in a user account object of // ours, which we'll use for a few things. The last parameter allows // environmentally based logon. // TCQCUserAccount uaccLogin; TCQCSecToken sectTmp; if (facCQCGKit().bLogon(TWindow::wndDesktop() , sectTmp , uaccLogin , tCQCKit::EUserRoles::SystemAdmin , m_strTitleText , kCIDLib::False , L"DriverIDE")) { // // Ok, they can log on, so let's set up our user context for // later user. // m_cuctxToUse.Set(uaccLogin, sectTmp); m_cuctxToUse.LoadEnvRTVsFromHost(); return kCIDLib::True; } return kCIDLib::False; } tCIDLib::TBoolean TFacCQCDrvDev::bParseParms(tCIDLib::TBoolean& bIgnoreState) { // // Most of our parms are handled by CQCKit, but we support a /NoState flag, to ignore // the saved state and start with default window positions. Assume not to ignore unless // told to. // bIgnoreState = kCIDLib::False; TSysInfo::TCmdLineCursor cursParms = TSysInfo::cursCmdLineParms(); for (; cursParms; ++cursParms) { if (cursParms->bCompareI(L"/NoState")) bIgnoreState = kCIDLib::True; } return kCIDLib::True; }
29.033846
95
0.54769
MarkStega
01eafe7fbc1f18a52ae6170123916fadc06473b2
1,983
cpp
C++
src/shaders/shader_loader.cpp
sardok/minecraft-challenge
709fe9ca887cf492fd48d49f84af0029fa996781
[ "MIT" ]
null
null
null
src/shaders/shader_loader.cpp
sardok/minecraft-challenge
709fe9ca887cf492fd48d49f84af0029fa996781
[ "MIT" ]
null
null
null
src/shaders/shader_loader.cpp
sardok/minecraft-challenge
709fe9ca887cf492fd48d49f84af0029fa996781
[ "MIT" ]
null
null
null
#include <stdexcept> #include <iostream> #include <shaders/shader_loader.hpp> #include <utils/file_utils.hpp> namespace { GLuint compile_shader(const GLchar *source, GLenum shader_type) { auto shader_id = glCreateShader(shader_type); glShaderSource(shader_id, 1, &source, nullptr); glCompileShader(shader_id); GLint success = 0; GLchar info_log[512]; glGetShaderiv(shader_id, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader_id, 512, nullptr, info_log); throw std::runtime_error("Unable to load a shader: " + std::string(info_log)); } return shader_id; } GLuint link_program(GLuint vertex_shader_id, GLuint fragment_shader_id) { auto id = glCreateProgram(); glAttachShader(id, vertex_shader_id); glAttachShader(id, fragment_shader_id); glLinkProgram(id); return id; } void check_link_success(GLuint shader_id) { GLint success = 0; GLchar info_log[512]; glGetProgramiv(shader_id, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader_id, 512, nullptr, info_log); throw std::runtime_error("Failed shader linking: " + std::string(info_log)); } } } // namespace GLuint load_shaders( const std::string &vertex_shader, const std::string &fragment_shader) { auto vertex_source = get_file_contents("shaders/" + vertex_shader + ".glsl"); auto fragment_source = get_file_contents("shaders/" + fragment_shader + ".glsl"); auto vertex_shader_id = compile_shader(vertex_source.c_str(), GL_VERTEX_SHADER); auto fragment_shader_id = compile_shader(fragment_source.c_str(), GL_FRAGMENT_SHADER); auto shader_id = link_program(vertex_shader_id, fragment_shader_id); check_link_success(shader_id); glDetachShader(shader_id, vertex_shader_id); glDetachShader(shader_id, fragment_shader_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); return shader_id; }
27.164384
90
0.723651
sardok
01f18891798599673655af558f6b7d1308d60d8d
701
cpp
C++
Problems/Timus/2056_Scholarship/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
Problems/Timus/2056_Scholarship/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
1
2019-05-09T19:17:00.000Z
2019-05-09T19:17:00.000Z
Problems/Timus/2056_Scholarship/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); // freopen("output.txt", "wt", stdout); #endif int marks; cin >> marks; bool has3 = false; bool only5 = true; float total = 0; for (int i = 0; i < marks; ++i) { int m; cin >> m; total += m; if (m != 5) { only5 = false; if (m == 3) has3 = true; } } if (only5) cout << "Named"; else if (!has3) { if(total / marks >= 4.5f) cout << "High"; else cout << "Common"; } else cout << "None"; }
16.302326
41
0.415121
grand87
01f2ce88c0667647af9032d4fc99a3b7a10f8a78
1,352
cpp
C++
Lab_3/DllStringReplacement/StringReplacer.cpp
BSUIR-SFIT-Labs/OSaSP-Labs-Windows
d32278525e1301ae61debb3d185495cf6130cdb6
[ "MIT" ]
4
2020-09-06T14:56:03.000Z
2022-03-11T10:42:06.000Z
Lab_3/DllStringReplacement/StringReplacer.cpp
BSUIR-SFIT-Labs/OSaSP-Labs-Windows
d32278525e1301ae61debb3d185495cf6130cdb6
[ "MIT" ]
null
null
null
Lab_3/DllStringReplacement/StringReplacer.cpp
BSUIR-SFIT-Labs/OSaSP-Labs-Windows
d32278525e1301ae61debb3d185495cf6130cdb6
[ "MIT" ]
null
null
null
#include <Windows.h> #include <vector> extern "C" void __declspec(dllexport) __stdcall ReplaceString( DWORD pid, const char* srcString, const char* resString) { HANDLE hProcess = OpenProcess( PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, pid); if (hProcess) { SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); MEMORY_BASIC_INFORMATION memoryInfo; std::vector<char> chunk; char* p = 0; while (p < systemInfo.lpMaximumApplicationAddress) { if (VirtualQueryEx(hProcess, p, &memoryInfo, sizeof(memoryInfo)) == sizeof(memoryInfo)) { if (memoryInfo.State == MEM_COMMIT && memoryInfo.AllocationProtect == PAGE_READWRITE) { p = (char*)memoryInfo.BaseAddress; chunk.resize(memoryInfo.RegionSize); SIZE_T bytesRead; try { if (ReadProcessMemory(hProcess, p, &chunk[0], memoryInfo.RegionSize, &bytesRead)) { for (size_t i = 0; i < (bytesRead - strlen(srcString)); ++i) { if (memcmp(srcString, &chunk[i], strlen(srcString)) == 0) { char* ref = (char*)p + i; for (int j = 0; j < strlen(resString); j++) ref[j] = resString[j]; ref[strlen(resString)] = 0; } } } } catch (std::bad_alloc& e) { } } p += memoryInfo.RegionSize; } } } }
21.806452
90
0.611686
BSUIR-SFIT-Labs
01f456ad347704771c52dc7f8d669f1b52702892
534
cpp
C++
Cpp/1657.determine-if-two-strings-are-close.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/1657.determine-if-two-strings-are-close.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/1657.determine-if-two-strings-are-close.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: bool closeStrings(string word1, string word2) { int mask1 = 0, mask2 = 0; for (char &c : word1) mask1 |= (1 << (c - 'a')); for (char &c : word2) mask2 |= (1 << (c - 'a')); if (mask1 != mask2) return false; vector<int> cnt1(26), cnt2(26); for (char &c : word1) cnt1[c-'a'] ++; for (char &c : word2) cnt2[c-'a'] ++; sort(cnt1.begin(), cnt1.end()); sort(cnt2.begin(), cnt2.end()); return cnt1 == cnt2; } };
31.411765
56
0.468165
zszyellow
bf058fcac6e12ef075732a6a8ae062e58600d10a
813
cpp
C++
Graphs/Floyd Warshall Algo.cpp
ans-coder-human/Java
f82a380d4f02a084f1ddf4b03d7317254dca39b8
[ "MIT" ]
null
null
null
Graphs/Floyd Warshall Algo.cpp
ans-coder-human/Java
f82a380d4f02a084f1ddf4b03d7317254dca39b8
[ "MIT" ]
10
2021-10-04T08:04:42.000Z
2021-10-13T08:27:56.000Z
Graphs/Floyd Warshall Algo.cpp
ans-coder-human/Java
f82a380d4f02a084f1ddf4b03d7317254dca39b8
[ "MIT" ]
5
2020-10-14T10:38:08.000Z
2021-10-30T11:08:40.000Z
void shortest_distance(vector<vector<int>>&matrix){ int n = matrix.size(); for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { if(matrix[i][j]==-1) matrix[i][j]=INT_MAX/2; } } for(int k=0;k<n;k++) { for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { matrix[i][j]=min(matrix[i][j],matrix[i][k]+matrix[k][j]); } } } for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { if(matrix[i][j]==INT_MAX/2) matrix[i][j]=-1; } } } //to detect negative cycle for(int i=0;i<n;i++){ if(matrix[i][i]<0){ cout<<"\n Its a negative weight cycle"; }
20.846154
72
0.360394
ans-coder-human
bf0709420a565f5212755dec90126cf26c00b536
17,928
cpp
C++
sourceCode/application/logic/model/core/InputFilesCheckerForComputation.cpp
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
2
2022-02-27T20:08:04.000Z
2022-03-03T13:45:40.000Z
sourceCode/application/logic/model/core/InputFilesCheckerForComputation.cpp
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
1
2021-06-07T17:09:04.000Z
2021-06-11T11:48:23.000Z
sourceCode/application/logic/model/core/InputFilesCheckerForComputation.cpp
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
1
2021-06-03T21:06:55.000Z
2021-06-03T21:06:55.000Z
#include <OpenImageIO/imageio.h> using namespace OIIO; #include <QDebug> #include "InputFilesCheckerForComputation.h" #include "../../io/InputImageFormatChecker.h" #include "../../toolbox/toolbox_pathAndFile.h" InputFilesForComputationMatchWithRequierement::InputFilesForComputationMatchWithRequierement( const S_InputFiles& inputFiles, e_mainComputationMode e_mainComputationMode, U_CorrelationScoreMapFileUseFlags correlationScoreUsageFlags): _inputFiles(inputFiles), _e_mainComputationMode(e_mainComputationMode), _correlationScoreUsageFlags(correlationScoreUsageFlags), _qvect_eSFC_PX1_PX2_DeltaZ{e_sFC_notSet, e_sFC_notSet, e_sFC_notSet}, _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ {e_sFC_notSet, e_sFC_notSet, e_sFC_notSet} { qDebug() << __FUNCTION__<< "inputFiles:"; qDebug() << __FUNCTION__<< inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__<< inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__<< "_inputFiles:"; qDebug() << __FUNCTION__<< _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__<< _inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ; } bool InputFilesForComputationMatchWithRequierement::getLayerToUseForComputationFlag(e_LayersAcces eLA) { qDebug() << __FUNCTION__<< "_eSFC_PX1_PX2_DeltaZ[" << eLA << "] =" << _qvect_eSFC_PX1_PX2_DeltaZ[eLA]; return(_qvect_eSFC_PX1_PX2_DeltaZ[eLA] == e_sFC_OK); } int InputFilesForComputationMatchWithRequierement::getQVectorLayersForComputationFlag(QVector<bool> &qvectb_LayersForComputationFlag) { qvectb_LayersForComputationFlag.clear(); qvectb_LayersForComputationFlag.fill(false, eLA_LayersCount); int count_sFC_OK = 0; for (int iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { if (_qvect_eSFC_PX1_PX2_DeltaZ[iela] == e_sFC_OK) { qvectb_LayersForComputationFlag[iela] = true; count_sFC_OK++; } } return(count_sFC_OK); } int InputFilesForComputationMatchWithRequierement::getQVectorCorrelationScoreMapFilesAvailabilityFlag(QVector<bool> &qvectb_correlationScoreMapFilesAvailability) { qvectb_correlationScoreMapFilesAvailability.clear(); qvectb_correlationScoreMapFilesAvailability.fill(false, eLA_LayersCount); //e_mCM_Typical_PX1PX2Together_DeltazAlone: optionnal but together: (PX1, PX2), optionnal and alone: DeltaZ if (_e_mainComputationMode != e_mCM_Typical_PX1PX2Together_DeltazAlone) { //strMsgErrorDetails = "Dev error 901# mainComputationMode not supported"; return(false); } int count_OK = 0; qvectb_correlationScoreMapFilesAvailability[eLA_CorrelScoreForPX1PX2Together] = (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] == e_sFC_OK); qvectb_correlationScoreMapFilesAvailability[eLA_CorrelScoreForDeltaZAlone] = (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] == e_sFC_OK); return(qvectb_correlationScoreMapFilesAvailability.count(true)); } //routeset file check for importation is not considered in this method bool InputFilesForComputationMatchWithRequierement::check_PX1PX2Together_DeltazAlone(QString& strMsgErrorDetails) { strMsgErrorDetails.clear(); QString _tqstrDescName_image[3] {"PX1", "PX2", "DeltaZ or Other"}; QString _tqstrDescName_correlScoreMap[3] {"(PX1,PX2)", "(PX1,PX2)", "DeltaZ or Other"}; _qvect_eSFC_PX1_PX2_DeltaZ = {e_sFC_notSet, e_sFC_notSet, e_sFC_notSet}; _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = {e_sFC_notSet, e_sFC_notSet, e_sFC_notSet}; //input files (PX1, PX2, deltaZ): //e_mCM_Typical_PX1PX2Together_DeltazAlone: optionnal but together: (PX1, PX2), optionnal and alone: DeltaZ if (_e_mainComputationMode != e_mCM_Typical_PX1PX2Together_DeltazAlone) { strMsgErrorDetails = "Dev error #9 mainComputationMode not supported"; return(false); } qDebug() << __FUNCTION__ << __LINE__ << "_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ = " << _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ; //test if (PX1, PX2) needs to be computed bool bPX1PX2_empty = false; e_statusFileCheck esFC_PX1PX2 = e_sFC_notSet; bool bPX1_empty = _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX1].isEmpty(); bool bPX2_empty = _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX2].isEmpty(); if (bPX1_empty && bPX2_empty) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX1] = e_sFC_notRequiered; _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX2] = e_sFC_notRequiered; esFC_PX1PX2 = e_sFC_notRequiered; bPX1PX2_empty = true; } else { if (bPX1_empty) { strMsgErrorDetails = "Missing mandatory input file for " + _tqstrDescName_image[eLA_PX1];//'Missing mandatory non independent input file' qDebug() << __FUNCTION__<< strMsgErrorDetails; return(false); } if (bPX2_empty) { strMsgErrorDetails = "Missing mandatory input file for " + _tqstrDescName_image[eLA_PX2]; //'Missing mandatory non independent input file' qDebug() << __FUNCTION__<< strMsgErrorDetails; return(false); } _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX1] = e_sFC_checkInProgress; _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX2] = e_sFC_checkInProgress; esFC_PX1PX2 = e_sFC_checkInProgress; } //test if deltaZOther needs to be computed bool bdeltaZ_empty = _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_deltaZ].isEmpty(); if (bdeltaZ_empty) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] = e_sFC_notRequiered; } else { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] = e_sFC_checkInProgress; } if (bPX1PX2_empty && bdeltaZ_empty) { strMsgErrorDetails = "None input image file"; return(false); } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that input correlation score files are set if usage at true //PX1PX2 if (!_correlationScoreUsageFlags._sCSF_PX1PX2Together_DeltazAlone._b_onPX1PX2) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = e_sFC_notRequiered; } else { bool bNoError = !_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together].isEmpty(); if (!bNoError) { strMsgErrorDetails = "Missing correlation score map input file for Px1,Px2"; return(false); } _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = e_sFC_checkInProgress; } //DeltaZ if (!_correlationScoreUsageFlags._sCSF_PX1PX2Together_DeltazAlone._b_onDeltaZ) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = e_sFC_notRequiered; } else { bool bNoError = !_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone].isEmpty(); if (!bNoError) { strMsgErrorDetails = "Missing correlation score map input file for deltaZ"; return(false); } _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = e_sFC_checkInProgress; } if (esFC_PX1PX2 == e_sFC_checkInProgress) { //check that input files PX1 and PX2 are different when e_mCM_Typical_PX1PX2Together_DeltazAlone if (!_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX1].compare( _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX2], Qt::CaseInsensitive)) { strMsgErrorDetails = "Input files for Px1 and Px2 have to be different"; //'Mandatory non independant input files have to be different' return(false); } } //check that files exists: PX1, PX2, DeltaZ for (uint iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { if (_qvect_eSFC_PX1_PX2_DeltaZ[iela] == e_sFC_checkInProgress) { if (!fileExists(_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[iela])) { _qvect_eSFC_PX1_PX2_DeltaZ[iela] = e_sFC_NotOK; strMsgErrorDetails = "Input file does not exist for " + _tqstrDescName_image[iela]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; QVector<uint> qvect_iela_forCorrelScoreMap = {eLA_CorrelScoreForPX1PX2Together, eLA_CorrelScoreForDeltaZAlone }; //check that files exists: correlation score map for (PX1,PX2) for (auto iter_iela_forCorScoMap : qvect_iela_forCorrelScoreMap) { if (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] == e_sFC_checkInProgress) { if (!fileExists(_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[iter_iela_forCorScoMap])) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; strMsgErrorDetails = "(correlation score map) input file does not exist for " + _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that PX1 and PX2 files format are valid for DisplacementMap file //added deltaZ here InputImageFormatChecker IIFC; ImageSpec imgSpec_PX1_PX2_deltaZ[eLA_LayersCount]; for (uint iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { if (_qvect_eSFC_PX1_PX2_DeltaZ[iela] == e_sFC_checkInProgress) { bool bNoError = true; bNoError &= IIFC.getImageSpec(_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[iela].toStdString(), imgSpec_PX1_PX2_deltaZ[iela]); if (!bNoError) { strMsgErrorDetails = "(displacement map) failed to getImageSpec for file " + _tqstrDescName_image[iela]; _qvect_eSFC_PX1_PX2_DeltaZ[iela]=e_sFC_NotOK; return(false); } if (!IIFC.formatIsAnAcceptedFormatForDisplacementMap(imgSpec_PX1_PX2_deltaZ[iela])) { _qvect_eSFC_PX1_PX2_DeltaZ[iela]=e_sFC_NotOK; strMsgErrorDetails = "(displacement map) file format not supported for file " + _tqstrDescName_image[iela]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; if (esFC_PX1PX2 == e_sFC_checkInProgress) { //check that PX1 and PX2 have the same size and typeDescBaseType if (!IIFC.checkSameWidthHeightBaseType(imgSpec_PX1_PX2_deltaZ[eLA_PX1],imgSpec_PX1_PX2_deltaZ[eLA_PX2], true)) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX1]=e_sFC_NotOK; _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX2]=e_sFC_NotOK; strMsgErrorDetails = _tqstrDescName_image[eLA_PX1] + " and " + _tqstrDescName_image[eLA_PX2] + " don't have the same width, height or basetype"; return(false); } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that correlation score map for (PX1,PX2) deltaZalone are valid for correlation score map ImageSpec imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[eLA_LayersCount]; for (auto iter_iela_forCorScoMap : qvect_iela_forCorrelScoreMap) { if (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] == e_sFC_checkInProgress) { bool bNoError = true; bNoError &= IIFC.getImageSpec(_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[iter_iela_forCorScoMap].toStdString(), imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[iter_iela_forCorScoMap]); if (!bNoError) { strMsgErrorDetails = "(correlation score map) failed to getImageSpec for file " + _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap]; _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; return(false); } if (!IIFC.formatIsAnAcceptedFormatForCorrelationScoreMap(imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[iter_iela_forCorScoMap])) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; strMsgErrorDetails = "(correlation score map) file format not supported for file " + _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that all the input file have the same width and height // //. PX1 and PX2 together already check above about w/h/basetype //. check that deltaZ have same w/h than PX1 // do not check about basetype, it's ok to be different if ( (esFC_PX1PX2 == e_sFC_checkInProgress) &&(_qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] == e_sFC_checkInProgress)) { if (!IIFC.checkSameWidthHeightBaseType( imgSpec_PX1_PX2_deltaZ[eLA_deltaZ], imgSpec_PX1_PX2_deltaZ[eLA_PX1], false)) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] = e_sFC_NotOK; strMsgErrorDetails = _tqstrDescName_image[eLA_deltaZ] + " don't have the same width or height than " + _tqstrDescName_image[eLA_PX1] + " and " + _tqstrDescName_image[eLA_PX2]; return(false); } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //the file to use for comparison needs to be adjusted, depending of what is provided as input files e_LayersAcces ela_forWHComparison = eLA_PX1; if (esFC_PX1PX2 == e_sFC_notRequiered) { ela_forWHComparison = eLA_deltaZ; } //check now about correlation score map for (auto iter_iela_forCorScoMap : qvect_iela_forCorrelScoreMap) { if (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] == e_sFC_checkInProgress) { if (!IIFC.checkSameWidthHeightBaseType(imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[iter_iela_forCorScoMap], imgSpec_PX1_PX2_deltaZ[ela_forWHComparison], false)) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; strMsgErrorDetails = _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap] + "don't have the same width or height than the other"; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; for (uint iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { _qvect_eSFC_PX1_PX2_DeltaZ[iela] = convertInProgressToFinalValue(_qvect_eSFC_PX1_PX2_DeltaZ[iela]); } qDebug() << __FUNCTION__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together]; qDebug() << __FUNCTION__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone]; _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = convertInProgressToFinalValue( _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] ); _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = convertInProgressToFinalValue( _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone]); qDebug() << __FUNCTION__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; return(true); } InputFilesForComputationMatchWithRequierement::e_statusFileCheck InputFilesForComputationMatchWithRequierement::convertInProgressToFinalValue(e_statusFileCheck esFC) { if (esFC == e_sFC_checkInProgress) { return(e_sFC_OK); } else { return(esFC); } }
50.644068
167
0.71564
lp-rep
bf0d3e10e5cb760e4c8222263f045e241fa4a11c
493
cpp
C++
src/UserInterface/uiTitle.cpp
KURUJISU/Top_P
d218656e13cbe05b01926366e114b34b8d430035
[ "MIT" ]
null
null
null
src/UserInterface/uiTitle.cpp
KURUJISU/Top_P
d218656e13cbe05b01926366e114b34b8d430035
[ "MIT" ]
null
null
null
src/UserInterface/uiTitle.cpp
KURUJISU/Top_P
d218656e13cbe05b01926366e114b34b8d430035
[ "MIT" ]
null
null
null
#include "precompiled.h" uiTitle::uiTitle() {} void uiTitle::setup(){ shared_ptr<uiInformation> uiInfo = make_shared<uiInformation>(); uiInfo->setPos(ofVec2f(0, g_local->HalfHeight())); AddUI(uiInfo); wp_uiInfo_ = uiInfo; shared_ptr<uiScoreRank> uiScore = make_shared<uiScoreRank>(); uiScore->disableDrawCurrentScore(); uiScore->setPos(ofVec2f(0, g_local->HalfHeight())); AddUI(uiScore); wp_uiScore_ = uiScore; } void uiTitle::update(float deltaTime){} void uiTitle::draw(){ }
20.541667
65
0.730223
KURUJISU
bf0f7c93ae7f1cece7cf59cbdea79bb10f563f13
345
hpp
C++
Source/Runtime/Engine/Public/Components/SkyLightComponent.hpp
Othereum/NoEngineGame
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
[ "MIT" ]
23
2020-05-21T06:25:29.000Z
2021-04-06T03:37:28.000Z
Source/Runtime/Engine/Public/Components/SkyLightComponent.hpp
Othereum/NoEngineGame
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
[ "MIT" ]
72
2020-06-09T04:46:27.000Z
2020-12-07T03:20:51.000Z
Source/Runtime/Engine/Public/Components/SkyLightComponent.hpp
Othereum/NoEngineGame
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
[ "MIT" ]
4
2020-06-10T02:23:54.000Z
2022-03-28T07:22:08.000Z
#pragma once #include "SceneComponent.hpp" namespace oeng { inline namespace engine { class ENGINE_API SkyLightComponent : public SceneComponent { CLASS_BODY(SkyLightComponent) public: Vec3 color{All{}, 0.2}; protected: void OnBeginPlay() override; void OnEndPlay() override; }; } // namespace engine } // namespace oeng
15.681818
58
0.718841
Othereum
bf10d1e469dde07c463b53135f98489f29947b1f
6,241
cpp
C++
srcs/molenet/mysqldataprovider.cpp
FLynnGame/moleserver
d79e84f4afc4017c983deb4d6bfe0f5851eccedd
[ "Apache-2.0" ]
37
2020-05-15T08:29:39.000Z
2022-03-21T05:18:35.000Z
srcs/molenet/mysqldataprovider.cpp
FLynnGame/moleserver
d79e84f4afc4017c983deb4d6bfe0f5851eccedd
[ "Apache-2.0" ]
null
null
null
srcs/molenet/mysqldataprovider.cpp
FLynnGame/moleserver
d79e84f4afc4017c983deb4d6bfe0f5851eccedd
[ "Apache-2.0" ]
23
2020-07-06T08:55:07.000Z
2022-03-31T06:38:31.000Z
#include "../../include/molnet/mysqldataprovider.h" #include "../../include/molnet/common.h" #include "../../include/molnet/dalexcept.h" /** * 构造函数 */ MySqlDataProvider::MySqlDataProvider(void) throw() { } /** * 析构函数 */ MySqlDataProvider::~MySqlDataProvider(void) throw() { if(mIsConnected) disconnect(); } /** * 得到数据库的类型 * * @return 用于返回当前数据库的类型 */ DbBackends MySqlDataProvider::getDbBackend(void) const throw() { return DB_BKEND_MYSQL; } /** * 建立与数据库的连接 * * @param host 要连接的数据库的IP地址 * @param username 要连接数据库的用户名 * @param password 要连接数据库的用户密码 * @param dbName 要连接的数据库名称 * @param port 要连接的数据库的端口号 */ bool MySqlDataProvider::connect(std::string host,std::string username,std::string password, std::string dbName,unsigned int port) { if(mIsConnected) return false; if(!m_ConnectPool.Init(MOL_CONN_POOL_MAX, host.c_str(), username.c_str(), password.c_str(), dbName.c_str(), port)) return false; mysql_thread_init(); mDbName = dbName; mIsConnected = true; return true; } /** * 执行SQL语句 * * @param sql 要执行的SQL语句 * @param refresh 是否要刷新数据,也就是重新从数据库中获取数据 * * @return 如果成功获取到数据返回这个数据记录,否则抛出异常 */ const RecordSetList MySqlDataProvider::execSql(const std::string& sql,const bool refresh) { if(!mIsConnected) throw std::runtime_error("没有与数据库建立连接。"); RecordSetList pRecordSetList; try { if(refresh || (sql != mSql)) { MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return pRecordSetList; if(mysql_query(m_curWorkingConn,sql.c_str()) != 0) { m_ConnectPool.PutConnet(m_curWorkingConn); throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)+sql); } do { int fieldCount = mysql_field_count(m_curWorkingConn); if(fieldCount > 0) { RecordSet pRecordSet; MYSQL_RES* res = NULL; if(!(res = mysql_store_result(m_curWorkingConn))) { m_ConnectPool.PutConnet(m_curWorkingConn); throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); } unsigned int nFields = mysql_num_fields(res); //MYSQL_FIELD* fields = mysql_fetch_fields(res); Row fieldNames; for(unsigned int i=0;i<nFields;i++) { MYSQL_FIELD* fields = NULL; fields=mysql_fetch_field_direct(res,i); if(fields) fieldNames.push_back(fields->name ? fields->name : ""); } pRecordSet.setColumnHeaders(fieldNames); MYSQL_ROW row; while((row = mysql_fetch_row(res))) { Row r; for(unsigned int i = 0;i < nFields; i++) { char *tmpStr = static_cast<char*>(row[i]); r.push_back(tmpStr ? tmpStr : ""); } pRecordSet.add(r); } if(!pRecordSet.isEmpty()) pRecordSetList.add(pRecordSet); mysql_free_result(res); } } while (!mysql_next_result( m_curWorkingConn )); m_ConnectPool.PutConnet(m_curWorkingConn); } } catch(std::exception e) { LOG_ERROR(e.what()); } return pRecordSetList; } /** * 关闭与数据库的连接 */ void MySqlDataProvider::disconnect(void) { if(!mIsConnected) return; m_ConnectPool.Close(); mysql_thread_end(); mysql_library_end(); mIsConnected = false; } /** * 开始一项事物 */ void MySqlDataProvider::beginTransaction(void) throw (std::runtime_error) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下开始一项事务!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return; mysql_autocommit(m_curWorkingConn,AUTOCOMMIT_OFF); execSql("BEGIN"); m_ConnectPool.PutConnet(m_curWorkingConn); } /** * 提交一项事物 */ void MySqlDataProvider::commitTransaction(void) throw (std::runtime_error) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下提交一项事务!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return; if(mysql_commit(m_curWorkingConn) != 0) throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); mysql_autocommit(m_curWorkingConn,AUTOCOMMIT_ON); m_ConnectPool.PutConnet(m_curWorkingConn); } /** * 回滚一项事物 */ void MySqlDataProvider::rollbackTransaction(void) throw (std::runtime_error) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下回滚一项事务!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return; if(mysql_rollback(m_curWorkingConn) != 0) throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); mysql_autocommit(m_curWorkingConn,AUTOCOMMIT_ON); m_ConnectPool.PutConnet(m_curWorkingConn); } /** * 得到最近执行SQL语句后改变的行的个数 * * @return 返回最近改变的行数 */ unsigned int MySqlDataProvider::getModifiedRows(void) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下试图执行getModifiedRows!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return 0; const my_ulonglong affected = mysql_affected_rows(m_curWorkingConn); if(affected > INT_MAX) throw std::runtime_error("MySqlDataProvider: getModifiedRows 超出范围."); if(affected == (my_ulonglong)-1) { throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); } m_ConnectPool.PutConnet(m_curWorkingConn); return (unsigned int)affected; } /** * 得到最近插入的数据的行号 * * @return 返回改变数据的最新的行号 */ unsigned int MySqlDataProvider::getLastId(void) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下试图执行getLastId!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return 0; const my_ulonglong lastId = mysql_insert_id(m_curWorkingConn); if(lastId > UINT_MAX) throw std::runtime_error("MySqlDataProvider: getLastId 超出范围."); m_ConnectPool.PutConnet(m_curWorkingConn); return (unsigned int)lastId; } /// 用于维护数据库连接 void MySqlDataProvider::Update(void) { m_ConnectPool.Update(); }
20.59736
92
0.670405
FLynnGame
bf15d382e043c444c2e0254fb449fa91241b0f00
2,131
hpp
C++
NetworkLib/src/Float.hpp
Bousk/Net
bb77d61f870a28752fdf7509c111d446819aff31
[ "MIT" ]
2
2021-12-29T16:29:13.000Z
2022-03-27T15:48:20.000Z
NetworkLib/src/Float.hpp
Bousk/Net
bb77d61f870a28752fdf7509c111d446819aff31
[ "MIT" ]
null
null
null
NetworkLib/src/Float.hpp
Bousk/Net
bb77d61f870a28752fdf7509c111d446819aff31
[ "MIT" ]
1
2020-10-31T23:50:23.000Z
2020-10-31T23:50:23.000Z
#pragma once #include <RangedInteger.hpp> #include <Serialization/Serialization.hpp> #include <Serialization/Serializer.hpp> #include <Serialization/Deserializer.hpp> namespace Bousk { template<class FLOATTYPE, int32 MIN, int32 MAX, uint8 NBDECIMALS, uint8 STEP = 1 > class Float : public Serialization::Serializable { static_assert(std::is_same_v<FLOATTYPE, float32> || std::is_same_v<FLOATTYPE, float64>, "Float can only be used with float32 or float64"); static_assert(MIN < MAX, "Min & Max values must be strictly ordered"); static_assert(NBDECIMALS > 0, "At least 1 decimal"); static_assert(NBDECIMALS < 10, "Maximum 10 decimals"); static_assert(STEP != 0, "Step must not be 0"); static_assert(STEP % 10 != 0, "Step should not be a multiple of 10. Remove a decimal"); using FloatType = FLOATTYPE; static constexpr int32 Min = MIN; static constexpr int32 Max = MAX; static constexpr uint32 Diff = Max - Min; static constexpr uint8 NbDecimals = NBDECIMALS; static constexpr uint32 Multiple = Pow<10, NbDecimals>::Value; static constexpr uint8 Step = STEP; static constexpr uint32 Domain = (MAX - MIN) * Multiple / STEP; public: Float() = default; Float(FloatType value) { mQuantizedValue = Quantize(value); } static uint32 Quantize(FloatType value) { assert(value >= Min && value <= Max); return static_cast<uint32>(((value - Min) * Multiple) / Step); } inline FloatType get() const { return static_cast<FloatType>((mQuantizedValue.get() * Step * 1.) / Multiple + Min); } inline operator FloatType() const { return get(); } bool write(Serialization::Serializer& serializer) const override { return mQuantizedValue.write(serializer); } bool read(Serialization::Deserializer& deserializer) override { return mQuantizedValue.read(deserializer); } private: RangedInteger<0, Domain> mQuantizedValue; }; template<int32 MIN, int32 MAX, uint8 NBDECIMALS, uint8 STEP = 1> using Float32 = Float<float32, MIN, MAX, NBDECIMALS, STEP>; template<int32 MIN, int32 MAX, uint8 NBDECIMALS, uint8 STEP = 1> using Float64 = Float<float64, MIN, MAX, NBDECIMALS, STEP>; }
38.745455
140
0.727358
Bousk
bf19a050a9d17181e6ef289ba3c576590fae4e9e
4,062
cpp
C++
src/prod/src/ServiceModel/PagingStatus.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/PagingStatus.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/PagingStatus.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Federation; StringLiteral const TraceSource("PagingStatus"); PagingStatus::PagingStatus() : continuationToken_() { } PagingStatus::PagingStatus(wstring && continuationToken) : continuationToken_(move(continuationToken)) { } PagingStatus::PagingStatus(PagingStatus && other) : continuationToken_(move(other.continuationToken_)) { } PagingStatus & PagingStatus::operator =(PagingStatus && other) { if (this != &other) { continuationToken_ = move(other.continuationToken_); } return *this; } PagingStatus::~PagingStatus() { } void PagingStatus::ToPublicApi( __in ScopedHeap & heap, __out FABRIC_PAGING_STATUS & publicPagingStatus) const { publicPagingStatus.ContinuationToken = heap.AddString(continuationToken_); } ErrorCode PagingStatus::FromPublicApi(FABRIC_PAGING_STATUS const & publicPagingStatus) { auto hr = StringUtility::LpcwstrToWstring(publicPagingStatus.ContinuationToken, true, ParameterValidator::MinStringSize, ParameterValidator::MaxStringSize, continuationToken_); if (FAILED(hr)) { Trace.WriteInfo(TraceSource, "Error parsing continuation token in FromPublicAPI: {0}", hr); return ErrorCode::FromHResult(hr); } return ErrorCode::Success(); } // // Templated methods // // This will return an error if the continuation token is empty (same as other specializations of this template's base template) template <> ErrorCode PagingStatus::GetContinuationTokenData<wstring>( std::wstring const & continuationToken, __inout wstring & data) { if (continuationToken.empty()) { return ErrorCode( ErrorCodeValue::ArgumentNull, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } data = continuationToken; return ErrorCode::Success(); } template <> std::wstring PagingStatus::CreateContinuationToken<Uri>(Uri const & data) { return data.ToString(); } template <> std::wstring PagingStatus::CreateContinuationToken<NodeId>(NodeId const & nodeId) { return wformatString("{0}", nodeId); } template <> ErrorCode PagingStatus::GetContinuationTokenData<NodeId>( std::wstring const & continuationToken, __inout NodeId & nodeId) { if (!NodeId::TryParse(continuationToken, nodeId)) { return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } return ErrorCode::Success(); } template <> std::wstring PagingStatus::CreateContinuationToken<Guid>(Guid const & guid) { return wformatString("{0}", guid); } template <> ErrorCode PagingStatus::GetContinuationTokenData<Guid>( std::wstring const & continuationToken, __inout Guid & guid) { if (!Guid::TryParse(continuationToken, guid)) { return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } return ErrorCode::Success(); } template <> std::wstring PagingStatus::CreateContinuationToken<FABRIC_REPLICA_ID>(FABRIC_REPLICA_ID const & replicaId) { return wformatString("{0}", replicaId); } template <> ErrorCode PagingStatus::GetContinuationTokenData<FABRIC_REPLICA_ID>( std::wstring const & continuationToken, __inout FABRIC_REPLICA_ID & replicaId) { if (!StringUtility::TryFromWString<FABRIC_REPLICA_ID>(continuationToken, replicaId)) { return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } return ErrorCode::Success(); }
28.405594
180
0.70384
vishnuk007
bf1f059e5368aebbc9e23f9c3aea0a796b21d911
4,328
cpp
C++
Libraries/Resources/Hcsr501/Hcsr501.cpp
automacaoiot/ESP8266-SDK
ee8028a9dce00dab7dee13afdc3b7a7c51af6d03
[ "MIT" ]
null
null
null
Libraries/Resources/Hcsr501/Hcsr501.cpp
automacaoiot/ESP8266-SDK
ee8028a9dce00dab7dee13afdc3b7a7c51af6d03
[ "MIT" ]
null
null
null
Libraries/Resources/Hcsr501/Hcsr501.cpp
automacaoiot/ESP8266-SDK
ee8028a9dce00dab7dee13afdc3b7a7c51af6d03
[ "MIT" ]
null
null
null
/** *MIT License * * Copyright (c) 2017 Automa��o-IOT * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Hcsr501.h" #ifdef WIFI int Hcsr501::counterHcsr501 = 0; Hcsr501::Hcsr501(GpiosEnum gpio, unsigned long refreshHcsr501,String nameHCSR501) { resourceJson = "Hcsr501"+String(counterHcsr501++); resourcesJson[indexJson++] = resourceJson; counterJson = counterHcsr501; this->gpio = gpio; refresh = refreshHcsr501; name = nameHCSR501+String(counterHcsr501); resourceWifiMode = true; } #endif Hcsr501::Hcsr501(unsigned long id, GpiosEnum gpio, unsigned long refreshHcsr501,String nameHCSR501) { this->id = id; this->gpio = gpio; refresh = refreshHcsr501; name = nameHCSR501+id; resourceWifiMode = false; } void ICACHE_FLASH_ATTR Hcsr501::setModeConfigNetwork() { #ifdef WIFI if(selectModeNetwork()==1) set(this->gpio,refresh); else if(selectModeNetwork()==2) set(this->id,this->gpio,refresh); #else set(this->id,this->gpio,refresh); #endif return; } void ICACHE_FLASH_ATTR Hcsr501::set(unsigned long id, GpiosEnum gpio, unsigned long refresh) { resourceWifi = true; pinMode(gpio, INPUT); return; } #ifdef WIFI void ICACHE_FLASH_ATTR Hcsr501::set(GpiosEnum gpio, unsigned long refresh) { this->id = idResource(resourceJson); if(this->id!=0) set(this->id,gpio,refresh); else { resourceWifi = false; debugIOT(MSG_ERROR,"Resource Hcsr501 referenced in main was not sent by JSON"); refreshTimer.stop(); } return; } #endif void ICACHE_FLASH_ATTR Hcsr501::responseHttpCallback() { if(!systemCall) { read(); refreshTimer.start(); } return; } void ICACHE_FLASH_ATTR Hcsr501::actionStart() { if((clientDeviceHTTP!=200) ||(clientHTTP->code==403)) { serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds/last"; sendHTTP(BLANK,GET); } if(RequestQueueOn) { String heap = String(system_get_free_heap_size()); debugIOT(MSG_INFO,name+" - Memory HEAP",heap); if(filter) { if(this->hcsr501Presence != json->response->feed.rawData.toInt()) { doCallback(CallbackEvents::DATA_CHANGED); serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds"; sendHTTP(json->parseJson(this->hcsr501Presence),POST); } else { serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds/last"; sendHTTP(BLANK,GET); } } else { doCallback(CallbackEvents::DATA_CHANGED); serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds"; sendHTTP(json->parseJson(this->hcsr501Presence),POST); } } return; } unsigned long ICACHE_FLASH_ATTR Hcsr501::read() { this->hcsr501Presence = digitalRead(this->gpio); return this->hcsr501Presence; }
34.903226
138
0.658965
automacaoiot
bf213da706fcc816c12313ec662a8e583798c00d
2,375
hpp
C++
math/geometry.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
math/geometry.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
math/geometry.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_MATH_GEOMETRY_HPP___ #define ___INANITY_MATH_GEOMETRY_HPP___ #include "basic.hpp" BEGIN_INANITY_MATH template <typename T> xmat<T, 4, 4> CreateTranslationMatrix(const xvec<T, 3>& translation) { xmat<T, 4, 4> r = identity_mat<T, 4>(); r(0, 3) = translation(0); r(1, 3) = translation(1); r(2, 3) = translation(2); return r; } template <typename T> xmat<T, 4, 4> CreateScalingMatrix(const xvec<T, 3>& scaling) { xmat<T, 4, 4> r = identity_mat<T, 4>(); r(0, 0) = scaling(0); r(1, 1) = scaling(1); r(2, 2) = scaling(2); return r; } template <typename T> xmat<T, 4, 4> CreateLookAtMatrix(const xvec<T, 3>& eye, const xvec<T, 3>& target, const xvec<T, 3>& up) { xmat<T, 4, 4> r; xvec<T, 3> z = normalize(eye - target); xvec<T, 3> x = normalize(cross(up, z)); xvec<T, 3> y = cross(z, x); r(0, 0) = x.x; r(1, 0) = y.x; r(2, 0) = z.x; r(3, 0) = 0; r(0, 1) = x.y; r(1, 1) = y.y; r(2, 1) = z.y; r(3, 1) = 0; r(0, 2) = x.z; r(1, 2) = y.z; r(2, 2) = z.z; r(3, 2) = 0; r(0, 3) = -dot(x, eye); r(1, 3) = -dot(y, eye); r(2, 3) = -dot(z, eye); r(3, 3) = 1; return r; } template <typename T> xmat<T, 4, 4> CreateProjectionPerspectiveFovMatrix(T fovY, T aspect, T zn, T zf) { xmat<T, 4, 4> r = zero_mat<T, 4, 4>(); T yScale = 1 / tan(fovY / 2); T xScale = yScale / aspect; r(0, 0) = xScale; r(1, 1) = yScale; r(2, 2) = zf / (zn - zf); r(2, 3) = zn * zf / (zn - zf); r(3, 2) = -1; return r; } template <typename T> xvec<T, 4> axis_rotation(const xvec<T, 3>& axis, T angle) { angle /= 2; T angleSin = sin(angle); T angleCos = cos(angle); return xvec<T, 4>( axis.x * angleSin, axis.y * angleSin, axis.z * angleSin, angleCos); } template <typename T> xmat<T, 4, 4> QuaternionToMatrix(const xquat<T>& q) { xmat<T, 4, 4> r; T ww = q.w * q.w; T xx = q.x * q.x; T yy = q.y * q.y; T zz = q.z * q.z; T wx2 = q.w * q.x * 2.0f; T wy2 = q.w * q.y * 2.0f; T wz2 = q.w * q.z * 2.0f; T xy2 = q.x * q.y * 2.0f; T xz2 = q.x * q.z * 2.0f; T yz2 = q.y * q.z * 2.0f; r(0, 0) = ww + xx - yy - zz; r(0, 1) = xy2 - wz2; r(0, 2) = xz2 + wy2; r(0, 3) = 0; r(1, 0) = xy2 + wz2; r(1, 1) = ww - xx + yy - zz; r(1, 2) = yz2 - wx2; r(1, 3) = 0; r(2, 0) = xz2 - wy2; r(2, 1) = yz2 + wx2; r(2, 2) = ww - xx - yy + zz; r(2, 3) = 0; r(3, 0) = 0; r(3, 1) = 0; r(3, 2) = 0; r(3, 3) = 1; return r; } END_INANITY_MATH #endif
20.299145
103
0.532211
quyse
bf222b8459571e85368deec0c2b8d337de4c5ddd
10,280
cpp
C++
mcrng/mcrng.cpp
tectrolabs/microrng
586576107d510374d0a5b8536da45b4743dcadbf
[ "MIT" ]
null
null
null
mcrng/mcrng.cpp
tectrolabs/microrng
586576107d510374d0a5b8536da45b4743dcadbf
[ "MIT" ]
null
null
null
mcrng/mcrng.cpp
tectrolabs/microrng
586576107d510374d0a5b8536da45b4743dcadbf
[ "MIT" ]
1
2020-04-21T20:43:01.000Z
2020-04-21T20:43:01.000Z
/** * Copyright (C) 2014-2022 TectroLabs LLC, https://tectrolabs.com * * 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. */ /** * @file mcrng.cpp * @author Andrian Belinski * @date 06/-7/2022 * @version 1.1 * * @brief downloads random bytes from MicroRNG device through SPI interface on Raspberry PI 3+ or other Linux-based single-board computers. * */ #include "mcrng.h" /** * Display usage message * */ void displayUsage() { printf("---------------------------------------------------------------------------\n"); printf("--- TectroLabs - mcrng - MicroRNG download utility Version 1.0 ---\n"); printf("--- Use with RPI 3+ or other Linux-based single-board computers ---\n"); printf("---------------------------------------------------------------------------\n"); printf("NAME\n"); printf(" mcrng - True Random Number Generator MicroRNG download utility \n"); printf("SYNOPSIS\n"); printf(" mcrng [options] \n"); printf("\n"); printf("DESCRIPTION\n"); printf(" Mcrng downloads random bytes from MicroRNG device into a data file.\n"); printf("\n"); printf("OPTIONS\n"); printf(" Operation modifiers:\n"); printf("\n"); printf(" -fn FILE, --file-name FILE\n"); printf(" a FILE name for storing random data. Use STDOUT to send bytes\n"); printf(" to standard output\n"); printf("\n"); printf(" -nb NUMBER, --number-bytes NUMBER\n"); printf(" NUMBER of random bytes to download, max value 200000000000,\n"); printf(" skip this option for continuous download of random bytes\n"); printf("\n"); printf(" -dp PATH, --device-path PATH\n"); printf(" SPI device path, default value: /dev/spidev0.0\n"); printf("\n"); printf(" -cf NUMBER, --clock-frequency NUMBER\n"); printf(" SPI master clock frequency in KHz, max value 60000,\n"); printf(" skip this option for default 250 KHz frequency.\n"); printf(" Setting this value too high may result in miscommunication.\n"); printf(" Use 'mcdiag' utility to determine the max frequency.\n"); printf("EXAMPLES:\n"); printf(" It may require 'sudo' permissions to run this utility.\n"); printf(" To download 12 MB of true random bytes to 'rnd.bin' file\n"); printf(" mcrng -dd -fn rnd.bin -nb 12000000\n"); printf(" To download 12 MB of true random bytes to a file using device path\n"); printf(" mcrng -dd -fn rnd.bin -nb 12000000 -dp /dev/spidev0.0\n"); printf(" To download 12 MB of true random bytes to standard output\n"); printf(" mcrng -dd -fn STDOUT -nb 12000000 -dp /dev/spidev0.0\n"); printf("\n"); } /** * Validate command line argument count * * @param int curIdx * @param int actualArgumentCount * @return true if run successfully */ bool validateArgumentCount(int curIdx, int actualArgumentCount) { if (curIdx >= actualArgumentCount) { fprintf(stderr, "\nMissing command line arguments\n\n"); displayUsage(); return false; } return true; } /** * Parse device path if specified * * @param int idx - current parameter number * @param int argc - number of parameters * @param char ** argv - parameters * @return int - 0 when successfully parsed */ int parseDevicePath(int idx, int argc, char **argv) { if (idx < argc) { if (strcmp("-dp", argv[idx]) == 0 || strcmp("--device-path", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } strcpy(devicePath, argv[idx++]); } } return 0; } /** * Parse arguments for extracting command line parameters * * @param int argc * @param char** argv * @return int - 0 when run successfully */ int processArguments(int argc, char **argv) { int idx = 1; strcpy(devicePath, DEFAULT_SPI_DEV_PATH); if (argc < 2) { displayUsage(); return -1; } while (idx < argc) { if (strcmp("-nb", argv[idx]) == 0 || strcmp("--number-bytes", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } numGenBytes = atoll(argv[idx++]); if (numGenBytes > 200000000000) { fprintf(stderr, "Number of bytes cannot exceed 200000000000\n"); return -1; } } else if (strcmp("-fn", argv[idx]) == 0 || strcmp("--file-name", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } filePathName = argv[idx++]; } else if (strcmp("-cf", argv[idx]) == 0 || strcmp("--clock-frequency", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } maxSpiMasterClock = (uint32_t)atoi(argv[idx++]) * 1000; } else if (parseDevicePath(idx, argc, argv) == -1) { return -1; } else { // Could not handle the argument, skip to the next one ++idx; } } return processDownloadRequest(); } /** * Close file handle * */ void closeHandle() { if (pOutputFile != NULL) { fclose(pOutputFile); pOutputFile = NULL; } } /** * Write bytes out to the file * * @param uint8_t* bytes - pointer to the byte array * @param uint32_t numBytes - number of bytes to write */ void writeBytes(uint8_t *bytes, uint32_t numBytes) { FILE *handle = pOutputFile; fwrite(bytes, 1, numBytes, handle); } /** * Handle download request * * @return int - 0 when run successfully */ int handleDownloadRequest() { uint8_t receiveByteBuffer[MCR_BUFF_FILE_SIZE_BYTES]; if (!spi.connect(devicePath)) { fprintf(stderr, " Cannot open SPI device %s, error: %s ... \n", devicePath, spi.getLastErrMsg()); return -1; } spi.setMaxClockFrequency(maxSpiMasterClock); if (!spi.validateDevice()) { fprintf(stderr, " Cannot access device, error: %s ... \n", spi.getLastErrMsg()); return -1; } if (filePathName == NULL) { fprintf(stderr, "No file name defined.\n"); return -1; } if (isOutputToStandardOutput == true) { pOutputFile = fdopen(dup(fileno(stdout)), "wb"); } else { pOutputFile = fopen(filePathName, "wb"); } if (pOutputFile == NULL) { fprintf(stderr, "Cannot open file: %s in write mode\n", filePathName); return -1; } while (numGenBytes == -1) { // Infinite loop for downloading unlimited random bytes if (!spi.retrieveRandomBytes(MCR_BUFF_FILE_SIZE_BYTES, receiveByteBuffer)) { fprintf(stderr, "Failed to receive %d bytes for unlimited download, error: %s. \n", MCR_BUFF_FILE_SIZE_BYTES, spi.getLastErrMsg()); return -1; } writeBytes(receiveByteBuffer, MCR_BUFF_FILE_SIZE_BYTES); } // Calculate number of complete random byte chunks to download int64_t numCompleteChunks = numGenBytes / MCR_BUFF_FILE_SIZE_BYTES; // Calculate number of bytes in the last incomplete chunk uint32_t chunkRemaindBytes = (uint32_t)(numGenBytes % MCR_BUFF_FILE_SIZE_BYTES); // Process each chunk int64_t chunkNum; for (chunkNum = 0; chunkNum < numCompleteChunks; chunkNum++) { if (!spi.retrieveRandomBytes(MCR_BUFF_FILE_SIZE_BYTES, receiveByteBuffer)) { fprintf(stderr, "Failed to receive %d bytes, error: %s. \n", MCR_BUFF_FILE_SIZE_BYTES, spi.getLastErrMsg()); return -1; } writeBytes(receiveByteBuffer, MCR_BUFF_FILE_SIZE_BYTES); } if (chunkRemaindBytes > 0) { //Process incomplete chunk if (!spi.retrieveRandomBytes(chunkRemaindBytes, receiveByteBuffer)) { fprintf(stderr, "Failed to receive %d bytes for last chunk, error: code %s. ", chunkRemaindBytes,spi.getLastErrMsg()); return -1; } writeBytes(receiveByteBuffer, chunkRemaindBytes); } closeHandle(); return 0; } /** * Process Request * * @return int - 0 when run successfully */ int processDownloadRequest() { if (filePathName != NULL && (!strcmp(filePathName, "STDOUT") || !strcmp(filePathName, "/dev/stdout"))) { isOutputToStandardOutput = true; } else { isOutputToStandardOutput = false; } int status = handleDownloadRequest(); return status; } /** * Main entry * * @param int argc - number of parameters * @param char ** argv - parameters * */ int main(int argc, char **argv) { if (!processArguments(argc, argv)) { return -1; }; return 0; }
30.146628
142
0.580156
tectrolabs
bf2278af946938a3377b419a537b09a9254a8cda
34,726
cpp
C++
src/plzma_path.cpp
readdle/PLzmaSDK
9587bbbb507249c66b90209e115bf0edd8d88274
[ "MIT" ]
null
null
null
src/plzma_path.cpp
readdle/PLzmaSDK
9587bbbb507249c66b90209e115bf0edd8d88274
[ "MIT" ]
null
null
null
src/plzma_path.cpp
readdle/PLzmaSDK
9587bbbb507249c66b90209e115bf0edd8d88274
[ "MIT" ]
null
null
null
// // By using this Software, you are accepting original [LZMA SDK] and MIT license below: // // The MIT License (MIT) // // Copyright (c) 2015 - 2021 Oleh Kulykov <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <cstddef> #include "../libplzma.hpp" #include "plzma_private.hpp" #include "plzma_path_utils.hpp" namespace plzma { using namespace pathUtils; /// Iterator enum PathIteratorFlags: uint16_t { PathIteratorFlagIsDir = 1 << 0, PathIteratorFlagSkipPathConcat = 1 << 1, PathIteratorFlagDone = 1 << 2, PathIteratorFlagSkipFindNext = 1 << 3 }; Path Path::Iterator::path() const { Path res(_path); if ( !(_flags & PathIteratorFlagSkipPathConcat) ) { res.append(_component); } return res; } const Path & Path::Iterator::component() const noexcept { return _component; } Path Path::Iterator::fullPath() const { Path res(_root); if ( !(_flags & PathIteratorFlagSkipPathConcat) ) { res.append(_component); } return res; } bool Path::Iterator::isDir() const noexcept { return (_flags & PathIteratorFlagIsDir) ? true : false; } void Path::Iterator::clearPaths() noexcept { _root.clear(plzma_erase_zero); _path.clear(plzma_erase_zero); _component.clear(plzma_erase_zero); } Path::Iterator::Iterator(const Path & root, const plzma_open_dir_mode_t mode) : _root(root), _mode(mode) { } #if defined(LIBPLZMA_MSC) class PathIteratorMSC final : public Path::Iterator { private: HANDLE _findHandle = INVALID_HANDLE_VALUE; Vector<HANDLE> _stack; WIN32_FIND_DATAW _findData; plzma_size_t _referenceCounter = 0; void closeMSC() noexcept { _flags |= PathIteratorFlagDone; plzma_size_t i = _stack.count(); if (i > 0) { do { FindClose(_stack.at(--i)); } while (i > 0); _stack.clear(); } if (_findHandle != INVALID_HANDLE_VALUE) { FindClose(_findHandle); _findHandle = INVALID_HANDLE_VALUE; } clearPaths(); } LIBPLZMA_NON_COPYABLE_NON_MOVABLE(PathIteratorMSC) protected: virtual void retain() noexcept override final { LIBPLZMA_RETAIN_IMPL(_referenceCounter) } virtual void release() noexcept override final { LIBPLZMA_RELEASE_IMPL(_referenceCounter) } public: virtual void close() noexcept override final { closeMSC(); } virtual bool next() override final { if (_flags & PathIteratorFlagDone) { return false; } BOOL reading = TRUE; BOOL findNextRes = (_flags & PathIteratorFlagSkipFindNext) ? TRUE : FALSE; _flags = 0; do { if (!findNextRes) { findNextRes = FindNextFileW(_findHandle, &_findData); } if (findNextRes) { findNextRes = FALSE; if (wcscmp(_findData.cFileName, L".") == 0 || wcscmp(_findData.cFileName, L"..") == 0) { continue; } const bool isLink = ((_findData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && (_findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) ? true : false; if (isLink && !(_mode & plzma_open_dir_mode_follow_symlinks)) { continue; } _component.set(_findData.cFileName); if (_findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { Path root(_root); root.append(_component); root.append(L"*"); RAIIFindHANDLE subHandle; subHandle.handle = FindFirstFileW(root.wide(), &_findData); if (subHandle.handle == INVALID_HANDLE_VALUE) { continue; } else { _stack.push(_findHandle); _findHandle = subHandle.handle; subHandle.handle = INVALID_HANDLE_VALUE; root.removeLastComponent(); // remove '/*' _root = static_cast<Path &&>(root); _path.append(_component); _flags |= (PathIteratorFlagSkipPathConcat | PathIteratorFlagIsDir | PathIteratorFlagSkipFindNext); return true; // report dir } } else { //TODO: filter & skip unsupported attribs if needed //https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants return true; // report file } } else if (_stack.count() > 0) { _root.removeLastComponent(); _path.removeLastComponent(); _findHandle = _stack.at(_stack.count() - 1); _stack.pop(); continue; } else { reading = FALSE; // no files, exit } } while (reading); _flags |= PathIteratorFlagDone; return false; } PathIteratorMSC(const Path & root, const plzma_open_dir_mode_t mode) : Path::Iterator(root, mode) { Path path(root); if (path.count() > 0) { path.append(L"*"); } else { path.set(L"." CLZMA_SEP_WSTR L"*"); } RAIIFindHANDLE subHandle; subHandle.handle = FindFirstFileW(path.wide(), &_findData); if (subHandle.handle == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { // function fails because no matching files can be found clearPaths(); _flags |= PathIteratorFlagDone; } else { Exception exception(plzma_error_code_io, nullptr, __FILE__, __LINE__); exception.setWhat("Can't open and iterate path: ", _root.utf8(), nullptr); exception.setReason("Path not found or not a directory.", nullptr); clearPaths(); throw exception; } } else { _findHandle = subHandle.handle; subHandle.handle = INVALID_HANDLE_VALUE; _flags |= PathIteratorFlagSkipFindNext; } } virtual ~PathIteratorMSC() noexcept { closeMSC(); } }; #elif defined(LIBPLZMA_POSIX) class PathIteratorPosix final : public Path::Iterator { private: DIR * _dir = nullptr; Vector<DIR *> _stack; plzma_size_t _referenceCounter = 0; void closePosix() noexcept { _flags |= PathIteratorFlagDone; plzma_size_t i = _stack.count(); if (i > 0) { do { closedir(_stack.at(--i)); } while (i > 0); _stack.clear(); } if (_dir) { closedir(_dir); _dir = nullptr; } clearPaths(); } LIBPLZMA_NON_COPYABLE_NON_MOVABLE(PathIteratorPosix) protected: virtual void retain() noexcept override final { LIBPLZMA_RETAIN_IMPL(_referenceCounter) } virtual void release() noexcept override final { LIBPLZMA_RELEASE_IMPL(_referenceCounter) } public: virtual void close() noexcept override final { closePosix(); } virtual bool next() override final { if (_flags & PathIteratorFlagDone) { return false; } _flags = 0; Path root; const char * rootUtf8; struct dirent d, * dp; int readRes; do { if ( (readRes = readdir_r(_dir, &d, &dp)) == 0 && dp) { if (strcmp(d.d_name, ".") == 0 || strcmp(d.d_name, "..") == 0) { continue; } bool isDir = false, isFile = false, isLink = false; rootUtf8 = nullptr; if (d.d_type != DT_UNKNOWN) { isDir = d.d_type == DT_DIR; isFile = d.d_type == DT_REG; isLink = d.d_type == DT_LNK; } else { root.set(_root); root.append(d.d_name); rootUtf8 = root.utf8(); struct stat statbuf; if (access(rootUtf8, F_OK) == 0 && stat(rootUtf8, &statbuf) == 0) { isDir = S_ISDIR(statbuf.st_mode); isFile = S_ISREG(statbuf.st_mode); isLink = S_ISLNK(statbuf.st_mode); } else { continue; } } if (isLink && !(_mode & plzma_open_dir_mode_follow_symlinks)) { continue; } _component.set(d.d_name); if (isFile) { return true; } else if (isDir || isLink) { if (!rootUtf8) { root.set(_root); root.append(_component); rootUtf8 = root.utf8(); } RAIIDIR dir; dir.dir = opendir(rootUtf8); if (dir.dir) { _stack.push(_dir); _dir = dir.dir; dir.dir = nullptr; _root = static_cast<Path &&>(root); rootUtf8 = nullptr; _path.append(_component); } else { continue; } _flags |= (PathIteratorFlagSkipPathConcat | PathIteratorFlagIsDir); return true; // report dir } else { continue; } } if (readRes == 0 && !dp && _stack.count() > 0) { _root.removeLastComponent(); _path.removeLastComponent(); closedir(_dir); _dir = _stack.at(_stack.count() - 1); _stack.pop(); dp = &d; continue; } } while (readRes == 0 && dp); _flags |= PathIteratorFlagDone; return false; } PathIteratorPosix(const Path & root, const plzma_open_dir_mode_t mode) : Path::Iterator(root, mode) { const char * path = nullptr; if (_root.count() > 0) { const char * utf8 = _root.utf8(); bool isDir = false; if (pathExists<char>(utf8, &isDir) && isDir) { path = utf8; } else { Exception exception(plzma_error_code_io, nullptr, __FILE__, __LINE__); exception.setWhat("Can't open and iterate path: ", _root.utf8(), nullptr); exception.setReason("Path not found or not a directory.", nullptr); clearPaths(); _flags |= PathIteratorFlagDone; throw exception; } } else { path = "."; } if ( !(_dir = opendir(path)) ) { Exception exception(plzma_error_code_io, nullptr, __FILE__, __LINE__); exception.setWhat("Can't open directory: ", _root.utf8(), nullptr); exception.setReason("No open directory permissions.", nullptr); clearPaths(); _flags |= PathIteratorFlagDone; throw exception; } } virtual ~PathIteratorPosix() noexcept { closePosix(); } }; #endif void Path::set(const String & str) { #if defined(LIBPLZMA_MSC) set(str.wide()); #elif defined(LIBPLZMA_POSIX) set(str.utf8()); #endif } void Path::set(const wchar_t * LIBPLZMA_NULLABLE str) { copyFrom(str, plzma_erase_zero); const auto reduced = normalize<wchar_t>(_ws); if (reduced > 0) { _size -= reduced; } } void Path::set(const char * LIBPLZMA_NULLABLE str) { copyFrom(str, plzma_erase_zero); const auto reduced = normalize<char>(_cs); if (reduced > 0) { _size -= reduced; _cslen -= reduced; } } void Path::append(const wchar_t * LIBPLZMA_NULLABLE str) { syncWide(); const size_t len = str ? wcslen(str) : 0; if (len > 0) { const wchar_t * stringsList[2]; Pair<size_t, size_t> sizesList[2]; size_t count = 0; if (requireSeparator<wchar_t>(_ws, _size, str)) { stringsList[count] = CLZMA_SEP_WSTR; sizesList[count].first = sizesList[count].second = 1; count++; } stringsList[count] = str; sizesList[count].first = sizesList[count].second = len; String::append(stringsList, sizesList, ++count, plzma_erase_zero); const auto reduced = normalize<wchar_t>(_ws); if (reduced > 0) { _size -= reduced; } } } void Path::append(const char * LIBPLZMA_NULLABLE str) { syncUtf8(); const auto len = lengthMaxCount(str, static_cast<size_t>(plzma_max_size())); if (len.first > 0) { const char * stringsList[2]; Pair<size_t, size_t> sizesList[2]; size_t count = 0; if (requireSeparator<char>(_cs, _cslen, str)) { stringsList[count] = CLZMA_SEP_CSTR; sizesList[count].first = sizesList[count].second = 1; count++; } stringsList[count] = str; sizesList[count] = len; String::append(stringsList, sizesList, ++count, plzma_erase_zero); const auto reduced = normalize<char>(_cs); if (reduced > 0) { _size -= reduced; _cslen -= reduced; } } } void Path::append(const Path & path) { #if defined(LIBPLZMA_MSC) append(path.wide()); #elif defined(LIBPLZMA_POSIX) append(path.utf8()); #endif } Path Path::appending(const wchar_t * LIBPLZMA_NULLABLE str) const { Path result(*this); result.append(str); return result; } Path Path::appending(const char * LIBPLZMA_NULLABLE str) const { Path result(*this); result.append(str); return result; } Path Path::appending(const Path & path) const { Path result(*this); result.append(path); return result; } void Path::appendRandomComponent() { #if defined(LIBPLZMA_MSC) syncWide(); _cs.clear(plzma_erase_zero, sizeof(char) * _cslen); _size += appendRandComp<wchar_t>(_ws, _size); #elif defined(LIBPLZMA_POSIX) syncUtf8(); _ws.clear(plzma_erase_zero, sizeof(wchar_t) * _size); const auto appended = appendRandComp<char>(_cs, _cslen); _size += appended; _cslen += appended; #endif } Path Path::appendingRandomComponent() const { Path result(*this); result.appendRandomComponent(); return result; } Path Path::lastComponent() const { Path res; #if defined(LIBPLZMA_MSC) syncWide(); if (_ws && _size > 0) { const auto comp = lastComp<wchar_t>(_ws, _size); if (comp.second > 0) { const wchar_t * stringsList[1] = { comp.first }; Pair<size_t, size_t> sizesList[1]; sizesList[0].first = sizesList[0].second = comp.second; res.String::append(stringsList, sizesList, 1, plzma_erase_zero); } } #elif defined(LIBPLZMA_POSIX) syncUtf8(); if (_cs && _cslen > 0) { const auto comp = lastComp<char>(_cs, _cslen); if (comp.second > 0) { const char * stringsList[1] = { comp.first }; Pair<size_t, size_t> sizesList[1] = { lengthMaxLength(comp.first, comp.second) }; res.String::append(stringsList, sizesList, 1, plzma_erase_zero); } } #endif return res; } void Path::removeLastComponent() { #if defined(LIBPLZMA_MSC) syncWide(); if (_ws && _size > 0 && removeLastComp<wchar_t>(_ws, _size)) { _size = static_cast<plzma_size_t>(wcslen(_ws)); _cs.clear(plzma_erase_zero, sizeof(char) * _cslen); _cslen = 0; } #elif defined(LIBPLZMA_POSIX) syncUtf8(); if (_cs && _cslen > 0 && removeLastComp<char>(_cs, _cslen)) { const auto len = String::lengthMaxCount(_cs, static_cast<size_t>(plzma_max_size())); _ws.clear(plzma_erase_zero, sizeof(wchar_t) * _size); _cslen = static_cast<plzma_size_t>(len.first); _size = static_cast<plzma_size_t>(len.second); } #endif } Path Path::removingLastComponent() const { Path result(*this); result.removeLastComponent(); return result; } bool Path::exists(bool * LIBPLZMA_NULLABLE isDir /* = nullptr */) const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathExists<wchar_t>(wide(), isDir) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathExists<char>(utf8(), isDir) : false; #endif } bool Path::readable() const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathReadable<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathReadable<char>(utf8()) : false; #endif } bool Path::writable() const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathWritable<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathWritable<char>(utf8()) : false; #endif } bool Path::readableAndWritable() const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathReadableAndWritable<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathReadableAndWritable<char>(utf8()) : false; #endif } plzma_path_stat Path::stat() const { #if defined(LIBPLZMA_MSC) return pathStat<wchar_t>(wide()); #elif defined(LIBPLZMA_POSIX) return pathStat<char>(utf8()); #endif } bool Path::remove(const bool skipErrors) const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? removePath<wchar_t>(wide(), skipErrors) : true; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? removePath<char>(utf8(), skipErrors) : true; #endif } bool Path::createDir(const bool withIntermediates) const { if (withIntermediates) { #if defined(LIBPLZMA_MSC) return (_size > 0) ? createIntermediateDirs<wchar_t>(wide(), _size) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? createIntermediateDirs<char>(utf8(), _cslen) : false; #endif } #if defined(LIBPLZMA_MSC) return (_size > 0) ? createSingleDir<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? createSingleDir<char>(utf8()) : false; #endif } FILE * LIBPLZMA_NULLABLE Path::openFile(const char * LIBPLZMA_NONNULL mode) const { #if defined(LIBPLZMA_MSC) if (_size > 0) { wchar_t wmode[32] = { 0 }; // more than enough for a max mode: "w+b, ccs=UNICODE" for (size_t i = 0, n = strlen(mode); ((i < n) && (i < 31)); i++) { wmode[i] = static_cast<wchar_t>(mode[i]); } return _wfopen(wide(), wmode); } return nullptr; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? fopen(utf8(), mode) : nullptr; #endif } SharedPtr<Path::Iterator> Path::openDir(const plzma_open_dir_mode_t mode /* = 0 */ ) const { #if defined(LIBPLZMA_MSC) return SharedPtr<Path::Iterator>(new PathIteratorMSC(*this, mode)); #elif defined(LIBPLZMA_POSIX) return SharedPtr<Path::Iterator>(new PathIteratorPosix(*this, mode)); #endif } bool Path::operator == (const Path & path) const { #if defined(LIBPLZMA_MSC) return pathsAreEqual<wchar_t>(wide(), path.wide(), _size, path._size); #elif defined(LIBPLZMA_POSIX) return pathsAreEqual<char>(utf8(), path.utf8(), _cslen, path._cslen); #endif } Path & Path::operator = (Path && path) noexcept { moveFrom(static_cast<Path &&>(path), plzma_erase_zero); return *this; } Path::Path(Path && path) noexcept : String(static_cast<Path &&>(path)) { } Path & Path::operator = (const Path & path) { copyFrom(path, plzma_erase_zero); return *this; } Path::Path(const Path & path) : String(path) { } Path::Path(const wchar_t * LIBPLZMA_NULLABLE path) : String(path) { const auto reduced = normalize<wchar_t>(_ws); if (reduced > 0) { _size -= reduced; } } Path::Path(const char * LIBPLZMA_NULLABLE path) : String(path) { const auto reduced = normalize<char>(_cs); if (reduced > 0) { _size -= reduced; _cslen -= reduced; } } Path::~Path() noexcept { _ws.erase(plzma_erase_zero, sizeof(wchar_t) * _size); _cs.erase(plzma_erase_zero, sizeof(char) * _cslen); } #if !defined(PATH_MAX) #define PATH_MAX 1024 #endif Path Path::tmpPath() { Path path; #if defined(__APPLE__) && defined(_CS_DARWIN_USER_TEMP_DIR) char buff[PATH_MAX]; const size_t res = confstr(_CS_DARWIN_USER_TEMP_DIR, buff, PATH_MAX); if (res > 0 && res < PATH_MAX && initializeTmpPath<char>(buff, "libplzma", path)) { return path; } #endif #if defined(LIBPLZMA_MSC) static const wchar_t * const wevs[4] = { L"TMPDIR", L"TEMPDIR", L"TEMP", L"TMP" }; for (size_t i = 0; i < 4; i++) { const wchar_t * p = _wgetenv(wevs[i]); if (p && initializeTmpPath<wchar_t>(p, L"libplzma", path)) { return path; } } #endif static const char * const cevs[4] = { "TMPDIR", "TEMPDIR", "TEMP", "TMP" }; for (size_t i = 0; i < 4; i++) { char * p = getenv(cevs[i]); if (p && initializeTmpPath<char>(p, "libplzma", path)) { return path; } } #if !defined(LIBPLZMA_OS_WINDOWS) if (initializeTmpPath<char>("/tmp", "libplzma", path)) { return path; } #endif return Path(); } } // namespace plzma #include "plzma_c_bindings_private.hpp" #if !defined(LIBPLZMA_NO_C_BINDINGS) using namespace plzma; plzma_path plzma_path_create_with_wide_string(const wchar_t * LIBPLZMA_NULLABLE path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_TRY(plzma_path) createdCObject.object = static_cast<void *>(new Path(path)); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_create_with_utf8_string(const char * LIBPLZMA_NULLABLE path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_TRY(plzma_path) createdCObject.object = static_cast<void *>(new Path(path)); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_create_with_tmp_dir(void) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_TRY(plzma_path) auto tmp = Path::tmpPath(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(tmp))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_size_t plzma_path_count(const plzma_path * LIBPLZMA_NONNULL path) { return path->exception ? 0 : static_cast<const Path *>(path->object)->count(); } void plzma_path_set_wide_string(plzma_path * LIBPLZMA_NONNULL path, const wchar_t * LIBPLZMA_NULLABLE str) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->set(str); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } void plzma_path_set_utf8_string(plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NULLABLE str) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->set(str); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } void plzma_path_append_wide_component(plzma_path * LIBPLZMA_NONNULL path, const wchar_t * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->append(component); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_appending_wide_component(const plzma_path * LIBPLZMA_NONNULL path, const wchar_t * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->appending(component); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_append_utf8_component(plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->append(component); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_appending_utf8_component(const plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->appending(component); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_append_random_component(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->appendRandomComponent(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_appending_random_component(const plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->appendingRandomComponent(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } const wchar_t * LIBPLZMA_NULLABLE plzma_path_wide_string(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, nullptr) return static_cast<Path *>(path->object)->wide(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, nullptr) } const char * LIBPLZMA_NULLABLE plzma_path_utf8_string(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, nullptr) return static_cast<Path *>(path->object)->utf8(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, nullptr) } bool plzma_path_exists(plzma_path * LIBPLZMA_NONNULL path, bool * LIBPLZMA_NULLABLE isDir) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->exists(isDir); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } bool plzma_path_readable(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->readable(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } bool plzma_path_writable(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->writable(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } bool plzma_path_readable_and_writable(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->readableAndWritable(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } plzma_path_stat plzma_path_get_stat(plzma_path * LIBPLZMA_NONNULL path) { plzma_path_stat emptyStat{0, 0, 0, 0}; LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, emptyStat) return static_cast<Path *>(path->object)->stat(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, emptyStat) } void plzma_path_clear(plzma_path * LIBPLZMA_NONNULL path, const plzma_erase erase_type) { plzma_object_exception_release(path); static_cast<Path *>(path->object)->clear(erase_type); } bool plzma_path_remove(plzma_path * LIBPLZMA_NONNULL path, const bool skip_errors) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->remove(skip_errors); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } plzma_path plzma_path_last_component(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) auto comp = static_cast<Path *>(path->object)->lastComponent(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(comp))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_remove_last_component(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->removeLastComponent(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_removing_last_component(const plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->removingLastComponent(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } bool plzma_path_create_dir(plzma_path * LIBPLZMA_NONNULL path, const bool with_intermediates) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->createDir(with_intermediates); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } FILE * LIBPLZMA_NULLABLE plzma_path_open_file(plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NONNULL mode) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, nullptr) return static_cast<Path *>(path->object)->openFile(mode); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, nullptr) } plzma_path_iterator plzma_path_open_dir(plzma_path * LIBPLZMA_NONNULL path, const plzma_open_dir_mode_t mode) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path_iterator, path) auto it = static_cast<Path *>(path->object)->openDir(mode); createdCObject.object = static_cast<void *>(it.take()); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_release(plzma_path * LIBPLZMA_NULLABLE path) { plzma_object_exception_release(path); delete static_cast<Path *>(path->object); path->object = nullptr; } plzma_path plzma_path_iterator_component(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, iterator) auto comp = static_cast<const Path::Iterator *>(iterator->object)->component(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(comp))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_iterator_path(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, iterator) auto path = static_cast<const Path::Iterator *>(iterator->object)->path(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(path))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_iterator_full_path(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, iterator) auto fullPath = static_cast<const Path::Iterator *>(iterator->object)->fullPath(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(fullPath))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } bool plzma_path_iterator_is_dir(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { return iterator->exception ? false : static_cast<const Path::Iterator *>(iterator->object)->isDir(); } bool plzma_path_iterator_next(plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(iterator, false) return static_cast<Path::Iterator *>(iterator->object)->next(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(iterator, false) } void plzma_path_iterator_close(plzma_path_iterator * LIBPLZMA_NONNULL iterator) { if (!iterator->exception) { static_cast<Path::Iterator *>(iterator->object)->close(); } } void plzma_path_iterator_release(plzma_path_iterator * LIBPLZMA_NULLABLE iterator) { plzma_object_exception_release(iterator); SharedPtr<Path::Iterator> iteratorSPtr; iteratorSPtr.assign(static_cast<Path::Iterator *>(iterator->object)); iterator->object = nullptr; } #endif // # !LIBPLZMA_NO_C_BINDINGS
38.076754
170
0.607384
readdle
bf28e1de4bb0ce3a2e2cc31e0877d1c8cb2f539a
120
hpp
C++
libs/shared/itsuptoyou.hpp
zepadovani/generic-makefile-withlibs
5c8da8f87a23c414700013efd569339f3fb798e6
[ "Unlicense" ]
null
null
null
libs/shared/itsuptoyou.hpp
zepadovani/generic-makefile-withlibs
5c8da8f87a23c414700013efd569339f3fb798e6
[ "Unlicense" ]
null
null
null
libs/shared/itsuptoyou.hpp
zepadovani/generic-makefile-withlibs
5c8da8f87a23c414700013efd569339f3fb798e6
[ "Unlicense" ]
null
null
null
#ifndef ITSUPTOYOU_HPP_INCLUDED #define ITSUPTOYOU_HPP_INCLUDED void itsuptoyou( ); #endif // ITSUPTOYOU_HPP_INCLUDED
17.142857
33
0.833333
zepadovani
bf294b7bfce9d40ebb6da5882bfb8327b03fed87
10,021
cpp
C++
src/chip8.cpp
Akaito/csaru-chip8
b30d2de2fac5493d5da13d38571936dd21a25e36
[ "Zlib" ]
null
null
null
src/chip8.cpp
Akaito/csaru-chip8
b30d2de2fac5493d5da13d38571936dd21a25e36
[ "Zlib" ]
null
null
null
src/chip8.cpp
Akaito/csaru-chip8
b30d2de2fac5493d5da13d38571936dd21a25e36
[ "Zlib" ]
null
null
null
// This is *heavily* based on Laurence Muller's tutorial at // http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/ #include <cstdlib> #include <cstdio> #include <cstring> #include "../include/chip8.hpp" //===================================================================== // // Static locals // //===================================================================== //===================================================================== // XXXX ..X. // X..X .XX. // X..X ..x. // X..X ..x. // XXXX .xxx static const uint8_t s_fontSet[80] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80, // F }; //===================================================================== // // Chip8 definitions // //===================================================================== //===================================================================== void Chip8::Initialize (unsigned randSeed) { CSaruCore::SecureZero(m_memory, s_memoryBytes); CSaruCore::SecureZero(m_v, s_registerCount); m_i = 0x0000; m_pc = s_progRomRamBegin; m_delayTimer = 0; m_soundTimer = 0; CSaruCore::SecureZero(m_keyStates, s_keyCount); m_opcode = 0x0000; CSaruCore::SecureZero(m_stack, s_stackSize); m_sp = 0x00; CSaruCore::SecureZero(m_renderOut, s_renderWidth * s_renderHeight); m_drawFlag = false; // Load default Chip8 font. std::memcpy(m_memory + s_fontBegin, s_fontSet, sizeof(s_fontSet)); // TODO : Replace with a per-Chip8 random number generator. std::srand(randSeed); } //===================================================================== void Chip8::EmulateCycle () { // Fetch opcode. m_opcode = m_memory[m_pc] << 8 | m_memory[m_pc + 1]; // Prepare common portions of opcode. const uint8_t x = (m_opcode & 0x0F00) >> 8; uint8_t & vx = m_v[x]; const uint8_t y = (m_opcode & 0x00F0) >> 4; uint8_t & vy = m_v[y]; const uint8_t n = m_opcode & 0x000F; const uint8_t nn = m_opcode & 0x00FF; const uint16_t nnn = m_opcode & 0x0FFF; // Decode opcode // https://en.wikipedia.org/wiki/CHIP-8#Opcode_table if (m_opcode == 0x00E0) { // 0x00E0: clear the screen CSaruCore::SecureZero(m_renderOut, s_renderWidth * s_renderHeight); m_pc += 2; m_drawFlag = true; } else if (m_opcode == 0x00EE) { // 0x00EE: return from call if (m_sp <= 0) { std::fprintf( stderr, "Chip8: stack underflow; pc {0x%04X}.", m_pc ); } else m_pc = m_stack[--m_sp] + 2; } /* else if ((m_opcode & 0xF000) == 0x0000) { // 0x0NNN // call RCA 1802 program at NNN // TODO : jump, or call? m_pc = nnn; } */ else if ((m_opcode & 0xF000) == 0x1000) { // 0x1NNN: jump to NNN m_pc = nnn; } else if ((m_opcode & 0xF000) == 0x2000) { // 0x2NNN: call NNN if (m_sp >= s_stackSize) { std::fprintf( stderr, "Chip8: stack overflow; pc {0x%04X}.", m_pc ); } else { m_stack[m_sp++] = m_pc; m_pc = m_opcode & 0x0FFF; } } else if ((m_opcode & 0xF000) == 0x3000) { // 0x3XNN // skip next instruction if VX == NN m_pc += (vx == nn) ? 4 : 2; } else if ((m_opcode & 0xF000) == 0x4000) { // 0x4XNN // skip next instruction if VX != NN m_pc += (vx != nn) ? 4 : 2; } else if ((m_opcode & 0xF000) == 0x6000) { // 0x6XNN: set VX to NN vx = nn; m_pc += 2; } else if ((m_opcode & 0xF000) == 0x7000) { // 0x7XNN: add NN to VX vx += nn; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8000) { // 0x8XY0: set VX to VY vx = vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8001) { // 0x8XY1: VX = VX | VY vx |= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8002) { // 0x8XY2: VX = VX & VY vx &= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8003) { // 0x8003: VX = VX ^ VY vx ^= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8004) { // 0x8XY4 // add VY to VX; VF is set to 1 on carry, 0 otherwise. m_v[0xF] = ((vx + vy) < vx) ? 1 : 0; vx += vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8005) { // 0x8XY5: VX -= VY // VF is set to 0 on borrow; 1 otherwise. m_v[0xF] = (vy > vx) ? 0 : 1; vx -= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8006) { // 0x8XY6 // VX >>= 1; VF = least-significant bit before shift m_v[0xF] = vx & 0x01; vx >>= 1; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x800E) { // 0x8XYE // VX <<= 1; VF = most-significant bit before shift m_v[0xF] = vx & 0x80; vx <<= 1; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x9000) { // 0x9XY0 // skip next instruction if VX != VY m_pc += (vx != vy) ? 4 : 2; } else if ((m_opcode & 0xF000) == 0xA000) { // 0xANNN: I = NNN m_i = nnn; m_pc += 2; } else if ((m_opcode & 0xF000) == 0xB000) { // 0xBNNN: jump to MMM + V0 m_pc = nnn + m_v[0]; } else if ((m_opcode & 0xF000) == 0xC000) { // 0xCXNN: VX = (rand & NN) // TODO : Replace with a per-Chip8 random number generator. vx = std::rand() & nn; m_pc += 2; } else if ((m_opcode & 0xF000) == 0xD000) { // 0xDXYN // XOR-draw N rows of 8-bit-wide sprites from I // at (VX, VY), (VX, VY+1), etc. // VF set to 1 if a pixel is toggled off, otherwise 0. m_v[0xF] = 0x0; // clear collision flag for (unsigned spriteTexY = 0; spriteTexY < n; ++spriteTexY) { const uint8_t spriteByte = m_memory[ m_i + spriteTexY ]; for (unsigned spriteTexX = 0; spriteTexX < 8; ++spriteTexX) { // shift b1000'0000 right to current column if (spriteByte & (0x80 >> spriteTexX)) { // rendering wraps on all edges uint16_t pixelX = (vx + spriteTexX) % s_renderWidth; uint16_t pixelY = ((vy + spriteTexY) % s_renderHeight) * s_renderWidth; auto & renderPixel = m_renderOut[pixelY + pixelX]; if (renderPixel) { renderPixel = 0; m_v[0xF] = 0x1; // collision! set flag } else { renderPixel = 1; } } } } m_pc += 2; m_drawFlag = true; } else if ((m_opcode & 0xF0FF) == 0xE09E) { // 0xEX9E // skip next instruction if key at VX is pressed m_pc += (m_keyStates[vx]) ? 4 : 2; } else if ((m_opcode & 0xF0FF) == 0xE0A1) { // 0xEXA1 // skip next instruction if key at VX isn't pressed m_pc += (!m_keyStates[vx]) ? 4 : 2; } else if ((m_opcode & 0xF0FF) == 0xF007) { // 0xFX07: VX = delay vx = m_delayTimer; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF00A) { // 0xFX0A // wait for key press, then store in VX for (uint8_t key = 0x0; key < s_keyCount; ++key) { if (m_keyStates[key]) { m_v[ (m_opcode & 0x0F00) >> 8 ] = key; m_pc += 2; } } } else if ((m_opcode & 0xF0FF) == 0xF015) { // 0xFX15: delay = VX m_delayTimer = vx; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF018) { // 0xFX18 m_soundTimer = vx; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF01E) { // 0xFX1E: I += VX // undocumented: VF = 1 on overflow; 0 otherwise // (used by "Spaceflight 2091!") m_v[0xF] = (m_i + vx < m_i) ? 1 : 0; m_i += vx; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF029) { // 0xFX29 // set I to location of character VX m_i = s_fontBegin + (0xF & vx) * 5; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF033) { // 0xFX33 // store binary-coded decimal representation of VX in memory // 100s digit at I, 10s at I+1, 1s at I+2 // (I unchanged) m_memory[ m_i ] = vx / 100; m_memory[ m_i+1 ] = (vx / 10) % 10; m_memory[ m_i+2 ] = (vx % 100) % 10; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF055) { // 0xFX55 // store V0...VX in memory, starting at I for (uint8_t i = 0; i <= vx; ++i) m_memory[ m_i + i ] = m_v[i]; m_i += vx + 1; // From BYTE magazine code comment: (I = I + X + 1). m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF065) { // 0xFX65 // fill V0 to VX from memory starting at I for (uint8_t i = 0; i <= x; ++i) m_v[i] = m_memory[m_i + i]; m_i += x + 1; // From BYTE magazine code comment: (I = I + X + 1). m_pc += 2; } else { std::fprintf( stderr, "Chip8: Bad opcode {0x%04X} at {0x%04X} ({0x%04X}).\n", m_opcode, m_pc, m_pc - s_progRomRamBegin ); } // Update timers if (m_delayTimer) --m_delayTimer; if (m_soundTimer) { CSaruCore::Beep(); // beep the PC speaker --m_soundTimer; // play sound if non-zero std::printf(" -- beep! -- \n"); // temporary } } //===================================================================== bool Chip8::LoadProgram (const char * path) { std::FILE * progFile = std::fopen(path, "rb"); if (!progFile) { std::fprintf(stderr, "Chip8: Failed to open program file at {%s}.\n", path); return false; } std::size_t readCount = std::fread( m_memory + s_progRomRamBegin, 1, /* size of element to read (in bytes) */ s_progRomRamEnd - s_progRomRamBegin, /* number of element to read */ progFile ); fclose(progFile); if (!readCount) { std::fprintf(stderr, "Chip8: Failed to read from program file {%s}.\n", path); return false; } return true; }
29.130814
86
0.518312
Akaito
bf2c8bf4bc92893840806d84d0309123ed0e9d69
7,977
cpp
C++
src/renderer/resource_managers/model_manager.cpp
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
4
2017-10-04T11:38:48.000Z
2021-11-16T20:35:37.000Z
src/renderer/resource_managers/model_manager.cpp
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
4
2018-06-07T23:27:02.000Z
2018-10-18T12:19:57.000Z
src/renderer/resource_managers/model_manager.cpp
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
null
null
null
#include "model_manager.h" #include "core/file/blob.h" #include "core/parsing/json.h" #include "../renderer.h" namespace Veng { ResourceType Model::RESOURCE_TYPE("model"); static ResourceType MATERIAL_TYPE("material"); ModelManager::ModelManager(Allocator& allocator, FileSystem& fileSystem, DependencyManager* depManager) : ResourceManager(Model::RESOURCE_TYPE, allocator, fileSystem, depManager) {} ModelManager::~ModelManager() {} const char* const * ModelManager::GetSupportedFileExt() const { static const char* buffer[] = { "model" }; return buffer; } size_t ModelManager::GetSupportedFileExtCount() const { return 1; } void ModelManager::SetRenderSystem(RenderSystem* renderSystem) { m_renderSystem = renderSystem; } Resource* ModelManager::CreateResource() { Resource* res = NEW_OBJECT(m_allocator, Model)(m_allocator); return res; } void ModelManager::DestroyResource(Resource* resource) { Model* model = static_cast<Model*>(resource); for (Mesh& mesh : model->meshes) { m_renderSystem->DestroyMeshData(mesh.renderDataHandle); m_allocator.Deallocate(mesh.verticesData); m_allocator.Deallocate(mesh.indicesData); m_depManager->UnloadResource(MATERIAL_TYPE, static_cast<resourceHandle>(mesh.material)); } DELETE_OBJECT(m_allocator, model); } void ModelManager::ReloadResource(Resource* resource) { ASSERT2(false, "Not implemented yet"); } void ModelManager::ResourceLoaded(resourceHandle handle, InputBlob& data) { Model* model = static_cast<Model*>(GetResource(handle)); Mesh& mesh = model->meshes.PushBack(); mesh.type = Mesh::PrimitiveType::Triangles;//todo: read from mesh char errorBuffer[64] = { 0 }; JsonValue parsedJson; ASSERT(JsonParseError((char*)data.GetData(), &m_allocator, &parsedJson, errorBuffer)); ASSERT(JsonIsObject(&parsedJson)); JsonKeyValue* verticesData = JsonObjectFind(&parsedJson, "vertices"); if (verticesData != nullptr) { ASSERT(JsonIsObject(&verticesData->value)); JsonKeyValue* countJson = JsonObjectFind(&verticesData->value, "count"); ASSERT(countJson != nullptr && JsonIsInt(&countJson->value)); size_t count = (size_t)JsonGetInt(&countJson->value); if (count < MAX_U32) { mesh.verticesCount = (u32)count; } else { ASSERT2(false, "Too many vertices, limit is 2^32 - 1, clamped count to this number"); mesh.verticesCount = MAX_U32; } JsonKeyValue* positions = JsonObjectFind(&verticesData->value, "positions"); JsonKeyValue* colors = JsonObjectFind(&verticesData->value, "colors"); JsonKeyValue* texCoords = JsonObjectFind(&verticesData->value, "uvs"); JsonKeyValue* normals = JsonObjectFind(&verticesData->value, "normals"); JsonKeyValue* tangents = JsonObjectFind(&verticesData->value, "tangents"); JsonValue* positionArr = nullptr; JsonValue* colorsArr = nullptr; JsonValue* texCoordArr = nullptr; JsonValue* normalsArr = nullptr; JsonValue* tangentsArr = nullptr; size_t bufferSize = 0; if (positions != nullptr) { ASSERT(JsonIsArray(&positions->value) && JsonArrayCount(&positions->value) == count * 3); positionArr = JsonArrayBegin(&positions->value); bufferSize += 3 * count * sizeof(float); mesh.varyings |= ShaderVarying_Position; } if (colors != nullptr) { ASSERT(JsonIsArray(&colors->value) && JsonArrayCount(&colors->value) == count); colorsArr = JsonArrayBegin(&colors->value); bufferSize += 4 * count * sizeof(u8); mesh.varyings |= ShaderVarying_Color0; } if (texCoords != nullptr) { ASSERT(JsonIsArray(&texCoords->value) && JsonArrayCount(&texCoords->value) == count * 2); texCoordArr = JsonArrayBegin(&texCoords->value); bufferSize += 2 * count * sizeof(float); mesh.varyings |= ShaderVarying_Texcoords0; } if(normals != nullptr) { ASSERT(JsonIsArray(&normals->value) && JsonArrayCount(&normals->value) == count * 3); normalsArr = JsonArrayBegin(&normals->value); bufferSize += 3 * count * sizeof(float); mesh.varyings |= ShaderVarying_Normal; } if (tangents != nullptr) { ASSERT(JsonIsArray(&tangents->value) && JsonArrayCount(&tangents->value) == count * 3); tangentsArr = JsonArrayBegin(&tangents->value); bufferSize += 3 * count * sizeof(float); mesh.varyings |= ShaderVarying_Tangent; } mesh.verticesData = (u8*)m_allocator.Allocate(bufferSize, alignof(float)); u8* dataBuffer = mesh.verticesData; for (size_t i = 0; i < count; ++i) { if (positionArr != nullptr) { float* posBuffer = (float*)dataBuffer; *posBuffer = (float)JsonGetDouble(positionArr++); *(posBuffer + 1) = (float)JsonGetDouble(positionArr++); *(posBuffer + 2) = (float)JsonGetDouble(positionArr++); dataBuffer = (u8*)(posBuffer + 3); } if (colorsArr != nullptr) { u32* colBuffer = (u32*)dataBuffer; *colBuffer = (u32)JsonGetInt(colorsArr++); dataBuffer = (u8*)(colBuffer + 1); } if (texCoordArr != nullptr) { float* uvBuffer = (float*)dataBuffer; *uvBuffer = (float)JsonGetDouble(texCoordArr++); *(uvBuffer + 1) = (float)JsonGetDouble(texCoordArr++); dataBuffer = (u8*)(uvBuffer + 2); } if(normalsArr != nullptr) { float* normalBuffer = (float*)dataBuffer; *normalBuffer = (float)JsonGetDouble(normalsArr++); *(normalBuffer + 1) = (float)JsonGetDouble(normalsArr++); *(normalBuffer + 2) = (float)JsonGetDouble(normalsArr++); dataBuffer = (u8*)(normalBuffer + 3); } if (tangentsArr != nullptr) { float* tangentBuffer = (float*)dataBuffer; *tangentBuffer = (float)JsonGetDouble(tangentsArr++); *(tangentBuffer + 1) = (float)JsonGetDouble(tangentsArr++); *(tangentBuffer + 2) = (float)JsonGetDouble(tangentsArr++); dataBuffer = (u8*)(tangentBuffer + 3); } } } else { ASSERT2(false, "Missing vertex data"); mesh.verticesData = nullptr; } JsonKeyValue* indicesData = JsonObjectFind(&parsedJson, "indices"); if (indicesData != nullptr) { ASSERT(JsonIsObject(&indicesData->value)); JsonKeyValue* countJson = JsonObjectFind(&indicesData->value, "count"); ASSERT(countJson != nullptr && JsonIsInt(&countJson->value)); size_t count = (size_t)JsonGetInt(&countJson->value); if (count < MAX_U32) { mesh.indicesCount = (u32)count; } else { ASSERT2(false, "Too many indices, limit is 2^32 - 1, clamped count to this number"); mesh.indicesCount = MAX_U32; } count *= 3;//hard coded triangles here JsonKeyValue* indices = JsonObjectFind(&indicesData->value, "data"); ASSERT(JsonIsArray(&indices->value) && JsonArrayCount(&indices->value) == count); JsonValue* indexArr = JsonArrayBegin(&indices->value); mesh.indicesData = (u16*)m_allocator.Allocate(count * sizeof(u16), alignof(u16)); u16* dataBuffer = mesh.indicesData; for (size_t i = 0; i < count; ++i) { *dataBuffer = (u16)JsonGetInt(indexArr++); dataBuffer++; } } else { ASSERT2(false, "Missing indices"); mesh.indicesData = nullptr; } JsonKeyValue* material = JsonObjectFind(&parsedJson, "material"); if(material != nullptr) { ASSERT(JsonIsString(&material->value)); const char* materialRawStr = JsonGetString(&material->value); Path materialPath(materialRawStr); mesh.material = m_depManager->LoadResource(Model::RESOURCE_TYPE, MATERIAL_TYPE, materialPath); Resource* material = GetResource(mesh.material); if(material->GetState() == Resource::State::Ready || material->GetState() == Resource::State::Failure) { FinalizeModel(model); } } JsonDeinit(&parsedJson); mesh.renderDataHandle = m_renderSystem->CreateMeshData(mesh); } void ModelManager::ChildResourceLoaded(resourceHandle handle, ResourceType type) { for (auto& res : m_resources) { Model* model = static_cast<Model*>(res.value); if (model->meshes[0].material == handle) { FinalizeModel(model); } } } void ModelManager::FinalizeModel(Model* model) { model->SetState(Resource::State::Ready); m_depManager->ResourceLoaded(Model::RESOURCE_TYPE, GetResourceHandle(model)); } }
28.694245
104
0.701642
JakubLukas
bf2d73bf2b9cc2c1f7a96fdecad2f840fbd3ddb2
421
hpp
C++
source/ashes/renderer/TestRenderer/Command/Commands/TestBeginQueryCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/TestRenderer/Command/Commands/TestBeginQueryCommand.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/TestRenderer/Command/Commands/TestBeginQueryCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder */ #pragma once #include "renderer/TestRenderer/Command/Commands/TestCommandBase.hpp" namespace ashes::test { class BeginQueryCommand : public CommandBase { public: BeginQueryCommand( VkDevice device , VkQueryPool pool , uint32_t query , VkQueryControlFlags flags ); void apply()const override; CommandPtr clone()const override; }; }
17.541667
69
0.745843
DragonJoker
bf3166d2389ca3917d2b6707c9142288ae7209a1
9,289
inl
C++
Base/PLCore/include/PLCore/Container/HashMapKeyIterator.inl
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/include/PLCore/Container/HashMapKeyIterator.inl
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/include/PLCore/Container/HashMapKeyIterator.inl
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: HashMapKeyIterator.inl * * Hash map iterator template implementation * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLCore/Container/HashMap.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HashMapKeyIterator(const HashMap<KeyType, ValueType, Hasher, Comparer, Grower> &mapOwner, uint32 nIndex) : m_pmapOwner(&mapOwner), m_pNextSlot(nullptr), m_pPreviousSlot(nullptr) { // Is there at least one element within the hash map? (we do not need to check whether the slots are already created :) if (m_pmapOwner->GetNumOfElements()) { // Find start slot if (nIndex <= m_pmapOwner->GetNumOfElements()/2) { // Find the first slot for (m_nNextSlots=0; m_nNextSlots<m_pmapOwner->GetNumOfSlots(); m_nNextSlots++) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot) { // Ok, we found a slots list which has any slots within it m_pNextSlot = m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot; break; } } // Find the correct start slot m_nPreviousSlots = m_nNextSlots; m_pPreviousSlot = nullptr; uint32 nCurrentIndex = 0; while (HasNext() && nCurrentIndex < nIndex) { m_nPreviousSlots = m_nNextSlots; m_pPreviousSlot = m_pNextSlot; Next(); nCurrentIndex++; } } else { // Find the last slot m_nPreviousSlots = m_pmapOwner->GetNumOfSlots()-1; int nPreviousSlots = m_nPreviousSlots; for (; nPreviousSlots>=0; nPreviousSlots--) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot) { // Ok, we found a slots list which has any slots within it m_pPreviousSlot = m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot; break; } } m_nPreviousSlots = (nPreviousSlots < 0) ? 0 : nPreviousSlots; // Find the correct start slot m_nNextSlots = m_nPreviousSlots; m_pNextSlot = nullptr; uint32 nCurrentIndex = m_pmapOwner->GetNumOfElements()-1; while (HasPrevious() && nCurrentIndex > nIndex) { m_nNextSlots = m_nPreviousSlots; m_pNextSlot = m_pPreviousSlot; Previous(); nCurrentIndex--; } } } } /** * @brief * Constructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HashMapKeyIterator(const HashMap<KeyType, ValueType, Hasher, Comparer, Grower> &mapOwner) : m_pmapOwner(&mapOwner), m_pNextSlot(nullptr), m_pPreviousSlot(nullptr) { // Is there at least one element within the hash map? (we do not need to check whether the slots are already created :) if (m_pmapOwner->GetNumOfElements()) { // Find the last slot m_nPreviousSlots = m_pmapOwner->GetNumOfSlots()-1; int nPreviousSlots = m_nPreviousSlots; for (; nPreviousSlots>=0; nPreviousSlots--) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot) { // Ok, we found a slots list which has any slots within it m_pPreviousSlot = m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot; break; } } m_nPreviousSlots = (nPreviousSlots < 0) ? 0 : nPreviousSlots; // Find the correct start slot m_nNextSlots = m_nPreviousSlots; m_pNextSlot = nullptr; } } /** * @brief * Copy constructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HashMapKeyIterator(const HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower> &cSource) : m_pmapOwner(cSource.m_pmapOwner), m_nNextSlots(cSource.m_nNextSlots), m_pNextSlot(cSource.m_pNextSlot), m_nPreviousSlots(cSource.m_nPreviousSlots), m_pPreviousSlot(cSource.m_pPreviousSlot) { } /** * @brief * Destructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::~HashMapKeyIterator() { } //[-------------------------------------------------------] //[ Private virtual IteratorImpl functions ] //[-------------------------------------------------------] template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> IteratorImpl<KeyType> *HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::Clone() const { return new HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>(*this); } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> bool HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HasNext() const { return (m_pNextSlot != nullptr); } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> KeyType &HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::Next() { // Is there's a next slot? if (!m_pNextSlot) return HashMap<KeyType, ValueType, Hasher, Comparer, Grower>::NullKey; // Error! // Get the next slot m_nPreviousSlots = m_nNextSlots; m_pPreviousSlot = m_pNextSlot; m_pNextSlot = m_pNextSlot->pNextSlot; // Is there a next slot? if (!m_pNextSlot && m_nNextSlots < m_pmapOwner->GetNumOfSlots()-1) { // Ok, now it becomes a bit tricky... look for the next slots list which has any slots within it m_nNextSlots++; for (; m_nNextSlots<m_pmapOwner->GetNumOfSlots(); m_nNextSlots++) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot) { // Ok, we found a slots list which has any slots within it m_pNextSlot = m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot; break; } } } // Return the key of the 'current' slot return m_pPreviousSlot->Key; } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> bool HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HasPrevious() const { return (m_pPreviousSlot != nullptr); } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> KeyType &HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::Previous() { // Is there's a previous slot? if (!m_pPreviousSlot) return HashMap<KeyType, ValueType, Hasher, Comparer, Grower>::NullKey; // Error! // Get the previous slot m_nNextSlots = m_nPreviousSlots; m_pNextSlot = m_pPreviousSlot; m_pPreviousSlot = m_pPreviousSlot->pPreviousSlot; // Is there a previous slot? if (!m_pPreviousSlot && m_nPreviousSlots > 0) { // Ok, now it becomes a bit tricky... look for the previous slots list which has any slots within it int nPreviousSlots; m_nPreviousSlots--; for (nPreviousSlots=m_nPreviousSlots; nPreviousSlots>=0; nPreviousSlots--) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot) { // Ok, we found a slots list which has any slots within it m_pPreviousSlot = m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot; break; } } m_nPreviousSlots = (nPreviousSlots < 0) ? 0 : nPreviousSlots; } // Return the key of the 'current' slot return m_pNextSlot->Key; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
37.760163
172
0.659705
ktotheoz
bf336c1c43956c888f5aec54109deeec9b052c61
4,196
cpp
C++
box2dweldjoint.cpp
folibis/qml-box2d
b564712492a2c5c9e8bdfbe2ba09a6e8cbbe7d54
[ "Zlib" ]
null
null
null
box2dweldjoint.cpp
folibis/qml-box2d
b564712492a2c5c9e8bdfbe2ba09a6e8cbbe7d54
[ "Zlib" ]
null
null
null
box2dweldjoint.cpp
folibis/qml-box2d
b564712492a2c5c9e8bdfbe2ba09a6e8cbbe7d54
[ "Zlib" ]
null
null
null
/* * box2dweldjoint.cpp * Copyright (c) 2011 Joonas Erkinheimo <[email protected]> * * This file is part of the Box2D QML plugin. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "box2dweldjoint.h" #include "box2dworld.h" #include "box2dbody.h" Box2DWeldJoint::Box2DWeldJoint(QObject *parent) : Box2DJoint(parent), mWeldJoint(0), anchorsAuto(true) { } Box2DWeldJoint::~Box2DWeldJoint() { cleanup(world()); } float Box2DWeldJoint::referenceAngle() const { return mWeldJointDef.referenceAngle; } void Box2DWeldJoint::setReferenceAngle(float referenceAngle) { float referenceAngleRad = referenceAngle * b2_pi / -180; if (qFuzzyCompare(mWeldJointDef.referenceAngle, referenceAngleRad)) return; mWeldJointDef.referenceAngle = referenceAngleRad; emit referenceAngleChanged(); } float Box2DWeldJoint::frequencyHz() const { return mWeldJointDef.frequencyHz; } void Box2DWeldJoint::setFrequencyHz(float frequencyHz) { if (qFuzzyCompare(mWeldJointDef.frequencyHz, frequencyHz)) return; mWeldJointDef.frequencyHz = frequencyHz; if (mWeldJoint) mWeldJoint->SetFrequency(frequencyHz); emit frequencyHzChanged(); } float Box2DWeldJoint::dampingRatio() const { return mWeldJointDef.dampingRatio; } void Box2DWeldJoint::setDampingRatio(float dampingRatio) { if (qFuzzyCompare(mWeldJointDef.dampingRatio, dampingRatio)) return; mWeldJointDef.dampingRatio = dampingRatio; if (mWeldJoint) mWeldJoint->SetDampingRatio(dampingRatio); emit dampingRatioChanged(); } QPointF Box2DWeldJoint::localAnchorA() const { return QPointF(mWeldJointDef.localAnchorA.x * scaleRatio, -mWeldJointDef.localAnchorA.y * scaleRatio); } void Box2DWeldJoint::setLocalAnchorA(const QPointF &localAnchorA) { mWeldJointDef.localAnchorA = b2Vec2(localAnchorA.x() / scaleRatio,-localAnchorA.y() / scaleRatio); anchorsAuto = false; emit localAnchorAChanged(); } QPointF Box2DWeldJoint::localAnchorB() const { return QPointF(mWeldJointDef.localAnchorB.x * scaleRatio, -mWeldJointDef.localAnchorB.y * scaleRatio); } void Box2DWeldJoint::setLocalAnchorB(const QPointF &localAnchorB) { mWeldJointDef.localAnchorB = b2Vec2(localAnchorB.x() / scaleRatio,-localAnchorB.y() / scaleRatio); anchorsAuto = false; emit localAnchorBChanged(); } void Box2DWeldJoint::nullifyJoint() { mWeldJoint = 0; } void Box2DWeldJoint::createJoint() { if (anchorsAuto) mWeldJointDef.Initialize(bodyA()->body(), bodyB()->body(),bodyA()->body()->GetWorldCenter()); else { mWeldJointDef.bodyA = bodyA()->body(); mWeldJointDef.bodyB = bodyB()->body(); } mWeldJointDef.collideConnected = collideConnected(); mWeldJoint = static_cast<b2WeldJoint*> (world()->CreateJoint(&mWeldJointDef)); mWeldJoint->SetUserData(this); mInitializePending = false; emit created(); } void Box2DWeldJoint::cleanup(b2World *world) { if (!world) { qWarning() << "WeldJoint: There is no world connected"; return; } if (mWeldJoint && bodyA() && bodyB()) { mWeldJoint->SetUserData(0); world->DestroyJoint(mWeldJoint); mWeldJoint = 0; } } b2Joint *Box2DWeldJoint::joint() const { return mWeldJoint; }
27.070968
102
0.709009
folibis
bf342d66f2b1af88dfd27c9857a3b310ee6f330c
780
cpp
C++
Raven.CppClient.Tests/CanGetBuildNumberTest.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient.Tests/CanGetBuildNumberTest.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient.Tests/CanGetBuildNumberTest.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
#include "pch.h" #include "RavenTestDriver.h" #include "raven_test_definitions.h" #include "MaintenanceOperationExecutor.h" #include "GetBuildNumberOperation.h" namespace ravendb::client::tests::client::documents::commands { class CanGetBuildNumberTest : public driver::RavenTestDriver { protected: void customise_store(std::shared_ptr<ravendb::client::documents::DocumentStore> store) override { //store->set_before_perform(infrastructure::set_for_fiddler); } }; TEST_F(CanGetBuildNumberTest, CanGetBuildNumber) { auto store = get_document_store(TEST_NAME); auto build_number = store->maintenance()->server()->send(serverwide::operations::GetBuildNumberOperation()); ASSERT_TRUE(build_number); ASSERT_FALSE(build_number->product_version.empty()); } }
27.857143
110
0.778205
mlawsonca
bf3d26bbed40fcdc015a95d6113f6f6785b9e6b6
574
cpp
C++
src/bug_01.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_01.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_01.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
#include "advent.h" void BugFix<1>::solve1st() { std::string input; std::getline(*mIn, input); int repeatsSum = 0; for (size_t i = 0; i <= input.size(); ++i) { if (input[i] == input[(i + 1) % input.size()]) repeatsSum += input[i] - '0'; } *mOut << repeatsSum << std::endl; } void BugFix<1>::solve2nd() { std::string input; std::getline(*mIn, input); int repeatsSum = 0; for (size_t i = 0; i <= input.size(); ++i) { if (input[i] == input[(i + input.size() / 2) % input.size()]) repeatsSum += input[i] - '0'; } *mOut << repeatsSum << std::endl; }
18.516129
63
0.559233
happanda
bf440988370b8e4e7597f6cc29eadafaad586aa7
1,100
cpp
C++
virtual-base-class.cpp
rsds8540/cpp-solved-problems
cbd63e0743d7653d8e06401026c16aa1dd5f775b
[ "Apache-2.0" ]
1
2021-04-27T18:23:05.000Z
2021-04-27T18:23:05.000Z
virtual-base-class.cpp
rsds8540/cpp-solved-problems
cbd63e0743d7653d8e06401026c16aa1dd5f775b
[ "Apache-2.0" ]
null
null
null
virtual-base-class.cpp
rsds8540/cpp-solved-problems
cbd63e0743d7653d8e06401026c16aa1dd5f775b
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class student { protected: int roll; public: void setroll(int r) { roll = r; } void getroll() { cout << "Roll No." << roll << endl; } }; class test : virtual public student { protected: float che, phy; public: void setmarks(float c, float p) { che = c; phy = p; } void getmarks() { cout<<"Marks in Phy and Che are "<<phy<<" and "<<che<<endl; } }; class sports: virtual public student { protected: int score; public: void setscore(int s) { score = s; } void getscore() { cout<<"Score is "<<score<<endl; } }; class result : public test,public sports { protected: float res; public: void display() { getroll(); getmarks(); getscore(); cout<<"Your total result is "<<(res+score+che+phy)<<endl; } }; int main() { result rohit; rohit.setroll(54); rohit.setmarks(63,62); rohit.setscore(78); rohit.display(); return 0; }
14.285714
67
0.519091
rsds8540
bf44380203645d8829ff51d0c1aaa496b20ab063
257
cpp
C++
examples/03_module/06_value_and_reference_params/sample_value_ref.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri
91322930bedf6897b6244c778c707231560ccb15
[ "MIT" ]
null
null
null
examples/03_module/06_value_and_reference_params/sample_value_ref.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri
91322930bedf6897b6244c778c707231560ccb15
[ "MIT" ]
null
null
null
examples/03_module/06_value_and_reference_params/sample_value_ref.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri
91322930bedf6897b6244c778c707231560ccb15
[ "MIT" ]
null
null
null
#include "sample_value_ref.h" // void pass_by_val_and_ref(int num1, int & num2, const int & num3) { num1 = 20; // modifying this value is local to function num2 = 50; // modifying this value will change caller variable //num3 = 100; can't be modified }
25.7
64
0.712062
acc-cosc-1337-spring-2019
bf44bc72b3fd86735b662c04470c43fabd94984a
5,271
hpp
C++
Query/GpDbQueryRes.hpp
ITBear/GpDbClient
877f1fba2816509d06c8c798fbc788a706859644
[ "Apache-2.0" ]
null
null
null
Query/GpDbQueryRes.hpp
ITBear/GpDbClient
877f1fba2816509d06c8c798fbc788a706859644
[ "Apache-2.0" ]
null
null
null
Query/GpDbQueryRes.hpp
ITBear/GpDbClient
877f1fba2816509d06c8c798fbc788a706859644
[ "Apache-2.0" ]
null
null
null
#pragma once #include "GpDbQueryResState.hpp" namespace GPlatform { class GPDBCLIENT_API GpDbQueryRes { public: CLASS_REMOVE_CTRS_MOVE_COPY(GpDbQueryRes) CLASS_DECLARE_DEFAULTS(GpDbQueryRes) using StateTE = GpDbQueryResState::EnumT; public: GpDbQueryRes (void) noexcept; virtual ~GpDbQueryRes (void) noexcept; virtual void Clear (void) = 0; [[nodiscard]] virtual StateTE State (void) const = 0; [[nodiscard]] virtual count_t RowsCount (void) const = 0; [[nodiscard]] virtual count_t ColumnsCount (void) const = 0; [[nodiscard]] virtual s_int_16 GetInt16 (const count_t aRowId, const count_t aColId, std::optional<s_int_16> aOnNullValue) const = 0; [[nodiscard]] virtual s_int_32 GetInt32 (const count_t aRowId, const count_t aColId, std::optional<s_int_32> aOnNullValue) const = 0; [[nodiscard]] virtual s_int_64 GetInt64 (const count_t aRowId, const count_t aColId, std::optional<s_int_64> aOnNullValue) const = 0; [[nodiscard]] virtual std::string_view GetStr (const count_t aRowId, const count_t aColId, std::optional<std::string_view> aOnNullValue) const = 0; [[nodiscard]] virtual GpRawPtrCharRW GetStrRW (const count_t aRowId, const count_t aColId, std::optional<GpRawPtrCharRW> aOnNullValue) = 0; [[nodiscard]] virtual const GpVector<std::string>& GetStrArray (const count_t aRowId, const count_t aColId, std::optional<std::string_view> aOnNullValue) const = 0; [[nodiscard]] virtual std::string_view GetJsonStr (const count_t aRowId, const count_t aColId, std::optional<std::string_view> aOnNullValue) const = 0; [[nodiscard]] virtual GpRawPtrCharRW GetJsonStrRW (const count_t aRowId, const count_t aColId, std::optional<GpRawPtrCharRW> aOnNullValue) = 0; [[nodiscard]] virtual GpUUID GetUUID (const count_t aRowId, const count_t aColId, std::optional<GpUUID> aOnNullValue) const = 0; [[nodiscard]] virtual GpRawPtrByteR GetBLOB (const count_t aRowId, const count_t aColId, std::optional<GpRawPtrByteR> aOnNullValue) const = 0; [[nodiscard]] virtual bool GetBoolean (const count_t aRowId, const count_t aColId, std::optional<bool> aOnNullValue) const = 0; template<typename T> [[nodiscard]] typename T::EnumT GetEnum (const count_t aRowId, const count_t aColId, std::optional<typename T::EnumT> aOnNullValue) const; }; template<typename T> [[nodiscard]] typename T::EnumT GpDbQueryRes::GetEnum (const count_t aRowId, const count_t aColId, std::optional<typename T::EnumT> aOnNullValue) const { std::string_view strVal = GetStr(aRowId, aColId, ""_sv); if (strVal.length() == 0) { THROW_GPE_COND ( aOnNullValue.has_value(), [&](){return "Value on ["_sv + aRowId + ", "_sv + aColId + "] is empty"_sv;} ); return aOnNullValue.value(); } return T::SFromString(strVal); } }//GPlatform
46.646018
113
0.393474
ITBear
bf49f09b76323dfb7f009f5a507f3ac43b6365e5
2,650
hpp
C++
include/kmeans/InitializeRandom.hpp
LTLA/CppKmeans
924ea37c55edbfbd2aacd3c55954d167f15a7922
[ "MIT" ]
2
2021-07-22T03:01:49.000Z
2021-11-11T11:07:30.000Z
include/kmeans/InitializeRandom.hpp
LTLA/CppKmeans
924ea37c55edbfbd2aacd3c55954d167f15a7922
[ "MIT" ]
3
2021-07-21T07:37:16.000Z
2022-02-15T06:55:38.000Z
vendor/kmeans/InitializeRandom.hpp
kojix2/umap
92404e3afe312393fb849227e0d6e91ad4355d8d
[ "MIT" ]
1
2021-11-12T22:02:46.000Z
2021-11-12T22:02:46.000Z
#ifndef KMEANS_INITIALIZE_RANDOM_HPP #define KMEANS_INITIALIZE_RANDOM_HPP #include <algorithm> #include <cstdint> #include <random> #include "Base.hpp" #include "random.hpp" /** * @file InitializeRandom.hpp * * @brief Class for random initialization. */ namespace kmeans { /** * @cond */ template<class V, typename DATA_t> void copy_into_array(const V& chosen, int ndim, const DATA_t* in, DATA_t* out) { for (auto c : chosen) { auto ptr = in + c * ndim; std::copy(ptr, ptr + ndim, out); out += ndim; } return; } /** * @endcond */ /** * @brief Initialize starting points by sampling random observations without replacement. * * @tparam DATA_t Floating-point type for the data and centroids. * @tparam CLUSTER_t Integer type for the cluster index. * @tparam INDEX_t Integer type for the observation index. */ template<typename DATA_t = double, typename CLUSTER_t = int, typename INDEX_t = int> class InitializeRandom : public Initialize<DATA_t, CLUSTER_t, INDEX_t> { public: /** * @brief Default parameter settings. */ struct Defaults { /** * See `set_seed()` for more details. */ static constexpr uint64_t seed = 6523u; }; /** * @param Random seed to use to construct the PRNG prior to sampling. * * @return A reference to this `InitializeRandom` object. */ InitializeRandom& set_seed(uint64_t s = Defaults::seed) { seed = s; return *this; } private: uint64_t seed = Defaults::seed; public: /* * @param ndim Number of dimensions. * @param nobs Number of observations. * @param data Pointer to an array where the dimensions are rows and the observations are columns. * Data should be stored in column-major format. * @param ncenters Number of centers to pick. * @param[out] centers Pointer to a `ndim`-by-`ncenters` array where columns are cluster centers and rows are dimensions. * On output, this will contain the final centroid locations for each cluster. * Data should be stored in column-major order. * @param clusters Ignored in this method. * * @return `centers` is filled with the new cluster centers. * The number of filled centers is returned, see `Initializer::run()`. */ CLUSTER_t run(int ndim, INDEX_t nobs, const DATA_t* data, CLUSTER_t ncenters, DATA_t* centers, CLUSTER_t* clusters) { std::mt19937_64 eng(seed); auto chosen = sample_without_replacement(nobs, ncenters, eng); copy_into_array(chosen, ndim, data, centers); return chosen.size(); } }; } #endif
28.804348
126
0.663019
LTLA
bf4ba4442addcd0775e1ac38a7f2bde3cee63fb7
10,521
cpp
C++
dsr_emeraldenvysrc/src/intro.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
20
2017-12-12T16:37:25.000Z
2022-02-19T10:35:46.000Z
dsr_emeraldenvysrc/src/intro.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
null
null
null
dsr_emeraldenvysrc/src/intro.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
7
2017-12-29T23:19:18.000Z
2021-08-17T09:53:15.000Z
//--------------------------------------------------------------------------// // iq / rgba . tiny codes . 2008 // //--------------------------------------------------------------------------// #define WIN32_LEAN_AND_MEAN #define WIN32_EXTRA_LEAN #include <windows.h> #include <mmsystem.h> #include <GL/gl.h> #include <math.h> #include "config.h" #include "ext.h" #include "shaders/fsh_rayt.inl" #include "shaders/vsh_2d.inl" #include "fp.h" #include "sync/sync.h" #include "sync.h" #include "emerald.h" struct sync_device *rocket; const struct sync_track *fades_rocket; const struct sync_track *sync_rocket; const struct sync_track *shader_rocket; const struct sync_track *snarehit1_rocket; const struct sync_track *snarehit2_rocket; const struct sync_track *colordistort_rocket; const struct sync_track * stripcnt_rocket; const struct sync_track * stripintense_rocket; const struct sync_track * striptransintense_rocket; const struct sync_track * striprgbdistort_rocket; //================================================================================================================= static void initShader( int *pid, const char *vs, const char *fs ) { pid[0] = oglCreateProgram(); const int vsId = oglCreateShader( GL_VERTEX_SHADER ); const int fsId = oglCreateShader( GL_FRAGMENT_SHADER ); oglShaderSource( vsId, 1, &vs, 0 ); oglShaderSource( fsId, 1, &fs, 0 ); oglCompileShader( vsId ); oglCompileShader( fsId ); oglAttachShader( pid[0], fsId ); oglAttachShader( pid[0], vsId ); oglLinkProgram( pid[0] ); #ifdef DEBUG int result; char info[1536]; oglGetObjectParameteriv( vsId, GL_OBJECT_COMPILE_STATUS_ARB, &result ); oglGetInfoLog( vsId, 1024, NULL, (char *)info ); if( !result ) DebugBreak(); oglGetObjectParameteriv( fsId, GL_OBJECT_COMPILE_STATUS_ARB, &result ); oglGetInfoLog( fsId, 1024, NULL, (char *)info ); if( !result ) DebugBreak(); oglGetObjectParameteriv( pid[0], GL_OBJECT_LINK_STATUS_ARB, &result ); oglGetInfoLog( pid[0], 1024, NULL, (char*)info ); if( !result ) DebugBreak(); #endif } #ifndef WAVE_FORMAT_PCM # define WAVE_FORMAT_PCM 0x0001 #endif #ifndef WAVE_FORMAT_IEEE_FLOAT # define WAVE_FORMAT_IEEE_FLOAT 0x0003 #endif #ifndef WAVE_FORMAT_EXTENSIBLE # define WAVE_FORMAT_EXTENSIBLE 0xfffe #endif SAMPLE_TYPE lpSoundBuffer[MAX_SAMPLES * 2]; HWAVEOUT hWaveOut; #pragma data_seg(".wavefmt") WAVEFORMATEX WaveFMT = { #ifdef FLOAT_32BIT WAVE_FORMAT_IEEE_FLOAT, #else WAVE_FORMAT_PCM, #endif 2, // channels SAMPLE_RATE, // samples per sec SAMPLE_RATE*sizeof(SAMPLE_TYPE) * 2, // bytes per sec sizeof(SAMPLE_TYPE) * 2, // block alignment; sizeof(SAMPLE_TYPE) * 8, // bits per sample 0 // extension not needed }; #pragma data_seg(".wavehdr") WAVEHDR WaveHDR = { (LPSTR)lpSoundBuffer, MAX_SAMPLES*sizeof(SAMPLE_TYPE) * 2, // MAX_SAMPLES*sizeof(float)*2(stereo) 0, 0, 0, 0, 0, 0 }; MMTIME MMTime = { TIME_SAMPLES, 0 }; #pragma code_seg(".initsnd") void InitSound() { // thx to xTr1m/blu-flame for providing a smarter and smaller way to create the thread :) CreateThread(0, 0, (LPTHREAD_START_ROUTINE)_4klang_render, lpSoundBuffer, 0, 0); //_4klang_render(lpSoundBuffer); waveOutOpen(&hWaveOut, WAVE_MAPPER, &WaveFMT, NULL, 0, CALLBACK_NULL); waveOutPrepareHeader(hWaveOut, &WaveHDR, sizeof(WaveHDR)); waveOutWrite(hWaveOut, &WaveHDR, sizeof(WaveHDR)); } //================================================================================================================= //shader 1 - creditsintro_frag //shader 2 - pillars_frag //shader 3 - circular/maze2_frag //shader 4 - ballmaze1_frag //shader 5 - ballmaze2_frag static int pid[6]; static int vhs_shader; static int distort_shader; GLuint vhs_texture; //================================================================================================================= int intro_init( void ) { if( !EXT_Init() ) return( 0 ); initShader( &pid[0], raymarch_vert, creditsintro_frag ); initShader(&pid[1], raymarch_vert, pillars_frag); initShader(&pid[2], raymarch_vert, circular_frag); initShader(&pid[3], raymarch_vert, ballmaze1_frag); initShader(&pid[4], raymarch_vert, ballmaze2_frag); initShader(&pid[5], raymarch_vert, ballmaze3_frag); initShader(&vhs_shader, vhs_vert, vhs_frag); initShader(&distort_shader,vhs_vert, image_distort); Resize(XRES, YRES); vhs_texture = init_rendertexture(XRES, YRES); rocket = sync_create_device("sync"); #ifndef DEBUG rocket = sync_create_device("sync"); fades_rocket = sync_get_track_mem(rocket, "fade", sync_fade_data, sizeof(sync_fade_data)); shader_rocket = sync_get_track_mem(rocket, "shadernum", sync_shadernum_data, sizeof(sync_shadernum_data)); sync_rocket = sync_get_track_mem(rocket, "sync", sync_sync_data, sizeof(sync_sync_data)); snarehit1_rocket = sync_get_track_mem(rocket, "snarehit1", sync_snarehit1_data, sizeof(sync_snarehit1_data)); snarehit2_rocket =sync_get_track_mem(rocket, "snarehit2", sync_snarehit2_data, sizeof(sync_snarehit2_data)); colordistort_rocket=sync_get_track_mem(rocket, "colordistort", sync_colordistort_data, sizeof(sync_colordistort_data)); stripcnt_rocket = sync_get_track_mem(rocket, "strp_cnt", sync_strp_cnt_data, sizeof(sync_strp_cnt_data)); stripintense_rocket = sync_get_track_mem(rocket, "strp_intens", sync_strp_intens_data, sizeof(sync_strp_intens_data)); striptransintense_rocket = sync_get_track_mem(rocket, "strp_trnsinst", sync_strp_trnsinst_data, sizeof(sync_strp_trnsinst_data)); striprgbdistort_rocket = sync_get_track_mem(rocket, "rgb_distort", sync_rgb_distort_data, sizeof(sync_rgb_distort_data)); #else if (sync_connect(rocket, "localhost", SYNC_DEFAULT_PORT)) { return 0; } fades_rocket = sync_get_track(rocket, "fade"); sync_rocket = sync_get_track(rocket, "sync"); shader_rocket = sync_get_track(rocket, "shadernum"); snarehit1_rocket = sync_get_track(rocket, "snarehit1"); snarehit2_rocket = sync_get_track(rocket, "snarehit2"); colordistort_rocket = sync_get_track(rocket, "colordistort"); stripcnt_rocket = sync_get_track(rocket, "strp_cnt"); stripintense_rocket = sync_get_track(rocket, "strp_intens"); striptransintense_rocket = sync_get_track(rocket, "strp_trnsinst"); striprgbdistort_rocket = sync_get_track(rocket, "rgb_distort"); #endif InitSound(); return 1; } //================================================================================================================= int intro_do( long time ) { //--- update parameters ----------------------------------------- static long lastTime = timeGetTime(); long currTime = timeGetTime(); static double delta = 0.0; long diff = currTime - lastTime; delta = diff; lastTime = currTime; static float sceneTime = 0; sceneTime += (float)delta / 1000.f; waveOutGetPosition(hWaveOut, &MMTime, sizeof(MMTIME)); static float synctime = 0.0; double row = synctime * 5.0; synctime += (float)delta / 1000.f; int rowtimes = (int)floor(row); if (rowtimes > 1049) return 1; #ifndef SYNC_PLAYER if (sync_update(rocket, (int)floor(row), NULL, NULL)) sync_connect(rocket, "localhost", SYNC_DEFAULT_PORT); #endif float fade_f = sync_get_val(fades_rocket, row); float sync_f = sync_get_val(sync_rocket, row); float shader_f = sync_get_val(shader_rocket, row); float stripcnt_f = sync_get_val(stripcnt_rocket, row); float stripintense_f = sync_get_val(stripintense_rocket, row); float striptransintense_f = sync_get_val(striptransintense_rocket, row); float striprgbdistort_f = sync_get_val(striprgbdistort_rocket, row); float snarehit1_f = 0; float snarehit2_f = 0; float colordistort_f =1.0; //1 - snare 2 - bassline 3 - flanger bass 4 - lead voice 5 - hi - hat 6 - bass drum float aha = (&_4klang_envelope_buffer)[((MMTime.u.sample >> 8) << 5) + 2 * 0 + 0]; int aha1 = (&_4klang_note_buffer)[((MMTime.u.sample >> 8) << 5) + 2 *0 + 0]; if (aha1 && aha > 0.55) { snarehit1_f = 1.0f; colordistort_f = 1.0; } if (!aha1 || aha < 0.55) { snarehit1_f = 0.0f; colordistort_f = 0.0; } const float fade = fade_f; const float sync = sync_f; const float t = sceneTime; int fragnum = shader_f; //--- render ----------------------------------------- float res[2] = { (float)XRES, (float)YRES }; glClear(GL_COLOR_BUFFER_BIT); oglUseProgram( pid[fragnum] ); oglUniform2fv(oglGetUniformLocation(pid[fragnum], "resolution"), 1, res); oglUniform1fv(oglGetUniformLocation(pid[fragnum], "time"), 1, &t); oglUniform1fv(oglGetUniformLocation(pid[fragnum], "fade"), 1, &fade); oglUniform1fv(oglGetUniformLocation(pid[fragnum], "sync"), 1, &sync); glRects( -1, -1, 1, 1 ); oglUseProgram(0); //copy tex to image for postproc glBindTexture(GL_TEXTURE_2D, vhs_texture); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, XRES, YRES); glBindTexture(GL_TEXTURE_2D, 0); GLuint shadertexture; oglUseProgram(distort_shader); oglActiveTextureARB(GL_TEXTURE0_ARB); shadertexture = oglGetUniformLocation(distort_shader, "tex"); oglUniform2fv(oglGetUniformLocation(distort_shader, "resolution"), 1, res); oglUniform1fv(oglGetUniformLocation(distort_shader, "time"), 1, &t); oglUniform1fv(oglGetUniformLocation(distort_shader, "strp_cnt"), 1, &stripcnt_f); oglUniform1fv(oglGetUniformLocation(distort_shader, "strp_intens"), 1, &stripintense_f); oglUniform1fv(oglGetUniformLocation(distort_shader, "strp_trnsinst"), 1, &striptransintense_f); oglUniform1fv(oglGetUniformLocation(distort_shader, "rgb_distort"), 1, &striprgbdistort_f); oglUniform1i(shadertexture, 0); draw_fbotexture(vhs_texture, XRES, YRES); oglUseProgram(0); glBindTexture(GL_TEXTURE_2D, vhs_texture); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, XRES, YRES); glBindTexture(GL_TEXTURE_2D, 0); //do vhs shader oglUseProgram(vhs_shader); oglActiveTextureARB(GL_TEXTURE0_ARB); shadertexture = oglGetUniformLocation(vhs_shader, "tex"); oglUniform2fv(oglGetUniformLocation(vhs_shader, "resolution"), 1, res); oglUniform1fv(oglGetUniformLocation(vhs_shader, "time"), 1, &t); oglUniform1fv(oglGetUniformLocation(vhs_shader, "snarehit"), 1, &snarehit1_f); oglUniform1fv(oglGetUniformLocation(vhs_shader, "snarehit2"), 1, &snarehit2_f); oglUniform1fv(oglGetUniformLocation(vhs_shader, "colordistort"), 1, &colordistort_f); oglUniform1i(shadertexture, 0); draw_fbotexture(vhs_texture, XRES, YRES); oglUseProgram(0); return 0; }
34.495082
160
0.690999
mudlord
bf4c4c29603944e5e62b8379a721ae33c6959824
2,017
cpp
C++
Solutions/Ch7/7-16 Vector Modification.cpp
menarus/C-Course
ac56ec4215a69f6a755e766b9d113e4a4e08b087
[ "MIT" ]
1
2017-09-14T01:07:44.000Z
2017-09-14T01:07:44.000Z
Solutions/Ch7/7-16 Vector Modification.cpp
menarus/C-Course
ac56ec4215a69f6a755e766b9d113e4a4e08b087
[ "MIT" ]
null
null
null
Solutions/Ch7/7-16 Vector Modification.cpp
menarus/C-Course
ac56ec4215a69f6a755e766b9d113e4a4e08b087
[ "MIT" ]
null
null
null
/* Project : 7-16 Vector Modification Author : Mohammad Al-Husseini Description : Change pin1, pin2, and pin3 to be Vectors. And modify testPin to accept Vectors. */ /////////////////////////////////////////////////////////////////////////////////////////////////// // This program is a driver that tests a function comparing the // contents of two int arrays. #include <iostream> #include <vector> using namespace std; // Function Prototype bool testPIN(vector<int>, vector<int>, int); int main() { const int NUM_DIGITS = 7; // Number of digits in a PIN vector<int> pin1 = { 2, 4, 1, 8, 7, 9, 0 }; // Base set of values. vector<int> pin2 = { 2, 4, 6, 8, 7, 9, 0 }; // Only 1 element is // different from pin1. vector<int> pin3 = { 1, 2, 3, 4, 5, 6, 7 }; // All elements are // different from pin1. if (testPIN(pin1, pin2, NUM_DIGITS)) cout << "ERROR: pin1 and pin2 report to be the same.\n"; else cout << "SUCCESS: pin1 and pin2 are different.\n"; if (testPIN(pin1, pin3, NUM_DIGITS)) cout << "ERROR: pin1 and pin3 report to be the same.\n"; else cout << "SUCCESS: pin1 and pin3 are different.\n"; if (testPIN(pin1, pin1, NUM_DIGITS)) cout << "SUCCESS: pin1 and pin1 report to be the same.\n"; else cout << "ERROR: pin1 and pin1 report to be different.\n"; return 0; } //****************************************************************** // The following function accepts two int arrays. The arrays are * // compared. If they contain the same values, true is returned. * // If the contain different values, false is returned. * //****************************************************************** bool testPIN(vector<int> custPIN, vector<int> databasePIN, int size) { for (int index = 0; index < size; index++) { if (custPIN[index] != databasePIN[index]) return false; // We've found two different values. } return true; // If we make it this far, the values are the same. }
36.017857
100
0.563213
menarus
bf4d029035b1315d7732082d299580db2ee936cc
3,477
cpp
C++
tests/string/tao/hello.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tests/string/tao/hello.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tests/string/tao/hello.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file hello.cpp * @author Mark Drijver * * @brief CORBA C++ server application * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "hello.h" #include <iostream> #include "testdata.h" Hello::Hello(CORBA::ORB_ptr orb, int& result) : orb_(CORBA::ORB::_duplicate(orb)), result_(result) { } char * Hello::get_string() { return CORBA::string_dup("Hello there!"); } void Hello::set_string(const char * text) { if (strcmp(text, "Hello there!") != 0) { std::cout << "ERROR: Hello::set_string parameter value expected 'Hello there!', received " << text << std::endl; ++result_; } } void Hello::out_string(CORBA::String_out text) { text = CORBA::string_dup("I hear you!"); } void Hello::inout_string(char *& text) { if (strcmp(text, "Hello there!") != 0) { std::cout << "ERROR: Hello::inout_string parameter value expected 'Hello there!', received " << text << std::endl; ++result_; } CORBA::string_free (text); text = CORBA::string_dup("I hear you!"); } char * Hello::get_lstring() { std::string longText; longText.assign(66000, 'a'); return CORBA::string_dup(longText.c_str()); } void Hello::set_lstring(const char * text) { std::string longText; longText.assign(66000, 'a'); if (longText.compare(text) != 0) { std::cout << "ERROR: Hello::set_lstring parameter value expected 66000 times 'a', received different." << std::endl; ++result_; } } void Hello::out_lstring(CORBA::String_out text) { std::string longText; longText.assign(66000, 'b'); text = CORBA::string_dup(longText.c_str()); } void Hello::inout_lstring(char *& text) { std::string longText; longText.assign(66000, 'c'); if (longText.compare(text) != 0) { std::cout << "ERROR: Hello::inout_string parameter value expected 66000 times 'c', received different." << std::endl; ++result_; } CORBA::string_free (text); std::string longText2; longText2.assign(66000, 'd'); text = CORBA::string_dup(longText2.c_str()); } // string sequence CORBA::StringSeq * Hello::get_stringSeq() { CORBA::StringSeq_var seq = Array2Seq(stringOutArr); return seq._retn (); } void Hello::set_stringSeq(const CORBA::StringSeq& seq) { CORBA::StringSeq_var seq2 = Array2Seq(stringArr); if (!(eqv(seq, seq2))) { { std::cout << "ERROR: Hello::set_stringSeq parameter unexpected value." << std::endl; ++result_; } } } void Hello::out_stringSeq(CORBA::StringSeq_out text) { CORBA::StringSeq_var seq = Array2Seq(stringOutArr); text = seq._retn (); } void Hello::inout_stringSeq(CORBA::StringSeq& seq) { CORBA::StringSeq_var seq2 = Array2Seq(stringArr); if (!(eqv(seq, seq2))) { std::cout << "ERROR: Hello::inout_stringSeq parameter unexpected value." << std::endl; ++result_; } seq2 = Array2Seq(stringOutArr); seq = seq2; } void Hello::bounded_string (const char * text) { std::string test (text); if (test.length () != 5) { std::cout << "ERROR: Hello::bounded_string parameter unexpected length : " << "expected <5> - found <" << test.length () << ">." << std::endl; ++this->result_; } if (test.compare ("12345") != 0) { std::cout << "ERROR: Hello::bounded_string parameter unexpected value : " << "expected <12345> - found <" << test << ">." << std::endl; ++this->result_; } } void Hello::shutdown() { this->orb_->shutdown(0); }
21.596273
101
0.626977
ClausKlein
bf50eb991a1b263fb8e6b6d17d78f2f86c1abbec
250
cpp
C++
R113-edu/b.cpp
patwadeepak/codeforces
5da8c79ad6f27a4a2436d19fc8cbf274ecd452e2
[ "Apache-2.0" ]
null
null
null
R113-edu/b.cpp
patwadeepak/codeforces
5da8c79ad6f27a4a2436d19fc8cbf274ecd452e2
[ "Apache-2.0" ]
null
null
null
R113-edu/b.cpp
patwadeepak/codeforces
5da8c79ad6f27a4a2436d19fc8cbf274ecd452e2
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; vector<vector<char>> table(n, vector<char>(n, 'X')); } int main() { int t; cin >> t; while(t--) solve(); }
13.157895
56
0.484
patwadeepak
bf5208b3e9ea852dcc52d95d52c359331585fdf2
5,550
cpp
C++
src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-03-23T06:41:14.000Z
2022-03-23T06:41:14.000Z
src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-03-31T23:58:31.000Z
2022-03-31T23:58:31.000Z
src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-01-11T09:39:03.000Z
2022-01-11T09:39:03.000Z
/* * SPDX-License-Identifier: Apache-2.0 */ //===-------- ZHighHelper.cpp - NNPA ZHigh Helper Functions ---------------===// // // Copyright 2019-2022 The IBM Research Authors. // // ============================================================================= // //===----------------------------------------------------------------------===// #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.hpp" #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighOps.hpp" #include "src/Accelerators/NNPA/Support/LayoutHelper.hpp" using namespace mlir; namespace onnx_mlir { namespace zhigh { /// Check if a value type is ranked or unranked. bool hasRankedType(Value val) { ShapedType shapedType = val.getType().cast<ShapedType>(); return (shapedType && shapedType.hasRank()); } /// Get a ztensor data layout by StringAttr. ZTensorEncodingAttr::DataLayout convertStringAttrToDataLayout( StringAttr layoutAttr) { if (layoutAttr) { StringRef layoutStr = layoutAttr.getValue(); if (layoutStr.equals_insensitive(LAYOUT_1D)) return ZTensorEncodingAttr::DataLayout::_1D; else if (layoutStr.equals_insensitive(LAYOUT_2D)) return ZTensorEncodingAttr::DataLayout::_2D; else if (layoutStr.equals_insensitive(LAYOUT_2DS)) return ZTensorEncodingAttr::DataLayout::_2DS; else if (layoutStr.equals_insensitive(LAYOUT_3D)) return ZTensorEncodingAttr::DataLayout::_3D; else if (layoutStr.equals_insensitive(LAYOUT_3DS)) return ZTensorEncodingAttr::DataLayout::_3DS; else if (layoutStr.equals_insensitive(LAYOUT_4D)) return ZTensorEncodingAttr::DataLayout::_4D; else if (layoutStr.equals_insensitive(LAYOUT_4DS)) return ZTensorEncodingAttr::DataLayout::_4DS; else if (layoutStr.equals_insensitive(LAYOUT_NCHW)) return ZTensorEncodingAttr::DataLayout::NCHW; else if (layoutStr.equals_insensitive(LAYOUT_NHWC)) return ZTensorEncodingAttr::DataLayout::NHWC; else if (layoutStr.equals_insensitive(LAYOUT_HWCK)) return ZTensorEncodingAttr::DataLayout::HWCK; else if (layoutStr.equals_insensitive(LAYOUT_FICO)) return ZTensorEncodingAttr::DataLayout::FICO; else if (layoutStr.equals_insensitive(LAYOUT_ZRH)) return ZTensorEncodingAttr::DataLayout::ZRH; else if (layoutStr.equals_insensitive(LAYOUT_BFICO)) return ZTensorEncodingAttr::DataLayout::BFICO; else if (layoutStr.equals_insensitive(LAYOUT_BZRH)) return ZTensorEncodingAttr::DataLayout::BZRH; else llvm_unreachable("Invalid data layout string"); } else llvm_unreachable("Could not get layout by an empty StringAttr"); } /// Get a ztensor data layout by rank. ZTensorEncodingAttr::DataLayout getDataLayoutByRank(int64_t rank) { if (rank == 1) return ZTensorEncodingAttr::DataLayout::_1D; else if (rank == 2) return ZTensorEncodingAttr::DataLayout::_2D; else if (rank == 3) return ZTensorEncodingAttr::DataLayout::_3D; else if (rank == 4) return ZTensorEncodingAttr::DataLayout::_4D; else llvm_unreachable( "Could not get layout by rank. Rank must be 1, 2, 3, or 4"); } /// Convert a data layout to StringAttr. StringAttr convertDataLayoutToStringAttr( OpBuilder &builder, ZTensorEncodingAttr::DataLayout layout) { StringAttr attr; switch (layout) { case ZTensorEncodingAttr::DataLayout::_1D: attr = builder.getStringAttr(LAYOUT_1D); break; case ZTensorEncodingAttr::DataLayout::_2D: attr = builder.getStringAttr(LAYOUT_2D); break; case ZTensorEncodingAttr::DataLayout::_2DS: attr = builder.getStringAttr(LAYOUT_2DS); break; case ZTensorEncodingAttr::DataLayout::_3D: attr = builder.getStringAttr(LAYOUT_3D); break; case ZTensorEncodingAttr::DataLayout::_3DS: attr = builder.getStringAttr(LAYOUT_3DS); break; case ZTensorEncodingAttr::DataLayout::_4D: attr = builder.getStringAttr(LAYOUT_4D); break; case ZTensorEncodingAttr::DataLayout::_4DS: attr = builder.getStringAttr(LAYOUT_4DS); break; case ZTensorEncodingAttr::DataLayout::NCHW: attr = builder.getStringAttr(LAYOUT_NCHW); break; case ZTensorEncodingAttr::DataLayout::NHWC: attr = builder.getStringAttr(LAYOUT_NHWC); break; case ZTensorEncodingAttr::DataLayout::HWCK: attr = builder.getStringAttr(LAYOUT_HWCK); break; case ZTensorEncodingAttr::DataLayout::FICO: attr = builder.getStringAttr(LAYOUT_FICO); break; case ZTensorEncodingAttr::DataLayout::BFICO: attr = builder.getStringAttr(LAYOUT_BFICO); break; case ZTensorEncodingAttr::DataLayout::ZRH: attr = builder.getStringAttr(LAYOUT_ZRH); break; case ZTensorEncodingAttr::DataLayout::BZRH: attr = builder.getStringAttr(LAYOUT_BZRH); break; default: break; } return attr; } //===----------------------------------------------------------------------===// // Utility functions to query ztensor information. bool isZTensor(Type type) { if (auto ttp = type.dyn_cast<RankedTensorType>()) if (ttp.getEncoding().dyn_cast_or_null<ZTensorEncodingAttr>()) return true; return false; } ZTensorEncodingAttr getZTensorEncoding(Type type) { if (auto ttp = type.dyn_cast<RankedTensorType>()) return ttp.getEncoding().dyn_cast_or_null<ZTensorEncodingAttr>(); return nullptr; } ZTensorEncodingAttr::DataLayout getZTensorLayout(Type type) { if (auto encoding = getZTensorEncoding(type)) return encoding.getDataLayout(); return ZTensorEncodingAttr::DataLayout::UNDEFINED; } } // namespace zhigh } // namespace onnx_mlir
34.90566
80
0.706847
philass
bf587f5647fa6585f26b6e88da7b178c3c8a2324
1,348
cpp
C++
Projects/Skylicht/Audio/Source/Decoder/CAudioDecoderRawWav.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
Projects/Skylicht/Audio/Source/Decoder/CAudioDecoderRawWav.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
Projects/Skylicht/Audio/Source/Decoder/CAudioDecoderRawWav.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CAudioDecoderRawWav.h" namespace SkylichtAudio { CAudioDecoderRawWav::CAudioDecoderRawWav(IStream* stream) :IAudioDecoder(stream) { m_streamCursor = stream->createCursor(); } CAudioDecoderRawWav::~CAudioDecoderRawWav() { delete m_streamCursor; } EStatus CAudioDecoderRawWav::initDecode() { return Success; } EStatus CAudioDecoderRawWav::decode(void* outputBuffer, int bufferSize) { // silent buffer memset(outputBuffer, 0, bufferSize); // need wait data // check safe data avaiable will be encode if (m_streamCursor->readyReadData(bufferSize) == false) { // return state wait data return WaitData; } // copy data from stream to waveBuffer m_streamCursor->read((unsigned char*)outputBuffer, bufferSize); // trim the readed memory m_streamCursor->trim(); return Success; } int CAudioDecoderRawWav::seek(int bufferSize) { return 0; } void CAudioDecoderRawWav::getTrackParam(STrackParams* track) { track->NumChannels = m_stream->getChannels(); track->SamplingRate = m_stream->getSampleRate(); track->BitsPerSample = 16; // 16bit } float CAudioDecoderRawWav::getCurrentTime() { // implement later return 0.0f; } void CAudioDecoderRawWav::stopStream() { m_streamCursor->seek(0, IStreamCursor::OriginStart); m_stream->stopStream(); } }
20.119403
72
0.727003
tsukoyumi
bf58ef26a145e3d12e63966e16a9725a4257cb68
777
cpp
C++
src/greeter/tests/greeter_api_tests.cpp
tstraus/cpp_starter
519c30945ac752ce95974df7826eeaec5949bd96
[ "MIT" ]
null
null
null
src/greeter/tests/greeter_api_tests.cpp
tstraus/cpp_starter
519c30945ac752ce95974df7826eeaec5949bd96
[ "MIT" ]
null
null
null
src/greeter/tests/greeter_api_tests.cpp
tstraus/cpp_starter
519c30945ac752ce95974df7826eeaec5949bd96
[ "MIT" ]
null
null
null
#include "greeter_api.h" #include "gtest/gtest.h" #define TEST_NAME "Margot" TEST(GreeterApiTests, Greet) { auto* g = greeter_new(); ASSERT_NE(g, nullptr); EXPECT_GT(greeter_greet(g, TEST_NAME), 0); auto* gc = g; greeter_free(g); ASSERT_EQ(g, gc); } TEST(GreeterApiTests, Length) { auto* g = greeter_new(); const auto length = greeter_greet(g, TEST_NAME); EXPECT_EQ(length, 6); greeter_free(g); } TEST(GreeterApiTests, Count) { auto* g = greeter_new(); ASSERT_EQ(greeter_total_greeted(g), 0); greeter_greet(g, "one"); ASSERT_EQ(greeter_total_greeted(g), 1); greeter_greet(g, "two"); ASSERT_EQ(greeter_total_greeted(g), 2); greeter_greet(g, "three"); ASSERT_EQ(greeter_total_greeted(g), 3); }
17.659091
52
0.655084
tstraus
bf5f3ddbf3c5107ba81a536e295076fb4bd4fbfd
3,622
cpp
C++
src/cic-plan/src/cic/plan/Target.cpp
Mezozoysky/cic
103a623db2b9d14c212867bd3319fb577cbcae1d
[ "Zlib" ]
null
null
null
src/cic-plan/src/cic/plan/Target.cpp
Mezozoysky/cic
103a623db2b9d14c212867bd3319fb577cbcae1d
[ "Zlib" ]
null
null
null
src/cic-plan/src/cic/plan/Target.cpp
Mezozoysky/cic
103a623db2b9d14c212867bd3319fb577cbcae1d
[ "Zlib" ]
null
null
null
// cic // // cic - Copyright (C) 2017-2018 Stanislav Demyanovich <[email protected]> // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. /// \file /// \brief Target class implementation /// \author Stanislav Demyanovich <[email protected]> /// \date 2018 /// \copyright cic is released under the terms of zlib/png license #include <cic/plan/Target.hpp> #include <cic/plan/Phase.hpp> #include <fmt/format.h> #include <Poco/Exception.h> #include <Poco/String.h> #include <cic/plan/Act.hpp> #include <cic/plan/Report.hpp> #include <Poco/DOM/Element.h> #include <Poco/AutoPtr.h> #include <Poco/DOM/NodeList.h> #include <algorithm> #include <functional> #include <Poco/Util/Application.h> using Poco::XML::Element; using Poco::XML::NodeList; using namespace fmt::literals; using Poco::AutoPtr; using cic::industry::Industry; namespace cic { namespace plan { Target::Target() : PerformConfig() { } void Target::loadFromXML( Element* root, Industry* industry ) { assert( Poco::XML::fromXMLString( root->nodeName() ) == "target" ); PerformConfig::loadFromXML( root, industry ); Element* elem{ root->getChildElement( "planPath" ) }; if ( elem != nullptr ) { std::string value{ Poco::trim( Poco::trim( elem->getAttribute( "value" ) ) ) }; // value can be empty setPlanPath( value ); } elem = root->getChildElement( "phases" ); if ( elem != nullptr ) { loadPhasesFromXML( elem, industry ); } } void Target::saveToXML( Element* root ) const {} void Target::setPlanPath( const std::string& planPath ) { onSetPlanPath( planPath ); mPlanPath = planPath; } void Target::onSetPlanPath( const std::string& planPath ) { return; } void Target::setPhases( const std::vector< std::string >& phaseList ) { onSetPhases( phaseList ); mPhases = phaseList; } void Target::onSetPhases( const std::vector< std::string >& phaseList ) { return; } void Target::loadPhasesFromXML( Element* root, Industry* industry ) { AutoPtr< NodeList > list{ root->childNodes() }; Element* elem{ nullptr }; std::vector< std::string > phaseNames; for ( std::size_t i{ 0 }; i < list->length(); ++i ) { elem = static_cast< Element* >( list->item( i ) ); if ( elem != nullptr && elem->nodeName() == "phase" ) { std::string value{ Poco::trim( elem->getAttribute( "value" ) ) }; if ( value.empty() ) { Poco::Util::Application::instance().logger().error( "Element 'phase' has no (or has empty) 'value' attribute" ); } else { phaseNames.push_back( value ); } } } setPhases( phaseNames ); } } // namespace plan } // namespace cic
26.437956
128
0.647156
Mezozoysky
bf607d50afdfd91d2462cc8c984bad9f5e3b0c3f
3,914
cpp
C++
library/celestia/source/catalogxref.cpp
Sphinkie/LongForgottenEarth
9008e4381091579e38feee03c56c5e3435419474
[ "MIT" ]
null
null
null
library/celestia/source/catalogxref.cpp
Sphinkie/LongForgottenEarth
9008e4381091579e38feee03c56c5e3435419474
[ "MIT" ]
null
null
null
library/celestia/source/catalogxref.cpp
Sphinkie/LongForgottenEarth
9008e4381091579e38feee03c56c5e3435419474
[ "MIT" ]
null
null
null
// catalogxref.cpp // // Copyright (C) 2001, Chris Laurel <[email protected]> // // 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. #include <cctype> #include <algorithm> #include <celutil/util.h> #include "catalogxref.h" #include "stardb.h" using namespace std; CatalogCrossReference::CatalogCrossReference() { } CatalogCrossReference::~CatalogCrossReference() { } string CatalogCrossReference::getPrefix() const { return prefix; } void CatalogCrossReference::setPrefix(const string& _prefix) { prefix = _prefix; } bool operator<(const CatalogCrossReference::Entry& a, const CatalogCrossReference::Entry& b) { return a.catalogNumber < b.catalogNumber; } struct XrefEntryPredicate { int dummy; XrefEntryPredicate() : dummy(0) {}; bool operator()(const CatalogCrossReference::Entry& a, const CatalogCrossReference::Entry& b) const { return a.catalogNumber < b.catalogNumber; } }; Star* CatalogCrossReference::lookup(uint32 catalogNumber) const { Entry e; e.catalogNumber = catalogNumber; e.star = NULL; XrefEntryPredicate pred; vector<Entry>::const_iterator iter = lower_bound(entries.begin(), entries.end(), e, pred); if (iter != entries.end() && iter->catalogNumber == catalogNumber) return iter->star; else return NULL; } Star* CatalogCrossReference::lookup(const string& name) const { uint32 catalogNumber = parse(name); if (catalogNumber == InvalidCatalogNumber) return NULL; else return lookup(catalogNumber); } uint32 CatalogCrossReference::parse(const string& name) const { if (compareIgnoringCase(name, prefix, prefix.length()) != 0) return InvalidCatalogNumber; unsigned int i = prefix.length(); unsigned int n = 0; bool readDigit = false; // Optional space between prefix and number if (name[i] == ' ') i++; while (isdigit(name[i])) { n = n * 10 + ((unsigned int) name[i] - (unsigned int) '0'); readDigit = true; // Limited to 24 bits if (n >= 0x1000000) return InvalidCatalogNumber; } // Must have read at least one digit if (!readDigit) return InvalidCatalogNumber; // Check for garbage at the end of the string if (i != prefix.length()) return InvalidCatalogNumber; else return n; } void CatalogCrossReference::addEntry(uint32 catalogNumber, Star* star) { Entry e; e.catalogNumber = catalogNumber; e.star = star; entries.insert(entries.end(), e); } void CatalogCrossReference::sortEntries() { XrefEntryPredicate pred; sort(entries.begin(), entries.end(), pred); } void CatalogCrossReference::reserve(size_t n) { if (n > entries.size()) entries.reserve(n); } static uint32 readUint32(istream& in) { unsigned char b[4]; in.read(reinterpret_cast<char*>(b), 4); return ((uint32) b[3] << 24) + ((uint32) b[2] << 16) + ((uint32) b[1] << 8) + (uint32) b[0]; } CatalogCrossReference* ReadCatalogCrossReference(istream& in, const StarDatabase& stardb) { CatalogCrossReference* xref = new CatalogCrossReference(); uint32 nEntries = readUint32(in); if (!in.good()) { delete xref; return NULL; } xref->reserve(nEntries); for (uint32 i = 0; i < nEntries; i++) { uint32 catNo1 = readUint32(in); uint32 catNo2 = readUint32(in); Star* star = stardb.find(catNo2); if (star != NULL) xref->addEntry(catNo1, star); } return xref; }
22.112994
77
0.628769
Sphinkie
bf69ca037c6ce7c337383dd06ea19a5b82da1e85
9,938
cpp
C++
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/control_ak4558.cpp
Pocketart/typhoonclawvex
eb4b523c13541b2b9136d32259bd0399b46a289e
[ "MIT" ]
4
2017-10-06T05:48:30.000Z
2018-03-30T06:20:22.000Z
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/control_ak4558.cpp
Pocketart/typhoonclawvex
eb4b523c13541b2b9136d32259bd0399b46a289e
[ "MIT" ]
null
null
null
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/control_ak4558.cpp
Pocketart/typhoonclawvex
eb4b523c13541b2b9136d32259bd0399b46a289e
[ "MIT" ]
3
2017-10-06T06:01:44.000Z
2018-05-25T06:37:19.000Z
/* * HiFi Audio Codec Module support library for Teensy 3.x * * Copyright 2015, Michele Perla * */ #include "control_ak4558.h" #include "Wire.h" void AudioControlAK4558::initConfig(void) { // puts all default registers values inside an array // this allows us to modify registers locally using annotation like follows: // // registers[AK4558_CTRL_1] &= ~AK4558_DIF2; // registers[AK4558_CTRL_1] |= AK4558_DIF1 | AK4558_DIF0; // // after manipulation, we can write the entire register value on the CODEC uint8_t n = 0; Wire.requestFrom(AK4558_I2C_ADDR,10); while(Wire.available()) { #if AK4558_SERIAL_DEBUG > 0 Serial.print("Register "); Serial.print(n); Serial.print(" = "); #endif registers[n++] = Wire.read(); #if AK4558_SERIAL_DEBUG > 0 Serial.println(registers[n-1], BIN); #endif } } void AudioControlAK4558::readConfig(void) { // reads registers values uint8_t n = 0; uint8_t c = 0; Wire.requestFrom(AK4558_I2C_ADDR, 10); while(Wire.available()) { Serial.print("Register "); Serial.print(n++); Serial.print(" = "); c = Wire.read(); Serial.println(c, BIN); } } bool AudioControlAK4558::write(unsigned int reg, unsigned int val) { Wire.beginTransmission(AK4558_I2C_ADDR); Wire.write(reg); Wire.write(val); return (Wire.endTransmission(true)==0); } bool AudioControlAK4558::enableIn(void) { // ADC setup (datasheet page 74 #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable ADC"); #endif // ignore this, leaving default values - ADC: Set up the de-emphasis filter (Addr = 07H). registers[AK4558_PWR_MNGT] |= AK4558_PMADR | AK4558_PMADL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif delay(300); // Power up the ADC: PMADL = PMADR bits = “0” → “1” // Initialization cycle of the ADC is 5200/fs @Normal mode. The SDTO pin outputs “L” during initialization. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable ADC - Done"); #endif return true; } bool AudioControlAK4558::enableOut(void) { #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable DAC"); #endif // DAC Output setup (datasheet page 75) registers[AK4558_MODE_CTRL] |= AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Set the DAC output to power-save mode: LOPS bit “0” → “1” // ignore this, leaving default values - DAC: Set up the digital filter mode. // ignore this, leaving default values - Set up the digital output volume (Address = 08H, 09H). registers[AK4558_PWR_MNGT] |= AK4558_PMDAR | AK4558_PMDAL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif delay(300); // Power up the DAC: PMDAL = PMDAR bits = “0” → “1” // Outputs of the LOUT and ROUT pins start rising. Rise time is 300ms (max.) when C = 1μF. registers[AK4558_MODE_CTRL] &= ~AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Release power-save mode of the DAC output: LOPS bit = “1” → “0” // Set LOPS bit to “0” after the LOUT and ROUT pins output “H”. Sound data will be output from the // LOUT and ROUT pins after this setting. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable DAC - Done"); #endif return true; } bool AudioControlAK4558::enable(void) { #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable device"); #endif // Power Up and Reset // Clock Setup (datasheet page 72) pinMode(PIN_PDN, OUTPUT); digitalWrite(0, LOW); delay(1); digitalWrite(0, HIGH); // After Power Up: PDN pin “L” → “H” // “L” time of 150ns or more is needed to reset the AK4558. delay(20); #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: PDN is HIGH (device reset)"); #endif // Control register settings become available in 10ms (min.) when LDOE pin = “H” Wire.begin(); initConfig(); // access all registers to store locally their default values // DIF2-0, DFS1-0 and ACKS bits must be set before MCKI, LRCK and BICK are supplied // PMPLL = 0 (EXT Slave Mode; disables internal PLL and uses ext. clock) (by DEFAULT) // ACKS = 0 (Manual Setting Mode; disables automatic clock selection) (by DEFAULT) // DFS1-0 = 00 (Sampling Speed = Normal Speed Mode) (by DEFAULT) // TDM1-0 = 00 (Time Division Multiplexing mode OFF) (by DEFAULT) registers[AK4558_CTRL_1] &= ~AK4558_DIF2; registers[AK4558_CTRL_1] |= AK4558_DIF1 | AK4558_DIF0; #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: CTRL_1 set to "); Serial.println(registers[AK4558_CTRL_1], BIN); #endif // DIF2-1-0 = 011 ( 16 bit I2S compatible when BICK = 32fs) registers[AK4558_CTRL_2] &= ~AK4558_MCKS1; #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: CTRL_2 set to "); Serial.println(registers[AK4558_CTRL_2], BIN); #endif // MCKS1-0 = 00 (Master Clock Input Frequency Select, set 256fs for Normal Speed Mode -> 11.2896 MHz) registers[AK4558_MODE_CTRL] &= ~AK4558_BCKO0; // BCKO1-0 = 00 (BICK Output Frequency at Master Mode = 32fs = 1.4112 MHz) registers[AK4558_MODE_CTRL] |= AK4558_FS1; // Set up the sampling frequency (FS3-0 bits). The ADC must be powered-up in consideration of PLL // lock time. (in this case (ref. table 17): Set clock to mode 5 / 44.100 KHz) #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // BCKO1-0 = 00 (BICK Output Frequency at Master Mode = 32fs = 1.4112 MHz) Wire.beginTransmission(AK4558_I2C_ADDR); Wire.write(AK4558_CTRL_1); Wire.write(registers[AK4558_CTRL_1]); Wire.write(registers[AK4558_CTRL_2]); Wire.write(registers[AK4558_MODE_CTRL]); Wire.endTransmission(); // Write configuration registers in a single write operation (datasheet page 81): // The AK4558 can perform more than one byte write operation per sequence. After receipt of the third byte // the AK4558 generates an acknowledge and awaits the next data. The master can transmit more than // one byte instead of terminating the write cycle after the first data byte is transferred. After receiving each // data packet the internal address counter is incremented by one, and the next data is automatically taken // into the next address. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable device - Done"); #endif return true; } bool AudioControlAK4558::disableIn(void) { // ADC power-down (datasheet page 74 registers[AK4558_PWR_MNGT] &= ~AK4558_PMADR | ~AK4558_PMADL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif // Power down ADC: PMADL = PMADR bits = “1” → “0” #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable ADC - Done"); #endif return true; } bool AudioControlAK4558::disableOut(void) { #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Disable DAC"); #endif // DAC Output power-down (datasheet page 75) registers[AK4558_MODE_CTRL] |= AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Set the DAC output to power-save mode: LOPS bit “0” → “1” registers[AK4558_PWR_MNGT] &= ~AK4558_PMDAR | ~AK4558_PMDAL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif delay(300); // Power down the DAC: PMDAL = PMDAR bits = “1” → “0” // Outputs of the LOUT and ROUT pins start falling. Rise time is 300ms (max.) when C = 1μF. registers[AK4558_MODE_CTRL] &= ~AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Release power-save mode of the DAC output: LOPS bit = “1” → “0” // Set LOPS bit to “0” after outputs of the LOUT and ROUT pins fall to “L”. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Disable DAC - Done"); #endif return true; } uint8_t AudioControlAK4558::convertVolume(float vol) { // Convert float (range 0.0-1.0) to unsigned char (range 0x00-0xFF) uint8_t temp = ((uint32_t)vol)>>22; return temp; } bool AudioControlAK4558::volume(float n) { // Set DAC output volume uint8_t vol = convertVolume(n); registers[AK4558_LOUT_VOL] = vol; registers[AK4558_ROUT_VOL] = vol; Wire.beginTransmission(AK4558_I2C_ADDR); Wire.write(AK4558_LOUT_VOL); Wire.write(registers[AK4558_LOUT_VOL]); Wire.write(registers[AK4558_ROUT_VOL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: LOUT_VOL set to "); Serial.println(registers[AK4558_LOUT_VOL], BIN); Serial.print("AK4558: ROUT_VOL set to "); Serial.println(registers[AK4558_ROUT_VOL], BIN); #endif return (Wire.endTransmission(true)==0); } bool AudioControlAK4558::volumeLeft(float n) { // Set DAC left output volume uint8_t vol = convertVolume(n); registers[AK4558_LOUT_VOL] = vol; bool ret = write(AK4558_LOUT_VOL, registers[AK4558_LOUT_VOL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: LOUT_VOL set to "); Serial.println(registers[AK4558_LOUT_VOL], BIN); #endif return ret; } bool AudioControlAK4558::volumeRight(float n) { // Set DAC right output volume uint8_t vol = convertVolume(n); registers[AK4558_ROUT_VOL] = vol; bool ret = write(AK4558_ROUT_VOL, registers[AK4558_ROUT_VOL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: ROUT_VOL set to "); Serial.println(registers[AK4558_ROUT_VOL], BIN); #endif return ret; }
33.016611
114
0.732642
Pocketart
bf6b647a11daff2589ffce149e9cad4eb08677be
4,914
cpp
C++
src/lib/pubkey/rw/rw.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
src/lib/pubkey/rw/rw.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
src/lib/pubkey/rw/rw.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
/* * Rabin-Williams * (C) 1999-2008 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/pk_utils.h> #include <botan/rw.h> #include <botan/keypair.h> #include <botan/parsing.h> #include <botan/reducer.h> #include <botan/blinding.h> #include <algorithm> #include <future> namespace Botan { /* * Create a Rabin-Williams private key */ RW_PrivateKey::RW_PrivateKey(RandomNumberGenerator& rng, size_t bits, size_t exp) { if(bits < 1024) throw Invalid_Argument(algo_name() + ": Can't make a key that is only " + std::to_string(bits) + " bits long"); if(exp < 2 || exp % 2 == 1) throw Invalid_Argument(algo_name() + ": Invalid encryption exponent"); m_e = exp; do { m_p = random_prime(rng, (bits + 1) / 2, m_e / 2, 3, 4); m_q = random_prime(rng, bits - m_p.bits(), m_e / 2, ((m_p % 8 == 3) ? 7 : 3), 8); m_n = m_p * m_q; } while(m_n.bits() != bits); m_d = inverse_mod(m_e, lcm(m_p - 1, m_q - 1) >> 1); m_d1 = m_d % (m_p - 1); m_d2 = m_d % (m_q - 1); m_c = inverse_mod(m_q, m_p); gen_check(rng); } /* * Check Private Rabin-Williams Parameters */ bool RW_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!IF_Scheme_PrivateKey::check_key(rng, strong)) return false; if(!strong) return true; if((m_e * m_d) % (lcm(m_p - 1, m_q - 1) / 2) != 1) return false; return KeyPair::signature_consistency_check(rng, *this, "EMSA2(SHA-1)"); } namespace { /** * Rabin-Williams Signature Operation */ class RW_Signature_Operation : public PK_Ops::Signature_with_EMSA { public: typedef RW_PrivateKey Key_Type; RW_Signature_Operation(const RW_PrivateKey& rw, const std::string& emsa) : PK_Ops::Signature_with_EMSA(emsa), m_n(rw.get_n()), m_e(rw.get_e()), m_q(rw.get_q()), m_c(rw.get_c()), m_powermod_d1_p(rw.get_d1(), rw.get_p()), m_powermod_d2_q(rw.get_d2(), rw.get_q()), m_mod_p(rw.get_p()), m_blinder(m_n, [this](const BigInt& k) { return power_mod(k, m_e, m_n); }, [this](const BigInt& k) { return inverse_mod(k, m_n); }) { } size_t max_input_bits() const override { return (m_n.bits() - 1); } secure_vector<byte> raw_sign(const byte msg[], size_t msg_len, RandomNumberGenerator& rng) override; private: const BigInt& m_n; const BigInt& m_e; const BigInt& m_q; const BigInt& m_c; Fixed_Exponent_Power_Mod m_powermod_d1_p, m_powermod_d2_q; Modular_Reducer m_mod_p; Blinder m_blinder; }; secure_vector<byte> RW_Signature_Operation::raw_sign(const byte msg[], size_t msg_len, RandomNumberGenerator&) { BigInt i(msg, msg_len); if(i >= m_n || i % 16 != 12) throw Invalid_Argument("Rabin-Williams: invalid input"); if(jacobi(i, m_n) != 1) i >>= 1; i = m_blinder.blind(i); auto future_j1 = std::async(std::launch::async, m_powermod_d1_p, i); const BigInt j2 = m_powermod_d2_q(i); BigInt j1 = future_j1.get(); j1 = m_mod_p.reduce(sub_mul(j1, j2, m_c)); const BigInt r = m_blinder.unblind(mul_add(j1, m_q, j2)); return BigInt::encode_1363(std::min(r, m_n - r), m_n.bytes()); } /** * Rabin-Williams Verification Operation */ class RW_Verification_Operation : public PK_Ops::Verification_with_EMSA { public: typedef RW_PublicKey Key_Type; RW_Verification_Operation(const RW_PublicKey& rw, const std::string& emsa) : PK_Ops::Verification_with_EMSA(emsa), m_n(rw.get_n()), m_powermod_e_n(rw.get_e(), rw.get_n()) {} size_t max_input_bits() const override { return (m_n.bits() - 1); } bool with_recovery() const override { return true; } secure_vector<byte> verify_mr(const byte msg[], size_t msg_len) override; private: const BigInt& m_n; Fixed_Exponent_Power_Mod m_powermod_e_n; }; secure_vector<byte> RW_Verification_Operation::verify_mr(const byte msg[], size_t msg_len) { BigInt m(msg, msg_len); if((m > (m_n >> 1)) || m.is_negative()) throw Invalid_Argument("RW signature verification: m > n / 2 || m < 0"); BigInt r = m_powermod_e_n(m); if(r % 16 == 12) return BigInt::encode_locked(r); if(r % 8 == 6) return BigInt::encode_locked(2*r); r = m_n - r; if(r % 16 == 12) return BigInt::encode_locked(r); if(r % 8 == 6) return BigInt::encode_locked(2*r); throw Invalid_Argument("RW signature verification: Invalid signature"); } BOTAN_REGISTER_PK_SIGNATURE_OP("RW", RW_Signature_Operation); BOTAN_REGISTER_PK_VERIFY_OP("RW", RW_Verification_Operation); } }
26.852459
87
0.614774
el-forkorama
bf6dad0efa8f4b117237b4443ee57524dfcbf432
4,213
hpp
C++
zen/bones/framework/bones_framework_accessor.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
1
2016-12-10T07:21:17.000Z
2016-12-10T07:21:17.000Z
zen/bones/framework/bones_framework_accessor.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
null
null
null
zen/bones/framework/bones_framework_accessor.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
null
null
null
#ifndef __ZEN__BONES_FRAMEWORK_ACCESSOR__HPP #define __ZEN__BONES_FRAMEWORK_ACCESSOR__HPP /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// #include <zen/bones/bones_framework.h> #include <zen/bones/framework/bones_framework_dispatcher.hpp> #include <unordered_map> #include <functional> #include <iostream> #include <sys/socket.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <netdb.h> #include <thread> /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// class zen::bones_framework_accessor : public std::enable_shared_from_this< zen::bones_framework_accessor > { using entangled_shared = types< zen::bones_framework_accessor >::weak; using event_callback_function = std::function< void( zen::bones_framework_event_shared & ) >; using callbacks_type = std::unordered_map< std::string, event_callback_function >; bones_framework_accessor( const zen::bones_framework_accessor & ) = delete; bones_framework_accessor & operator=( zen::bones_framework_accessor ) = delete; bones_framework_accessor( zen::bones_framework_accessor && ) = delete; bones_framework_accessor & operator=( zen::bones_framework_accessor && ) = delete; public: ~bones_framework_accessor(); bones_framework_accessor( zen::bones_framework_dispatcher_shared dispatcher_, std::string name_, zen::bones_framework_accessor_shared ownership_ ); bones_framework_accessor( const zen::bones_framework_dispatcher_shared &dispatcher_, const std::string &name_ ); const std::string& name() const { return _name; } static zen::bones_framework_accessor_shared factory( zen::bones_framework_dispatcher_shared dispatcher_, const std::string &name_ ); static zen::bones_framework_accessor_shared factory( zen::bones_framework_dispatcher_shared dispatcher_, const std::string &host_, int port_ ); void start_dispatcher( zen::bones_framework_accessor_shared me_shared_, int sock_fd_ ); void set_entangled( zen::bones_framework_accessor_shared &entangled_ ); void set_session_ownership( zen::bones_framework_session_shared &session_instance_ ); template< typename Session > void callback( const std::string &name_, void (Session::*callback_function_)( const zen::bones_framework_event_shared &event_ ), Session *callback_session_ ); void uncallback( const std::string &name_ ); void deliver( const zen::bones_framework_event_shared &event_ ); void dispatch( const zen::bones_framework_event_shared &event_ ); void dispatch( const std::string &tag_, const std::string &payload_ = "" ); private: void dispatcher( zen::bones_framework_accessor_shared keep_me_alive_, int sock_fd_ ); private: int _sock_fd{ -1 }; std::string _name; entangled_shared _entangled; callbacks_type _callbacks; zen::bones_framework_dispatcher_shared _service_dispatcher{ nullptr }; zen::bones_framework_accessor_shared _accessor_ownership{ nullptr }; zen::bones_framework_session_shared _session_ownership{ nullptr }; }; /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// template< typename Session > void zen::bones_framework_accessor::callback( const std::string &name_, void (Session::*callback_function_)( const zen::bones_framework_event_shared &event_ ), Session *callback_session_ ) { auto callback = [ callback_session_, callback_function_ ]( zen::bones_framework_event_shared &event_ ) { ( callback_session_->*callback_function_ )( event_ ); }; _callbacks[ name_ ] = callback; } /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// #endif // __ZEN__BONES_FRAMEWORK_ACCESSOR__HPP
25.533333
99
0.631379
shauncroton
bf73c8565bb825a44bedfc152cb1df858b7db48b
1,208
cpp
C++
prog-lab-I/VE2019/ve_17029_Q1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
prog-lab-I/VE2019/ve_17029_Q1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
prog-lab-I/VE2019/ve_17029_Q1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
// Feito por Henrique Navarro - 17029 #include<bits/stdc++.h> using namespace std; // usando funcionalidades do C++11 class burrowsWheeler{ string palavra; string modificarEntrada(){ return '^' + palavra + '|'; } vector<string> rotacoes(string modificada){ vector<string> resposta; resposta.push_back(modificada); while(true){ char ultima = modificada.back(); modificada = ultima + modificada; modificada.pop_back(); if(modificada == resposta[0]) break; resposta.push_back(modificada); } return resposta; } vector<string> ordena(vector<string> rotacoes){ sort(rotacoes.begin(), rotacoes.end()); return rotacoes; } string destacaColuna(vector<string> ordenado){ string ans; //C++ 11 for(auto x : ordenado) ans += x.back(); return ans; } public: burrowsWheeler(string palavra) : palavra(palavra) {} string getPalavra() { return palavra; } void transformada(){ vector<string> rot = rotacoes(modificarEntrada()); rot = ordena(rot); palavra = destacaColuna(rot); } }; int main(){ burrowsWheeler A("BANANA"); A.transformada(); cout << A.getPalavra() << endl; }
23.686275
56
0.638245
hsnavarro
bf78ce060d8b93791d53aaf5d3cdc29b4743d110
1,465
cc
C++
LeetCode/Medium/GenerateParanthesis.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
LeetCode/Medium/GenerateParanthesis.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
LeetCode/Medium/GenerateParanthesis.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/generate-parentheses/description/ /*Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] */ #include <iostream> #include <algorithm> #include <vector> #include <stack> using namespace std; class Solution { public: bool valid_paranthesis(string s) { bool flag = true; stack<char> stk; for (int i = 0; i < s.length(); i++) { if (s[i] == '(') stk.push(s[i]); if (s[i] == ')') { if (stk.empty()) return false; else stk.pop(); } } return flag; } vector<string> generateParenthesis(int n) { if (n <= 0) return {}; vector<string> v; string s; for (int i = 0; i < n; i++) s += "("; for (int i = 0; i < n; i++) s += ")"; do { if (valid_paranthesis(s)) v.push_back(s); } while (next_permutation(s.begin(), s.end())); return v; } }; int main() { Solution obj; int count = 1; vector<string> v = obj.generateParenthesis(6); for (string i : v) { cout << count << ":\t" << i << endl; count++; } }
20.347222
105
0.43959
ChakreshSinghUC
bf7aa0fff25188cfa7e25e89e340e723447887d0
3,982
cc
C++
src/iohal/translators/vm_i386_pae.cc
MarkMankins/libosi
2d67ed8066098bc798a53c06dffb5ba257d89bde
[ "BSD-3-Clause" ]
3
2021-02-23T09:13:07.000Z
2021-08-13T14:15:06.000Z
src/iohal/translators/vm_i386_pae.cc
MarkMankins/libosi
2d67ed8066098bc798a53c06dffb5ba257d89bde
[ "BSD-3-Clause" ]
3
2021-12-02T17:51:48.000Z
2022-03-04T20:02:32.000Z
src/iohal/translators/vm_i386_pae.cc
MarkMankins/libosi
2d67ed8066098bc798a53c06dffb5ba257d89bde
[ "BSD-3-Clause" ]
2
2021-12-07T00:42:31.000Z
2022-03-04T15:42:12.000Z
#include <cstdio> #include <cstdlib> #include "iohal/memory/physical_memory.h" #include "iohal/memory/virtual_memory.h" #include "vm_i386_pae.h" namespace i386_pae_translator { #define HW_PTE_MASK 0xFFFFFFFFFF000 static inline pm_addr_t get_page_directory_pointer_index(vm_addr_t vaddr) { uint64_t pdpimask = 0xC0000000; return ((vaddr & pdpimask) >> 30); } static inline pm_addr_t get_page_directory_index(vm_addr_t vaddr) // index * sizeof(QUAD) { uint64_t pdimask = 0x3FE00000; return ((vaddr & pdimask) >> 21); } static inline pm_addr_t get_page_table_index(vm_addr_t vaddr) // index * sizeof(QUAD) { uint64_t ptimask = 0x1FF000; return ((vaddr & ptimask) >> 12); } static inline pm_addr_t get_byte_offset(vm_addr_t vaddr) // index * sizeof(QUAD) { uint64_t byteoffsetmask = 0xFFF; return (vaddr & byteoffsetmask); } static inline pm_addr_t get_2MB_byte_offset(vm_addr_t vaddr) { uint64_t byteoffsetmask = 0x1FFFFF; return (vaddr & byteoffsetmask); } static inline bool entry_present(vm_addr_t entry, TranslateProfile profile) { bool present = ((entry & 1) == 1); bool in_transition = ((entry & (1 << 11)) && !(entry & (1 << 10))); bool global = (entry & (1 << 8)); if (profile == TPROF_GENERIC_LINUX) { return present || global; } else if (profile == TPROF_GENERIC_WINDOWS) { return present || in_transition; } return present; } static inline bool is_large_page(pm_addr_t entry) { return ((entry & (1 << 7)) > 0); } static inline pm_addr_t get_pdpe(PhysicalMemory* pmem, vm_addr_t addr, pm_addr_t pdpt_base_addr) { int size_of_pdpe = 8; auto pdpe_index = get_page_directory_pointer_index(addr); auto pdpe_addr = pdpt_base_addr + (pdpe_index * size_of_pdpe); pm_addr_t pdpe_entry = 0; pmem->read(pmem, pdpe_addr, (uint8_t*)&pdpe_entry, size_of_pdpe); return pdpe_entry; } static inline pm_addr_t get_pde(struct PhysicalMemory* pmem, vm_addr_t addr, pm_addr_t pdt_base_addr) { size_t size_of_pde = 8; auto pde_index = get_page_directory_index(addr); auto pde_addr = pdt_base_addr + (pde_index * size_of_pde); pm_addr_t pde = 0; pmem->read(pmem, pde_addr, (uint8_t*)&pde, size_of_pde); return pde; } static inline pm_addr_t get_pte(struct PhysicalMemory* pmem, vm_addr_t addr, pm_addr_t pt_base_addr) { size_t size_of_pte = 8; auto pte_index = get_page_table_index(addr); auto pte_addr = pt_base_addr + (pte_index * size_of_pte); pm_addr_t pte = 0; pmem->read(pmem, pte_addr, (uint8_t*)&pte, size_of_pte); return pte; } TranslateStatus translate_address(struct PhysicalMemory* pm, vm_addr_t vm_addr, pm_addr_t* pm_addr, pm_addr_t asid, TranslateProfile profile) { // Read the base address of the page directory pointer table (pdpt) from cr4 uint64_t cr3_pfn = asid & 0xFFFFFFE0; auto pdp_entry = get_pdpe(pm, vm_addr, cr3_pfn); if (!entry_present(pdp_entry, profile)) { return TSTAT_INVALID_ADDRESS; } uint64_t pdp_pfn = pdp_entry & 0xFFFFFFFFFF000; auto pde = get_pde(pm, vm_addr, pdp_pfn); if (!entry_present(pde, profile)) { return TSTAT_INVALID_ADDRESS; // TODO check if paged out } // Handle large pages if (is_large_page(pde)) { *pm_addr = (pde & 0xFFFFFFFE00000) + get_2MB_byte_offset(vm_addr); return TSTAT_SUCCESS; } uint64_t pd_pfn = pde & HW_PTE_MASK; // Read the base address of the page table (PT) from the PDT auto pte = get_pte(pm, vm_addr, pd_pfn); if (!entry_present(pte, profile)) { return TSTAT_PAGED_OUT; // TODO check if paged out } // Read the physical page offset from the PT *pm_addr = (pte & HW_PTE_MASK) + get_byte_offset(vm_addr); return TSTAT_SUCCESS; } } // namespace i386_pae_translator
30.630769
89
0.67328
MarkMankins
bf81a58df9838c786792dbb2904cf32b7cf74f85
1,314
cpp
C++
vr/vr_rt/src/vr/market/books/execution_order_book.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
4
2019-09-09T22:08:40.000Z
2021-05-17T13:43:31.000Z
vr/vr_rt/src/vr/market/books/execution_order_book.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
null
null
null
vr/vr_rt/src/vr/market/books/execution_order_book.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
1
2019-09-09T15:46:20.000Z
2019-09-09T15:46:20.000Z
#include "vr/market/books/execution_order_book.h" #include "vr/util/ops_int.h" //---------------------------------------------------------------------------- namespace vr { namespace market { namespace ex { //............................................................................ std::ostream & operator<< (std::ostream & os, fsm_state const & obj) VR_NOEXCEPT { os << print (obj.order_state ()); auto ps = obj.pending_state (); if (ps) { os << " {"; bool first { true }; while (ps > 0) { int32_t const bit = (ps & - ps); ps ^= bit; if (first) first = false; else os << '|'; os << static_cast<fsm_state::pending::enum_t> (bit); } os << '}'; } return os; } //............................................................................ std::ostream & operator<< (std::ostream & os, fsm_error const & obj) VR_NOEXCEPT { if (VR_LIKELY (obj.m_lineno <= 0)) return os << "N/A"; else return os << "[line: " << obj.m_lineno << ", src state: " << print (obj.m_state) << ']'; } } // end of 'ex' } // end of 'market' } // end of namespace //----------------------------------------------------------------------------
22.271186
96
0.376712
vladium
bf907e9f5e5f84062729562f279fa88c83c05377
4,232
cpp
C++
src/game/game_state_phase1.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/game/game_state_phase1.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/game/game_state_phase1.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
namespace Phase1 { Logic::EntityID player_id; Physics::Body bordere_rect_container[4]; f32 progess; f32 saddness; f32 saddness_target; Vec4 START_COLOR = V4(0.1, 0.05, 0.05, 1.0); Vec4 END_COLOR = V4(0.3, 0.3, 0.3, 1.0); void setup(); void enter(); void update(f32 now, f32 delta); void draw(); void exit(); Mixer::AudioID tickID; void setup() {} Logic::LogicID leave_id; void enter() { current_exit(); Logic::update_callback(update_id, update, 0.0, Logic::FOREVER); Logic::update_callback(draw_id, draw, 0.0, Logic::FOREVER); current_exit = exit; enemy_spawner.set_phase(1); enemy_spawner.set_paused(false); cog_spawner.set_phase(11); cog_spawner.set_paused(false); cog_spawner.spawn_cog(V2(0.6, 0)); progess = 0; saddness_target = 1.0; saddness = saddness_target; auto leave = []() { if (progess >= 1.0) { LOG("cut"); Logic::update_callback(update_id, empty_func, 0.0, Logic::FOREVER); Logic::update_callback(draw_id, empty_func, 0.0, Logic::FOREVER); transitioning = true; Cutscene::enter(1); } }; leave_id = Logic::add_callback(Logic::POST_DRAW, leave, 0.0, Logic::FOREVER); PlayerPhase1 player; player.init(); player_id = Logic::add_entity(player); init_hit_particles(); tickID = Mixer::play_sound(2, ASSET_METRONOME_2, 1.0, Mixer::AUDIO_DEFAULT_GAIN, Mixer::AUDIO_DEFAULT_VARIANCE, Mixer::AUDIO_DEFAULT_VARIANCE, true); transitioning = false; } void update(f32 delta, f32 now) { if (transitioning) return; hitEnemy.update(delta); enemy_spawner.update(delta); cog_spawner.update(delta); PlayerPhase1 *player = (PlayerPhase1 *) Logic::fetch_entity(player_id); for (s32 i = cog_spawner.entities.size() - 1; i >= 0; i--) { GameEntity *cog = Logic::fetch_entity<GameEntity>(cog_spawner.entities[i]); if (Physics::check_overlap(&cog->body, &player->body)) { cog->hp = 0; pick_up_compliment(); // TODO: Fix this later progess = CLAMP(0, 1.0, progess + 0.2); saddness_target -= 0.2; } } for (s32 i = enemy_spawner.entities.size() - 1; i >= 0; i--) { GameEntity *enemy = Logic::fetch_entity<GameEntity>(enemy_spawner.entities[i]); Physics::Overlap overlap = Physics::check_overlap(&enemy->body, &player->body); if (overlap) { player->body.velocity += overlap.normal * 0.1; enemy->body.velocity -= overlap.normal * 0.1; hitEnemy.position = (player->body.position + enemy->body.position)/2; for (int i = 0; i < 300; i++) { hitEnemy.spawn(); } // TODO(ed): Which channel AssetID alts[] = { ASSET_SPACESUIT_HIT_1, ASSET_SPACESUIT_HIT_2, ASSET_SPACESUIT_HIT_3, ASSET_SPACESUIT_HIT_4, }; Mixer::play_sound(6, alts[random_int() % LEN(alts)]); saddness_target += 0.2; progess = CLAMP(0, 1.0, progess - 0.2); } } saddness_target = CLAMP(0, 1.0, saddness_target); Vec2 target = -player->body.position; Vec2 curr = Renderer::get_camera()->position; Renderer::get_camera()->position = LERP(curr, 2 * length(target - curr) * delta, target); } void draw() { if (transitioning) return; // Draw background Vec4 tint = LERP(START_COLOR, progess, END_COLOR); draw_sprite(0, -Renderer::get_camera(0)->position, 2, 0, Sprites::BACKGROUND, tint); saddness = LERP(saddness, Logic::delta() * 2, saddness_target); Renderer::vignette_strength = (saddness * saddness) * 4.5; Renderer::vignette_radius = (saddness * saddness) * 0.5; hitEnemy.draw(); stars.draw(); // Physics::Overlap curr_overlap = // Physics::check_overlap(&player1.player_body, &temp_rect); // Physics::solve(curr_overlap); // Physics::debug_draw_body(&temp_rect); } void exit() { Logic::remove_callback(leave_id); Logic::remove_entity(player_id); enemy_spawner.clear(); cog_spawner.clear(); Mixer::stop_sound(tickID); } }; // namespace Phase1
30.666667
153
0.615312
FredTheDino
bf95036bb06e29cfa2fd68d72ecebe00fe1ebe46
3,032
hpp
C++
include/rectojump/game/main_menu/background_main_menu.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/game/main_menu/background_main_menu.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/game/main_menu/background_main_menu.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
// // Copyright (c) 2013-2021 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #define RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/star5.hpp> #include <rectojump/game/components/triangles4.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <mlk/time/simple_timer.h> #include <mlk/tools/random_utl.h> namespace rj { template <typename Main_Menu> class background_main_menu { Main_Menu& m_mainmenu; background_manager<typename Main_Menu::gh_type>& m_backgroundmgr; const sf::Color m_fillcolor{settings::get_color_light()}; mlk::tm::simple_timer m_timer{300}; bool m_use_effects{settings::get_main_menu_effects()}; public: background_main_menu(Main_Menu& mm) : m_mainmenu{mm}, m_backgroundmgr{mm.gamehandler().backgroundmgr()} { this->init(); } void update(dur duration) { this->update_bg_objs(duration); } void update_bg_objs(dur duration) noexcept { if(!m_use_effects) return; if(m_timer.timed_out()) { auto size{settings::get_window_size<vec2f>()}; auto pos_x{mlk::rnd(0.f, size.x)}; auto length{mlk::rnd(30.f, 60.f)}; auto rotatestep{mlk::rnd(-0.1f, 0.5f)}; vec2f movestep{mlk::rnd(-0.3f, 0.5f), mlk::rnd(0.05f, 0.5f)}; auto object_type{mlk::rnd(0, 1)}; if(object_type) { auto ptr{ m_backgroundmgr.template create_object_for_state<star5>( state::main_menu, vec2f{pos_x, 0.f}, vec2f{0.f, length}, 5000, rotatestep, movestep)}; ptr->render_object().setFillColor( {m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); } else { auto ptr{m_backgroundmgr .template create_object_for_state<triangles4>( state::main_menu, vec2f{pos_x, 0.f}, vec2f{15.5f, 30.f}, 5000, rotatestep, movestep)}; ptr->render_object().setFillColor( {m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); } m_timer.restart(static_cast<mlk::ullong>( mlk::rnd<mlk::ullong>(70, 100) / duration)); } } void render() {} private: void init() { auto window_size{settings::get_window_size<vec2f>()}; // nova if(m_use_effects) { auto nova{m_backgroundmgr .template create_object_for_state<triangles4>( state::main_menu, vec2f{window_size.x / 2.f, window_size.y / 2.f}, vec2f{window_size.y / 3.f, window_size.x}, 0, 0.1f, vec2f{0.f, 0.f})}; nova->render_object().setFillColor(to_rgb("#bdbdbd", 100)); } // timer m_timer.run(); // set the background m_backgroundmgr.set_bg_shape( state::main_menu, {settings::get_window_size<vec2f>(), to_rgb("#373737"), to_rgb("#373737")}); } }; } #endif// RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP
27.816514
70
0.681728
Malekblubb
bf98fc7753949724cf8bfd66501702e6b1e1e137
710
cpp
C++
OpenGL_Triangle/src/TextureLoader.cpp
HeyIAmDave/OpenGL-Moving-Triangle
b820bdacc7bc8ff2ce8f0398663753b9761c1f4b
[ "MIT", "BSD-3-Clause" ]
null
null
null
OpenGL_Triangle/src/TextureLoader.cpp
HeyIAmDave/OpenGL-Moving-Triangle
b820bdacc7bc8ff2ce8f0398663753b9761c1f4b
[ "MIT", "BSD-3-Clause" ]
null
null
null
OpenGL_Triangle/src/TextureLoader.cpp
HeyIAmDave/OpenGL-Moving-Triangle
b820bdacc7bc8ff2ce8f0398663753b9761c1f4b
[ "MIT", "BSD-3-Clause" ]
1
2021-09-12T16:18:47.000Z
2021-09-12T16:18:47.000Z
#include "TextureLoader.h" #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> TextureLoader::TextureLoader() { } Texture & TextureLoader::Load(const std::string & filePath) { if (m_textures.find(filePath) == m_textures.end()) { int w, h; unsigned char* data = stbi_load(("./data/" + filePath).c_str(), &w, &h, 0, 4); if (data == NULL) printf("Error: failed to load texture: %s\n", filePath.c_str()); std::shared_ptr<Texture> texture = std::make_shared<Texture>(); texture->Init(data, w, h); stbi_image_free(data); m_textures[filePath] = texture; } return *m_textures[filePath]; } void TextureLoader::CleanUp() { for (auto& texture : m_textures) texture.second->CleanUp(); }
21.515152
80
0.68169
HeyIAmDave
bcc62a9abe019a1a84db55076b145ba228cb17f3
36,947
cpp
C++
DecompressLogo/DecompressLogo.cpp
clandrew/nhl94e
65faad66965f65f0f3a5080f9a38f5458b978849
[ "MIT" ]
2
2021-11-10T15:36:56.000Z
2021-11-10T16:16:40.000Z
DecompressLogo/DecompressLogo.cpp
clandrew/nhl94e
65faad66965f65f0f3a5080f9a38f5458b978849
[ "MIT" ]
null
null
null
DecompressLogo/DecompressLogo.cpp
clandrew/nhl94e
65faad66965f65f0f3a5080f9a38f5458b978849
[ "MIT" ]
null
null
null
// DecompressLogo.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <iomanip> #include <vector> #include <assert.h> std::vector<unsigned char> romData; std::vector<unsigned char> out; // Bootstrap // 1. Break-on-write 7FA671 // 2. Step in to the first jump- 80BDE1 // Snapshot is at // $80/BDC5 7C C8 BD JMP ($BDC8,x)[$80:BDE1] A:CE14 X:0010 Y:00CE P:envmXdizc // Initial values unsigned char decompressedValueDictionary_7E0500[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x1F, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x20, 0x40, 0x40, 0x40, 0x40, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFE, 0xFE, 0xFE, 0xFE, 0x06, 0x06, 0x0C, 0x0C, 0x0F, 0x0F, 0x18, 0x18, 0x30, 0x30, 0x3F, 0x3F, 0x60, 0x60, 0x70, 0x70, 0x7F, 0x7F, 0xB2, 0xB2, 0xF8, 0xF8, 0xFC, 0xFC, 0x05, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x11, 0x14, 0x1C, 0x1E, 0x21, 0x24, 0x28, 0x2F, 0x38, 0x3C, 0x78, 0x7E, 0x8F, 0x90, 0x9F, 0xA0, 0xB0, 0xBF, 0xDF, 0xEF, 0xF7, 0xF9, 0xFB, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x12, 0x12, 0x0C, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10 }; unsigned char array_7E0600[] = { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x12, 0x12, 0x0C, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x0D, 0x00, 0x0C, 0x00, 0x1E, 0x00 }; struct Regs { unsigned short A; unsigned short X; unsigned short Y; } regs; struct Wram { std::vector<unsigned char> Data; Wram() { unsigned char dataAt_7FA671_Write[] = { 0xCA, 0xFD, 0x0A, 0x00, 0x3B, 0x00, 0xCA, 0x8E, 0x00, 0x01, 0x10, 0x00, 0x9B, 0xCD, 0x81, 0x00, 0x00, 0x78, 0x7F, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x9E, 0x00, 0xCA, 0x00, 0x9E, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD2, 0x00, 0x00, 0x00, 0x03, 0x00, 0xF0, 0xFF, 0x00, 0x01, 0xF0, 0xFF, 0xE0, 0x00, 0xC9, 0xB4, 0x9B, 0x00, 0x00, 0x00, 0x40, 0x01, 0x40, 0x01, 0xD3, 0x16, 0x00, 0x00, 0xEC, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x4F, 0xC2, 0x89, 0xBC, 0x9B, 0x00, 0x10, 0x00, 0x24, 0x00, 0x50, 0xC2, 0x90, 0x00, 0x61, 0x00, 0x00, 0x00, 0x61, 0x00, 0xDF, 0x09, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x14, 0xCE, 0x00, 0x0D, 0x00, 0x08, 0x00, 0xB2, 0x07, 0x00, 0x10, 0xFF, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x06, 0x00, 0x00, 0x00, 0x00, 0xBC, 0x34, 0x7E, 0x00, 0xD8, 0xE4, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6A, 0x00, 0x20, 0x00, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x3D, 0x03, 0x00, 0x00, 0x5D, 0x01, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x7C, 0xEE, 0x9A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x90, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x80, 0x02, 0x03, 0x04, 0x07, 0x08, 0x10, 0x1F, 0x20, 0x40, 0xC0, 0xE0, 0xF0, 0xFE, 0x06, 0x0C, 0x0F, 0x18, 0x30, 0x3F, 0x60, 0x70, 0x7F, 0xB2, 0xF8, 0xFC, 0x05, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x11, 0x14, 0x1C, 0x1E, 0x21, 0x24, 0x28, 0x2F, 0x38, 0x3C, 0x78, 0x7E, 0x8F, 0x90, 0x9F, 0xA0, 0xB0, 0xBF, 0xDF, 0xEF, 0xF7, 0xF9, 0xFB, 0xFD, 0x12, 0x13, 0x15, 0x16, 0x17, 0x19, 0x1A, 0x1B, 0x1D, 0x22, 0x23, 0x25, 0x26, 0x2C, 0x31, 0x37, 0x3E, 0x41, 0x42, 0x43, 0x44, 0x47, 0x48, 0x4F, 0x50, 0x5F, 0x61, 0x6F, 0x7C, 0x81, 0x82, 0x83, 0x84, 0x86, 0x87, 0x88, 0x8C, 0x98, 0xAF, 0xB8, 0xC1, 0xC2, 0xC4, 0xC8, 0xCF, 0xD0, 0xD8, 0xE2, 0xE3, 0xE7, 0xE8, 0xF1, 0xF2, 0xF3, 0xF4, 0xF6, 0xFA, 0x27, 0x29, 0x2A, 0x2B, 0x2D, 0x2E, 0x33, 0x34, 0x35, 0x36, 0x39, 0x3B, 0x3D, 0x46, 0x4C, 0x4E, 0x58, 0x5C, 0x5E, 0x62, 0x63, 0x64, 0x66, 0x67, 0x68, 0x6A, 0x6C, 0x6E, 0x72, 0x73, 0x74, 0x76, 0x77, 0x79, 0x7B, 0x7D, 0x89, 0x8D, 0x8E, 0x91, 0x92, 0x9C, 0x9E, 0xA1, 0xA4, 0xAA, 0xB6, 0xB7, 0xBC, 0xBE, 0xC3, 0xC6, 0xC7, 0xCC, 0xD3, 0xD5, 0xD7, 0xDB, 0xDC, 0xDE, 0xE1, 0xE4, 0xE6, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xF5, 0x32, 0x3A, 0x45, 0x49, 0x4B, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x59, 0x5A, 0x5B, 0x65, 0x6B, 0x6D, 0x71, 0x75, 0x7A, 0x85, 0x8A, 0x8B, 0x93, 0x94, 0x95, 0x97, 0x99, 0x9A, 0x9B, 0x9D, 0xA3, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAB, 0xAC, 0xAE, 0xB1, 0xB3, 0xB4, 0xB9, 0xBA, 0xBB, 0xBD, 0xC5, 0xC9, 0xCB, 0xCD, 0xCE, 0xD1, 0xD4, 0xD6, 0xD9, 0xDA, 0xDD, 0xE5, 0xE9, 0x4A, 0x4D, 0x5D, 0x69, 0x96, 0xA2, 0xAD, 0xB5, 0xCA, 0xD2, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0x80, 0x06, 0x00, 0x00, 0x01, 0x0C, 0xC8, 0x8E, 0x40, 0x00, 0x00, 0x7A, 0x01, 0x38, 0xC9, 0x8E, 0x40, 0x00, 0x20, 0x7A, 0x01, 0x14, 0xCF, 0x8E, 0x40, 0x00, 0x40, 0x7A, 0x01, 0x64, 0xCA, 0x8E, 0x40, 0x00, 0x00, 0x7B, 0xFB, 0x06, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x1E, 0xFB, 0x10, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x1E, 0xFB, 0x1A, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x1F, 0xFB, 0x24, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x1F, 0xFB, 0x2E, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x20, 0xFB, 0x38, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x20, 0xFB, 0x42, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x21, 0xFB, 0x4C, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x21, 0xFB, 0x56, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x22, 0xFB, 0x60, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x22, 0xFB, 0x6A, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x23, 0xFB, 0x74, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x23, 0x01, 0x43, 0x68, 0x7F, 0x80, 0x01, 0x20, 0x62, 0x01, 0xC3, 0x69, 0x7F, 0x40, 0x01, 0x20, 0x63, 0xFA, 0x00, 0x00, 0x7F, 0x00, 0x10, 0x00, 0x20, 0xFA, 0x00, 0x10, 0x7F, 0xC0, 0x02, 0x00, 0x30, 0xFB, 0x06, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1E, 0xFB, 0x12, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1E, 0xFB, 0x1E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1F, 0xFB, 0x2A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1F, 0xFB, 0x36, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x20, 0xFB, 0x42, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x20, 0xFB, 0x4E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x21, 0xFB, 0x5A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x21, 0xFB, 0x66, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x22, 0xFB, 0x72, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x22, 0xFB, 0x7E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x23, 0xFB, 0x8A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x23, 0xFB, 0x06, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x1F, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0xC0, 0x04, 0x00, 0x00, 0x01, 0xC8, 0x6B, 0x7F, 0x20, 0x09, 0x00, 0x64, 0x01, 0xE8, 0x74, 0x7F, 0x00, 0x01, 0x00, 0x69, 0xFB, 0x06, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1E, 0xFB, 0x12, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1E, 0xFB, 0x1E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1F, 0xFB, 0x2A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1F, 0xFB, 0x36, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x20, 0xFB, 0x42, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x20, 0xFB, 0x4E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x21, 0xFB, 0x5A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x21, 0xFB, 0x66, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x22, 0xFB, 0x72, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x22, 0xFB, 0x7E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x23, 0xFB, 0x8A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x23, 0xFB, 0x06, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x1F, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0x40, 0x06, 0x00, 0x00, 0x01, 0x2F, 0x76, 0x7F, 0xC0, 0x01, 0x00, 0x6A, 0x01, 0xEF, 0x77, 0x7F, 0xC0, 0x01, 0x00, 0x6B, 0xFB, 0x06, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1E, 0xFB, 0x12, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1E, 0xFB, 0x1E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1F, 0xFB, 0x2A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1F, 0xFB, 0x36, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x20, 0xFB, 0x42, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x20, 0xFB, 0x4E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x21, 0xFB, 0x5A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x21, 0xFB, 0x66, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x22, 0xFB, 0x72, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x22, 0xFB, 0x7E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x23, 0xFB, 0x8A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x23, 0xFB, 0x06, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x1F, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0x80, 0x06, 0x00, 0x00, 0x01, 0xD4, 0xC8, 0x8E, 0x40, 0x00, 0x00, 0x7A, 0x01, 0x38, 0xC9, 0x8E, 0x40, 0x00, 0x20, 0x7A, 0x01, 0xB0, 0xCE, 0x8E, 0x40, 0x00, 0x40, 0x7A, 0x01, 0xC8, 0xCA, 0x8E, 0x40, 0x00, 0x60, 0x7A, 0x01, 0x00, 0xCA, 0x8E, 0x40, 0x00, 0x80, 0x7A, 0x01, 0xBC, 0xCC, 0x8E, 0x40, 0x00, 0xA0, 0x7A, 0x01, 0xA8, 0xC7, 0x8E, 0x40, 0x00, 0xC0, 0x7A, 0x01, 0x84, 0xCD, 0x8E, 0x40, 0x00, 0xE0, 0x7A, 0x01, 0x14, 0xCF, 0x8E, 0x40, 0x00, 0x00, 0x7B, 0x01, 0x0C, 0xC8, 0x8E, 0x40, 0x00, 0x20, 0x7B, 0x01, 0x08, 0xD1, 0x8E, 0x40, 0x00, 0x40, 0x7B, 0x01, 0x58, 0xCC, 0x8E, 0x40, 0x00, 0x60, 0x7B, 0x01, 0x70, 0xC8, 0x8E, 0x40, 0x00, 0x80, 0x7B, 0x01, 0x64, 0xCA, 0x8E, 0x40, 0x00, 0xA0, 0x7B, 0x01, 0xF4, 0xCB, 0x8E, 0x40, 0x00, 0xC0, 0x7B, 0x01, 0x4C, 0xCE, 0x8E, 0x40, 0x00, 0xE0, 0x7B, 0x01, 0x20, 0xCD, 0x8E, 0x40, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x1F, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x20, 0x40, 0x40, 0x40, 0x40, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFE, 0xFE, 0xFE, 0xFE, 0x06, 0x06, 0x0C, 0x0C, 0x0F, 0x0F, 0x18, 0x18, 0x30, 0x30, 0x3F, 0x3F, 0x60, 0x60, 0x70, 0x70, 0x7F, 0x7F, 0xB2, 0xB2, 0xF8, 0xF8, 0xFC, 0xFC, 0x05, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x11, 0x14, 0x1C, 0x1E, 0x21, 0x24, 0x28, 0x2F, 0x38, 0x3C, 0x78, 0x7E, 0x8F, 0x90, 0x9F, 0xA0, 0xB0, 0xBF, 0xDF, 0xEF, 0xF7, 0xF9, 0xFB, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x12, 0x12, 0x0C, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x0D, 0x00, 0x0C, 0x00, 0x1E, 0x00, 0x39, 0x00, 0x45, 0x00, 0x3D, 0x00, 0x0A, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x08, 0x00, 0x14, 0x00, 0x39, 0x00, 0x8F, 0x00, 0x59, 0x01, 0x26, 0x03, 0x05, 0x07, 0x00, 0x0F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x50, 0x00, 0x60, 0x00, 0x94, 0x00, 0xAC, 0x00, 0xCA, 0x80, 0xE6, 0xC0, 0xF7, 0x60, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDD, 0xBF, 0x8F, 0x00, 0x78, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x7C, 0xEE, 0x9A, 0x00, 0x00, 0x00, 0x9C, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x0F, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x99, 0x9C, 0x19, 0x80, 0x80, 0x4E, 0x85, 0x00, 0x00, 0xBD, 0xF6, 0xAD, 0x45, 0x41, 0x43, 0x44, 0x53, 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x24, 0x00, 0x21, 0x20, 0x23, 0x3C, 0x00, 0x31, 0x25, 0x03, 0x00, 0x00, 0x60, 0x00, 0x00, 0xA0, 0x01, 0x0F, 0x00, 0x30, 0x24, 0x10, 0x22, 0x00, 0x00, 0x02, 0x00, 0xA4, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0xC2, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x25, 0x41, 0x00, 0x50, 0x00, 0x00, 0x69, 0x00, 0x68, 0x00, 0x00, 0x0E, 0x0E, 0x00, 0x00, 0x4F, 0xC2, 0xA5, 0xC3, 0xB7, 0xC4, 0x3C, 0xC5, 0xD5, 0xC5, 0x49, 0xC6, 0x17, 0xCA, 0x39, 0xCE, 0x4F, 0xD0, 0xC3, 0xD3, 0x29, 0xDC, 0xAC, 0xDC, 0x65, 0xDE, 0x15, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0xC2, 0x92, 0xC3, 0x98, 0xC4, 0x28, 0xC5, 0xC2, 0xC5, 0x26, 0xC6, 0xF4, 0xC9, 0x16, 0xCE, 0x40, 0xD0, 0xB6, 0xD3, 0x16, 0xDC, 0x94, 0xDC, 0x4E, 0xDE, 0x06, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x45, 0x00, 0x2D, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x89, 0xBC, 0x59, 0xBC, 0xF9, 0xB5, 0x09, 0xB8, 0x59, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, 0xB5, 0x00, 0x00, 0x39, 0xBB, 0xF9, 0xBB, 0x29, 0xBC, 0xC9, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x50, 0x5C, 0x36, 0x40, 0x43, 0x01, 0x01, 0x01, 0x7F, 0x01, 0x45, 0x7F, 0x31, 0x61, 0x00, 0x00, 0x00, 0x4F, 0x5C, 0x42, 0x61, 0x59, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x4C, 0x40, 0x61, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; for (int i = 0; i < _countof(dataAt_7FA671_Write); ++i) { Data.push_back(dataAt_7FA671_Write[i]); } } unsigned char& Key_Byte_6C() { return Data[0x6C]; } void ShiftLeft_Key_6C() { Data[0x6C] *= 2; } unsigned short GetShort_6C() { return GetShort(0x6C); } void SetShort_6C(unsigned short val) { SetShort(0x6C, val); } void SetLowByteOfShort(int addr, unsigned short val) { unsigned char ch0 = val & 0xFF; Data[addr] = ch0; } void SetShort(int addr, unsigned short val) { unsigned char ch0 = val & 0xFF; unsigned char ch1 = val >> 8; Data[addr] = ch0; Data[addr+1] = ch1; } unsigned char& LastWrittenValue_08() { return Data[0x08]; } unsigned char& ArrayIndex_6D() { return Data[0x6D]; } unsigned short GetByte(int addr) { unsigned char ch0 = Data[addr]; return ch0; } void GetLowByteOfShort(int addr, unsigned short* result) { unsigned char ch0 = Data[addr]; *result &= 0xFF00; *result |= ch0; } unsigned short GetShort(int addr) { unsigned char ch0 = Data[addr]; unsigned char ch1 = Data[addr+1]; unsigned short r = 0; r |= (ch1 << 8); r |= ch0; return r; } int GetLongPointer_0C() { unsigned char ch0 = Data[0xC]; unsigned char ch1 = Data[0xD]; int addr = 0x810000; addr |= (ch1 << 8); addr |= ch0; return addr; } void IncrementPointer_0C() { unsigned char& ch0 = Data[0xC]; ch0++; if (ch0 != 0) return; unsigned char& ch1 = Data[0xD]; assert(ch1 < 0xFF); ch1++; } } wram; int jumpElements_BCF9[] = { 0, 0, 0, 0, 0, 0, 0x80BEAE, 0, 0, 0, 0, 0, 0, 0, 0x80BD70 }; int jumpElements_BD2D[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80BEF2, 0, 0x80BF44 }; int jumpElements_BD7A[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0x80BEF3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80BD8E }; int jumpElements_BDC8[] = { 0x80BE04, 0x0, 0x80BE53, 0x0, 0x80BEA3, 0x0, 0x80BEF4, 0x0, 0x80BF46, 0x0, 0x80BD0D, 0x0, 0x80BD59, 0x0, 0x80BDA6, 0x0, 0x80BDE1, 0x0, 0x80BDDC }; int jumpElements_BE67[] = { 0x80BEA5, 0x0, 0x80BEF6, 0x0, 0x80BF48, 0x0, 0x80BD0F, 0x0, 0x80BD5B, 0x0, 0x80BDA8, 0x0, 0x80BDF6, 0x0, 0x80BE45, 0x0, 0x80BE80 }; int jumpElements_BEB8[] = { 0x80BEF7, 0x0, 0x80BF49, 0x0, 0x80BD10, 0x0, 0x80BD5C, 0x0, 0x80BDA9, 0x0, 0x80BDF7, 0x0, 0x80BE46, 0x0, 0x80BE96, 0x0, 0x80BED1, 0x0, 0x80BECC }; int jumpElements_BF0A[] = { 0, 0, 0x80BD11 }; int jumpElements_BF5D[] = { 0x80BD12, 0x0, 0x80BD5E, 0x0, 0x80BDAB, 0x0, 0x80BDF9, 0x0, 0x80BE48, 0x0, 0x80BE98, 0x0, 0x80BEE9, 0x0, 0x80BF3B, 0x0, 0x80BF76, 0x0, 0x80BF71 }; int jumpValue = 0; int previousJumpValue = 0; int ROMAddressToFileOffset(int romAddress) { assert(romAddress >= 0x800000); // Lower ones haven't been tested int offsetWithinSection = romAddress % 0x8000; int section = (romAddress - 0x800000) >> 16; int offset = section * 0x8000 + offsetWithinSection; return offset; } int FileOffsetToROMAddress(int fileOffset) { int section = fileOffset / 0x8000; int offsetWithinSection = fileOffset % 0x8000; int addr = 0x800000 + (section * 0x10000) + 0x8000 + offsetWithinSection; return addr; } unsigned short GetROMDataShort(int ptr) { unsigned char data0 = romData[ROMAddressToFileOffset(ptr)]; unsigned char data1 = romData[ROMAddressToFileOffset(ptr+1)]; return (data1 << 8) | data0; } void SetJumpValue(int newValue) { previousJumpValue = jumpValue; jumpValue = newValue; } void Impl_BC02() { assert(false); // incomplete impl regs.A = wram.GetShort(0x75); wram.SetShort(0x0, regs.A); } void Impl_BD11() { regs.A *= 4; unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.X = decompressedValueDictionary_7E0500[regs.Y]; out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); unsigned short x = wram.GetShort(0x600 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; SetJumpValue(jumpElements_BD2D[regs.X]); } void Impl_BD5E() { regs.A *= 2; unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.A *= 2; unsigned short x = wram.GetShort(0x500 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; unsigned char decompressed = x & 0xFF; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); x = wram.GetShort(0x600 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; SetJumpValue(jumpElements_BD7A[regs.X]); } void Impl_BD70() { wram.SetLowByteOfShort(0x6C, regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); regs.X = array_7E0600[regs.Y]; SetJumpValue(jumpElements_BD7A[regs.X]); } void Impl_BD8E() { regs.X = 0xE; SetJumpValue(0x80C17C); } void Impl_BDA6(int multiplier) { regs.A *= multiplier; // Set 8-bit acc for just this part unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.A *= 4; unsigned short x = wram.GetShort(0x500 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; unsigned char decompressed = x & 0xFF; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); x = wram.GetShort(0x600 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; SetJumpValue(jumpElements_BDC8[regs.X]); } void Impl_BDE1() { regs.X = 0x0C; wram.Data[0x6A] = 0; regs.A = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF; regs.A *= 2; regs.A *= 2; regs.A |= wram.GetShort(0x6B); wram.SetShort(0x6B, regs.A); regs.A = wram.GetShort_6C(); SetJumpValue(0x80BFDD); } void Impl_BE0D() { // C153 // BE0D jump wram.SetShort_6C(regs.A); regs.Y = wram.GetShort(0x6D); regs.Y &= 0xFF; regs.X = wram.GetShort(0x600 + regs.Y); regs.X &= 0xFF; // This is in 8-bit index mode assert(regs.X == 2); SetJumpValue(0x80BEA4); } void Impl_BE53() { regs.A *= 4; regs.X = wram.GetShort(0x500 + regs.Y); out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); wram.GetLowByteOfShort(0x600 + regs.Y, &regs.X); SetJumpValue(jumpElements_BE67[regs.X]); } void Impl_BE96(int multiplier) { regs.A *= multiplier; unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.A *= 32; wram.GetLowByteOfShort(0x500 + regs.Y, &regs.X); out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); wram.GetLowByteOfShort(0x600 + regs.Y, &regs.X); SetJumpValue(jumpElements_BEB8[regs.X]); } void Impl_BEA4() { // Jump to ($BE17, x) meaning we look at address 80BE17+2 which contains short address BEA4 // Jump to BEA4 regs.A *= 4; assert(regs.Y == 0x29); regs.X = wram.GetShort(0x500 + regs.Y); out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); wram.GetLowByteOfShort(0x600 + regs.Y, &regs.X); SetJumpValue(jumpElements_BEB8[regs.X]); } void Impl_BEAE() // Could merge with last part of Impl_BEA4 { wram.SetShort_6C(regs.A); regs.Y = wram.GetShort(0x6D); regs.Y &= 0xFF; regs.X = wram.GetShort(0x600 + regs.Y); regs.X &= 0xFF; // This is in 8-bit index mode SetJumpValue(jumpElements_BEB8[regs.X]); } void Impl_BEB5() { regs.X = 0x6; SetJumpValue(0x80C17C); } void Impl_BECC() { regs.X = 0x6; SetJumpValue(0x80C17C); } void Impl_BEF2(int multiplier) { regs.A *= multiplier; unsigned char decompressed = decompressedValueDictionary_7E0500[regs.Y]; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); unsigned short x = wram.GetShort(0x600 + regs.Y); unsigned char xLow = x & 0xFF; regs.X &= 0xFF00; regs.X |= xLow; SetJumpValue(jumpElements_BF0A[regs.X]); } void Impl_BF44(int multiplier) { regs.A *= multiplier; unsigned char decompressed = decompressedValueDictionary_7E0500[regs.Y]; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); unsigned short x = wram.GetShort(0x600 + regs.Y); unsigned char xLow = x & 0xFF; regs.X &= 0xFF00; regs.X |= xLow; SetJumpValue(jumpElements_BF5D[regs.X]); } void Impl_BFDD() { unsigned short val0750 = wram.GetShort(0x750); if (val0750 == 0xE680) { // BF8F regs.A /= 128; unsigned short val0730 = wram.GetShort(0x730); regs.A -= val0730; regs.Y = regs.A; regs.A = wram.GetByte(0x100 + regs.Y); regs.Y = 1; unsigned char val73 = wram.GetByte(0x73); if (val73 == 0) { // BFC2 // untested assert(false); } else { // BFA6 // Jumped right to C0E8 // WriteImpl unsigned char b = regs.A & 0xFF; out.push_back(b); wram.LastWrittenValue_08() = b; wram.IncrementPointer_0C(); regs.A = wram.GetShort(0x6B); assert(regs.X == 0xC); SetJumpValue(0x80C10E); } } else { // Fall thru to BFE2 assert(false); // untested } } void Fn_C2DC() { regs.A = wram.GetShort_6C(); regs.Y = wram.GetShort(0x74); // Dunno what this is do { regs.A *= 2; regs.X -= 2; if (regs.X == 0) { unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A = regs.A & 0xFF00; regs.A = regs.A | low; wram.IncrementPointer_0C(); regs.X = 16; } regs.Y--; } while (regs.Y > 0); } unsigned short RotateLeft(unsigned short v, bool& carry) { bool high = v >= 0x8000; v = v << 1; if (carry) { v |= 1; } carry = high; return v; } void Fn_C232() { // Postconditions: Result1_08 contains the repeated value and Result0_A contains the repeat count. wram.SetShort(0x6F, 0); regs.A = wram.GetShort_6C(); bool carry = regs.A > 0x7FFF; regs.A = regs.A * 2; regs.X-=2; if (regs.X == 0) { // goto C250 assert(false); } else { if (!carry) // went to C277 { regs.Y = 2; bool carry = regs.A > 0x7FFF; regs.A = regs.A * 2; regs.X -= 2; if (regs.X == 0) { // goto C2A2 assert(false); } regs.Y++; if (!carry) { // goto c279 assert(false); } else { wram.SetShort(0x14, regs.Y); while (1) // C283 { carry = regs.A > 0x7FFF; regs.A = regs.A * 2; unsigned short val1 = wram.GetShort(0x6f); unsigned short val2 = RotateLeft(val1, carry); wram.SetShort(0x6F, val2); regs.X -= 2; if (regs.X == 0) { // C2AE unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A = regs.A & 0xFF00; regs.A = regs.A | low; wram.IncrementPointer_0C(); regs.X = 0x10; } regs.Y--; // C28A if (regs.Y != 0) { // Continue in loop } else { // C28D wram.SetShort_6C(regs.A); regs.Y = regs.X; regs.A = wram.GetShort(0x14); regs.A = regs.A & 0xFF; regs.A *= 2; regs.X = regs.A; int loadAddress = 0x80C2B6 + regs.A; regs.A = GetROMDataShort(loadAddress); regs.X = regs.Y; regs.A += wram.GetShort(0x6F); wram.SetShort(0x6F, regs.A); return; } } } } else { // fell thru to C23D assert(false); } } } void Impl_C10E() { // takes an acc parameter regs.A *= 2; regs.Y--; if (regs.Y == 0) { SetJumpValue(0x80BE0D); } else { assert(false); // untested } } void Impl_C17C() { wram.GetLowByteOfShort(0x74, &regs.Y); Fn_C2DC(); wram.SetShort_6C(regs.A); Fn_C232(); unsigned char repeatingValue = wram.LastWrittenValue_08(); int repeatCount = regs.A; if (repeatCount == 0) { SetJumpValue(0x80C195); return; } for (int i = 0; i < repeatCount; ++i) { out.push_back(repeatingValue); } regs.A = wram.GetShort_6C(); SetJumpValue(jumpElements_BCF9[regs.X]); } int main() { FILE* file{}; fopen_s(&file, "E:\\Emulation\\SNES\\Images\\Test\\nhl94.sfc", "rb"); fseek(file, 0, SEEK_END); long length = ftell(file); romData.resize(length); fseek(file, 0, SEEK_SET); fread(romData.data(), 1, length, file); fclose(file); // Initial values SetJumpValue(0x80BDE1); regs.A = 0xCE14; regs.X = 0X10; regs.Y = 0xCE; for (int i = 0; i < 37; ++i) { switch (jumpValue) { case 0x80BD11: Impl_BD11(); break; case 0x80BD5E: Impl_BD5E(); break; case 0x80BD70: Impl_BD70(); break; case 0x80BD8E: Impl_BD8E(); break; case 0x80BDA6: Impl_BDA6(64); break; case 0x80BDA7: Impl_BDA6(32); break; case 0x80BDA8: Impl_BDA6(16); break; case 0x80BDA9: Impl_BDA6(8); break; case 0x80BDAA: Impl_BDA6(4); break; case 0x80BDAB: Impl_BDA6(2); break; case 0x80BDAC: Impl_BDA6(1); break; case 0x80BDE1: Impl_BDE1(); break; case 0x80BE0D: Impl_BE0D(); break; case 0x80BE53: Impl_BE53(); break; case 0x80BE98: Impl_BE96(2); break; case 0x80BEA4: Impl_BEA4(); break; case 0x80BEAE: Impl_BEAE(); break; case 0x80BEB5: Impl_BEB5(); break; case 0x80BECC: Impl_BECC(); break; case 0x80BEF2: Impl_BEF2(64); break; case 0x80BEF3: Impl_BEF2(32); break; case 0x80BF44: Impl_BF44(128); break; case 0x80BF45: Impl_BF44(64); break; case 0x80BF46: Impl_BF44(32); break; case 0x80BF47: Impl_BF44(16); break; case 0x80BF48: Impl_BF44(8); break; case 0x80BF49: Impl_BF44(4); break; case 0x80BF4A: Impl_BF44(2); break; case 0x80BF4B: Impl_BF44(1); break; case 0x80BFDD: Impl_BFDD(); break; case 0x80C10E: Impl_C10E(); break; case 0x80C17C: Impl_C17C(); break; default: assert(false); } } unsigned char expected[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x07, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x01, 0x07, 0x03, 0x0F, 0x07 }; for (int i = 0; i < out.size(); ++i) { int val = out[i]; std::cout << std::hex << std::setw(2) << val << " "; if (i % 16 == 15) { std::cout << "\n"; } } } // SEP #$20 - Use 8-bit accumulator mode // REP #$20 - Use 16-bit accumulator mode // SEP #$10 - Use 8-bit indexing mode // REP #$10 - Use 16-bit indexing mode
48.614474
13,873
0.598235
clandrew
bccad925333905252f09ea9d654acc9f88ac598b
4,090
cpp
C++
code archive/CF/1079G.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/CF/1079G.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/CF/1079G.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
//{ #include<bits/stdc++.h> using namespace std; typedef int ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define REP1(i,n) for(ll i=1;i<=n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #define IOS() #else #define debug(...) #define pary(...) #define endl '\n' #define IOS() ios_base::sync_with_stdio(0);cin.tie(0); #endif // brian //} const ll MAXn=2e5+5,MAXlg=__lg(MAXn)+2; const ll MOD=1000000007; const ll INF=ll(1e9); struct node{ ll l,r; node *lc,*rc; ll dtl,dtr; void pull(){ dtl = min(lc->dtl,rc->dtl); dtr = max(lc->dtr,rc->dtr); } void insl(ll x,ll k) { if(l == r-1)dtl = min(dtl,k); else { if(x < (l+r)/2)lc->insl(x,k); else rc->insl(x,k); pull(); } } void insr(ll x,ll k) { if(l == r-1)dtr = max(dtr,k); else { if(x < (l+r)/2)lc->insr(x,k); else rc->insr(x,k); pull(); } } ll qrl(ll li,ll ri) { if(li >= r || ri <= l)return INF; else if(li <= l && ri >= r)return dtl; else return min(lc->qrl(li,ri),rc->qrl(li,ri)); } ll qrr(ll li,ll ri) { if(li >= r || ri <= l)return -1; else if(li <= l && ri >= r)return dtr; else return max(lc->qrr(li,ri),rc->qrr(li,ri)); } void clr() { dtl = INF,dtr = -1; if(l == r-1)return; if(lc->dtl != INF || lc->dtr != -1)lc->clr(); if(rc->dtl != INF || rc->dtr != -1)rc->clr(); } }; node *build(ll l,ll r) { if(l == r-1)return new node{l,r,0,0,INF,-1}; else return new node{l,r,build(l,(l+r)/2),build((l+r)/2,r),INF,-1}; } ll d[MAXn]; ll l[MAXn][MAXlg],r[MAXn][MAXlg],nl[MAXn],nr[MAXn],ct[MAXn]; node *rt; int main() { IOS(); ll n,nn; cin>>n; nn = 2 * n; if(n == 1) { cout<<0<<endl; return 0; } rt = build(0,nn); REP(i,n)cin>>d[i]; REP(i,n)d[n + i] = d[i]; REP(i,nn)l[i][0] = max(0,i - d[i]),r[i][0] = min(nn-1,i + d[i]); for(int i = 0; i < nn;i ++)nl[i] = nr[i] = i,ct[i] = 0; REP1(i,MAXlg-1) { //rt->clr(); REP(j,nn) { rt->insl(j,l[j][i-1]),rt->insr(j,r[j][i-1]); } REP(j,nn) { l[j][i] = rt->qrl(l[j][i-1],r[j][i-1]+1); r[j][i] = rt->qrr(l[j][i-1],r[j][i-1]+1); } } for(int i = MAXlg-1;i > 0;i--) { rt->clr(); REP(j,nn) { rt->insl(j,l[j][i-1]),rt->insr(j,r[j][i-1]); } for(int j = 0; j < nn;j ++) { ll tmpl = rt->qrl(nl[j],nr[j]+1); ll tmpr = rt->qrr(nl[j],nr[j]+1); if(tmpr - tmpl + 1 < n) { nl[j] = tmpl, nr[j] = tmpr; ct[j] += (1<<(i-1)); } } } for(int j = 0; j < n;j ++)cout<<min(ct[j],ct[j+n])+1<<" "; }
25.5625
129
0.476528
brianbbsu
bccbb768c15017dd2a04701b65a8bfead74a8802
12,924
hpp
C++
Engine/Code/Engine/Core/App.hpp
cugone/Abrams2019
0b94c43275069275bbbeadfa773c336fa1947882
[ "MIT" ]
1
2020-07-14T06:58:50.000Z
2020-07-14T06:58:50.000Z
Engine/Code/Engine/Core/App.hpp
cugone/Abrams2019
0b94c43275069275bbbeadfa773c336fa1947882
[ "MIT" ]
1
2020-04-06T06:52:11.000Z
2020-04-06T06:52:19.000Z
Engine/Code/Engine/Core/App.hpp
cugone/Abrams2019
0b94c43275069275bbbeadfa773c336fa1947882
[ "MIT" ]
2
2019-05-01T21:49:33.000Z
2021-04-01T08:22:21.000Z
#pragma once #include "Engine/Audio/AudioSystem.hpp" #include "Engine/Core/Config.hpp" #include "Engine/Core/Console.hpp" #include "Engine/Core/EngineConfig.hpp" #include "Engine/Core/EngineCommon.hpp" #include "Engine/Core/EngineSubsystem.hpp" #include "Engine/Core/FileLogger.hpp" #include "Engine/Core/JobSystem.hpp" #include "Engine/Core/KeyValueParser.hpp" #include "Engine/Core/StringUtils.hpp" #include "Engine/Core/TimeUtils.hpp" #include "Engine/Input/InputSystem.hpp" #include "Engine/Physics/PhysicsSystem.hpp" #include "Engine/Profiling/AllocationTracker.hpp" #include "Engine/Renderer/Renderer.hpp" #include "Engine/Renderer/Window.hpp" #include "Engine/Services/IAudioService.hpp" #include "Engine/Services/IAppService.hpp" #include "Engine/Services/IConfigService.hpp" #include "Engine/Services/IFileLoggerService.hpp" #include "Engine/Services/IInputService.hpp" #include "Engine/Services/IJobSystemService.hpp" #include "Engine/Services/IRendererService.hpp" #include "Engine/Services/IPhysicsService.hpp" #include "Engine/Services/ServiceLocator.hpp" #include "Engine/System/System.hpp" #include "Engine/UI/UISystem.hpp" #include "Engine/Game/GameBase.hpp" #include <algorithm> #include <condition_variable> #include <iomanip> #include <memory> template<typename T> class App : public EngineSubsystem, public IAppService { public: App() noexcept = default; explicit App(const std::string& title, const std::string& cmdString); App(const App& other) = default; App(App&& other) = default; App& operator=(const App& other) = default; App& operator=(App&& other) = default; using GameType = T; static_assert(std::is_base_of_v<std::remove_cv_t<std::remove_reference_t<std::remove_pointer_t<GameBase>>>, std::remove_cv_t<std::remove_reference_t<std::remove_pointer_t<GameType>>>>); virtual ~App() noexcept; static void CreateApp(const std::string& title, const std::string& cmdString) noexcept; static void DestroyApp() noexcept; void InitializeService() override; void RunFrame() override; bool IsQuitting() const override; void SetIsQuitting(bool value) override; bool HasFocus() const override; bool LostFocus() const override; bool GainedFocus() const override; protected: private: void RunMessagePump() const; void SetupEngineSystemPointers(); void SetupEngineSystemChainOfResponsibility(); void Initialize() noexcept override; void BeginFrame() noexcept override; void Update(TimeUtils::FPSeconds deltaSeconds) noexcept override; void Render() const noexcept override; void EndFrame() noexcept override; bool ProcessSystemMessage(const EngineMessage& msg) noexcept override; void LogSystemDescription() const; bool _isQuitting = false; bool _current_focus = false; bool _previous_focus = false; std::string _title{"UNTITLED GAME"}; std::unique_ptr<JobSystem> _theJobSystem{}; std::unique_ptr<FileLogger> _theFileLogger{}; std::unique_ptr<Config> _theConfig{}; std::unique_ptr<Renderer> _theRenderer{}; std::unique_ptr<Console> _theConsole{}; std::unique_ptr<PhysicsSystem> _thePhysicsSystem{}; std::unique_ptr<InputSystem> _theInputSystem{}; std::unique_ptr<UISystem> _theUI{}; std::unique_ptr<AudioSystem> _theAudioSystem{}; std::unique_ptr<GameType> _theGame{}; static inline std::unique_ptr<App<GameType>> _theApp{}; static inline NullAppService _nullApp{}; }; namespace detail { bool CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); EngineMessage GetEngineMessageFromWindowsParams(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); } template<typename T> /*static*/ void App<T>::CreateApp(const std::string& title, const std::string& cmdString) noexcept { if(_theApp) { return; } _theApp = std::make_unique<App<T>>(title, cmdString); ServiceLocator::provide(*static_cast<IAppService*>(_theApp.get())); } template<typename T> /*static*/ void App<T>::DestroyApp() noexcept { if(!_theApp) { return; } _theApp.reset(nullptr); } template<typename T> App<T>::App(const std::string& title, const std::string& cmdString) : EngineSubsystem() , _title{title} , _theConfig{std::make_unique<Config>(KeyValueParser{cmdString})} { SetupEngineSystemPointers(); SetupEngineSystemChainOfResponsibility(); LogSystemDescription(); } template<typename T> App<T>::~App() noexcept { if(g_theApp<T>) { g_theSubsystemHead = g_theApp<T>; } } template<typename T> void App<T>::SetupEngineSystemPointers() { ServiceLocator::provide(*static_cast<IConfigService*>(_theConfig.get())); _theJobSystem = std::make_unique<JobSystem>(-1, static_cast<std::size_t>(JobType::Max), new std::condition_variable); ServiceLocator::provide(*static_cast<IJobSystemService*>(_theJobSystem.get())); _theFileLogger = std::make_unique<FileLogger>("game"); ServiceLocator::provide(*static_cast<IFileLoggerService*>(_theFileLogger.get())); _thePhysicsSystem = std::make_unique<PhysicsSystem>(); ServiceLocator::provide(*static_cast<IPhysicsService*>(_thePhysicsSystem.get())); _theRenderer = std::make_unique<Renderer>(); ServiceLocator::provide(*static_cast<IRendererService*>(_theRenderer.get())); _theInputSystem = std::make_unique<InputSystem>(); ServiceLocator::provide(*static_cast<IInputService*>(_theInputSystem.get())); _theAudioSystem = std::make_unique<AudioSystem>(); ServiceLocator::provide(*static_cast<IAudioService*>(_theAudioSystem.get())); _theUI = std::make_unique<UISystem>(); _theConsole = std::make_unique<Console>(); _theGame = std::make_unique<GameType>(); g_theJobSystem = _theJobSystem.get(); g_theFileLogger = _theFileLogger.get(); g_theConfig = _theConfig.get(); g_theRenderer = _theRenderer.get(); g_theUISystem = _theUI.get(); g_theConsole = _theConsole.get(); g_thePhysicsSystem = _thePhysicsSystem.get(); g_theInputSystem = _theInputSystem.get(); g_theAudioSystem = _theAudioSystem.get(); g_theGame = _theGame.get(); g_theApp<T> = this; } template<typename T> void App<T>::SetupEngineSystemChainOfResponsibility() { g_theConsole->SetNextHandler(g_theUISystem); g_theUISystem->SetNextHandler(g_theInputSystem); g_theInputSystem->SetNextHandler(g_thePhysicsSystem); g_thePhysicsSystem->SetNextHandler(g_theRenderer); g_theRenderer->SetNextHandler(g_theApp<T>); g_theApp<T>->SetNextHandler(nullptr); g_theSubsystemHead = g_theConsole; } template<typename T> void App<T>::Initialize() noexcept { auto& settings = g_theGame->GetSettings(); bool vsync = settings.DefaultVsyncEnabled(); if(g_theConfig->HasKey("vsync")) { g_theConfig->GetValue(std::string{"vsync"}, vsync); } else { g_theConfig->SetValue(std::string{"vsync"}, vsync); } settings.SetVsyncEnabled(vsync); int width = settings.DefaultWindowWidth(); int height = settings.DefaultWindowHeight(); if(g_theConfig->HasKey("width")) { g_theConfig->GetValue(std::string{"width"}, width); } else { g_theConfig->SetValue(std::string{"width"}, width); } if(g_theConfig->HasKey("height")) { g_theConfig->GetValue(std::string{"height"}, height); } else { g_theConfig->SetValue(std::string{"height"}, height); } settings.SetWindowResolution(IntVector2{width, height}); g_theRenderer->Initialize(); g_theRenderer->SetVSync(vsync); auto* output = g_theRenderer->GetOutput(); output->SetTitle(_title); output->GetWindow()->custom_message_handler = detail::WindowProc; g_theUISystem->Initialize(); g_theInputSystem->Initialize(); g_theConsole->Initialize(); g_theAudioSystem->Initialize(); g_thePhysicsSystem->Initialize(); g_theGame->Initialize(); } template<typename T> void App<T>::InitializeService() { Initialize(); } template<typename T> void App<T>::BeginFrame() noexcept { g_theJobSystem->BeginFrame(); g_theUISystem->BeginFrame(); g_theInputSystem->BeginFrame(); g_theConsole->BeginFrame(); g_theAudioSystem->BeginFrame(); g_thePhysicsSystem->BeginFrame(); g_theGame->BeginFrame(); g_theRenderer->BeginFrame(); } template<typename T> void App<T>::Update(TimeUtils::FPSeconds deltaSeconds) noexcept { g_theUISystem->Update(deltaSeconds); g_theInputSystem->Update(deltaSeconds); g_theConsole->Update(deltaSeconds); g_theAudioSystem->Update(deltaSeconds); g_thePhysicsSystem->Update(deltaSeconds); g_theGame->Update(deltaSeconds); g_theRenderer->Update(deltaSeconds); } template<typename T> void App<T>::Render() const noexcept { g_theGame->Render(); g_theUISystem->Render(); g_theConsole->Render(); g_theAudioSystem->Render(); g_theInputSystem->Render(); g_thePhysicsSystem->Render(); g_theRenderer->Render(); } template<typename T> void App<T>::EndFrame() noexcept { g_theUISystem->EndFrame(); g_theGame->EndFrame(); g_theConsole->EndFrame(); g_theAudioSystem->EndFrame(); g_theInputSystem->EndFrame(); g_thePhysicsSystem->EndFrame(); g_theRenderer->EndFrame(); } template<typename T> bool App<T>::ProcessSystemMessage(const EngineMessage& msg) noexcept { switch(msg.wmMessageCode) { case WindowsSystemMessage::Window_Close: { SetIsQuitting(true); return true; } case WindowsSystemMessage::Window_Quit: { SetIsQuitting(true); return true; } case WindowsSystemMessage::Window_Destroy: { ::PostQuitMessage(0); return true; } case WindowsSystemMessage::Window_ActivateApp: { WPARAM wp = msg.wparam; bool losing_focus = wp == FALSE; bool gaining_focus = wp == TRUE; if(losing_focus) { _current_focus = false; _previous_focus = true; } if(gaining_focus) { _current_focus = true; _previous_focus = false; } return true; } case WindowsSystemMessage::Keyboard_Activate: { WPARAM wp = msg.wparam; auto active_type = LOWORD(wp); switch(active_type) { case WA_ACTIVE: /* FALLTHROUGH */ case WA_CLICKACTIVE: _current_focus = true; _previous_focus = false; return true; case WA_INACTIVE: _current_focus = false; _previous_focus = true; return true; default: return false; } } //case WindowsSystemMessage::Window_Size: //{ // LPARAM lp = msg.lparam; // const auto w = HIWORD(lp); // const auto h = LOWORD(lp); // g_theRenderer->ResizeBuffers(); // return true; //} default: return false; } } template<typename T> bool App<T>::IsQuitting() const { return _isQuitting; } template<typename T> void App<T>::SetIsQuitting(bool value) { _isQuitting = value; } template<typename T> void App<T>::RunFrame() { using namespace TimeUtils; RunMessagePump(); BeginFrame(); static FPSeconds previousFrameTime = TimeUtils::GetCurrentTimeElapsed(); FPSeconds currentFrameTime = TimeUtils::GetCurrentTimeElapsed(); FPSeconds deltaSeconds = (currentFrameTime - previousFrameTime); previousFrameTime = currentFrameTime; #ifdef DEBUG_BUILD deltaSeconds = (std::min)(FPSeconds{FPFrames{1}}, deltaSeconds); #endif Update(deltaSeconds); Render(); EndFrame(); AllocationTracker::tick(); } template<typename T> void App<T>::LogSystemDescription() const { const auto section_break_field_width = std::size_t{80u}; const auto system = System::GetSystemDesc(); std::ostringstream ss; ss << std::right << std::setfill('-') << std::setw(section_break_field_width) << '\n'; ss << StringUtils::to_string(system); ss << std::right << std::setfill('-') << std::setw(section_break_field_width) << '\n'; g_theFileLogger->LogAndFlush(ss.str()); } template<typename T> bool App<T>::HasFocus() const { return _current_focus; } template<typename T> bool App<T>::LostFocus() const { return _previous_focus && !_current_focus; } template<typename T> bool App<T>::GainedFocus() const { return !_previous_focus && _current_focus; } template<typename T> void App<T>::RunMessagePump() const { MSG msg{}; for(;;) { const BOOL hasMsg = ::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE); if(!hasMsg) { break; } if(!::TranslateAcceleratorA(reinterpret_cast<HWND>(g_theRenderer->GetOutput()->GetWindow()->GetWindowHandle()), reinterpret_cast<HACCEL>(g_theConsole->GetAcceleratorTable()), &msg)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } } }
30.553191
191
0.692587
cugone
bccbcfe71904fbe1fb6874b5f9cccc537f7c6b8a
189
hpp
C++
CSGOSimple/features/nosmoke.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
null
null
null
CSGOSimple/features/nosmoke.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
1
2022-03-07T21:32:36.000Z
2022-03-07T21:32:36.000Z
CSGOSimple/features/nosmoke.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
null
null
null
#pragma once #include "../Singleton.hpp" #include "../options.hpp" #include "../valve_sdk/csgostructs.hpp" class NoSmoke : public Singleton<NoSmoke> { public: void RemoveSmoke(); };
14.538462
41
0.693122
alerion921
bccc0128518c88978b4044c4442b8713be10a5fc
884
cpp
C++
src/Process/TextureGL.cpp
ThiagoLuizNunes/CG-TerrorProject
ec373bdadb1340703a5c5881d900c7648842864a
[ "MIT" ]
2
2017-12-17T05:02:58.000Z
2019-04-17T20:59:42.000Z
src/Process/TextureGL.cpp
ThiagoLuizNunes/TerrorOnTheHouse
ec373bdadb1340703a5c5881d900c7648842864a
[ "MIT" ]
1
2017-08-04T19:39:23.000Z
2017-08-21T04:12:13.000Z
src/Process/TextureGL.cpp
ThiagoLuizNunes/CG-TerrorProject
ec373bdadb1340703a5c5881d900c7648842864a
[ "MIT" ]
null
null
null
#include "TextureGL.hpp" TextureGL::TextureGL(int w, int h, int ch ,unsigned char* img) { this->width = w; this->height = h; this->channels = ch; this->data = img; } TextureGL::~TextureGL() {} int TextureGL::getWidth(void){ return this->width; } int TextureGL::getHeight(void){ return this->height; } int TextureGL::getChannels(void){ return this->channels; } unsigned char* TextureGL::getData(void){ return this->data; } GLint TextureGL::getTextureID(void) { return this->texture_id; } void TextureGL::setTextureID(GLint id) { this->texture_id = id; } void TextureGL::printAtt(void) { std::clog << "SOIL texture loading with succes!" << std::endl; std::clog << " Image width........ : " << this->width << std::endl; std::clog << " Image height....... : " << this->height << std::endl; std::clog << " Image channels..... : " << this->channels << std::endl; }
25.257143
74
0.647059
ThiagoLuizNunes
bccf11d17f62a85a9166f4894ffa358e13b755b9
10,126
cpp
C++
MadLibs.cpp
quorten/madlibs-hist
1b217cca5001b27aba29f914dea234f1c757287b
[ "Unlicense" ]
null
null
null
MadLibs.cpp
quorten/madlibs-hist
1b217cca5001b27aba29f914dea234f1c757287b
[ "Unlicense" ]
null
null
null
MadLibs.cpp
quorten/madlibs-hist
1b217cca5001b27aba29f914dea234f1c757287b
[ "Unlicense" ]
null
null
null
//A simple Mad Libs game which loads a random story from a file. //Later a configuration pannel may be added. #ifdef MSVC #include <io.h> #else #include <dirent.h> //POSIX compliant code #endif #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> /*#include <sys/stat.h> #include <sys/types.h>*/ using namespace std; struct CacheInfoExtra { char* storyTitle; unsigned storyAddr; unsigned storySize; }; struct CacheInfo { unsigned numStories; CacheInfoExtra* cheExtra; }; struct MadLibsStory { string titleForPrev; //When allowed to pick a story vector<string> storyFragments; vector<string> customWords; vector<unsigned> wordRefs; }; inline bool FindFiles(vector<string>& files); void AskQuestion(string qBegin, string& wordDesc); void FormatCustomWord(string& wordDesc); int main(int argc, char* argv[]) { //First find all the story files in the directory vector<string> files; if (!FindFiles(files)) { cout << "ERROR: Could not find any story files.\n"; return 1; } //Check if the story info cache is up to date /*stat* s = new stat[]; stat("strche.dat", &s); if (s.st_mtime) printf("is directory\n");*/ //Read the cache file CacheInfo* cacheInfo = new CacheInfo[files.size()]; FILE* fp = fopen("strche.dat", "rb"); for (unsigned i = 0; i < files.size(); i++) { fread(&cacheInfo[i].numStories, sizeof(cacheInfo[i].numStories), 1, fp); } //Prepare psudorandom number table srand(time(NULL)); //Compute that: unsigned totNumStories = 0; for (unsigned i = 0; i < files.size(); i++) totNumStories += cacheInfo[i].numStories; //Pick a story unsigned story; if (argc > 1) story = atoi(argv[1]); else story = rand() % totNumStories; //Reformat and store file to parse unsigned prevStories = 0; unsigned fileID; //Which story file? for (unsigned i = 0; i < files.size(); i++) { if (story < cacheInfo[i].numStories + prevStories) { story -= prevStories; fileID = i; break; } prevStories += cacheInfo[i].numStories; } //We're done with cacheInfo free(cacheInfo); //Read the whole file into memory //We have to parse the file to find out how many stories it has since it does not //have a table of contents. fp = fopen(files[fileID].c_str(), "rb"); fseek(fp, 0, SEEK_END); unsigned fileSize = ftell(fp); fseek(fp, 0, SEEK_SET); char* buffer = new char[fileSize]; fread(buffer, fileSize, 1, fp); fclose(fp); //Since we read the whole file this way, we will have to properly format newlines. string fileContents; for (unsigned i = 0; i < fileSize; i++) { if (buffer[i] != '\r') fileContents.push_back(buffer[i]); else { if (buffer[i+1] == '\n') //CR+LF i++; fileContents.push_back('\n'); } } delete []buffer; //Parse the file //We have to format three arrays: story fragments, custom words, and word references //Story fragments and word references are interleaved to create the story vector<MadLibsStory> stories; unsigned curWordRef = 0; bool inTitle = true; //The first line should be a title { //Allocate memory for the first story MadLibsStory temp; temp.storyFragments.push_back(string("")); stories.push_back(temp); } for (unsigned i = 0; i < fileContents.size(); i++) { if (fileContents[i] != '(') { for (; i < fileContents.size() && fileContents[i] != '('; i++) { //Check for end tag const string endTag("\n\nEND STORY"); bool foundEndTag = true; for (unsigned j = i, k = 0; j < i + endTag.size(); j++, k++) { if (j == fileContents.size()) { //The end of file came early foundEndTag = false; break; } if (fileContents[j] != endTag[k]) { foundEndTag = false; break; } } if (foundEndTag == true) { i += 11; if (i == fileContents.size()) goto storyEnd; else if (fileContents[i] != '\n') break; //if (fileContents[i] != '\n') i++; //Skip double newline { //Allocate memory for the next story MadLibsStory temp; temp.storyFragments.push_back(string("")); stories.push_back(temp); } //Reset proper variables curWordRef = 0; inTitle = true; goto storyEnd; } //Do the normal story fragment copy stories.back().storyFragments.back().push_back(fileContents[i]); if (inTitle == true) { if (fileContents[i] != '\n') stories.back().titleForPrev.push_back(fileContents[i]); else { inTitle = false; //if (fileContents[i+1] != '\n') //Then we should tell the user about this //We might temporarily fix it too } } } i--; storyEnd: ; } else { i++; if (fileContents[i] == '(') { //These parentheses are meant for the story content for (; i < fileContents.size() && fileContents[i] == '('; i++) stories.back().storyFragments.back().push_back(fileContents[i]); i--; } else { //We found a custom word stories.back().customWords.push_back(string("")); //Save the custom word temporarily for (; i < fileContents.size() && fileContents[i] != ')'; i++) stories.back().customWords.back().push_back(fileContents[i]); //Search for a match with this custom word and previous custom words bool foundReuse = false; for (unsigned i = 0; i < stories.back().customWords.size() - 1; i++) { if (stories.back().customWords.back() == stories.back().customWords[i]) { //We have a match. Fill in the proper word reference stories.back().wordRefs.push_back(i); //Delete reused word stories.back().customWords.pop_back(); foundReuse = true; break; } } if (foundReuse == false) { //No match found. Store reference and keep stored word stories.back().wordRefs.push_back(curWordRef); curWordRef++; } stories.back().storyFragments.push_back(string("")); } if (inTitle == true) { stories.back().titleForPrev.push_back('?'); } } } if (inTitle == true) { //We have a newline at the end of the file, but of course no story stories.pop_back(); } //Ask the words FormatCustomWord(stories[story].customWords.front()); bool sayAnotherNext = false; for (unsigned i = 0; i < stories[story].customWords.size(); i++) { if (sayAnotherNext == true) //This flag is set at the end of the loop { sayAnotherNext = false; //If the next type of word is the same type, then set the //flag so next time we say "Type another ..." if (i < stories[story].customWords.size() - 1) FormatCustomWord(stories[story].customWords[i+1]); if (i < stories[story].customWords.size() - 1 && stories[story].customWords[i] == stories[story].customWords[i+1]) sayAnotherNext = true; //Now we can change the word when we ask the question AskQuestion(string("Type another "), stories[story].customWords[i]); } else { //If the next type of word is the same type, then set the //flag so next time we say "Type another ..." if (i < stories[story].customWords.size() - 1) FormatCustomWord(stories[story].customWords[i+1]); if (i < stories[story].customWords.size() - 1 && stories[story].customWords[i] == stories[story].customWords[i+1]) sayAnotherNext = true; //If the first letter of the word is a vowel (a, e, i, o, u, not //including y), then say "Type an ..." const string accptdVowls("aeiou"); bool useAn = false; for (unsigned j = 0; j < 5; j++) { if (stories[story].customWords[i][0] == accptdVowls[j]) { useAn = true; break; } } if (useAn == true) AskQuestion(string("Type an "), stories[story].customWords[i]); //Otherwise, just say "Type a ..." else AskQuestion(string("Type a "), stories[story].customWords[i]); //cout << "Type a " << stories[story].customWords[i] << ":\n"; } } //Display the story cout << endl; for (unsigned i = 0; i < stories[story].storyFragments.size() - 1; i++) cout << stories[story].storyFragments[i] << stories[story].customWords[stories[story].wordRefs[i]]; cout << stories[story].storyFragments.back() << endl; return 0; } inline bool FindFiles(vector<string>& files) { #ifdef MSVC _finddata_t findData; intptr_t findHandle; findHandle = _findfirst("*.mlb", &findData); if (findHandle == -1) return false; files.push_back(string(findData.name)); while (_findnext(findHandle, &findData) == 0) { files.push_back(string(findData.name)); } _findclose(findHandle); sort(files.begin(), files.end()); return true; #else DIR *d = opendir("."); if (d == NULL) return false; struct dirent *de; while (de = readdir(d)) { files.push_back(string(de->d_name)); if (files.back().find(".mlb") != files.back().size() - 4) files.pop_back(); } closedir(d); if (files.size() > 0) { sort(files.begin(), files.end()); return true; } else return false; #endif } void AskQuestion(string qBegin, string& wordDesc) { string answer; cout << qBegin << wordDesc << ": "; getline(cin, answer, '\n'); wordDesc = answer; } //Erases the numeric ID from the custom word description void FormatCustomWord(string& wordDesc) { //NOTE: Here we consider it pointless to have only a //number for the word description. unsigned numBegin; bool inNumber = true; for (numBegin = wordDesc.size() - 1; numBegin > 0 && inNumber == true; numBegin--) { const string numbers("0123456789"); inNumber = false; for (unsigned j = 0; j < 10; j++) { if (numbers[j] == wordDesc[numBegin]) inNumber = true; } } numBegin += 2; //Undo the extra numBegin-- and... //Don't erase the last letter of the description wordDesc.erase(numBegin); }
26.301299
118
0.613767
quorten
bcd5e56e3950bb5a15fd853fdc9f0eef5676b254
1,414
hpp
C++
src/mge/behaviours/AbstractBehaviour.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
src/mge/behaviours/AbstractBehaviour.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
src/mge/behaviours/AbstractBehaviour.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
#ifndef ABSTRACTBEHAVIOUR_H #define ABSTRACTBEHAVIOUR_H #include "Physics/RigidBody.h" class GameObject; /** * An AbstractBehaviour allows you to attach reusable behaviours to GameObjects (Steering, rotating, billboarding, etc). * A Behaviour is set on a GameObject, which in turn passes in a reference to itself through the setOwner method. * This way we can enforce that a Behaviour can never have an owner different from the object it has been attached to. * * The concept is similar to MonoBehaviours in Unity. */ class AbstractBehaviour { public: AbstractBehaviour(); virtual ~AbstractBehaviour() = 0; //we would like to have this private and only accessible by GameObject, but this //doesnt work out for the CompositeBehaviour, we would have to declare both of them //as friends, tying this class to one of its subclasses, so design decision: //this is kept public but should not be used directly. virtual void setOwner (GameObject* pGameObject); //behaviour should be able to update itself every step and MUST be implemented virtual void update(float pStep) = 0; protected: //reference back its owner GameObject* _owner; private: //disallow copy and assignment AbstractBehaviour(const AbstractBehaviour&); AbstractBehaviour& operator=(const AbstractBehaviour&); }; #endif // ABSTRACTBEHAVIOUR_H
31.422222
120
0.730552
mtesseracttech
bcd8f37017ce4bf5caf3939556e80374a792fc27
13,273
cpp
C++
library/ltbl/LightDirectionEmission.cpp
NeroGames/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
26
2020-09-02T18:14:36.000Z
2022-02-08T18:28:36.000Z
library/ltbl/LightDirectionEmission.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
14
2020-08-30T01:37:04.000Z
2021-07-19T20:47:29.000Z
library/ltbl/LightDirectionEmission.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
6
2020-09-02T18:14:57.000Z
2021-12-31T00:32:09.000Z
#include <ltbl/LightDirectionEmission.hpp> namespace ltbl { LightDirectionEmission::LightDirectionEmission() : BaseLight() , mShape() , mCastDirection(0.f, 1.f) , mCastAngle(90.f) , mSourceRadius(5.0f) , mSourceDistance(100.0f) { } void LightDirectionEmission::setColor(const sf::Color& color) { mShape.setFillColor(color); } const sf::Color& LightDirectionEmission::getColor() const { return mShape.getFillColor(); } void LightDirectionEmission::render(const sf::View& view, sf::RenderTexture& lightTempTexture, sf::RenderTexture& antumbraTempTexture, sf::Shader& unshadowShader, const std::vector<priv::QuadtreeOccupant*>& shapes, float shadowExtension) { lightTempTexture.setView(view); lightTempTexture.clear(sf::Color::White); // Mask off light shape (over-masking - mask too much, reveal penumbra/antumbra afterwards) unsigned int shapesCount = shapes.size(); for (unsigned int i = 0; i < shapesCount; ++i) { LightShape* pLightShape = static_cast<LightShape*>(shapes[i]); if (pLightShape != nullptr && pLightShape->isTurnedOn()) { // Get boundaries std::vector<priv::Penumbra> penumbras; std::vector<int> innerBoundaryIndices; std::vector<int> outerBoundaryIndices; std::vector<sf::Vector2f> innerBoundaryVectors; std::vector<sf::Vector2f> outerBoundaryVectors; getPenumbrasDirection(penumbras, innerBoundaryIndices, innerBoundaryVectors, outerBoundaryIndices, outerBoundaryVectors, *pLightShape); if (innerBoundaryIndices.size() != 2 || outerBoundaryIndices.size() != 2) { continue; } antumbraTempTexture.clear(sf::Color::White); antumbraTempTexture.setView(view); float maxDist = 0.0f; for (unsigned j = 0; j < pLightShape->getPointCount(); j++) { maxDist = std::max(maxDist, priv::vectorMagnitude(view.getCenter() - pLightShape->getTransform().transformPoint(pLightShape->getPoint(j)))); } float totalShadowExtension = shadowExtension + maxDist; sf::ConvexShape maskShape; maskShape.setPointCount(4); maskShape.setPoint(0, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[0]))); maskShape.setPoint(1, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[1]))); maskShape.setPoint(2, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[1])) + priv::vectorNormalize(innerBoundaryVectors[1]) * totalShadowExtension); maskShape.setPoint(3, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[0])) + priv::vectorNormalize(innerBoundaryVectors[0]) * totalShadowExtension); maskShape.setFillColor(sf::Color::Black); antumbraTempTexture.draw(maskShape); unmaskWithPenumbras(antumbraTempTexture, sf::BlendAdd, unshadowShader, penumbras, totalShadowExtension); antumbraTempTexture.display(); lightTempTexture.setView(lightTempTexture.getDefaultView()); lightTempTexture.draw(sf::Sprite(antumbraTempTexture.getTexture()), sf::BlendMultiply); lightTempTexture.setView(view); } } for (unsigned int i = 0; i < shapesCount; i++) { LightShape* pLightShape = static_cast<LightShape*>(shapes[i]); if (pLightShape->renderLightOver() && pLightShape->isTurnedOn()) { pLightShape->setColor(sf::Color::White); lightTempTexture.draw(*pLightShape); } } lightTempTexture.setView(lightTempTexture.getDefaultView()); mShape.setSize(lightTempTexture.getView().getSize()); lightTempTexture.draw(mShape, sf::BlendMultiply); lightTempTexture.display(); } void LightDirectionEmission::setCastDirection(const sf::Vector2f& castDirection) { mCastDirection = priv::vectorNormalize(castDirection); mCastAngle = priv::_radToDeg * std::atan2(mCastDirection.y, mCastDirection.x); } const sf::Vector2f& LightDirectionEmission::getCastDirection() const { return mCastDirection; } void LightDirectionEmission::setCastAngle(float angle) { mCastAngle = angle; float radAngle = angle * priv::_degToRad; mCastDirection.x = std::cos(radAngle); mCastDirection.y = std::sin(radAngle); } float LightDirectionEmission::getCastAngle() const { return mCastAngle; } void LightDirectionEmission::setSourceRadius(float radius) { mSourceRadius = radius; } float LightDirectionEmission::getSourceRadius() const { return mSourceRadius; } void LightDirectionEmission::setSourceDistance(float distance) { mSourceDistance = distance; } float LightDirectionEmission::getSourceDistance() const { return mSourceDistance; } void LightDirectionEmission::getPenumbrasDirection(std::vector<priv::Penumbra>& penumbras, std::vector<int>& innerBoundaryIndices, std::vector<sf::Vector2f>& innerBoundaryVectors, std::vector<int>& outerBoundaryIndices, std::vector<sf::Vector2f>& outerBoundaryVectors, const LightShape& shape) { const int numPoints = shape.getPointCount(); innerBoundaryIndices.reserve(2); innerBoundaryVectors.reserve(2); penumbras.reserve(2); std::vector<bool> bothEdgesBoundaryWindings; bothEdgesBoundaryWindings.reserve(2); // Calculate front and back facing sides std::vector<bool> facingFrontBothEdges; facingFrontBothEdges.reserve(numPoints); std::vector<bool> facingFrontOneEdge; facingFrontOneEdge.reserve(numPoints); for (int i = 0; i < numPoints; i++) { sf::Vector2f point = shape.getTransform().transformPoint(shape.getPoint(i)); sf::Vector2f nextPoint = shape.getTransform().transformPoint(shape.getPoint((i < numPoints - 1) ? i + 1 : 0)); sf::Vector2f perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; sf::Vector2f firstEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); sf::Vector2f secondEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); sf::Vector2f firstNextEdgeRay = nextPoint - (point - mCastDirection * mSourceDistance - perpendicularOffset); sf::Vector2f secondNextEdgeRay = nextPoint - (point - mCastDirection * mSourceDistance + perpendicularOffset); sf::Vector2f pointToNextPoint = nextPoint - point; sf::Vector2f normal = priv::vectorNormalize(sf::Vector2f(-pointToNextPoint.y, pointToNextPoint.x)); // Front facing, mark it facingFrontBothEdges.push_back((priv::vectorDot(firstEdgeRay, normal) > 0.0f && priv::vectorDot(secondEdgeRay, normal) > 0.0f) || (priv::vectorDot(firstNextEdgeRay, normal) > 0.0f && priv::vectorDot(secondNextEdgeRay, normal) > 0.0f)); facingFrontOneEdge.push_back((priv::vectorDot(firstEdgeRay, normal) > 0.0f || priv::vectorDot(secondEdgeRay, normal) > 0.0f) || priv::vectorDot(firstNextEdgeRay, normal) > 0.0f || priv::vectorDot(secondNextEdgeRay, normal) > 0.0f); } // Go through front/back facing list. Where the facing direction switches, there is a boundary for (int i = 1; i < numPoints; i++) { if (facingFrontBothEdges[i] != facingFrontBothEdges[i - 1]) { innerBoundaryIndices.push_back(i); bothEdgesBoundaryWindings.push_back(facingFrontBothEdges[i]); } } // Check looping indices separately if (facingFrontBothEdges[0] != facingFrontBothEdges[numPoints - 1]) { innerBoundaryIndices.push_back(0); bothEdgesBoundaryWindings.push_back(facingFrontBothEdges[0]); } // Go through front/back facing list. Where the facing direction switches, there is a boundary for (int i = 1; i < numPoints; i++) { if (facingFrontOneEdge[i] != facingFrontOneEdge[i - 1]) { outerBoundaryIndices.push_back(i); } } // Check looping indices separately if (facingFrontOneEdge[0] != facingFrontOneEdge[numPoints - 1]) { outerBoundaryIndices.push_back(0); } for (unsigned bi = 0; bi < innerBoundaryIndices.size(); bi++) { int penumbraIndex = innerBoundaryIndices[bi]; bool winding = bothEdgesBoundaryWindings[bi]; sf::Vector2f point = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex)); sf::Vector2f perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; sf::Vector2f firstEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); sf::Vector2f secondEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); // Add boundary vector innerBoundaryVectors.push_back(winding ? secondEdgeRay : firstEdgeRay); sf::Vector2f outerBoundaryVector = winding ? firstEdgeRay : secondEdgeRay; outerBoundaryVectors.push_back(outerBoundaryVector); // Add penumbras bool hasPrevPenumbra = false; sf::Vector2f prevPenumbraLightEdgeVector; float prevBrightness = 1.0f; while (penumbraIndex != -1) { sf::Vector2f nextPoint; int nextPointIndex; if (penumbraIndex < numPoints - 1) { nextPointIndex = penumbraIndex + 1; nextPoint = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex + 1)); } else { nextPointIndex = 0; nextPoint = shape.getTransform().transformPoint(shape.getPoint(0)); } sf::Vector2f pointToNextPoint = nextPoint - point; sf::Vector2f prevPoint; int prevPointIndex; if (penumbraIndex > 0) { prevPointIndex = penumbraIndex - 1; prevPoint = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex - 1)); } else { prevPointIndex = numPoints - 1; prevPoint = shape.getTransform().transformPoint(shape.getPoint(numPoints - 1)); } sf::Vector2f pointToPrevPoint = prevPoint - point; priv::Penumbra penumbra; penumbra._source = point; if (!winding) { penumbra._lightEdge = (hasPrevPenumbra) ? prevPenumbraLightEdgeVector : innerBoundaryVectors.back(); penumbra._darkEdge = outerBoundaryVector; penumbra._lightBrightness = prevBrightness; // Next point, check for intersection float intersectionAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(pointToNextPoint))); float penumbraAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(penumbra._darkEdge))); if (intersectionAngle < penumbraAngle) { prevBrightness = penumbra._darkBrightness = intersectionAngle / penumbraAngle; assert(prevBrightness >= 0.0f && prevBrightness <= 1.0f); penumbra._darkEdge = pointToNextPoint; penumbraIndex = nextPointIndex; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = true; prevPenumbraLightEdgeVector = penumbra._darkEdge; point = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex)); perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; firstEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); secondEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); outerBoundaryVector = secondEdgeRay; } else { penumbra._darkBrightness = 0.0f; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = false; penumbraIndex = -1; } } else // Winding = true { penumbra._lightEdge = (hasPrevPenumbra) ? prevPenumbraLightEdgeVector : innerBoundaryVectors.back(); penumbra._darkEdge = outerBoundaryVector; penumbra._lightBrightness = prevBrightness; // Next point, check for intersection float intersectionAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(pointToPrevPoint))); float penumbraAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(penumbra._darkEdge))); if (intersectionAngle < penumbraAngle) { prevBrightness = penumbra._darkBrightness = intersectionAngle / penumbraAngle; assert(prevBrightness >= 0.0f && prevBrightness <= 1.0f); penumbra._darkEdge = pointToPrevPoint; penumbraIndex = prevPointIndex; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = true; prevPenumbraLightEdgeVector = penumbra._darkEdge; point = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex)); perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; firstEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); secondEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); outerBoundaryVector = firstEdgeRay; } else { penumbra._darkBrightness = 0.0f; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = false; penumbraIndex = -1; } } penumbras.push_back(penumbra); } } } } // namespace ltbl
36.265027
293
0.736533
NeroGames
bcd971f123367cb08b61f06a14ece77ff5adea14
7,716
cpp
C++
src/Game.cpp
johnhues/ae-asteroids
6d47c1e794b060718b21230ab59b04e62633f8fb
[ "MIT" ]
null
null
null
src/Game.cpp
johnhues/ae-asteroids
6d47c1e794b060718b21230ab59b04e62633f8fb
[ "MIT" ]
null
null
null
src/Game.cpp
johnhues/ae-asteroids
6d47c1e794b060718b21230ab59b04e62633f8fb
[ "MIT" ]
null
null
null
#include "Game.h" #include "Components.h" ae::DebugLines*& GetDebugLines() { static ae::DebugLines* g_debugLines = nullptr; return g_debugLines; } void Game::Initialize() { window.Initialize( 800, 600, false, true ); window.SetTitle( "AE-Asteroids" ); render.Initialize( &window ); debugLines.Initialize( 256 ); input.Initialize( &window ); #if _AE_WINDOWS_ const char* dataDir = "../data"; #elif _AE_APPLE_ const char* dataDir = "data"; #else const char* dataDir = ""; #endif file.Initialize( dataDir, "johnhues", "AE-Asteroids" ); timeStep.SetTimeStep( 1.0f / 60.0f ); GetDebugLines() = &debugLines; shader.Initialize( kVertShader, kFragShader, nullptr, 0 ); shader.SetDepthTest( true ); shader.SetDepthWrite( true ); level0.Initialize( &file, "level0.fbx" ); cubeModel.Initialize( &file, "cube.fbx" ); shipModel.Initialize( &file, "ship.fbx" ); asteroidModel.Initialize( kAsteroidVerts, kAsteroidIndices, countof(kAsteroidVerts), countof(kAsteroidIndices) ); } void Game::Terminate() { AE_INFO( "Terminate" ); //input.Terminate(); debugLines.Terminate(); render.Terminate(); window.Terminate(); } void Game::Load() { // Level { entt::entity entity = registry.create(); Level& level = registry.emplace< Level >( entity ); level.Clear(); level.AddMesh( &level0, ae::Matrix4::Identity() ); level.AddMesh( &cubeModel, ae::Matrix4::Translation( ae::Vec3( 3.0f, 3.0f, 0.0f ) ) * ae::Matrix4::Scaling( ae::Vec3( 3.0f ) ) ); } // Ship { entt::entity entity = registry.create(); registry.emplace< Transform >( entity ); registry.emplace< Collision >( entity ); Physics& physics = registry.emplace< Physics >( entity ); physics.moveDrag = 0.7f; physics.rotationDrag = 1.7f; physics.collisionRadius = 0.7f; Ship& ship = registry.emplace< Ship >( entity ); ship.local = true; ship.speed = 10.0f; ship.rotationSpeed = 5.0f; Team& team = registry.emplace< Team >( entity ); team.teamId = TeamId::Player; registry.emplace< Shooter >( entity ); Model& model = registry.emplace< Model >( entity ); model.mesh = &shipModel; model.shader = &shader; model.color = ae::Color::PicoBlue(); localShip = entity; } // Camera { entt::entity entity = registry.create(); Transform& transform = registry.emplace< Transform >( entity ); transform.SetPosition( ae::Vec3( 0, 0, 20.0f ) ); registry.emplace< Camera >( entity ); } // // Asteroids // for ( uint32_t i = 0; i < 8; i++ ) // { // entt::entity entity = registry.create(); // // Transform& transform = registry.emplace< Transform >( entity ); // transform.SetPosition( ae::Vec3( ae::Random( -1.0f, 1.0f ), ae::Random( -1.0f, 1.0f ), 0.0f ) ); // // registry.emplace< Collision >( entity ); // // float angle = ae::Random( 0.0f, ae::TWO_PI ); // float speed = ae::Random( 0.1f, 0.7f ); // Physics& physics = registry.emplace< Physics >( entity ); // physics.vel = ae::Vec3( cosf( angle ), sinf( angle ), 0.0f ) * speed; // // registry.emplace< Asteroid >( entity ); // // Model& model = registry.emplace< Model >( entity ); // model.mesh = &asteroidModel; // model.shader = &shader; // } // Turret { entt::entity entity = registry.create(); Transform& transform = registry.emplace< Transform >( entity ); transform.SetPosition( ae::Vec3( -4.0f, 4.0f, 0.0f ) ); registry.emplace< Collision >( entity ); Physics& physics = registry.emplace< Physics >( entity ); physics.rotationDrag = 1.7f; registry.emplace< Turret >( entity ); Team& team = registry.emplace< Team >( entity ); team.teamId = TeamId::Enemy; Shooter& shooter = registry.emplace< Shooter >( entity ); shooter.fireInterval = 0.4f; Model& model = registry.emplace< Model >( entity ); model.mesh = &shipModel; model.shader = &shader; model.color = ae::Color::PicoDarkPurple(); } } void Game::Run() { AE_INFO( "Run" ); while ( !input.quit ) //while ( !input.GetState()->exit ) { input.Pump(); // Update for( auto [ entity, ship, transform, physics ] : registry.view< Ship, Transform, Physics >().each() ) { ship.Update( this, entity, transform, physics ); } for( auto [ entity, turret ] : registry.view< Turret >().each() ) { turret.Update( this, entity ); } for( auto [ entity, asteroid, transform, physics ] : registry.view< Asteroid, Transform, Physics >().each() ) { asteroid.Update( this, transform, physics ); } for( auto [ entity, shooter ] : registry.view< Shooter >().each() ) { shooter.Update( this, entity ); } for( auto [ entity, projectile ] : registry.view< Projectile >().each() ) { projectile.Update( this, entity ); } for( auto [ entity, physics, transform ]: registry.view< Physics, Transform >().each() ) { physics.Update( this, transform ); } for( auto [ entity, level ]: registry.view< Level >().each() ) { for( auto [ entity, physics, transform ]: registry.view< Physics, Transform >().each() ) { if ( physics.collisionRadius ) { physics.hit = level.Test( &transform, &physics ); } } } for( auto [ entity, camera, transform ] : registry.view< Camera, Transform >().each() ) { camera.Update( this, transform ); } uint32_t pendingKillCount = m_pendingKill.Length(); for ( uint32_t i = 0; i < pendingKillCount; i++ ) { registry.destroy( m_pendingKill.GetKey( i ) ); } m_pendingKill.Clear(); // Render render.Activate(); render.Clear( ae::Color::PicoBlack() ); auto drawView = registry.view< const Transform, const Model >(); for( auto [ entity, transform, model ]: drawView.each() ) { model.Draw( this, transform ); } if ( Level* level = registry.try_get< Level >( this->level ) ) { level->Render( this ); } //debugLines.Render( worldToNdc ); debugLines.Clear(); render.Present(); timeStep.Wait(); } } bool Game::IsOnScreen( ae::Vec3 pos ) const { float halfWidth = render.GetAspectRatio(); float halfHeight = 1.0f; if ( -halfWidth < pos.x && pos.x < halfWidth && -halfHeight < pos.y && pos.y < halfHeight ) { return true; } else { return false; } } void Game::Kill( entt::entity entity ) { m_pendingKill.Set( entity, 0 ); } entt::entity Game::SpawnProjectile( entt::entity source, ae::Vec3 offset ) { const Transform& sourceTransform = registry.get< Transform >( source ); const Team& sourceTeam = registry.get< Team >( source ); const Physics* sourcePhysics = registry.try_get< Physics >( source ); entt::entity entity = registry.create(); Transform& transform = registry.emplace< Transform >( entity ); offset = ( sourceTransform.transform * ae::Vec4( offset, 0.0f ) ).GetXYZ(); transform.SetPosition( sourceTransform.GetPosition() + offset ); transform.transform.SetRotation( sourceTransform.transform.GetRotation() ); transform.transform.SetScale( ae::Vec3( 0.25f ) ); Physics& physics = registry.emplace< Physics >( entity ); if ( sourcePhysics ) { physics.vel += sourcePhysics->vel; } physics.vel += sourceTransform.GetForward() * 15.0f; physics.collisionRadius = 0.1f; Projectile& projectile = registry.emplace< Projectile >( entity ); projectile.killTime = ae::GetTime() + 2.0f; Team& team = registry.emplace< Team >( entity ); team.teamId = sourceTeam.teamId; Model& model = registry.emplace< Model >( entity ); model.mesh = &shipModel; model.shader = &shader; switch ( sourceTeam.teamId ) { case TeamId::None: model.color = ae::Color::Gray(); break; case TeamId::Player: model.color = ae::Color::PicoYellow(); break; case TeamId::Enemy: model.color = ae::Color::PicoRed(); break; default: AE_FAIL_MSG( "Invalid team" ); break; } return entity; }
26.424658
131
0.649171
johnhues
bcda1b04a810ad7ad4182e38ffe1f791e1979b1e
238
cpp
C++
AlgorithmCpp/Leetcode题解/L017.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
AlgorithmCpp/Leetcode题解/L017.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
AlgorithmCpp/Leetcode题解/L017.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
// 根据九宫格布局输出电话号码的可能组合 // 回溯法递归求解,接收两个参数:1.当前数字已经组成的对应字符串,2.剩余的数字字符串;返回条件:剩余的字符串为空,即所有的数字都匹配完;定义一个全局list存放可能的结果,当一个分支完整地遍历之后记录结果 #include<iostream> #include<vector> #include<map> using namespace std; int main() { return 0; }
14
105
0.752101
PusenYang
bce1fe7197d317fbf312a52f653dfad6f5e5b112
737
cpp
C++
codility/07_Brackets.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
codility/07_Brackets.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
codility/07_Brackets.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(string &S) { // write your code in C++11 (g++ 4.8.2) int N = S.size(); if (N == 0) return 1; if (N % 2 == 1) return 0; string stack; for (char c : S) { if (c == '(' || c == '[' || c == '{') { stack.push_back(c); } else { if (stack.empty()) return 0; if ((c == ')' && stack.back() != '(') || (c == ']' && stack.back() != '[') || (c == '}' && stack.back() != '{')) return 0; stack.pop_back(); } } return stack.empty() ? 1 : 0; }
27.296296
60
0.428765
longztian
bce3d1f9ce7a835ef9367f925e156817c9809789
4,644
hpp
C++
include/boost/hana/ext/std/ratio.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
2
2015-12-06T05:10:14.000Z
2021-09-05T21:48:27.000Z
include/boost/hana/ext/std/ratio.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
null
null
null
include/boost/hana/ext/std/ratio.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
1
2017-06-06T10:50:17.000Z
2017-06-06T10:50:17.000Z
/*! @file Adapts `std::ratio` for use with Hana. @copyright Louis Dionne 2015 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_HANA_EXT_STD_RATIO_HPP #define BOOST_HANA_EXT_STD_RATIO_HPP #include <boost/hana/bool.hpp> #include <boost/hana/concept/integral_constant.hpp> #include <boost/hana/core/when.hpp> #include <boost/hana/fwd/core/convert.hpp> #include <boost/hana/fwd/core/tag_of.hpp> #include <boost/hana/fwd/div.hpp> #include <boost/hana/fwd/equal.hpp> #include <boost/hana/fwd/less.hpp> #include <boost/hana/fwd/minus.hpp> #include <boost/hana/fwd/mod.hpp> #include <boost/hana/fwd/mult.hpp> #include <boost/hana/fwd/one.hpp> #include <boost/hana/fwd/plus.hpp> #include <boost/hana/fwd/zero.hpp> #include <cstdint> #include <ratio> #include <type_traits> namespace boost { namespace hana { namespace ext { namespace std { struct ratio_tag; }} template <std::intmax_t num, std::intmax_t den> struct tag_of<std::ratio<num, den>> { using type = ext::std::ratio_tag; }; ////////////////////////////////////////////////////////////////////////// // Conversion from IntegralConstants ////////////////////////////////////////////////////////////////////////// template <typename C> struct to_impl<ext::std::ratio_tag, C, when< hana::IntegralConstant<C>::value >> { template <typename N> static constexpr auto apply(N const&) { return std::ratio<N::value>{}; } }; ////////////////////////////////////////////////////////////////////////// // Comparable ////////////////////////////////////////////////////////////////////////// template <> struct equal_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr auto apply(R1 const&, R2 const&) { return hana::bool_c<std::ratio_equal<R1, R2>::value>; } }; ////////////////////////////////////////////////////////////////////////// // Orderable ////////////////////////////////////////////////////////////////////////// template <> struct less_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr auto apply(R1 const&, R2 const&) { return hana::bool_c<std::ratio_less<R1, R2>::value>; } }; ////////////////////////////////////////////////////////////////////////// // Monoid ////////////////////////////////////////////////////////////////////////// template <> struct plus_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_add<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; template <> struct zero_impl<ext::std::ratio_tag> { static constexpr std::ratio<0> apply() { return {}; } }; ////////////////////////////////////////////////////////////////////////// // Group ////////////////////////////////////////////////////////////////////////// template <> struct minus_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_subtract<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; ////////////////////////////////////////////////////////////////////////// // Ring ////////////////////////////////////////////////////////////////////////// template <> struct mult_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_multiply<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; template <> struct one_impl<ext::std::ratio_tag> { static constexpr std::ratio<1> apply() { return {}; } }; ////////////////////////////////////////////////////////////////////////// // EuclideanRing ////////////////////////////////////////////////////////////////////////// template <> struct div_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_divide<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; template <> struct mod_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio<0> apply(R1 const&, R2 const&) { return {}; } }; }} // end namespace boost::hana #endif // !BOOST_HANA_EXT_STD_RATIO_HPP
34.4
80
0.48385
qicosmos
bce3ea10273c30077254035d26981fee66346d94
1,273
cpp
C++
Programs/21 Stack/linkedListImplementation.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
5
2021-04-04T18:39:14.000Z
2021-12-18T09:31:55.000Z
Programs/21 Stack/linkedListImplementation.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
null
null
null
Programs/21 Stack/linkedListImplementation.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
1
2021-09-26T11:01:26.000Z
2021-09-26T11:01:26.000Z
//implementation using single ll //top <-node4 <-node3 <-node2 <-node1 #include <iostream> using namespace std; class node{ public: int data; node* next; // node* prev; node(int val){ data = val; next = NULL; // prev = NULL; } }; class stack{ node* top; public: stack(){ top = NULL; }//constructor void push(int x){ node* n = new node(x); // top->next = n; n->next = top; //singly ll implementation top = n; // top->prev = top; } void pop(){ if(top==NULL){ cout<<"Stack Underflow"<<endl; return; } node* todelete = top; // top = top->next; delete todelete; } int Top(){ if(top == NULL){ cout<<"Empty Stack"<<endl; return -1; } return top->data; } bool empty(){ return top==NULL; } }; int main(){ stack st; st.push(1); st.push(2); st.push(3); st.push(4); cout<<st.Top()<<endl; st.pop(); cout<<st.Top()<<endl; st.pop(); cout<<st.Top()<<endl; st.pop(); cout<<st.Top()<<endl; st.pop(); st.pop(); cout<<st.empty()<<endl; return 0; }
15.337349
49
0.451689
Lord-Lava
bce4c58ee69b751be22d58a1a61db3dcde96d3c3
1,183
hpp
C++
libs/modelmd3/impl/include/sge/model/md3/impl/frame.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/modelmd3/impl/include/sge/model/md3/impl/frame.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/modelmd3/impl/include/sge/model/md3/impl/frame.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_MODEL_MD3_IMPL_FRAME_HPP_INCLUDED #define SGE_MODEL_MD3_IMPL_FRAME_HPP_INCLUDED #include <sge/model/md3/scalar.hpp> #include <sge/model/md3/string.hpp> #include <sge/model/md3/impl/vec3.hpp> #include <fcppt/config/external_begin.hpp> #include <iosfwd> #include <fcppt/config/external_end.hpp> namespace sge::model::md3::impl { class frame { public: explicit frame(std::istream &); [[nodiscard]] sge::model::md3::impl::vec3 const &min_bounds() const; [[nodiscard]] sge::model::md3::impl::vec3 const &max_bounds() const; [[nodiscard]] sge::model::md3::impl::vec3 const &local_origin() const; [[nodiscard]] sge::model::md3::scalar radius() const; [[nodiscard]] sge::model::md3::string const &name() const; private: sge::model::md3::impl::vec3 min_bounds_; sge::model::md3::impl::vec3 max_bounds_; sge::model::md3::impl::vec3 local_origin_; sge::model::md3::scalar radius_; sge::model::md3::string name_; }; } #endif
24.142857
72
0.705833
cpreh
bcf0e815b7d797a4eb99a6de118174a97048d0f3
4,315
cpp
C++
source/rendering/pipes/MirrorPipe.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
2
2021-01-27T15:49:04.000Z
2021-01-28T07:40:30.000Z
source/rendering/pipes/MirrorPipe.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
null
null
null
source/rendering/pipes/MirrorPipe.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
1
2021-03-07T23:17:31.000Z
2021-03-07T23:17:31.000Z
#include "MirrorPipe.h" #include "rendering/assets/GpuAssetManager.h" #include "rendering/assets/GpuShader.h" #include "rendering/assets/GpuShaderStage.h" #include "rendering/pipes/StaticPipes.h" #include "rendering/scene/Scene.h" #include "rendering/scene/SceneCamera.h" namespace { struct PushConstant { int32 depth; int32 pointlightCount; int32 spotlightCount; int32 dirlightCount; int32 irragridCount; int32 quadlightCount; int32 reflprobeCount; }; static_assert(sizeof(PushConstant) <= 128); } // namespace namespace vl { vk::UniquePipelineLayout MirrorPipe::MakePipelineLayout() { return rvk::makePipelineLayout<PushConstant>( { DescriptorLayouts->global.handle(), // gbuffer and stuff DescriptorLayouts->_1storageImage.handle(), // images DescriptorLayouts->accelerationStructure.handle(), // as DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // geometry and texture DescriptorLayouts->_1storageBuffer.handle(), // pointlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // spotlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // dirlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // irragrids DescriptorLayouts->_1storageBuffer.handle(), // quadlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // reflprobes }, vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eClosestHitKHR); } vk::UniquePipeline MirrorPipe::MakePipeline() { auto getShader = [](const auto& path) -> auto& { GpuAsset<Shader>& gpuShader = GpuAssetManager->CompileShader(path); gpuShader.onCompile = [&]() { StaticPipes::Recompile<MirrorPipe>(); }; return gpuShader; }; // all rt shaders here auto& ptshader = getShader("engine-data/spv/raytrace/mirror/mirror.shader"); auto& ptQuadlightShader = getShader("engine-data/spv/raytrace/mirror/mirror-quadlight.shader"); auto get = [](auto shader) { return *shader.Lock().module; }; AddRaygenGroup(get(ptshader.rayGen)); AddMissGroup(get(ptshader.miss)); // miss general 0 AddHitGroup(get(ptshader.closestHit), get(ptshader.anyHit)); // gltf mat 0, ahit for mask AddHitGroup(get(ptQuadlightShader.closestHit)); // quad lights 1 vk::RayTracingPipelineCreateInfoKHR rayPipelineInfo{}; rayPipelineInfo .setLayout(layout()) // .setMaxPipelineRayRecursionDepth(1); // Assemble the shader stages and construct the SBT return MakeRaytracingPipeline(rayPipelineInfo); } void MirrorPipe::RecordCmd(vk::CommandBuffer cmdBuffer, const SceneRenderDesc& sceneDesc, const vk::Extent3D& extent, vk::DescriptorSet mirrorImageStorageDescSet, int32 bounces) const { COMMAND_SCOPE_AUTO(cmdBuffer); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eRayTracingKHR, pipeline()); cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eRayTracingKHR, layout(), 0u, { sceneDesc.globalDesc, mirrorImageStorageDescSet, sceneDesc.scene->sceneAsDescSet, sceneDesc.scene->tlas.sceneDesc.descSetGeometryAndTextures[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetPointlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetSpotlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetDirlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetIrragrids[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetQuadlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetReflprobes[sceneDesc.frameIndex], }, nullptr); PushConstant pc{ .depth = bounces, .pointlightCount = sceneDesc.scene->tlas.sceneDesc.pointlightCount, .spotlightCount = sceneDesc.scene->tlas.sceneDesc.spotlightCount, .dirlightCount = sceneDesc.scene->tlas.sceneDesc.dirlightCount, .irragridCount = sceneDesc.scene->tlas.sceneDesc.irragridCount, .quadlightCount = sceneDesc.scene->tlas.sceneDesc.quadlightCount, .reflprobeCount = sceneDesc.scene->tlas.sceneDesc.reflprobeCount, }; cmdBuffer.pushConstants(layout(), vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eClosestHitKHR, 0u, sizeof(PushConstant), &pc); TraceRays(cmdBuffer, extent.width, extent.height, 1u); } } // namespace vl
37.198276
117
0.756431
RaygenEngine
bcf8c8fec0ebf865e37923634ced910583cb65e8
3,082
hpp
C++
inc/streamDumper.hpp
WMFO/Silence-Detector
af932c13e6e121b094038ad08e7d2e667c67351c
[ "MIT" ]
18
2015-07-18T11:44:41.000Z
2021-03-27T17:23:48.000Z
inc/streamDumper.hpp
WMFO/Silence-Detector
af932c13e6e121b094038ad08e7d2e667c67351c
[ "MIT" ]
null
null
null
inc/streamDumper.hpp
WMFO/Silence-Detector
af932c13e6e121b094038ad08e7d2e667c67351c
[ "MIT" ]
6
2017-05-26T08:55:05.000Z
2021-10-08T01:56:41.000Z
#ifndef STREAMDUMPER_H #define STREAMDUMPER_H #include <exception> #include <string> #include <iostream> #include <list> class streamDumper { public: streamDumper(); streamDumper(const std::string &bindAddr, const std::string &ipaddr, int portNumber); void openMulticastStream(const std::string &bindAddr, const std::string &ipaddr, int portNumber); ~streamDumper(); void getSocketData(unsigned char* buf, unsigned long bufLen); private: std::string multicastAddr; int port; bool socketActive; bool subscriptionActive; int socketDescriptor; unsigned char *remainderData; unsigned long remainderDataLength; void openSocket(); void closeSocket(); void readSocket(); class RTPHeader { public: RTPHeader(); RTPHeader(unsigned char*); ~RTPHeader(); void readData(unsigned char*); int getVersion() const; bool hasPadding() const; bool hasExtension() const; unsigned int getCSRCCount() const; unsigned int getPayloadType() const; unsigned long getSequenceNumber() const; unsigned long getTimestamp() const; unsigned long getSSRCIdentifier() const; unsigned long getHeaderLength() const; private: int version; bool padding; bool extensions; unsigned int CSRCCount; unsigned int payloadType; unsigned long sequenceNumber; unsigned long timeStamp; unsigned long SSRCIdentifier; unsigned long extensionLength; }; class RTPPacket { public: RTPHeader header; RTPPacket(); RTPPacket(unsigned char*, unsigned long); ~RTPPacket(); void readData(unsigned char*, unsigned long); unsigned long getContentLength() const; unsigned char *getContent() const; bool operator<(const RTPPacket &b) const; RTPPacket(const RTPPacket &b); RTPPacket &operator=(const RTPPacket &b); private: unsigned char *content; unsigned long contentLength; }; void setRemainderData(const unsigned char *, unsigned long, const std::list<RTPPacket>&); }; //Exceptions class streamDumperException : public std::exception { public: streamDumperException(const std::string &reason) throw() { exceptionWhat = reason; } virtual const char *what() const throw() { return exceptionWhat.c_str(); } virtual ~streamDumperException() throw() {}; private: std::string exceptionWhat; }; #endif
28.803738
105
0.544452
WMFO
bcfbc46ae8d61352d53dac09f9d91c2d8c3b3f7d
9,319
cpp
C++
src/theory/sets/theory_sets_rewriter.cpp
HasibShakur/CVC4
7a303390a65fd395a53085833d504acc312dc6a6
[ "BSL-1.0" ]
null
null
null
src/theory/sets/theory_sets_rewriter.cpp
HasibShakur/CVC4
7a303390a65fd395a53085833d504acc312dc6a6
[ "BSL-1.0" ]
null
null
null
src/theory/sets/theory_sets_rewriter.cpp
HasibShakur/CVC4
7a303390a65fd395a53085833d504acc312dc6a6
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file theory_sets_rewriter.cpp ** \verbatim ** Original author: Kshitij Bansal ** Major contributors: none ** Minor contributors (to current version): none ** This file is part of the CVC4 project. ** Copyright (c) 2013-2014 New York University and The University of Iowa ** See the file COPYING in the top-level source directory for licensing ** information.\endverbatim ** ** \brief Sets theory rewriter. ** ** Sets theory rewriter. **/ #include "theory/sets/theory_sets_rewriter.h" namespace CVC4 { namespace theory { namespace sets { typedef std::set<TNode> Elements; typedef std::hash_map<TNode, Elements, TNodeHashFunction> SettermElementsMap; bool checkConstantMembership(TNode elementTerm, TNode setTerm) { // Assume from pre-rewrite constant sets look like the following: // (union (setenum bla) (union (setenum bla) ... (union (setenum bla) (setenum bla) ) ... )) if(setTerm.getKind() == kind::EMPTYSET) { return false; } if(setTerm.getKind() == kind::SET_SINGLETON) { return elementTerm == setTerm[0]; } Assert(setTerm.getKind() == kind::UNION && setTerm[1].getKind() == kind::SET_SINGLETON, "kind was %d, term: %s", setTerm.getKind(), setTerm.toString().c_str()); return elementTerm == setTerm[1][0] || checkConstantMembership(elementTerm, setTerm[0]); // switch(setTerm.getKind()) { // case kind::EMPTYSET: // return false; // case kind::SET_SINGLETON: // return elementTerm == setTerm[0]; // case kind::UNION: // return checkConstantMembership(elementTerm, setTerm[0]) || // checkConstantMembership(elementTerm, setTerm[1]); // case kind::INTERSECTION: // return checkConstantMembership(elementTerm, setTerm[0]) && // checkConstantMembership(elementTerm, setTerm[1]); // case kind::SETMINUS: // return checkConstantMembership(elementTerm, setTerm[0]) && // !checkConstantMembership(elementTerm, setTerm[1]); // default: // Unhandled(); // } } // static RewriteResponse TheorySetsRewriter::postRewrite(TNode node) { NodeManager* nm = NodeManager::currentNM(); Kind kind = node.getKind(); switch(kind) { case kind::MEMBER: { if(node[0].isConst() && node[1].isConst()) { // both are constants TNode S = preRewrite(node[1]).node; bool isMember = checkConstantMembership(node[0], S); return RewriteResponse(REWRITE_DONE, nm->mkConst(isMember)); } break; }//kind::MEMBER case kind::SUBSET: { // rewrite (A subset-or-equal B) as (A union B = B) TNode A = node[0]; TNode B = node[1]; return RewriteResponse(REWRITE_AGAIN_FULL, nm->mkNode(kind::EQUAL, nm->mkNode(kind::UNION, A, B), B) ); }//kind::SUBSET case kind::EQUAL: case kind::IFF: { //rewrite: t = t with true (t term) //rewrite: c = c' with c different from c' false (c, c' constants) //otherwise: sort them if(node[0] == node[1]) { Trace("sets-postrewrite") << "Sets::postRewrite returning true" << std::endl; return RewriteResponse(REWRITE_DONE, nm->mkConst(true)); } else if (node[0].isConst() && node[1].isConst()) { Trace("sets-postrewrite") << "Sets::postRewrite returning false" << std::endl; return RewriteResponse(REWRITE_DONE, nm->mkConst(false)); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::IFF case kind::SETMINUS: { if(node[0] == node[1]) { Node newNode = nm->mkConst(EmptySet(nm->toType(node[0].getType()))); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } else if(node[0].getKind() == kind::EMPTYSET || node[1].getKind() == kind::EMPTYSET) { Trace("sets-postrewrite") << "Sets::postRewrite returning " << node[0] << std::endl; return RewriteResponse(REWRITE_DONE, node[0]); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::INTERSECION case kind::INTERSECTION: { if(node[0] == node[1]) { Trace("sets-postrewrite") << "Sets::postRewrite returning " << node[0] << std::endl; return RewriteResponse(REWRITE_DONE, node[0]); } else if(node[0].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[0]); } else if(node[1].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[1]); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::INTERSECION case kind::UNION: { if(node[0] == node[1]) { Trace("sets-postrewrite") << "Sets::postRewrite returning " << node[0] << std::endl; return RewriteResponse(REWRITE_DONE, node[0]); } else if(node[0].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[1]); } else if(node[1].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[0]); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::UNION default: break; }//switch(node.getKind()) // This default implementation return RewriteResponse(REWRITE_DONE, node); } const Elements& collectConstantElements(TNode setterm, SettermElementsMap& settermElementsMap) { SettermElementsMap::const_iterator it = settermElementsMap.find(setterm); if(it == settermElementsMap.end() ) { Kind k = setterm.getKind(); unsigned numChildren = setterm.getNumChildren(); Elements cur; if(numChildren == 2) { const Elements& left = collectConstantElements(setterm[0], settermElementsMap); const Elements& right = collectConstantElements(setterm[1], settermElementsMap); switch(k) { case kind::UNION: if(left.size() >= right.size()) { cur = left; cur.insert(right.begin(), right.end()); } else { cur = right; cur.insert(left.begin(), left.end()); } break; case kind::INTERSECTION: std::set_intersection(left.begin(), left.end(), right.begin(), right.end(), std::inserter(cur, cur.begin()) ); break; case kind::SETMINUS: std::set_difference(left.begin(), left.end(), right.begin(), right.end(), std::inserter(cur, cur.begin()) ); break; default: Unhandled(); } } else { switch(k) { case kind::EMPTYSET: /* assign emptyset, which is default */ break; case kind::SET_SINGLETON: Assert(setterm[0].isConst()); cur.insert(TheorySetsRewriter::preRewrite(setterm[0]).node); break; default: Unhandled(); } } Debug("sets-rewrite-constant") << "[sets-rewrite-constant] "<< setterm << " " << setterm.getId() << std::endl; it = settermElementsMap.insert(SettermElementsMap::value_type(setterm, cur)).first; } return it->second; } Node elementsToNormalConstant(Elements elements, TypeNode setType) { NodeManager* nm = NodeManager::currentNM(); if(elements.size() == 0) { return nm->mkConst(EmptySet(nm->toType(setType))); } else { Elements::iterator it = elements.begin(); Node cur = nm->mkNode(kind::SET_SINGLETON, *it); while( ++it != elements.end() ) { cur = nm->mkNode(kind::UNION, cur, nm->mkNode(kind::SET_SINGLETON, *it)); } return cur; } } // static RewriteResponse TheorySetsRewriter::preRewrite(TNode node) { NodeManager* nm = NodeManager::currentNM(); // do nothing if(node.getKind() == kind::EQUAL && node[0] == node[1]) return RewriteResponse(REWRITE_DONE, nm->mkConst(true)); // Further optimization, if constants but differing ones if(node.getType().isSet() && node.isConst()) { //rewrite set to normal form SettermElementsMap setTermElementsMap; // cache const Elements& elements = collectConstantElements(node, setTermElementsMap); RewriteResponse response(REWRITE_DONE, elementsToNormalConstant(elements, node.getType())); Debug("sets-rewrite-constant") << "[sets-rewrite-constant] Rewriting " << node << std::endl << "[sets-rewrite-constant] to " << response.node << std::endl; return response; } return RewriteResponse(REWRITE_DONE, node); } }/* CVC4::theory::sets namespace */ }/* CVC4::theory namespace */ }/* CVC4 namespace */
35.568702
114
0.620882
HasibShakur
bcfdc549ffe55591888e2088498b9f43fa364212
37,103
cpp
C++
RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2017 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreVulkanTextureGpu.h" #include "OgreException.h" #include "OgreVector.h" #include "OgreVulkanMappings.h" #include "OgreVulkanTextureGpuManager.h" #include "OgreVulkanUtils.h" #include "OgreVulkanHardwareBuffer.h" #include "OgreBitwise.h" #include "OgreRoot.h" #include "OgreVulkanTextureGpuWindow.h" #define TODO_add_resource_transitions namespace Ogre { VulkanHardwarePixelBuffer::VulkanHardwarePixelBuffer(VulkanTextureGpu* tex, uint32 width, uint32 height, uint32 depth, uint8 face, uint32 mip) : HardwarePixelBuffer(width, height, depth, tex->getFormat(), tex->getUsage(), false, false), mParent(tex), mFace(face), mLevel(mip) { if(mParent->getUsage() & TU_RENDERTARGET) { // Create render target for each slice mSliceTRT.reserve(mDepth); for(size_t zoffset=0; zoffset<mDepth; ++zoffset) { String name; name = "rtt/"+StringConverter::toString((size_t)this) + "/" + mParent->getName(); RenderTexture *trt = new VulkanRenderTexture(name, this, zoffset, mParent, mFace); mSliceTRT.push_back(trt); Root::getSingleton().getRenderSystem()->attachRenderTarget(*trt); } } } PixelBox VulkanHardwarePixelBuffer::lockImpl(const Box &lockBox, LockOptions options) { PixelBox ret(lockBox, mParent->getFormat()); auto textureManager = static_cast<VulkanTextureGpuManager*>(mParent->getCreator()); VulkanDevice* device = textureManager->getDevice(); mStagingBuffer.reset(new VulkanHardwareBuffer(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, ret.getConsecutiveSize(), HBU_CPU_ONLY, false, device)); return PixelBox(lockBox, mParent->getFormat(), mStagingBuffer->lock(options)); } void VulkanHardwarePixelBuffer::unlockImpl() { mStagingBuffer->unlock(); auto textureManager = static_cast<VulkanTextureGpuManager*>(mParent->getCreator()); VulkanDevice* device = textureManager->getDevice(); device->mGraphicsQueue.getCopyEncoder( 0, mParent, false ); VkBuffer srcBuffer = mStagingBuffer->getVkBuffer(); VkBufferImageCopy region; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = mLevel; region.imageSubresource.baseArrayLayer = mFace; region.imageSubresource.layerCount = 1; region.imageOffset.x = mCurrentLock.left; region.imageOffset.y = mCurrentLock.top; region.imageOffset.z = mCurrentLock.front; region.imageExtent.width = mCurrentLock.getWidth(); region.imageExtent.height = mCurrentLock.getHeight(); region.imageExtent.depth = mCurrentLock.getDepth(); if(mParent->getTextureType() == TEX_TYPE_2D_ARRAY) { region.imageSubresource.baseArrayLayer = mCurrentLock.front; region.imageOffset.z = 0; } vkCmdCopyBufferToImage(device->mGraphicsQueue.mCurrentCmdBuffer, srcBuffer, mParent->getFinalTextureName(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &region); bool finalSlice = region.imageSubresource.baseArrayLayer == mParent->getNumLayers() - 1; if((mParent->getUsage() & TU_AUTOMIPMAP) && finalSlice) mParent->_autogenerateMipmaps(); mStagingBuffer.reset(); } void VulkanHardwarePixelBuffer::blitFromMemory(const PixelBox& src, const Box& dstBox) { OgreAssert(src.getSize() == dstBox.getSize(), "scaling currently not supported"); // convert to image native format if necessary if(src.format != mFormat) { std::vector<uint8> buffer; buffer.resize(PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), src.getDepth(), mFormat)); PixelBox converted = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), mFormat, buffer.data()); PixelUtil::bulkPixelConversion(src, converted); blitFromMemory(converted, dstBox); // recursive call return; } auto ptr = lock(dstBox, HBL_WRITE_ONLY).data; memcpy(ptr, src.data, src.getConsecutiveSize()); unlock(); } void VulkanHardwarePixelBuffer::blitToMemory(const Box& srcBox, const PixelBox& dst) { OgreAssert(srcBox.getSize() == dst.getSize(), "scaling currently not supported"); auto textureManager = static_cast<VulkanTextureGpuManager*>(mParent->getCreator()); VulkanDevice* device = textureManager->getDevice(); auto stagingBuffer = std::make_shared<VulkanHardwareBuffer>( VK_BUFFER_USAGE_TRANSFER_DST_BIT, dst.getConsecutiveSize(), HBU_CPU_ONLY, false, device); device->mGraphicsQueue.getCopyEncoder(0, mParent, true); VkBuffer dstBuffer = stagingBuffer->getVkBuffer(); VkBufferImageCopy region; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset.x = 0; region.imageOffset.y = 0; region.imageOffset.z = 0; region.imageExtent.width = srcBox.getWidth(); region.imageExtent.height = srcBox.getHeight(); region.imageExtent.depth = srcBox.getDepth(); vkCmdCopyImageToBuffer(device->mGraphicsQueue.mCurrentCmdBuffer, mParent->getFinalTextureName(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstBuffer, 1u, &region); device->mGraphicsQueue.commitAndNextCommandBuffer(); stagingBuffer->readData(0, dst.getConsecutiveSize(), dst.data); } VulkanTextureGpu::VulkanTextureGpu(TextureManager* textureManager, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : Texture(textureManager, name, handle, group, isManual, loader ), mDefaultDisplaySrv( 0 ), mDisplayTextureName( 0 ), mFinalTextureName( 0 ), mMemory(VK_NULL_HANDLE), mMsaaTextureName( 0 ), mMsaaMemory(VK_NULL_HANDLE), mCurrLayout( VK_IMAGE_LAYOUT_UNDEFINED ), mNextLayout( VK_IMAGE_LAYOUT_UNDEFINED ) { } //----------------------------------------------------------------------------------- VulkanTextureGpu::~VulkanTextureGpu() { unload(); } //----------------------------------------------------------------------------------- void VulkanTextureGpu::createInternalResourcesImpl( void ) { if( mFormat == PF_UNKNOWN ) return; // Nothing to do // Adjust format if required. mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); mNumMipmaps = std::min(mNumMipmaps, Bitwise::mostSignificantBitSet(std::max(mWidth, std::max(mHeight, mDepth)))); VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; imageInfo.imageType = getVulkanTextureType(); imageInfo.extent.width = getWidth(); imageInfo.extent.height = getHeight(); imageInfo.extent.depth = getDepth(); imageInfo.mipLevels = mNumMipmaps + 1; imageInfo.arrayLayers = getNumFaces(); imageInfo.flags = 0; imageInfo.format = VulkanMappings::get( mFormat ); imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if(mTextureType == TEX_TYPE_2D_ARRAY) std::swap(imageInfo.extent.depth, imageInfo.arrayLayers); if( hasMsaaExplicitResolves() ) { imageInfo.samples = VkSampleCountFlagBits(std::max(mFSAA, 1u)); } else imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; if( mTextureType == TEX_TYPE_CUBE_MAP /*|| mTextureType == TextureTypes::TypeCubeArray*/ ) imageInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; imageInfo.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if (PixelUtil::isDepth(mFormat)) imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; else if(mUsage & TU_RENDERTARGET) imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if( isUav() ) imageInfo.usage |= VK_IMAGE_USAGE_STORAGE_BIT; String textureName = getName(); auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice* device = textureManager->getDevice(); OGRE_VK_CHECK(vkCreateImage(device->mDevice, &imageInfo, 0, &mFinalTextureName)); setObjectName( device->mDevice, (uint64_t)mFinalTextureName, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, textureName.c_str() ); VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements( device->mDevice, mFinalTextureName, &memRequirements ); VkMemoryAllocateInfo memAllocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; memAllocInfo.allocationSize = memRequirements.size; memAllocInfo.memoryTypeIndex = 0; const auto& memProperties = device->mDeviceMemoryProperties; for(; memAllocInfo.memoryTypeIndex < memProperties.memoryTypeCount; memAllocInfo.memoryTypeIndex++) { if ((memProperties.memoryTypes[memAllocInfo.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { break; } } OGRE_VK_CHECK(vkAllocateMemory(device->mDevice, &memAllocInfo, NULL, &mMemory)); OGRE_VK_CHECK(vkBindImageMemory(device->mDevice, mFinalTextureName, mMemory, 0)); OgreAssert(device->mGraphicsQueue.getEncoderState() != VulkanQueue::EncoderGraphicsOpen, "interrupting RenderPass not supported"); device->mGraphicsQueue.endAllEncoders(); // Pool owners transition all its slices to read_only_optimal to avoid the validation layers // from complaining the unused (and untouched) slices are in the wrong layout. // We wait for no stage, and no stage waits for us. No caches are flushed. // // Later our TextureGpus using individual slices will perform an // undefined -> read_only_optimal transition on the individual slices & mips // to fill the data; and those transitions will be the ones who take care of blocking // previous/later stages in their respective barriers VkImageMemoryBarrier imageBarrier = this->getImageMemoryBarrier(); imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; if( PixelUtil::isDepth( mFormat ) ) imageBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); mCurrLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; mNextLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // create uint32 depth = mDepth; for (uint8 face = 0; face < getNumFaces(); face++) { uint32 width = mWidth; uint32 height = mHeight; for (uint32 mip = 0; mip <= getNumMipmaps(); mip++) { auto buf = std::make_shared<VulkanHardwarePixelBuffer>(this, width, height, depth, face, mip); mSurfaceList.push_back(buf); if (width > 1) width = width / 2; if (height > 1) height = height / 2; if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) depth = depth / 2; } } mDefaultDisplaySrv = _createView(0, 0, 0, getNumLayers()); if( mFSAA > 1 && !hasMsaaExplicitResolves() ) createMsaaSurface(); } //----------------------------------------------------------------------------------- void VulkanTextureGpu::freeInternalResourcesImpl( void ) { // If 'this' is being destroyed: We must call notifyTextureDestroyed // // If 'this' is only being transitioned to OnStorage: // Our VkImage is being destroyed; and there may be pending image operations on it. // This wouldn't be a problem because the vkDestroyImage call is delayed. // However if the texture is later transitioned again to Resident, mCurrLayout & mNextLayout // will get out of sync when endCopyEncoder gets called. // // e.g. if a texture performs: // OnStorage -> Resident -> <upload operation> -> OnStorage -> Resident -> // endCopyEncoder -> <upload operation> -> endCopyEncoder // // then the 1st endCopyEncoder will set mCurrLayout to SHADER_READ_ONLY_OPTIMAL because // it thinks it changed the layout of the current mFinalTextureName, but it actually // changed the layout of the previous mFinalTextureName which is scheduled to be destroyed auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice *device = textureManager->getDevice(); device->mGraphicsQueue.notifyTextureDestroyed( this ); vkDestroyImageView(device->mDevice, mDefaultDisplaySrv, 0); mDefaultDisplaySrv = 0; vkDestroyImage(device->mDevice, mFinalTextureName, 0); vkFreeMemory(device->mDevice, mMemory, 0); destroyMsaaSurface(); mCurrLayout = VK_IMAGE_LAYOUT_UNDEFINED; mNextLayout = VK_IMAGE_LAYOUT_UNDEFINED; } //----------------------------------------------------------------------------------- void VulkanTextureGpu::copyTo( TextureGpu *dst, const PixelBox &dstBox, uint8 dstMipLevel, const PixelBox &srcBox, uint8 srcMipLevel, bool keepResolvedTexSynced, ResourceAccess::ResourceAccess issueBarriers ) { //TextureGpu::copyTo( dst, dstBox, dstMipLevel, srcBox, srcMipLevel, issueBarriers ); OGRE_ASSERT_HIGH( dynamic_cast<VulkanTextureGpu *>( dst ) ); VulkanTextureGpu *dstTexture = static_cast<VulkanTextureGpu *>( dst ); VulkanTextureGpuManager *textureManager = static_cast<VulkanTextureGpuManager *>( mCreator ); VulkanDevice *device = textureManager->getDevice(); if( issueBarriers & ResourceAccess::Read ) device->mGraphicsQueue.getCopyEncoder( 0, this, true ); else { // This won't generate barriers, but it will close all other encoders // and open the copy one device->mGraphicsQueue.getCopyEncoder( 0, 0, true ); } if( issueBarriers & ResourceAccess::Write ) device->mGraphicsQueue.getCopyEncoder( 0, dstTexture, false ); VkImageCopy region; const uint32 sourceSlice = srcBox.front;// + getInternalSliceStart(); const uint32 destinationSlice = dstBox.front;// + dstTexture->getInternalSliceStart(); const uint32 numSlices = dstBox.getDepth() != 0 ? dstBox.getDepth() : dstTexture->getDepth(); region.srcSubresource.aspectMask = VulkanMappings::getImageAspect( this->getFormat() ); region.srcSubresource.mipLevel = srcMipLevel; region.srcSubresource.baseArrayLayer = sourceSlice; region.srcSubresource.layerCount = numSlices; region.srcOffset.x = static_cast<int32_t>( srcBox.left ); region.srcOffset.y = static_cast<int32_t>( srcBox.top ); region.srcOffset.z = static_cast<int32_t>( srcBox.front ); region.dstSubresource.aspectMask = VulkanMappings::getImageAspect( dst->getFormat() ); region.dstSubresource.mipLevel = dstMipLevel; region.dstSubresource.baseArrayLayer = destinationSlice; region.dstSubresource.layerCount = numSlices; region.dstOffset.x = dstBox.left; region.dstOffset.y = dstBox.top; region.dstOffset.z = dstBox.front; region.extent.width = srcBox.getWidth(); region.extent.height = srcBox.getHeight(); region.extent.depth = srcBox.getDepth(); VkImage srcTextureName = this->mFinalTextureName; VkImage dstTextureName = dstTexture->mFinalTextureName; if( this->isMultisample() && !this->hasMsaaExplicitResolves() ) srcTextureName = this->mMsaaTextureName; if( dstTexture->isMultisample() && !dstTexture->hasMsaaExplicitResolves() ) dstTextureName = dstTexture->mMsaaTextureName; vkCmdCopyImage( device->mGraphicsQueue.mCurrentCmdBuffer, srcTextureName, mCurrLayout, dstTextureName, dstTexture->mCurrLayout, 1u, &region ); if( dstTexture->isMultisample() && !dstTexture->hasMsaaExplicitResolves() && keepResolvedTexSynced ) { TODO_add_resource_transitions; // We must add res. transitions and then restore them // Must keep the resolved texture up to date. VkImageResolve resolve = {}; resolve.srcSubresource = region.dstSubresource; resolve.dstSubresource = region.dstSubresource; resolve.extent.width = getWidth(); resolve.extent.height = getHeight(); resolve.extent.depth = getDepth(); vkCmdResolveImage( device->mGraphicsQueue.mCurrentCmdBuffer, dstTexture->mMsaaTextureName, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstTexture->mFinalTextureName, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &resolve ); } // Do not perform the sync if notifyDataIsReady hasn't been called yet (i.e. we're // still building the HW mipmaps, and the texture will never be ready) /*if( dst->_isDataReadyImpl() && dst->getGpuPageOutStrategy() == GpuPageOutStrategy::AlwaysKeepSystemRamCopy ) { dst->_syncGpuResidentToSystemRam(); }*/ } //----------------------------------------------------------------------------------- void VulkanTextureGpu::_autogenerateMipmaps( bool bUseBarrierSolver ) { // TODO: Integrate FidelityFX Single Pass Downsampler - SPD // // https://gpuopen.com/fidelityfx-spd/ // https://github.com/GPUOpen-Effects/FidelityFX-SPD VulkanTextureGpuManager *textureManager = static_cast<VulkanTextureGpuManager *>( mCreator ); VulkanDevice *device = textureManager->getDevice(); const bool callerIsCompositor = mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; if( callerIsCompositor ) device->mGraphicsQueue.getCopyEncoder( 0, 0, true ); else { // We must transition to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL // By the time we exit _autogenerateMipmaps, the texture will // still be in VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, thus // endCopyEncoder will perform as expected device->mGraphicsQueue.getCopyEncoder( 0, this, true ); } const uint32 numSlices = getNumLayers(); VkImageMemoryBarrier imageBarrier = getImageMemoryBarrier(); imageBarrier.subresourceRange.levelCount = 1u; const uint32 internalWidth = getWidth(); const uint32 internalHeight = getHeight(); for( size_t i = 1u; i <= mNumMipmaps; ++i ) { // Convert the dst mipmap 'i' to TRANSFER_DST_OPTIMAL. Does not have to wait // on anything because previous barriers (compositor or getCopyEncoder) // have already waited imageBarrier.subresourceRange.baseMipLevel = static_cast<uint32_t>( i ); imageBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; imageBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; imageBarrier.srcAccessMask = 0; imageBarrier.dstAccessMask = 0; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); VkImageBlit region; region.srcSubresource.aspectMask = VulkanMappings::getImageAspect( this->getFormat() ); region.srcSubresource.mipLevel = static_cast<uint32_t>( i - 1u ); region.srcSubresource.baseArrayLayer = 0u; region.srcSubresource.layerCount = numSlices; region.srcOffsets[0].x = 0; region.srcOffsets[0].y = 0; region.srcOffsets[0].z = 0; region.srcOffsets[1].x = static_cast<int32_t>( std::max( internalWidth >> ( i - 1u ), 1u ) ); region.srcOffsets[1].y = static_cast<int32_t>( std::max( internalHeight >> ( i - 1u ), 1u ) ); region.srcOffsets[1].z = static_cast<int32_t>( std::max( getDepth() >> ( i - 1u ), 1u ) ); region.dstSubresource.aspectMask = region.srcSubresource.aspectMask; region.dstSubresource.mipLevel = static_cast<uint32_t>( i ); region.dstSubresource.baseArrayLayer = 0u; region.dstSubresource.layerCount = numSlices; region.dstOffsets[0].x = 0; region.dstOffsets[0].y = 0; region.dstOffsets[0].z = 0; region.dstOffsets[1].x = static_cast<int32_t>( std::max( internalWidth >> i, 1u ) ); region.dstOffsets[1].y = static_cast<int32_t>( std::max( internalHeight >> i, 1u ) ); region.dstOffsets[1].z = static_cast<int32_t>( std::max( getDepth() >> i, 1u ) ); if(mTextureType == TEX_TYPE_2D_ARRAY) { region.srcOffsets[1].z = 1; region.dstOffsets[1].z = 1; } vkCmdBlitImage( device->mGraphicsQueue.mCurrentCmdBuffer, mFinalTextureName, mCurrLayout, mFinalTextureName, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &region, VK_FILTER_LINEAR ); // Wait for vkCmdBlitImage on mip i to finish before advancing to mip i+1 // Also transition src mip 'i' to TRANSFER_SRC_OPTIMAL imageBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; imageBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; imageBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); } } //----------------------------------------------------------------------------------- VkImageType VulkanTextureGpu::getVulkanTextureType( void ) const { // clang-format off switch( mTextureType ) { case TEX_TYPE_1D: return VK_IMAGE_TYPE_1D; case TEX_TYPE_2D: return VK_IMAGE_TYPE_2D; case TEX_TYPE_2D_ARRAY: return VK_IMAGE_TYPE_2D; case TEX_TYPE_CUBE_MAP: return VK_IMAGE_TYPE_2D; case TEX_TYPE_3D: return VK_IMAGE_TYPE_3D; case TEX_TYPE_EXTERNAL_OES: break; } // clang-format on return VK_IMAGE_TYPE_2D; } //----------------------------------------------------------------------------------- VkImageViewType VulkanTextureGpu::getInternalVulkanTextureViewType( void ) const { // clang-format off switch( getTextureType() ) { case TEX_TYPE_1D: return VK_IMAGE_VIEW_TYPE_1D; case TEX_TYPE_2D: return VK_IMAGE_VIEW_TYPE_2D; case TEX_TYPE_2D_ARRAY: return VK_IMAGE_VIEW_TYPE_2D_ARRAY; case TEX_TYPE_CUBE_MAP: return VK_IMAGE_VIEW_TYPE_CUBE; case TEX_TYPE_3D: return VK_IMAGE_VIEW_TYPE_3D; case TEX_TYPE_EXTERNAL_OES: break; } // clang-format on return VK_IMAGE_VIEW_TYPE_2D; } //----------------------------------------------------------------------------------- VkImageView VulkanTextureGpu::_createView( uint8 mipLevel, uint8 numMipmaps, uint16 arraySlice, uint32 numSlices, VkImage imageOverride ) const { VkImageViewType texType = this->getInternalVulkanTextureViewType(); if (numSlices == 1u && mTextureType == TEX_TYPE_CUBE_MAP) { texType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; } if( !numMipmaps ) numMipmaps = mNumMipmaps - mipLevel + 1; OGRE_ASSERT_LOW( numMipmaps <= (mNumMipmaps - mipLevel + 1) && "Asking for more mipmaps than the texture has!" ); auto textureManager = static_cast<VulkanTextureGpuManager*>(TextureManager::getSingletonPtr()); VulkanDevice *device = textureManager->getDevice(); VkImageViewCreateInfo imageViewCi = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; imageViewCi.image = imageOverride ? imageOverride : mFinalTextureName; imageViewCi.viewType = texType; imageViewCi.format = VulkanMappings::get( mFormat ); if (PixelUtil::isLuminance(mFormat) && !PixelUtil::isDepth(mFormat)) { if (PixelUtil::getComponentCount(mFormat) == 2) { imageViewCi.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G}; } else { imageViewCi.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_ONE}; } } else if (mFormat == PF_A8) { imageViewCi.components = {VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_R}; } // Using both depth & stencil aspects in an image view for texture sampling is illegal // Thus prefer depth over stencil. We only use both flags for FBOs imageViewCi.subresourceRange.aspectMask = VulkanMappings::getImageAspect(mFormat, imageOverride == 0); imageViewCi.subresourceRange.baseMipLevel = mipLevel; imageViewCi.subresourceRange.levelCount = numMipmaps; imageViewCi.subresourceRange.baseArrayLayer = arraySlice; if( numSlices == 0u ) imageViewCi.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; else imageViewCi.subresourceRange.layerCount = numSlices; VkImageViewUsageCreateInfo flagRestriction = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; if( textureManager->canRestrictImageViewUsage() && isUav() ) { // Some formats (e.g. *_SRGB formats) do not support USAGE_STORAGE_BIT at all // Thus we need to mark when this view won't be using that bit. // // If VK_KHR_maintenance2 is not available then we cross our fingers // and hope the driver doesn't stop us from doing it (it should work) // // The validation layers will complain though. This was a major Vulkan oversight. imageViewCi.pNext = &flagRestriction; flagRestriction.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; flagRestriction.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if (mUsage & TU_RENDERTARGET) { flagRestriction.usage |= PixelUtil::isDepth(mFormat) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } } VkImageView imageView; OGRE_VK_CHECK(vkCreateImageView( device->mDevice, &imageViewCi, 0, &imageView )); return imageView; } //----------------------------------------------------------------------------------- void VulkanTextureGpu::destroyView( VkImageView imageView ) { //VulkanTextureGpuManager *textureManager = // static_cast<VulkanTextureGpuManager *>( mCreator ); //VulkanDevice *device = textureManager->getDevice(); //delayed_vkDestroyImageView( textureManager->getVaoManager(), device->mDevice, imageView, 0 ); } //----------------------------------------------------------------------------------- VkImageView VulkanTextureGpu::createView( void ) const { OGRE_ASSERT_MEDIUM( mDefaultDisplaySrv && "Either the texture wasn't properly loaded or _setToDisplayDummyTexture " "wasn't called when it should have been" ); return mDefaultDisplaySrv; } //----------------------------------------------------------------------------------- VkImageMemoryBarrier VulkanTextureGpu::getImageMemoryBarrier( void ) const { VkImageMemoryBarrier imageMemBarrier = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; imageMemBarrier.image = mFinalTextureName; imageMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemBarrier.subresourceRange.aspectMask = VulkanMappings::getImageAspect(mFormat); imageMemBarrier.subresourceRange.baseMipLevel = 0u; imageMemBarrier.subresourceRange.levelCount = mNumMipmaps + 1; imageMemBarrier.subresourceRange.baseArrayLayer = 0; imageMemBarrier.subresourceRange.layerCount = getNumLayers(); return imageMemBarrier; } //----------------------------------------------------------------------------------- void VulkanTextureGpu::createMsaaSurface( void ) { VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; imageInfo.imageType = getVulkanTextureType(); imageInfo.extent.width = getWidth(); imageInfo.extent.height = getHeight(); imageInfo.extent.depth = getDepth(); imageInfo.mipLevels = 1u; imageInfo.arrayLayers = 1u; imageInfo.format = VulkanMappings::get( mFormat ); imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.samples = VkSampleCountFlagBits( mFSAA ); imageInfo.flags = 0; imageInfo.usage |= PixelUtil::isDepth( mFormat ) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; String textureName = getName() + "/MsaaImplicit"; auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice* device = textureManager->getDevice(); OGRE_VK_CHECK(vkCreateImage( device->mDevice, &imageInfo, 0, &mMsaaTextureName )); setObjectName(device->mDevice, (uint64_t)mMsaaTextureName, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, textureName.c_str()); VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements( device->mDevice, mMsaaTextureName, &memRequirements ); VkMemoryAllocateInfo memAllocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; memAllocInfo.allocationSize = memRequirements.size; memAllocInfo.memoryTypeIndex = 0; const auto& memProperties = device->mDeviceMemoryProperties; for(; memAllocInfo.memoryTypeIndex < memProperties.memoryTypeCount; memAllocInfo.memoryTypeIndex++) { if ((memProperties.memoryTypes[memAllocInfo.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { break; } } OGRE_VK_CHECK(vkAllocateMemory(device->mDevice, &memAllocInfo, NULL, &mMsaaMemory)); OGRE_VK_CHECK(vkBindImageMemory(device->mDevice, mMsaaTextureName, mMsaaMemory, 0)); // Immediately transition to its only state VkImageMemoryBarrier imageBarrier = this->getImageMemoryBarrier(); imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; if( PixelUtil::isDepth( mFormat ) ) imageBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; imageBarrier.image = mMsaaTextureName; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); } //----------------------------------------------------------------------------------- void VulkanTextureGpu::destroyMsaaSurface( void ) { if(!mMsaaTextureName) return; auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice *device = textureManager->getDevice(); vkDestroyImage(device->mDevice, mMsaaTextureName, 0); vkFreeMemory(device->mDevice, mMsaaMemory, 0); } VulkanRenderTexture::VulkanRenderTexture(const String& name, HardwarePixelBuffer* buffer, uint32 zoffset, VulkanTextureGpu* target, uint32 face) : RenderTexture(buffer, zoffset) { mName = name; auto texMgr = TextureManager::getSingletonPtr(); VulkanDevice* device = static_cast<VulkanTextureGpuManager*>(texMgr)->getDevice(); target->setFSAA(1, ""); bool depthTarget = PixelUtil::isDepth(target->getFormat()); if(!depthTarget) { mDepthTexture.reset(new VulkanTextureGpu(texMgr, mName+"/Depth", 0, "", true, 0)); mDepthTexture->setWidth(target->getWidth()); mDepthTexture->setHeight(target->getHeight()); mDepthTexture->setFormat(PF_DEPTH32F); mDepthTexture->createInternalResources(); mDepthTexture->setFSAA(1, ""); } mRenderPassDescriptor.reset(new VulkanRenderPassDescriptor(&device->mGraphicsQueue, device->mRenderSystem)); mRenderPassDescriptor->mColour[0] = depthTarget ? 0 : target; mRenderPassDescriptor->mSlice = face; mRenderPassDescriptor->mDepth = depthTarget ? target : mDepthTexture.get(); mRenderPassDescriptor->mNumColourEntries = int(depthTarget == 0); mRenderPassDescriptor->entriesModified(true); } } // namespace Ogre
46.436796
122
0.630488
dawlane
4c010613929393f758a5955fe16d392919f02e27
4,419
hpp
C++
include/codegen/include/UnityEngine/UI/Mask.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/UI/Mask.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/UI/Mask.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:38 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.EventSystems.UIBehaviour #include "UnityEngine/EventSystems/UIBehaviour.hpp" // Including type: UnityEngine.ICanvasRaycastFilter #include "UnityEngine/ICanvasRaycastFilter.hpp" // Including type: UnityEngine.UI.IMaterialModifier #include "UnityEngine/UI/IMaterialModifier.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RectTransform class RectTransform; // Forward declaring type: Material class Material; // Forward declaring type: Vector2 struct Vector2; // Forward declaring type: Camera class Camera; } // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Graphic class Graphic; } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Autogenerated type: UnityEngine.UI.Mask class Mask : public UnityEngine::EventSystems::UIBehaviour, public UnityEngine::ICanvasRaycastFilter, public UnityEngine::UI::IMaterialModifier { public: // private UnityEngine.RectTransform m_RectTransform // Offset: 0x18 UnityEngine::RectTransform* m_RectTransform; // private System.Boolean m_ShowMaskGraphic // Offset: 0x20 bool m_ShowMaskGraphic; // private UnityEngine.UI.Graphic m_Graphic // Offset: 0x28 UnityEngine::UI::Graphic* m_Graphic; // private UnityEngine.Material m_MaskMaterial // Offset: 0x30 UnityEngine::Material* m_MaskMaterial; // private UnityEngine.Material m_UnmaskMaterial // Offset: 0x38 UnityEngine::Material* m_UnmaskMaterial; // public UnityEngine.RectTransform get_rectTransform() // Offset: 0x11EBDC0 UnityEngine::RectTransform* get_rectTransform(); // public System.Boolean get_showMaskGraphic() // Offset: 0x11EBE40 bool get_showMaskGraphic(); // public System.Void set_showMaskGraphic(System.Boolean value) // Offset: 0x11EBE48 void set_showMaskGraphic(bool value); // public UnityEngine.UI.Graphic get_graphic() // Offset: 0x11EBF20 UnityEngine::UI::Graphic* get_graphic(); // public System.Boolean MaskEnabled() // Offset: 0x11EBFB0 bool MaskEnabled(); // public System.Void OnSiblingGraphicEnabledDisabled() // Offset: 0x11EC050 void OnSiblingGraphicEnabledDisabled(); // protected System.Void .ctor() // Offset: 0x11EBFA0 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static Mask* New_ctor(); // protected override System.Void OnEnable() // Offset: 0x11EC054 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnEnable() void OnEnable(); // protected override System.Void OnDisable() // Offset: 0x11EC37C // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDisable() void OnDisable(); // public System.Boolean IsRaycastLocationValid(UnityEngine.Vector2 sp, UnityEngine.Camera eventCamera) // Offset: 0x11EC4E4 // Implemented from: UnityEngine.ICanvasRaycastFilter // Base method: System.Boolean ICanvasRaycastFilter::IsRaycastLocationValid(UnityEngine.Vector2 sp, UnityEngine.Camera eventCamera) bool IsRaycastLocationValid(UnityEngine::Vector2 sp, UnityEngine::Camera* eventCamera); // public UnityEngine.Material GetModifiedMaterial(UnityEngine.Material baseMaterial) // Offset: 0x11EC5AC // Implemented from: UnityEngine.UI.IMaterialModifier // Base method: UnityEngine.Material IMaterialModifier::GetModifiedMaterial(UnityEngine.Material baseMaterial) UnityEngine::Material* GetModifiedMaterial(UnityEngine::Material* baseMaterial); }; // UnityEngine.UI.Mask } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::Mask*, "UnityEngine.UI", "Mask"); #pragma pack(pop)
42.085714
147
0.732519
Futuremappermydud
4c08f1f1a28af24ed904991632ed5e0570289d4a
9,988
cpp
C++
IdClient/Platform/Windows/PWindows.cpp
skrishnasantosh/id-desktop-lite
1bc9c056ec7fa50e02cf360552e794e22f74e501
[ "MIT" ]
null
null
null
IdClient/Platform/Windows/PWindows.cpp
skrishnasantosh/id-desktop-lite
1bc9c056ec7fa50e02cf360552e794e22f74e501
[ "MIT" ]
null
null
null
IdClient/Platform/Windows/PWindows.cpp
skrishnasantosh/id-desktop-lite
1bc9c056ec7fa50e02cf360552e794e22f74e501
[ "MIT" ]
null
null
null
#ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #define WIN32_LEAN_AND_MEAN #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING #include <Windows.h> #include <Shlwapi.h> #include <wincrypt.h> #include <WinInet.h> #include <codecvt> #include <string> #include <vector> #pragma comment(lib, "Shlwapi.lib") #pragma comment(lib, "Crypt32.lib") #pragma comment(lib, "Wininet.lib") #include "../../Platform.h" using namespace Autodesk::Identity::Client::Internal; struct BLOB_DMY { BLOBHEADER header; DWORD len; BYTE key[0]; }; thread_local uint64_t m_platformErrorCode = 0; pstring Platform::UrlEncode(const pstring& url) { HRESULT apiResult = E_FAIL; wchar_t sizeTest[1] = { 0 }; DWORD destSize = 1; size_t urlLen = url.length(); m_platformErrorCode = 0; if (urlLen == 0 || urlLen > INTERNET_MAX_URL_LENGTH) return pstring(); wstring urlW = Strings.ToDefaultString<wstring>(url); apiResult = UrlEscape(urlW.c_str(), sizeTest, &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult) && apiResult != E_POINTER) //E_POINTER expected { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } if (destSize <= 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } wstring destW; destW.resize(destSize); apiResult = UrlEscape(urlW.c_str(), &(destW.data())[0], &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult)) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } destW.resize(destSize); pstring dest = Strings.FromDefaultString<wstring>(destW); return dest; } pstring Platform::UrlDecode(const pstring& url) { HRESULT apiResult = E_FAIL; wchar_t sizeTest[1] = { 0 }; DWORD destSize = 1; size_t urlLen = url.length(); m_platformErrorCode = 0; if (urlLen == 0 || urlLen > INTERNET_MAX_URL_LENGTH) return pstring(); wstring urlW = Strings.ToDefaultString<wstring>(url); apiResult = UrlUnescape(&(urlW.data())[0], sizeTest, &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult) && apiResult != E_POINTER) //E_POINTER expected { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } if (destSize <= 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } wstring destW; destW.resize(destSize); apiResult = UrlUnescape(&(urlW.data())[0], &(destW.data())[0], &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult)) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } destW.resize(destSize); pstring dest = Strings.FromDefaultString<wstring>(destW); return dest; } pstring Platform::Base64Encode(const vector<uint8_t>& data) { DWORD destSizeRecv = 0; BOOL result = FALSE; size_t dataLength = data.size(); if (dataLength > MAXDWORD || dataLength == 0) return pstring(); result = CryptBinaryToStringW((const BYTE*)&data[0], (DWORD)dataLength, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &destSizeRecv); if (!result || destSizeRecv == 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } wstring destW; destW.resize(destSizeRecv - 1); result = CryptBinaryToStringW((const BYTE*)&data[0], (DWORD)dataLength, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, &(destW.data())[0], &destSizeRecv); if (!result || destSizeRecv == 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } pstring dest = Strings.FromDefaultString<wstring>(destW); return dest; } vector<uint8_t> Platform::HmacSha1(const vector<uint8_t>& data, const vector<uint8_t>& key) { HCRYPTPROV hProv = NULL; HCRYPTHASH hHash = NULL; HCRYPTKEY hKey = NULL; HCRYPTHASH hHmacHash = NULL; DWORD dwDataLen = 0; HMAC_INFO hMacInfo = { 0 }; BOOL result = FALSE; vector<uint8_t> hashValue; const int hashSize = 20; m_platformErrorCode = 0; hMacInfo.HashAlgid = CALG_SHA1; result = CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET); if (!result) m_platformErrorCode = GetLastError(); struct BLOB_DMY* blob = NULL; size_t keyLen = key.size(); size_t dataLen = data.size(); if (keyLen > MAXDWORD || dataLen > MAXDWORD) return vector<uint8_t>(); DWORD blobSize = sizeof(struct BLOB_DMY) + key.size() + 1; blob = (struct BLOB_DMY*)malloc(blobSize); if (blob == NULL) return vector<uint8_t>(); memset(blob, 0, blobSize); blob->header.bType = PLAINTEXTKEYBLOB; blob->header.aiKeyAlg = CALG_RC2; blob->header.reserved = 0; blob->header.bVersion = CUR_BLOB_VERSION; blob->len = (DWORD)keyLen; memcpy(&(blob->key), &(key[0]), keyLen + 1); //Copy zero at end result = CryptImportKey(hProv, (BYTE*)blob, blobSize, 0, CRYPT_IPSEC_HMAC_KEY, &hKey); if (!result) m_platformErrorCode = GetLastError(); else result = CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHmacHash); if (!result) m_platformErrorCode = GetLastError(); else result = CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE*)&hMacInfo, 0); if (!result) m_platformErrorCode = GetLastError(); else result = CryptHashData(hHmacHash, (BYTE*)&data[0], dataLen, 0); if (!result) m_platformErrorCode = GetLastError(); else { hashValue.resize(hashSize, 0); dwDataLen = hashSize; result = CryptGetHashParam(hHmacHash, HP_HASHVAL, (BYTE*) & (hashValue[0]), &dwDataLen, 0); if (!result) m_platformErrorCode = GetLastError(); } if (hHmacHash) CryptDestroyHash(hHmacHash); if (hKey) CryptDestroyKey(hKey); if (hHash) CryptDestroyHash(hHash); if (hProv) CryptReleaseContext(hProv, 0); return hashValue; //PlatformErrorCode set to 0 and return NULL if out of memory } HttpResponse Platform::HttpGet(const pstring& url, const map<pstring, pstring>& queries, const map<pstring, pstring>& headers) { pstring content = u""; HttpResponse response; HINTERNET hSession, hConnection, hRequest; response.m_httpStatusCode = 0; wstring agentName = GetHttpAgentName<wstring>(); Internal::Url urlParts; if (!TryParseUrl(url, urlParts)) return response; hSession = ::InternetOpen(agentName.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession == NULL) { m_platformErrorCode = ::GetLastError(); return response; } wstring wideUrl = Strings.ToDefaultString<wstring>(urlParts.m_host); wstring widePath = Strings.ToDefaultString<wstring>(urlParts.m_path); INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; DWORD flags = 0; if (urlParts.m_protocol.back() == u'S' || urlParts.m_protocol.back() == u's') { port = INTERNET_DEFAULT_HTTPS_PORT; flags = INTERNET_FLAG_SECURE | INTERNET_FLAG_NO_UI; } else { port = INTERNET_DEFAULT_HTTP_PORT; flags = INTERNET_FLAG_NO_UI; } hConnection = ::InternetConnect(hSession, wideUrl.c_str(), port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL); if (hConnection) { const wchar_t* acceptTypes[] = { L"*/*", NULL }; hRequest = ::HttpOpenRequest(hConnection, L"GET", widePath.c_str(), L"HTTP/1.1", NULL, acceptTypes, flags, 0); if (hRequest) { /*if (::HttpSendRequest(hRequest, ) { canContinue = HttpEndRequest(hRequest, NULL, 0, 0); }*/ } else m_platformErrorCode = ::GetLastError(); ::InternetCloseHandle(hConnection); } else m_platformErrorCode = ::GetLastError(); ::InternetCloseHandle(hSession); return response; } HttpResponse Platform::HttpPost(const pstring& url, const map<pstring, pstring>& queries, const map<pstring, pstring>& headers) { pstring content = u""; return { 0, content }; } bool Platform::TryParseUrl(const pstring& fullUrl, Url& url) { bool ret = false; URL_COMPONENTS urlComponents = { 0 }; wstring wstr = Strings.ToDefaultString<wstring>(fullUrl); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.dwSchemeLength = DWORD(-1); urlComponents.dwHostNameLength = DWORD(-1); urlComponents.dwUserNameLength = DWORD(-1); urlComponents.dwPasswordLength = DWORD(-1); urlComponents.dwUrlPathLength = DWORD(-1); urlComponents.dwExtraInfoLength = DWORD(-1); urlComponents.nPort = 0; ret = ::InternetCrackUrl(wstr.c_str(), wstr.length(), 0, &urlComponents); if (ret) { if (urlComponents.dwSchemeLength > 0 && urlComponents.lpszScheme != NULL) { wstring wstr(urlComponents.lpszScheme, urlComponents.dwSchemeLength); url.m_protocol = Strings.FromDefaultString(wstr); } if (urlComponents.dwHostNameLength > 0 && urlComponents.lpszHostName != NULL) { wstring wstr(urlComponents.lpszHostName, urlComponents.dwHostNameLength); url.m_host = Strings.FromDefaultString(wstr); } if (urlComponents.dwUrlPathLength > 1 && urlComponents.lpszUrlPath != NULL) { wstring wstr(urlComponents.lpszUrlPath, 1, urlComponents.dwUrlPathLength - 1); url.m_path = Strings.FromDefaultString(wstr); } if (urlComponents.dwExtraInfoLength > 0 && urlComponents.lpszExtraInfo != NULL) { wstring query(urlComponents.lpszExtraInfo, urlComponents.dwExtraInfoLength + 1); //Skip the '?' unsigned int port = urlComponents.nPort; size_t fragmentPos = query.find_last_of(L'#'); if (fragmentPos != wstring::npos) { url.m_queryString = Strings.FromDefaultString(query.substr(1, fragmentPos - 1)); if (fragmentPos + 1 < query.length()) url.m_fragment = Strings.FromDefaultString(query.substr(fragmentPos + 1, query.length() - 1 - (fragmentPos + 1))); } else url.m_queryString = Strings.FromDefaultString(query); } url.m_port = urlComponents.nPort; } return ret; } #define AGENT_FORMAT_STRING L"AdDesktopClient[version(1.0),platform(win64),os(#),defaultCharSize(2)]"; template<class TString> TString Platform::GetHttpAgentName() { wstring agentName = AGENT_FORMAT_STRING; //TODO: Fill the OS Version before sending this return agentName; } #endif //_WIN32
25.414758
154
0.721165
skrishnasantosh
4c098427f2899cb8e91f687a7475d165dbc55687
152
cpp
C++
service/src/exo/hexcode.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
4
2021-01-23T14:36:34.000Z
2021-06-07T10:02:28.000Z
service/src/exo/hexcode.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2019-08-04T19:15:56.000Z
2019-08-04T19:15:56.000Z
service/src/exo/hexcode.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2022-01-29T22:41:01.000Z
2022-01-29T22:41:01.000Z
#include <exodus/library.h> libraryinit() function main(in /*mode*/, io /*text*/) { //called from listen but only in DOS return 0; } libraryexit()
13.818182
41
0.671053
BOBBYWY
4c0d770609dfe91d96ff21ce4991fa78831cad15
4,455
cpp
C++
src/game/client/tf/c_entity_bird.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/client/tf/c_entity_bird.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/client/tf/c_entity_bird.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Dove entity for the Meet the Medic tease. // //=============================================================================// #include "cbase.h" #include "tf_gamerules.h" #include "c_baseanimating.h" #define ENTITY_FLYING_BIRD_MODEL "models/props_forest/dove.mdl" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class C_EntityFlyingBird : public CBaseAnimating { DECLARE_CLASS( C_EntityFlyingBird, CBaseAnimating ); public: void InitFromServerData( float flyAngle, float flyAngleRate, float flAccelZ, float flSpeed, float flGlideTime ); virtual void Touch( CBaseEntity *pOther ); private: virtual void ClientThink( void ); void UpdateFlyDirection( void ); private: Vector m_flyForward; float m_flyAngle; float m_flyAngleRate; float m_flyZ; float m_accelZ; float m_speed; float m_timestamp; CountdownTimer m_lifetimeTimer; CountdownTimer m_glideTimer; }; //----------------------------------------------------------------------------- // Purpose: Server message that tells us to create a dove //----------------------------------------------------------------------------- void __MsgFunc_SpawnFlyingBird( bf_read &msg ) { Vector vecPos; msg.ReadBitVec3Coord( vecPos ); float flyAngle = msg.ReadFloat(); float flyAngleRate = msg.ReadFloat(); float flAccelZ = msg.ReadFloat(); float flSpeed = msg.ReadFloat(); float flGlideTime = msg.ReadFloat(); C_EntityFlyingBird *pBird = new C_EntityFlyingBird(); if ( !pBird ) return; pBird->SetAbsOrigin( vecPos ); pBird->InitFromServerData( flyAngle, flyAngleRate, flAccelZ, flSpeed, flGlideTime ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_EntityFlyingBird::UpdateFlyDirection( void ) { Vector forward; forward.x = cos( m_flyAngle ); forward.y = sin( m_flyAngle ); forward.z = m_flyZ; forward.NormalizeInPlace(); SetAbsVelocity( forward * m_speed ); QAngle angles; VectorAngles( forward, angles ); SetAbsAngles( angles ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_EntityFlyingBird::InitFromServerData( float flyAngle, float flyAngleRate, float flAccelZ, float flSpeed, float flGlideTime ) { if ( InitializeAsClientEntity( ENTITY_FLYING_BIRD_MODEL, RENDER_GROUP_OPAQUE_ENTITY ) == false ) { Release(); return; } SetMoveType( MOVETYPE_FLY ); SetSolid( SOLID_BBOX ); SetCollisionGroup( COLLISION_GROUP_DEBRIS ); SetSize( -Vector(8,8,0), Vector(8,8,16) ); m_flyAngle = flyAngle; m_flyAngleRate = flyAngleRate; m_accelZ = flAccelZ; m_flyZ = 0.0; m_speed = flSpeed; UpdateFlyDirection(); SetSequence( 0 ); SetPlaybackRate( 1.0f ); SetCycle( 0 ); ResetSequenceInfo(); // make sure the bird is removed m_lifetimeTimer.Start( 10.0f ); m_glideTimer.Start( flGlideTime ); SetNextClientThink( CLIENT_THINK_ALWAYS ); m_timestamp = gpGlobals->curtime; SetModelScale( 0.1f ); SetModelScale( 1.0f, 0.5f ); } //----------------------------------------------------------------------------- // Purpose: Fly away! //----------------------------------------------------------------------------- void C_EntityFlyingBird::ClientThink( void ) { if ( m_lifetimeTimer.IsElapsed() ) { Release(); return; } if ( m_glideTimer.HasStarted() && m_glideTimer.IsElapsed() ) { SetSequence( 1 ); SetPlaybackRate( 1.0f ); SetCycle( 0 ); ResetSequenceInfo(); m_glideTimer.Invalidate(); } StudioFrameAdvance(); PhysicsSimulate(); const float deltaT = gpGlobals->curtime - m_timestamp; m_flyAngle += m_flyAngleRate * deltaT; m_flyZ += m_accelZ * deltaT; UpdateFlyDirection(); m_timestamp = gpGlobals->curtime; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_EntityFlyingBird::Touch( CBaseEntity *pOther ) { if ( !pOther || !pOther->IsWorld() ) return; BaseClass::Touch( pOther ); // Die at next think. Not safe to remove ourselves during physics touch. m_lifetimeTimer.Invalidate(); }
26.052632
131
0.557351
cstom4994
4c110491426056fb34ad624b6aeb08532da44def
2,239
cpp
C++
src/Entry.cpp
teaglu/timeoutd
855d93cc291c1744abcb1fd901beb639b1ed51ce
[ "Apache-2.0" ]
null
null
null
src/Entry.cpp
teaglu/timeoutd
855d93cc291c1744abcb1fd901beb639b1ed51ce
[ "Apache-2.0" ]
null
null
null
src/Entry.cpp
teaglu/timeoutd
855d93cc291c1744abcb1fd901beb639b1ed51ce
[ "Apache-2.0" ]
null
null
null
#include "system.h" #include "Entry.h" #include "Log.h" std::string Entry::notifyScript= SCRIPTDIR "/timeoutd-notify"; Entry::Entry(char const *key, struct timeval & expires, char const *address) { this->key= key; this->expires= expires; this->lastAddress= address; } Entry::~Entry() { } void Entry::notify() { Log::log(LOG_INFO, "Timeout for %s (%s)", key.c_str(), lastAddress.c_str()); char const *childArgv[4]; childArgv[0]= notifyScript.c_str(); childArgv[1]= key.c_str(); childArgv[2]= lastAddress.c_str(); childArgv[3]= NULL; pid_t childPid= fork(); if (childPid == -1) { Log::log(LOG_ERROR, "Failed to fork for notification: %s", strerror(errno)); } else if (childPid == 0) { // This is the child execv(childArgv[0], (char **)childArgv); Log::log(LOG_ERROR, "Failed to launch notify script %s: %s", childArgv[0], strerror(errno)); _exit(99); } else { for (bool wait= true; wait; ) { wait=false; int status; pid_t waitRval= waitpid(childPid, &status, 0); if (waitRval == -1) { if (errno == EINTR) { wait= true; } else { Log::log(LOG_ERROR, "Error waiting for notification script: %s", strerror(errno)); } } else if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { Log::log(LOG_WARNING, "Notification script exited with status %d", WEXITSTATUS(status)); } } else if (WIFSIGNALED(status)) { Log::log(LOG_WARNING, "Notification script exited on signal %d", WTERMSIG(status)); } } } } bool Entry::CompareTimeout( const std::shared_ptr<Entry> a, const std::shared_ptr<Entry> b) { struct timeval *aExpires= a->getExpires(); struct timeval *bExpires= b->getExpires(); if (aExpires->tv_sec < bExpires->tv_sec) { return true; } else if (aExpires->tv_sec > bExpires->tv_sec) { return false; } else { if (aExpires->tv_usec < bExpires->tv_usec) { return true; } else if (aExpires->tv_usec > bExpires->tv_usec) { return false; } else { // Because we're using a multiset instead of a // priority queue, we have to make sure that // our key is absolutely unique or we could // remove the wrong item. return (strcmp(a->getKey(), b->getKey()) < 0); } } }
22.39
76
0.634658
teaglu
4c16165059184f7eb584fa5775deed9b746cd94e
900
hpp
C++
Solution/Crosshair/Source/Crosshair.hpp
c-m-w/Crosshair-Overlay
8fbefbbf9fed35a08b2a0a6a65fd816c97e05355
[ "MIT" ]
6
2019-01-27T20:42:43.000Z
2021-06-09T07:36:15.000Z
Solution/Crosshair/Source/Crosshair.hpp
c-m-w/Crosshair-Overlay
8fbefbbf9fed35a08b2a0a6a65fd816c97e05355
[ "MIT" ]
null
null
null
Solution/Crosshair/Source/Crosshair.hpp
c-m-w/Crosshair-Overlay
8fbefbbf9fed35a08b2a0a6a65fd816c97e05355
[ "MIT" ]
1
2020-01-14T08:25:35.000Z
2020-01-14T08:25:35.000Z
/// Crosshair.hpp #pragma once #if not defined UNICODE or defined _MBCS #error Unicode must be used for this project. #endif #if not defined WIN32 #error This project must be built in 32 bit mode. #endif #define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <cstdio> #include <cassert> #include <string> #include <fstream> #include <sstream> #include <ctime> #include <chrono> #include <iostream> #include <thread> #include <filesystem> #include <d3d9.h> #include <d3dx9core.h> #pragma comment( lib, "d3d9.lib" ) #pragma comment( lib, "d3dx9.lib" ) #undef DeleteFile // theres a winapi function to delete files but filesystem has a function called deletefile inline BOOL bShutdown = FALSE; inline HINSTANCE hCurrentInstance = nullptr; #include "Utilities.hpp" #include "FileSystem.hpp" #include "Configuration.hpp" #include "Window.hpp" #include "Logging.hpp" #include "Drawing.hpp"
20.930233
109
0.753333
c-m-w
4c1b3ec1782a85f5a76811c000e4bcc0992dc1c9
2,225
cpp
C++
D2hackIt/toolhelp.cpp
inrg/D2HackIt-backup
2f1e81f5ea29168ef780c8a957b02611954db3af
[ "Unlicense" ]
24
2016-10-09T08:53:35.000Z
2022-02-07T11:34:37.000Z
D2hackIt/toolhelp.cpp
bethington/D2HackIt
2f1e81f5ea29168ef780c8a957b02611954db3af
[ "Unlicense" ]
null
null
null
D2hackIt/toolhelp.cpp
bethington/D2HackIt
2f1e81f5ea29168ef780c8a957b02611954db3af
[ "Unlicense" ]
33
2016-08-30T08:35:22.000Z
2022-02-07T11:34:40.000Z
////////////////////////////////////////////////////////////////////// // toolhelp.cpp // ------------------------------------------------------------------- // // <[email protected]> ////////////////////////////////////////////////////////////////////// #define THIS_IS_SERVER #include "..\D2HackIt.h" ////////////////////////////////////////////////////////////////////// // GetImageSize_toolhelp // ------------------------------------------------------------------- // Used to get the image size of a dll/exe. ////////////////////////////////////////////////////////////////////// DWORD PRIVATE GetImageSize_toolhelp(LPSTR ModuleName) { MODULEENTRY32 lpme; if (FindImage_toolhelp(ModuleName, &lpme)) return lpme.modBaseSize; else return 0; } ////////////////////////////////////////////////////////////////////// // GetBaseAddress_toolhelp // ------------------------------------------------------------------- // Used to get the base address of a dll/exe. ////////////////////////////////////////////////////////////////////// DWORD PRIVATE GetBaseAddress_toolhelp(LPSTR ModuleName) { MODULEENTRY32 lpme; if (FindImage_toolhelp(ModuleName, &lpme)) return (DWORD)lpme.modBaseAddr; else return 0; } ////////////////////////////////////////////////////////////////////// // FindImage_toolhelp // ------------------------------------------------------------------- // Loop through loaded images to get the MODULEINFO32 you need. ////////////////////////////////////////////////////////////////////// BOOL PRIVATE FindImage_toolhelp(LPSTR ModuleName, MODULEENTRY32* lpme) { // Get a snapshot HANDLE hSnapshot = pfep->toolhelp.CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, psi->pid); if ((int)hSnapshot == -1) return FALSE; lpme->dwSize=sizeof(MODULEENTRY32); // Get first module, this is needed for win9x/ME if (!pfep->toolhelp.Module32First(hSnapshot, lpme)) { CloseHandle(hSnapshot); return FALSE; }; // Loop through all other modules while (TRUE) { if (!strcmpi(lpme->szModule, ModuleName)) { CloseHandle(hSnapshot); return TRUE; } if (!pfep->toolhelp.Module32Next(hSnapshot, lpme)) { CloseHandle(hSnapshot); return FALSE; }; } }
35.887097
96
0.439551
inrg
4c1fc073a965e88346a3f3f17d6326318d51cc3d
1,056
cpp
C++
set_power_series/test/subset_log.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
20
2021-06-21T00:18:54.000Z
2022-03-17T17:45:44.000Z
set_power_series/test/subset_log.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
56
2021-06-03T14:42:13.000Z
2022-03-26T14:15:30.000Z
set_power_series/test/subset_log.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
3
2019-12-11T06:45:45.000Z
2020-09-07T13:45:32.000Z
#define PROBLEM "https://atcoder.jp/contests/arc105/tasks/arc105_f" #include "../../modint.hpp" #include "../subset_convolution.hpp" #include <iostream> using namespace std; using mint = ModInt<998244353>; // https://codeforces.com/blog/entry/83535?#comment-709269 int main() { int N, M; cin >> N >> M; vector<int> to(N); while (M--) { int a, b; cin >> a >> b; a--, b--; to[a] += 1 << b, to[b] += 1 << a; } const mint inv2 = mint(2).inv(); vector<mint> pow2(N * N + 1, 1), pow2inv(N * N + 1, 1); for (int i = 1; i <= N * N; i++) pow2[i] = pow2[i - 1] * 2, pow2inv[i] = pow2inv[i - 1] * inv2; vector<int> nbe(1 << N); vector<mint> f(1 << N); for (int s = 0; s < 1 << N; s++) { for (int i = 0; i < N; i++) nbe[s] += __builtin_popcount(to[i] & s) * ((s >> i) & 1); nbe[s] /= 2; f[s] = pow2inv[nbe[s]]; } f = subset_convolution(f, f); for (int s = 0; s < 1 << N; s++) f[s] *= pow2[nbe[s]]; subset_log(f); cout << f.back() / 2 << '\n'; }
29.333333
99
0.485795
ankit6776
4c220997bc1e1284fabf6b2232df796f81e904cb
2,880
cpp
C++
test/parsed.cpp
olanmatt/orq
0e85e547cdc78cfd37681b8addfa0f4507e9516a
[ "MIT" ]
35
2015-01-07T05:06:50.000Z
2022-01-15T13:59:35.000Z
test/parsed.cpp
olanmatt/orq
0e85e547cdc78cfd37681b8addfa0f4507e9516a
[ "MIT" ]
null
null
null
test/parsed.cpp
olanmatt/orq
0e85e547cdc78cfd37681b8addfa0f4507e9516a
[ "MIT" ]
11
2015-01-27T09:29:22.000Z
2021-10-21T10:47:11.000Z
/* * The MIT License (MIT) * * Copyright (c) 2014 Matt Olan, Prajjwal Bhandari * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <parsed.h> #include <catch.h> #include <vector> #include <string> TEST_CASE("Parsed::of returns a 'valid' Parsed Object", "[Parsed]") { std::vector<int> test {1, 2, 3}; Parsed< std::vector<int> > &p = Parsed< std::vector<int> >::of(test); SECTION("It should be valid,") { REQUIRE(p.is_valid()); } SECTION("value() should return a copy of the object passed in.") { REQUIRE(p.value() == test); SECTION("The object that was passed in should be deep copied.") { std::vector<int> backup = test; test.push_back(4); REQUIRE(p.value() == backup); } } SECTION("failure_reason() should be empty.") { REQUIRE(p.failure_reason() == ""); } } TEST_CASE("Parsed::invalid returns an 'invalid' Parsed Object", "[Parsed]") { std::string reason = "reasons"; Parsed<int> &p = Parsed<int>::invalid(reason); SECTION("It should not be valid,") { REQUIRE_FALSE(p.is_valid()); } SECTION("value() should throw an exception") { REQUIRE_THROWS_AS(p.value(), std::string); SECTION("exception message should be the same as it's failure reason") { try { p.value(); } catch (std::string exception) { REQUIRE(p.failure_reason() == exception); } } } SECTION("failure_reason() returns a copy of the string passed in.") { REQUIRE(p.failure_reason() == reason); SECTION("The object that was passed in should be deep copied.") { std::string backup_reason = reason; reason += "foo"; REQUIRE(p.failure_reason() == backup_reason); } } }
33.103448
81
0.642014
olanmatt
4c24d15d97e70ebf71d7ae7fa2c94192251dcc5d
1,925
hh
C++
src/Utilities/nodeBoundingBoxes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Utilities/nodeBoundingBoxes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Utilities/nodeBoundingBoxes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // nodeBoundingBoxes // // Compute minimum volume bounding boxes for nodes and their extent. // // Created by JMO, Sun Jan 24 16:13:16 PST 2010 //----------------------------------------------------------------------------// #ifndef __Spheral_nodeBoundingBox__ #define __Spheral_nodeBoundingBox__ #include <utility> namespace Spheral { // Forward declarations. template<typename Dimension> class NodeList; template<typename Dimension, typename Value> class Field; template<typename Dimension, typename Value> class FieldList; template<typename Dimension> class DataBase; //------------------------------------------------------------------------------ // The bounding box for a position and H. //------------------------------------------------------------------------------ template<typename Dimension> std::pair<typename Dimension::Vector, typename Dimension::Vector> boundingBox(const typename Dimension::Vector& xi, const typename Dimension::SymTensor& Hi, const typename Dimension::Scalar& kernelExtent); //------------------------------------------------------------------------------ // The bounding boxes for a NodeList. //------------------------------------------------------------------------------ template<typename Dimension> Field<Dimension, std::pair<typename Dimension::Vector, typename Dimension::Vector> > nodeBoundingBoxes(const NodeList<Dimension>& nodes); //------------------------------------------------------------------------------ // The bounding boxes for all nodes in a DataBase. //------------------------------------------------------------------------------ template<typename Dimension> FieldList<Dimension, std::pair<typename Dimension::Vector, typename Dimension::Vector> > nodeBoundingBoxes(const DataBase<Dimension>& dataBase); } #include "nodeBoundingBoxesInline.hh" #endif
39.285714
88
0.523117
jmikeowen
4c2bc806ac09ad7825ab0d94b335e4437584cf16
330
hpp
C++
Delauney/Sorting.hpp
tod91/Delauney
946419312e3e2d789c2203a40de4084c4d1bbe5f
[ "MIT" ]
2
2020-03-03T17:05:54.000Z
2020-05-11T14:15:55.000Z
Delauney/Sorting.hpp
tod91/Delauney
946419312e3e2d789c2203a40de4084c4d1bbe5f
[ "MIT" ]
null
null
null
Delauney/Sorting.hpp
tod91/Delauney
946419312e3e2d789c2203a40de4084c4d1bbe5f
[ "MIT" ]
null
null
null
// // Sorting.hpp // PojectDelone // // Created by Todor Ivanov on 5/25/17. // Copyright © 2017 Todor Ivanov. All rights reserved. // #ifndef Sorting_hpp #define Sorting_hpp struct Vertex3D; // sorts points by their x coord bool BottomUpMergeSort(Vertex3D* points, const unsigned numOfPoints); #endif /* Sorting_hpp */
16.5
70
0.718182
tod91
4c2ec4e004efcb973644ef859f80a39e89310592
4,261
ipp
C++
xs/src/boost/test/utils/runtime/cla/named_parameter.ipp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
xs/src/boost/test/utils/runtime/cla/named_parameter.ipp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
197
2017-07-06T16:53:59.000Z
2019-05-31T17:57:51.000Z
xs/src/boost/test/utils/runtime/cla/named_parameter.ipp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
// (C) Copyright Gennadiy Rozental 2005-2008. // Use, modification, and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 54633 $ // // Description : implements model of named parameter // *************************************************************************** #ifndef BOOST_RT_CLA_NAMED_PARAMETER_IPP_062904GER #define BOOST_RT_CLA_NAMED_PARAMETER_IPP_062904GER // Boost.Runtime.Parameter #include <boost/test/utils/runtime/config.hpp> #include <boost/test/utils/runtime/cla/named_parameter.hpp> #include <boost/test/utils/runtime/cla/char_parameter.hpp> // Boost.Test #include <boost/test/utils/algorithm.hpp> namespace boost { namespace BOOST_RT_PARAM_NAMESPACE { namespace cla { // ************************************************************************** // // ************** string_name_policy ************** // // ************************************************************************** // BOOST_RT_PARAM_INLINE string_name_policy::string_name_policy() : basic_naming_policy( rtti::type_id<string_name_policy>() ) , m_guess_name( false ) { assign_op( p_prefix.value, BOOST_RT_PARAM_CSTRING_LITERAL( "-" ), 0 ); } //____________________________________________________________________________// BOOST_RT_PARAM_INLINE bool string_name_policy::responds_to( cstring name ) const { std::pair<cstring::iterator,dstring::const_iterator> mm_pos; mm_pos = unit_test::mismatch( name.begin(), name.end(), p_name->begin(), p_name->end() ); return mm_pos.first == name.end() && (m_guess_name || (mm_pos.second == p_name->end()) ); } //____________________________________________________________________________// #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable:4244) #endif BOOST_RT_PARAM_INLINE bool string_name_policy::conflict_with( identification_policy const& id ) const { if( id.p_type_id == p_type_id ) { string_name_policy const& snp = static_cast<string_name_policy const&>( id ); if( p_name->empty() || snp.p_name->empty() ) return false; if( p_prefix != snp.p_prefix ) return false; std::pair<dstring::const_iterator,dstring::const_iterator> mm_pos = unit_test::mismatch( p_name->begin(), p_name->end(), snp.p_name->begin(), snp.p_name->end() ); return mm_pos.first != p_name->begin() && // there is common substring ((m_guess_name && (mm_pos.second == snp.p_name->end()) ) || // that match other guy and I am guessing (snp.m_guess_name && (mm_pos.first == p_name->end()) )); // or me and the other guy is } if( id.p_type_id == rtti::type_id<char_name_policy>() ) { char_name_policy const& cnp = static_cast<char_name_policy const&>( id ); return m_guess_name && (p_prefix == cnp.p_prefix) && unit_test::first_char( cstring( p_name ) ) == unit_test::first_char( cstring( cnp.p_name ) ); } return false; } #ifdef BOOST_MSVC # pragma warning(pop) #endif //____________________________________________________________________________// BOOST_RT_PARAM_INLINE bool string_name_policy::match_name( argv_traverser& tr ) const { if( !m_guess_name ) return basic_naming_policy::match_name( tr ); cstring in = tr.input(); std::pair<cstring::iterator,dstring::const_iterator> mm_pos; mm_pos = unit_test::mismatch( in.begin(), in.end(), p_name->begin(), p_name->end() ); if( mm_pos.first == in.begin() ) return false; tr.trim( mm_pos.first - in.begin() ); return true; } //____________________________________________________________________________// } // namespace cla } // namespace BOOST_RT_PARAM_NAMESPACE } // namespace boost #endif // BOOST_RT_CLA_NAMED_PARAMETER_IPP_062904GER
32.776923
122
0.619808
born2b
4c33abdbf9b3217e0cec1aa5d43de2bec595a6a8
2,010
cpp
C++
src/plugins/anim/nodes/frame/edit.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
232
2017-10-09T11:45:28.000Z
2022-03-28T11:14:46.000Z
src/plugins/anim/nodes/frame/edit.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
26
2019-01-20T21:38:25.000Z
2021-10-16T03:57:17.000Z
src/plugins/anim/nodes/frame/edit.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
33
2017-10-26T19:20:38.000Z
2022-03-16T11:21:43.000Z
#include <OpenEXR/ImathEuler.h> #include <OpenEXR/ImathMatrix.h> #include <OpenEXR/ImathVec.h> #include <possumwood_sdk/node_implementation.h> #include "datatypes/animation.h" #include "datatypes/frame_editor_data.h" #include "maths/io/vec3.h" namespace { dependency_graph::InAttr<anim::Skeleton> a_inFrame; dependency_graph::InAttr<Imath::Vec3<float>> a_translate; dependency_graph::InAttr<float> a_scale; dependency_graph::InAttr<anim::FrameEditorData> a_editorData; dependency_graph::OutAttr<anim::Skeleton> a_outFrame; dependency_graph::State compute(dependency_graph::Values& data) { // update a_editorData, if needed if(data.get(a_editorData).skeleton() != data.get(a_inFrame)) { anim::FrameEditorData editorData = data.get(a_editorData); editorData.setSkeleton(data.get(a_inFrame)); data.set(a_editorData, editorData); } // do the computation itself anim::Skeleton frame = data.get(a_inFrame); const Imath::Vec3<float>& tr = data.get(a_translate); const float sc = data.get(a_scale); if(frame.size() > 0) { for(auto& b : frame) b.tr().translation *= sc; frame[0].tr().translation += tr; for(auto& i : data.get(a_editorData)) if(i.first < frame.size()) frame[i.first].tr() = frame[i.first].tr() * i.second; } data.set(a_outFrame, frame); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inFrame, "in_frame", anim::Skeleton(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_translate, "translate", Imath::Vec3<float>(0, 0, 0)); meta.addAttribute(a_scale, "scale", 1.0f); meta.addAttribute(a_editorData, "rotations"); meta.addAttribute(a_outFrame, "out_frame", anim::Skeleton(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_inFrame, a_outFrame); meta.addInfluence(a_editorData, a_outFrame); meta.addInfluence(a_translate, a_outFrame); meta.addInfluence(a_scale, a_outFrame); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("anim/frame/edit", init); } // namespace
30.923077
96
0.743781
martin-pr
4c353b39db60349f67cc8f036962b5dda0d59d63
296
hpp
C++
UnitTests/GXLayerUnitTest.hpp
manu88/GX
1eaeb0361db4edfb9c0764b4c47817ed77d4159c
[ "Apache-2.0" ]
2
2017-07-12T02:25:23.000Z
2017-08-30T23:46:32.000Z
UnitTests/GXLayerUnitTest.hpp
manu88/GX
1eaeb0361db4edfb9c0764b4c47817ed77d4159c
[ "Apache-2.0" ]
null
null
null
UnitTests/GXLayerUnitTest.hpp
manu88/GX
1eaeb0361db4edfb9c0764b4c47817ed77d4159c
[ "Apache-2.0" ]
null
null
null
// // GXLayerUnitTest.hpp // GX // // Created by Manuel Deneu on 22/06/2017. // Copyright © 2017 Unlimited Development. All rights reserved. // #ifndef GXLayerUnitTest_hpp #define GXLayerUnitTest_hpp class GXLayerUnitTest { public: bool run(); }; #endif /* GXLayerUnitTest_hpp */
14.8
64
0.699324
manu88
4c36b0fc84fa3d97c04c8876df4c6efeeca7d707
778
hpp
C++
src/include/test.hpp
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
src/include/test.hpp
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
src/include/test.hpp
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
#pragma once #include "matcher.hpp" #include "number.hpp" #include "util.hpp" class Test { public: Test() { } void all(); void semantics(); void memory(); void knownPrograms(); void ackermann(); void collatz(); void optimizer(); void minimizer( size_t tests ); void linearMatcher(); void deltaMatcher(); void polynomialMatcher( size_t tests, size_t degree ); void stats(); void config(); private: void testSeq( size_t id, const Sequence &values ); void testBinary( const std::string &func, const std::string &file, const std::vector<std::vector<number_t> > &values ); void testMatcherSet( Matcher &matcher, const std::vector<size_t> &ids ); void testMatcherPair( Matcher &matcher, size_t id1, size_t id2 ); };
14.679245
74
0.66581
jmorken
4c392489a357dfbf7e556482c2d7587cff3b2500
1,234
cpp
C++
LeetCode/Two Sum.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
LeetCode/Two Sum.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
LeetCode/Two Sum.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include<queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <fstream> using namespace std; typedef pair<int,int> scpair; class Solution { public: int n; vector <scpair> a; vector<int> twoSum(vector<int> &numbers, int target) { n=numbers.size(); a.resize(n); for (int i=0;i<n;i++){ a[i]=scpair(numbers[i],i+1); } sort(a.begin(),a.end()); vector <int> res; for (int i=0;i<n-1;i++){ int left=target-a[i].first; int p=lower_bound(a.begin()+i+1,a.end(),scpair(left,0))-a.begin(); if (p<n){ if (a[p].first!=left){continue;} res.push_back(a[i].second); res.push_back(a[p].second); sort(res.begin(),res.end()); return res; } } return res; } }; int main (){ Solution *sol=new Solution; int a[]={150,24,79,50,88,345,3}; int t=200; vector<int> ret=sol->twoSum(vector<int>(a,a+sizeof(a)/sizeof(a[0])),t); for (int i=0;i<ret.size();i++){ cout<<ret[i]<<" "; } return 0; }
20.566667
72
0.63128
zombiecry