hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
e607a277d584751297f091ceba54a55e2f02909d
33,624
cpp
C++
lib/game_save_gen2impl.cpp
ncorgan/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
4
2017-06-10T13:21:44.000Z
2019-10-30T21:20:19.000Z
lib/game_save_gen2impl.cpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
12
2017-04-05T11:13:34.000Z
2018-06-03T14:31:03.000Z
lib/game_save_gen2impl.cpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
2
2019-01-22T21:02:31.000Z
2019-10-30T21:20:20.000Z
/* * Copyright (c) 2016-2018 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "exception_internal.hpp" #include "game_save_gen2impl.hpp" #include "item_bag_gen2impl.hpp" #include "item_list_gbimpl.hpp" #include "pokedex_gbimpl.hpp" #include "pokemon_party_gbimpl.hpp" #include "pokemon_pc_gen2impl.hpp" #include "pksav/enum_maps.hpp" #include "pksav/pksav_call.hpp" #include <pkmn/exception.hpp> #include <pksav/gen2/palette.h> #include <pksav/math/endian.h> #include <boost/algorithm/string.hpp> #include <boost/assert.hpp> #include <boost/assign.hpp> #include <boost/bimap.hpp> #include <boost/filesystem.hpp> #include <boost/thread/lock_guard.hpp> #include <stdexcept> namespace fs = boost::filesystem; namespace pkmn { BOOST_STATIC_CONSTEXPR int GOLD_GAME_ID = 4; BOOST_STATIC_CONSTEXPR int SILVER_GAME_ID = 5; BOOST_STATIC_CONSTEXPR int CRYSTAL_GAME_ID = 6; BOOST_STATIC_CONSTEXPR int GS_PC_ID = 9; BOOST_STATIC_CONSTEXPR int CRYSTAL_PC_ID = 14; game_save_gen2impl::game_save_gen2impl( const std::string& filepath, std::vector<uint8_t>&& raw ): game_save_impl(filepath, std::move(raw)) { PKSAV_CALL( pksav_gen2_load_save_from_buffer( _raw.data(), _raw.size(), &_pksav_save ); ) if(_pksav_save.save_type == PKSAV_GEN2_SAVE_TYPE_CRYSTAL) { _game_id = CRYSTAL_GAME_ID; BOOST_ASSERT(_pksav_save.item_storage.p_item_pc != nullptr); _item_pc = std::make_shared<item_list_gen2_pcimpl>( CRYSTAL_PC_ID, _game_id, _pksav_save.item_storage.p_item_pc ); } else { /* * As there is no way to distinguish Gold and Silver saves from the saves * themselves, we'll try to depend on the fact that .sav files match * the name of their game's ROM, which are usually the game titles, so * we'll check for the version in the filename. */ std::string filename_lower = boost::algorithm::to_lower_copy( fs::path(filepath).stem().string() ); if(filename_lower.find("gold") != std::string::npos) { _game_id = GOLD_GAME_ID; } else if(filename_lower.find("silver") != std::string::npos) { _game_id = SILVER_GAME_ID; } else { // Default to Gold, doesn't practically matter within a version group _game_id = GOLD_GAME_ID; } BOOST_ASSERT(_pksav_save.item_storage.p_item_pc != nullptr); _item_pc = std::make_shared<item_list_gen2_pcimpl>( GS_PC_ID, _game_id, _pksav_save.item_storage.p_item_pc ); } BOOST_ASSERT(_pksav_save.pokedex_lists.p_seen != nullptr); BOOST_ASSERT(_pksav_save.pokedex_lists.p_owned != nullptr); _pokedex = std::make_shared<pokedex_gen2impl>( _game_id, &_pksav_save.pokedex_lists ); BOOST_ASSERT(_pksav_save.pokemon_storage.p_party != nullptr); _pokemon_party = std::make_shared<pokemon_party_gen2impl>( _game_id, _pksav_save.pokemon_storage.p_party ); BOOST_ASSERT(_pksav_save.pokemon_storage.p_box_names != nullptr); _pokemon_pc = std::make_shared<pokemon_pc_gen2impl>( _game_id, &_pksav_save.pokemon_storage ); BOOST_ASSERT(_pksav_save.item_storage.p_item_bag != nullptr); _item_bag = std::make_shared<item_bag_gen2impl>( _game_id, _pksav_save.item_storage.p_item_bag ); // When a Pokémon is added to the PC or party, it should be // reflected in the Pokédex. pokemon_party_impl* p_party_impl = dynamic_cast<pokemon_party_impl*>(_pokemon_party.get()); pokemon_pc_impl* p_pc_impl = dynamic_cast<pokemon_pc_impl*>(_pokemon_pc.get()); BOOST_ASSERT(p_party_impl != nullptr); BOOST_ASSERT(p_pc_impl != nullptr); p_party_impl->set_pokedex(_pokedex); p_pc_impl->set_pokedex(_pokedex); _register_attributes(); } game_save_gen2impl::~game_save_gen2impl() { pksav_gen2_free_save(&_pksav_save); } void game_save_gen2impl::save_as( const std::string& filepath ) { boost::lock_guard<game_save_gen2impl> lock(*this); // These get_native() calls will call the mutex for every subclass // it copies, so we don't need to worry about that here. pkmn::rcast_equal<struct pksav_gen2_item_bag>( _item_bag->get_native(), _pksav_save.item_storage.p_item_bag ); pkmn::rcast_equal<struct pksav_gen2_item_pc>( _item_pc->get_native(), _pksav_save.item_storage.p_item_pc ); pkmn::rcast_equal<struct pksav_gen2_pokemon_party>( _pokemon_party->get_native(), _pksav_save.pokemon_storage.p_party ); // The PC is stored in multiple pointers, so this is more manual. const struct pksav_gen2_pokemon_storage* p_pokemon_storage = static_cast<const struct pksav_gen2_pokemon_storage*>( _pokemon_pc->get_native() ); for(size_t box_index = 0; box_index < PKSAV_GEN2_NUM_POKEMON_BOXES; ++box_index) { *(_pksav_save.pokemon_storage.pp_boxes[box_index]) = *(p_pokemon_storage->pp_boxes[box_index]); } *(_pksav_save.pokemon_storage.p_current_box_num) = *(p_pokemon_storage->p_current_box_num); *(_pksav_save.pokemon_storage.p_current_box) = *(p_pokemon_storage->p_current_box); save_gb_pokedex( &_pksav_save.pokedex_lists, PKSAV_GEN2_POKEDEX_BUFFER_SIZE_BYTES ); PKSAV_CALL( pksav_gen2_save_save( filepath.c_str(), &_pksav_save ); ) _filepath = fs::absolute(filepath).string(); } pkmn::time_duration game_save_gen2impl::get_time_played() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.save_time.p_time_played != nullptr); return pkmn::time_duration( _pksav_save.save_time.p_time_played->hours, _pksav_save.save_time.p_time_played->minutes, _pksav_save.save_time.p_time_played->seconds, _pksav_save.save_time.p_time_played->frames ); } void game_save_gen2impl::set_time_played( const pkmn::time_duration& time_played ) { pkmn::enforce_bounds( "Hours played", time_played.hours, 0, 255 ); pkmn::enforce_bounds( "Minutes played", time_played.minutes, 0, 59 ); pkmn::enforce_bounds( "Seconds played", time_played.seconds, 0, 59 ); pkmn::enforce_bounds( "Frames played", time_played.frames, 0, 59 ); boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.save_time.p_time_played != nullptr); _pksav_save.save_time.p_time_played->hours = static_cast<uint8_t>(time_played.hours); _pksav_save.save_time.p_time_played->minutes = static_cast<uint8_t>(time_played.minutes); _pksav_save.save_time.p_time_played->seconds = static_cast<uint8_t>(time_played.seconds); _pksav_save.save_time.p_time_played->frames = static_cast<uint8_t>(time_played.frames); } std::string game_save_gen2impl::get_trainer_name() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_name != nullptr); char trainer_name[PKSAV_GEN2_TRAINER_NAME_LENGTH + 1] = {0}; PKSAV_CALL( pksav_gen2_import_text( _pksav_save.trainer_info.p_name, trainer_name, PKSAV_GEN2_TRAINER_NAME_LENGTH ); ) return std::string(trainer_name); } void game_save_gen2impl::set_trainer_name( const std::string& trainer_name ) { pkmn::enforce_string_length( "Trainer name", trainer_name, 1, PKSAV_GEN2_TRAINER_NAME_LENGTH ); boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_name != nullptr); PKSAV_CALL( pksav_gen2_export_text( trainer_name.c_str(), _pksav_save.trainer_info.p_name, PKSAV_GEN2_TRAINER_NAME_LENGTH ); ) } uint32_t game_save_gen2impl::get_trainer_id() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); return pksav_bigendian16(*_pksav_save.trainer_info.p_id); } void game_save_gen2impl::set_trainer_id( uint32_t trainer_id ) { pkmn::enforce_gb_trainer_id_bounds(trainer_id); boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); *_pksav_save.trainer_info.p_id = pksav_bigendian16(uint16_t(trainer_id)); } uint16_t game_save_gen2impl::get_trainer_public_id() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); return pksav_bigendian16(*_pksav_save.trainer_info.p_id); } void game_save_gen2impl::set_trainer_public_id( uint16_t trainer_public_id ) { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); *_pksav_save.trainer_info.p_id = pksav_bigendian16(trainer_public_id); } uint16_t game_save_gen2impl::get_trainer_secret_id() { throw pkmn::feature_not_in_game_error("Secret ID", "Generation II"); } void game_save_gen2impl::set_trainer_secret_id( PKMN_UNUSED(uint16_t trainer_secret_id) ) { throw pkmn::feature_not_in_game_error("Secret ID", "Generation II"); } pkmn::e_gender game_save_gen2impl::get_trainer_gender() { boost::lock_guard<game_save_gen2impl> lock(*this); pkmn::e_gender ret; if(_game_id == CRYSTAL_GAME_ID) { ret = (*_pksav_save.trainer_info.p_gender == PKSAV_GEN2_GENDER_MALE) ? pkmn::e_gender::MALE : pkmn::e_gender::FEMALE; } else { ret = pkmn::e_gender::MALE; } return ret; } void game_save_gen2impl::set_trainer_gender(pkmn::e_gender trainer_gender) { if(_game_id == CRYSTAL_GAME_ID) { BOOST_ASSERT(_pksav_save.trainer_info.p_gender != nullptr); const pksav::gen2_gender_bimap_t& gen2_gender_bimap = pksav::get_gen2_gender_bimap(); pkmn::enforce_value_in_map_keys( "Trainer gender", trainer_gender, gen2_gender_bimap.left ); boost::lock_guard<game_save_gen2impl> lock(*this); *_pksav_save.trainer_info.p_gender = uint8_t(gen2_gender_bimap.left.at(trainer_gender)); } else { throw pkmn::feature_not_in_game_error("All trainers are male in Gold/Silver."); } } std::string game_save_gen2impl::get_rival_name() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_rival_name != nullptr); char rival_name[PKSAV_GEN2_TRAINER_NAME_LENGTH + 1] = {0}; PKSAV_CALL( pksav_gen2_import_text( _pksav_save.misc_fields.p_rival_name, rival_name, PKSAV_GEN2_TRAINER_NAME_LENGTH ); ) return std::string(rival_name); } void game_save_gen2impl::set_rival_name( const std::string& rival_name ) { pkmn::enforce_string_length( "Rival name", rival_name, 1, PKSAV_GEN2_TRAINER_NAME_LENGTH ); boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_rival_name != nullptr); PKSAV_CALL( pksav_gen2_export_text( rival_name.c_str(), _pksav_save.misc_fields.p_rival_name, PKSAV_GEN2_TRAINER_NAME_LENGTH ); ) } int game_save_gen2impl::get_money() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_money != nullptr); size_t money_from_pksav = 0; PKSAV_CALL( pksav_import_base256( _pksav_save.trainer_info.p_money, PKSAV_GEN2_SAVE_MONEY_BUFFER_SIZE_BYTES, &money_from_pksav ); ) return int(money_from_pksav); } void game_save_gen2impl::set_money( int money ) { pkmn::enforce_bounds("Money", money, 0, MONEY_MAX_VALUE); boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_money != nullptr); PKSAV_CALL( pksav_export_base256( size_t(money), _pksav_save.trainer_info.p_money, PKSAV_GEN2_SAVE_MONEY_BUFFER_SIZE_BYTES ); ) } // Functions for attributes bool game_save_gen2impl::get_is_daylight_savings() { boost::lock_guard<game_save_gen2impl> lock(*this); return bool(*_pksav_save.save_time.p_daylight_savings & PKSAV_GEN2_DAYLIGHT_SAVINGS_TIME_MASK); } void game_save_gen2impl::set_is_daylight_savings(bool is_daylight_savings) { boost::lock_guard<game_save_gen2impl> lock(*this); if(is_daylight_savings) { *_pksav_save.save_time.p_daylight_savings |= PKSAV_GEN2_DAYLIGHT_SAVINGS_TIME_MASK; } else { *_pksav_save.save_time.p_daylight_savings &= ~PKSAV_GEN2_DAYLIGHT_SAVINGS_TIME_MASK; } } typedef boost::bimap<std::string, enum pksav_gen2_palette> gen2_palette_bimap_t; static const gen2_palette_bimap_t GEN2_PALETTE_BIMAP = boost::assign::list_of<gen2_palette_bimap_t::relation> ("Red", PKSAV_GEN2_PALETTE_RED) ("Blue", PKSAV_GEN2_PALETTE_BLUE) ("Green", PKSAV_GEN2_PALETTE_GREEN) ("Brown", PKSAV_GEN2_PALETTE_BROWN) ("Orange", PKSAV_GEN2_PALETTE_ORANGE) ("Gray", PKSAV_GEN2_PALETTE_GRAY) ("Dark Green", PKSAV_GEN2_PALETTE_DARK_GREEN) ("Dark Red", PKSAV_GEN2_PALETTE_DARK_RED) ; std::string game_save_gen2impl::get_palette() { boost::lock_guard<game_save_gen2impl> lock(*this); // If the save file is screwed up enough, the palette may not be // valid, so just return something. std::string ret = "Red"; auto palette_iter = GEN2_PALETTE_BIMAP.right.find((enum pksav_gen2_palette) (*_pksav_save.trainer_info.p_palette) ); if(palette_iter != GEN2_PALETTE_BIMAP.right.end()) { ret = palette_iter->second; } return ret; } void game_save_gen2impl::set_palette(const std::string& palette) { pkmn::enforce_value_in_map_keys( "Player palette", palette, GEN2_PALETTE_BIMAP.left ); boost::lock_guard<game_save_gen2impl> lock(*this); *_pksav_save.trainer_info.p_palette = uint8_t(GEN2_PALETTE_BIMAP.left.at(palette)); } // TODO: is there enough in common with the Gen I implementation to consolidate // these? std::string game_save_gen2impl::get_text_speed() { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); // Sensible default in the case of a corrupted save std::string text_speed = "Normal"; uint8_t raw_text_speed = (*_pksav_save.options.p_misc_options & PKSAV_GEN2_OPTIONS_TEXT_SPEED_MASK); const pksav::gen2_text_speed_bimap_t& gen2_text_speed_bimap = pksav::get_gen2_text_speed_bimap(); auto gen2_text_speed_iter = gen2_text_speed_bimap.right.find( static_cast<enum pksav_gen2_text_speed>(raw_text_speed) ); if(gen2_text_speed_iter != gen2_text_speed_bimap.right.end()) { text_speed = gen2_text_speed_iter->second; } return text_speed; } void game_save_gen2impl::set_text_speed( const std::string& text_speed ) { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); const pksav::gen2_text_speed_bimap_t& gen2_text_speed_bimap = pksav::get_gen2_text_speed_bimap(); pkmn::enforce_value_in_map_keys( "Text speed", text_speed, gen2_text_speed_bimap.left ); boost::lock_guard<game_save_gen2impl> lock(*this); *_pksav_save.options.p_misc_options &= ~PKSAV_GEN2_OPTIONS_TEXT_SPEED_MASK; *_pksav_save.options.p_misc_options |= static_cast<uint8_t>( gen2_text_speed_bimap.left.at(text_speed) ); } std::string game_save_gen2impl::get_sound_output() { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); // Sensible default in the case of a corrupted save std::string sound_output = "Mono"; bool is_stereo = bool(*_pksav_save.options.p_misc_options & PKSAV_GEN2_OPTIONS_SOUND_STEREO_MASK); sound_output = is_stereo ? "Stereo" : "Mono"; return sound_output; } void game_save_gen2impl::set_sound_output( const std::string& sound_output ) { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); pkmn::enforce_value_in_vector( "Sound output", sound_output, {"Stereo", "Mono"} ); boost::lock_guard<game_save_gen2impl> lock(*this); if(sound_output == "Stereo") { *_pksav_save.options.p_misc_options |= PKSAV_GEN2_OPTIONS_SOUND_STEREO_MASK; } else { *_pksav_save.options.p_misc_options &= ~PKSAV_GEN2_OPTIONS_SOUND_STEREO_MASK; } } std::string game_save_gen2impl::get_battle_style() { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); bool is_battle_style_set = (*_pksav_save.options.p_misc_options & PKSAV_GEN2_OPTIONS_BATTLE_STYLE_SET_MASK); return is_battle_style_set ? "Set" : "Shift"; } void game_save_gen2impl::set_battle_style( const std::string& battle_style ) { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); pkmn::enforce_value_in_vector( "Battle style", battle_style, {"Set", "Shift"} ); if(battle_style == "Set") { *_pksav_save.options.p_misc_options |= PKSAV_GEN2_OPTIONS_BATTLE_STYLE_SET_MASK; } else { *_pksav_save.options.p_misc_options &= ~PKSAV_GEN2_OPTIONS_BATTLE_STYLE_SET_MASK; } } bool game_save_gen2impl::get_is_battle_scene_enabled() { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); // The save stored whether the effects are disabled, so reverse // the result. // // TODO: verify, the disassembly is unclear return !(*_pksav_save.options.p_misc_options & PKSAV_GEN2_OPTIONS_BATTLE_SCENE_MASK); } void game_save_gen2impl::set_is_battle_scene_enabled( bool is_battle_scene_enabled ) { BOOST_ASSERT(_pksav_save.options.p_misc_options != nullptr); // The save stored whether the effects are disabled, so reverse // the input. // // TODO: verify, the disassembly is unclear if(is_battle_scene_enabled) { *_pksav_save.options.p_misc_options &= ~PKSAV_GEN2_OPTIONS_BATTLE_SCENE_MASK; } else { *_pksav_save.options.p_misc_options |= PKSAV_GEN2_OPTIONS_BATTLE_SCENE_MASK; } } int game_save_gen2impl::get_textbox_frame_index() { BOOST_ASSERT(_pksav_save.options.p_textbox_frame_index != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); return (*_pksav_save.options.p_textbox_frame_index & PKSAV_GEN2_OPTIONS_TEXTBOX_FRAME_MASK); } void game_save_gen2impl::set_textbox_frame_index(int textbox_frame_index) { BOOST_ASSERT(_pksav_save.options.p_textbox_frame_index != nullptr); pkmn::enforce_bounds( "Textbox frame", textbox_frame_index, static_cast<int>(PKSAV_GEN2_OPTIONS_TEXTBOX_MIN_FRAME + 1), static_cast<int>(PKSAV_GEN2_OPTIONS_TEXTBOX_MAX_FRAME + 1) ); boost::lock_guard<game_save_gen2impl> lock(*this); // The value is stored 0-based. uint8_t raw_textbox_frame_index = static_cast<uint8_t>(textbox_frame_index) - 1; *_pksav_save.options.p_textbox_frame_index &= ~PKSAV_GEN2_OPTIONS_TEXTBOX_FRAME_MASK; *_pksav_save.options.p_textbox_frame_index |= raw_textbox_frame_index; } std::string game_save_gen2impl::get_gameboy_printer_brightness() { BOOST_ASSERT(_pksav_save.options.p_gbprinter_brightness != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); // Sensible default in case of save corruption std::string gameboy_printer_brightness = "Normal"; uint8_t raw_gameboy_printer_brightness = (*_pksav_save.options.p_gbprinter_brightness & PKSAV_GEN2_GBPRINTER_BRIGHTNESS_MASK); const pksav::gen2_gbprinter_brightness_bimap_t& gen2_gbprinter_brightness_bimap = pksav::get_gen2_gbprinter_brightness_bimap(); auto gen2_gbprinter_brightness_iter = gen2_gbprinter_brightness_bimap.right.find( static_cast<enum pksav_gen2_gbprinter_brightness>( raw_gameboy_printer_brightness ) ); if(gen2_gbprinter_brightness_iter != gen2_gbprinter_brightness_bimap.right.end()) { gameboy_printer_brightness = gen2_gbprinter_brightness_iter->second; } return gameboy_printer_brightness; } void game_save_gen2impl::set_gameboy_printer_brightness( const std::string& gameboy_printer_brightness ) { BOOST_ASSERT(_pksav_save.options.p_gbprinter_brightness != nullptr); const pksav::gen2_gbprinter_brightness_bimap_t& gen2_gbprinter_brightness_bimap = pksav::get_gen2_gbprinter_brightness_bimap(); pkmn::enforce_value_in_map_keys( "Game Boy Printer brightness", gameboy_printer_brightness, gen2_gbprinter_brightness_bimap.left ); boost::lock_guard<game_save_gen2impl> lock(*this); *_pksav_save.options.p_gbprinter_brightness &= ~PKSAV_GEN2_GBPRINTER_BRIGHTNESS_MASK; *_pksav_save.options.p_gbprinter_brightness |= static_cast<uint8_t>( gen2_gbprinter_brightness_bimap.left.at(gameboy_printer_brightness) ); } bool game_save_gen2impl::get_is_menu_account_enabled() { BOOST_ASSERT(_pksav_save.options.p_menu_account != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); return bool(*_pksav_save.options.p_menu_account & PKSAV_GEN2_OPTIONS_MENU_ACCOUNT_MASK); } void game_save_gen2impl::set_is_menu_account_enabled(bool is_menu_account_enabled) { BOOST_ASSERT(_pksav_save.options.p_menu_account != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); if(is_menu_account_enabled) { *_pksav_save.options.p_menu_account |= PKSAV_GEN2_OPTIONS_MENU_ACCOUNT_MASK; } else { *_pksav_save.options.p_menu_account &= ~PKSAV_GEN2_OPTIONS_MENU_ACCOUNT_MASK; } } int game_save_gen2impl::get_money_with_mom() { BOOST_ASSERT(_pksav_save.misc_fields.p_money_with_mom != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); size_t money_with_mom; PKSAV_CALL( pksav_import_bcd( _pksav_save.misc_fields.p_money_with_mom, PKSAV_GEN2_SAVE_MONEY_BUFFER_SIZE_BYTES, &money_with_mom ); ) return static_cast<int>(money_with_mom); } void game_save_gen2impl::set_money_with_mom(int money_with_mom) { pkmn::enforce_bounds( "Money with Mom", money_with_mom, 0, PKSAV_GEN2_SAVE_MONEY_MAX_VALUE ); BOOST_ASSERT(_pksav_save.misc_fields.p_money_with_mom != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); PKSAV_CALL( pksav_export_bcd( static_cast<size_t>(money_with_mom), _pksav_save.misc_fields.p_money_with_mom, PKSAV_GEN2_SAVE_MONEY_BUFFER_SIZE_BYTES ); ) } std::string game_save_gen2impl::get_mom_money_policy() { BOOST_ASSERT(_pksav_save.misc_fields.p_mom_money_policy != nullptr); boost::lock_guard<game_save_gen2impl> lock(*this); std::string mom_money_policy = "Not saving money"; // If this flag isn't set, the player hasn't reached the point where this is // introduced, so naturally, Mom's not saving money. if(*_pksav_save.misc_fields.p_mom_money_policy & PKSAV_GEN2_MOM_MONEY_POLICY_ACTIVE_FLAG) { uint8_t raw_mom_money_policy = (*_pksav_save.misc_fields.p_mom_money_policy & ~PKSAV_GEN2_MOM_MONEY_POLICY_ACTIVE_FLAG); const pksav::gen2_mom_money_policy_bimap_t& gen2_mom_money_policy_bimap = pksav::get_gen2_mom_money_policy_bimap(); // Go with the default above in the case of save corruption. auto gen2_mom_money_policy_iter = gen2_mom_money_policy_bimap.right.find( static_cast<enum pksav_gen2_mom_money_policy>( raw_mom_money_policy ) ); if(gen2_mom_money_policy_iter != gen2_mom_money_policy_bimap.right.end()) { mom_money_policy = gen2_mom_money_policy_iter->second; } } return mom_money_policy; } void game_save_gen2impl::set_mom_money_policy( const std::string& mom_money_policy ) { BOOST_ASSERT(_pksav_save.misc_fields.p_mom_money_policy != nullptr); const pksav::gen2_mom_money_policy_bimap_t& gen2_mom_money_policy_bimap = pksav::get_gen2_mom_money_policy_bimap(); pkmn::enforce_value_in_map_keys( "Mom money policy", mom_money_policy, gen2_mom_money_policy_bimap.left ); boost::lock_guard<game_save_gen2impl> lock(*this); auto mom_money_policy_iter = gen2_mom_money_policy_bimap.left.find( mom_money_policy ); BOOST_ASSERT(mom_money_policy_iter != gen2_mom_money_policy_bimap.left.end()); uint8_t raw_mom_money_policy = static_cast<uint8_t>( mom_money_policy_iter->second ); // This separate flag indicates the event where this was introduced has // occurred. raw_mom_money_policy |= PKSAV_GEN2_MOM_MONEY_POLICY_ACTIVE_FLAG; *_pksav_save.misc_fields.p_mom_money_policy = raw_mom_money_policy; } int game_save_gen2impl::get_casino_coins() { boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_casino_coins != nullptr); size_t casino_coins_from_pksav = 0; PKSAV_CALL( pksav_import_bcd( _pksav_save.misc_fields.p_casino_coins, PKSAV_GEN2_SAVE_CASINO_COINS_BUFFER_SIZE_BYTES, &casino_coins_from_pksav ) ); return int(casino_coins_from_pksav); } void game_save_gen2impl::set_casino_coins( int casino_coins ) { pkmn::enforce_bounds( "Casino coins", casino_coins, 0, PKSAV_GEN2_SAVE_CASINO_COINS_MAX_VALUE ); boost::lock_guard<game_save_gen2impl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_casino_coins != nullptr); PKSAV_CALL( pksav_export_bcd( size_t(casino_coins), _pksav_save.misc_fields.p_casino_coins, PKSAV_GEN2_SAVE_CASINO_COINS_BUFFER_SIZE_BYTES ) ); } void game_save_gen2impl::_register_attributes() { using std::placeholders::_1; _numeric_attribute_engine.register_attribute_fcns( "Textbox frame", std::bind(&game_save_gen2impl::get_textbox_frame_index, this), std::bind(&game_save_gen2impl::set_textbox_frame_index, this, _1) ); _numeric_attribute_engine.register_attribute_fcns( "Money with Mom", std::bind(&game_save_gen2impl::get_money_with_mom, this), std::bind(&game_save_gen2impl::set_money_with_mom, this, _1) ); _numeric_attribute_engine.register_attribute_fcns( "Casino coins", std::bind(&game_save_gen2impl::get_casino_coins, this), std::bind(&game_save_gen2impl::set_casino_coins, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Player palette", std::bind(&game_save_gen2impl::get_palette, this), std::bind(&game_save_gen2impl::set_palette, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Text speed", std::bind(&game_save_gen2impl::get_text_speed, this), std::bind(&game_save_gen2impl::set_text_speed, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Sound output", std::bind(&game_save_gen2impl::get_sound_output, this), std::bind(&game_save_gen2impl::set_sound_output, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Battle style", std::bind(&game_save_gen2impl::get_battle_style, this), std::bind(&game_save_gen2impl::set_battle_style, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Game Boy Printer brightness", std::bind(&game_save_gen2impl::get_gameboy_printer_brightness, this), std::bind(&game_save_gen2impl::set_gameboy_printer_brightness, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Mom money policy", std::bind(&game_save_gen2impl::get_mom_money_policy, this), std::bind(&game_save_gen2impl::set_mom_money_policy, this, _1) ); _boolean_attribute_engine.register_attribute_fcns( "Daylight savings time?", std::bind(&game_save_gen2impl::get_is_daylight_savings, this), std::bind(&game_save_gen2impl::set_is_daylight_savings, this, _1) ); _boolean_attribute_engine.register_attribute_fcns( "Enable battle scene?", std::bind(&game_save_gen2impl::get_is_battle_scene_enabled, this), std::bind(&game_save_gen2impl::set_is_battle_scene_enabled, this, _1) ); _boolean_attribute_engine.register_attribute_fcns( "Enable menu account?", std::bind(&game_save_gen2impl::get_is_menu_account_enabled, this), std::bind(&game_save_gen2impl::set_is_menu_account_enabled, this, _1) ); } }
33.061947
106
0.617833
[ "vector" ]
e60d32bdd0ed16bf96f287d231d6772fa6b63de8
1,174
hh
C++
include/click/driver.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
include/click/driver.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
include/click/driver.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
// -*- c-basic-offset: 4; related-file-name: "../../lib/driver.cc" -*- #ifndef CLICK_DRIVER_HH #define CLICK_DRIVER_HH #include <click/package.hh> #define CLICK_DEFAULT_PROVIDES /* nada */ #if defined(CLICK_USERLEVEL) || defined(CLICK_MINIOS) CLICK_DECLS class Router; class Master; class ErrorHandler; class Lexer; struct ArchiveElement; void click_static_initialize(); void click_static_cleanup(); Lexer *click_lexer(); Router *click_read_router(String filename, bool is_expr, ErrorHandler * = 0, bool initialize = true, Master * = 0); String click_compile_archive_file(const Vector<ArchiveElement> &ar, const ArchiveElement *ae, String package, const String &target, int quiet, bool &tmpdir_populated, ErrorHandler *errh); CLICK_ENDDECLS #elif CLICK_TOOL CLICK_DECLS class ErrorHandler; struct ArchiveElement; void click_static_initialize(); String click_compile_archive_file(const Vector<ArchiveElement> &archive, const ArchiveElement *ae, String package, const String &target, int quiet, bool &tmpdir_populated, ErrorHandler *errh); CLICK_ENDDECLS #endif #endif
26.681818
115
0.72402
[ "vector" ]
e611f78098c09cc31577355cfe4d138f1a8c7cb6
13,683
cpp
C++
daemon/linux/proc/ProcStatFileRecord.cpp
RufUsul/gator
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
[ "BSD-3-Clause" ]
118
2015-03-24T16:09:42.000Z
2022-03-21T09:01:59.000Z
daemon/linux/proc/ProcStatFileRecord.cpp
RufUsul/gator
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
[ "BSD-3-Clause" ]
26
2016-03-03T23:24:08.000Z
2022-03-21T10:24:43.000Z
daemon/linux/proc/ProcStatFileRecord.cpp
RufUsul/gator
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
[ "BSD-3-Clause" ]
73
2015-06-09T09:44:06.000Z
2021-12-30T09:49:00.000Z
/* Copyright (C) 2017-2021 by Arm Limited. All rights reserved. */ #include "linux/proc/ProcStatFileRecord.h" #include "lib/Assert.h" #include "lib/Format.h" #include <cctype> #include <cstdlib> #include <cstring> namespace lnx { namespace { /** * Skip over any spaces * * @return Index into string of next non-space character */ unsigned skipSpaces(const char * string, unsigned from) { while (string[from] == ' ') { from += 1; } return from; } /** * Find the next break in the stat file; either a space, newline or end of string * * @return Index into string of next space, newline or null terminator */ unsigned findNextBreak(const char * string, unsigned from) { while ((string[from] != ' ') && (string[from] != '\n') && (string[from] != '\0')) { from += 1; } return from; } /** * Skip to the start of the next line, or to end of string. * * @return Index into string of start of next line, or of null terminator */ unsigned skipLine(const char * string, unsigned from) { // find the end of the line/string while (string[from] == ' ') { from = findNextBreak(string, from + 1); } if (string[from] == '\0') { return from; } return from + 1; } /** * Check that some substring of "string" matches "against". * Specifically the characters `string[from...(from + strlen(against))]` must match and either * when `full` is true, `(from + strlen(against))` must be == `to`, or * when `full` is false, `(from + strlen(against))` must be <= `to`. * * @return True if the strings match, false otherwise */ bool matchToken(const char * string, const unsigned from, const unsigned to, const char * against, const bool full) { unsigned apos = 0; unsigned spos = from; while (against[apos] != '\0') { if ((spos >= to) || (string[spos] != against[apos])) { return false; } apos += 1; spos += 1; } return (!full) || (spos == to); } /** * Decode an unsigned long value into the argument `result` * * @return The index of the next character starting at `from` that is not a digit */ unsigned decodeUnsignedLong(unsigned long & result, const char * string, const unsigned from) { result = 0; unsigned pos = from; while (std::isdigit(string[pos]) != 0) { result = (result * 10) + (string[pos] - '0'); pos += 1; } return pos; } /** * Extract an unsigned long value from the substring of string starting at from * * @return As per skipLine */ unsigned parseUnsignedLong(lib::Optional<unsigned long> & result, const char * string, const unsigned from) { // just decode a single value unsigned long value = 0; const unsigned pos = decodeUnsignedLong(value, string, skipSpaces(string, from)); if (pos > from) { result.set(value); } else { result.clear(); } return skipLine(string, pos); } /** * Extract a `PagingCounts` value from the substring of string starting at from. The value is encoded as two unsigned longs separated by a space. * * @return As per skipLine */ unsigned parsePagingCounts(lib::Optional<ProcStatFileRecord::PagingCounts> & result, const char * string, const unsigned from) { // decode two values unsigned long in = 0; unsigned long out = 0; // decode first const unsigned pos_in = decodeUnsignedLong(in, string, skipSpaces(string, from)); // decode second if ((pos_in > from) && (string[pos_in] == ' ')) { const unsigned pos_out = decodeUnsignedLong(out, string, pos_in + 1); if (pos_out > (pos_in + 1)) { result.set(ProcStatFileRecord::PagingCounts(in, out)); } else { result.clear(); } return skipLine(string, pos_out); } result.clear(); return skipLine(string, pos_in); } /** * Extract the time fields for `CpuTimes` */ template<unsigned N> static unsigned decodeCpuTimes(const char * string, const unsigned from, unsigned long long (&times)[N], unsigned & out_num_decoded) { unsigned last_pos = from; out_num_decoded = 0; for (unsigned index = 0; index < N; ++index) { unsigned long time_val = 0; const unsigned pos = decodeUnsignedLong(time_val, string, last_pos); if (pos <= last_pos) { break; } out_num_decoded = index + 1; times[index] = time_val; // leave as ticks if (string[pos] == ' ') { last_pos = pos + 1; } else { return pos; } } return last_pos; } /** * Extract a `Cputimes` value from the substring of string starting at from. The value is encoded as two unsigned longs separated by a space. * * @return As per skipLine */ unsigned parseCpuTime(std::vector<ProcStatFileRecord::CpuTime> & cpus, const char * string, unsigned identifier_from, unsigned token_end) { unsigned long cpu_id; unsigned long long times[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // decode the cpu number if ((identifier_from + 1) < token_end) { const unsigned pos = decodeUnsignedLong(cpu_id, string, identifier_from); runtime_assert((pos + 1) == token_end, lib::Format() << "Unexpected value for 'pos': " << pos << ", expected " << token_end); } else { cpu_id = ProcStatFileRecord::GLOBAL_CPU_TIME_ID; } // read times unsigned num_decoded = 0; const unsigned pos = decodeCpuTimes(string, skipSpaces(string, token_end), times, num_decoded); if (num_decoded == 10) { cpus.emplace_back(cpu_id, times); } return skipLine(string, pos); } } ProcStatFileRecord::ProcStatFileRecord(const char * stat_contents) : ProcStatFileRecord() { if (stat_contents != nullptr) { unsigned current_offset = 0; while (stat_contents[current_offset] != '\0') { // find the next token break const unsigned next_break = findNextBreak(stat_contents, current_offset); // if the token is terminated by anything other than a space then skip it if (stat_contents[next_break] != ' ') { current_offset = skipLine(stat_contents, next_break); } else { // use the first char to speed parsing switch (stat_contents[current_offset]) { // btime case 'b': { if (matchToken(stat_contents, current_offset + 1, next_break, "time", true)) { current_offset = parseUnsignedLong(btime, stat_contents, next_break + 1); } else { current_offset = skipLine(stat_contents, next_break); } break; } // cpu, ctxt case 'c': { if (matchToken(stat_contents, current_offset + 1, next_break, "pu", false)) { current_offset = parseCpuTime(cpus, stat_contents, current_offset + 3, next_break + 1); } else if (matchToken(stat_contents, current_offset + 1, next_break, "txt", true)) { current_offset = parseUnsignedLong(ctxt, stat_contents, next_break + 1); } else { current_offset = skipLine(stat_contents, next_break); } break; } // intr case 'i': { if (matchToken(stat_contents, current_offset + 1, next_break, "ntr", true)) { current_offset = parseUnsignedLong(intr, stat_contents, next_break + 1); } else { current_offset = skipLine(stat_contents, next_break); } break; } // page, processes, procs_running, procs_blocked case 'p': { if (matchToken(stat_contents, current_offset + 1, next_break, "age", false)) { current_offset = parsePagingCounts(page, stat_contents, next_break + 1); } else if (matchToken(stat_contents, current_offset + 1, next_break, "rocesses", true)) { current_offset = parseUnsignedLong(processes, stat_contents, next_break + 1); } else if (matchToken(stat_contents, current_offset + 1, next_break, "rocs_running", true)) { current_offset = parseUnsignedLong(procs_running, stat_contents, next_break + 1); } else if (matchToken(stat_contents, current_offset + 1, next_break, "rocs_blocked", true)) { current_offset = parseUnsignedLong(procs_blocked, stat_contents, next_break + 1); } else { current_offset = skipLine(stat_contents, next_break); } break; } // soft_irq, swap case 's': { if (matchToken(stat_contents, current_offset + 1, next_break, "wap", false)) { current_offset = parsePagingCounts(swap, stat_contents, next_break + 1); } else if (matchToken(stat_contents, current_offset + 1, next_break, "oftirq", true)) { current_offset = parseUnsignedLong(soft_irq, stat_contents, next_break + 1); } else { current_offset = skipLine(stat_contents, next_break); } break; } // all others default: { current_offset = skipLine(stat_contents, next_break); break; } } } } } } ProcStatFileRecord::ProcStatFileRecord(std::vector<CpuTime> && cpus_, lib::Optional<PagingCounts> && page_, lib::Optional<PagingCounts> && swap_, lib::Optional<unsigned long> && intr_, lib::Optional<unsigned long> && soft_irq_, lib::Optional<unsigned long> && ctxt_, lib::Optional<unsigned long> && btime_, lib::Optional<unsigned long> && processes_, lib::Optional<unsigned long> && procs_running_, lib::Optional<unsigned long> && procs_blocked_) : cpus(std::move(cpus_)), page(std::move(page_)), swap(std::move(swap_)), intr(std::move(intr_)), soft_irq(std::move(soft_irq_)), ctxt(std::move(ctxt_)), btime(std::move(btime_)), processes(std::move(processes_)), procs_running(std::move(procs_running_)), procs_blocked(std::move(procs_blocked_)) { } }
39.776163
153
0.450778
[ "vector" ]
e612fb8eadda127f7c50847ab76d28c2619cbf7a
2,354
cc
C++
cpp/Codeforces/51-100/58A_Chat_room.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/51-100/58A_Chat_room.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/51-100/58A_Chat_room.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> void fillArr(bool *arr, int size, bool value) { for (int i = 0; i != size; ++i) { arr[i] = value; } } int skipChar(std::string str, char c, int curIdx) { while (str[curIdx] != c) { ++curIdx; } return curIdx; } int main(int argc, char **argv) { std::string s; std::cin >> s; // Loop through the string // - If found h // + Mark helloMatches[0] = true // + Skip all h // - Next if found e // + Mark helloMatches[1] = true // + Skip all e // - Next if found ll // + Mark helloMatches[2-3] = true // + Skip all l // - Next if found o // + Mark helloMatches[4] = true // + Skip all o // + Return true // bool isFound = false; for (unsigned int i = 0; i != s.length(); ++i) { if (s[i] == 'h') { // std::cout << "h found at i = " << i << std::endl; i = skipChar(s, 'e', i); if (i < s.length()) { // std::cout << "e found at i = " << i << std::endl; i = skipChar(s, 'l', i); if (i < s.length()) { // std::cout << "l found at i = " << i << std::endl; i = skipChar(s, 'l', ++i); if (i < s.length()) { // std::cout << "l found at i = " << i << std::endl; i = skipChar(s, 'o', i); if (i < s.length()) { // std::cout << "o found at i = " << i << std::endl; isFound = true; break; } else { // if (s[i - 1] == 'o') { // isFound = true; // break; // } } } else { break; } } else { break; } } else { break; } } } if (isFound) { std::cout << "YES"; } else { std::cout << "NO"; } return 0; }
23.306931
80
0.329227
[ "vector" ]
e625c9765c61ba1bae1233793fdea05cd566008f
2,969
cpp
C++
Sharing/Src/Source/Common/Private/RemoveOperation.cpp
matthejo/MixedRealityToolkit
c97ace84cfc4cdf97044b35b568bd9182497497a
[ "MIT" ]
300
2017-08-12T12:57:42.000Z
2019-05-06T00:31:29.000Z
Sharing/Src/Source/Common/Private/RemoveOperation.cpp
matthejo/MixedRealityToolkit
c97ace84cfc4cdf97044b35b568bd9182497497a
[ "MIT" ]
84
2017-08-14T11:03:37.000Z
2019-04-24T22:59:59.000Z
Sharing/Src/Source/Common/Private/RemoveOperation.cpp
matthejo/MixedRealityToolkit
c97ace84cfc4cdf97044b35b568bd9182497497a
[ "MIT" ]
114
2017-08-12T03:51:58.000Z
2019-05-06T03:36:26.000Z
////////////////////////////////////////////////////////////////////////// // RemoveOperation.cpp // // Copyright (C) 2016 Microsoft Corp. All Rights Reserved ////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "RemoveOperation.h" XTOOLS_NAMESPACE_BEGIN NAMESPACE_BEGIN(Sync) RemoveOperation::RemoveOperation(Sync::AuthorityLevel authLevel) : Operation(Operation::Type::Remove, authLevel) , m_elementGuid(kInvalidXGuid) , m_index(-1) { } RemoveOperation::RemoveOperation(XGuid guid, int32 index, AuthorityLevel authLevel, const SyncContextPtr& context) : Operation(Operation::Type::Remove, authLevel, context->GetHierarchy(context->GetElement(guid)->GetParent()->GetGUID())) , m_elementGuid(guid) , m_index(index) { } RemoveOperation::RemoveOperation(XGuid guid, int32 index, AuthorityLevel authLevel, const std::vector<XGuid>& hierarchy) : Operation(Operation::Type::Remove, authLevel, hierarchy) , m_elementGuid(guid) , m_index(index) { } XGuid RemoveOperation::GetTargetGuid() const { return m_elementGuid; } void RemoveOperation::Apply(const SyncContextPtr& context) { ElementPtr modifiedElement = context->GetElement(m_elementGuid); if (XTVERIFY(modifiedElement)) { ArrayElement* arrayElement = reflection_cast<ArrayElement>(modifiedElement); if (XTVERIFY(arrayElement)) { m_removedValue = arrayElement->GetXValue(m_index); arrayElement->RemoveXValue(m_index); } } } void RemoveOperation::Serialize(const NetworkOutMessagePtr& msg) const { msg->Write(m_elementGuid); msg->Write(m_index); // Write the number of ancestors msg->Write(static_cast<uint32>(m_hierarchy.size())); // Write the GUIDs of the ancestors for (size_t i = 0; i < m_hierarchy.size(); ++i) { msg->Write(m_hierarchy[i]); } } void RemoveOperation::Deserialize(NetworkInMessage& msg) { m_elementGuid = msg.ReadInt64(); m_index = msg.ReadInt32(); // Read the number of ancestors uint32 numAncestors = msg.ReadUInt32(); m_hierarchy.reserve(numAncestors); // Read the GUIDs of the ancestors for (uint32 i = 0; i < numAncestors; ++i) { m_hierarchy.push_back(msg.ReadInt64()); } } void RemoveOperation::Notify(const SyncContextPtr& context) const { // Check that the element has not been deleted since this op was applied ElementPtr modifiedElement = context->GetElement(m_elementGuid); if (modifiedElement) { // Cast to an ArrayElement ArrayElement* arrayElement = reflection_cast<ArrayElement>(modifiedElement); if (XTVERIFY(arrayElement)) { // Notify the listener that the value was updated arrayElement->NotifyRemoved(m_index, m_removedValue); } } } std::string RemoveOperation::GetOpDescription() const { char buffer[512]; sprintf_s(buffer, sizeof(buffer), "%s, ID: %lli, Index: %i", GetTypeName(), m_elementGuid, m_index); return buffer; } int32 RemoveOperation::GetIndex() const { return m_index; } NAMESPACE_END(Sync) XTOOLS_NAMESPACE_END
23.377953
122
0.710677
[ "vector" ]
e6285ca57aed64cd06dd00b12d2e50e446dcb460
9,858
cpp
C++
GameFramwork/GameFramwork/Mesh.cpp
Suroboros/Game-Framwork
95dd3c2fe8504722990abb6c7cdf810881ad84c2
[ "MIT" ]
null
null
null
GameFramwork/GameFramwork/Mesh.cpp
Suroboros/Game-Framwork
95dd3c2fe8504722990abb6c7cdf810881ad84c2
[ "MIT" ]
null
null
null
GameFramwork/GameFramwork/Mesh.cpp
Suroboros/Game-Framwork
95dd3c2fe8504722990abb6c7cdf810881ad84c2
[ "MIT" ]
null
null
null
///////////////////////////////////// // Object.cpp // The mesh of object. ///////////////////////////////////// #include "Mesh.h" #include "D3DClass.h" #include <fstream> #include <string> Mesh::Mesh() { m_vertexBuffer = nullptr; m_indexBuffer = nullptr; } Mesh::Mesh(const Mesh &) { } Mesh::~Mesh() { } bool Mesh::InitializeBuffers() { HRESULT hr; // Setup the description of the vertex buffer. D3D11_BUFFER_DESC vbDesc; vbDesc.Usage = D3D11_USAGE_DEFAULT; vbDesc.ByteWidth = sizeof(VertexDataType)*m_data.size(); vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbDesc.CPUAccessFlags = 0; vbDesc.MiscFlags = 0; vbDesc.StructureByteStride = 0; // Give the subresource structure a pointer to the vertex data. D3D11_SUBRESOURCE_DATA vertexData; vertexData.pSysMem = &(m_data[0]); vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; // Create vertex buffer hr = D3DClass::GetInstance().GetDevice()->CreateBuffer(&vbDesc, &vertexData, &m_vertexBuffer); if(FAILED(hr)) return false; // Setup the description of index buffer. D3D11_BUFFER_DESC indexDesc; indexDesc.Usage = D3D11_USAGE_DEFAULT; indexDesc.ByteWidth = sizeof(unsigned int)*m_indices.size(); indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.CPUAccessFlags = 0; indexDesc.MiscFlags = 0; indexDesc.StructureByteStride = 0; // Give the subresource structure a pointer to the index data. D3D11_SUBRESOURCE_DATA indexData; indexData.pSysMem = &(m_indices[0]); indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; // Create index buffer hr = D3DClass::GetInstance().GetDevice()->CreateBuffer(&indexDesc, &indexData, &m_indexBuffer); if(FAILED(hr)) return false; return true; } void Mesh::ShutdownBuffer() { // Release the index buffer if(m_indexBuffer) { m_indexBuffer->Release(); m_indexBuffer = nullptr; } // Release the vertex buffer if(m_vertexBuffer) { m_vertexBuffer->Release(); m_vertexBuffer = nullptr; } return; } void Mesh::RenderBuffers() { // Set vertex buffer stride and offset UINT strides = sizeof(VertexDataType); UINT offsets = 0; // Set the vertex buffer to active D3DClass::GetInstance().GetDeviceContext()->IASetVertexBuffers(0, 1, &m_vertexBuffer, &strides, &offsets); // Set the index buffer to active D3DClass::GetInstance().GetDeviceContext()->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); // Set the type of primitive tha should be rendered from this vertex buffer D3DClass::GetInstance().GetDeviceContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); } Model::Model() { m_texture = nullptr; } Model::Model(Model & model) { } Model::~Model() { } bool Model::Initialize(TCHAR* meshPath, TCHAR* texPath) { bool result; // Load mesh result = LoadFromObj(meshPath); if(!result) return false; result = LoadMtl(); if (!result) return false; // Load texture if texture is setted if(texPath) { result = LoadTexture(texPath); if(!result) return false; } // Initialize the vertex and index buffers. for(auto mesh : m_model) { result = mesh->InitializeBuffers(); if(!result) return false; } return true; } void Model::Shutdown() { // Release texture ReleaseTexture(); // Release meshes for(auto mesh : m_model) { mesh->ShutdownBuffer(); delete mesh; mesh = nullptr; } return; } void Model::Render() { for(auto mesh: m_model) mesh->RenderBuffers(); } int Model::GetIndexCount() { int indexCnt = 0; for(auto mesh : m_model) indexCnt += mesh->m_indices.size(); return indexCnt; } ID3D11ShaderResourceView * Model::GetTexture() { if(m_texture) return m_texture->GetTexture(); else return nullptr; } bool Model::LoadFromObj(TCHAR* filePath) { ifstream fin; string input, input2; float maxX = 0.0f, minX = 0.0f, maxY = 0.0f, minY = 0.0f, maxZ = 0.0f, minZ = 0.0f; int cnt = 0; XMFLOAT3 v, vn; XMFLOAT2 vt; XMINT3 vertex; Face f; GroupInfo gInfo; // Open file fin.open(filePath, ios::in); if(fin.fail()) { MessageBox(nullptr, _T("Can't open mesh file"), _T("Error"), MB_OK); return false; } // Read data while(!fin.eof() && fin.peek() != EOF) { fin >> input; // Read mtl file path if(input.compare("mtllib") == 0) fin >> m_objData.mtllib; // Read geometric vertex if(input.compare("v") == 0) { fin >> v.x >> v.y >> v.z; // Invert the Z vertex to change to left hand system v.z = v.z*-1.0f; // Store the maxin and minin of the mesh if(cnt == 0) { maxX = minX = v.x; maxY = minY = v.y; maxZ = minZ = v.z; cnt++; } else { if(v.x > maxX) maxX = v.x; else if(v.x < minX) minX = v.x; if(v.y > maxY) maxY = v.y; else if(v.y < minY) minY = v.y; if(v.z > maxZ) maxZ = v.z; else if(v.z < minZ) minZ = v.z; } m_objData.v.push_back(v); } // Read vertex texture Coordinate Indices if(input.compare("vt") == 0) { fin >> vt.x >> vt.y; // Invert the V texture coordinates to left hand system. vt.y = 1.0f - vt.y; m_objData.vt.push_back(vt); } // Read vertex normal if(input.compare("vn") == 0) { fin >> vn.x >> vn.y >> vn.z; // Invert the Z normal to left hand system. vn.z = vn.z*-1.0f; m_objData.vn.push_back(vn); } // Read group information if(input.compare("g") == 0) { string g; fin >> g >> input; if(input.compare("usemtl") != 0) { fin.unget(); continue; } gInfo.name = g; // Read material name fin >> gInfo.usemtl; // Read face fin.get(); input = (char)fin.peek(); while(input.compare("f") == 0) { fin >> input; while(fin.peek() != '\n') { fin >> input2; DivideIndexString(vertex, input2); f.vertices.insert(f.vertices.begin(), vertex); } gInfo.faces.push_back(f); f.vertices.clear(); fin.get(); input = (char)fin.peek(); } m_objData.groups.push_back(gInfo); gInfo.name = ""; gInfo.usemtl = ""; gInfo.faces.clear(); } } // Close file fin.close(); // Calculate the size of the model m_width = maxX - minX; m_height = maxY - minY; m_depth = maxZ - minZ; // Write to mesh if(!WriteMesh()) return false; return true; } bool Model::LoadMtl() { ifstream fin; string input, input2; MaterialType material; string newmtl; // Open file fin.open(m_mtlPath, ios::in); if (fin.fail()) { MessageBox(nullptr, _T("Can't open material file"), _T("Error"), MB_OK); return false; } // Read data while (!fin.eof() && fin.peek() != EOF) { fin >> input; // Read comment if (input.compare("#") == 0) fin.ignore(256, '\n'); // Read material name if (input.compare("newmtl") == 0) fin >> newmtl; else continue; // Read material data while(input.compare("\n")!=0 && (!fin.eof() && fin.peek() != EOF)) { fin >> input; // Read ambient color if (input.compare("Ka") == 0) { fin >> material.ambient.x >> material.ambient.y >> material.ambient.z >> material.ambient.w; } // Read diffuse color if (input.compare("Kd") == 0) { fin >> material.diffuse.x >> material.diffuse.y >> material.diffuse.z >> material.diffuse.w; } // Read specular color if (input.compare("Ks") == 0) { fin >> material.specular.x >> material.specular.y >> material.specular.z; } // Read specular power if (input.compare("Ns") == 0) { fin >> material.specularPower; } // Read comment if (input.compare("#") == 0) { fin.ignore(256, '\n'); continue; } fin.get(); input = fin.peek(); //fin >> input; } m_materials.insert(pair<string, MaterialType>(newmtl, material)); } // Close file fin.close(); return true; } void Model::DivideIndexString(XMINT3 & index, string input) { char num[3][256]; int i = 0, j = 0; for(auto ch : input) { if(ch != '/') { num[j][i] = ch; ++i; } else { num[j][i] = '\0'; ++j; i = 0; } } num[j][i] = '\0'; index.x = atoi(num[0]); index.y = atoi(num[1]); index.z = atoi(num[2]); } void Model::ReleaseTexture() { if(m_texture) { m_texture->ShutDown(); delete m_texture; m_texture = nullptr; } } bool Model::WriteMesh() { // Write mtl file path m_mtlPath = "./data/model/" + m_objData.mtllib; // Write vertex information for(auto group : m_objData.groups) { int vIndex = 0, vtIndex = 0, vnIndex = 0; Mesh* mesh = new Mesh; // Write group name and material name mesh->m_name = group.name; mesh->m_usemtl = group.usemtl; unsigned int idxCnt = 0; // Write face information for(auto f : group.faces) { vector<int> iList({ 0,1,2 }); // If the face has 4 vertices if(f.vertices.size() == 4) { vector<int> sub({ 0,2,3 }); iList.insert(iList.end(), sub.begin(), sub.end()); } for(auto i : iList) { vIndex = f.vertices[i].x - 1; vtIndex = f.vertices[i].y - 1; vnIndex = f.vertices[i].z - 1; VertexDataType vd; // Write vertex vd.pos = m_objData.v[vIndex]; if(vtIndex < 0) // If no texture coordinate data vd.tex = { 0.0,0.0 }; else vd.tex = m_objData.vt[vtIndex]; vd.nor = m_objData.vn[vnIndex]; mesh->m_data.push_back(vd); // Write index mesh->m_indices.push_back(idxCnt); ++idxCnt; } } m_model.push_back(mesh); } if(m_model.empty()) return false; // Clear objData m_objData.v.clear(); m_objData.vn.clear(); m_objData.vt.clear(); m_objData.mtllib = ""; for(auto group : m_objData.groups) { for(auto face : group.faces) face.vertices.clear(); group.faces.clear(); } m_objData.groups.clear(); return true; } bool Model::LoadTexture(TCHAR * texPath) { bool result; // Create the texture object m_texture = new Texture; if(!m_texture) return false; result = m_texture->Initialize(texPath); if(!result) return false; return true; }
18.848948
107
0.624772
[ "mesh", "render", "object", "vector", "model" ]
e639dc7a8deabc1c7236896ee36d15db5edaeaa6
178
cc
C++
test/states/test_states.cc
gorobot/symctrl
ca76bcd2bfed8c5bef21545d735125aa6f3dd1dd
[ "MIT" ]
1
2018-04-17T20:01:43.000Z
2018-04-17T20:01:43.000Z
test/states/test_states.cc
gorobot/symctrl
ca76bcd2bfed8c5bef21545d735125aa6f3dd1dd
[ "MIT" ]
null
null
null
test/states/test_states.cc
gorobot/symctrl
ca76bcd2bfed8c5bef21545d735125aa6f3dd1dd
[ "MIT" ]
1
2018-05-13T03:50:07.000Z
2018-05-13T03:50:07.000Z
#include <catch2/catch.hpp> #include <symctrl/states/state.hpp> #include <symctrl/states/vector.hpp> using namespace symctrl; TEST_CASE("States: operations", "[states]") { }
16.181818
45
0.730337
[ "vector" ]
e63b817cbf02643c23a5d05a29ad481925504d2d
9,802
cpp
C++
module/src/main/cpp/main.cpp
musheng2020/Riru-ModuleFridaGadget
4e77bcf6194668ed37b7d50330c52e20292b360b
[ "MIT" ]
69
2021-10-21T03:18:58.000Z
2022-03-28T05:22:19.000Z
module/src/main/cpp/main.cpp
musheng2020/Riru-ModuleFridaGadget
4e77bcf6194668ed37b7d50330c52e20292b360b
[ "MIT" ]
6
2021-12-06T12:02:07.000Z
2022-03-30T11:34:33.000Z
module/src/main/cpp/main.cpp
musheng2020/Riru-ModuleFridaGadget
4e77bcf6194668ed37b7d50330c52e20292b360b
[ "MIT" ]
32
2021-09-14T06:23:17.000Z
2022-03-29T07:29:44.000Z
#include <jni.h> #include <sys/types.h> #include <riru.h> #include <malloc.h> #include <vector> #include <cstring> #include <dlfcn.h> #include "logging.h" #include "main.h" static char nice_process_name[256] = {0}; static char package_name[256] = {0}; static jint my_uid = 0; static bool isApp(int uid) { if (uid < 0) { return false; } int appId = uid % 100000; // limit only regular app, or strange situation will happen, such as zygote process not start (dead for no reason and leave no clues?) // https://android.googlesource.com/platform/frameworks/base/+/android-9.0.0_r8/core/java/android/os/UserHandle.java#151 return appId >= 10000 && appId <= 19999; } static void my_forkAndSpecializePre(JNIEnv *env, jint *uid, jstring *niceName, jstring *appDataDir) { //LOGI("Q_M xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx %s", "forkAndSpecializePre"); my_uid = *uid; if (!isApp(my_uid)) { return; } const char *tablePath = (env->GetStringUTFChars(*niceName, 0)); sprintf(nice_process_name, "%s", tablePath); delete tablePath; if (!appDataDir) { LOGI("Q_M forkAndSpecializePre appDataDir null"); return; } const char *app_data_dir = env->GetStringUTFChars(*appDataDir, NULL); if (app_data_dir == nullptr) { return; } //LOGI("Q_M xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx app_data_dir %s",app_data_dir); int user = 0; if (sscanf(app_data_dir, "/data/%*[^/]/%d/%s", &user, package_name) != 2) { if (sscanf(app_data_dir, "/data/%*[^/]/%s", package_name) != 1) { package_name[0] = '\0'; LOGI("Q_M can't parse %s", app_data_dir); } } env->ReleaseStringUTFChars(*appDataDir, app_data_dir); } static void my_forkAndSpecializePost(JNIEnv *env) { if (!isApp(my_uid)) { return; } // if (!strstr(nice_process_name, "com.smile.gifmaker") // && !strstr(nice_process_name, "com.ss.android.ugc.aweme") // && !strstr(nice_process_name, "com.xingin.xhs") // ) { // return; // } //http://www.cplusplus.com/reference/cstdio/fread/ 读取整个文件 char *white_list; //白名单的pkgName 最好以逗号或者分好分割开来 const char *filepath = "/data/local/tmp/_white_list.config"; FILE *fp = nullptr; fp = fopen(filepath, "r"); if (fp != nullptr) { fseek(fp, 0, SEEK_END); int fileLen = ftell(fp); white_list = (char *) malloc(sizeof(char) * (fileLen + 1)); fseek(fp, 0, SEEK_SET); // size_t count = fread(white_list, fileLen, sizeof(char), fp); size_t count = fread(white_list, 1, fileLen, fp); // LOGI("Q_M xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 白名单长度 %zu", count); white_list[count] = '\0'; fclose(fp); LOGI("Q_M xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 白名单:%s", white_list); } else { white_list = ""; } if (!strstr(white_list, package_name)) { return; } LOGI("Q_M xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx nice_process_name=%s, pkg=%s,uid=%d, isApp= %d", nice_process_name, package_name, my_uid, isApp(my_uid)); //添加这种机制,就可以提前设置进程名, 从而让frida 的gadget 能够识别到 jclass java_Process = env->FindClass("android/os/Process"); if (java_Process != nullptr && isApp(my_uid)) { jmethodID mtd_setArgV0 = env->GetStaticMethodID(java_Process, "setArgV0", "(Ljava/lang/String;)V"); jstring name = env->NewStringUTF(nice_process_name); env->CallStaticVoidMethod(java_Process, mtd_setArgV0, name); void *handle = dlopen(nextLoadSo, RTLD_LAZY); if (!handle) { // LOGE("%s",dlerror()); LOGE("Q_M %s loaded in libgadget 出错 %s", nice_process_name, dlerror()); } else { LOGI("Q_M xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-> %s 加载 ' %s ' 成功 ", nice_process_name, nextLoadSo); } } } static void forkAndSpecializePre( JNIEnv *env, jclass clazz, jint *uid, jint *gid, jintArray *gids, jint *runtimeFlags, jobjectArray *rlimits, jint *mountExternal, jstring *seInfo, jstring *niceName, jintArray *fdsToClose, jintArray *fdsToIgnore, jboolean *is_child_zygote, jstring *instructionSet, jstring *appDataDir, jboolean *isTopApp, jobjectArray *pkgDataInfoList, jobjectArray *whitelistedDataInfoList, jboolean *bindMountAppDataDirs, jboolean *bindMountAppStorageDirs) { my_forkAndSpecializePre(env, uid, niceName, appDataDir); } //很遗憾,执行这行代码的时候,还没有设置进程名字,导致,这个方法里面加载 frida gadget 的动态库获取不到进程名 // 只有执行完 Zygote.forkAndSpecialize 会在 handleChildProc 里面设置进程名,Process.setArgV0(parsedArgs.niceName); // libandroid_runtime.so //https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/jni/android_util_Process.cpp;l=593?q=setSwappiness&ss=android%2Fplatform%2Fsuperproject static void forkAndSpecializePost(JNIEnv *env, jclass clazz, jint res) { if (res == 0) { my_forkAndSpecializePost(env); } else { // in zygote process, res is child pid // don't print log here, see https://github.com/RikkaApps/Riru/blob/77adfd6a4a6a81bfd20569c910bc4854f2f84f5e/riru-core/jni/main/jni_native_method.cpp#L55-L66 } } static void specializeAppProcessPre( JNIEnv *env, jclass clazz, jint *uid, jint *gid, jintArray *gids, jint *runtimeFlags, jobjectArray *rlimits, jint *mountExternal, jstring *seInfo, jstring *niceName, jboolean *startChildZygote, jstring *instructionSet, jstring *appDataDir, jboolean *isTopApp, jobjectArray *pkgDataInfoList, jobjectArray *whitelistedDataInfoList, jboolean *bindMountAppDataDirs, jboolean *bindMountAppStorageDirs) { // added from Android 10, but disabled at least in Google Pixel devices my_forkAndSpecializePre(env, uid, niceName, appDataDir); } static void specializeAppProcessPost( JNIEnv *env, jclass clazz) { // added from Android 10, but disabled at least in Google Pixel devices my_forkAndSpecializePost(env); } static void forkSystemServerPre( JNIEnv *env, jclass clazz, uid_t *uid, gid_t *gid, jintArray *gids, jint *runtimeFlags, jobjectArray *rlimits, jlong *permittedCapabilities, jlong *effectiveCapabilities) { } static void forkSystemServerPost(JNIEnv *env, jclass clazz, jint res) { if (res == 0) { // in system server process } else { // in zygote process, res is child pid // don't print log here, see https://github.com/RikkaApps/Riru/blob/77adfd6a4a6a81bfd20569c910bc4854f2f84f5e/riru-core/jni/main/jni_native_method.cpp#L55-L66 } } static int shouldSkipUid(int uid) { // By default (the module does not provide this function in init), Riru will only call // module functions in "normal app processes" (10000 <= uid % 100000 <= 19999) // Provide this function so that the module can control if a specific uid should be skipped return false; } static void onModuleLoaded() { // called when the shared library of Riru core is loaded } extern "C" { int riru_api_version; RiruApiV9 *riru_api_v9; /* * Init will be called three times. * * The first time: * Returns the highest version number supported by both Riru and the module. * * arg: (int *) Riru's API version * returns: (int *) the highest possible API version * * The second time: * Returns the RiruModuleX struct created by the module. * (X is the return of the first call) * * arg: (RiruApiVX *) RiruApi strcut, this pointer can be saved for further use * returns: (RiruModuleX *) RiruModule strcut * * The third time: * Let the module to cleanup (such as RiruModuleX struct created before). * * arg: null * returns: (ignored) * */ void *init(void *arg) { static int step = 0; step += 1; LOGI("Q_M Riru-ModuleFridaGadget xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx %s", "init"); static void *_module; switch (step) { case 1: { auto core_max_api_version = *(int *) arg; riru_api_version = core_max_api_version <= RIRU_MODULE_API_VERSION ? core_max_api_version : RIRU_MODULE_API_VERSION; return &riru_api_version; } case 2: { switch (riru_api_version) { // RiruApiV10 and RiruModuleInfoV10 are equal to V9 case 10: case 9: { riru_api_v9 = (RiruApiV9 *) arg; auto module = (RiruModuleInfoV9 *) malloc(sizeof(RiruModuleInfoV9)); memset(module, 0, sizeof(RiruModuleInfoV9)); _module = module; module->supportHide = true; module->version = RIRU_MODULE_VERSION; module->versionName = RIRU_MODULE_VERSION_NAME; module->onModuleLoaded = onModuleLoaded; module->shouldSkipUid = shouldSkipUid; module->forkAndSpecializePre = forkAndSpecializePre; module->forkAndSpecializePost = forkAndSpecializePost; module->specializeAppProcessPre = specializeAppProcessPre; module->specializeAppProcessPost = specializeAppProcessPost; module->forkSystemServerPre = forkSystemServerPre; module->forkSystemServerPost = forkSystemServerPost; return module; } default: { return nullptr; } } } case 3: { free(_module); return nullptr; } default: { return nullptr; } } } }
35.643636
172
0.633646
[ "vector" ]
e63d86f6fbff4b0307f0c4f91c147919c3d82e4b
7,493
cc
C++
src/objects/float.cc
Cc618/Riddim
da79694b78f854a075632d36e1bd9fa70d744ef2
[ "MIT" ]
7
2021-06-20T13:40:28.000Z
2022-01-05T15:49:53.000Z
src/objects/float.cc
Cc618/Riddim
da79694b78f854a075632d36e1bd9fa70d744ef2
[ "MIT" ]
null
null
null
src/objects/float.cc
Cc618/Riddim
da79694b78f854a075632d36e1bd9fa70d744ef2
[ "MIT" ]
1
2021-06-27T12:53:20.000Z
2021-06-27T12:53:20.000Z
#include "float.hh" #include "bool.hh" #include "error.hh" #include "hash.hh" #include "int.hh" #include "map.hh" #include "str.hh" #include "vec.hh" #include "program.hh" #include <iomanip> #include <sstream> // Avoid typedef conflicts #define float_t cmath_float_t #include <cmath> #undef float_t using namespace std; #define OUT_PRECISION 16 Float *float_inf = nullptr; Float *float_nan = nullptr; float_t to_float(const str_t &fn_name, Object *o) { if (o->type == Float::class_type) { return reinterpret_cast<Float *>(o)->data; } else if (o->type == Int::class_type) { return reinterpret_cast<Int *>(o)->data; } throw_fmt(TypeError, (fn_name + " : Invalid argument, must be a number").c_str()); return 0; } Type *Float::class_type = nullptr; Object *Float::zero = nullptr; Object *Float::one = nullptr; Float::Float(const float_t &data) : Object(Float::class_type), data(data) {} void Float::init_class_type() { class_type = new (nothrow) Type("Float"); if (!class_type) { THROW_MEMORY_ERROR; return; } // @new class_type->constructor = [](Object *self, Object *args, Object *kwargs) -> Object * { INIT_METHOD(Object, "Float"); CHECK_ARGSLEN(1, "Float"); CHECK_NOKWARGS("Float"); float_t data; if (args_data[0]->type == Int::class_type) { data = reinterpret_cast<Int *>(args_data[0])->data; } else if (args_data[0]->type == Float::class_type) { data = reinterpret_cast<Float *>(args_data[0])->data; } else if (args_data[0]->type == Bool::class_type) { data = reinterpret_cast<Bool *>(args_data[0])->data; } else if (args_data[0]->type == Str::class_type) { auto val = str_to_float(reinterpret_cast<Str *>(args_data[0])->data); if (val) { data = val.value(); } else { throw_fmt(ArithmeticError, "Float@new{data: Str} : Invalid format"); return nullptr; } } else { throw_fmt( TypeError, "Float@new{data} : Data must be either Float, Int or Str"); return nullptr; } auto result = new (nothrow) Float(data); // Dispatch error if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @add class_type->fn_add = [](Object *self, Object *o) -> Object * { auto me = reinterpret_cast<Float *>(self); auto val = to_float("Float.@add", o); if (on_error()) { return nullptr; } auto result = new (nothrow) Float(me->data + val); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @cmp class_type->fn_cmp = [](Object *self, Object *o) -> Object * { auto me = reinterpret_cast<Float *>(self); auto val = to_float("Float.@cmp", o); int_t threeway; // Incompatible types : not equal if (on_error()) { clear_error(); threeway = -1; } else { threeway = me->data > val ? 1 : me->data < val ? -1 : 0; } auto result = new (nothrow) Int(threeway); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @copy class_type->fn_copy = [](Object *self) -> Object * { auto me = reinterpret_cast<Float *>(self); auto result = new (nothrow) Float(me->data); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @div class_type->fn_div = [](Object *self, Object *o) -> Object * { auto me = reinterpret_cast<Float *>(self); auto val = to_float("Float.@div", o); if (on_error()) { return nullptr; } if (val == 0.0) { THROW_ARITHMETIC_ERROR("/", "Division by 0"); return nullptr; } auto result = new (nothrow) Float(me->data / val); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @hash class_type->fn_hash = [](Object *self) -> Object * { auto me = reinterpret_cast<Float *>(self); auto hdata = reinterpret_cast<size_t *>(&me->data); auto result = new (nothrow) Int(hash_ptr(hdata)); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @mod class_type->fn_mod = [](Object *self, Object *o) -> Object * { auto me = reinterpret_cast<Float *>(self); auto val = to_float("Float.@mod", o); if (on_error()) { return nullptr; } if (val == 0.0) { THROW_ARITHMETIC_ERROR("%", "Modulo by 0"); return nullptr; } auto result = new (nothrow) Float(fmod(me->data, val)); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @mul class_type->fn_mul = [](Object *self, Object *o) -> Object * { auto me = reinterpret_cast<Float *>(self); auto val = to_float("Float.@mul", o); if (on_error()) { return nullptr; } auto result = new (nothrow) Float(me->data * val); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @neg class_type->fn_neg = [](Object *self) -> Object * { auto me = reinterpret_cast<Float *>(self); auto result = new (nothrow) Float(-me->data); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; // @str class_type->fn_str = [](Object *self) -> Object * { auto me = reinterpret_cast<Float *>(self); std::setprecision(OUT_PRECISION); std::ostringstream ss; ss << me->data; std::string repr(ss.str()); auto result = Str::New(repr); if (!result) { return nullptr; } return result; }; // @sub class_type->fn_sub = [](Object *self, Object *o) -> Object * { auto me = reinterpret_cast<Float *>(self); auto val = to_float("Float.@sub", o); if (on_error()) { return nullptr; } auto result = new (nothrow) Float(me->data - val); if (!result) { THROW_MEMORY_ERROR; return nullptr; } return result; }; } void Float::init_class_objects() { zero = new (nothrow) Float(0); if (!zero) { THROW_MEMORY_ERROR; return; } one = new (nothrow) Float(1); if (!one) { THROW_MEMORY_ERROR; return; } float_inf = new (nothrow) Float(INFINITY); if (!float_inf) { THROW_MEMORY_ERROR; return; } float_nan = new (nothrow) Float(NAN); if (!float_nan) { THROW_MEMORY_ERROR; return; } Program::add_global(zero); Program::add_global(one); Program::add_global(float_inf); Program::add_global(float_nan); }
21.286932
76
0.513546
[ "object" ]
e6467ebd140c0565da6f20fa880da2da4618c004
8,997
cpp
C++
src/Lib/rfc5285/RtpHeaderExtension.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Lib/rfc5285/RtpHeaderExtension.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Lib/rfc5285/RtpHeaderExtension.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "CorePch.h" #include <rtp++/rfc5285/RtpHeaderExtension.h> #include <cpputil/Utility.h> #define COMPONENT_LOG_LEVEL 10 namespace rtp_plus_plus { namespace rfc5285 { RtpHeaderExtension::RtpHeaderExtension(uint16_t uiProfileDefined, RtpHeaderExtensionType eType, uint16_t uiExtensionLengthInWords, uint8_t uiAppBits) :m_eType(eType), m_uiProfileDefined(uiProfileDefined), m_uiExtensionLengthInWords(uiExtensionLengthInWords), m_uiAppBits(uiAppBits), m_uiPadding(0) { } RtpHeaderExtension::~RtpHeaderExtension() { } void RtpHeaderExtension::clear() { m_vHeaderExtensions.clear(); } bool RtpHeaderExtension::containsExtensions() const { return !empty(); } bool RtpHeaderExtension::empty() const { return m_vHeaderExtensions.empty(); } std::size_t RtpHeaderExtension::getHeaderExtensionCount() const { return m_vHeaderExtensions.size(); } const HeaderExtensionElement& RtpHeaderExtension::getHeaderExtensions(size_t index) const { return m_vHeaderExtensions.at(index); } void RtpHeaderExtension::addHeaderExtensions(const HeaderExtensionElement& headerExtension) { m_vHeaderExtensions.push_back(headerExtension); } const std::vector<HeaderExtensionElement>& RtpHeaderExtension::getHeaderExtensions() const { return m_vHeaderExtensions; } uint32_t RtpHeaderExtension::removeHeaderExtension(const uint32_t uiId) { for (auto it = m_vHeaderExtensions.begin(); it != m_vHeaderExtensions.end(); ++it) { if (it->getId() == uiId) { m_vHeaderExtensions.erase(it); return 1; } } return 0; } uint32_t RtpHeaderExtension::getSize() const { if (m_uiExtensionLengthInWords == 0) calculateExtensionProperties(); // if there are no header extensions, then don't count the 4 bytes of the // header extension header if (m_uiExtensionLengthInWords == 0) { return 0; } return rfc3550::MIN_EXTENSION_HEADER_SIZE + (4* m_uiExtensionLengthInWords); } void RtpHeaderExtension::calculateExtensionProperties() const { VLOG(COMPONENT_LOG_LEVEL) << "RtpHeaderExtension::calculateExtensionProperties"; // first check if there are any elements with a length greater than 16 // if not, we will use the one byte header extension uint32_t uiTotalBytes = 0; for (HeaderExtensionElement element : m_vHeaderExtensions) { VLOG(COMPONENT_LOG_LEVEL) << "Element length: " << element.getDataLength(); uiTotalBytes += element.getDataLength(); if (element.getDataLength() > 16) { VLOG(COMPONENT_LOG_LEVEL) << "Using two byte extension header: " << element.getDataLength(); m_eType = TWO_BYTE_HEADER; } } switch (m_eType) { case ONE_BYTE_HEADER: { m_uiProfileDefined = 0xBEDE; uiTotalBytes += m_vHeaderExtensions.size(); break; } case TWO_BYTE_HEADER: { m_uiProfileDefined = (0x0100 << 4) | (m_uiAppBits & 0x0F); uiTotalBytes += 2 * m_vHeaderExtensions.size(); break; } default: { assert(false); } } VLOG(COMPONENT_LOG_LEVEL) << "Profile defined: " << m_uiProfileDefined << "(" << hex(m_uiProfileDefined) << ") Total bytes: " << uiTotalBytes; uint32_t uiRem = uiTotalBytes % 4; if ( uiRem == 0) { m_uiExtensionLengthInWords = uiTotalBytes/4; } else { m_uiPadding = 4 - uiRem; m_uiExtensionLengthInWords = uiTotalBytes/4 + 1; } } void RtpHeaderExtension::writeExtensionData(OBitStream& ob) const { // this also sets m_eType calculateExtensionProperties(); ob.write( m_uiProfileDefined, 16); ob.write( m_uiExtensionLengthInWords, 16); switch (m_eType) { case ONE_BYTE_HEADER: { for (size_t i = 0; i < m_vHeaderExtensions.size(); ++i) { const HeaderExtensionElement& header = m_vHeaderExtensions[i]; VLOG(COMPONENT_LOG_LEVEL) << "Writing extension element id " << header.getId() << " len: " << header.getDataLength(); ob.write(header.getId(), 4); // NOTE that this fields stores length - 1 in one byte headers ob.write(header.getDataLength() - 1, 4); const uint8_t* pData = header.getExtensionData(); ob.writeBytes(pData, header.getDataLength()); } break; } case TWO_BYTE_HEADER: { for (size_t i = 0; i < m_vHeaderExtensions.size(); ++i) { const HeaderExtensionElement& header = m_vHeaderExtensions[i]; VLOG(COMPONENT_LOG_LEVEL) << "Writing extension element id " << header.getId() << " len: " << header.getDataLength(); ob.write(header.getId(), 8); // NOTE that this fields stores length - 1 in one byte headers ob.write(header.getDataLength(), 8); const uint8_t* pData = header.getExtensionData(); ob.writeBytes(pData, header.getDataLength()); } break; } } // padding for (size_t i = 0; i < m_uiPadding; ++i) { ob.write(0, 8); } } void RtpHeaderExtension::readExtensionData(IBitStream& ib) { bool res = ib.read(m_uiProfileDefined, 16); assert(res); res = ib.read(m_uiExtensionLengthInWords, 16); assert(res); VLOG(COMPONENT_LOG_LEVEL) << "read profile defined " << m_uiProfileDefined << "(" << hex(m_uiProfileDefined) << ") length in words: " << m_uiExtensionLengthInWords; if (m_uiProfileDefined == PROFILE_ONE_BYTE_HEADER) { int32_t iTotalBytesToRead = m_uiExtensionLengthInWords * 4; while (iTotalBytesToRead > 0) { uint32_t uiId = 0; uint32_t uiLength = 0; unsigned char data[HeaderExtensionElement::MAX_HDR_EXT_SIZE]; res = ib.read(uiId, 4); assert(res); res = ib.read(uiLength, 4); assert(res); --iTotalBytesToRead; if ( uiId == 15) { // invalid according to rfc5285: skip rest of headers LOG(WARNING) << " Invalid id for one byte extension header: " << uiId << " skipping rest of extension header: " << iTotalBytesToRead << " bytes"; res = ib.skipBytes(iTotalBytesToRead); assert(res); break; } else if (uiId == 0 && uiLength == 0) { // this is a padding byte which we should just ignore continue; } VLOG(COMPONENT_LOG_LEVEL) << "Read extension element id " << uiId << " len: " << uiLength + 1; // sanity check: one byte header extension length = len field + 1 if (uiLength + 1 > (uint32_t) iTotalBytesToRead) { LOG(WARNING) << " Error parsing one byte extension header: Length " << uiLength << " larger than bytes remaining " << iTotalBytesToRead << " skipping rest of extension header: " << iTotalBytesToRead << " bytes"; res = ib.skipBytes(iTotalBytesToRead); assert(res); break; } uint8_t* pData = (uint8_t*)data; res = ib.readBytes(pData, uiLength + 1); assert(res); HeaderExtensionElement headerExtension(uiId, uiLength + 1, data); m_vHeaderExtensions.push_back(headerExtension); iTotalBytesToRead -= (uiLength + 1); } } else if ((m_uiProfileDefined >> 4) == 0x100) { int32_t iTotalBytesToRead = m_uiExtensionLengthInWords * 4; VLOG(COMPONENT_LOG_LEVEL) << "Parsing two byte header extensions: Total bytes: " << iTotalBytesToRead; while (iTotalBytesToRead > 0) { VLOG(COMPONENT_LOG_LEVEL) << "bytes left: " << iTotalBytesToRead; uint32_t uiId = 0; uint32_t uiLength = 0; unsigned char data[HeaderExtensionElement::MAX_HDR_EXT_SIZE]; res = ib.read(uiId, 8); assert(res); --iTotalBytesToRead; if (iTotalBytesToRead == 0) { if (uiId != 0) { LOG(WARNING) << "Malformed extension, this should be a padding byte but has value " << uiId; } continue; } res = ib.read(uiLength, 8); assert(res); --iTotalBytesToRead; if (uiId == 0 && uiLength == 0) { // this is a padding byte which we should just ignore continue; } VLOG(COMPONENT_LOG_LEVEL) << "Read extension element id " << uiId << " len: " << uiLength; if (uiLength > (uint32_t) iTotalBytesToRead) { LOG(WARNING) << " Error parsing two byte extension header: Length " << uiLength << " larger than bytes remaining " << iTotalBytesToRead << " skipping rest of extension header: " << iTotalBytesToRead << " bytes"; res = ib.skipBytes(iTotalBytesToRead); assert(res); break; } uint8_t* pData = (uint8_t*)data; res = ib.readBytes(pData, uiLength); assert(res); HeaderExtensionElement headerExtension(uiId, uiLength, data); m_vHeaderExtensions.push_back(headerExtension); iTotalBytesToRead -= uiLength; } } else { // for now we'll just skip the header LOG(WARNING) << " Unsupported header extension profile: " << m_uiProfileDefined << "(" << hex(m_uiProfileDefined) << ") skipping extension header: " << m_uiExtensionLengthInWords << " words"; res = ib.skipBytes(m_uiExtensionLengthInWords * 4); assert(res); } } } // rfc5285 } // rtp_plus_plus
31.348432
219
0.661332
[ "vector" ]
e64bfda271903dc2bd8cc9b5f48f966f6876917f
1,069
hh
C++
Testcase4-Application-breakdown/online-compiling/src/net/redis.hh
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
129
2020-08-09T12:02:30.000Z
2022-03-31T15:26:03.000Z
Testcase4-Application-breakdown/online-compiling/src/net/redis.hh
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
11
2020-09-17T09:42:07.000Z
2022-03-30T19:05:38.000Z
Testcase4-Application-breakdown/online-compiling/src/net/redis.hh
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
22
2020-08-20T06:59:24.000Z
2022-03-18T21:00:05.000Z
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ #ifndef NET_REDIS_HH #define NET_REDIS_HH #include <vector> #include <string> #include <functional> #include "net/requests.hh" struct RedisClientConfig { std::string ip { "0.0.0.0" }; uint16_t port { 6379 }; std::string username {}; std::string password {}; size_t max_threads { 32 }; size_t max_batch_size { 32 }; }; class Redis { private: RedisClientConfig config_; public: Redis( const RedisClientConfig & config ) : config_( config ) {} void upload_files( const std::vector<storage::PutRequest> & upload_requests, const std::function<void( const storage::PutRequest & )> & success_callback = []( const storage::PutRequest & ){} ); void download_files( const std::vector<storage::GetRequest> & download_requests, const std::function<void( const storage::GetRequest & )> & success_callback = []( const storage::GetRequest & ){} ); }; #endif /* NET_REDIS_HH */
24.295455
98
0.626754
[ "vector" ]
e651dfc2aa8b0091c5d22be75a7f4a3275ac7c7f
6,765
cpp
C++
New Source/Hgine/C++/Classes/3D/Mesh/Mesh.cpp
survivalizeed/CppRawEnginePrototype
2aa87c4b09771ea252583cc0c6f6566b90f1bead
[ "MIT" ]
5
2021-04-18T11:07:54.000Z
2021-06-11T08:16:29.000Z
New Source/Hgine/C++/Classes/3D/Mesh/Mesh.cpp
survivalizeed/CppRawEnginePrototype
2aa87c4b09771ea252583cc0c6f6566b90f1bead
[ "MIT" ]
null
null
null
New Source/Hgine/C++/Classes/3D/Mesh/Mesh.cpp
survivalizeed/CppRawEnginePrototype
2aa87c4b09771ea252583cc0c6f6566b90f1bead
[ "MIT" ]
2
2021-02-25T08:48:33.000Z
2021-03-02T12:20:24.000Z
#include "Mesh.h" sur::Mesh::Mesh(const std::string& file, Vec3f position, Color color, Vec3f origin, const Mat3x3& projection) { this->position = position; this->color = color; this->origin = origin; this->projection = projection; auto replacestr = [](std::string& input, char from, char to) { for (i32 i = 0; i < input.size(); ++i) { if (input[i] == from) input[i] = to; } }; auto round = [=](f32 n) -> f32 { f32 pow_10 = pow(10.0f, (f32)3); return ::round(n * pow_10) / pow_10; }; std::ifstream f(file); #ifdef _DEBUG if (!f) { Error(("Unable to read file: " + file).c_str()); } #endif std::vector<sur::Vec3f> verts; std::string buf; std::stringstream ss; std::string word; std::vector<std::string> words; bool once = false; ss << f.rdbuf(); buf = ss.str(); ss.str(""); replacestr(buf, '\n', ' '); ss << buf; while (std::getline(ss, word, ' ')) { if (word == "" || word == " ") continue; words.push_back(word); } for (i32 i = 0; i < words.size(); ++i) { if (words[i] == "v") verts.push_back(sur::Vec3f(round(stof(words[i + 1])), round(stof(words[i + 2])), round(stof(words[i + 3])))); if (words[i] == "f") { std::string container[3]; for (i32 c = 1; c <= 3; ++c) { for (i32 j = 0;; ++j) { if (words[i + c][j] == '/') break; else container[c - 1] += words[i + c][j]; } } if (!once) { for (i32 a = 0; a < 3; ++a) { std::vector<f32> values; for (i32 c = 0; c < verts.size(); ++c) { if (a == 0) values.push_back(verts[c].x); if (a == 1) values.push_back(verts[c].y); if (a == 2) values.push_back(verts[c].z); } f32 min = *std::min_element(values.begin(), values.end()); for (i32 c = 0; c < verts.size(); ++c) { if (a == 0) verts[c].x += -min + 1; if (a == 1) verts[c].y += -min + 1; if (a == 2) verts[c].z += -min + 1; } } for (auto& iter : verts) { iter.x *= 100; iter.y *= 100; iter.z *= 100; } once = true; } triCon.push_back( { verts[stoi(container[0]) - 1], verts[stoi(container[1]) - 1], verts[stoi(container[2]) - 1], } ); } } } void sur::Mesh::Rotate(Dimension dimension, i32 angle) { switch (dimension) { case Dimension::X: angleX = angle; break; case Dimension::Y: angleY = angle; break; case Dimension::Z: angleZ = angle; break; } } void sur::Mesh::Move(Vec3f direction) { origin = origin + direction; for (auto& iter : triCon) { iter.a = iter.a + direction; iter.b = iter.b + direction; iter.c = iter.c + direction; } } void sur::Mesh::Bind(bool render, bool wireframe, i32 perspectiveThreshold, i32 clipping) { struct TrianglePosColContainer { Vec3f a, b, c; Color color; }; std::vector<TrianglePosColContainer> renderableTris; std::vector<Vec3f> transformed; for (auto& iter : triCon) { for (i32 i = 0; i < 3; ++i) { Vec3f tmp{}; if (i == 0) tmp = iter.a - origin; if (i == 1) tmp = iter.b - origin; if (i == 2) tmp = iter.c - origin + position; tmp = sur::RotateX(tmp, origin - origin, angleX); tmp = sur::RotateY(tmp, origin - origin, angleY); tmp = sur::RotateZ(tmp, origin - origin, angleZ); if (perspectiveThreshold != 0) { f32 z = 0; if (tmp.z + origin.z == 0) z = 1; else z = 1 / ((tmp.z + origin.z) / perspectiveThreshold); projection ( z, 0, 0, 0, z, 0, 0, 0, 1 ); } Vec3f projectedPoint = projection.multiplyWithVector(tmp); transformed.push_back(projectedPoint + origin); } } for (i32 i = 0; i < transformed.size(); i += 3) { Vec3f normal{}, line1{}, line2{}; line1 = transformed[i + 1] - transformed[i]; line2 = transformed[i + 2] - transformed[i]; normal = line1.cross(line2); normal.normalize(); Vec3f light(0, 0, 1); f32 dp = -light.dot(normal); dp = 1 - dp; if (normal.z > 0 && transformed[i].z > clipping && transformed[i + 1].z > clipping && transformed[i + 2].z > clipping) { renderableTris.push_back( { // GetRValue and GetBValue have been changed. Idk why I needed to do so :| transformed[i], transformed[i + 1], transformed[i + 2], Color(u32(GetBValue(color) * dp), u32(GetGValue(color) * dp), u32(GetRValue(color) * dp)) } ); } } std::sort(renderableTris.begin(), renderableTris.end(), [](TrianglePosColContainer& t1, TrianglePosColContainer& t2) { f32 z1 = (t1.a.z + t1.b.z + t1.c.z) / 3.f; f32 z2 = (t2.a.z + t2.b.z + t2.c.z) / 3.f; return z1 > z2; } ); if (wireframe) { for (auto& iter : renderableTris) { algorithm::DrawTriangleWire( STA(Vec2((i32)iter.a.x, (i32)iter.a.y)), STA(Vec2((i32)iter.b.x, (i32)iter.b.y)), STA(Vec2((i32)iter.c.x, (i32)iter.c.y)), iter.color ); } } else { for (auto& iter : renderableTris) { algorithm::DrawTriangle( STA(Vec2((i32)iter.a.x, (i32)iter.a.y)), STA(Vec2((i32)iter.b.x, (i32)iter.b.y)), STA(Vec2((i32)iter.c.x, (i32)iter.c.y)), iter.color ); } } }
31.760563
166
0.416999
[ "mesh", "render", "vector" ]
e658778419a4316ab206014fcc10bd2b88ae4b1f
567
cpp
C++
cpp/WordBreak.cpp
sizeoftank/leetcode-solutions
ccf27cdf4eeb816175c51ac67a5d79c8cbfd5beb
[ "MIT" ]
null
null
null
cpp/WordBreak.cpp
sizeoftank/leetcode-solutions
ccf27cdf4eeb816175c51ac67a5d79c8cbfd5beb
[ "MIT" ]
null
null
null
cpp/WordBreak.cpp
sizeoftank/leetcode-solutions
ccf27cdf4eeb816175c51ac67a5d79c8cbfd5beb
[ "MIT" ]
null
null
null
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { vector<bool> dp(s.size()+1); set<int> wordsize; for (auto it : dict) wordsize.insert(it.size()); dp[0] = true; for (int i = 0; i<s.size(); i++){ for (auto k : wordsize){ if (i+1-k >= 0 && dp[i+1-k] == true){ if (dict.find(s.substr(i+1-k, k)) != dict.end()) dp[i+1] = dp[i+1-k]; } } } return dp[s.size()]; } };
28.35
68
0.405644
[ "vector" ]
e65ed833bbbfe521449d0dc38a5348bdbe509ab2
40,000
cpp
C++
samples/mha_sample.cpp
azrael417/cudnn-frontend
704a61f7a3c16bcc52acfa9c4587b2df7703a29c
[ "MIT" ]
null
null
null
samples/mha_sample.cpp
azrael417/cudnn-frontend
704a61f7a3c16bcc52acfa9c4587b2df7703a29c
[ "MIT" ]
null
null
null
samples/mha_sample.cpp
azrael417/cudnn-frontend
704a61f7a3c16bcc52acfa9c4587b2df7703a29c
[ "MIT" ]
null
null
null
/* * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * 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 "cudnn_frontend.h" #include "cudnn_frontend_utils.h" #include "error_util.h" #include "mha_sample.h" using namespace cudnn_frontend; ExecutionPlan_v8 get_plan_from_heuristics(OperationGraph_v8 &opGraph, cudnnHandle_t handle) { auto heuristics = cudnn_frontend::EngineHeuristicsBuilder() .setOperationGraph(opGraph) .setHeurMode(CUDNN_HEUR_MODE_INSTANT) .build(); auto& engine_config = heuristics.getEngineConfig(heuristics.getEngineConfigCount()); auto plan_builder = [&]() -> cudnn_frontend::ExecutionPlan { for (auto &ecfg : engine_config) { try { auto plan = cudnn_frontend::ExecutionPlanBuilder() .setHandle(handle) .setEngineConfig(ecfg, opGraph.getTag()) .build(); return plan; } catch (cudnn_frontend::cudnnException &e) { continue; } } return cudnn_frontend::ExecutionPlanBuilder() .setHandle(handle) .setEngineConfig(engine_config[0], opGraph.getTag()) .build(); }; return std::move(plan_builder()); } class MHAParams { public: friend class MHA_intputProjLayer; friend class MHA_outputProjLayer; friend class MHA_attentionLayer; friend class MHAParamsBuilder; MHAParams(MHAParams &&from) = default; MHAParams & operator= (MHAParams &&from) = default; ~MHAParams() = default; private: int64_t inputSize = 0; int64_t outputSize = 0; int64_t headSize = 0; int64_t numHeads = 1; int64_t seqLength = 1; int64_t batchSize = 1; cudnnDataType_t dataType = CUDNN_DATA_HALF; cudnnDataType_t mathPrec = CUDNN_DATA_FLOAT; MHAParams() = default; MHAParams(MHAParams const &) = delete; MHAParams & operator=(MHAParams const &) = delete; }; /// /// MHAParamsBuilder Class /// Helper class used to build MHAParams class class MHAParamsBuilder { public: /** @defgroup MHAParamsBuilder * Set individual property of MHAParams class * @{ */ //! Set input vector size auto setInputSize(int64_t inputSize_) -> MHAParamsBuilder & { mhaParams.inputSize = inputSize_; return *this; } /** @} */ //! Set output vector size auto setOutputSize(int64_t outputSize_) -> MHAParamsBuilder & { mhaParams.outputSize = outputSize_; return *this; } /** @} */ //! Set attention head size auto setHeadSize(int64_t headSize_) -> MHAParamsBuilder & { mhaParams.headSize = headSize_; return *this; } /** @} */ //! Set number of heads auto setNumHeads(int64_t numHeads_) -> MHAParamsBuilder & { mhaParams.numHeads = numHeads_; return *this; } /** @} */ //! Set input sequence length auto setSeqLength(int64_t seqLength_) -> MHAParamsBuilder & { mhaParams.seqLength = seqLength_; return *this; } /** @} */ //! Set input batch size auto setBatchSize(int64_t batchSize_) -> MHAParamsBuilder & { mhaParams.batchSize = batchSize_; return *this; } /** @} */ //! Set input data type auto setDataType(cudnnDataType_t dataType_) -> MHAParamsBuilder & { mhaParams.dataType = dataType_; return *this; } /** @} */ //! Set math precision auto setMathPrec(cudnnDataType_t mathPrec_) -> MHAParamsBuilder & { mhaParams.mathPrec = mathPrec_; return *this; } /** @} */ //! constructs the MHAParams by calling the cudnn API //! Throws the appropriate error message MHAParams && build() { if (mhaParams.inputSize <= 0) { set_error_and_throw_exception( nullptr, CUDNN_STATUS_BAD_PARAM, "MHA: Check and Set the input vector size to valid value"); return std::move(mhaParams); } if (mhaParams.outputSize <= 0) { set_error_and_throw_exception( nullptr, CUDNN_STATUS_BAD_PARAM, "MHA: Check and Set the output vector size to valid value"); return std::move(mhaParams); } if (mhaParams.headSize <= 0) { set_error_and_throw_exception( nullptr, CUDNN_STATUS_BAD_PARAM, "MHA: Check and Set the head size to valid value"); return std::move(mhaParams); } return std::move(mhaParams); } explicit MHAParamsBuilder() = default; ~MHAParamsBuilder() = default; MHAParamsBuilder(MHAParamsBuilder &&) = delete; MHAParamsBuilder(MHAParamsBuilder const &) = delete; MHAParamsBuilder & operator=(MHAParamsBuilder const &) = delete; private: MHAParams mhaParams; }; class MHA_intputProjLayer { public: MHA_intputProjLayer(MHA_intputProjLayer &&from) = default; MHA_intputProjLayer & operator= (MHA_intputProjLayer &&from) = default; ~MHA_intputProjLayer() = default; MHA_intputProjLayer(cudnnHandle_t handle, MHAParams &mhaParams) { const int64_t inputSize = mhaParams.inputSize; const int64_t outputSize = mhaParams.inputSize; const int64_t headSize = mhaParams.headSize; const int64_t numHeads = mhaParams.numHeads; const int64_t seqLength = mhaParams.seqLength; const int64_t batchSize = mhaParams.batchSize; const cudnnDataType_t dataType = mhaParams.dataType; const cudnnDataType_t mathPrec = mhaParams.mathPrec; const int64_t wDim[3] = {3, inputSize, headSize * numHeads}; const int64_t wStride[3] = {headSize * numHeads * inputSize, headSize * numHeads, 1}; auto wMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, wDim) .setStrides(3, wStride) .setId('W') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for input matrix const int64_t iDim[3] = {1, seqLength * batchSize, inputSize}; const int64_t iStride[3] = {inputSize * seqLength * batchSize, inputSize, 1}; auto iMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, iDim) .setStrides(3, iStride) .setId('i') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for QKVBias Matrix const int64_t bDim[3] = {3, 1, headSize * numHeads}; const int64_t bStride[3] = {headSize * numHeads, headSize * numHeads, 1}; auto bTensor = cudnn_frontend::TensorBuilder() .setDim(3, bDim) .setStrides(3, bStride) .setId('b') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptors for embeddings Q, K, V const int64_t oDim[3] = {3, seqLength * batchSize, headSize * numHeads}; const int64_t oStride[3] = {headSize * numHeads * seqLength * batchSize, headSize * numHeads, 1}; auto beforeBiasMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, oDim) .setStrides(3, oStride) .setId('a') .setAlignment(16) .setVirtual() .setDataType(CUDNN_DATA_FLOAT) .build(); auto oMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, oDim) .setStrides(3, oStride) .setId('o') .setAlignment(16) .setDataType(dataType) .build(); // Define the matmul descriptor for Q, K, V = W * Input auto matmulDesc = cudnn_frontend::MatMulDescBuilder() .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Define the Bias descriptor for Q, K, V = W * Input + Bias auto biasDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Create a matmul Node for Q, K, V = W * Input auto matmulOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR) .setaMatDesc(iMatrixTensor) .setbMatDesc(wMatrixTensor) .setcMatDesc(beforeBiasMatrixTensor) .setmatmulDesc(matmulDesc) .build(); // Create a Bias Node for Q, K, V = W * Input + Bias auto biasOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(matmulOp.getOutputTensor()) .setbDesc(bTensor) .setyDesc(oMatrixTensor) .setpwDesc(biasDesc) .build(); // Create an Operation Graphs std::array<cudnn_frontend::Operation const*, 2> ops = {&matmulOp, &biasOp}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle) .setOperationGraph(ops.size(), ops.data()) .build(); auto plan = std::move(get_plan_from_heuristics(opGraph, handle)); inputProjLayerPlan = std::make_shared<cudnn_frontend::ExecutionPlan>(std::move(plan)); std::cout << "[INFO] Execution Plan tag for input projection layer: " << inputProjLayerPlan->getTag() << std::endl; }; cudnnStatus_t execute(cudnnHandle_t handle, void const *devPtrIn, void const *devPtrWeight, void const *devPtrBias, void *devPtrQKV) { void* data_ptrs[] = {const_cast<void*>(devPtrIn), const_cast<void*>(devPtrWeight), const_cast<void*>(devPtrBias), devPtrQKV}; int64_t uids[] = {'i', 'W', 'b', 'o'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setDataPointers(4, data_ptrs) .setUids(4, uids) .build(); return cudnnBackendExecute(handle, inputProjLayerPlan->get_raw_desc(), variantPack.get_raw_desc()); }; private: std::shared_ptr<cudnn_frontend::ExecutionPlan> inputProjLayerPlan; MHA_intputProjLayer() = delete; MHA_intputProjLayer(MHA_intputProjLayer const &) = delete; MHA_intputProjLayer & operator=(MHA_intputProjLayer const &) = delete; }; class MHA_outputProjLayer { public: MHA_outputProjLayer(MHA_outputProjLayer &&from) = default; MHA_outputProjLayer & operator= (MHA_outputProjLayer &&from) = default; ~MHA_outputProjLayer() = default; MHA_outputProjLayer(cudnnHandle_t handle, MHAParams &mhaParams) { const int64_t inputSize = mhaParams.inputSize; const int64_t outputSize = mhaParams.inputSize; const int64_t headSize = mhaParams.headSize; const int64_t numHeads = mhaParams.numHeads; const int64_t seqLength = mhaParams.seqLength; const int64_t batchSize = mhaParams.batchSize; const cudnnDataType_t dataType = mhaParams.dataType; const cudnnDataType_t mathPrec = mhaParams.mathPrec; // Create tensor descriptor for OWeight Matrix const int64_t wDim[3] = {1, headSize * numHeads, outputSize}; const int64_t wStride[3] = {outputSize * headSize * numHeads, outputSize, 1}; auto wMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, wDim) .setStrides(3, wStride) .setId('W') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for Y^T matrix const int64_t iDim[3] = {1, seqLength * batchSize, headSize * numHeads}; const int64_t iStride[3] = {seqLength * batchSize * headSize * numHeads, headSize * numHeads, 1}; auto iMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, iDim) .setStrides(3, iStride) .setId('i') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for QKVBias Matrix const int64_t bDim[3] = {1, 1, outputSize}; const int64_t bStride[3] = {outputSize, outputSize, 1}; auto bTensor = cudnn_frontend::TensorBuilder() .setDim(3, bDim) .setStrides(3, bStride) .setId('b') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for Output before bias add const int64_t oDim[3] = {1, seqLength * batchSize, outputSize}; const int64_t oStride[3] = {seqLength * batchSize * outputSize, outputSize, 1}; auto beforeBiasMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, oDim) .setStrides(3, oStride) .setId('a') .setAlignment(16) .setVirtual() .setDataType(CUDNN_DATA_FLOAT) .build(); auto oMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, oDim) .setStrides(3, oStride) .setId('o') .setAlignment(16) .setDataType(dataType) .build(); // Define the matmul descriptor auto matmulDesc = cudnn_frontend::MatMulDescBuilder() .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Define the Bias descriptor auto biasDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Create a matmul Node auto matmulOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR) .setaMatDesc(iMatrixTensor) .setbMatDesc(wMatrixTensor) .setcMatDesc(beforeBiasMatrixTensor) .setmatmulDesc(matmulDesc) .build(); // Create a Bias Node auto biasOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(matmulOp.getOutputTensor()) .setbDesc(bTensor) .setyDesc(oMatrixTensor) .setpwDesc(biasDesc) .build(); // Create an Operation Graphs std::array<cudnn_frontend::Operation const*, 2> ops = {&matmulOp, &biasOp}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle) .setOperationGraph(ops.size(), ops.data()) .build(); auto plan = std::move(get_plan_from_heuristics(opGraph, handle)); outputProjLayerPlan = std::make_shared<cudnn_frontend::ExecutionPlan>(std::move(plan)); std::cout << "[INFO] Execution Plan tag for output projection layer: " << outputProjLayerPlan->getTag() << std::endl; }; cudnnStatus_t execute(cudnnHandle_t handle, void const *devPtrIn, void const *devPtrWeight, void const *devPtrBias, void *devPtrOut) { void* data_ptrs[] = {const_cast<void*>(devPtrIn), const_cast<void*>(devPtrWeight), const_cast<void*>(devPtrBias), devPtrOut}; int64_t uids[] = {'i', 'W', 'b', 'o'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setDataPointers(4, data_ptrs) .setUids(4, uids) .build(); return cudnnBackendExecute(handle, outputProjLayerPlan->get_raw_desc(), variantPack.get_raw_desc()); }; private: std::shared_ptr<cudnn_frontend::ExecutionPlan> outputProjLayerPlan; MHA_outputProjLayer() = delete; MHA_outputProjLayer(MHA_outputProjLayer const &) = delete; MHA_outputProjLayer & operator=(MHA_outputProjLayer const &) = delete; }; class MHA_attentionLayer { public: MHA_attentionLayer(MHA_attentionLayer &&from) = default; MHA_attentionLayer & operator= (MHA_attentionLayer &&from) = default; ~MHA_attentionLayer() = default; MHA_attentionLayer(cudnnHandle_t handle, MHAParams &mhaParams) { const int64_t inputSize = mhaParams.inputSize; const int64_t outputSize = mhaParams.inputSize; const int64_t headSize = mhaParams.headSize; const int64_t numHeads = mhaParams.numHeads; const int64_t seqLength = mhaParams.seqLength; const int64_t batchSize = mhaParams.batchSize; const cudnnDataType_t dataType = mhaParams.dataType; const cudnnDataType_t mathPrec = mhaParams.mathPrec; #if (CUDNN_VERSION >= 8310) { // Softmax scaler const float softmaxScaler = static_cast<float>(1.0 / sqrt(static_cast<double>(headSize))); // Create tensor descriptor for embedding Q const int64_t qDim[3] = {batchSize * numHeads, headSize, seqLength}; const int64_t qStride[3] = {headSize, 1, headSize * numHeads * batchSize}; auto qMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, qDim) .setStrides(3, qStride) .setId('q') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for embedding K^T const int64_t kDim[3] = {batchSize * numHeads, seqLength, headSize}; const int64_t kStride[3] = {headSize, headSize * numHeads * batchSize, 1}; auto kMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, kDim) .setStrides(3, kStride) .setId('k') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for S = K^T * Q const int64_t sDim[3] = {batchSize * numHeads, seqLength, seqLength}; const int64_t sStride[3] = {seqLength * seqLength, seqLength, 1}; auto sMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, sDim) .setStrides(3, sStride) .setId('s') .setAlignment(16) .setVirtual() .setDataType(CUDNN_DATA_FLOAT) .build(); // Create tensor descriptor for Z = softmaxScaler * S auto zMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, sDim) .setStrides(3, sStride) .setId('z') .setAlignment(16) .setVirtual() .setDataType(CUDNN_DATA_FLOAT) .build(); // Create tensor descriptor for E = exp(Z) auto eMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, sDim) .setStrides(3, sStride) .setId('e') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for softmaxScaler const int64_t scalerDim[3] = {1, 1, 1}; const int64_t scalerStride[3] = {1, 1, 1}; auto softmaxScalerTensor = cudnn_frontend::TensorBuilder() .setDim(3, scalerDim) .setStrides(3, scalerStride) .setId('m') .setAlignment(16) .setDataType(CUDNN_DATA_FLOAT) .build(); // Create tensor descriptor for Col-Reduction of E const int64_t cDim[3] = {batchSize * numHeads, 1, seqLength}; const int64_t cStride[3] = {seqLength, seqLength, 1}; auto cTensor = cudnn_frontend::TensorBuilder() .setDim(3, cDim) .setStrides(3, cStride) .setId('c') .setAlignment(16) .setDataType(CUDNN_DATA_FLOAT) .build(); // Define the matmul descriptor for S = (Q^T * K) auto matmulDesc = cudnn_frontend::MatMulDescBuilder().setMathPrecision(CUDNN_DATA_FLOAT).build(); // Define the scale descriptor for S' = softmaxScaler * S auto softmaxScalerDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Define the activation descriptor for E = exp(S') auto expDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_EXP) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Define the reduction descriptor auto colRedunctionDesc = cudnn_frontend::ReductionDescBuilder() .setMathPrecision(CUDNN_DATA_FLOAT) .setReductionOp(CUDNN_REDUCE_TENSOR_ADD) .build(); // Create a matmul Node for S = (Q^T * K) auto matmulOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR) .setaMatDesc(kMatrixTensor) .setbMatDesc(qMatrixTensor) .setcMatDesc(sMatrixTensor) .setmatmulDesc(matmulDesc) .build(); // Create a scale Node for S' = softmaxScaler * S auto softmaxScalerOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(matmulOp.getOutputTensor()) .setbDesc(softmaxScalerTensor) .setyDesc(zMatrixTensor) .setpwDesc(softmaxScalerDesc) .build(); // Create a EXP Node for E = exp(S') auto expOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(softmaxScalerOp.getOutputTensor()) .setyDesc(eMatrixTensor) .setpwDesc(expDesc) .build(); // Create a row-reduction Node auto colReductionOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR) .setxDesc(expOp.getOutputTensor()) .setyDesc(cTensor) .setreductionDesc(colRedunctionDesc) .build(); // Create an Operation Graphs std::array<cudnn_frontend::Operation const*, 4> ops = {&matmulOp, &softmaxScalerOp, &expOp, &colReductionOp}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle) .setOperationGraph(ops.size(), ops.data()) .build(); auto plan = std::move(get_plan_from_heuristics(opGraph, handle)); attentionLayerPlan0 = std::make_shared<cudnn_frontend::ExecutionPlan>(std::move(plan)); } { // Create tensor descriptor for embedding V^T const int64_t vDim[3] = {batchSize * numHeads, seqLength, headSize}; const int64_t vStride[3] = {headSize, headSize * numHeads * batchSize, 1}; auto vMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, vDim) .setStrides(3, vStride) .setId('v') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for E^T const int64_t eDim[3] = {batchSize * numHeads, seqLength, seqLength}; const int64_t eStride[3] = {seqLength * seqLength, 1, seqLength}; auto eMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, eDim) .setStrides(3, eStride) .setId('e') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for Y = E^T * V^T const int64_t yDim[3] = {batchSize * numHeads, seqLength, headSize}; const int64_t yStride[3] = {headSize, headSize * numHeads * batchSize, 1}; auto yMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, yDim) .setStrides(3, yStride) .setId('y') .setAlignment(16) .setVirtual() .setDataType(CUDNN_DATA_FLOAT) .build(); // Create tensor descriptor for P = Y / R auto pMatrixTensor = cudnn_frontend::TensorBuilder() .setDim(3, yDim) .setStrides(3, yStride) .setId('p') .setAlignment(16) .setDataType(dataType) .build(); // Create tensor descriptor for Row-broadcast const int64_t rDim[3] = {batchSize * numHeads, seqLength, 1}; const int64_t rStride[3] = {seqLength, 1, seqLength}; auto rTensor = cudnn_frontend::TensorBuilder() .setDim(3, rDim) .setStrides(3, rStride) .setId('r') .setAlignment(16) .setDataType(CUDNN_DATA_FLOAT) .build(); // Define the matmul descriptor for Y = E * V^T auto matmulDesc = cudnn_frontend::MatMulDescBuilder().setMathPrecision(CUDNN_DATA_FLOAT).build(); // Define the row-broadcast descriptor for P = Y / R auto rowBroadcastDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_DIV) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); // Create a matmul Node for Y = E * V^T auto matmulOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR) .setaMatDesc(eMatrixTensor) .setbMatDesc(vMatrixTensor) .setcMatDesc(yMatrixTensor) .setmatmulDesc(matmulDesc) .build(); // Create a row-broadcast Node for P = Y / R auto rowBroadcastOp = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(matmulOp.getOutputTensor()) .setbDesc(rTensor) .setyDesc(pMatrixTensor) .setpwDesc(rowBroadcastDesc) .build(); // Create an Operation Graphs std::array<cudnn_frontend::Operation const*, 2> ops = {&matmulOp, &rowBroadcastOp}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle) .setOperationGraph(ops.size(), ops.data()) .build(); auto plan = std::move(get_plan_from_heuristics(opGraph, handle)); attentionLayerPlan1 = std::make_shared<cudnn_frontend::ExecutionPlan>(std::move(plan)); } std::cout << "[INFO] Execution Plan tag for attention layer, part 0: " << attentionLayerPlan0->getTag() << std::endl; std::cout << "[INFO] Execution Plan tag for attention layer, part 1: " << attentionLayerPlan1->getTag() << std::endl; #endif }; cudnnStatus_t execute(cudnnHandle_t handle, void const *devPtrQ, void const *devPtrK, void const *devPtrV, void const *devPtrScaler, void *devPtrE, void *devPtrR, void *devPtrX) { void* data_ptrs0[] = {const_cast<void *>(devPtrQ), const_cast<void *>(devPtrK), const_cast<void *>(devPtrE), devPtrR, const_cast<void *>(devPtrScaler)}; int64_t uids0[] = {'q', 'k', 'e', 'c', 'm'}; void* data_ptrs1[] = {devPtrE, const_cast<void *>(devPtrV), devPtrR, devPtrX}; int64_t uids1[] = {'e', 'v', 'r', 'p'}; auto variantPack0 = cudnn_frontend::VariantPackBuilder() .setDataPointers(5, data_ptrs0) .setUids(5, uids0) .build(); auto variantPack1 = cudnn_frontend::VariantPackBuilder() .setDataPointers(4, data_ptrs1) .setUids(4, uids1) .build(); cudnnStatus_t status = cudnnBackendExecute(handle, attentionLayerPlan0->get_raw_desc(), variantPack0.get_raw_desc()); if (status != CUDNN_STATUS_SUCCESS) { return status; } return cudnnBackendExecute(handle, attentionLayerPlan1->get_raw_desc(), variantPack1.get_raw_desc()); }; private: std::shared_ptr<cudnn_frontend::ExecutionPlan> attentionLayerPlan0; std::shared_ptr<cudnn_frontend::ExecutionPlan> attentionLayerPlan1; MHA_attentionLayer() = delete; MHA_attentionLayer(MHA_attentionLayer const &) = delete; MHA_attentionLayer & operator=(MHA_attentionLayer const &) = delete; }; void multiHeadAttention(const int64_t inputSize, const int64_t headSize, const int64_t seqLength, const int64_t numHeads, const int64_t batchSize, const int64_t outputSize, cudnnDataType_t dataType, void const *devPtrIn, void const *devPtrQKVWeight, void const *devPtrOWeight, void const *devPtrQKVBias, void const *devPtrOBias, void *devPtrOut) { #if (CUDNN_VERSION >= 8310) cudnnHandle_t handle_; /* Suppose the following layouts: - input data layout: [seqLength, batchSize, inputSize] - QKV Weight layout: [3, projSize * numHeads, inputSize] Q-Weight followed by K-Weight followed by V-Weight - QKV Bias layout: [3, projSize * numHeads, 1] Q-Bias followed by K-Bias followed by V-Bias - O Weight layout: [1, projSize * numHeads, outputSize] - O Bias layout: [1, 1, outputSize] - output data layout: [seqLength, batchSize, outputSize] All tensors are fully-packed. */ try { // Create cudnn handle checkCudnnErr(cudnnCreate(&handle_)); cudnnStatus_t status = CUDNN_STATUS_SUCCESS; // Softmax scaler const float softmaxScaler = static_cast<float>(1.0 / sqrt(static_cast<double>(headSize))); const int64_t embeddingSize = batchSize * numHeads * headSize * seqLength; void *devPtrQKV = nullptr; void *devPtrE = nullptr; void *devPtrR = nullptr; void *devPtrX = nullptr; void *devPtrScaler = nullptr; // Device Memory to store embeddings Q, K, V checkCudaErr(cudaMalloc(&devPtrQKV, embeddingSize * sizeof(half) * 3)); // Device Memory to store internal data E = exp(softmaxScaler * (Q * K^T)) checkCudaErr(cudaMalloc(&devPtrE, batchSize * numHeads * seqLength * seqLength * sizeof(half))); // Device Memory to store internal data R = row-reduction of E checkCudaErr(cudaMalloc(&devPtrR, batchSize * numHeads * seqLength * sizeof(float))); // Device Memory to store the output from attention layer checkCudaErr(cudaMalloc(&devPtrX, batchSize * numHeads * seqLength * headSize * sizeof(half))); // Device memory for softmax scaler parameter checkCudaErr(cudaMalloc(&devPtrScaler, sizeof(float))); // Copy softmax scaler to device memory checkCudaErr(cudaMemcpy(devPtrScaler, &softmaxScaler, sizeof(float), cudaMemcpyHostToDevice)); void *devPtrQ = reinterpret_cast<char *>(devPtrQKV); void *devPtrK = reinterpret_cast<char *>(devPtrQ) + embeddingSize * sizeof(half); void *devPtrV = reinterpret_cast<char *>(devPtrK) + embeddingSize * sizeof(half); auto mhaParams = MHAParamsBuilder().setInputSize(inputSize) .setOutputSize(outputSize) .setHeadSize(headSize) .setNumHeads(numHeads) .setSeqLength(seqLength) .setBatchSize(batchSize) .setDataType(dataType) .setMathPrec(CUDNN_DATA_FLOAT) .build(); // Build input projection layer to generate embeddings Q, K, V // Q = Wq * input + Bq // K = Wk * input + Bk // V = Wv * input + Bv auto inputProjLayer = MHA_intputProjLayer(handle_, mhaParams); // Build attention layer // S = softmax(softmaxScaler * (Q^T * K)) * V concatenated across all heads auto attnLayer = MHA_attentionLayer(handle_, mhaParams); // Build output projection layer to generate final output // Output = Wo * S + Bo auto outputProjLayer = MHA_outputProjLayer(handle_, mhaParams); status = inputProjLayer.execute(handle_, devPtrIn, devPtrQKVWeight, devPtrQKVBias, devPtrQKV); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "input layer execution error", status); status = attnLayer.execute(handle_, devPtrQ, devPtrK, devPtrV, devPtrScaler, devPtrE, devPtrR, devPtrX); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "attention layer execution error", status); status = outputProjLayer.execute(handle_, devPtrX, devPtrOWeight, devPtrOBias, devPtrOut); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "output layer execution error", status); cudaFree(devPtrQKV); cudaFree(devPtrE); cudaFree(devPtrR); cudaFree(devPtrX); cudaFree(devPtrScaler); } catch (cudnn_frontend::cudnnException &e) { std::cout << "[ERROR] Exception " << e.what() << std::endl; CHECK(false); } #endif }
44.642857
133
0.5189
[ "vector" ]
e66339ea718adb09f6ed23cb7bcbf16de50231f7
26,443
cpp
C++
src/client/ParticleSystem.cpp
bqqbarbhg/spear
727f41fa5197f9681337d1ff37ea63c44708f0d4
[ "BSD-3-Clause" ]
29
2020-07-27T09:56:02.000Z
2022-03-28T01:38:07.000Z
src/client/ParticleSystem.cpp
bqqbarbhg/spear
727f41fa5197f9681337d1ff37ea63c44708f0d4
[ "BSD-3-Clause" ]
3
2020-05-29T11:43:20.000Z
2020-09-04T09:56:56.000Z
src/client/ParticleSystem.cpp
bqqbarbhg/spear
727f41fa5197f9681337d1ff37ea63c44708f0d4
[ "BSD-3-Clause" ]
2
2020-05-29T11:34:46.000Z
2021-03-08T08:39:07.000Z
#include "ParticleSystem.h" #include "client/AreaSystem.h" #include "sf/HashMap.h" #include "sf/Frustum.h" #include "sf/Random.h" #include "sf/Float4.h" #include "sf/Sort.h" #include "sp/Renderer.h" #include "client/ParticleTexture.h" #include "client/BSpline.h" #include "client/VisFogSystem.h" #include "game/shader/GameShaders.h" #include "game/shader/Particle.h" #include "sp/Srgb.h" namespace cl { static const constexpr uint32_t MaxParticlesPerFrame = 4*1024; static const constexpr uint32_t MaxParticleCacheFrames = 16; static const constexpr float HugeParticleLife = 1e20f; static const constexpr float HugeParticleLifeCmp = 1e19f; struct ComponentKey { void *ptr; bool operator==(const ComponentKey &rhs) const { return ptr == rhs.ptr; } }; uint32_t hash(const ComponentKey &key) { return sf::hashPointer(key.ptr); } sf_inline float approxAcos(float a) { float x = sf::abs(a); float v = -1.280827681872808f + 1.280827681872808f*sf::sqrt(1.0f - x) - 0.28996864492208857f*x; return sf::F_PI*0.5f - sf::copysign(v, a); } sf_inline sf::Float4 approxCosSin2(float a, float b) { const sf::ScalarFloat4 rcp2pi = 1.0f / sf::F_2PI; const sf::Float4 bias = sf::Float4(0.0f, -0.25f, 0.0f, -0.25f); sf::Float4 t = sf::Float4(a, a, b, b); t *= rcp2pi; t += bias; t -= (t - 0.25f).round() + 0.25f; t *= (t.abs() - 0.5f) * 16.0f; t += t * (t.abs() - 1.0f) * 0.225f; return t; } sf_inline float approxCbrt(float a) { return 1.5142669123810535f*sf::sqrt(a) - 0.5142669123810535f*a; } struct RandomVec3Imp { enum Flags { Box = 0x1, Sphere = 0x2, Rotation = 0x4, }; uint32_t flags = 0; sf::Vec3 offset; // Box sf::Vec3 boxExtent; // Sphere float thetaBias, thetaScale; float cosPhiBias, cosPhiScale; float radiusCubeScale; float radiusScale; sf::Vec3 sphereScale; // Rotation sf::Quat rotation; void init(const sv::RandomVec3 &sv) { flags = 0; offset = sv.offset; if (sv.boxExtent.x != 0.0f || sv.boxExtent.y != 0.0f || sv.boxExtent.z != 0.0f) { flags |= Box; boxExtent = sv.boxExtent; } if (sv.sphere.maxRadius > 0.0f) { flags |= Sphere; thetaBias = sv.sphere.minTheta * (sf::F_PI/180.0f); thetaScale = (sv.sphere.maxTheta - sv.sphere.minTheta) * (sf::F_PI/180.0f); cosPhiBias = cosf(sv.sphere.maxPhi * (sf::F_PI/180.0f)); cosPhiScale = cosf(sv.sphere.minPhi * (sf::F_PI/180.0f)) - cosPhiBias; radiusCubeScale = approxCbrt(1.0f - sv.sphere.minRadius / sv.sphere.maxRadius); radiusScale = sv.sphere.maxRadius; sphereScale = sv.sphere.scale; } if (sv.rotation != sf::Vec3(0.0f)) { flags |= Rotation; rotation = sf::eulerAnglesToQuat(sv.rotation * (sf::F_PI/180.0f)); } } sf::Vec3 sample(sf::Random &rng) const { sf::Vec3 p = offset; if (flags & Box) { p += (rng.nextVec3() - sf::Vec3(0.5f)) * boxExtent; } if (flags & Sphere) { float u = rng.nextFloat(); float v = rng.nextFloat(); float w = rng.nextFloat(); float theta = thetaBias + u * thetaScale; float phi = approxAcos(cosPhiBias + v * cosPhiScale); const sf::Float4 trig = approxCosSin2(theta, phi); const float cosTheta = trig.getX(), sinTheta = trig.getY(); const float cosPhi = trig.getZ(), sinPhi = trig.getW(); float radius = approxCbrt(1.0f - w * radiusCubeScale) * radiusScale; p += sf::Vec3(sinPhi * cosTheta, cosPhi, sinPhi * sinTheta) * radius * sphereScale; } if (flags & Rotation) { p = sf::rotate(rotation, p); } return p; } }; struct ParticleSystemImp final : ParticleSystem { struct EffectType { sf::Box<sv::ParticleSystemComponent> svComponent; double renderOrder = 0.0; uint32_t tiebreaker = 0; uint32_t refCount = 0; float updateRadius; float timeStep; RandomVec3Imp emitPosition; RandomVec3Imp emitVelocity; // TODO: Cache this? Particle_VertexType_t typeUbo; ParticleTextureRef texture; }; struct Particle4 { sf::Float4 px, py, pz; sf::Float4 vx, vy, vz; sf::Float4 life; sf::Float4 seed; }; struct GpuParticle { sf::Vec3 position; float life; sf::Vec3 velocity; float seed; }; struct Effect { uint32_t typeId; uint32_t areaId; sf::Vec3 origin; sf::Bounds3 gpuBounds; float timeDelta = 0.0f; float timeStep; sf::Vec3 gravity; double lastUpdateTime; sf::Float4 emitterToWorld[4]; sf::Float4 prevEmitterToWorld[4]; sf::Float4 prevWorldToEmitter[4]; sf::Vec3 prevOrigin; sf::Mat34 particlesToWorld; bool stopEmit = false; bool firstEmit = true; bool instantDelete = false; float spawnTimer = 0.0f; float emitOnTimer = -1.0f; uint32_t uploadByteOffset = 0; uint64_t uploadFrameIndex = MaxParticleCacheFrames; sf::Array<Particle4> particles; // TODO: Alignment sf::Array<GpuParticle> gpuParticles; sf::Array<uint32_t> freeIndices; }; struct ParticleUpdateCtx { sf::Random rng; }; struct SortedEffect { double renderOrder; uint32_t tiebreaker; float depth; uint32_t effectId; bool operator<(const SortedEffect &rhs) const { if (renderOrder != rhs.renderOrder) return renderOrder < rhs.renderOrder; if (tiebreaker != rhs.tiebreaker) return tiebreaker < rhs.tiebreaker; if (depth != rhs.depth) return depth < rhs.depth; if (effectId != rhs.effectId) return effectId < rhs.effectId; return false; } }; sf::Array<Effect> effects; sf::Array<uint32_t> freeEffectIds; sf::Array<EffectType> types; sf::Array<uint32_t> freeTypeIds; sf::HashMap<ComponentKey, uint32_t> svCompponentToType; sf::Array<SortedEffect> sortedEffects; sf::Random initRng; ParticleUpdateCtx updateCtx; static constexpr const uint32_t SplineSampleRate = 64; static constexpr const uint32_t SplineAtlasWidth = 8; static constexpr const uint32_t SplineAtlasHeight = 256; static constexpr const uint32_t SplineCountPerType = 2; static constexpr const uint32_t SplineAtlasResX = SplineSampleRate * SplineAtlasWidth; static constexpr const uint32_t SplineAtlasResY = SplineAtlasHeight * SplineCountPerType; sp::Texture splineTexture; sp::Buffer vertexBuffers[MaxParticleCacheFrames]; sp::Pipeline particlePipe; uint64_t bufferFrameIndex = MaxParticleCacheFrames; ParticleSystemImp(const SystemsDesc &desc) { updateCtx.rng = sf::Random(desc.seed[1], 581271); for (uint32_t i = 0; i < MaxParticleCacheFrames; i++) { sf::SmallStringBuf<128> name; name.format("particle vertexBuffer %u", i); vertexBuffers[i].initDynamicVertex(name.data, sizeof(GpuParticle) * 4 * MaxParticlesPerFrame); } { uint32_t flags = sp::PipeIndex16|sp::PipeDepthTest|sp::PipeBlendPremultiply; sg_pipeline_desc &d = particlePipe.init(gameShaders.particle, flags); d.blend.src_factor_alpha = SG_BLENDFACTOR_ZERO; d.blend.dst_factor_alpha = SG_BLENDFACTOR_ONE; d.layout.attrs[0].format = SG_VERTEXFORMAT_FLOAT4; d.layout.attrs[1].format = SG_VERTEXFORMAT_FLOAT4; } { sg_image_desc d = { }; d.usage = SG_USAGE_IMMUTABLE; d.bqq_copy_target = true; d.pixel_format = SG_PIXELFORMAT_RGBA8; d.mag_filter = SG_FILTER_LINEAR; d.min_filter = SG_FILTER_LINEAR; d.width = SplineAtlasResX; d.height = SplineAtlasResY; d.label = "ParticleSystem splineTexture"; splineTexture.init(d); } } void initEffectType(uint32_t typeId, const sv::ParticleSystemComponent &c) { EffectType &type = types[typeId]; type.texture.load(c.texture); type.updateRadius = c.updateRadius; type.timeStep = c.timeStep; type.emitPosition.init(c.emitPosition); type.emitVelocity.init(c.emitVelocity); type.renderOrder = c.renderOrder; type.tiebreaker = typeId; sf::memZero(type.typeUbo); type.typeUbo.u_FrameCount = sf::Vec2(c.frameCount); type.typeUbo.u_FrameRate = c.frameRate; type.typeUbo.u_RotationControl.x = c.rotation * (sf::F_PI/180.0f); type.typeUbo.u_RotationControl.y = c.rotationVariance * (sf::F_PI/180.0f); type.typeUbo.u_RotationControl.z = c.spin * (sf::F_PI/180.0f); type.typeUbo.u_RotationControl.w = c.spinVariance * (sf::F_PI/180.0f); if (c.randomStartFrame) { type.typeUbo.u_StartFrame = 1.0f; } uint32_t atlasX = typeId / SplineAtlasHeight; uint32_t atlasY = typeId % SplineAtlasHeight; uint8_t splineTex[SplineSampleRate * 4 * 2]; float splineY[SplineSampleRate]; if (c.scaleSpline.points.size >= 1) { cl::discretizeBSplineY(splineY, c.scaleSpline.points, 0.0f, 1.0f); } else { for (float &v : splineY) v = 1.0f; } for (uint32_t i = 0; i < SplineSampleRate; i++) { splineTex[i * 4 + 0] = (uint8_t)sf::clamp((int)(splineY[i] * 255.0f), 0, 255); } if (c.alphaSpline.points.size >= 1) { cl::discretizeBSplineY(splineY, c.alphaSpline.points, 0.0f, 1.0f); } else { for (float &v : splineY) v = 1.0f; } for (uint32_t i = 0; i < SplineSampleRate; i++) { splineTex[i * 4 + 1] = (uint8_t)sf::clamp((int)(splineY[i] * 255.0f), 0, 255); } if (c.additiveSpline.points.size >= 1) { cl::discretizeBSplineY(splineY, c.additiveSpline.points, 0.0f, 1.0f); for (float &v : splineY) v = 1.0f - v; } else { for (float &v : splineY) v = 1.0f; } for (uint32_t i = 0; i < SplineSampleRate; i++) { splineTex[i * 4 + 2] = (uint8_t)sf::clamp((int)(splineY[i] * 255.0f), 0, 255); } if (c.erosionSpline.points.size >= 1) { cl::discretizeBSplineY(splineY, c.erosionSpline.points, 0.0f, 1.0f); } else { for (float &v : splineY) v = 1.0f; } for (uint32_t i = 0; i < SplineSampleRate; i++) { splineTex[i * 4 + 3] = (uint8_t)sf::clamp((int)(splineY[i] * 255.0f), 0, 255); } uint8_t *gradientTex = splineTex + SplineSampleRate * 4; sv::GradientPoint defaultGradient[] = { { 1.0f, c.gradient.defaultColor }, }; { sf::Slice<const sv::GradientPoint> points = c.gradient.points; if (points.size == 0) { points = defaultGradient; } float splineStep = 1.0f / (SplineSampleRate - 1); uint32_t pointIx = 0; for (uint32_t i = 0; i < SplineSampleRate; i++) { float t = (float)i * splineStep; while (pointIx < points.size && t >= points[pointIx].t) { pointIx++; } sf::Vec3 col; if (pointIx == 0) { col = points[0].color; } else if (pointIx == points.size) { col = points[points.size - 1].color; } else { const sv::GradientPoint &p0 = points[pointIx - 1]; const sv::GradientPoint &p1 = points[pointIx]; float relT = (t - p0.t) / (p1.t - p0.t); col = sf::lerp(p0.color, p1.color, relT); } uint8_t *dst = gradientTex + i * 4; sp::linearToSrgbUnorm(dst, col); } } uint32_t x = atlasX * SplineSampleRate; uint32_t y = atlasY * SplineCountPerType; sf::Vec2 atlasRes = sf::Vec2((float)SplineAtlasResX, (float)SplineAtlasResY); sf::Vec2 uvBias = sf::Vec2((float)x + 0.5f, (float)y + 0.5f) / atlasRes; sf::Vec2 uvScale = sf::Vec2((float)(SplineSampleRate - 1), 1.0f) / atlasRes; type.typeUbo.u_SplineMad.x = uvScale.x; type.typeUbo.u_SplineMad.y = uvScale.y; type.typeUbo.u_SplineMad.z = uvBias.x; type.typeUbo.u_SplineMad.w = uvBias.y; type.typeUbo.u_ScaleBaseVariance.x = c.size; type.typeUbo.u_ScaleBaseVariance.y = c.sizeVariance; type.typeUbo.u_LifeTimeBaseVariance.x = c.lifeTime; type.typeUbo.u_LifeTimeBaseVariance.y = c.lifeTimeVariance * (1.0f / 16777216.0f); sg_image_desc d = { }; d.width = SplineSampleRate; d.height = SplineCountPerType; d.pixel_format = SG_PIXELFORMAT_RGBA8; d.content.subimage[0][0].ptr = splineTex; d.content.subimage[0][0].size = sizeof(splineTex); sg_image staging = sg_make_image(&d); { sg_bqq_subimage_rect rect; rect.src_x = 0; rect.src_y = 0; rect.dst_x = (int)x; rect.dst_y = (int)y; rect.dst_z = 0; rect.width = (int)SplineSampleRate; rect.height = (int)SplineCountPerType; sg_bqq_subimage_copy_desc desc; desc.dst_image = splineTexture.image; desc.src_image = staging; desc.rects = &rect; desc.num_rects = 1; desc.num_mips = 1; sg_bqq_copy_subimages(&desc); } sg_destroy_image(staging); } void simulateParticlesImp(sf::Random &rng, Effect &effect, float dt) { EffectType &type = types[effect.typeId]; const sv::ParticleSystemComponent &comp = *type.svComponent; bool firstEmit = effect.firstEmit; uint32_t burstAmount = 0; if (firstEmit) { memcpy(effect.prevEmitterToWorld, effect.emitterToWorld, sizeof(sf::Float4) * 4); burstAmount = comp.burstAmount; effect.firstEmit = false; } if (effect.emitOnTimer >= 0.0f) { effect.emitOnTimer -= dt; if (effect.emitOnTimer < 0.0f) { effect.stopEmit = true; } } sf::Float4 dt4 = dt; sf::ScalarFloat4 drag4 = comp.drag; // Update spawning (scalar) effect.spawnTimer -= dt; int spawnsLeft = 20; while ((effect.spawnTimer <= 0.0f && !effect.stopEmit) || burstAmount > 0) { if (burstAmount > 0) { burstAmount--; } else { if (spawnsLeft-- <= 0) break; effect.spawnTimer += comp.spawnTime + comp.spawnTimeVariance * rng.nextFloat(); } if (effect.freeIndices.size == 0) { uint32_t base = effect.particles.size * 4; Particle4 &parts = effect.particles.push(); parts.life = HugeParticleLife; for (uint32_t i = 0; i < 4; i++) { effect.freeIndices.push(base + i); } } uint32_t index = effect.freeIndices.popValue(); sf::Vec3 pos = type.emitPosition.sample(rng); sf::Vec3 vel = type.emitVelocity.sample(rng); if (comp.emitVelocityAttractorStrength != 0.0f) { vel += sf::normalizeOrZero(pos - comp.emitVelocityAttractorOffset) * comp.emitVelocityAttractorStrength; } sf::ScalarFloat4 emitT = sf::clamp(-effect.spawnTimer / dt, 0.0f, 1.0f); sf::Float4 simdPos = effect.emitterToWorld[3] + (effect.prevEmitterToWorld[3] - effect.emitterToWorld[3]) * emitT; simdPos += (effect.emitterToWorld[0] + (effect.prevEmitterToWorld[0] - effect.emitterToWorld[0]) * emitT) * pos.x; simdPos += (effect.emitterToWorld[1] + (effect.prevEmitterToWorld[1] - effect.emitterToWorld[1]) * emitT) * pos.y; simdPos += (effect.emitterToWorld[2] + (effect.prevEmitterToWorld[2] - effect.emitterToWorld[2]) * emitT) * pos.z; pos = simdPos.asVec3(); Particle4 &p = effect.particles[index >> 2]; uint32_t lane = index & 3; sf::setLaneInMemory(p.px, lane, pos.x); sf::setLaneInMemory(p.py, lane, pos.y); sf::setLaneInMemory(p.pz, lane, pos.z); sf::setLaneInMemory(p.vx, lane, vel.x); sf::setLaneInMemory(p.vy, lane, vel.y); sf::setLaneInMemory(p.vz, lane, vel.z); sf::setLaneInMemory(p.life, lane, 1.0f); sf::setLaneInMemory(p.seed, lane, rng.nextFloat() * 16777216.0f); } effect.spawnTimer = sf::max(effect.spawnTimer, 0.0f); // Integration size_t numGpuParticles = effect.particles.size * (4 * 4); effect.gpuParticles.reserveGeometric(numGpuParticles); effect.gpuParticles.resizeUninit(numGpuParticles); GpuParticle *dst = effect.gpuParticles.data; sf::Float4 pMin = +HUGE_VALF, pMax = -HUGE_VALF; sf::ScalarAddFloat4 lifeTime = comp.lifeTime; sf::ScalarFloat4 lifeTimeVariance = comp.lifeTimeVariance * (1.0f / 16777216.0f); sf::Float4 rcpDt4 = 1.0f / dt; sf::SmallArray<sv::GravityPoint, 16> localGravityPoints; for (const sv::GravityPoint &p : comp.gravityPoints) { sv::GravityPoint &lp = localGravityPoints.push(); sf::Float4 simdPos = effect.emitterToWorld[3] + (effect.prevEmitterToWorld[3] - effect.emitterToWorld[3]); simdPos += effect.emitterToWorld[0] * p.position.x; simdPos += effect.emitterToWorld[1] * p.position.y; simdPos += effect.emitterToWorld[2] * p.position.z; lp.position = simdPos.asVec3(); lp.radius = sf::max(p.radius, 0.05f); lp.strength = -p.strength; } for (Particle4 &p : effect.particles) { sf::Float4 life = p.life; if (!life.allGreaterThanZero()) { uint32_t base = (uint32_t)(&p - effect.particles.data) * 4; float lifes[4]; life.storeu(lifes); for (uint32_t i = 0; i < 4; i++) { if (lifes[i] <= 0.0f) { effect.freeIndices.push(base + i); lifes[i] = HugeParticleLife; } } life = sf::Float4::loadu(lifes); } sf::Float4 seed = p.seed; sf::Float4 px = p.px, py = p.py, pz = p.pz; sf::Float4 vx = p.vx, vy = p.vy, vz = p.vz; sf::Float4 ax = effect.gravity.x; sf::Float4 ay = effect.gravity.y; sf::Float4 az = effect.gravity.z; ax -= vx * drag4; ay -= vy * drag4; az -= vz * drag4; for (const sv::GravityPoint &p : localGravityPoints) { sf::Float4 dx = px - p.position.x; sf::Float4 dy = py - p.position.y; sf::Float4 dz = pz - p.position.z; sf::Float4 lenSq = (dx*dx + dy*dy + dz*dz) + p.radius; sf::Float4 weight = lenSq.rsqrt() / lenSq * p.strength; ax += dx * weight; ay += dy * weight; az += dz * weight; } vx += ax * dt4; vy += ay * dt4; vz += az * dt4; p.vx = vx; p.vy = vy; p.vz = vz; px += vx * dt4; py += vy * dt4; pz += vz * dt4; p.px = px; p.py = py; p.pz = pz; life -= dt4 / (seed * lifeTimeVariance + lifeTime); p.life = life; sf::Float4::transpose4(px, py, pz, life); sf::Float4::transpose4(vx, vy, vz, seed); if (px.getW() < HugeParticleLifeCmp) { px.storeu((float*)&dst[0] + 0); vx.storeu((float*)&dst[0] + 4); px.storeu((float*)&dst[1] + 0); vx.storeu((float*)&dst[1] + 4); px.storeu((float*)&dst[2] + 0); vx.storeu((float*)&dst[2] + 4); px.storeu((float*)&dst[3] + 0); vx.storeu((float*)&dst[3] + 4); pMin = pMin.min(px); pMax = pMax.max(px); dst += 4; } if (py.getW() < HugeParticleLifeCmp) { py.storeu((float*)&dst[0] + 0); vy.storeu((float*)&dst[0] + 4); py.storeu((float*)&dst[1] + 0); vy.storeu((float*)&dst[1] + 4); py.storeu((float*)&dst[2] + 0); vy.storeu((float*)&dst[2] + 4); py.storeu((float*)&dst[3] + 0); vy.storeu((float*)&dst[3] + 4); pMin = pMin.min(py); pMax = pMax.max(py); dst += 4; } if (pz.getW() < HugeParticleLifeCmp) { pz.storeu((float*)&dst[0] + 0); vz.storeu((float*)&dst[0] + 4); pz.storeu((float*)&dst[1] + 0); vz.storeu((float*)&dst[1] + 4); pz.storeu((float*)&dst[2] + 0); vz.storeu((float*)&dst[2] + 4); pz.storeu((float*)&dst[3] + 0); vz.storeu((float*)&dst[3] + 4); pMin = pMin.min(pz); pMax = pMax.max(pz); dst += 4; } if (life.getW() < HugeParticleLifeCmp) { life.storeu((float*)&dst[0] + 0); seed.storeu((float*)&dst[0] + 4); life.storeu((float*)&dst[1] + 0); seed.storeu((float*)&dst[1] + 4); life.storeu((float*)&dst[2] + 0); seed.storeu((float*)&dst[2] + 4); life.storeu((float*)&dst[3] + 0); seed.storeu((float*)&dst[3] + 4); pMin = pMin.min(life); pMax = pMax.max(life); dst += 4; } } memcpy(effect.prevEmitterToWorld, effect.emitterToWorld, sizeof(sf::Float4) * 4); effect.gpuParticles.resizeUninit(dst - effect.gpuParticles.data); effect.gpuBounds.origin = ((pMin + pMax) * 0.5f).asVec3(); effect.gpuBounds.extent = ((pMax - pMin) * 0.5f + comp.cullPadding).asVec3(); if (comp.localSpace) { effect.gpuBounds = sf::transformBounds(effect.particlesToWorld, effect.gpuBounds); } effect.uploadFrameIndex = 0; } void releaseEffectTypeImp(uint32_t typeId) { EffectType &type = types[typeId]; if (--type.refCount == 0) { ComponentKey key = { (void*)type.svComponent.ptr }; svCompponentToType.remove(key); sf::reset(type); freeTypeIds.push(typeId); } } // API virtual uint32_t reserveEffectType(Systems &systems, const sf::Box<sv::ParticleSystemComponent> &c) override { uint32_t typeId; ComponentKey key = { (void*)c.ptr }; auto res = svCompponentToType.insert(key); if (res.inserted) { typeId = types.size; if (freeTypeIds.size > 0) { typeId = freeTypeIds.popValue(); } else { types.push(); } res.entry.val = typeId; types[typeId].svComponent = c; initEffectType(typeId, *c); } else { typeId = res.entry.val; } EffectType &type = types[typeId]; type.refCount++; return typeId; } virtual void releaseEffectType(Systems &systems, const sf::Box<sv::ParticleSystemComponent> &c) override { ComponentKey key = { (void*)c.ptr }; if (uint32_t *typeId = svCompponentToType.findValue(key)) { releaseEffectTypeImp(*typeId); } } virtual void addEffect(Systems &systems, uint32_t entityId, uint8_t componentIndex, const sf::Box<sv::ParticleSystemComponent> &c, const Transform &transform) override { uint32_t effectId = effects.size; if (freeEffectIds.size > 0) { effectId = freeEffectIds.popValue(); } else { effects.push(); } uint32_t typeId = reserveEffectType(systems, c); EffectType &type = types[typeId]; Effect &effect = effects[effectId]; effect.typeId = typeId; effect.timeStep = type.timeStep * (1.0f + initRng.nextFloat() * 0.1f); effect.gravity = c->gravity; effect.prevOrigin = effect.origin = transform.position; effect.emitOnTimer = c->emitterOnTime; effect.instantDelete = c->instantDelete; sf::Mat34 entityToWorld = transform.asMatrix(); if (type.svComponent->localSpace) { sf::Mat34().writeColMajor44((float*)effect.emitterToWorld); effect.particlesToWorld = entityToWorld; } else { entityToWorld.writeColMajor44((float*)effect.emitterToWorld); } sf::Sphere sphere = { transform.position, c->updateRadius }; effect.areaId = systems.area->addSphereArea(AreaGroup::ParticleEffect, effectId, sphere, Area::Activate | Area::Visibility); systems.entities.addComponent(entityId, this, effectId, 0, componentIndex, Entity::UpdateTransform|Entity::PrepareForRemove); } void updateTransform(Systems &systems, uint32_t entityId, const EntityComponent &ec, const TransformUpdate &update) override { uint32_t effectId = ec.userId; Effect &effect = effects[effectId]; EffectType &type = types[effect.typeId]; if (type.svComponent->localSpace) { effect.particlesToWorld = update.entityToWorld; } else { update.entityToWorld.writeColMajor44((float*)effect.emitterToWorld); } effect.origin = update.transform.position; sf::Sphere sphere = { update.transform.position, type.updateRadius }; systems.area->updateSphereArea(effect.areaId, sphere); } bool prepareForRemove(Systems &systems, uint32_t entityId, const EntityComponent &ec, const FrameArgs &frameArgs) override { uint32_t effectId = ec.userId; Effect &effect = effects[effectId]; effect.stopEmit = true; return effect.gpuParticles.size == 0 || frameArgs.gameTime - effect.lastUpdateTime > 2.0 || effect.instantDelete; } void remove(Systems &systems, uint32_t entityId, const EntityComponent &ec) override { uint32_t effectId = ec.userId; Effect &effect = effects[effectId]; systems.area->removeSphereArea(effect.areaId); releaseEffectTypeImp(effect.typeId); sf::reset(effect); freeEffectIds.push(effectId); } void updateParticles(const VisibleAreas &activeAreas, const FrameArgs &args) override { float clampedDt = sf::min(args.dt, 0.1f); for (uint32_t effectId : activeAreas.get(AreaGroup::ParticleEffect)) { Effect &effect = effects[effectId]; effect.lastUpdateTime = args.gameTime; effect.timeDelta += clampedDt; while (effect.timeDelta >= effect.timeStep) { simulateParticlesImp(updateCtx.rng, effect, effect.timeStep); effect.timeDelta -= effect.timeStep; } } } void renderMain(const VisFogSystem *visFogSystem, const VisibleAreas &visibleAreas, const RenderArgs &renderArgs) override { // TODO: Sort by type uint32_t frameParticlesLeft = MaxParticlesPerFrame; VisFogImage visFog = visFogSystem->getVisFogImage(); bufferFrameIndex++; uint64_t frame = bufferFrameIndex; sortedEffects.clear(); for (uint32_t effectId : visibleAreas.get(AreaGroup::ParticleEffect)) { Effect &effect = effects[effectId]; EffectType &type = types[effect.typeId]; uint32_t numParticles = effect.gpuParticles.size / 4; if (numParticles == 0) continue; if (!renderArgs.frustum.intersects(effect.gpuBounds)) continue; SortedEffect &sorted = sortedEffects.push(); sorted.renderOrder = type.renderOrder; sorted.tiebreaker = type.tiebreaker; sorted.depth = sf::lengthSq(renderArgs.cameraPosition - effect.origin); sorted.effectId = effectId; } sf::sort(sortedEffects); uint32_t prevTypeId = ~0u; for (SortedEffect &sorted : sortedEffects) { uint32_t effectId = sorted.effectId; Effect &effect = effects[effectId]; EffectType &type = types[effect.typeId]; uint32_t numParticles = effect.gpuParticles.size / 4; if (numParticles == 0) continue; if (!renderArgs.frustum.intersects(effect.gpuBounds)) continue; if (frame - effect.uploadFrameIndex >= MaxParticleCacheFrames) { if (numParticles >= frameParticlesLeft) return; frameParticlesLeft -= numParticles; effect.uploadByteOffset = (uint32_t)sg_append_buffer(vertexBuffers[(uint32_t)frame % MaxParticleCacheFrames].buffer, effect.gpuParticles.data, (int)effect.gpuParticles.byteSize()); effect.uploadFrameIndex = frame; } sp::Buffer &vertexBuffer = vertexBuffers[(uint32_t)effect.uploadFrameIndex % MaxParticleCacheFrames]; Particle_VertexInstance_t ubo; effect.particlesToWorld.writeColMajor44(ubo.u_ParticleToWorld); renderArgs.worldToClip.writeColMajor44(ubo.u_WorldToClip); ubo.u_Aspect = renderArgs.viewToClip.m00 / renderArgs.viewToClip.m11; ubo.u_InvDelta = effect.timeStep - effect.timeDelta; ubo.u_VisFogMad = visFog.worldMad; particlePipe.bind(); if (effect.typeId != prevTypeId) { sg_apply_uniforms(SG_SHADERSTAGE_VS, SLOT_Particle_VertexType, &type.typeUbo, sizeof(type.typeUbo)); prevTypeId = effect.typeId; } sg_apply_uniforms(SG_SHADERSTAGE_VS, SLOT_Particle_VertexInstance, &ubo, sizeof(ubo)); sg_image image = ParticleTexture::defaultImage; if (type.texture.isLoaded() && type.texture->image.id) { image = type.texture->image; } sg_bindings binds = { }; binds.vertex_buffers[0] = vertexBuffer.buffer; binds.vertex_buffer_offsets[0] = effect.uploadByteOffset; binds.index_buffer = sp::getSharedQuadIndexBuffer(); binds.vs_images[SLOT_Particle_u_SplineTexture] = splineTexture.image; binds.vs_images[SLOT_Particle_u_VisFogTexture] = visFog.image; binds.fs_images[SLOT_Particle_u_Texture] = image; sg_apply_bindings(&binds); sg_draw(0, numParticles * 6, 1); } } }; sf::Box<ParticleSystem> ParticleSystem::create(const SystemsDesc &desc) { return sf::box<ParticleSystemImp>(desc); } }
29.026345
184
0.676587
[ "transform" ]
e663fd16376ed3977785689079408b556a53b596
6,084
cpp
C++
examples/learned_decompositions.cpp
shubho/gtn
9d2d7a6269bc7c2b594aed7ef80b5039b0f40dec
[ "MIT" ]
478
2020-09-30T11:25:18.000Z
2022-03-14T12:40:17.000Z
examples/learned_decompositions.cpp
KonstantinKlepikov/gtn
319e939f292121dcfc6bcb001773889b18227034
[ "MIT" ]
18
2020-09-30T16:23:54.000Z
2021-06-02T22:51:46.000Z
examples/learned_decompositions.cpp
KonstantinKlepikov/gtn
319e939f292121dcfc6bcb001773889b18227034
[ "MIT" ]
47
2020-09-30T11:38:44.000Z
2021-11-06T01:32:22.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <sstream> #include "gtn/gtn.h" using namespace gtn; void asgWithTransducers() { // We can simplify ASG to it's core assumptions by using transducers. std::unordered_map<int, std::string> symbols = {{0, "e"}, {1, "h"}, {2, "t"}}; // Each individual token graph encodes the fact that we can consume the same // token repeatedly while only emitting a single output. Graph e; e.addNode(true); e.addNode(false, true); e.addArc(0, 1, 0); e.addArc(1, 1, 0, epsilon); Graph h; h.addNode(true); h.addNode(false, true); h.addArc(0, 1, 1); h.addArc(1, 1, 1, epsilon); Graph t; t.addNode(true); t.addNode(false, true); t.addArc(0, 1, 2); t.addArc(1, 1, 2, epsilon); draw(e, "asg_e_graph.dot", symbols, symbols); draw(h, "asg_h_graph.dot", symbols, symbols); draw(t, "asg_t_graph.dot", symbols, symbols); // The closure of the union of the individual token graphs encodes the // fact that we can emit any sequence of zero or more tokens. auto tokens = closure(union_({e, h, t})); draw(tokens, "asg_tokens.dot", symbols, symbols); // The "the" graph can be simplified to just accepting the token sequence: // ['t', 'h', 'e'] auto the = loadTxt(std::stringstream("0\n" "3\n" "0 1 2\n" "1 2 1\n" "2 3 0\n")); draw(the, "asg_simple_the.dot", symbols); // This gives the standard force align graph for "the" auto asg_the = compose(tokens, the); draw(asg_the, "asg_eps_the.dot", symbols, symbols); // Clean-up / remove unneeded epsilons to speed things up. asg_the = remove(asg_the, epsilon); draw(asg_the, "asg_fst_the.dot", symbols, symbols); // Get an FSA (using the FST would be fine, but this way we don't have to // worry about the order in future composes with other FSAs). asg_the = projectInput(asg_the); draw(asg_the, "asg_fsa_the.dot", symbols); // At this point, we can use the standard emissions and transitions graph to // complete the ASG loss (see e.g. examples/asg.cpp). } void ctcWithTransducers() { // Just as in ASG, we can simplify CTC to it's core assumptions by using // transducers. We use "<B>" to denote the "blank" token to distinguish // it from an actual epsilon. std::unordered_map<int, std::string> symbols = { {0, "e"}, {1, "h"}, {2, "t"}, {3, "<B>"}}; // The only difference from ASG and CTC is that we add a special blank (<B>) // token. Graph e; e.addNode(true); e.addNode(false, true); e.addArc(0, 1, 0); e.addArc(1, 1, 0, epsilon); Graph h; h.addNode(true); h.addNode(false, true); h.addArc(0, 1, 1); h.addArc(1, 1, 1, epsilon); Graph t; t.addNode(true); t.addNode(false, true); t.addArc(0, 1, 2); t.addArc(1, 1, 2, epsilon); // The <B> token is optional Graph blank; blank.addNode(true, true); blank.addArc(0, 0, 3, epsilon); draw(blank, "ctc_blank.dot", symbols, symbols); // Everything else is the same as in ASG! auto tokens = closure(union_({e, h, t, blank})); draw(tokens, "ctc_tokens.dot", symbols, symbols); // The "the" graph can be simplified to just accepting the token sequence: // ['t', 'h', 'e'] Graph the = loadTxt(std::stringstream("0\n" "3\n" "0 1 2\n" "1 2 1\n" "2 3 0\n")); // This gives the standard CTC force align graph for "the" auto ctc_the = remove(compose(tokens, the), epsilon); draw(ctc_the, "ctc_eps_the.dot", symbols, symbols); // At this point, we can use the standard emissions graph to // complete the CTC loss (see e.g. examples/ctc.cpp). } void wordDecompositions() { // Now that we know how to simplify ASG and CTC with transducers, we can do // things like adding many decompositions for a given word easily and in a // generic way. For example maybe we want to allow all possible // decompositions for the word "the": // [t, h, e], [th, e], [t, he], [the] // given the token set [e, h, t, he, th, the]. std::unordered_map<int, std::string> symbols = { {0, "e"}, {1, "h"}, {2, "t"}, {3, "th"}, {4, "he"}, {5, "the"}}; std::vector<Graph> tokens_vec; for (auto& kv : symbols) { Graph g; g.addNode(true); g.addNode(false, true); g.addArc(0, 1, kv.first); g.addArc(1, 1, kv.first, epsilon); tokens_vec.push_back(g); } auto tokens = closure(union_(tokens_vec)); // The graph for "the" encodes the fact that multiple decompositions are // allowed and is the only change needed (other than augmenting the token // set). auto the = loadTxt(std::stringstream("0\n" "3\n" "0 1 2 -1\n" "0 2 3 -1\n" "0 3 5 5\n" "1 2 1 -1\n" "1 3 4 5\n" "2 3 0 5\n")); draw(the, "word_decomps_the.dot", symbols, symbols); auto asg_the = remove(compose(tokens, the), epsilon); draw(asg_the, "asg_word_decomps_the.dot", symbols, symbols); // At this point, we can use the standard emissions and transitions graph to // complete the ASG loss (see e.g. examples/asg.cpp). // CTC with word decompositions is exactly the same except with the addition // of the special blank token. // Add blank to the symbol table symbols[6] = "<B>"; // Add blank graph to the tokens graph Graph blank; blank.addNode(true, true); blank.addArc(0, 0, 6, epsilon); tokens_vec.push_back(blank); tokens = closure(union_(tokens_vec)); auto ctc_the = remove(compose(tokens, the), epsilon); draw(ctc_the, "ctc_word_decomps_the.dot", symbols, symbols); } int main() { asgWithTransducers(); ctcWithTransducers(); wordDecompositions(); }
31.853403
80
0.605851
[ "vector" ]
e669697ee3c048914b9d5656aafbcf52051527e5
2,406
cpp
C++
sources/dansandu/math/clustering.cpp
dansandu/math
48e463c01a440a8f3c7b1d99c230e141f0037266
[ "MIT" ]
null
null
null
sources/dansandu/math/clustering.cpp
dansandu/math
48e463c01a440a8f3c7b1d99c230e141f0037266
[ "MIT" ]
null
null
null
sources/dansandu/math/clustering.cpp
dansandu/math
48e463c01a440a8f3c7b1d99c230e141f0037266
[ "MIT" ]
null
null
null
#include "dansandu/math/clustering.hpp" #include "dansandu/ballotin/exception.hpp" #include "dansandu/math/common.hpp" #include <algorithm> #include <limits> #include <random> using dansandu::math::matrix::ConstantMatrixView; using dansandu::math::matrix::distance; using dansandu::math::matrix::dynamic; using dansandu::math::matrix::Matrix; using dansandu::math::matrix::MatrixView; using dansandu::math::matrix::sliceRow; namespace dansandu::math::clustering { std::vector<int> kMeans(const ConstantMatrixView<float> samples, const MatrixView<float> centroids, const int iterations) { if (centroids.rowCount() <= 0) { THROW(std::invalid_argument, "invalid cluster count ", centroids.rowCount(), " -- centroids row count must be greater than zero"); } if (centroids.columnCount() != samples.columnCount()) { THROW(std::invalid_argument, "centroids column count ", centroids.columnCount(), " does not match samples column count ", samples.columnCount()); } auto labels = std::vector<int>(samples.rowCount()); auto newCentroids = Matrix<float>{centroids.rowCount(), centroids.columnCount()}; auto count = std::vector<int>(centroids.rowCount()); for (auto iteration = 0; iteration < iterations; ++iteration) { for (auto s = 0; s < samples.rowCount(); ++s) { const auto sample = sliceRow(samples, s); auto label = 0; auto minimumDistance = std::numeric_limits<float>::max(); for (auto c = 0; c < centroids.rowCount(); ++c) { const auto centroid = sliceRow(centroids, c); const auto d = distance(sample, centroid); const auto isCloser = d < minimumDistance; label = isCloser * c + !isCloser * label; minimumDistance = isCloser * d + !isCloser * minimumDistance; } labels[s] = label; sliceRow(newCentroids, label) += sample; ++count[label]; } for (auto c = 0; c < centroids.rowCount(); ++c) { sliceRow(newCentroids, c) /= static_cast<float>(count[c]); } centroids.deepCopy(newCentroids); std::fill(newCentroids.begin(), newCentroids.end(), 0.0f); std::fill(count.begin(), count.end(), 0); } return labels; } }
34.869565
99
0.608063
[ "vector" ]
e66c34f97e922ce6bb67257e9b5e83332dda7923
10,507
hpp
C++
misc/baxter_class/include/baxter.hpp
YoshimitsuMatsutaIe/rmp_test
a7c94ff68b518ef51821484795c308c2c8519c4c
[ "MIT" ]
null
null
null
misc/baxter_class/include/baxter.hpp
YoshimitsuMatsutaIe/rmp_test
a7c94ff68b518ef51821484795c308c2c8519c4c
[ "MIT" ]
null
null
null
misc/baxter_class/include/baxter.hpp
YoshimitsuMatsutaIe/rmp_test
a7c94ff68b518ef51821484795c308c2c8519c4c
[ "MIT" ]
null
null
null
/****************************************************************************** * Code generated with sympy 1.9 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'phi_W0project' * ******************************************************************************/ #ifndef BAXTER__HPP #define BAXTER__HPP #include <iostream> #include <cmath> #include <vector> #include <array> #include "/usr/include/eigen3/Eigen/Core" /** * @brief バクスター関係 * */ namespace baxter { //joint vector using Vector7d = Eigen::VectorXd; using Matrix_3_7_d = Eigen::MatrixXd; using std::cos; using std::sin; using Eigen::VectorXd; using Eigen::MatrixXd; /** * @brief * */ class Baxter { private: public: double L, h, H, L0, L1, L2, L3, L4, L5, L6; VectorXd q_max; VectorXd q_min; VectorXd q_neutral; Baxter(void); const void print_all(void); std::array<VectorXd, 2> static_os; std::array<VectorXd, 2> static_rxs; std::array<VectorXd, 2> static_rys; std::array<VectorXd, 2> static_rzs; std::array<Matrix_3_7_d, 2> static_jos; std::array<Matrix_3_7_d, 2> static_jrxs; std::array<Matrix_3_7_d, 2> static_jrys; std::array<Matrix_3_7_d, 2> static_jrzs; std::array<Matrix_3_7_d, 2> static_jo_dots; std::array<Matrix_3_7_d, 2> static_jrx_dots; std::array<Matrix_3_7_d, 2> static_jry_dots; std::array<Matrix_3_7_d, 2> static_jrz_dots; std::array<VectorXd, 7> os; std::array<VectorXd, 7> rxs; std::array<VectorXd, 7> rys; std::array<VectorXd, 7> rzs; std::array<Matrix_3_7_d, 7> jos; std::array<Matrix_3_7_d, 7> jrxs; std::array<Matrix_3_7_d, 7> jrys; std::array<Matrix_3_7_d, 7> jrzs; std::array<Matrix_3_7_d, 7> jo_dots; std::array<Matrix_3_7_d, 7> jrx_dots; std::array<Matrix_3_7_d, 7> jry_dots; std::array<Matrix_3_7_d, 7> jrz_dots; VectorXd o_ee; VectorXd rx_ee; VectorXd ry_ee; VectorXd rz_ee; Matrix_3_7_d jo_ee; Matrix_3_7_d jrx_ee; Matrix_3_7_d jry_ee; Matrix_3_7_d jrz_ee; Matrix_3_7_d jo_dot_ee; Matrix_3_7_d jrx_dot_ee; Matrix_3_7_d jry_dot_ee; Matrix_3_7_d jrz_dot_ee; void calc_all(const Vector7d& q, const Vector7d& q_dot); void Rx_W0(const Vector7d& q, VectorXd& out); void Rx_BR(const Vector7d& q, VectorXd& out); void Rx_0(const Vector7d& q, VectorXd& out); void Rx_1(const Vector7d& q, VectorXd& out); void Rx_2(const Vector7d& q, VectorXd& out); void Rx_3(const Vector7d& q, VectorXd& out); void Rx_4(const Vector7d& q, VectorXd& out); void Rx_5(const Vector7d& q, VectorXd& out); void Rx_6(const Vector7d& q, VectorXd& out); void Rx_ee(const Vector7d& q, VectorXd& out); void Ry_W0(const Vector7d& q, VectorXd& out); void Ry_BR(const Vector7d& q, VectorXd& out); void Ry_0(const Vector7d& q, VectorXd& out); void Ry_1(const Vector7d& q, VectorXd& out); void Ry_2(const Vector7d& q, VectorXd& out); void Ry_3(const Vector7d& q, VectorXd& out); void Ry_4(const Vector7d& q, VectorXd& out); void Ry_5(const Vector7d& q, VectorXd& out); void Ry_6(const Vector7d& q, VectorXd& out); void Ry_ee(const Vector7d& q, VectorXd& out); void Rz_W0(const Vector7d& q, VectorXd& out); void Rz_BR(const Vector7d& q, VectorXd& out); void Rz_0(const Vector7d& q, VectorXd& out); void Rz_1(const Vector7d& q, VectorXd& out); void Rz_2(const Vector7d& q, VectorXd& out); void Rz_3(const Vector7d& q, VectorXd& out); void Rz_4(const Vector7d& q, VectorXd& out); void Rz_5(const Vector7d& q, VectorXd& out); void Rz_6(const Vector7d& q, VectorXd& out); void Rz_ee(const Vector7d& q, VectorXd& out); void phi_W0(const Vector7d& q, VectorXd& out); void phi_BR(const Vector7d& q, VectorXd& out); void phi_0(const Vector7d& q, VectorXd& out); void phi_1(const Vector7d& q, VectorXd& out); void phi_2(const Vector7d& q, VectorXd& out); void phi_3(const Vector7d& q, VectorXd& out); void phi_4(const Vector7d& q, VectorXd& out); void phi_5(const Vector7d& q, VectorXd& out); void phi_6(const Vector7d& q, VectorXd& out); void phi_ee(const Vector7d& q, VectorXd& out); void JRx_W0(const Vector7d& q, Matrix_3_7_d& out); void JRx_BR(const Vector7d& q, Matrix_3_7_d& out); void JRx_0(const Vector7d& q, Matrix_3_7_d& out); void JRx_1(const Vector7d& q, Matrix_3_7_d& out); void JRx_2(const Vector7d& q, Matrix_3_7_d& out); void JRx_3(const Vector7d& q, Matrix_3_7_d& out); void JRx_4(const Vector7d& q, Matrix_3_7_d& out); void JRx_5(const Vector7d& q, Matrix_3_7_d& out); void JRx_6(const Vector7d& q, Matrix_3_7_d& out); void JRx_ee(const Vector7d& q, Matrix_3_7_d& out); void JRy_W0(const Vector7d& q, Matrix_3_7_d& out); void JRy_BR(const Vector7d& q, Matrix_3_7_d& out); void JRy_0(const Vector7d& q, Matrix_3_7_d& out); void JRy_1(const Vector7d& q, Matrix_3_7_d& out); void JRy_2(const Vector7d& q, Matrix_3_7_d& out); void JRy_3(const Vector7d& q, Matrix_3_7_d& out); void JRy_4(const Vector7d& q, Matrix_3_7_d& out); void JRy_5(const Vector7d& q, Matrix_3_7_d& out); void JRy_6(const Vector7d& q, Matrix_3_7_d& out); void JRy_ee(const Vector7d& q, Matrix_3_7_d& out); void JRz_W0(const Vector7d& q, Matrix_3_7_d& out); void JRz_BR(const Vector7d& q, Matrix_3_7_d& out); void JRz_0(const Vector7d& q, Matrix_3_7_d& out); void JRz_1(const Vector7d& q, Matrix_3_7_d& out); void JRz_2(const Vector7d& q, Matrix_3_7_d& out); void JRz_3(const Vector7d& q, Matrix_3_7_d& out); void JRz_4(const Vector7d& q, Matrix_3_7_d& out); void JRz_5(const Vector7d& q, Matrix_3_7_d& out); void JRz_6(const Vector7d& q, Matrix_3_7_d& out); void JRz_ee(const Vector7d& q, Matrix_3_7_d& out); void Jo_W0(const Vector7d& q, Matrix_3_7_d& out); void Jo_BR(const Vector7d& q, Matrix_3_7_d& out); void Jo_0(const Vector7d& q, Matrix_3_7_d& out); void Jo_1(const Vector7d& q, Matrix_3_7_d& out); void Jo_2(const Vector7d& q, Matrix_3_7_d& out); void Jo_3(const Vector7d& q, Matrix_3_7_d& out); void Jo_4(const Vector7d& q, Matrix_3_7_d& out); void Jo_5(const Vector7d& q, Matrix_3_7_d& out); void Jo_6(const Vector7d& q, Matrix_3_7_d& out); void Jo_ee(const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_W0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_BR(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_1(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_2(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_3(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_4(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_5(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_6(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRx_dot_ee(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_W0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_BR(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_1(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_2(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_3(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_4(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_5(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_6(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRy_dot_ee(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_W0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_BR(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_1(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_2(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_3(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_4(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_5(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_6(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void JRz_dot_ee(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_W0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_BR(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_1(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_2(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_3(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_4(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_5(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_6(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); void Jo_dot_ee(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out); }; }; #endif
45.288793
82
0.624346
[ "vector" ]
e67cbcd35cf891dd7ff29f5aa79d4b6a47b9cd41
9,988
cpp
C++
packages/monte_carlo/collision/native/src/MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/collision/native/src/MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/collision/native/src/MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp //! \author Alex Robinson //! \brief The subshell incoherent photon scattering distribution decl. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <limits> // Boost Includes #include <boost/function.hpp> #include <boost/bind.hpp> // FRENSIE Includes #include "MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.hpp" #include "MonteCarlo_PhotonKinematicsHelpers.hpp" #include "MonteCarlo_ElectronState.hpp" #include "Utility_PhysicalConstants.hpp" #include "Utility_RandomNumberGenerator.hpp" #include "Utility_GaussKronrodIntegrator.hpp" #include "Utility_ContractException.hpp" namespace MonteCarlo{ // Constructor /*! \details The occupation number grid must be in me*c units. */ SubshellIncoherentPhotonScatteringDistribution::SubshellIncoherentPhotonScatteringDistribution( const SubshellType interaction_subshell, const double num_electrons_in_subshell, const double binding_energy, const Teuchos::RCP<const Utility::OneDDistribution>& occupation_number, const double kahn_sampling_cutoff_energy ) : IncoherentPhotonScatteringDistribution( kahn_sampling_cutoff_energy ), d_subshell( interaction_subshell ), d_num_electrons_in_subshell( num_electrons_in_subshell ), d_binding_energy( binding_energy ), d_occupation_number( occupation_number ) { // Make sure the interaction subshell is valid testPrecondition( interaction_subshell != INVALID_SUBSHELL ); testPrecondition( interaction_subshell != UNKNOWN_SUBSHELL ); // Make sure the number of electrons is valid testPrecondition( num_electrons_in_subshell > 0.0 ); // Make sure the binding energy is valid testPrecondition( binding_energy > 0.0 ); // Make sure the occupation number is valid testPrecondition( !occupation_number.is_null() ); testPrecondition( occupation_number->getLowerBoundOfIndepVar() == -1.0 ); } // Return the subshell SubshellType SubshellIncoherentPhotonScatteringDistribution::getSubshell() const { return d_subshell; } // Return the number of electrons in the subshell double SubshellIncoherentPhotonScatteringDistribution::getNumberOfElectronsInSubshell() const { return d_num_electrons_in_subshell; } // Return the binding energy double SubshellIncoherentPhotonScatteringDistribution::getBindingEnergy() const { return d_binding_energy; } // Evaluate the distribution double SubshellIncoherentPhotonScatteringDistribution::evaluate( const double incoming_energy, const double scattering_angle_cosine ) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy > d_binding_energy ); // Make sure the scattering angle cosine is valid testPrecondition( scattering_angle_cosine >= -1.0 ); testPrecondition( scattering_angle_cosine <= 1.0 ); const double occupation_number = this->evaluateOccupationNumber( incoming_energy, scattering_angle_cosine ); const double diff_kn_cross_section = this->evaluateKleinNishinaDist( incoming_energy, scattering_angle_cosine ); return d_num_electrons_in_subshell*occupation_number*diff_kn_cross_section; } // Evaluate the integrated cross section (cm^2) double SubshellIncoherentPhotonScatteringDistribution::evaluateIntegratedCrossSection( const double incoming_energy, const double precision) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy > d_binding_energy ); // Evaluate the integrated cross section boost::function<double (double x)> diff_cs_wrapper = boost::bind<double>( &SubshellIncoherentPhotonScatteringDistribution::evaluate, boost::cref( *this ), incoming_energy, _1 ); double abs_error, integrated_cs; Utility::GaussKronrodIntegrator quadrature_gkq_set( precision ); quadrature_gkq_set.integrateAdaptively<15>( diff_cs_wrapper, -1.0, 1.0, integrated_cs, abs_error ); // Make sure the integrated cross section is valid testPostcondition( integrated_cs > 0.0 ); return integrated_cs; } // Sample an outgoing energy and direction from the distribution /*! \details This function will only sample a Compton line energy (no * Doppler broadening). */ void SubshellIncoherentPhotonScatteringDistribution::sample( const double incoming_energy, double& outgoing_energy, double& scattering_angle_cosine ) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy > d_binding_energy ); unsigned trial_dummy; return this->sampleAndRecordTrials( incoming_energy, outgoing_energy, scattering_angle_cosine, trial_dummy ); } // Sample an outgoing energy and direction and record the number of trials /*! \details This function will only sample a Compton line energy (no * Doppler broadening). */ void SubshellIncoherentPhotonScatteringDistribution::sampleAndRecordTrials( const double incoming_energy, double& outgoing_energy, double& scattering_angle_cosine, unsigned& trials ) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy > d_binding_energy ); // Evaluate the maximum occupation number const double max_occupation_number = this->evaluateOccupationNumber( incoming_energy, -1.0 ); while( true ) { this->sampleAndRecordTrialsKleinNishina( incoming_energy, outgoing_energy, scattering_angle_cosine, trials ); const double occupation_number = this->evaluateOccupationNumber( incoming_energy, scattering_angle_cosine ); const double scaled_random_number = max_occupation_number* Utility::RandomNumberGenerator::getRandomNumber<double>(); if( scaled_random_number <= occupation_number ) break; } // Make sure the scattering angle cosine is valid testPostcondition( scattering_angle_cosine >= -1.0 ); testPostcondition( scattering_angle_cosine <= 1.0 ); // Make sure the compton line energy is valid testPostcondition( outgoing_energy <= incoming_energy ); remember( double alpha = incoming_energy/ Utility::PhysicalConstants::electron_rest_mass_energy ); testPostcondition( outgoing_energy >= incoming_energy/(1+2*alpha) ); } // Evaluate the occupation number double SubshellIncoherentPhotonScatteringDistribution::evaluateOccupationNumber( const double incoming_energy, const double scattering_angle_cosine ) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy >= d_binding_energy ); // Make sure the scattering angle cosine is valid testPrecondition( scattering_angle_cosine >= -1.0 ); testPrecondition( scattering_angle_cosine <= 1.0 ); const double occupation_number_arg = this->calculateOccupationNumberArgument( incoming_energy, scattering_angle_cosine ); return d_occupation_number->evaluate( occupation_number_arg ); } // Calculate the occupation number argument (pz max) double SubshellIncoherentPhotonScatteringDistribution::calculateOccupationNumberArgument( const double incoming_energy, const double scattering_angle_cosine ) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy >= d_binding_energy ); // Make sure the scattering angle cosine is valid testPrecondition( scattering_angle_cosine >= -1.0 ); testPrecondition( scattering_angle_cosine <= 1.0 ); double occupation_number_arg = calculateMaxElectronMomentumProjection( incoming_energy, d_binding_energy, scattering_angle_cosine ); if( occupation_number_arg >= d_occupation_number->getUpperBoundOfIndepVar() ) occupation_number_arg = d_occupation_number->getUpperBoundOfIndepVar(); // Make sure the occupation number arg is valid testPostcondition( occupation_number_arg >= d_occupation_number->getLowerBoundOfIndepVar() ); testPostcondition( occupation_number_arg <= d_occupation_number->getUpperBoundOfIndepVar() ); return occupation_number_arg; } // Randomly scatter the photon /*! \details The particle bank is used to store the electron that is emitted * from the collision. Whether or not Doppler broadening is done, the * energy and direction of the outgoing electron is calculated as if it were * at rest initially (feel free to update this model!). */ void SubshellIncoherentPhotonScatteringDistribution::scatterPhoton( PhotonState& photon, ParticleBank& bank, SubshellType& shell_of_interaction ) const { // Make sure the photon energy is valid testPrecondition( photon.getEnergy() > d_binding_energy ); double outgoing_energy, scattering_angle_cosine; // Sample an outgoing energy and direction this->sample( photon.getEnergy(), outgoing_energy, scattering_angle_cosine ); // Set the interaction subshell shell_of_interaction = d_subshell; // Sample the azimuthal angle of the outgoing photon const double azimuthal_angle = this->sampleAzimuthalAngle(); // Create the ejectected electron this->createEjectedElectron( photon, scattering_angle_cosine, azimuthal_angle, bank ); // Set the new energy if( outgoing_energy > 0.0 ) { photon.setEnergy( outgoing_energy ); // Set the new direction photon.rotateDirection( scattering_angle_cosine, azimuthal_angle ); } else { photon.setEnergy( std::numeric_limits<double>::min() ); photon.setAsGone(); } } } // end MonteCarlo namespace //---------------------------------------------------------------------------// // end MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp //---------------------------------------------------------------------------//
34.205479
95
0.733881
[ "model" ]
e67ecd773decbcfaded6fc4dd9ab4a020f958c1b
3,673
cpp
C++
src/CollisionDispatcher.cpp
20tab/pybulletphysics
7e227fc9870321785a1b6c53dd4e767cc66aad6f
[ "MIT" ]
21
2015-09-16T15:24:41.000Z
2019-03-19T07:28:32.000Z
src/CollisionDispatcher.cpp
20tab/pybulletphysics
7e227fc9870321785a1b6c53dd4e767cc66aad6f
[ "MIT" ]
2
2015-07-17T16:54:25.000Z
2016-09-24T14:45:33.000Z
src/CollisionDispatcher.cpp
20tab/pybulletphysics
7e227fc9870321785a1b6c53dd4e767cc66aad6f
[ "MIT" ]
1
2020-03-31T09:26:54.000Z
2020-03-31T09:26:54.000Z
#include "pybulletphysics.h" extern PyTypeObject bulletphysics_DefaultCollisionConfigurationType; static void CollisionDispatcher_dealloc(bulletphysics_DispatcherObject* self) { Py_DECREF(self->collision_configuration); delete(self->dispatcher); self->ob_type->tp_free((PyObject*)self); } static PyObject* CollisionDispatcher_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { bulletphysics_CollisionConfigurationObject *py_collisionConfiguration = NULL; if (!PyArg_ParseTuple(args, "O", &py_collisionConfiguration)) { return NULL; } if (!PyObject_TypeCheck(py_collisionConfiguration, &bulletphysics_DefaultCollisionConfigurationType)) { PyErr_SetString(PyExc_TypeError, "expected a DefaultCollisionConfigurationType"); return NULL; } bulletphysics_DispatcherObject *self = (bulletphysics_DispatcherObject *)type->tp_alloc(type, 0); if (self != NULL) { self->dispatcher = new btCollisionDispatcher(py_collisionConfiguration->configuration); self->collision_configuration = py_collisionConfiguration; Py_INCREF(self->collision_configuration); } return (PyObject *)self; } PyTypeObject bulletphysics_CollisionDispatcherType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "bulletphysics.CollisionDispatcher", /*tp_name*/ sizeof(bulletphysics_DispatcherObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)CollisionDispatcher_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ "CollisionDispatcher object", /* tp_doc */ }; static PyObject * CollisionDispatcher_getNumManifolds(bulletphysics_DispatcherObject *self, PyObject *args, PyObject *kwds) { return PyInt_FromLong(self->dispatcher->getNumManifolds()); } static PyObject * CollisionDispatcher_getManifoldByIndexInternal(bulletphysics_DispatcherObject *self, PyObject *args, PyObject *kwds) { int i = 0; if (!PyArg_ParseTuple(args, "i", &i)) { return NULL; } btPersistentManifold *manifold = self->dispatcher->getManifoldByIndexInternal(i); return new_pypersistentmanifold_from_persistentmanifold(manifold); } static PyMethodDef CollisionDispatcher_methods[] = { {"getNumManifolds", (PyCFunction)CollisionDispatcher_getNumManifolds, METH_VARARGS, NULL }, {"getManifoldByIndexInternal", (PyCFunction)CollisionDispatcher_getManifoldByIndexInternal, METH_VARARGS, NULL }, {NULL, NULL, 0, NULL} }; void pybulletphysics_add_CollisionDispatcher(PyObject *module) { bulletphysics_CollisionDispatcherType.tp_methods = CollisionDispatcher_methods; bulletphysics_CollisionDispatcherType.tp_new = CollisionDispatcher_new; if (PyType_Ready(&bulletphysics_CollisionDispatcherType) < 0) return; Py_INCREF(&bulletphysics_CollisionDispatcherType); PyModule_AddObject(module, "CollisionDispatcher", (PyObject *)&bulletphysics_CollisionDispatcherType); }
40.362637
118
0.658045
[ "object" ]
e6805c50fab243d63ba297ea12faf57535d79e47
19,403
cpp
C++
B2G/hardware/libhardware_legacy/audio/audio_hw_hal.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/hardware/libhardware_legacy/audio/audio_hw_hal.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/hardware/libhardware_legacy/audio/audio_hw_hal.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "legacy_audio_hw_hal" //#define LOG_NDEBUG 0 #include <stdint.h> #include <hardware/hardware.h> #include <system/audio.h> #include <hardware/audio.h> #include <hardware_legacy/AudioHardwareInterface.h> #include <hardware_legacy/AudioSystemLegacy.h> namespace android_audio_legacy { extern "C" { struct legacy_audio_module { struct audio_module module; }; struct legacy_audio_device { struct audio_hw_device device; struct AudioHardwareInterface *hwif; }; struct legacy_stream_out { struct audio_stream_out stream; AudioStreamOut *legacy_out; }; struct legacy_stream_in { struct audio_stream_in stream; AudioStreamIn *legacy_in; }; /** audio_stream_out implementation **/ static uint32_t out_get_sample_rate(const struct audio_stream *stream) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); return out->legacy_out->sampleRate(); } static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate) { struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); LOGE("(%s:%d) %s: Implement me!", __FILE__, __LINE__, __func__); /* TODO: implement this */ return 0; } static size_t out_get_buffer_size(const struct audio_stream *stream) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); return out->legacy_out->bufferSize(); } static uint32_t out_get_channels(const struct audio_stream *stream) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); return out->legacy_out->channels(); } static int out_get_format(const struct audio_stream *stream) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); return out->legacy_out->format(); } static int out_set_format(struct audio_stream *stream, int format) { struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); LOGE("(%s:%d) %s: Implement me!", __FILE__, __LINE__, __func__); /* TODO: implement me */ return 0; } static int out_standby(struct audio_stream *stream) { struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); return out->legacy_out->standby(); } static int out_dump(const struct audio_stream *stream, int fd) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); Vector<String16> args; return out->legacy_out->dump(fd, args); } static int out_set_parameters(struct audio_stream *stream, const char *kvpairs) { struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); return out->legacy_out->setParameters(String8(kvpairs)); } static char * out_get_parameters(const struct audio_stream *stream, const char *keys) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); String8 s8; s8 = out->legacy_out->getParameters(String8(keys)); return strdup(s8.string()); } static uint32_t out_get_latency(const struct audio_stream_out *stream) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); return out->legacy_out->latency(); } static int out_set_volume(struct audio_stream_out *stream, float left, float right) { struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); return out->legacy_out->setVolume(left, right); } static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes) { struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); return out->legacy_out->write(buffer, bytes); } static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames) { const struct legacy_stream_out *out = reinterpret_cast<const struct legacy_stream_out *>(stream); return out->legacy_out->getRenderPosition(dsp_frames); } static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { return 0; } static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { return 0; } /** audio_stream_in implementation **/ static uint32_t in_get_sample_rate(const struct audio_stream *stream) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); return in->legacy_in->sampleRate(); } static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); LOGE("(%s:%d) %s: Implement me!", __FILE__, __LINE__, __func__); /* TODO: implement this */ return 0; } static size_t in_get_buffer_size(const struct audio_stream *stream) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); return in->legacy_in->bufferSize(); } static uint32_t in_get_channels(const struct audio_stream *stream) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); return in->legacy_in->channels(); } static int in_get_format(const struct audio_stream *stream) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); return in->legacy_in->format(); } static int in_set_format(struct audio_stream *stream, int format) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); LOGE("(%s:%d) %s: Implement me!", __FILE__, __LINE__, __func__); /* TODO: implement me */ return 0; } static int in_standby(struct audio_stream *stream) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); return in->legacy_in->standby(); } static int in_dump(const struct audio_stream *stream, int fd) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); Vector<String16> args; return in->legacy_in->dump(fd, args); } static int in_set_parameters(struct audio_stream *stream, const char *kvpairs) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); return in->legacy_in->setParameters(String8(kvpairs)); } static char * in_get_parameters(const struct audio_stream *stream, const char *keys) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); String8 s8; s8 = in->legacy_in->getParameters(String8(keys)); return strdup(s8.string()); } static int in_set_gain(struct audio_stream_in *stream, float gain) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); return in->legacy_in->setGain(gain); } static ssize_t in_read(struct audio_stream_in *stream, void* buffer, size_t bytes) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); return in->legacy_in->read(buffer, bytes); } static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream) { struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); return in->legacy_in->getInputFramesLost(); } static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); return in->legacy_in->addAudioEffect(effect); } static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { const struct legacy_stream_in *in = reinterpret_cast<const struct legacy_stream_in *>(stream); return in->legacy_in->removeAudioEffect(effect); } /** audio_hw_device implementation **/ static inline struct legacy_audio_device * to_ladev(struct audio_hw_device *dev) { return reinterpret_cast<struct legacy_audio_device *>(dev); } static inline const struct legacy_audio_device * to_cladev(const struct audio_hw_device *dev) { return reinterpret_cast<const struct legacy_audio_device *>(dev); } static uint32_t adev_get_supported_devices(const struct audio_hw_device *dev) { /* XXX: The old AudioHardwareInterface interface is not smart enough to * tell us this, so we'll lie and basically tell AF that we support the * below input/output devices and cross our fingers. To do things properly, * audio hardware interfaces that need advanced features (like this) should * convert to the new HAL interface and not use this wrapper. */ return (/* OUT */ AUDIO_DEVICE_OUT_EARPIECE | AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_WIRED_HEADSET | AUDIO_DEVICE_OUT_WIRED_HEADPHONE | AUDIO_DEVICE_OUT_AUX_DIGITAL | AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET | AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET | AUDIO_DEVICE_OUT_ALL_SCO | AUDIO_DEVICE_OUT_DEFAULT | /* IN */ AUDIO_DEVICE_IN_COMMUNICATION | AUDIO_DEVICE_IN_AMBIENT | AUDIO_DEVICE_IN_BUILTIN_MIC | AUDIO_DEVICE_IN_WIRED_HEADSET | AUDIO_DEVICE_IN_AUX_DIGITAL | AUDIO_DEVICE_IN_BACK_MIC | AUDIO_DEVICE_IN_ALL_SCO | AUDIO_DEVICE_IN_DEFAULT); } static int adev_init_check(const struct audio_hw_device *dev) { const struct legacy_audio_device *ladev = to_cladev(dev); return ladev->hwif->initCheck(); } static int adev_set_voice_volume(struct audio_hw_device *dev, float volume) { struct legacy_audio_device *ladev = to_ladev(dev); return ladev->hwif->setVoiceVolume(volume); } static int adev_set_master_volume(struct audio_hw_device *dev, float volume) { struct legacy_audio_device *ladev = to_ladev(dev); return ladev->hwif->setMasterVolume(volume); } static int adev_set_mode(struct audio_hw_device *dev, int mode) { struct legacy_audio_device *ladev = to_ladev(dev); return ladev->hwif->setMode(mode); } static int adev_set_mic_mute(struct audio_hw_device *dev, bool state) { struct legacy_audio_device *ladev = to_ladev(dev); return ladev->hwif->setMicMute(state); } static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state) { const struct legacy_audio_device *ladev = to_cladev(dev); return ladev->hwif->getMicMute(state); } static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs) { struct legacy_audio_device *ladev = to_ladev(dev); return ladev->hwif->setParameters(String8(kvpairs)); } static char * adev_get_parameters(const struct audio_hw_device *dev, const char *keys) { const struct legacy_audio_device *ladev = to_cladev(dev); String8 s8; s8 = ladev->hwif->getParameters(String8(keys)); return strdup(s8.string()); } static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev, uint32_t sample_rate, int format, int channel_count) { const struct legacy_audio_device *ladev = to_cladev(dev); return ladev->hwif->getInputBufferSize(sample_rate, format, channel_count); } static int adev_open_output_stream(struct audio_hw_device *dev, uint32_t devices, int *format, uint32_t *channels, uint32_t *sample_rate, struct audio_stream_out **stream_out) { struct legacy_audio_device *ladev = to_ladev(dev); status_t status; struct legacy_stream_out *out; int ret; out = (struct legacy_stream_out *)calloc(1, sizeof(*out)); if (!out) return -ENOMEM; out->legacy_out = ladev->hwif->openOutputStream(devices, format, channels, sample_rate, &status); if (!out->legacy_out) { ret = status; goto err_open; } out->stream.common.get_sample_rate = out_get_sample_rate; out->stream.common.set_sample_rate = out_set_sample_rate; out->stream.common.get_buffer_size = out_get_buffer_size; out->stream.common.get_channels = out_get_channels; out->stream.common.get_format = out_get_format; out->stream.common.set_format = out_set_format; out->stream.common.standby = out_standby; out->stream.common.dump = out_dump; out->stream.common.set_parameters = out_set_parameters; out->stream.common.get_parameters = out_get_parameters; out->stream.common.add_audio_effect = out_add_audio_effect; out->stream.common.remove_audio_effect = out_remove_audio_effect; out->stream.get_latency = out_get_latency; out->stream.set_volume = out_set_volume; out->stream.write = out_write; out->stream.get_render_position = out_get_render_position; *stream_out = &out->stream; return 0; err_open: free(out); *stream_out = NULL; return ret; } static void adev_close_output_stream(struct audio_hw_device *dev, struct audio_stream_out* stream) { struct legacy_audio_device *ladev = to_ladev(dev); struct legacy_stream_out *out = reinterpret_cast<struct legacy_stream_out *>(stream); ladev->hwif->closeOutputStream(out->legacy_out); free(out); } /** This method creates and opens the audio hardware input stream */ static int adev_open_input_stream(struct audio_hw_device *dev, uint32_t devices, int *format, uint32_t *channels, uint32_t *sample_rate, audio_in_acoustics_t acoustics, struct audio_stream_in **stream_in) { struct legacy_audio_device *ladev = to_ladev(dev); status_t status; struct legacy_stream_in *in; int ret; in = (struct legacy_stream_in *)calloc(1, sizeof(*in)); if (!in) return -ENOMEM; in->legacy_in = ladev->hwif->openInputStream(devices, format, channels, sample_rate, &status, (AudioSystem::audio_in_acoustics)acoustics); if (!in->legacy_in) { ret = status; goto err_open; } in->stream.common.get_sample_rate = in_get_sample_rate; in->stream.common.set_sample_rate = in_set_sample_rate; in->stream.common.get_buffer_size = in_get_buffer_size; in->stream.common.get_channels = in_get_channels; in->stream.common.get_format = in_get_format; in->stream.common.set_format = in_set_format; in->stream.common.standby = in_standby; in->stream.common.dump = in_dump; in->stream.common.set_parameters = in_set_parameters; in->stream.common.get_parameters = in_get_parameters; in->stream.common.add_audio_effect = in_add_audio_effect; in->stream.common.remove_audio_effect = in_remove_audio_effect; in->stream.set_gain = in_set_gain; in->stream.read = in_read; in->stream.get_input_frames_lost = in_get_input_frames_lost; *stream_in = &in->stream; return 0; err_open: free(in); *stream_in = NULL; return ret; } static void adev_close_input_stream(struct audio_hw_device *dev, struct audio_stream_in *stream) { struct legacy_audio_device *ladev = to_ladev(dev); struct legacy_stream_in *in = reinterpret_cast<struct legacy_stream_in *>(stream); ladev->hwif->closeInputStream(in->legacy_in); free(in); } static int adev_dump(const struct audio_hw_device *dev, int fd) { const struct legacy_audio_device *ladev = to_cladev(dev); Vector<String16> args; return ladev->hwif->dumpState(fd, args); } static int legacy_adev_close(hw_device_t* device) { struct audio_hw_device *hwdev = reinterpret_cast<struct audio_hw_device *>(device); struct legacy_audio_device *ladev = to_ladev(hwdev); if (!ladev) return 0; if (ladev->hwif) delete ladev->hwif; free(ladev); return 0; } static int legacy_adev_open(const hw_module_t* module, const char* name, hw_device_t** device) { struct legacy_audio_device *ladev; int ret; if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL; ladev = (struct legacy_audio_device *)calloc(1, sizeof(*ladev)); if (!ladev) return -ENOMEM; ladev->device.common.tag = HARDWARE_DEVICE_TAG; ladev->device.common.version = 0; ladev->device.common.module = const_cast<hw_module_t*>(module); ladev->device.common.close = legacy_adev_close; ladev->device.get_supported_devices = adev_get_supported_devices; ladev->device.init_check = adev_init_check; ladev->device.set_voice_volume = adev_set_voice_volume; ladev->device.set_master_volume = adev_set_master_volume; ladev->device.set_mode = adev_set_mode; ladev->device.set_mic_mute = adev_set_mic_mute; ladev->device.get_mic_mute = adev_get_mic_mute; ladev->device.set_parameters = adev_set_parameters; ladev->device.get_parameters = adev_get_parameters; ladev->device.get_input_buffer_size = adev_get_input_buffer_size; ladev->device.open_output_stream = adev_open_output_stream; ladev->device.close_output_stream = adev_close_output_stream; ladev->device.open_input_stream = adev_open_input_stream; ladev->device.close_input_stream = adev_close_input_stream; ladev->device.dump = adev_dump; ladev->hwif = createAudioHardware(); if (!ladev->hwif) { ret = -EIO; goto err_create_audio_hw; } *device = &ladev->device.common; return 0; err_create_audio_hw: free(ladev); return ret; } static struct hw_module_methods_t legacy_audio_module_methods = { open: legacy_adev_open }; struct legacy_audio_module HAL_MODULE_INFO_SYM = { module: { common: { tag: HARDWARE_MODULE_TAG, version_major: 1, version_minor: 0, id: AUDIO_HARDWARE_MODULE_ID, name: "LEGACY Audio HW HAL", author: "The Android Open Source Project", methods: &legacy_audio_module_methods, dso : NULL, reserved : {0}, }, }, }; }; // extern "C" }; // namespace android_audio_legacy
32.018152
93
0.695769
[ "vector" ]
e6846e542ded5ddc6da34f84e74b2a549bbed210
1,914
hpp
C++
vcl/interaction/light_animation_data/light_animation_data.hpp
vogr/OceanGL
e894df3319243b8ee2102856785ab3a9930e0029
[ "MIT" ]
null
null
null
vcl/interaction/light_animation_data/light_animation_data.hpp
vogr/OceanGL
e894df3319243b8ee2102856785ab3a9930e0029
[ "MIT" ]
null
null
null
vcl/interaction/light_animation_data/light_animation_data.hpp
vogr/OceanGL
e894df3319243b8ee2102856785ab3a9930e0029
[ "MIT" ]
null
null
null
#pragma once #include <vcl/interaction/camera/camera.hpp> #include <vcl/wrapper/glad/glad.hpp> namespace vcl { enum class DrawType { STANDARD, PASS0, PASS1 }; class light_animation_data { public: light_animation_data() = default; light_animation_data(GLuint shader0, GLuint shader1); mat4 orthographic_projection_matrix() const; vcl::vec3 fog_color {0.282, 0.239, 0.545}; float fog_intensity_linear = 0.3; float fog_intensity_exp = 0.01; // /!\ We use a camera but camera_scene light_camera; GLuint shader_pass0{0}; GLuint shader_pass1{0}; float view_size = 500.; float z_near = 0.1f; float z_far = 400.f; // framebuffer object : will be used as rendering target in first // pass (off-line rendering). It will contain a simple texture `depth` GLuint light_view_fbo{0}; // Handle to the texture stored in light_view_fbo. This texture // will be filled by the first pass, and read from at the second pass. // When viewed from the the light source point of view, a fragment at position (x,y) has // a depth z. This texture stores the depth of the fragment closest to the light source // at position (x,y) : i.e. if we determine that a fragment (when viewed by the user) is // at this depth (when viewed by the light source), then we know that it is directly illuminated // by the light source (no obstruction), and therefore we can draw a caustics animation. // WARNING : as a texture, it should nbe indexed by values in [0,1]. // (x,y) in [-1,1] needs to be mapped to a value in [0,1] GLuint depth_texture_id{0}; // Id to the caustices texture that will be used to draw. // Should be changed on each iteration. GLuint caustics_sprite_id{0}; }; }
37.529412
104
0.643156
[ "object" ]
e6898d7ac640a6746d5f555bdce121fe7d7ed0d1
626
cpp
C++
src/QModel/SqliteModelIndex.cpp
bradosia/BookFiler-Lib-Sort-Filter-Table-Widget
6d4b99ed27eb6b43f6ac0495a8adb02bec5c801e
[ "MIT" ]
2
2021-02-25T05:09:29.000Z
2022-01-12T03:27:26.000Z
src/QModel/SqliteModelIndex.cpp
bradosia/BookFiler-Lib-Sort-Filter-Table-Widget
6d4b99ed27eb6b43f6ac0495a8adb02bec5c801e
[ "MIT" ]
null
null
null
src/QModel/SqliteModelIndex.cpp
bradosia/BookFiler-Lib-Sort-Filter-Table-Widget
6d4b99ed27eb6b43f6ac0495a8adb02bec5c801e
[ "MIT" ]
1
2020-12-11T17:19:44.000Z
2020-12-11T17:19:44.000Z
/* * @name BookFiler Widget - Sqlite Model * @author Branden Lee * @version 1.00 * @license MIT * @brief QAbstractItemModel with a sqlite3 backend. */ #if DEPENDENCY_SQLITE // C++ #include <iostream> // Local Project #include "SqliteModelIndex.hpp" /* * bookfiler - widget */ namespace bookfiler { namespace widget { SqliteModelIndex::SqliteModelIndex() {} SqliteModelIndex::~SqliteModelIndex() {} int SqliteModelIndex::setParent(SqliteModelIndex *parentIndex_) { parentIndex = parentIndex_; return 0; } int SqliteModelIndex::run() { return 0; } } // namespace widget } // namespace bookfiler #endif
15.65
65
0.71246
[ "model" ]
e695410a7d14de262beba871fe0e69aca3485e61
4,105
hpp
C++
src/BayesW.hpp
medical-genomics-group/hydra
d352f1096d8397a36d6984ff7ea944bdb6c4e1d5
[ "MIT" ]
7
2020-09-09T08:35:24.000Z
2021-11-14T16:09:12.000Z
src/BayesW.hpp
medical-genomics-group/hydra
d352f1096d8397a36d6984ff7ea944bdb6c4e1d5
[ "MIT" ]
2
2020-12-09T14:48:15.000Z
2021-04-23T09:56:24.000Z
src/BayesW.hpp
medical-genomics-group/hydra
d352f1096d8397a36d6984ff7ea944bdb6c4e1d5
[ "MIT" ]
1
2020-10-11T12:33:25.000Z
2020-10-11T12:33:25.000Z
/* * BayesRRm.h * * Created on: 5 Sep 2018 * Author: admin */ #ifndef SRC_BAYESW_HPP_ #define SRC_BAYESW_HPP_ #include "BayesRRm.h" #include "data.hpp" #include "options.hpp" #include "distributions_boost.hpp" #include <Eigen/Eigen> // Three structures for ARS struct pars{ /* Common parameters for the densities */ VectorXd epsilon; // epsilon per subject (before each sampling, need to remove the effect of the sampled parameter and then carry on //Probably unnecessary to store mixture classes //VectorXd mixture_classes; // Vector to store mixture component C_k values //int used_mixture; //Write the index of the mixture we decide to use /* Store the current variables */ double alpha; /* Beta_j - specific variables */ VectorXd X_j; /* of sum(X_j*failure) */ double sum_failure; /* Mu-specific variables */ double sigma_mu; /* sigma_b-specific variables */ double alpha_sigma, beta_sigma; /* Number of events (sum of failure indicators) */ double d; }; struct pars_beta_sparse{ /* Common parameters for the densities */ double mixture_value; // Instead of storing the vector of mixtures and the corresponding index, we keep only the mixture value in the structure /* Store the current variables */ double alpha, sigmaG; /* Beta_j - specific variables */ double vi_0, vi_1, vi_2; // Sums of vi elements // Mean, std dev and their ratio for snp j double mean, sd, mean_sd_ratio; /* of sum(X_j*failure) */ double sum_failure; /* Number of events (sum of failure indicators) */ double d; }; struct pars_alpha{ VectorXd failure_vector; VectorXd epsilon; // epsilon per subject (before each sampling, need to remove the effect of the sampled parameter and then carry on /* Alpha-specific variables */ double alpha_0, kappa_0; /* Prior parameters */ /* Number of events (sum of failure indicators) */ double d; }; class BayesW : public BayesRRm { public: const double alpha_0 = 0.01; const double kappa_0 = 0.01; const double sigma_mu = 100; const double alpha_sigma = 1; const double beta_sigma = 0.0001; const string quad_points = opt.quad_points; // Number of Gaussian quadrature points unsigned int K = opt.S.size()+1; //number of mixtures + 0 class unsigned int km1 = opt.S.size(); //number of mixtures const size_t LENBUF_gamma = 3500; //Not more than 160 "fixed effects can be used at the moment // The ARS structures struct pars used_data; struct pars_beta_sparse used_data_beta; struct pars_alpha used_data_alpha; // Component variables MatrixXd pi_L; // mixture probabilities VectorXd marginal_likelihoods; // likelihood for each mixture component (for specific group) VectorXd marginal_likelihood_0; // 0th likelihood for each group component int numGroups; VectorXi groups; // Linear model variables VectorXd vi; //VectorXd y; BayesW(Data &data, Options &opt, const long memPageSize) : BayesRRm(data, opt, memPageSize) { }; virtual ~BayesW(); #ifdef USE_MPI int runMpiGibbs_bW(); #endif private: void init(unsigned int individualCount, unsigned int Mtot, unsigned int fixedCount); void init_from_restart(const int K, const uint M, const uint Mtot, const uint Ntot, const uint fixtot, const int* MrankS, const int* MrankL, const bool use_xfiles_in_restart); void marginal_likelihood_vec_calc(VectorXd prior_prob, VectorXd &post_marginals, string n, double vi_sum, double vi_2,double vi_1, double vi_0, double mean, double sd, double mean_sd_ratio, unsigned int group_index); double gauss_hermite_adaptive_integral(double C_k, double sigma, string n, double vi_sum, double vi_2, double vi_1, double vi_0, double mean, double sd, double mean_sd_ratio); double partial_sum(const double* __restrict__ vec, const uint* __restrict__ IX, const size_t NXS, const size_t NXL); // VectorXd getSnpData(unsigned int marker) const; // void printDebugInfo() const; }; #endif /* SRC_BAYESW_HPP_ */
30.183824
217
0.711328
[ "vector", "model" ]
e6972d503562dbb99fcae87d85f0bce13d01f9e4
1,969
cpp
C++
DammitGLFW/Camera.cpp
SuniTheFish/DammitGLFW
bf80928ba1bbc439b06a54098110d8dff7388e38
[ "MIT" ]
null
null
null
DammitGLFW/Camera.cpp
SuniTheFish/DammitGLFW
bf80928ba1bbc439b06a54098110d8dff7388e38
[ "MIT" ]
null
null
null
DammitGLFW/Camera.cpp
SuniTheFish/DammitGLFW
bf80928ba1bbc439b06a54098110d8dff7388e38
[ "MIT" ]
null
null
null
#include "Camera.h" void Camera::updateCameraVectors() { // Calculate the new Front vector glm::vec3 front { cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)), // x sin(glm::radians(m_pitch)), // y sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)) // z }; m_front = glm::normalize(front); // Also re-calculate the Right and Up vector m_right = glm::normalize(glm::cross(m_front, m_worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. m_up = glm::normalize(glm::cross(m_right, m_front)); } glm::mat4 Camera::getViewMatrix() { return glm::lookAt(m_position, m_position + m_front, m_up); } void Camera::processKeyboard(Camera_Movement direction, float deltaTime) { float velocity = m_movementSpeed * deltaTime; switch (direction) { case Camera::FORWARD: m_position += m_front * velocity; break; case Camera::BACKWARD: m_position -= m_front * velocity; break; case Camera::LEFT: m_position -= m_right * velocity; break; case Camera::RIGHT: m_position += m_right * velocity; break; case Camera::UP: m_position += m_up * velocity; break; case Camera::DOWN: m_position -= m_up * velocity; break; default: throw "Invalid Direction"; break; } } void Camera::processMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch) { xoffset *= m_mouseSensitivity; yoffset *= m_mouseSensitivity; m_yaw += xoffset; m_pitch += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (m_pitch > 89.0f) m_pitch = 89.0f; if (m_pitch < -89.0f) m_pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Euler angles updateCameraVectors(); } void Camera::processMouseScroll(float yoffset) { if (m_zoom >= 1.0f && m_zoom <= 45.0f) m_zoom -= yoffset; if (m_zoom <= 1.0f) m_zoom = 1.0f; if (m_zoom >= 45.0f) m_zoom = 45.0f; }
24.308642
186
0.693245
[ "vector" ]
e69c93c06176e475312cf1bcf7b51b2ef7cb09db
5,294
hpp
C++
include/Objects.hpp
jLantxa/PathTracer
37dabfeefebd16799357233242b76eed1f0cd2ab
[ "Apache-2.0" ]
null
null
null
include/Objects.hpp
jLantxa/PathTracer
37dabfeefebd16799357233242b76eed1f0cd2ab
[ "Apache-2.0" ]
5
2018-07-11T22:13:05.000Z
2018-07-13T21:22:29.000Z
include/Objects.hpp
jLantxa/PathTracer
37dabfeefebd16799357233242b76eed1f0cd2ab
[ "Apache-2.0" ]
null
null
null
/* * This source file is part of PathTracer * * Copyright 2018, 2019 Javier Lancha Vázquez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _INCLUDE_PATHTRACER_OBJECTS_H_ #define _INCLUDE_PATHTRACER_OBJECTS_H_ #include "Common.hpp" #include "Light.hpp" #include "Vector3D.hpp" #include <vector> /* Object library * These are the primitives to build a 3D scene. Any mesh can be constructed * simply by means of Triangle objects. Some more complex objects are also * provided. * * Available objects: * - Plane * - Triangle * - Sphere */ struct Material { Color color; Color emission; }; struct Enclosure { Real x_min, x_max; Real y_min, y_max; Real z_min, z_max; }; /** * 3D Object base */ class IObject3D { public: IObject3D(struct Material material); virtual ~IObject3D(); /** Returns the intersection point of the ray and the object * as the distance from the ray's origin in the direction of the ray. */ virtual Real intersect(Ray& ray) = 0; /** Returns a vector normal to the object's surface in a given point * and hit direction. */ virtual Vec3D getHitNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v) = 0; /** Returns a vector normal to the object's surface in a given point * facing out of the object */ virtual Vec3D getSurfaceNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v) = 0; virtual struct Enclosure getEnclosure() = 0; struct Material& material(); Color& color(); protected: struct Material mMaterial; }; /** A container of objects and light sources */ /// \todo Delete objects struct Scene { std::vector<IObject3D*> objects; Color backgroundColor; }; /// \todo Define a Cube object /// \todo Define a Square object /** A plane object derived from the IObject3D base */ class Plane : public IObject3D { public: Plane(struct Material material, Vec3D position_v, Vec3D normal_v); virtual ~Plane(); virtual Real intersect(Ray& ray); virtual Vec3D getHitNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); virtual Vec3D getSurfaceNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); virtual struct Enclosure getEnclosure(); private: Vec3D mPosition_v; Vec3D mNormal_v; }; /** A triangle object derived from the IObject3D base * Surface normal depends on the order of (A, B, C) */ class Triangle : public IObject3D { public: /** A colour and vertices A, B and C */ Triangle(struct Material material, Vec3D A_v, Vec3D B_v, Vec3D C_v); virtual ~Triangle(); virtual Real intersect(Ray& ray); virtual Vec3D getHitNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); virtual Vec3D getSurfaceNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); virtual struct Enclosure getEnclosure(); private: Vec3D mA_v, mB_v, mC_v; Vec3D mNormal_v; }; /** A sphere object derived from the IObject3D base */ class Sphere : public IObject3D { public: Sphere(struct Material material, Vec3D center_v, Real radius); virtual ~Sphere(); virtual Real intersect(Ray& ray); virtual Vec3D getHitNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); virtual Vec3D getSurfaceNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); /// \todo Return the cubic enclosure of the sphere virtual struct Enclosure getEnclosure(); Vec3D center() { return mCenter_v; } Real radius() { return mRadius; } private: Vec3D mCenter_v; Real mRadius; }; /** A CompositeObject3D groups an arbitrary number of IObject3D entities * into a single one. */ class CompositeObject3D : public IObject3D { public: CompositeObject3D(); virtual ~CompositeObject3D() = 0; virtual Real intersect(Ray& ray); /* In the case of a CompositeObject3D we first need to calculate the * intersections to determine what object in the composite we hit */ virtual Vec3D getHitNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); virtual Vec3D getSurfaceNormal(Vec3D& hitPoint_v, Vec3D& hitDirection_v); // Add object to vector virtual void addObject(IObject3D* object); // Get a reference to the children vector virtual std::vector<IObject3D*>& children(); virtual struct Enclosure getEnclosure(); protected: /** \todo Define a Cube object to use as a container boundary. * Can this pointer leak? */ IObject3D* mBoundary; struct Enclosure mEnclosure; std::vector<IObject3D*> mObjects; IObject3D* intersectedObject(Ray& ray); void updateBoundary(); }; #endif // _INCLUDE_PATHTRACER_OBJECTS_H_
28.159574
85
0.680582
[ "mesh", "object", "vector", "3d" ]
e69f3ed92eab824f0936d897504ef1d088cd3697
756
cpp
C++
Leetcode_challenges/Day6/longestconsecutivesequence.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Leetcode_challenges/Day6/longestconsecutivesequence.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Leetcode_challenges/Day6/longestconsecutivesequence.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; class Solution { public: int longestConsecutive(vector<int>& nums) { if(nums.size() == 0){ return 0; } else if(nums.size() == 1) return 1; sort(nums.begin(),nums.end()); int c =0; int m =0,i; for(i=0;i<nums.size()-1;i++){ if(nums[i+1]-nums[i] == 1){ c++; cout<<nums[i]<<endl; } else if(nums[i+1]-nums[i] >1 ){ c = 0; } if(c+1>m){ m = c+1; } } return m; } };
21.6
47
0.332011
[ "vector" ]
e69fd73ef33e45f62ce5f7f56ec3e694e30e8272
3,382
cpp
C++
src/pytorch/cpp/approx_linear_xA_b.cpp
adelmanm/approx
6a1e26b5996c464f7a47701cbd06c35865268d60
[ "BSD-3-Clause" ]
5
2021-07-08T12:28:27.000Z
2022-03-10T16:44:25.000Z
src/pytorch/cpp/approx_linear_xA_b.cpp
adelmanm/approx
6a1e26b5996c464f7a47701cbd06c35865268d60
[ "BSD-3-Clause" ]
null
null
null
src/pytorch/cpp/approx_linear_xA_b.cpp
adelmanm/approx
6a1e26b5996c464f7a47701cbd06c35865268d60
[ "BSD-3-Clause" ]
2
2021-10-20T04:29:11.000Z
2022-03-10T16:44:29.000Z
#include <torch/extension.h> /*********************************************************************** Applies approximate linear transformation to the incoming data: y = xA + b. Note: A is assumed not transposed the matrix multiply xA is approximated Shape: - Input: (N, *, in\_features) where `*` means any number of additional dimensions - Weight: (in\_features, out\_features) - Bias: (out\_features) - Output: (N, *, out\_features) **********************************************************************/ torch::Tensor approx_linear_xA_b_topk( const torch::Tensor& input, const torch::Tensor& weight, const torch::Tensor& bias, const float sample_ratio, const int64_t minimal_k) { //std::cout << "sample_ratio= " << sample_ratio << "minimal_k = " << minimal_k << std::endl; //calculate the number of column-row pairs to sample const int64_t in_features = weight.sizes()[0]; int64_t k_candidate = (int)((float)in_features*sample_ratio); //make k at least minimal_k int64_t k = std::min(std::max(k_candidate,minimal_k),in_features); //std::cout <<"k = " << k << std::endl; // if no sampling is required, perform exact computation if (k == in_features) { std::cout << "no sampling needed, executing regular matmul" << std::endl; if (input.dim() == 2 && bias.numel() != 0) { std::cout << "matmul with bias" << std::endl; return torch::addmm(bias,input,weight); } else { auto C_approx = torch::matmul(input, weight); if (bias.numel() == 0) { std::cout << "matmul without bias" << std::endl; return C_approx; } else { return torch::add(C_approx, bias); } } } // calculate norms of the columns of A and rows of B auto a_col_norms = (input.dim()==2) ? torch::frobenius_norm(input,{0}) : torch::frobenius_norm(input.view({-1,in_features}),{0}); auto b_row_norms = torch::frobenius_norm(weight,{1}); // multiply both norms element-wise to and pick the indices of the top K column-row pairs auto norm_mult = torch::mul(a_col_norms, b_row_norms); // pick topk indices. as of pytorch v1.1.0, it turns out that torch.sort[:k] is faster than torch.topk //auto top_k_indices = std::get<1>(torch::topk(norm_mult, k, -1,true,false)); auto top_k_indices = torch::argsort(norm_mult,0,true).narrow(0,0,k); // pick top-k column-row pairs to form new smaller matrices auto A_top_k_cols = torch::index_select(input, -1, top_k_indices); auto B_top_k_rows = torch::index_select(weight, 0, top_k_indices); //multiply smaller matrices if (input.dim() == 2 && bias.numel() != 0) { //std::cout << "matmul with bias" << std::endl; return torch::addmm(bias,A_top_k_cols,B_top_k_rows); } else { auto C_approx = torch::matmul(A_top_k_cols, B_top_k_rows); if (bias.numel() == 0) { std::cout << "matmul without bias" << std::endl; return C_approx; } else { return torch::add(C_approx, bias); } } } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("topk", &approx_linear_xA_b_topk, "Approx linear topk cpp"); }
37.164835
133
0.575991
[ "shape" ]
e6a0bdfa89fcfb9c0706d44e684a5d55af6dd89a
8,449
cc
C++
xmysqlnd/xmysqlnd_index_collection_commands.cc
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
14
2017-11-16T03:13:31.000Z
2022-03-10T14:59:53.000Z
xmysqlnd/xmysqlnd_index_collection_commands.cc
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
8
2018-03-02T06:08:27.000Z
2022-01-18T10:34:43.000Z
xmysqlnd/xmysqlnd_index_collection_commands.cc
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
18
2018-03-01T13:45:16.000Z
2022-03-10T06:30:02.000Z
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Darek Slusarczyk <marines@php.net> | +----------------------------------------------------------------------+ */ #include "php_api.h" #include "mysqlnd_api.h" #include "xmysqlnd.h" #include "xmysqlnd_driver.h" #include "xmysqlnd_session.h" #include "xmysqlnd_schema.h" #include "xmysqlnd_collection.h" #include "xmysqlnd_stmt.h" #include "xmysqlnd_stmt_result_meta.h" #include "xmysqlnd_utils.h" #include "xmysqlnd_zval2any.h" #include "xmysqlnd_wireprotocol.h" #include "xmysqlnd_index_collection_commands.h" #include "mysqlx_object.h" #include "mysqlx_class_properties.h" #include "proto_gen/mysqlx_sql.pb.h" #include "proto_gen/mysqlx_expr.pb.h" #include "util/allocator.h" #include "util/object.h" #include "util/pb_utils.h" #include "util/strings.h" #include "util/string_utils.h" #include "util/types.h" #include "xmysqlnd/crud_parsers/mysqlx_crud_parser.h" #include "xmysqlnd/crud_parsers/expression_parser.h" #include <boost/algorithm/string/predicate.hpp> namespace mysqlx { namespace drv { bool Index_field::is_geojson() const { return boost::iequals(type, "GEOJSON"); } bool Index_field::is_required() const { return required ? required.value() : is_geojson(); } // ----------------------------------------------------------------------------- Index_definition::Index_definition(const util::string_view& index_name) : name(index_name) , is_unique(false) //TODO temporary - shouldn't be needed in future version of server { if (index_name.empty()) { throw std::invalid_argument("empty index name"); } } std::optional<util::string> Index_definition::get_type_str() const { using Type_to_str = std::map<Index_definition::Type, std::string>; static const Type_to_str type_to_str = { { Index_definition::Type::Index, "INDEX" }, { Index_definition::Type::Spatial, "SPATIAL" } }; if (type) { return util::to_string(type_to_str.at(type.value())); } return std::nullopt; } /****************************** COLLECTION.CREATE_INDEX() *******************************************************/ namespace { struct collection_create_index_var_binder_ctx { const util::string_view schema_name; const util::string_view collection_name; const Index_definition& index_def; }; class Bind_create_index_args { public: Bind_create_index_args( Mysqlx::Sql::StmtExecute& stmt_message, const collection_create_index_var_binder_ctx& ctx); public: void run(); private: void bind_index_args(); void bind_index_fields(); private: const collection_create_index_var_binder_ctx& ctx; util::pb::Object* idx_obj{nullptr}; }; Bind_create_index_args::Bind_create_index_args( Mysqlx::Sql::StmtExecute& stmt_message, const collection_create_index_var_binder_ctx& ctx) : ctx{ctx} , idx_obj{util::pb::add_object_arg(stmt_message)} { } void Bind_create_index_args::run() { bind_index_args(); bind_index_fields(); } void Bind_create_index_args::bind_index_args() { const Index_definition& index_def = ctx.index_def; util::pb::add_field_to_object("schema", ctx.schema_name, idx_obj); util::pb::add_field_to_object("collection", ctx.collection_name, idx_obj); util::pb::add_field_to_object("name", index_def.name, idx_obj); util::pb::add_optional_field_to_object("type", index_def.get_type_str(), idx_obj); util::pb::add_optional_field_to_object("unique", index_def.is_unique, idx_obj); } void Bind_create_index_args::bind_index_fields() { std::unique_ptr<util::pb::Array> fields{std::make_unique<util::pb::Array>()}; for (auto field : ctx.index_def.fields) { std::unique_ptr<util::pb::Object> pb_obj{std::make_unique<util::pb::Object>()}; util::pb::add_field_to_object("member", field.path, pb_obj); util::pb::add_field_to_object("type", field.type, pb_obj); util::pb::add_field_to_object("required", field.is_required(), pb_obj); if (field.is_geojson()) { util::pb::add_optional_field_to_object("options", field.options, pb_obj); util::pb::add_optional_field_to_object("srid", field.srid, pb_obj); } util::pb::add_optional_field_to_object("array", field.is_array, pb_obj); util::pb::add_value_to_array(pb_obj.release(), fields); } util::pb::add_field_to_object("constraint", fields.release(), idx_obj); } const enum_hnd_func_status collection_create_index_var_binder( void* context, XMYSQLND_SESSION session, XMYSQLND_STMT_OP__EXECUTE* const stmt_execute) { DBG_ENTER("collection_create_index_var_binder"); collection_create_index_var_binder_ctx* ctx = static_cast<collection_create_index_var_binder_ctx*>(context); Mysqlx::Sql::StmtExecute& stmt_message = xmysqlnd_stmt_execute__get_pb_msg(stmt_execute); Bind_create_index_args bind_args(stmt_message, *ctx); bind_args.run(); DBG_RETURN(HND_PASS); } } // anonymous namespace bool collection_create_index_execute( XMYSQLND_SESSION session, const util::string_view& schema_name, const util::string_view& collection_name, const Index_definition& index_def, st_xmysqlnd_session_on_error_bind on_error) { DBG_ENTER("collection_create_index_execute"); constexpr util::string_view query("create_collection_index"); collection_create_index_var_binder_ctx var_binder_ctx{ schema_name, collection_name, index_def }; const st_xmysqlnd_session_query_bind_variable_bind var_binder{ collection_create_index_var_binder, &var_binder_ctx }; const enum_func_status ret = session->query_cb( namespace_mysqlx, query, var_binder, noop__on_result_start, noop__on_row, noop__on_warning, on_error, noop__on_result_end, noop__on_statement_ok); DBG_RETURN(ret == PASS); } /****************************** COLLECTION.DROP_INDEX() *******************************************************/ namespace { struct collection_drop_index_var_binder_ctx { const util::string_view schema_name; const util::string_view collection_name; const util::string_view index_name; }; const enum_hnd_func_status collection_drop_index_var_binder( void* context, XMYSQLND_SESSION session, XMYSQLND_STMT_OP__EXECUTE* const stmt_execute) { DBG_ENTER("collection_drop_index_var_binder"); collection_drop_index_var_binder_ctx* ctx = static_cast<collection_drop_index_var_binder_ctx*>(context); Mysqlx::Sql::StmtExecute& stmt_message = xmysqlnd_stmt_execute__get_pb_msg(stmt_execute); util::pb::Object* idx_obj{util::pb::add_object_arg(stmt_message)}; util::pb::add_field_to_object("schema", ctx->schema_name, idx_obj); util::pb::add_field_to_object("collection", ctx->collection_name, idx_obj); util::pb::add_field_to_object("name", ctx->index_name, idx_obj); DBG_RETURN(HND_PASS); } } // anonymous namespace bool collection_drop_index_execute( XMYSQLND_SESSION session, const util::string_view& schema_name, const util::string_view& collection_name, const util::string_view& index_name, st_xmysqlnd_session_on_error_bind on_error) { DBG_ENTER("xmysqlnd_collection_drop_index__execute"); constexpr util::string_view query("drop_collection_index"); collection_drop_index_var_binder_ctx var_binder_ctx{ schema_name, collection_name, index_name }; const st_xmysqlnd_session_query_bind_variable_bind var_binder{ collection_drop_index_var_binder, &var_binder_ctx }; const enum_func_status ret = session->query_cb( namespace_mysqlx, query, var_binder, noop__on_result_start, noop__on_row, noop__on_warning, on_error, noop__on_result_end, noop__on_statement_ok); DBG_RETURN(ret == PASS); } } // namespace drv } // namespace mysqlx
28.447811
114
0.698544
[ "object" ]
e6a693b9d9f20bac64a4df7f7c3b4e393e866085
541
cpp
C++
codechef/feb18/1.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
codechef/feb18/1.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
codechef/feb18/1.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(int argc, char const *argv[]){ int t; cin>>t; while(t--){ int n; cin>>n; int max1=0,max2=0; int sum1=0,sum2=0; for(int i=0;i<n;i++){ int x; cin>>x; if(x>max1) max1=x; sum1+=x; } for(int i=0;i<n;i++){ int x; cin>>x; if(x>max2) max2=x; sum2+=x; } if((sum1-max1)<(sum2-max2)){ cout<<"Alice\n"; }else if((sum1-max1)>(sum2-max2)){ cout<<"Bob\n"; }else cout<<"Draw\n"; } return 0; }
15.911765
39
0.55268
[ "vector" ]
e6ab32f34c151d416484080513c6642ee278eafc
4,496
cpp
C++
src/CgiHelper.cpp
praveenster/leplib
f3db88d9e0ca72be7faec820590f17f576b93b75
[ "MIT" ]
1
2018-10-30T07:43:42.000Z
2018-10-30T07:43:42.000Z
src/CgiHelper.cpp
praveenster/leplib
f3db88d9e0ca72be7faec820590f17f576b93b75
[ "MIT" ]
7
2015-02-03T18:40:35.000Z
2015-05-04T06:33:20.000Z
src/CgiHelper.cpp
praveenster/leplib
f3db88d9e0ca72be7faec820590f17f576b93b75
[ "MIT" ]
null
null
null
/* Copyright (c) 2011 Neevarp Yhtroom 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 <cstdio> #include <cstdlib> #include <ctime> #include <vector> #include "CgiHelper.h" using std::vector; using std::map; namespace lep { const String CgiHelper::kHttpHost = "HTTP_HOST"; const String CgiHelper::kHttpUserAgent = "HTTP_USER_AGENT"; const String CgiHelper::kRemoteAddress = "REMOTE_ADDR"; const String CgiHelper::kPathInfo = "PATH_INFO"; const String CgiHelper::kQueryString = "QUERY_STRING"; const int CgiHelper::kHttpOk = 200; const int kOutputFileBufferSize = 1024; CgiHelper::CgiHelper() : environment_variables_(), url_parameters_(), path_elements_() { } CgiHelper::~CgiHelper() { } void CgiHelper::OutputHeader(int http_status, int content_length, const String& server_name, const String& mime_type) { String status; switch (http_status) { default: case kHttpOk: status = "200 OK"; break; } time_t timestamp = time(NULL); tm* gmt = gmtime(&timestamp); char current_time[1024]; strftime(current_time, sizeof(current_time), "%a, %d %b %Y %H:%M:%S %Z", gmt); printf("Status: %s\r\n", status.toCharArray()); printf("Date: %s\r\n", current_time); printf("Server: %s\r\n", server_name.toCharArray()); printf("Content-Type: %s\r\n", mime_type.toCharArray()); printf("Content-Length: %d\r\n", content_length); printf("Connection: close\r\n"); printf("\r\n"); } void CgiHelper::OutputBodyText(const String& body) { printf("%s", body.toCharArray()); } void CgiHelper::OutputBodyFile(const String& file_name) { FILE* file = fopen(file_name.toCharArray(), "r"); if (file != NULL) { char buffer[kOutputFileBufferSize]; int bytes_read = 0; while (!feof(file)) { bytes_read = fread(buffer, 1, kOutputFileBufferSize, file); if (bytes_read > 0) { fwrite(buffer, 1, bytes_read, stdout); } } } } void CgiHelper::ParseEnvironmentVariables() { environment_variables_[kPathInfo] = new String(getenv(kPathInfo.toCharArray())); environment_variables_[kHttpHost] = new String(getenv(kHttpHost.toCharArray())); environment_variables_[kHttpUserAgent] = new String(getenv(kHttpUserAgent.toCharArray())); environment_variables_[kRemoteAddress] = new String(getenv(kRemoteAddress.toCharArray())); environment_variables_[kQueryString] = new String(getenv(kQueryString.toCharArray())); // first parse parameters passed through key-value pairs in the QUERY_STRING // these are typically passed in as key=value with an & separating them. vector<String> parameters; environment_variables_[kQueryString]->tokenize('&', parameters); for (int i = 0; i < (int)parameters.size(); i++) { vector<String> key_values; parameters[i].tokenize('=', key_values); if (key_values.size() == 2) { url_parameters_[key_values[0]] = new String(key_values[1]); } else { break; } } // next parse the path elements in the url. these are separated by a /. // PATH_INFO starts with a / as a separator, which will make the tokenizer add an empty // string as the first token (expected behavior). but CGI applications aren't necessarily // interested in the empty string. so the loop below starts from 1 instead of 0. parameters.clear(); environment_variables_[kPathInfo]->tokenize('/', parameters); for (int i = 1; i < parameters.size(); ++i) { path_elements_.push_back(new String(parameters[i])); } } } // namespace lep
32.345324
92
0.717749
[ "vector" ]
e6b1a64cfe77e575c8246085f4e3538c55b449a3
262
cpp
C++
cold/cold/render/impl/debug.cpp
bqqbarbhg/cold
23237e0112e1a904c2ae0c0e32420bd08ca5595c
[ "MIT" ]
null
null
null
cold/cold/render/impl/debug.cpp
bqqbarbhg/cold
23237e0112e1a904c2ae0c0e32420bd08ca5595c
[ "MIT" ]
null
null
null
cold/cold/render/impl/debug.cpp
bqqbarbhg/cold
23237e0112e1a904c2ae0c0e32420bd08ca5595c
[ "MIT" ]
null
null
null
#include "debug.h" #include <cold/render/render.h> namespace cold { namespace impl { void RenderDebugHandle::check_error() const { render::error_t err; if (render::get_error(err)) { std::string s = render::get_error_string(err); __debugbreak(); } } } }
18.714286
48
0.698473
[ "render" ]
e6b2ed11b389e54462238a915a150f3d3eb6ba8b
2,125
cc
C++
test/shuffle_unittest.cc
cgetzen/cpp-infima
a0fb32946181c6fe0c207e602f9849466d0031ea
[ "Apache-2.0" ]
null
null
null
test/shuffle_unittest.cc
cgetzen/cpp-infima
a0fb32946181c6fe0c207e602f9849466d0031ea
[ "Apache-2.0" ]
null
null
null
test/shuffle_unittest.cc
cgetzen/cpp-infima
a0fb32946181c6fe0c207e602f9849466d0031ea
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include "infima/infima.h" template <typename T> void equal_vector(std::vector<T> x, std::vector<T> y) { ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; for (long unsigned int i = 0; i < x.size(); ++i) { EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; } } TEST(Shuffle, SingleCell) { std::vector<std::string> dimensions {"AZ"}; Lattice<int> lattice = Lattice<int>(dimensions); lattice.add_endpoints_for_sector(Lattice<int>::Coordinate{"us-east-1a"}, std::vector<int>{1}); lattice.add_endpoints_for_sector(Lattice<int>::Coordinate{"us-east-1a"}, std::vector<int>{2,3,4,5}); ShuffleSharder<int> sharder = ShuffleSharder<int>(5353); for(int i=0; i<100; i++) { Lattice<int> * shard = sharder.shuffleShard(lattice, i, 2); EXPECT_EQ(shard->get_endpoints_for_sector(Lattice<int>::Coordinate{"us-east-1a"}).size(), 2); } } TEST(Shuffle, OneDimensionsWithLess) { // Shuffle shard when endpoints_per_cell > available_endpoints std::vector<std::string> dimensions {"Region"}; Lattice<int> lattice = Lattice<int>(dimensions); lattice.add_endpoints_for_sector(Lattice<int>::Coordinate{"a"}, std::vector<int>{1}); lattice.add_endpoints_for_sector(Lattice<int>::Coordinate{"b"}, std::vector<int>{2,3,4,5}); ShuffleSharder<int> sharder = ShuffleSharder<int>(5353); Lattice<int> * shard = sharder.shuffleShard(lattice, 1, 2); equal_vector(shard->get_endpoints_for_sector(Lattice<int>::Coordinate{"a"}), (std::vector<int>{1})); } TEST(Shuffle, Empty2DCell) { std::vector<std::string> dimensions {"Region", "AZ"}; Lattice<int> lattice = Lattice<int>(dimensions); lattice.add_endpoints_for_sector(Lattice<int>::Coordinate{"us-east-1", "a"}, std::vector<int>{1,2}); lattice.add_endpoints_for_sector(Lattice<int>::Coordinate{"us-east-2", "b"}, std::vector<int>{3,4,5}); ShuffleSharder<int> sharder = ShuffleSharder<int>(5353); Lattice<int> * shard = sharder.shuffleShard(lattice, 1, 3); equal_vector(shard->get_endpoints_for_sector(Lattice<int>::Coordinate{"us-east-1", "a"}), (std::vector<int>{1, 2})); }
42.5
118
0.696471
[ "vector" ]
e6b77b3cf54b5d2947b0fa84e476fc41a33f67c9
1,297
cpp
C++
src/systems/HealthBarRenderSystem.cpp
losinggeneration/starwarrior
31b6b531f67166467c424c710186c02701ac8ccc
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/systems/HealthBarRenderSystem.cpp
losinggeneration/starwarrior
31b6b531f67166467c424c710186c02701ac8ccc
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/systems/HealthBarRenderSystem.cpp
losinggeneration/starwarrior
31b6b531f67166467c424c710186c02701ac8ccc
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "systems/HealthBarRenderSystem.h" #include "components/Health.h" #include "components/Transform.h" #include <sstream> using namespace hecate; namespace StarWarrior { HealthBarRenderSystem::HealthBarRenderSystem(SDL_Surface *screen, TTF_Font *font) { Health h; Transform t; componentList_t l; l.push_back(&h); l.push_back(&t); setupTypes(l); this->screen = screen; this->font = font; } HealthBarRenderSystem::~HealthBarRenderSystem() { delete healthMapper; delete transformMapper; } void HealthBarRenderSystem::initialize() { healthMapper = new ComponentMapper<Health>(Health(), world); transformMapper = new ComponentMapper<Transform>(Transform(), world); } void HealthBarRenderSystem::process(Entity *e) { Health *health = healthMapper->get(*e); Transform *transform = transformMapper->get(*e); std::string text; SDL_Color white = {255, 255, 255}; SDL_Rect r; if(health) { std::stringstream ss; ss << health->getHealthPercentage() << "%"; ss >> text; SDL_Surface *rendered = TTF_RenderText_Solid(font, text.c_str(), white); if(rendered != NULL) { r.w = rendered->w; r.h = rendered->h; r.x = transform->getX() - 10; r.y = transform->getY() - 30; SDL_BlitSurface(rendered, NULL, screen, &r); SDL_FreeSurface(rendered); } } } }
21.616667
83
0.706245
[ "transform" ]
e6bdbbe9101840857cfe52970937735dca81356c
5,790
cpp
C++
game.cpp
blatchley/AUHACK19
e2c2c07a4f318bde2c888c64da72bb2b12dfc0a6
[ "BSL-1.0" ]
1
2020-12-29T04:43:11.000Z
2020-12-29T04:43:11.000Z
game.cpp
killerdogice/AUHACK19
e2c2c07a4f318bde2c888c64da72bb2b12dfc0a6
[ "BSL-1.0" ]
null
null
null
game.cpp
killerdogice/AUHACK19
e2c2c07a4f318bde2c888c64da72bb2b12dfc0a6
[ "BSL-1.0" ]
null
null
null
#include <ctime> #include "time.h" #include "shared_state.hpp" #include <chrono> #include <thread> #include <sstream> #include <iostream> // private: // int height, width; // int headx, heady; // enum eDirection {STOP, LEFT, RIGHT, UP, DOWN}; // eDirection dir; // bool gameRunning; // public: game:: game() { foodx = 12; foody = 12; height = 24; width = 24; headx = 10; heady = 10; prevdir = RIGHT; dir = RIGHT; gameRunning = true; snakelength = 4; std::vector<snakebody> snakeparts = {snakebody(10, 10)}; headx2 = 14; heady2 = 14; dir2 = LEFT; prevdir2 = LEFT; snakelength2 = 4; std::vector<snakebody> snakeparts2 = {snakebody(14, 14)}; // gameloop(); } void game:: moveall() { move(); move2(); } void game:: move() { if (dir == LEFT) { if (headx > 1) { headx--; } else { headx = 24; } } if (dir == UP) { if (heady > 0) { heady--; } else { heady = 24; } } if (dir == RIGHT) { if (headx < 24) { headx++; } else { headx = 0; } } if (dir == DOWN) { if (heady < 24) { heady++; } else { heady = 0; } } if (headx == foodx && heady == foody) { snakelength++; updatefood(); } if (snakeparts.size() < static_cast<unsigned int>(snakelength)) { snakeparts.insert(snakeparts.begin(), snakebody(headx,heady)); } else { snakeparts.insert(snakeparts.begin(), snakebody(headx,heady)); snakeparts.pop_back(); } prevdir = dir; } void game:: move2() { if (dir2 == LEFT) { if (headx2 > 1) { headx2--; } else { headx2 = 24; } } if (dir2 == UP) { if (heady2 > 0) { heady2--; } else { heady2 = 24; } } if (dir2 == RIGHT) { if (headx2 < 24) { headx2++; } else { headx2 = 0; } } if (dir2 == DOWN) { if (heady2 < 24) { heady2++; } else { heady2 = 0; } } if (headx2 == foodx && heady2 == foody) { snakelength2++; updatefood(); } if (snakeparts2.size() < static_cast<unsigned int>(snakelength2)) { snakeparts2.insert(snakeparts2.begin(), snakebody(headx2,heady2)); } else { snakeparts2.insert(snakeparts2.begin(), snakebody(headx2,heady2)); snakeparts2.pop_back(); } prevdir2 = dir2; } void game:: updatefood() { std::srand(std::time(nullptr)); // use current time as seed for random generator foodx = std::rand() % 22 + 1; foody = std::rand() % 22 + 1; } void game:: setDirection(std::string directionfull) { std::string direction2 = directionfull.substr(1); std::string prefix = directionfull.substr(0,1); std::string comparator = "1"; if (prefix == comparator) { if (direction2 == "left" && prevdir != RIGHT) { dir = LEFT; } if (direction2 == "up" && prevdir != DOWN) { dir = UP; } if (direction2 == "right" && prevdir != LEFT) { dir = RIGHT; } if (direction2 == "down" && prevdir != UP) { dir = DOWN; } } else { setDirection2(direction2); } } void game:: setDirection2(std::string direction) { if (direction == "left" && prevdir2 != RIGHT) { dir2 = LEFT; } if (direction == "up" && prevdir2 != DOWN) { dir2 = UP; } if (direction == "right" && prevdir2 != LEFT) { dir2 = RIGHT; } if (direction == "down" && prevdir2 != UP) { dir2 = DOWN; } } void game:: render(std::shared_ptr<shared_state> const& state){ int death = 0; int death2 = 0; std::ostringstream ss; ss << std::to_string(foodx)+","+std::to_string(foody); // for (auto it = snakeparts.cbegin(); it != snakeparts.cend(); it++) { for ( const auto part: snakeparts ) { ss << "." << part.strrep(); if (part.x == headx && part.y == heady) { death += 1; } if (part.x == headx2 && part.y == heady2) { death += 1; } } ss << "@"; for ( const auto part: snakeparts2 ) { ss << "." << part.strrep(); if (part.x == headx2 && part.y == heady2) { death2 += 1; } if (part.x == headx && part.y == heady) { death2 += 1; } } //detects overlap and kills state->send(ss.str()); if (death > 1) { reset(); } if (death2 > 1) { reset(); } } void game:: reset() { foodx = 12; foody = 12; height = 24; width = 24; headx = 10; heady = 10; dir = RIGHT; gameRunning = true; snakelength = 4; snakeparts = {snakebody(10, 10)}; headx2 = 14; heady2 = 14; dir2 = LEFT; snakelength2 = 4; snakeparts2 = {snakebody(14, 14)}; } void game:: gameloop(std::shared_ptr<shared_state> const& state) { auto start = std::chrono::high_resolution_clock::now(); double ticktime = 134; while (gameRunning) { auto now = std::chrono::high_resolution_clock::now(); auto seconds_since_start = std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count(); if (seconds_since_start < ticktime) { if ((ticktime - seconds_since_start) > 40) { std::this_thread::sleep_for(std::chrono::milliseconds(30)); } } else { start = std::chrono::high_resolution_clock::now(); moveall(); render(state); } } }
22.183908
110
0.490674
[ "render", "vector" ]
e6be0ad82c4a2f06f70cf7aa6836b896b509509e
33,708
cpp
C++
src/common/Honey/Math/Alge/Matrix/Matrix4.cpp
Qarterd/Honeycomb
9b7066529444cdd85d3e3467b02b72eea651853d
[ "CC0-1.0" ]
33
2015-05-08T00:11:01.000Z
2022-03-04T08:25:06.000Z
src/common/Honey/Math/Alge/Matrix/Matrix4.cpp
Qarterd/Honeycomb
9b7066529444cdd85d3e3467b02b72eea651853d
[ "CC0-1.0" ]
null
null
null
src/common/Honey/Math/Alge/Matrix/Matrix4.cpp
Qarterd/Honeycomb
9b7066529444cdd85d3e3467b02b72eea651853d
[ "CC0-1.0" ]
6
2015-08-08T13:47:14.000Z
2021-04-06T02:29:41.000Z
// Honeycomb, Copyright (C) 2015 NewGamePlus Inc. Distributed under the Boost Software License v1.0. #pragma hdrstop #include "Honey/Math/Alge/Matrix/Matrix4.h" #include "Honey/Math/Alge/Transform.h" #define Section_Source #include "Honey/Math/Alge/Matrix/platform/Matrix4.h" #undef Section_Source namespace honey { template<class Real, int O> const Matrix<4,4,Real,O> Matrix<4,4,Real,O>::zero ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); template<class Real, int O> const Matrix<4,4,Real,O> Matrix<4,4,Real,O>::identity ( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); template<class Real, int O> Matrix<4,4,Real,O>& Matrix<4,4,Real,O>::fromTm(const Transform& tm) { return fromTrs(tm.getTrans(), tm.getRot(), tm.getScale(), tm.getSkew()); } template<class Real, int O> Matrix<4,4,Real,O>& Matrix<4,4,Real,O>::fromObliqueProjection(const Vec3& normal, const Vec3& point, const Vec3& dir) { // The projection plane is dot(N,X-P) = 0 where N is a 3-by-1 unit-length // normal vector and P is a 3-by-1 poInt on the plane. The projection // is oblique to the plane, in the direction of the 3-by-1 vector D. // Necessarily dot(N,D) is not zero for this projection to make sense. // Given a 3-by-1 poInt U, compute the intersection of the line U+t*D // with the plane to obtain t = -dot(N,U-P)/dot(N,D). Then // // projection(U) = P + [I - D*N^T/dot(N,D)]*(U-P) // // A 4-by-4 homogeneous transformation representing the projection is // // +- -+ // M = | D*N^T - dot(N,D)*I -dot(N,P)D | // | 0^T -dot(N,D) | // +- -+ // // where M applies to [U^T 1]^T by M*[U^T 1]^T. The matrix is chosen so // that M[3][3] > 0 whenever dot(N,D) < 0 (projection is onto the // "positive side" of the plane). Real ndD = normal.dot(dir); Real ndP = normal.dot(point); m( 0) = dir[0]*normal[0] - ndD; m( 1) = dir[0]*normal[1]; m( 2) = dir[0]*normal[2]; m( 3) = -ndP*dir[0]; m( 4) = dir[1]*normal[0]; m( 5) = dir[1]*normal[1] - ndD; m( 6) = dir[1]*normal[2]; m( 7) = -ndP*dir[1]; m( 8) = dir[2]*normal[0]; m( 9) = dir[2]*normal[1]; m(10) = dir[2]*normal[2] - ndD; m(11) = -ndP*dir[2]; m(12) = 0; m(13) = 0; m(14) = 0; m(15) = -ndD; return *this; } template<class Real, int O> Matrix<4,4,Real,O>& Matrix<4,4,Real,O>::fromPerspectiveProjection(const Vec3& normal, const Vec3& point, const Vec3& eye) { // +- -+ // M = | dot(N,E-P)*I - E*N^T -(dot(N,E-P)*I - E*N^T)*E | // | -N^t dot(N,E) | // +- -+ // // where E is the eye point, P is a poInt on the plane, and N is a // unit-length plane normal. Real ndEmP = normal.dot(eye-point); m( 0) = ndEmP - eye[0]*normal[0]; m( 1) = -eye[0]*normal[1]; m( 2) = -eye[0]*normal[2]; m( 3) = -(m(0)*eye[0] + m(1)*eye[1] + m(2)*eye[2]); m( 4) = -eye[1]*normal[0]; m( 5) = ndEmP - eye[1]*normal[1]; m( 6) = -eye[1]*normal[2]; m( 7) = -(m(4)*eye[0] + m(5)*eye[1] + m(6)*eye[2]); m( 8) = -eye[2]*normal[0]; m( 9) = -eye[2]*normal[1]; m(10) = ndEmP- eye[2]*normal[2]; m(11) = -(m(8)*eye[0] + m(9)*eye[1] + m(10)*eye[2]); m(12) = -normal[0]; m(13) = -normal[1]; m(14) = -normal[2]; m(15) = normal.dot(eye); return *this; } template<class Real, int O> Matrix<4,4,Real,O>& Matrix<4,4,Real,O>::fromReflection(const Vec3& normal, const Vec3& point) { // +- -+ // M = | I-2*N*N^T 2*dot(N,P)*N | // | 0^T 1 | // +- -+ // // where P is a poInt on the plane and N is a unit-length plane normal. Real twoNdP = 2*(normal.dot(point)); m( 0) = 1 - 2*normal[0]*normal[0]; m( 1) = -2*normal[0]*normal[1]; m( 2) = -2*normal[0]*normal[2]; m( 3) = twoNdP*normal[0]; m( 4) = -2*normal[1]*normal[0]; m( 5) = 1 - 2*normal[1]*normal[1]; m( 6) = -2*normal[1]*normal[2]; m( 7) = twoNdP*normal[1]; m( 8) = -2*normal[2]*normal[0]; m( 9) = -2*normal[2]*normal[1]; m(10) = 1 - 2*normal[2]*normal[2]; m(11) = twoNdP*normal[2]; m(12) = 0; m(13) = 0; m(14) = 0; m(15) = 1; return *this; } template<class Real, int O> Matrix<4,4,Real,O>& Matrix<4,4,Real,O>::fromLookAt(const Vec3& eye, const Vec3& at, const Vec3& up) { Vec3 z = (eye - at).normalize(); Vec3 x = up.crossUnit(z); Vec3 y = z.cross(x); this->row(0) = Vec4(x, -x.dot(eye)); this->row(1) = Vec4(y, -y.dot(eye)); this->row(2) = Vec4(z, -z.dot(eye)); this->row(3) = Vec4::axisW; return *this; } template<class Real, int O> void Matrix<4,4,Real,O>::orthonormalize() { // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix has // upper-left 3x3 block M = [m0|m1|m2], then the orthonormal output matrix // is Q = [q0|q1|q2], // // q0 = m0/|m0| // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| // // where |V| indicates length of vector V and A*B indicates dot // product of vectors A and B. // Compute q0. Real invLength = 1 / Alge::sqrt(m(0)*m(0) + m(4)*m(4) + m(8)*m(8)); m(0) *= invLength; m(4) *= invLength; m(8) *= invLength; // Compute q1. Real dot0 = m(0)*m(1) + m(4)*m(5) + m(8)*m(9); m(1) -= dot0*m(0); m(5) -= dot0*m(4); m(9) -= dot0*m(8); invLength = 1 / Alge::sqrt(m(1)*m(1) + m(5)*m(5) + m(9)*m(9)); m(1) *= invLength; m(5) *= invLength; m(9) *= invLength; // Compute q2. Real dot1 = m(1)*m(2) + m(5)*m(6) + m(9)*m(10); dot0 = m(0)*m(2) + m(4)*m(6) + m(8)*m(10); m( 2) -= dot0*m(0) + dot1*m(1); m( 6) -= dot0*m(4) + dot1*m(5); m(10) -= dot0*m(8) + dot1*m(9); invLength = 1 / Alge::sqrt(m(2)*m(2) + m(6)*m(6) + m(10)*m(10)); m( 2) *= invLength; m( 6) *= invLength; m(10) *= invLength; } template<class Real, int O> Matrix<4,4,Real,O> Matrix<4,4,Real,O>::inverse(optional<Real&> det) const { Real a0 = m( 0)*m( 5) - m( 1)*m( 4); Real a1 = m( 0)*m( 6) - m( 2)*m( 4); Real a2 = m( 0)*m( 7) - m( 3)*m( 4); Real a3 = m( 1)*m( 6) - m( 2)*m( 5); Real a4 = m( 1)*m( 7) - m( 3)*m( 5); Real a5 = m( 2)*m( 7) - m( 3)*m( 6); Real b0 = m( 8)*m(13) - m( 9)*m(12); Real b1 = m( 8)*m(14) - m(10)*m(12); Real b2 = m( 8)*m(15) - m(11)*m(12); Real b3 = m( 9)*m(14) - m(10)*m(13); Real b4 = m( 9)*m(15) - m(11)*m(13); Real b5 = m(10)*m(15) - m(11)*m(14); Real d = a0*b5-a1*b4+a2*b3+a3*b2-a4*b1+a5*b0; if (det) det = d; if (Alge::isNearZero(d)) { if (det) det = 0; return zero; } Matrix inv; inv( 0) = + m( 5)*b5 - m( 6)*b4 + m( 7)*b3; inv( 4) = - m( 4)*b5 + m( 6)*b2 - m( 7)*b1; inv( 8) = + m( 4)*b4 - m( 5)*b2 + m( 7)*b0; inv(12) = - m( 4)*b3 + m( 5)*b1 - m( 6)*b0; inv( 1) = - m( 1)*b5 + m( 2)*b4 - m( 3)*b3; inv( 5) = + m( 0)*b5 - m( 2)*b2 + m( 3)*b1; inv( 9) = - m( 0)*b4 + m( 1)*b2 - m( 3)*b0; inv(13) = + m( 0)*b3 - m( 1)*b1 + m( 2)*b0; inv( 2) = + m(13)*a5 - m(14)*a4 + m(15)*a3; inv( 6) = - m(12)*a5 + m(14)*a2 - m(15)*a1; inv(10) = + m(12)*a4 - m(13)*a2 + m(15)*a0; inv(14) = - m(12)*a3 + m(13)*a1 - m(14)*a0; inv( 3) = - m( 9)*a5 + m(10)*a4 - m(11)*a3; inv( 7) = + m( 8)*a5 - m(10)*a2 + m(11)*a1; inv(11) = - m( 8)*a4 + m( 9)*a2 - m(11)*a0; inv(15) = + m( 8)*a3 - m( 9)*a1 + m(10)*a0; inv /= d; return inv; } template<class Real, int O> Matrix<4,4,Real,O> Matrix<4,4,Real,O>::adjugate() const { Real a0 = m( 0)*m( 5) - m( 1)*m( 4); Real a1 = m( 0)*m( 6) - m( 2)*m( 4); Real a2 = m( 0)*m( 7) - m( 3)*m( 4); Real a3 = m( 1)*m( 6) - m( 2)*m( 5); Real a4 = m( 1)*m( 7) - m( 3)*m( 5); Real a5 = m( 2)*m( 7) - m( 3)*m( 6); Real b0 = m( 8)*m(13) - m( 9)*m(12); Real b1 = m( 8)*m(14) - m(10)*m(12); Real b2 = m( 8)*m(15) - m(11)*m(12); Real b3 = m( 9)*m(14) - m(10)*m(13); Real b4 = m( 9)*m(15) - m(11)*m(13); Real b5 = m(10)*m(15) - m(11)*m(14); Matrix adj; adj( 0) = + m( 5)*b5 - m( 6)*b4 + m( 7)*b3; adj( 4) = - m( 4)*b5 + m( 6)*b2 - m( 7)*b1; adj( 8) = + m( 4)*b4 - m( 5)*b2 + m( 7)*b0; adj(12) = - m( 4)*b3 + m( 5)*b1 - m( 6)*b0; adj( 1) = - m( 1)*b5 + m( 2)*b4 - m( 3)*b3; adj( 5) = + m( 0)*b5 - m( 2)*b2 + m( 3)*b1; adj( 9) = - m( 0)*b4 + m( 1)*b2 - m( 3)*b0; adj(13) = + m( 0)*b3 - m( 1)*b1 + m( 2)*b0; adj( 2) = + m(13)*a5 - m(14)*a4 + m(15)*a3; adj( 6) = - m(12)*a5 + m(14)*a2 - m(15)*a1; adj(10) = + m(12)*a4 - m(13)*a2 + m(15)*a0; adj(14) = - m(12)*a3 + m(13)*a1 - m(14)*a0; adj( 3) = - m( 9)*a5 + m(10)*a4 - m(11)*a3; adj( 7) = + m( 8)*a5 - m(10)*a2 + m(11)*a1; adj(11) = - m( 8)*a4 + m( 9)*a2 - m(11)*a0; adj(15) = + m( 8)*a3 - m( 9)*a1 + m(10)*a0; return adj; } template<class Real, int O> auto Matrix<4,4,Real,O>::determinant() const -> Real { Real a0 = m( 0)*m( 5) - m( 1)*m( 4); Real a1 = m( 0)*m( 6) - m( 2)*m( 4); Real a2 = m( 0)*m( 7) - m( 3)*m( 4); Real a3 = m( 1)*m( 6) - m( 2)*m( 5); Real a4 = m( 1)*m( 7) - m( 3)*m( 5); Real a5 = m( 2)*m( 7) - m( 3)*m( 6); Real b0 = m( 8)*m(13) - m( 9)*m(12); Real b1 = m( 8)*m(14) - m(10)*m(12); Real b2 = m( 8)*m(15) - m(11)*m(12); Real b3 = m( 9)*m(14) - m(10)*m(13); Real b4 = m( 9)*m(15) - m(11)*m(13); Real b5 = m(10)*m(15) - m(11)*m(14); Real det = a0*b5-a1*b4+a2*b3+a3*b2-a4*b1+a5*b0; return det; } template<class Real, int O> void Matrix<4,4,Real,O>::decompose( optional<Vec3&> trans, optional<Quat&> rot, optional<Vec3&> scale, optional<Quat&> skew) const { //Get scale and shear. Vec3 row[3], scl; row[0] = Vec3(this->col(0).eval()); row[1] = Vec3(this->col(1).eval()); row[2] = Vec3(this->col(2).eval()); // Compute X scale factor and normalize first row. row[0] = row[0].normalize(scl.x); // Compute XY shear factor and make 2nd row orthogonal to 1st. row[1] = row[1] - row[0] * row[0].dot(row[1]); // Compute Y scale and normalize 2nd row. row[1] = row[1].normalize(scl.y); // Compute XZ and YZ shears, orthogonalize 3rd row. row[2] = row[2] - row[0] * row[0].dot(row[2]); row[2] = row[2] - row[1] * row[1].dot(row[2]); // Get Z scale and normalize 3rd row. row[2] = row[2].normalize(scl.z); if (skew) { //Skew algorithm is expensive, only do it if scale is non-uniform. Real tol = scl.x * 1.0e-4; if (!Alge::isNear(scl.x, scl.y, tol) || !Alge::isNear(scl.x, scl.z, tol)) { decomposeSkew(trans, rot, scale, skew); return; } skew = Quat::identity; } // At this point, the matrix (in rows[]) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. if (row[0].dot(row[1].cross(row[2])) < 0) { row[0] = -row[0]; row[1] = -row[1]; row[2] = -row[2]; scl.x = -scl.x; scl.y = -scl.y; scl.z = -scl.z; } if (trans) trans = getTrans(); if (scale) scale = scl; // Get the rotations out if (rot) { Vec3 vrot; vrot.y = Trig::asin(-row[0].z); if (Trig::cos(vrot.y) != 0) { vrot.x = Trig::atan2(row[1].z, row[2].z); vrot.z = Trig::atan2(row[0].y, row[0].x); } else { vrot.x = Trig::atan2(row[1].x, row[1].y); vrot.z = 0; } rot->fromEulerAngles(vrot); } } //============================================================================================================== // Algorithm to handle special case where skew is required in decomposition //============================================================================================================== /**** Decompose.h ****/ /* Ken Shoemake, 1993 */ template<class Real> class DecompAffine { typedef Alge_<Real> Alge; public: typedef struct {Real x, y, z, w;} Quat; /* Quat */ enum QuatPart {X, Y, Z, W}; typedef Quat HVect; /* Homogeneous 3D vector */ typedef Real HMatrix[4][4]; /* Right-handed, for column vectors */ typedef struct { HVect t; /* Translation components */ Quat q; /* Essential rotation */ Quat u; /* Stretch rotation */ HVect k; /* Stretch factors */ Real f; /* Sign of determinant */ } AffineParts; static Real polar_decomp(HMatrix M, HMatrix Q, HMatrix S); static HVect spect_decomp(HMatrix S, HMatrix U); static Quat snuggle(Quat q, HVect *k); static void decomp_affine(HMatrix A, AffineParts *parts); static void invert_affine(AffineParts *parts, AffineParts *inverse); private: static void mat_mult(HMatrix A, HMatrix B, HMatrix AB); static Real vdot(Real *va, Real *vb); static void vcross(Real *va, Real *vb, Real *v); static void adjoint_transpose(HMatrix M, HMatrix MadjT); static Quat Qt_(Real x, Real y, Real z, Real w); static Quat Qt_Conj(Quat q); static Quat Qt_Mul(Quat l, Quat r); static Quat Qt_Scale(Quat q, Real w); static Quat Qt_FromMatrix(HMatrix mat); static HMatrix mat_id; static Real mat_norm(HMatrix M, int tpose); static Real norm_inf(HMatrix M); static Real norm_one(HMatrix M); static int find_max_col(HMatrix M); static void make_reflector(Real *v, Real *u); static void reflect_cols(HMatrix M, Real *u); static void reflect_rows(HMatrix M, Real *u); static void do_rank1(HMatrix M, HMatrix Q); static void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q); }; /**** Decompose.c ****/ /* Ken Shoemake, 1993 */ /******* Matrix Preliminaries *******/ /** Fill out 3x3 matrix to 4x4 **/ #define mat_pad(A) (A[W][X]=A[X][W]=A[W][Y]=A[Y][W]=A[W][Z]=A[Z][W]=0,A[W][W]=1) /** Copy nxn matrix A to C using "gets" for assignment **/ #define mat_copy(C,gets,A,n) {int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++)\ C[i][j] gets (A[i][j]);} /** Copy transpose of nxn matrix A to C using "gets" for assignment **/ #define mat_tpose(AT,gets,A,n) {int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++)\ AT[i][j] gets (A[j][i]);} /** Assign nxn matrix C the element-wise combination of A and B using "op" **/ #define mat_binop(C,gets,A,op,B,n) {int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++)\ C[i][j] gets (A[i][j]) op (B[i][j]);} /** Multiply the upper left 3x3 parts of A and B to get AB **/ template<class Real> void DecompAffine<Real>::mat_mult(HMatrix A, HMatrix B, HMatrix AB) { int i, j; for (i=0; i<3; i++) for (j=0; j<3; j++) AB[i][j] = A[i][0]*B[0][j] + A[i][1]*B[1][j] + A[i][2]*B[2][j]; } /** Return dot product of length 3 vectors va and vb **/ template<class Real> Real DecompAffine<Real>::vdot(Real *va, Real *vb) { return (va[0]*vb[0] + va[1]*vb[1] + va[2]*vb[2]); } /** Set v to cross product of length 3 vectors va and vb **/ template<class Real> void DecompAffine<Real>::vcross(Real *va, Real *vb, Real *v) { v[0] = va[1]*vb[2] - va[2]*vb[1]; v[1] = va[2]*vb[0] - va[0]*vb[2]; v[2] = va[0]*vb[1] - va[1]*vb[0]; } /** Set MadjT to transpose of inverse of M times determinant of M **/ template<class Real> void DecompAffine<Real>::adjoint_transpose(HMatrix M, HMatrix MadjT) { vcross(M[1], M[2], MadjT[0]); vcross(M[2], M[0], MadjT[1]); vcross(M[0], M[1], MadjT[2]); } /******* Quat Preliminaries *******/ /* Construct a (possibly non-unit) quaternion from real components. */ template<class Real> typename DecompAffine<Real>::Quat DecompAffine<Real>::Qt_(Real x, Real y, Real z, Real w) { Quat qq; qq.x = x; qq.y = y; qq.z = z; qq.w = w; return (qq); } /* Return conjugate of quaternion. */ template<class Real> typename DecompAffine<Real>::Quat DecompAffine<Real>::Qt_Conj(Quat q) { Quat qq; qq.x = -q.x; qq.y = -q.y; qq.z = -q.z; qq.w = q.w; return (qq); } /** Return quaternion product l * r. Note: order is important! * To combine rotations, use the product mul(second, first), * which gives the effect of rotating by first then second. */ template<class Real> typename DecompAffine<Real>::Quat DecompAffine<Real>::Qt_Mul(Quat l, Quat r) { Quat qq; qq.w = l.w*r.w - l.x*r.x - l.y*r.y - l.z*r.z; qq.x = l.w*r.x + l.x*r.w + l.y*r.z - l.z*r.y; qq.y = l.w*r.y + l.y*r.w + l.z*r.x - l.x*r.z; qq.z = l.w*r.z + l.z*r.w + l.x*r.y - l.y*r.x; return (qq); } /* Return product of quaternion q by scalar w. */ template<class Real> typename DecompAffine<Real>::Quat DecompAffine<Real>::Qt_Scale(Quat q, Real w) { Quat qq; qq.w = q.w*w; qq.x = q.x*w; qq.y = q.y*w; qq.z = q.z*w; return (qq); } /* Construct a unit quaternion from rotation matrix. Assumes matrix is * used to multiply column vector on the left: vnew = mat vold. Works * correctly for right-handed coordinate system and right-handed rotations. * Translation and perspective components ignored. */ template<class Real> typename DecompAffine<Real>::Quat DecompAffine<Real>::Qt_FromMatrix(HMatrix mat) { /* This algorithm avoids near-zero divides by looking for a large component * - first w, then x, y, or z. When the trace is greater than zero, *|w| is greater than 1/2, which is as small as a largest component can be. * Otherwise, the largest diagonal entry corresponds to the largest of |x|, *|y|, or |z|, one of which must be larger than |w|, and at least 1/2. */ Quat qu; qu.x = 0; Real tr, s; tr = mat[X][X] + mat[Y][Y]+ mat[Z][Z]; if (tr >= 0.0) { s = Alge::sqrt(tr + mat[W][W]); qu.w = s*0.5; s = 0.5 / s; qu.x = (mat[Z][Y] - mat[Y][Z]) * s; qu.y = (mat[X][Z] - mat[Z][X]) * s; qu.z = (mat[Y][X] - mat[X][Y]) * s; } else { int h = X; if (mat[Y][Y] > mat[X][X]) h = Y; if (mat[Z][Z] > mat[h][h]) h = Z; switch (h) { #define caseMacro(i,j,k,I,J,K) \ case I:\ s = Alge::sqrt( (mat[I][I] - (mat[J][J]+mat[K][K])) + mat[W][W] );\ qu.i = s*0.5;\ s = 0.5 / s;\ qu.j = (mat[I][J] + mat[J][I]) * s;\ qu.k = (mat[K][I] + mat[I][K]) * s;\ qu.w = (mat[K][J] - mat[J][K]) * s;\ break caseMacro(x,y,z,X,Y,Z); caseMacro(y,z,x,Y,Z,X); caseMacro(z,x,y,Z,X,Y); } } if (mat[W][W] != 1.0) qu = Qt_Scale(qu, 1/Alge::sqrt(mat[W][W])); return (qu); } /******* Decomp Auxiliaries *******/ template<class Real> typename DecompAffine<Real>::HMatrix DecompAffine<Real>::mat_id = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; /** Compute either the 1 or infinity norm of M, depending on tpose **/ template<class Real> Real DecompAffine<Real>::mat_norm(HMatrix M, int tpose) { int i; Real sum, max; max = 0.0; for (i=0; i<3; i++) { if (tpose) sum = Alge::abs(M[0][i])+Alge::abs(M[1][i])+Alge::abs(M[2][i]); else sum = Alge::abs(M[i][0])+Alge::abs(M[i][1])+Alge::abs(M[i][2]); if (max<sum) max = sum; } return max; } template<class Real> Real DecompAffine<Real>::norm_inf(HMatrix M) {return mat_norm(M, 0);} template<class Real> Real DecompAffine<Real>::norm_one(HMatrix M) {return mat_norm(M, 1);} /** Return index of column of M containing maximum abs entry, or -1 if M=0 **/ template<class Real> int DecompAffine<Real>::find_max_col(HMatrix M) { Real abs, max; int i, j, col; max = 0.0; col = -1; for (i=0; i<3; i++) for (j=0; j<3; j++) { abs = M[i][j]; if (abs<0.0) abs = -abs; if (abs>max) {max = abs; col = j;} } return col; } /** Set up u for Household reflection to zero all v components but first **/ template<class Real> void DecompAffine<Real>::make_reflector(Real *v, Real *u) { Real s = Alge::sqrt(vdot(v, v)); u[0] = v[0]; u[1] = v[1]; u[2] = v[2] + ((v[2]<0.0) ? -s : s); s = Alge::sqrt(2.0/vdot(u, u)); u[0] = u[0]*s; u[1] = u[1]*s; u[2] = u[2]*s; } /** Apply Householder reflection represented by u to column vectors of M **/ template<class Real> void DecompAffine<Real>::reflect_cols(HMatrix M, Real *u) { int i, j; for (i=0; i<3; i++) { Real s = u[0]*M[0][i] + u[1]*M[1][i] + u[2]*M[2][i]; for (j=0; j<3; j++) M[j][i] -= u[j]*s; } } /** Apply Householder reflection represented by u to row vectors of M **/ template<class Real> void DecompAffine<Real>::reflect_rows(HMatrix M, Real *u) { int i, j; for (i=0; i<3; i++) { Real s = vdot(u, M[i]); for (j=0; j<3; j++) M[i][j] -= u[j]*s; } } /** Find orthogonal factor Q of rank 1 (or less) M **/ template<class Real> void DecompAffine<Real>::do_rank1(HMatrix M, HMatrix Q) { Real v1[3], v2[3], s; int col; mat_copy(Q,=,mat_id,4); /* If rank(M) is 1, we should find a non-zero column in M */ col = find_max_col(M); if (col<0) return; /* Rank is 0 */ v1[0] = M[0][col]; v1[1] = M[1][col]; v1[2] = M[2][col]; make_reflector(v1, v1); reflect_cols(M, v1); v2[0] = M[2][0]; v2[1] = M[2][1]; v2[2] = M[2][2]; make_reflector(v2, v2); reflect_rows(M, v2); s = M[2][2]; if (s<0.0) Q[2][2] = -1.0; reflect_cols(Q, v1); reflect_rows(Q, v2); } /** Find orthogonal factor Q of rank 2 (or less) M using adjoInt transpose **/ template<class Real> void DecompAffine<Real>::do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q) { Real v1[3], v2[3]; Real w, x, y, z, c, s, d; int col; /* If rank(M) is 2, we should find a non-zero column in MadjT */ col = find_max_col(MadjT); if (col<0) {do_rank1(M, Q); return;} /* Rank<2 */ v1[0] = MadjT[0][col]; v1[1] = MadjT[1][col]; v1[2] = MadjT[2][col]; make_reflector(v1, v1); reflect_cols(M, v1); vcross(M[0], M[1], v2); make_reflector(v2, v2); reflect_rows(M, v2); w = M[0][0]; x = M[0][1]; y = M[1][0]; z = M[1][1]; if (w*z>x*y) { c = z+w; s = y-x; d = Alge::sqrt(c*c+s*s); c = c/d; s = s/d; Q[0][0] = Q[1][1] = c; Q[0][1] = -(Q[1][0] = s); } else { c = z-w; s = y+x; d = Alge::sqrt(c*c+s*s); c = c/d; s = s/d; Q[0][0] = -(Q[1][1] = c); Q[0][1] = Q[1][0] = s; } Q[0][2] = Q[2][0] = Q[1][2] = Q[2][1] = 0.0; Q[2][2] = 1.0; reflect_cols(Q, v1); reflect_rows(Q, v2); } /******* Polar Decomposition *******/ /** Polar Decomposition of 3x3 matrix in 4x4, * M = QS. See Nicholas Higham and Robert S. Schreiber, * Fast Polar Decomposition of An Arbitrary Matrix, * Technical Report 88-942, October 1988, * Department of Computer Science, Cornell University. */ template<class Real> Real DecompAffine<Real>::polar_decomp(HMatrix M, HMatrix Q, HMatrix S) { #define TOL 1.0e-6 HMatrix Mk, MadjTk, Ek; Real det, M_one, M_inf, MadjT_one, MadjT_inf, E_one, gamma, g1, g2; int i, j; mat_tpose(Mk,=,M,3); M_one = norm_one(Mk); M_inf = norm_inf(Mk); do { adjoint_transpose(Mk, MadjTk); det = vdot(Mk[0], MadjTk[0]); if (det==0.0) {do_rank2(Mk, MadjTk, Mk); break;} MadjT_one = norm_one(MadjTk); MadjT_inf = norm_inf(MadjTk); gamma = Alge::sqrt(Alge::sqrt((MadjT_one*MadjT_inf)/(M_one*M_inf))/Alge::abs(det)); g1 = gamma*0.5; g2 = 0.5/(gamma*det); mat_copy(Ek,=,Mk,3); mat_binop(Mk,=,g1*Mk,+,g2*MadjTk,3); mat_copy(Ek,-=,Mk,3); E_one = norm_one(Ek); M_one = norm_one(Mk); M_inf = norm_inf(Mk); } while (E_one>(M_one*TOL)); mat_tpose(Q,=,Mk,3); mat_pad(Q); mat_mult(Mk, M, S); mat_pad(S); for (i=0; i<3; i++) for (j=i; j<3; j++) S[i][j] = S[j][i] = 0.5*(S[i][j]+S[j][i]); return (det); } /******* Spectral Decomposition *******/ /** Compute the spectral decomposition of symmetric positive semi-definite S. * Returns rotation in U and scale factors in result, so that if K is a diagonal * matrix of the scale factors, then S = U K (U transpose). Uses Jacobi method. * See Gene H. Golub and Charles F. Van Loan. Matrix Computations. Hopkins 1983. */ template<class Real> typename DecompAffine<Real>::HVect DecompAffine<Real>::spect_decomp(HMatrix S, HMatrix U) { HVect kv; Real Diag[3],OffD[3]; /* OffD is off-diag (by omitted index) */ Real g,h,fabsh,fabsOffDi,t,theta,c,s,tau,ta,OffDq,a,b; static char nxt[] = {Y,Z,X}; int sweep, i, j; mat_copy(U,=,mat_id,4); Diag[X] = S[X][X]; Diag[Y] = S[Y][Y]; Diag[Z] = S[Z][Z]; OffD[X] = S[Y][Z]; OffD[Y] = S[Z][X]; OffD[Z] = S[X][Y]; for (sweep=20; sweep>0; sweep--) { Real sm = Alge::abs(OffD[X])+Alge::abs(OffD[Y])+Alge::abs(OffD[Z]); if (sm==0.0) break; for (i=Z; i>=X; i--) { int p = nxt[i]; int q = nxt[p]; fabsOffDi = Alge::abs(OffD[i]); g = 100.0*fabsOffDi; if (fabsOffDi>0.0) { h = Diag[q] - Diag[p]; fabsh = Alge::abs(h); if (fabsh+g==fabsh) { t = OffD[i]/h; } else { theta = 0.5*h/OffD[i]; t = 1.0/(Alge::abs(theta)+Alge::sqrt(theta*theta+1.0)); if (theta<0.0) t = -t; } c = 1.0/Alge::sqrt(t*t+1.0); s = t*c; tau = s/(c+1.0); ta = t*OffD[i]; OffD[i] = 0.0; Diag[p] -= ta; Diag[q] += ta; OffDq = OffD[q]; OffD[q] -= s*(OffD[p] + tau*OffD[q]); OffD[p] += s*(OffDq - tau*OffD[p]); for (j=Z; j>=X; j--) { a = U[j][p]; b = U[j][q]; U[j][p] -= s*(b + tau*a); U[j][q] += s*(a - tau*b); } } } } kv.x = Diag[X]; kv.y = Diag[Y]; kv.z = Diag[Z]; kv.w = 1.0; return (kv); } /******* Spectral Axis Adjustment *******/ /** Given a unit quaternion, q, and a scale vector, k, find a unit quaternion, p, * which permutes the axes and turns freely in the plane of duplicate scale * factors, such that q p has the largest possible w component, i.e. the * smallest possible angle. Permutes k's components to go with q p instead of q. * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. * Proceedings of Graphics Interface 1992. Details on p. 262-263. */ template<class Real> typename DecompAffine<Real>::Quat DecompAffine<Real>::snuggle(Quat q, HVect *k) { #define SQRTHALF (0.7071067811865475244) #define sgn(n,v) ((n)?-(v):(v)) #define swap(a,i,j) {a[3]=a[i]; a[i]=a[j]; a[j]=a[3];} #define cycle(a,p) if (p) {a[3]=a[0]; a[0]=a[1]; a[1]=a[2]; a[2]=a[3];}\ else {a[3]=a[2]; a[2]=a[1]; a[1]=a[0]; a[0]=a[3];} Quat p; p.x = 0; Real ka[4]; int i, turn = -1; ka[X] = k->x; ka[Y] = k->y; ka[Z] = k->z; if (ka[X]==ka[Y]) {if (ka[X]==ka[Z]) turn = W; else turn = Z;} else {if (ka[X]==ka[Z]) turn = Y; else if (ka[Y]==ka[Z]) turn = X;} if (turn>=0) { Quat qtoz, qp; unsigned neg[3], win; Real mag[3], t; static Quat qxtoz = {0,SQRTHALF,0,SQRTHALF}; static Quat qytoz = {SQRTHALF,0,0,SQRTHALF}; static Quat qppmm = { 0.5, 0.5,-0.5,-0.5}; static Quat qpppp = { 0.5, 0.5, 0.5, 0.5}; static Quat qmpmm = {-0.5, 0.5,-0.5,-0.5}; static Quat qpppm = { 0.5, 0.5, 0.5,-0.5}; static Quat q0001 = { 0.0, 0.0, 0.0, 1.0}; static Quat q1000 = { 1.0, 0.0, 0.0, 0.0}; switch (turn) { default: return (Qt_Conj(q)); case X: q = Qt_Mul(q, qtoz = qxtoz); swap(ka,X,Z) break; case Y: q = Qt_Mul(q, qtoz = qytoz); swap(ka,Y,Z) break; case Z: qtoz = q0001; break; } q = Qt_Conj(q); mag[0] = (Real)q.z*q.z+(Real)q.w*q.w-0.5; mag[1] = (Real)q.x*q.z-(Real)q.y*q.w; mag[2] = (Real)q.y*q.z+(Real)q.x*q.w; for (i=0; i<3; i++) if ((neg[i] = (mag[i]<0.0)) == true) mag[i] = -mag[i]; if (mag[0]>mag[1]) {if (mag[0]>mag[2]) win = 0; else win = 2;} else {if (mag[1]>mag[2]) win = 1; else win = 2;} switch (win) { case 0: if (neg[0]) p = q1000; else p = q0001; break; case 1: if (neg[1]) p = qppmm; else p = qpppp; cycle(ka,0) break; case 2: if (neg[2]) p = qmpmm; else p = qpppm; cycle(ka,1) break; } qp = Qt_Mul(q, p); t = Alge::sqrt(mag[win]+0.5); p = Qt_Mul(p, Qt_(0.0,0.0,-qp.z/t,qp.w/t)); p = Qt_Mul(qtoz, Qt_Conj(p)); } else { Real qa[4], pa[4]; unsigned lo, hi, neg[4], par = 0; Real all, big, two; qa[0] = q.x; qa[1] = q.y; qa[2] = q.z; qa[3] = q.w; for (i=0; i<4; i++) { pa[i] = 0.0; if ((neg[i] = (qa[i]<0.0)) == true) qa[i] = -qa[i]; par ^= neg[i]; } /* Find two largest components, indices in hi and lo */ if (qa[0]>qa[1]) lo = 0; else lo = 1; if (qa[2]>qa[3]) hi = 2; else hi = 3; if (qa[lo]>qa[hi]) { if (qa[lo^1]>qa[hi]) {hi = lo; lo ^= 1;} else {hi ^= lo; lo ^= hi; hi ^= lo;} } else {if (qa[hi^1]>qa[lo]) lo = hi^1;} all = (qa[0]+qa[1]+qa[2]+qa[3])*0.5; two = (qa[hi]+qa[lo])*SQRTHALF; big = qa[hi]; if (all>two) { if (all>big) {/*all*/ {int i; for (i=0; i<4; i++) pa[i] = sgn(neg[i], 0.5);} cycle(ka,par) } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} } else { if (two>big) {/*two*/ pa[hi] = sgn(neg[hi],SQRTHALF); pa[lo] = sgn(neg[lo], SQRTHALF); if (lo>hi) {hi ^= lo; lo ^= hi; hi ^= lo;} if (hi==W) {hi = "\001\002\000"[lo]; lo = 3-hi-lo;} swap(ka,hi,lo) } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} } p.x = -pa[0]; p.y = -pa[1]; p.z = -pa[2]; p.w = pa[3]; } k->x = ka[X]; k->y = ka[Y]; k->z = ka[Z]; return (p); } /******* Decompose Affine Matrix *******/ /** Decompose 4x4 affine matrix A as TFRUK(U transpose), where t contains the * translation components, q contains the rotation R, u contains U, k contains * scale factors, and f contains the sign of the determinant. * Assumes A transforms column vectors in right-handed coordinates. * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. * Proceedings of Graphics Interface 1992. */ template<class Real> void DecompAffine<Real>::decomp_affine(HMatrix A, AffineParts *parts) { HMatrix Q, S, U; Quat p; Real det; parts->t = Qt_(A[X][W], A[Y][W], A[Z][W], 0); det = polar_decomp(A, Q, S); if (det<0.0) { mat_copy(Q,=,-Q,3); parts->f = -1; } else parts->f = 1; parts->q = Qt_FromMatrix(Q); parts->k = spect_decomp(S, U); parts->u = Qt_FromMatrix(U); p = snuggle(parts->u, &parts->k); parts->u = Qt_Mul(parts->u, p); } /******* Invert Affine Decomposition *******/ /* Compute inverse of affine decomposition. */ template<class Real> void DecompAffine<Real>::invert_affine(AffineParts *parts, AffineParts *inverse) { Quat t, p; inverse->f = parts->f; inverse->q = Qt_Conj(parts->q); inverse->u = Qt_Mul(parts->q, parts->u); inverse->k.x = (parts->k.x==0.0) ? 0.0 : 1.0/parts->k.x; inverse->k.y = (parts->k.y==0.0) ? 0.0 : 1.0/parts->k.y; inverse->k.z = (parts->k.z==0.0) ? 0.0 : 1.0/parts->k.z; inverse->k.w = parts->k.w; t = Qt_(-parts->t.x, -parts->t.y, -parts->t.z, 0); t = Qt_Mul(Qt_Conj(inverse->u), Qt_Mul(t, inverse->u)); t = Qt_(inverse->k.x*t.x, inverse->k.y*t.y, inverse->k.z*t.z, 0); p = Qt_Mul(inverse->q, inverse->u); t = Qt_Mul(p, Qt_Mul(t, Qt_Conj(p))); inverse->t = (inverse->f>0.0) ? t : Qt_(-t.x, -t.y, -t.z, 0); } //============================================================================================================== //============================================================================================================== template<class Real, int O> void Matrix<4,4,Real,O>::decomposeSkew( optional<Vec3&> trans, optional<Quat&> rot, optional<Vec3&> scale, optional<Quat&> skew) const { DecompAffine::HMatrix hmat; this->toArray(&hmat[0][0]); DecompAffine::AffineParts parts; DecompAffine::decomp_affine(hmat, &parts); if (trans) trans = Vec3(Real(parts.t.x), Real(parts.t.y), Real(parts.t.z)); if (rot) rot = Quat(Real(parts.q.x), Real(parts.q.y), Real(parts.q.z), Real(parts.q.w)); if (scale) scale = parts.f >= 0 ? Vec3(Real(parts.k.x), Real(parts.k.y), Real(parts.k.z)) : Vec3(Real(-parts.k.x), Real(-parts.k.y), Real(-parts.k.z)); if (skew) skew = Quat(Real(parts.u.x), Real(parts.u.y), Real(parts.u.z), Real(parts.u.w)); } template class Matrix<4,4,Float>; template class Matrix<4,4,Double>; template class Matrix<4,4,Quad>; }
34.966805
122
0.503501
[ "vector", "transform", "3d" ]
e6d0e517ab5fd3c87a94124f7cdff1c4128b02e8
2,605
cpp
C++
atcoder/arc070/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
atcoder/arc070/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
atcoder/arc070/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
// atcoder/arc070/D/main.cpp // author: @___Johniel // github: https://github.com/johniel/ #include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } template<typename T> struct PrefixSum { vector<T> sum; PrefixSum(vector<T> v) { sum.push_back(0); each (i, v) { sum.push_back(sum.back() + i); } } T query(size_t begin, size_t end) { return sum[end] - sum[begin]; } }; int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n; lli k; while (cin >> n >> k) { vector<lli> a(n); cin >> a; vector<lli> b = a; reverse(b.begin(), b.end()); const int N = 5000 + 5; const int K = 5000 + 5; static bool dp1[N][K]; static bool dp2[N][K]; fill(&dp1[0][0], &dp1[N - 1][K - 1] + 1, false); fill(&dp2[0][0], &dp2[N - 1][K - 1] + 1, false); dp1[0][0] = dp2[0][0] = true; for (int i = 0; i < n; ++i) { for (int j = 0; j < K; ++j) { dp1[i + 1][j] |= dp1[i][j]; dp2[i + 1][j] |= dp2[i][j]; if (j + a[i] < K) dp1[i + 1][j + a[i]] |= dp1[i][j]; if (j + b[i] < K) dp2[i + 1][j + b[i]] |= dp2[i][j]; } } int cnt = 0; for (int i = 0; i < n; ++i) { if (k <= a[i]) { ++cnt; continue; } vector<lli> v1, v2; for (int j = 0; j < K; ++j) { v1.push_back(dp1[i][j]); v2.push_back(dp2[n - i - 1][j]); } PrefixSum<lli> ps1(v1); PrefixSum<lli> ps2(v2); bool f = false; for (int j = 0; j <= k - 1; ++j) { const int p = max<int>(0, k - a[i] - j); f = f || (dp1[i][j] && ps2.query(p, k - j)); f = f || (dp2[n - i - 1][j] && ps1.query(p, k - j)); } cnt += f; } cout << n - cnt << endl; } return 0; }
27.421053
144
0.495585
[ "vector" ]
e6d2145605230831468fd028aa3e99ee15fad163
10,767
cpp
C++
src/hard/ray-of-light/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
src/hard/ray-of-light/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
src/hard/ray-of-light/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <cmath> #include <cstddef> #include <fstream> #include <functional> #include <iostream> #include <limits> #include <queue> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_map> #include <vector> struct Entity { using value_type = char; Entity() = delete; static bool isTransparent(const value_type entity) { switch(entity) { case Entity::space: case Entity::prism: case Entity::rayMinor: case Entity::rayMajor: case Entity::rayJunction: { return true; } } return false; } static const value_type space = ' ', // Ether. prism = '*', // Diffractive. tower = 'o', // Absorptive. mirror = '#', // Reflective. rayMajor = '\\', // 135° and 315° ray segment. rayMinor = '/', // 45° and 225° ray segment. rayJunction = 'X'; // Ray segment intersection. }; enum class Trajectory : unsigned short { #define DEFINE(Value) A##Value = (Value) #define VALUE_TYPE std::underlying_type<Trajectory>::type DEFINE( 45), DEFINE(135), DEFINE(225), DEFINE(315), Undefined = std::numeric_limits<VALUE_TYPE>::max() #undef VALUE_TYPE #undef DEFINE }; static constexpr Trajectory operator"" _deg(const unsigned long long angle) { #define IS(Value) angle == (Value) ? (Trajectory::A##Value) return IS( 45) : IS(135) : IS(225) : IS(315) : throw std::domain_error("Undefined"); #undef IS } struct EnumHasher { template<typename T> std::size_t operator()(const T value) const { return static_cast<std::size_t>(value); } }; struct Photon { Photon() : Photon(0, 0, Trajectory::Undefined) {} Photon(const int x, const int y, const Trajectory trajectory) : x(x), y(y), age(), trajectory(trajectory) {} void move(const int xOffset, const int yOffset) { this->x += xOffset; this->y += yOffset; } void reflect(const int xOffset, const int yOffset, const Trajectory trajectory) { this->move(xOffset, yOffset); this->trajectory = trajectory; } Photon clone(const Trajectory trajectory) const { auto clone = *this; clone.trajectory = trajectory; return clone; } bool operator==(const Photon& other) const { return (this->x == other.x) && (this->y == other.y) && (this->trajectory == other.trajectory); } int x, y; unsigned age; Trajectory trajectory; }; struct PhotonTraits { Entity::value_type symbol; int directionalOffsets[2]; Trajectory complements[2]; std::function<void(Photon&)> reflect; }; template<unsigned PhotonLifeSpan> class World { public: World& render() { for(Photon lastFrame; !this->photons.empty();) { this->tick(); if(!this->photons.empty()) { const auto& photon = this->photons.front(); // No more visible updates left for this packet. if(photon == lastFrame) { this->photons.pop(); continue; } lastFrame = photon; } } return *this; } private: void tick() { assert(!this->photons.empty()); const auto frameWidth = this->cells.size(); auto& photon = this->photons.front(); if(++photon.age > PhotonLifeSpan) { return this->photons.pop(); } const auto exists = [&](const int xOffset, const int yOffset) { const auto x = (photon.x + xOffset), y = (photon.y + yOffset), w = static_cast<int>(frameWidth); return ((x >= 0) && (y >= 0) && (x < w) && (y < w)); }; const auto at = [&](const int xOffset, const int yOffset) -> char& { assert(exists(xOffset, yOffset)); return this->cells[photon.y + yOffset][photon.x + xOffset]; }; const auto reflect = [&](Photon& self, const Trajectory trajectory, const int xOffset, const int yOffset) { const auto neighbor = this->cells[self.y + yOffset][self.x + xOffset]; if(Entity::isTransparent(neighbor)) { self.reflect(xOffset, yOffset, trajectory); } }; /* ┌─/───┐ ┌───\─┐ ┌─────┐ ┌─────┐ -1,-1 +1,-1 135°│ 45° │/ │ │ \│ │ 045 │ │ 135 │ ┌───┬───┬───┐ \ │ / │ 225 │ │ 315 │ │ /│ │\ │ │ \ │ ░ │ / │ II \│/ I └─────┘ └─────┘ └───/─┘ └─\───┘ ├───┼───┼───┤ ─────X───── │ ░ │ X │ ░ │ III /│\ IV ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ├───┼───┼───┤ / │ \ │ 225 / \ 315 │ │/ │ │ \│ │ / │ ░ │ \ │ 225°│ 315° │ /│ │\ │ / 045 │ │ 135 \ └───┴───┴───┘ └─────┘ └─────┘ └─────┘ └─────┘ -1,+1 +1,+1 */ using Traits = PhotonTraits; static const std::unordered_map<Trajectory, Traits, EnumHasher> rules = { // Quadrant I. { 45_deg, { Entity::rayMinor, {+1, -1}, {135_deg, 315_deg}, [&](Photon& self) { // Top edge. if(self.y == 1) reflect(self, 315_deg, +1, +0); // Right edge. else reflect(self, 135_deg, +0, -1); } } }, // Quadrant II. { 135_deg, { Entity::rayMajor, {-1, -1}, {45_deg, 225_deg}, [&](Photon& self) { // Top edge. if(self.y == 1) reflect(self, 225_deg, -1, +0); // Left edge. else reflect(self, 45_deg, +0, -1); } } }, // Quadrant III. { 225_deg, { Entity::rayMinor, {-1, +1}, {135_deg, 315_deg}, [&](Photon& self) { // Bottom edge. if(self.y == (frameWidth - 2)) reflect(self, 135_deg, -1, +0); // Left edge. else reflect(self, 315_deg, +0, +1); } } }, // Quadrant IV. { 315_deg, { Entity::rayMajor, {+1, +1}, {45_deg, 225_deg}, [&](Photon& self) { // Bottom edge. if(self.y == (frameWidth - 2)) reflect(self, 45_deg, +1, +0); // Right edge. else reflect(self, 225_deg, +0, +1); } } } }; assert(rules.find(photon.trajectory) != rules.cend()); const auto& traits = rules.at(photon.trajectory); // Render self. { auto& origin = at(0, 0); if(origin == Entity::space) origin = traits.symbol; else if((origin == Entity::rayMinor) || (origin == Entity::rayMajor)) { if(origin != traits.symbol) origin = Entity::rayJunction; } } const auto x = traits.directionalOffsets[0], y = traits.directionalOffsets[1]; // Decay self if we've departed from the world's bounds. if(!exists(x, y)) { photon.age = PhotonLifeSpan; return; } switch(at(x, y)) { // Propel self. case Entity::space: case Entity::rayMinor: case Entity::rayMajor: case Entity::rayJunction: { photon.move(x, y); } break; // Split self. case Entity::prism: { // Propagation inside prisms is free in terms of aging. --photon.age; photon.move(x, y); this->photons.emplace(photon.clone(traits.complements[0])); this->photons.emplace(photon.clone(traits.complements[1])); } break; // Reflect self. case Entity::mirror: traits.reflect(photon); break; } } private: friend std::istream& operator>>(std::istream& inputStream, World& self) { std::string payload; if(!std::getline(inputStream, payload)) return inputStream; const std::size_t worldWidth = std::sqrt(payload.size()); assert(worldWidth >= 3); assert((worldWidth * worldWidth) == payload.size()); auto& cells = self.cells; cells.clear(); for(std::size_t i = 0; i < worldWidth; ++i) { cells.emplace_back(payload.substr((i * worldWidth), worldWidth)); } // The world is supposed to be square. assert(!cells.empty() && (cells.size() == worldWidth)); // Slices should be of equal width and contain only whitelisted entities. assert(std::all_of(cells.cbegin(), cells.cend(), [&](const std::string& row) { const auto isAligned = (row.size() == cells.front().size()); const auto isWellFormed = (row.find_first_not_of("/\\ o*#") == std::string::npos); return (isAligned && isWellFormed); })); // Only one injection port should be present. assert(std::count_if(payload.cbegin(), payload.cend(), [](const char c) { return (c == '\\') || (c == '/'); }) == 1); // Inject the initial photon packet. { const auto injectionPort = payload.find_first_of("\\/"); const auto x = (injectionPort % worldWidth), y = (injectionPort / worldWidth); const auto packetTrajectory = [&] { const bool isForwardSlash = (payload[injectionPort] == '/'); if(!y) return (isForwardSlash ? 225_deg : 315_deg); if(!x) return (isForwardSlash ? 45_deg : 315_deg); if(y == (worldWidth - 1)) return (isForwardSlash ? 45_deg : 135_deg); if(x == (worldWidth - 1)) return (isForwardSlash ? 225_deg : 135_deg); assert(false); return Trajectory::Undefined; }(); cells[y][x] = Entity::space; self.photons.emplace(x, y, packetTrajectory); } return inputStream; } private: friend std::ostream& operator<<(std::ostream& outputStream, const World& self) { for(const auto& slice : self.cells) std::cout << slice; return outputStream; } private: std::vector<std::string> cells; private: std::queue<Photon> photons; }; int main(const int argc, const char* const argv[]) { // Getting away with no error checking throughout because CodeEval makes some // strong guarantees about our runtime environment. No need to pay when we're // being benchmarked. Don't forget to define NDEBUG prior to submitting! assert(argc >= 2 && "Expecting at least one command-line argument."); std::ifstream inputStream(argv[1]); assert(inputStream && "Failed to open input stream."); for(World<20> world; inputStream >> world;) { std::cout << world.render() << '\n'; } }
24.923611
80
0.521315
[ "render", "vector" ]
e6d42cfe4c383713389c254c77a0a4bf96b1eb2c
17,930
cpp
C++
create_clang_svml_intrinsic.cpp
Neumann-A/llvm_svml_intrinsic_generator
cdfeb4db8110de8b8c0684a98c74bc079605ea98
[ "MIT" ]
3
2019-06-09T20:55:05.000Z
2021-11-23T13:30:24.000Z
create_clang_svml_intrinsic.cpp
Neumann-A/llvm_svml_intrinsic_generator
cdfeb4db8110de8b8c0684a98c74bc079605ea98
[ "MIT" ]
null
null
null
create_clang_svml_intrinsic.cpp
Neumann-A/llvm_svml_intrinsic_generator
cdfeb4db8110de8b8c0684a98c74bc079605ea98
[ "MIT" ]
1
2022-02-06T21:26:11.000Z
2022-02-06T21:26:11.000Z
///------------------------------------------------------------------------------------------------- // file: create_clang_svml_intrinsic.cpp // // Copyright (c) 2019 Alexander Neumann. // MIT License see https://github.com/Neumann-A/llvm_svml_intrinsic_generator/blob/master/LICENSE // // author: Alexander // date: 09.04.2019 ///------------------------------------------------------------------------------------------------- #include <immintrin.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include <type_traits> #include <optional> #include <regex> #include <boost/program_options.hpp> #include "create_clang_svml_intrinsic.h" #include "svml_assembly_creator.h" #include "svml_test_creator.h" namespace bo_opts = ::boost::program_options; namespace fs = ::std::filesystem; struct func_str_list { std::vector<std::string> vdecl; std::vector<std::string> svml; }; constexpr const opts_string optstr{ "vdecl-list","svml-list", "avx-out","avx-test-out","avx512-out","avx512-test-out" }; bo_opts::options_description desc{ "Options" }; void displayHelp() { ::std::cerr << "This programm will use the VDECL & SVML input files to automatically generate a header to map VS __vdecl symbols to SVML __mm intrinsics.\n"; ::std::cerr << desc << std::endl; } void parseOptions(int argc, char** argv, Opts& opts) { desc.add_options() ("help", "This programm will") (optstr.vdecl.data(), bo_opts::value<fs::path>(&opts.vdecl)->default_value({ "vdecl_list.txt" }), "list with vdecl symbols to map") (optstr.svml.data(), bo_opts::value<fs::path>(&opts.svml)->default_value({ "svml_intrinsics_vs.txt" }), "list with all svml intrinsics") // (optstr.svml.data(), bo_opts::value<fs::path>(&opts.svml)->default_value({ "svml_intrinsics.txt" }), "list with all svml intrinsics"); (optstr.avx_out.data(), bo_opts::value<fs::path>(&opts.avx_out)->default_value({ "avx_svml_intrin.h" }), "Ouptut file for avx svml intrinsics") (optstr.avx_test_out.data(), bo_opts::value<fs::path>(&opts.avx_test_out)->default_value({ "avx_svml_test.cpp" }), "Ouptut file for avx svml test file") (optstr.avx512_out.data(), bo_opts::value<fs::path>(&opts.avx512_out)->default_value({ "avx512_svml_intrin.h" }), "Ouptut file for avx512 svml intrinsics") (optstr.avx512_test_out.data(), bo_opts::value<fs::path>(&opts.avx512_test_out)->default_value({ "avx512_svml_test.cpp" }), "Ouptut file for avx512 svml test file"); bo_opts::variables_map vm; bo_opts::store(bo_opts::parse_command_line(argc, argv, desc), vm); bo_opts::notify(vm); if (vm.count("help") > 0) { displayHelp(); } //const auto val = vm[optstr.vdecl.data()]; //Opts opts{ vm[optstr.vdecl.data()].as<fs::path>(), vm[optstr.svml.data()].as<fs::path>() }; ::std::cerr << "This programm will use the VDECL & SVML input files to automatically generate a header to map Microsofts __vdecl symbols to SVML __mm intrinsics.\n"; ::std::cerr << "SVML Input file: " << opts.svml << '\n'; ::std::cerr << "VDECL Input file: " << opts.svml << '\n'; } void checkOpts(const Opts& opts) { if (!std::filesystem::exists(opts.vdecl)) { ::std::cerr << "VDECL Input does not exist! Filepath: " << opts.vdecl << '\n'; ::std::abort(); } if (!std::filesystem::exists(opts.svml)) { ::std::cerr << "SVML Input does not exist! Filepath: " << opts.svml << '\n'; ::std::abort(); } }; func_str_list loadLists(const Opts& opts) { func_str_list lines; { std::ifstream vdeclfile(opts.vdecl); std::ifstream svmlfile(opts.svml); for (std::string line; std::getline(vdeclfile, line);) { lines.vdecl.push_back(line); } for (std::string line; std::getline(svmlfile, line);) { lines.svml.push_back(line); } } return lines; } std::map<packed_type_info, std::string_view> packed_type_name_map_info{ {packed_type_info::pd, "pd"}, {packed_type_info::ps, "ps"}, {packed_type_info::epi8, "epi8"}, {packed_type_info::epi16, "epi16"}, {packed_type_info::epi32, "epi32"}, {packed_type_info::epi64, "epi64"}, {packed_type_info::epu8, "epu8"}, {packed_type_info::epu16, "epu16"}, {packed_type_info::epu32, "epu32"}, {packed_type_info::epu64, "epu64"} }; std::map<packed_type_info, std::size_t> packed_type_size_map_info{ {packed_type_info::pd, sizeof(double)}, {packed_type_info::ps, sizeof(float)}, {packed_type_info::epi8, sizeof(std::int8_t)}, {packed_type_info::epi16, sizeof(std::int16_t)}, {packed_type_info::epi32, sizeof(std::int32_t)}, {packed_type_info::epi64, sizeof(std::int64_t)}, {packed_type_info::epu8, sizeof(std::uint8_t)}, {packed_type_info::epu16, sizeof(std::uint16_t)}, {packed_type_info::epu32, sizeof(std::uint32_t)}, {packed_type_info::epu64, sizeof(std::uint64_t)} }; std::map<packed_type_info, std::string_view> packed_type_vdecl_name_map_info{ {packed_type_info::pd, ""}, {packed_type_info::ps, "f"}, {packed_type_info::epi8, "i8"}, {packed_type_info::epi16, "i16"}, {packed_type_info::epi32, "i32"}, {packed_type_info::epi64, "i64"}, {packed_type_info::epu8, "u8"}, {packed_type_info::epu16, "u16"}, {packed_type_info::epu32, "u32"}, {packed_type_info::epu64, "u64"} }; std::map<intrin_type_info, std::string_view> intrin_param_map_info{ {intrin_type_info::m128i, "__m128i"}, {intrin_type_info::m256i, "__m256i"}, {intrin_type_info::m512i, "__m512i"}, {intrin_type_info::m128, "__m128"}, {intrin_type_info::m256, "__m256"}, {intrin_type_info::m512, "__m512"}, {intrin_type_info::m128d, "__m128d"}, {intrin_type_info::m256d, "__m256d"}, {intrin_type_info::m512d, "__m512d"}, {intrin_type_info::pm128i, "__m128i *"}, {intrin_type_info::pm256i, "__m256i *"}, {intrin_type_info::pm512i, "__m512i *"}, {intrin_type_info::pm128, "__m128 *"}, {intrin_type_info::pm256, "__m256 *"}, {intrin_type_info::pm512, "__m512 *"}, {intrin_type_info::pm128d, "__m128d *"}, {intrin_type_info::pm256d, "__m256d *"}, {intrin_type_info::pm512d, "__m512d *"}, {intrin_type_info::mask8, "__mmask8"}, {intrin_type_info::mask16, "__mmask16"}, }; std::map<intrin_type_info, std::string_view> intrin_regprefix{ {intrin_type_info::m128i, "x"}, {intrin_type_info::m256i, "y"}, {intrin_type_info::m512i, "z"}, {intrin_type_info::m128, "x"}, {intrin_type_info::m256, "y"}, {intrin_type_info::m512, "z"}, {intrin_type_info::m128d, "x"}, {intrin_type_info::m256d, "y"}, {intrin_type_info::m512d, "z"}, {intrin_type_info::pm128i, "x"}, {intrin_type_info::pm256i, "y"}, {intrin_type_info::pm512i, "z"}, {intrin_type_info::pm128, "x"}, {intrin_type_info::pm256, "y"}, {intrin_type_info::pm512, "z"}, {intrin_type_info::pm128d, "x"}, {intrin_type_info::pm256d, "y"}, {intrin_type_info::pm512d, "z"}, {intrin_type_info::mask8, "k"}, {intrin_type_info::mask16, "k"}, }; std::map<intrin_type_info, std::size_t> intrin_type_size_map_info{ {intrin_type_info::m128, sizeof(__m128)}, {intrin_type_info::m256, 2*sizeof(__m128)}, {intrin_type_info::m512, 4*sizeof(__m128)}, {intrin_type_info::m128i, sizeof(__m128)}, {intrin_type_info::m256i, 2 * sizeof(__m128)}, {intrin_type_info::m512i, 4 * sizeof(__m128)}, {intrin_type_info::m128d, sizeof(__m128)}, {intrin_type_info::m256d, 2 * sizeof(__m128)}, {intrin_type_info::m512d, 4 * sizeof(__m128)} }; [[nodiscard]] bool is_pointer_type(intrin_type_info type) { switch (type) { case intrin_type_info::pm128i: case intrin_type_info::pm256i: case intrin_type_info::pm512i: case intrin_type_info::pm128: case intrin_type_info::pm256: case intrin_type_info::pm512: case intrin_type_info::pm128d: case intrin_type_info::pm256d: case intrin_type_info::pm512d: return true; default: return false; } } [[nodiscard]] bool is_mask_type(intrin_type_info type) { switch (type) { case intrin_type_info::mask8: case intrin_type_info::mask16: return true; default: return false; } } [[nodiscard]] bool is_interger_func(packed_type_info type) { switch (type) { case packed_type_info::epi8: case packed_type_info::epi16: case packed_type_info::epi32: case packed_type_info::epi64: case packed_type_info::epu8: case packed_type_info::epu16: case packed_type_info::epu32: case packed_type_info::epu64: return true; default: return false; } } std::map<intrin_type_info, std::string_view> intrin_func_prefix_info{ {intrin_type_info::m128, "mm"}, {intrin_type_info::m256, "mm256"}, {intrin_type_info::m512, "mm512"}, {intrin_type_info::m128i, "mm"}, {intrin_type_info::m256i, "mm256"}, {intrin_type_info::m512i, "mm512"}, {intrin_type_info::m128d, "mm"}, {intrin_type_info::m256d, "mm256"}, {intrin_type_info::m512d, "mm512"}, {intrin_type_info::pm128, "mm"}, {intrin_type_info::pm256, "mm256"}, {intrin_type_info::pm512, "mm512"}, {intrin_type_info::pm128i, "mm"}, {intrin_type_info::pm256i, "mm256"}, {intrin_type_info::pm512i, "mm512"}, {intrin_type_info::pm128d, "mm"}, {intrin_type_info::pm256d, "mm256"}, {intrin_type_info::pm512d, "mm512"} }; std::map<intrin_type_info, std::string_view> intrin_func_suffix_info{ {intrin_type_info::m128i, ""}, {intrin_type_info::m256i, ""}, {intrin_type_info::m512i, ""}, {intrin_type_info::m128, "ps"}, {intrin_type_info::m256, "ps"}, {intrin_type_info::m512, "ps"}, {intrin_type_info::m128d, "pd"}, {intrin_type_info::m256d, "pd"}, {intrin_type_info::m512d, "pd"} }; std::ostream& operator<<(std::ostream& os, const svml_string_info& info) { os << "SVML STRING INFO Return: " << info.retval << '\n'; os << "SVML STRING INFO Prefix: " << info.prefix << '\n'; os << "SVML STRING INFO Mask: " << (info.mask.empty() ? false : true) << '\n'; os << "SVML STRING INFO Name: " << info.func << '\n'; os << "SVML STRING INFO Postfix: " << info.postfix << '\n'; os << "SVML STRING INFO Params: " << info.params << '\n'; return os; } [[nodiscard]] bool is_complex_func(const std::string_view str) { bool is_csqrt = (str.find("csqrt") != std::string_view::npos); bool is_clog = (str.find("clog") != std::string_view::npos); bool is_cexp = (str.find("cexp") != std::string_view::npos); return (is_csqrt || is_clog || is_cexp); } static const std::regex vdeclanalyzeregex{ "__vdecl_[a-zA-Z0-9]+[2468]" }; [[nodiscard]] std::optional<vdecl_symbol_info> analyze_vdecl_line(const std::string& str) { std::smatch m; std::regex_search(str, m, vdeclanalyzeregex); if (!m.empty()) { for (auto& elems : m) { ::std::cerr << "Match: " << elems << '\n'; } return vdecl_symbol_info{ m[0] }; } return { std::nullopt }; } static const std::regex isinversesuffixregex{"[a-z]+inv"}; static const std::regex isinverseprefixregex{ "inv[a-z]+" }; [[nodiscard]] bool is_inverse_suffix_func(const std::string& str) { std::smatch m; return std::regex_match(str, m, isinversesuffixregex); } [[nodiscard]] bool is_inverse_prefix_func(const std::string& str) { std::smatch m; return std::regex_match(str, m, isinverseprefixregex); } std::string remove_inverse_suffix(const std::string& str) { return str.substr(0, str.size() - 3); } std::string remove_inverse_prefix(const std::string& str) { return str.substr(3, str.size()); } std::string build_vdecl_symbol_name(const mm_intrinsics_info& info) { std::stringstream stream; stream << "__vdecl_"; if (info.isIntegerFunction) { stream << packed_type_vdecl_name_map_info[info.Suffix]; if ((info.MathFunction[0] == 'u' || info.MathFunction[0] == 'i')) stream << info.MathFunction.substr(1, info.MathFunction.size()); else stream << info.MathFunction; } else { if (info.isInversePrefix) stream << "inv"; stream << info.MathFunction; if (info.isInverseSuffix) stream << "inv"; stream << packed_type_vdecl_name_map_info[info.Suffix]; } stream << std::to_string(info.PackedElements); return stream.str(); } static const std::regex svmlanalyzerregex{ "(__[^_]+) (_([^_]+)_(mask)?_?(svml_)?([^_]+)_([^_]+)) ?\\(([^\\(\\)]+)\\)" }; static const std::regex svmlanalyzerparams{ "(__m[0-9id]{3,4} \\*|__m[0-9id]{3,4}|__mmask8|__mmask16)" }; [[nodiscard]] std::optional<svml_definition_info> analyze_svml_line(const std::string& str) { ::std::cerr << "Analysing line: " << str << '\n'; std::smatch m; std::regex_search(str, m, svmlanalyzerregex); if (!m.empty()) { svml_string_info info{ m[0],m[1],m[2],m[3],m[5],m[6],m[7],m[8] }; //mm_intrinsics_info{ !info.mask.empty(), }; //::std::cerr << info; std::size_t pos{ 0 }; std::size_t lastpos{ 0 }; std::smatch m2; std::vector<intrin_type_info> params; //should probably rename this lambda to something more usefull auto func_on_type_lambda = [](auto& map, const std::string& strtype, auto& func) { auto type = from_string(map, strtype); if (type) { func(*type); } else { ::std::cerr << "Could not determine type for " << strtype << '\n'; } }; auto return_type = [](auto& map,const std::string& strtype) { auto type = from_string(map, strtype); return type.value(); }; while(pos < info.params.size()) { pos = info.params.find_first_of(',', lastpos); auto substr = info.params.substr(lastpos, pos-lastpos); lastpos = pos+1; std::regex_search(substr, m2, svmlanalyzerparams); if (!m2.empty() && m2.size() > 1) { auto emplace_back = [&params](auto elem) {params.emplace_back(std::move(elem)); }; func_on_type_lambda(intrin_param_map_info, m2[1].str(), emplace_back); } } //Setting all the intrinsic information. mm_intrinsics_info mm_info; mm_info.ReturnType = return_type(intrin_param_map_info, info.retval); mm_info.isInverseSuffix = is_inverse_suffix_func(info.func); mm_info.isInversePrefix = is_inverse_prefix_func(info.func); if (mm_info.isInverseSuffix) mm_info.MathFunction = remove_inverse_suffix(info.func); else if (mm_info.isInversePrefix) mm_info.MathFunction = remove_inverse_prefix(info.func); else mm_info.MathFunction = info.func; mm_info.Prefix = return_type(intrin_func_prefix_info, info.prefix); mm_info.Suffix = return_type(packed_type_name_map_info, info.postfix); mm_info.isIntegerFunction = is_interger_func(mm_info.Suffix); mm_info.NumberOfParams = params.size(); mm_info.ParamList = params; auto find_mask = [](auto & list) { for (auto& elem : list) { if (is_mask_type(elem)) return true; } return false; }; mm_info.hasMask = find_mask(params); mm_info.FullFunctionName = info.fullsignature; mm_info.PackedElements = intrin_type_size_map_info[mm_info.ReturnType]/packed_type_size_map_info[mm_info.Suffix]; if (is_complex_func(mm_info.MathFunction)) mm_info.PackedElements /= 2; return svml_definition_info{ info, mm_info, build_vdecl_symbol_name(mm_info)}; } return { std::nullopt }; } [[nodiscard]] std::vector<vdecl_symbol_info> analyze_vdecl_list(std::vector<std::string>& strlist) { std::vector<vdecl_symbol_info> symbol_info; symbol_info.reserve(strlist.size()); std::vector<std::string> notanalyzed; for (const auto& elem : strlist) { auto info = analyze_vdecl_line(elem); if (!info) { notanalyzed.push_back(elem); ::std::cerr << "Could not analyze line: " << elem << '\n'; continue; } symbol_info.emplace_back(std::move(*info)); } strlist = notanalyzed; symbol_info.shrink_to_fit(); return symbol_info; } [[nodiscard]] std::vector<svml_definition_info> analyze_svml_list(std::vector<std::string>& strlist) { std::vector<svml_definition_info> symbol_info; symbol_info.reserve(strlist.size()); std::vector<std::string> notanalyzed; for (const auto& elem : strlist) { auto info = analyze_svml_line(elem); if (!info) { notanalyzed.push_back(elem); ::std::cerr << "Could not analyze line: " << elem << '\n'; continue; } symbol_info.emplace_back(std::move(*info)); } strlist = notanalyzed; symbol_info.shrink_to_fit(); return symbol_info; } [[nodiscard]] svml_mapping_info analyzeInputLists(func_str_list& list) { auto vdeclinfo = analyze_vdecl_list(list.vdecl); auto svmlinfo = analyze_svml_list(list.svml); for (auto& elem : svmlinfo) { auto vdeclelem = std::find_if(vdeclinfo.begin(), vdeclinfo.end(), [&](vdecl_symbol_info & elem2) { return elem2.FunctionName == elem.svml_to_vdecl_name; }); if (vdeclelem == vdeclinfo.end()) { ::std::cerr << "No Mapping for: " << elem.strinfo.fullsignature << " found\n"; ::std::cerr << "Mapping should have been: " << elem.svml_to_vdecl_name << "!\n"; continue; } elem.mapping_valid = true; vdeclelem->svml_mapping.push_back(&elem); } for (auto& elem : vdeclinfo) { if (elem.svml_mapping.size() != 0) { ::std::cerr << "Symbol:\t" << elem.FunctionName << "\t->\t"; for (auto& mapped : elem.svml_mapping) ::std::cerr << mapped->strinfo.mmfuncname << "\t"; ::std::cerr << "\n\n"; } } for (auto& elem : vdeclinfo) { if (elem.svml_mapping.size() == 0) { ::std::cerr << "No Mapping for vdecl symbol: " << elem.FunctionName << " \n"; } } //std::size_t mappings_found = std::count_if(svmlinfo.begin(), svmlinfo.end(), [&](svml_definition_info & elem) { // return std::find_if(vdeclinfo.begin(), vdeclinfo.end(), [&](vdecl_symbol_info & elem2) { // return elem2.FunctionName == elem.svml_to_vdecl_name; // }) != vdeclinfo.end(); // }); return { vdeclinfo , svmlinfo }; } void outputRemainingLists(func_str_list& list) { ::std::cerr << "The following __vdecl symbols have not been mapped: \n"; for (const auto& elem : list.vdecl) ::std::cerr << elem << '\n'; ::std::cerr << "The following SVML intrinsics could not be found within the __vdecl symbols: \n"; for (const auto& elem : list.svml) ::std::cerr << elem << '\n'; } int main(int argc, char** argv) { Opts opts; parseOptions(argc, argv, opts); checkOpts(opts); auto list = loadLists(opts); auto mapping_info = analyzeInputLists(list); svml::write_svml_intrinsics(mapping_info, opts.avx_out, opts.avx512_out); svml::write_svml_tests(mapping_info, opts.avx_test_out, opts.avx512_test_out); //outputRemainingLists(list); return EXIT_SUCCESS; }
32.132616
167
0.685611
[ "vector" ]
5c7fcd28c99b17a4f44ae1312cd8977ef9cf2377
1,969
cpp
C++
ss/utils.cpp
leduftw/ss
eb9ec70b8adbf6cd991f009c89f1667682150701
[ "MIT" ]
1
2021-09-01T09:00:06.000Z
2021-09-01T09:00:06.000Z
ss/utils.cpp
leduftw/ss
eb9ec70b8adbf6cd991f009c89f1667682150701
[ "MIT" ]
null
null
null
ss/utils.cpp
leduftw/ss
eb9ec70b8adbf6cd991f009c89f1667682150701
[ "MIT" ]
null
null
null
#include "utils.hpp" #include "usage_error.hpp" void Utils::process_input(int argc, char** argv, string& input_file_name, string& output_file_name) { if (argc < 2 || argc > 4) { throw UsageError(); } if (string(argv[1]) == "-o") { if (argc != 4) { throw UsageError(); } output_file_name = string(argv[2]); input_file_name = string(argv[3]); } else { if (argc != 2) { throw UsageError(); } input_file_name = string(argv[1]); } // If you just want input file name as argument without typing whole path, uncomment next line //input_file_name = "./test/" + input_file_name; } string Utils::get_file_name_without_extension(string& file_name) { size_t last_index = file_name.find_last_of("."); // If last_index == string::npos, then substring is the whole string return file_name.substr(0, last_index); } vector<string> Utils::split_string(string s, string delimiter) { size_t pos_start = 0, pos_end, delim_len = delimiter.length(); string token; vector<string> res; while ((pos_end = s.find(delimiter, pos_start)) != string::npos) { token = s.substr(pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; res.push_back(token); } res.push_back(s.substr(pos_start)); return res; } void Utils::left_trim_string(string& s) { s.erase(s.begin(), find_if(s.begin(), s.end(), [](unsigned char ch) { return !isspace(ch); })); } void Utils::right_trim_string(string& s) { s.erase(find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !isspace(ch); }).base(), s.end()); } string Utils::trim_string(string s) { left_trim_string(s); right_trim_string(s); return s; } string Utils::int_to_hex(int i) { stringstream stream; stream << "0x" << setfill('0') << setw(4) << hex << i; return stream.str(); }
24.924051
101
0.606399
[ "vector" ]
5c7ff4034195f5f2126e876965c6ea3d3c27c289
4,272
cpp
C++
clmagmablas/zlascl_2x2.cpp
Zhitao-Li/clMagma
c8dcc4025601ac67736714fb43f8f4382c05d900
[ "BSD-3-Clause" ]
null
null
null
clmagmablas/zlascl_2x2.cpp
Zhitao-Li/clMagma
c8dcc4025601ac67736714fb43f8f4382c05d900
[ "BSD-3-Clause" ]
1
2021-03-13T10:05:16.000Z
2021-03-13T10:05:16.000Z
clmagmablas/zlascl_2x2.cpp
Zhitao-Li/clMagma
c8dcc4025601ac67736714fb43f8f4382c05d900
[ "BSD-3-Clause" ]
null
null
null
/* -- MAGMA (version 1.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date @precisions normal z -> s d c auto-converted from zlascl_2x2.cu @author Ichitaro Yamazaki */ #include "clmagma_runtime.h" #include "common_magma.h" #include "zlascl_2x2.h" /** Purpose ------- ZLASCL_2x2 scales the M by M complex matrix A by the 2-by-2 pivot. TYPE specifies that A may be upper or lower triangular. Arguments --------- @param[in] type magma_type_t TYPE indices the storage type of the input matrix A. = MagmaLower: lower triangular matrix. = MagmaUpper: upper triangular matrix. Other formats that LAPACK supports, MAGMA does not currently support. @param[in] m INTEGER The number of rows of the matrix A. M >= 0. @param[in] dW DOUBLE PRECISION vector, dimension (2*lddw) The matrix containing the 2-by-2 pivot. @param[in] lddw INTEGER The leading dimension of the array W. LDDA >= max(1,M). @param[in,out] dA COMPLEX*16 array, dimension (LDDA,N) The matrix to be scaled by dW. See TYPE for the storage type. @param[in] ldda INTEGER The leading dimension of the array A. LDDA >= max(1,M). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value. @ingroup magma_zaux2 ********************************************************************/ extern "C" void magmablas_zlascl_2x2( magma_type_t type, magma_int_t m, magmaDoubleComplex_const_ptr dW, size_t dW_offset, magma_int_t lddw, magmaDoubleComplex_ptr dA, size_t dA_offset, magma_int_t ldda, magma_queue_t queue, magma_int_t *info ) { cl_kernel kernel; cl_int err; int arg; *info = 0; if ( type != MagmaLower && type != MagmaUpper ) *info = -1; else if ( m < 0 ) *info = -2; else if ( ldda < max(1,m) ) *info = -4; if (*info != 0) { magma_xerbla( __func__, -(*info) ); return; //info; } const int ndim = 1; size_t threads[ndim]; threads[0] = NB; size_t grid[ndim]; grid[0] = magma_ceildiv( m, NB ); grid[0] *= threads[0]; if (type == MagmaLower) { kernel = g_runtime.get_kernel( "zlascl_2x2_lower" ); if ( kernel != NULL ) { err = 0; arg = 0; err |= clSetKernelArg( kernel, arg++, sizeof(m ), &m ); err |= clSetKernelArg( kernel, arg++, sizeof(dW ), &dW ); err |= clSetKernelArg( kernel, arg++, sizeof(dW_offset), &dW_offset ); err |= clSetKernelArg( kernel, arg++, sizeof(lddw ), &lddw ); err |= clSetKernelArg( kernel, arg++, sizeof(dA ), &dA ); err |= clSetKernelArg( kernel, arg++, sizeof(dA_offset), &dA_offset ); err |= clSetKernelArg( kernel, arg++, sizeof(ldda ), &ldda ); check_error( err ); err = clEnqueueNDRangeKernel( queue, kernel, ndim, NULL, grid, threads, 0, NULL, NULL ); check_error( err ); } } else { kernel = g_runtime.get_kernel( "zlascl_2x2_upper" ); if ( kernel != NULL ) { err = 0; arg = 0; err |= clSetKernelArg( kernel, arg++, sizeof(m ), &m ); err |= clSetKernelArg( kernel, arg++, sizeof(dW ), &dW ); err |= clSetKernelArg( kernel, arg++, sizeof(dW_offset), &dW_offset ); err |= clSetKernelArg( kernel, arg++, sizeof(lddw ), &lddw ); err |= clSetKernelArg( kernel, arg++, sizeof(dA ), &dA ); err |= clSetKernelArg( kernel, arg++, sizeof(dA_offset), &dA_offset ); err |= clSetKernelArg( kernel, arg++, sizeof(ldda ), &ldda ); check_error( err ); err = clEnqueueNDRangeKernel( queue, kernel, ndim, NULL, grid, threads, 0, NULL, NULL ); check_error( err ); } } }
32.610687
100
0.529494
[ "vector" ]
5c82388bfe8a0007c55b5f3f4ea7b55518b865ba
1,338
hpp
C++
shared_model/backend/protobuf/query_responses/proto_transaction_response.hpp
artyom-yurin/iroha-archive
1ad3a149d21d30e99c650a9a4bad88b2792d751d
[ "Apache-2.0" ]
31
2019-04-17T19:32:05.000Z
2022-02-05T01:35:02.000Z
shared_model/backend/protobuf/query_responses/proto_transaction_response.hpp
artyom-yurin/iroha-archive
1ad3a149d21d30e99c650a9a4bad88b2792d751d
[ "Apache-2.0" ]
11
2016-10-13T10:09:55.000Z
2019-06-13T08:49:11.000Z
shared_model/backend/protobuf/query_responses/proto_transaction_response.hpp
artyom-yurin/iroha-archive
1ad3a149d21d30e99c650a9a4bad88b2792d751d
[ "Apache-2.0" ]
12
2019-06-03T10:31:31.000Z
2021-12-13T12:17:15.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_SHARED_MODEL_PROTO_TRANSACTION_RESPONSE_HPP #define IROHA_SHARED_MODEL_PROTO_TRANSACTION_RESPONSE_HPP #include "backend/protobuf/common_objects/trivial_proto.hpp" #include "backend/protobuf/transaction.hpp" #include "interfaces/common_objects/types.hpp" #include "interfaces/query_responses/transactions_response.hpp" #include "qry_responses.pb.h" namespace shared_model { namespace proto { class TransactionsResponse final : public CopyableProto<interface::TransactionsResponse, iroha::protocol::QueryResponse, TransactionsResponse> { public: template <typename QueryResponseType> explicit TransactionsResponse(QueryResponseType &&queryResponse); TransactionsResponse(const TransactionsResponse &o); TransactionsResponse(TransactionsResponse &&o); interface::types::TransactionsCollectionType transactions() const override; private: const iroha::protocol::TransactionsResponse &transaction_response_; const std::vector<proto::Transaction> transactions_; }; } // namespace proto } // namespace shared_model #endif // IROHA_SHARED_MODEL_PROTO_TRANSACTION_RESPONSE_HPP
32.634146
73
0.740658
[ "vector" ]
5c826d3b4813716b1dd11940edf33bb172e619a4
21,095
hxx
C++
include/itkVariationalRegistrationElasticRegularizer.hxx
InsightSoftwareConsortium/ITKVariationalRegistration
7634013fa2b661eda81d79e52b804f669ec0ce79
[ "Apache-2.0" ]
1
2018-11-05T19:59:43.000Z
2018-11-05T19:59:43.000Z
include/itkVariationalRegistrationElasticRegularizer.hxx
InsightSoftwareConsortium/ITKVariationalRegistration
7634013fa2b661eda81d79e52b804f669ec0ce79
[ "Apache-2.0" ]
23
2016-12-06T17:11:58.000Z
2020-02-23T09:01:51.000Z
include/itkVariationalRegistrationElasticRegularizer.hxx
InsightSoftwareConsortium/ITKVariationalRegistration
7634013fa2b661eda81d79e52b804f669ec0ce79
[ "Apache-2.0" ]
3
2016-12-05T21:52:36.000Z
2020-05-08T18:17:46.000Z
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkVariationalRegistrationElasticRegularizer_hxx #define itkVariationalRegistrationElasticRegularizer_hxx #if defined(ITK_USE_FFTWD) || defined(ITK_USE_FFTWF) # include "itkVariationalRegistrationElasticRegularizer.h" # include "itkImageRegionConstIterator.h" # include "itkImageRegionConstIteratorWithIndex.h" # include "itkNeighborhoodAlgorithm.h" namespace itk { /** * Default constructor */ template <typename TDisplacementField> VariationalRegistrationElasticRegularizer<TDisplacementField>::VariationalRegistrationElasticRegularizer() { for (unsigned int i = 0; i < ImageDimension; ++i) { m_Size[i] = 0; m_ComplexSize[i] = 0; m_Spacing[i] = 1.0; m_ComplexOffsetTable[i] = 0; } m_TotalComplexSize = 0; m_TotalSize = 0; // Initialize regularization weights m_Lambda = 1.0; m_Mu = 1.0; for (unsigned int i = 0; i < ImageDimension; ++i) { this->m_MatrixCos[i] = nullptr; this->m_MatrixSin[i] = nullptr; this->m_ComplexBuffer[i] = nullptr; this->m_PlanForward[i] = nullptr; this->m_PlanBackward[i] = nullptr; } this->m_InputBuffer = nullptr; this->m_OutputBuffer = nullptr; } /** * Generate data */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::GenerateData() { // Allocate the output image this->AllocateOutputs(); // Initialize and allocate data this->Initialize(); // Execute regularization this->Regularize(); } /* * Initialize flags */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::Initialize() { this->Superclass::Initialize(); DisplacementFieldPointer DisplacementField = this->GetOutput(); this->m_Spacing = DisplacementField->GetSpacing(); typename DisplacementFieldType::SizeType size = DisplacementField->GetRequestedRegion().GetSize(); // Only reinitialize FFT plans if size has changed since last Initialize() if (size != this->m_Size) { // Set new image size and complex buffer size including total sizes. // According to the FFTW manual, the complex buffer has the size // [n_0/2+1 , n_1, ..., n_d]. this->m_Size = size; this->m_ComplexSize[0] = static_cast<unsigned int>(size[0]) / 2 + 1; for (unsigned int i = 1; i < ImageDimension; ++i) { this->m_ComplexSize[i] = size[i]; } // Calculate offset table for complex image this->m_ComplexOffsetTable[0] = 1; for (unsigned int j = 0; j + 1 < ImageDimension; j++) { this->m_ComplexOffsetTable[j + 1] = this->m_ComplexOffsetTable[j] * this->m_ComplexSize[j]; } // Compute total number of pixels this->m_TotalSize = 1; this->m_TotalComplexSize = 1; for (unsigned int i = 0; i < ImageDimension; ++i) { this->m_TotalSize *= this->m_Size[i]; this->m_TotalComplexSize *= this->m_ComplexSize[i]; } // Reset old data FreeData(); // initialize matrix and FFTW plans if (!InitializeElasticMatrix()) { itkExceptionMacro(<< "Initializing Elastic Matrix failed!"); return; } if (!InitializeElasticFFTPlans()) { itkExceptionMacro(<< "Initializing Elastic Plans for FFT failed!"); return; } } } /* * Reset data */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::FreeData() { for (unsigned int i = 0; i < ImageDimension; ++i) { if (this->m_MatrixCos[i] != nullptr) delete[] this->m_MatrixCos[i]; if (this->m_MatrixSin[i] != nullptr) delete[] this->m_MatrixSin[i]; if (this->m_PlanForward[i] != nullptr) FFTWProxyType::DestroyPlan(this->m_PlanForward[i]); if (this->m_PlanBackward[i] != nullptr) FFTWProxyType::DestroyPlan(this->m_PlanBackward[i]); if (this->m_ComplexBuffer[i] != nullptr) delete[] this->m_ComplexBuffer[i]; } if (this->m_InputBuffer != nullptr) delete[] this->m_InputBuffer; if (this->m_OutputBuffer != nullptr) delete[] this->m_OutputBuffer; } /** * Initialize FFT plans */ template <typename TDisplacementField> bool VariationalRegistrationElasticRegularizer<TDisplacementField>::InitializeElasticFFTPlans() { itkDebugMacro(<< "Initializing elastic plans for FFT..."); // Get image size in reverse order for FFTW auto * n = new int[ImageDimension]; for (unsigned int i = 0; i < ImageDimension; ++i) { n[(ImageDimension - 1) - i] = this->m_Size[i]; } // Allocate buffers this->m_InputBuffer = new FFTWProxyType::PixelType[this->m_TotalSize]; this->m_OutputBuffer = new FFTWProxyType::PixelType[this->m_TotalSize]; for (unsigned int i = 0; i < ImageDimension; ++i) { this->m_ComplexBuffer[i] = new typename FFTWProxyType::ComplexType[this->m_TotalComplexSize]; } // Create the plans for the FFT for (unsigned int i = 0; i < ImageDimension; ++i) { this->m_PlanForward[i] = FFTWProxyType::Plan_dft_r2c( ImageDimension, n, this->m_InputBuffer, this->m_ComplexBuffer[i], FFTW_MEASURE, this->GetNumberOfWorkUnits()); this->m_PlanBackward[i] = FFTWProxyType::Plan_dft_c2r( ImageDimension, n, this->m_ComplexBuffer[i], this->m_OutputBuffer, FFTW_MEASURE, this->GetNumberOfWorkUnits()); } // delete n delete[] n; return true; } /** * Initialize elastic matrix */ template <typename TDisplacementField> bool VariationalRegistrationElasticRegularizer<TDisplacementField>::InitializeElasticMatrix() { itkDebugMacro(<< "Initializing elastic matrix for FFT..."); // Calculate cosine and sine values for faster calculation double a = 0.0; for (unsigned int i = 0; i < ImageDimension; ++i) { this->m_MatrixCos[i] = new double[this->m_ComplexSize[i]]; this->m_MatrixSin[i] = new double[this->m_ComplexSize[i]]; for (unsigned int n = 0; n < this->m_ComplexSize[i]; n++) { a = (2.0 * itk::Math::pi * n) / static_cast<double>(this->m_Size[i]); this->m_MatrixCos[i][n] = 2.0 * std::cos(a); this->m_MatrixSin[i][n] = std::sin(a); } } return true; } /** * Execute regularization */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::Regularize() { DisplacementFieldConstPointer inputField = this->GetInput(); if (!inputField) { itkExceptionMacro(<< "input displacement field is NULL!"); return; } // Perform Forward FFT for input field itkDebugMacro(<< "Performing Forward FFT..."); using ConstIteratorType = ImageRegionConstIterator<DisplacementFieldType>; ConstIteratorType inputIt(inputField, inputField->GetRequestedRegion()); unsigned int n; // Counter for field copying for (unsigned int i = 0; i < ImageDimension; ++i) { // Copy vector component into input buffer for FFT for (n = 0, inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++n, ++inputIt) { m_InputBuffer[n] = inputIt.Get()[i]; } // Execute FFT for component FFTWProxyType::Execute(this->m_PlanForward[i]); } // Solve the LES in Fourier domain itkDebugMacro(<< "Solving Elastic LES..."); this->SolveElasticLES(); // Perform Backward FFT for the result in the complex domain itkDebugMacro(<< "Performing Backward FFT..."); DisplacementFieldPointer outField = this->GetOutput(); using IteratorType = ImageRegionIterator<DisplacementFieldType>; IteratorType outIt(outField, outField->GetRequestedRegion()); for (unsigned int i = 0; i < ImageDimension; ++i) { // Execute FFT for component FFTWProxyType::Execute(this->m_PlanBackward[i]); // Copy complex buffer for component to component of field for (n = 0, outIt.GoToBegin(); !outIt.IsAtEnd(); ++n, ++outIt) { PixelType vec = outIt.Get(); vec[i] = m_OutputBuffer[n] / static_cast<double>(this->m_TotalSize); outIt.Set(vec); } } outField->Modified(); } /** * Solve elastic LES */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::SolveElasticLES() { // Declare thread data struct and set filter ElasticFFTThreadStruct elasticLESStr; elasticLESStr.Filter = this; elasticLESStr.totalComplexSize = this->m_TotalComplexSize; // Setup MultiThreader this->GetMultiThreader()->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits()); this->GetMultiThreader()->SetSingleMethod(this->SolveElasticLESThreaderCallback, &elasticLESStr); // Execute MultiThreader this->GetMultiThreader()->SingleMethodExecute(); } /** * Solve elastic LES */ template <typename TDisplacementField> ITK_THREAD_RETURN_TYPE VariationalRegistrationElasticRegularizer<TDisplacementField>::SolveElasticLESThreaderCallback(void * arg) { // Get MultiThreader struct auto * threadStruct = (MultiThreaderBase::WorkUnitInfo *)arg; int threadId = threadStruct->WorkUnitID; int threadCount = threadStruct->NumberOfWorkUnits; // Calculate region for current thread auto * userStruct = (ElasticFFTThreadStruct *)threadStruct->UserData; // Calculate the range in the m_ComplexBuffer of the thread OffsetValueType threadRange = userStruct->totalComplexSize / threadCount; OffsetValueType from = threadId * threadRange; OffsetValueType to = (threadId == threadCount - 1) ? userStruct->totalComplexSize : (threadId + 1) * threadRange; // Solve LES for thread userStruct->Filter->ThreadedSolveElasticLES(from, to); return ITK_THREAD_RETURN_DEFAULT_VALUE; } /** * Solve elastic LES */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::ThreadedSolveElasticLES(OffsetValueType from, OffsetValueType to) { // Only implemented for Imagedimension 2 and 3 - throw exception otherwise if (ImageDimension == 3) { // Get parameters from struct const double * Cosj = m_MatrixCos[0]; const double * Cosk = m_MatrixCos[1]; const double * Cosl = m_MatrixCos[2]; const double * Sinj = m_MatrixSin[0]; const double * Sink = m_MatrixSin[1]; const double * Sinl = m_MatrixSin[2]; const double m2lp4m = -2 * (m_Lambda + 4 * m_Mu); const double lp2m = m_Lambda + 2 * m_Mu; const double lpm = m_Lambda + m_Mu; double fftInX[2]; double fftInY[2]; double fftInZ[2]; double detD; double d11, d12, d13, d22, d23, d33; double invD11, invD12, invD13, invD22, invD23, invD33; const double mu_hx2 = m_Mu / itk::Math::sqr(m_Spacing[0]); const double mu_hy2 = m_Mu / itk::Math::sqr(m_Spacing[1]); const double mu_hz2 = m_Mu / itk::Math::sqr(m_Spacing[2]); const double lambdaPlus2mu_hx2 = (m_Lambda + 2 * m_Mu) / itk::Math::sqr(m_Spacing[0]); const double lambdaPlus2mu_hy2 = (m_Lambda + 2 * m_Mu) / itk::Math::sqr(m_Spacing[1]); const double lambdaPlus2mu_hz2 = (m_Lambda + 2 * m_Mu) / itk::Math::sqr(m_Spacing[2]); const double lambdaPlusmu_hxhy = (m_Lambda + m_Mu) / (m_Spacing[0] * m_Spacing[1]); const double lambdaPlusmu_hxhz = (m_Lambda + m_Mu) / (m_Spacing[0] * m_Spacing[2]); const double lambdaPlusmu_hyhz = (m_Lambda + m_Mu) / (m_Spacing[1] * m_Spacing[2]); ValueType meanSquaredSpacing = 0.0; for (unsigned int i = 0; i < ImageDimension; ++i) { meanSquaredSpacing += itk::Math::sqr(m_Spacing[i]); } meanSquaredSpacing /= 3.0; // Iterate over each pixel in thread range for (OffsetValueType i = from; i < to; ++i) { // Get image index according to offset typename DisplacementFieldType::IndexType index = this->CalculateComplexImageIndex(i); // Save values of forward FFT X,Y,Z for this pixel // to be able to overwrite the array fftInX[0] = m_ComplexBuffer[0][i][0]; fftInX[1] = m_ComplexBuffer[0][i][1]; fftInY[0] = m_ComplexBuffer[1][i][0]; fftInY[1] = m_ComplexBuffer[1][i][1]; fftInZ[0] = m_ComplexBuffer[2][i][0]; fftInZ[1] = m_ComplexBuffer[2][i][1]; // Calculate the matrix values for current pixel position using the // precomputed sine and cosine values. if (this->GetUseImageSpacing()) { // Calculate matrix M d11 = -2 * (lambdaPlus2mu_hx2 + mu_hy2 + mu_hz2) + lambdaPlus2mu_hx2 * Cosj[index[0]] + mu_hy2 * Cosk[index[1]] + mu_hz2 * Cosl[index[2]]; d12 = -lambdaPlusmu_hxhy * Sinj[index[0]] * Sink[index[1]]; d13 = -lambdaPlusmu_hxhz * Sinj[index[0]] * Sinl[index[2]]; d22 = -2 * (lambdaPlus2mu_hy2 + mu_hx2 + mu_hz2) + lambdaPlus2mu_hy2 * Cosk[index[1]] + mu_hx2 * Cosj[index[0]] + mu_hz2 * Cosl[index[2]]; d23 = -lambdaPlusmu_hyhz * Sink[index[1]] * Sinl[index[2]]; d33 = -2 * (lambdaPlus2mu_hz2 + mu_hx2 + mu_hy2) + lambdaPlus2mu_hz2 * Cosl[index[2]] + mu_hx2 * Cosj[index[0]] + mu_hy2 * Cosk[index[1]]; // Calculate Id - h^2 * M. d11 = 1 - meanSquaredSpacing * d11; d12 = -meanSquaredSpacing * d12; d13 = -meanSquaredSpacing * d13; d22 = 1 - meanSquaredSpacing * d22; d23 = -meanSquaredSpacing * d23; d33 = 1 - meanSquaredSpacing * d33; } else { // Calculate Id - h^2 * M. d11 = 1 - m2lp4m - lp2m * Cosj[index[0]] - m_Mu * (Cosk[index[1]] + Cosl[index[2]]); d12 = lpm * Sinj[index[0]] * Sink[index[1]]; d13 = lpm * Sinj[index[0]] * Sinl[index[2]]; d22 = 1 - m2lp4m - lp2m * Cosk[index[1]] - m_Mu * (Cosj[index[0]] + Cosl[index[2]]); d23 = lpm * Sink[index[1]] * Sinl[index[2]]; d33 = 1 - m2lp4m - lp2m * Cosl[index[2]] - m_Mu * (Cosj[index[0]] + Cosk[index[1]]); } // Calculate determinant detD = d11 * d22 * d33 - d11 * d23 * d23 - d12 * d12 * d33 + d12 * d13 * d23 + d12 * d13 * d23 - d13 * d13 * d22; // Calculate the inverse values if (fabs(detD) < 1e-15) { // If determinant is (close to) zero, inverse is zero m_ComplexBuffer[0][i][0] = 0; m_ComplexBuffer[0][i][1] = 0; m_ComplexBuffer[1][i][0] = 0; m_ComplexBuffer[1][i][1] = 0; m_ComplexBuffer[2][i][0] = 0; m_ComplexBuffer[2][i][1] = 0; } else { // Calculate inverse of the 3x3 matrix invD11 = (d22 * d33 - d23 * d23) / detD; invD12 = (d13 * d23 - d12 * d33) / detD; invD13 = (d12 * d23 - d13 * d22) / detD; invD22 = (d11 * d33 - d13 * d13) / detD; invD23 = (d12 * d13 - d11 * d23) / detD; invD33 = (d11 * d22 - d12 * d12) / detD; // Calculate du1 = invD11.*fft3(in1) + invD12.*fft3(in2) + invD13.*fft3(in3) m_ComplexBuffer[0][i][0] = invD11 * fftInX[0] + invD12 * fftInY[0] + invD13 * fftInZ[0]; m_ComplexBuffer[0][i][1] = invD11 * fftInX[1] + invD12 * fftInY[1] + invD13 * fftInZ[1]; // Calculate du2 = invD12.*fft3(in1) + invD22.*fft3(in2) + invD23.*fft3(in3) m_ComplexBuffer[1][i][0] = invD12 * fftInX[0] + invD22 * fftInY[0] + invD23 * fftInZ[0]; m_ComplexBuffer[1][i][1] = invD12 * fftInX[1] + invD22 * fftInY[1] + invD23 * fftInZ[1]; // Calculate du3 = invD13.*fft3(in1) + invD23.*fft3(in2) + invD33.*fft3(in3) m_ComplexBuffer[2][i][0] = invD13 * fftInX[0] + invD23 * fftInY[0] + invD33 * fftInZ[0]; m_ComplexBuffer[2][i][1] = invD13 * fftInX[1] + invD23 * fftInY[1] + invD33 * fftInZ[1]; } } } else if (ImageDimension == 2) { // Get parameters from struct const double * Cosj = m_MatrixCos[0]; const double * Cosk = m_MatrixCos[1]; const double * Sinj = m_MatrixSin[0]; const double * Sink = m_MatrixSin[1]; const double m2lp3m = -2 * (m_Lambda + 3 * m_Mu); const double lp2m = m_Lambda + 2 * m_Mu; const double lpm = m_Lambda + m_Mu; double fftInX[2]; double fftInY[2]; double detD; double d11, d12, d22; double invD11, invD12, invD22; const double mu_hx2 = m_Mu / itk::Math::sqr(m_Spacing[0]); const double mu_hy2 = m_Mu / itk::Math::sqr(m_Spacing[1]); const double lambdaPlus2mu_hx2 = (m_Lambda + 2 * m_Mu) / itk::Math::sqr(m_Spacing[0]); const double lambdaPlus2mu_hy2 = (m_Lambda + 2 * m_Mu) / itk::Math::sqr(m_Spacing[1]); const double lambdaPlusmu_hxhy = (m_Lambda + m_Mu) / (m_Spacing[0] * m_Spacing[1]); ValueType meanSquaredSpacing = 0.0; for (unsigned int i = 0; i < ImageDimension; ++i) { meanSquaredSpacing += itk::Math::sqr(m_Spacing[i]); } meanSquaredSpacing /= ImageDimension; // Iterate over each pixel in thread range for (OffsetValueType i = from; i < to; ++i) { // Get image index according to offset typename DisplacementFieldType::IndexType index = this->CalculateComplexImageIndex(i); // Save values of forward FFT X,Y for this pixel // to be able to overwrite the array fftInX[0] = m_ComplexBuffer[0][i][0]; fftInX[1] = m_ComplexBuffer[0][i][1]; fftInY[0] = m_ComplexBuffer[1][i][0]; fftInY[1] = m_ComplexBuffer[1][i][1]; // Calculate the matrix values for current pixel position using the // precomputed sine and cosine values. if (this->GetUseImageSpacing()) { // Calculate matrix M d11 = -2 * (lambdaPlus2mu_hx2 + mu_hy2) + lambdaPlus2mu_hx2 * Cosj[index[0]] + mu_hy2 * Cosk[index[1]]; d12 = -lambdaPlusmu_hxhy * Sinj[index[0]] * Sink[index[1]]; d22 = -2 * (lambdaPlus2mu_hy2 + mu_hx2) + lambdaPlus2mu_hy2 * Cosk[index[1]] + mu_hx2 * Cosj[index[0]]; // Calculate Id - h^2 * M. d11 = 1 - meanSquaredSpacing * d11; d12 = -meanSquaredSpacing * d12; d22 = 1 - meanSquaredSpacing * d22; } else { // Calculate Id - M. d11 = 1 - m2lp3m - lp2m * Cosj[index[0]] - m_Mu * (Cosk[index[1]]); d12 = lpm * Sinj[index[0]] * Sink[index[1]]; d22 = 1 - m2lp3m - lp2m * Cosk[index[1]] - m_Mu * (Cosj[index[0]]); } // Calculate determinant detD = d11 * d22 - d12 * d12; // Calculate the inverse values if (fabs(detD) < 1e-15) { // If determinant is (close to) zero, inverse is zero m_ComplexBuffer[0][i][0] = 0; m_ComplexBuffer[0][i][1] = 0; m_ComplexBuffer[1][i][0] = 0; m_ComplexBuffer[1][i][1] = 0; } else { // Calculate inverse of the 2x2 matrix invD11 = d22 / detD; invD12 = -d12 / detD; invD22 = d11 / detD; // Calculate du1 = invD11.*fft2(in1) + invD12.*fft2(in2) m_ComplexBuffer[0][i][0] = invD11 * fftInX[0] + invD12 * fftInY[0]; m_ComplexBuffer[0][i][1] = invD11 * fftInX[1] + invD12 * fftInY[1]; // Calculate du2 = invD12.*fft2(in1) + invD22.*fft2(in2) m_ComplexBuffer[1][i][0] = invD12 * fftInX[0] + invD22 * fftInY[0]; m_ComplexBuffer[1][i][1] = invD12 * fftInX[1] + invD22 * fftInY[1]; } } } else { itkExceptionMacro(<< "Elastic regularizer implemented only for ImageDimension = 2 or 3!"); } } /* * Calculate the index in the complex image for a given offset. */ template <typename TDisplacementField> typename VariationalRegistrationElasticRegularizer<TDisplacementField>::DisplacementFieldType::IndexType VariationalRegistrationElasticRegularizer<TDisplacementField>::CalculateComplexImageIndex(OffsetValueType offset) { typename DisplacementFieldType::IndexType index; typename DisplacementFieldType::IndexType requestedRegionIndex = this->GetOutput()->GetRequestedRegion().GetIndex(); for (int j = ImageDimension - 1; j > 0; j--) { index[j] = static_cast<typename DisplacementFieldType::IndexValueType>(offset / this->m_ComplexOffsetTable[j]); offset -= (index[j] * this->m_ComplexOffsetTable[j]); index[j] += requestedRegionIndex[j]; } index[0] = requestedRegionIndex[0] + static_cast<typename DisplacementFieldType::IndexValueType>(offset); return index; } /* * Print status information */ template <typename TDisplacementField> void VariationalRegistrationElasticRegularizer<TDisplacementField>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Size: "; os << m_Size << std::endl; os << indent << "Spacing: "; os << m_Spacing << std::endl; } } // end namespace itk #endif #endif
33.590764
119
0.647736
[ "vector" ]
5c88943deb4512df1a0ab3fa528db7d7f7573bde
2,404
cpp
C++
src/VISParser.cpp
Open-Source-Autonomous-Boat/Vessel-Instruction-Set-Interpreter
b06ae3aca657f844bc3e0e42957d7f1b6c7b66f5
[ "MIT" ]
null
null
null
src/VISParser.cpp
Open-Source-Autonomous-Boat/Vessel-Instruction-Set-Interpreter
b06ae3aca657f844bc3e0e42957d7f1b6c7b66f5
[ "MIT" ]
null
null
null
src/VISParser.cpp
Open-Source-Autonomous-Boat/Vessel-Instruction-Set-Interpreter
b06ae3aca657f844bc3e0e42957d7f1b6c7b66f5
[ "MIT" ]
null
null
null
#include "VISParser.h" #ifndef UNICODE #define UNICODE #endif #ifdef __cplusplus VISParser::VISParser(){}; VISParser::~VISParser() {} void VISParser::OpenFile(VISFile *a_file) { // Opens file with ifstream this->m_file = a_file; // Strips unneeded characters and seperates lines into vector entries this->PrepareFile(); // Parse file this->Parse(); return; } void VISParser::ParseLine(std::string a_line) { // Init vector of tokens std::vector<std::string> tokens; if (a_line.rfind("#", 0) == 0) { // Stops if comment return; } tokens = string_utils::split_string(a_line, ';'); for (auto &i : tokens) { string_utils::strip_string(&i, ' '); } this->Parse(); return; } /* Closes file */ void VISParser::CloseFile() { this->m_file = nullptr; } /* Prepare file for parsing */ void VISParser::PrepareFile() { // Init vector of lines std::vector<std::string> lines; // Init empty "line" string std::string line; // For each line in file... for (std::string tmp; std::getline(*this->m_file->GetFileObject(), tmp);) { if (tmp.rfind("#", 0) == 0) { // Strip comments out continue; } // Concancate into string line += tmp; } // Split string by semi-colon (;) lines = string_utils::split_string(line, ';'); for (auto &i : lines) { // For each line in file... // Strip whitespace string_utils::strip_string(&i, ' '); } // Set class property (lines) with local vector (tokens) this->m_lines = lines; } /* Parse file */ void VISParser::Parse() { // WIP for (auto &i : this->m_lines) { visl_cpp::tokens_type line_tokens; auto local_tokens = string_utils::split_string(i, ','); auto instruction = this->DetermineTypeFromLine(i); if (instruction == visl_tokens::visl_emp) { continue; } // token_utils::map_insert(this->m_tokens, instruction, ""); this->m_tokens.insert(std::pair<visl_tokens, std::string>(instruction, "")); for (const auto &pair : this->m_tokens) { std::cout << string_utils::token_stringify(instruction) << " - " << pair.second; } // Test } } visl_tokens VISParser::DetermineTypeFromLine(std::string a_line) { auto def_flags = std::regex_constants::icase | std::regex_constants::grep; if (string_utils::regex_find(a_line, "H1", def_flags)) { return visl_tokens::visl_h1; }; return visl_tokens::visl_emp; } #endif
26.711111
80
0.644343
[ "vector" ]
5c89a75126f769ff779098ccc7695fdbe894b916
13,041
cpp
C++
src/main.cpp
nickerso/opencor
63e164c6424dc855a4e46b835a777f6f84c617dc
[ "Apache-2.0" ]
null
null
null
src/main.cpp
nickerso/opencor
63e164c6424dc855a4e46b835a777f6f84c617dc
[ "Apache-2.0" ]
null
null
null
src/main.cpp
nickerso/opencor
63e164c6424dc855a4e46b835a777f6f84c617dc
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you 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. *******************************************************************************/ //============================================================================== // Main //============================================================================== #include "checkforupdateswindow.h" #include "cliutils.h" #include "coresettings.h" #include "guiutils.h" #include "mainwindow.h" #include "settings.h" #include "splashscreenwindow.h" //============================================================================== #include <QDir> #include <QLocale> #include <QProcess> #include <QSettings> #include <QVariant> #ifdef Q_OS_WIN #include <QWebSettings> #endif //============================================================================== #include <QtSingleApplication> //============================================================================== int main(int pArgC, char *pArgV[]) { // Initialise Qt's message pattern OpenCOR::initQtMessagePattern(); // Determine whether we should try the CLI version of OpenCOR: // - Windows: we never try the CLI version of OpenCOR. We go straight for // its GUI version. // - Linux: we always try the CLI version of OpenCOR and then go for its // GUI version, if needed. // - OS X: we try the CLI version of OpenCOR unless the user double clicks // on the OpenCOR bundle or opens it from the command line by // entering something like: // open OpenCOR.app // in which case we go for its GUI version. // Note #1: on Windows, we have two binaries (.com and .exe that are for the // CLI and GUI versions of OpenCOR, respectively). This means that // when a console window is open, to enter something like: // C:\>OpenCOR // will effectively call OpenCOR.com. From there, should there be // no argument that requires CLI treatment, then the GUI version of // OpenCOR will be run. This is, unfortunately, the only way to // have OpenCOR to behave as both a CLI and a GUI application on // Windows, hence the [OpenCOR]/windows/main.cpp file, which is // used to generate the CLI version of OpenCOR... // Note #2: on OS X, if we were to try to open the OpenCOR bundle from the // command line, then we would get an error message similar to: // LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app. // Fortunately, when double clicking on the OpenCOR bundle or // opening it from the command line, a special argument in the form // of -psn_0_1234567 is passed to OpenCOR, so we can use that to // determine whether we need to force OpenCOR to be run in GUI mode // or whether we first try the CLI version of OpenCOR, and then its // GUI version, if needed... #if defined(Q_OS_WIN) bool tryCliVersion = false; #elif defined(Q_OS_LINUX) bool tryCliVersion = true; #elif defined(Q_OS_MAC) bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5); #else #error Unsupported platform #endif // Run the CLI version of OpenCOR, if possible/needed if (tryCliVersion) { // Initialise the plugins path OpenCOR::initPluginsPath(pArgV[0]); // Create and initialise the CLI version of OpenCOR QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV); OpenCOR::initApplication(cliApp); // Try to run the CLI version of OpenCOR int res; bool runCliApplication = OpenCOR::cliApplication(cliApp, &res); OpenCOR::removeGlobalInstances(); delete cliApp; if (runCliApplication) // OpenCOR was run as a CLI application, so leave return res; // Note: at this stage, we tried the CLI version of OpenCOR, but in the // end we need to go for its GUI version, so start over but with // the GUI version of OpenCOR this time... } // Make sure that we always use indirect rendering on Linux // Note: indeed, depending on which plugins are selected, OpenCOR may need // LLVM. If that's the case, and in case the user's video card uses a // driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there // may be a conflict between the version of LLVM used by OpenCOR and // the one used by the video card. One way to address this issue is by // using indirect rendering... #ifdef Q_OS_LINUX qputenv("LIBGL_ALWAYS_INDIRECT", "1"); #endif // Initialise the plugins path OpenCOR::initPluginsPath(pArgV[0]); // Create the GUI version of OpenCOR SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); // Send a message (containing the arguments that were passed to this // instance of OpenCOR minus the first one since it corresponds to the full // path to our executable, which we are not interested in) to our 'official' // instance of OpenCOR, should there be one. If there is none, then just // carry on as normal, otherwise exit since we want only one instance of // OpenCOR at any given time QStringList appArguments = guiApp->arguments(); appArguments.removeFirst(); QString arguments = appArguments.join("|"); if (guiApp->isRunning()) { guiApp->sendMessage(arguments); delete guiApp; return 0; } // Initialise the GUI version of OpenCOR QString appDate = QString(); OpenCOR::initApplication(guiApp, &appDate); // Check whether we want to check for new versions at startup QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication); #ifndef QT_DEBUG settings.beginGroup("CheckForUpdatesWindow"); bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool(); bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool(); settings.endGroup(); #endif // Check whether a new version of OpenCOR is available #ifndef QT_DEBUG if (checkForUpdatesAtStartup) { OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate); checkForUpdatesEngine->check(); if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion()) || (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) { // Retrieve the language to be used to show the check for updates // window const QString systemLocale = QLocale::system().name().left(2); QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString(); if (locale.isEmpty()) locale = systemLocale; QLocale::setDefault(QLocale(locale)); QTranslator qtTranslator; QTranslator appTranslator; qtTranslator.load(":qt_"+locale); qApp->installTranslator(&qtTranslator); appTranslator.load(":app_"+locale); qApp->installTranslator(&appTranslator); // Show the check for updates window // Note: checkForUpdatesEngine gets deleted by // checkForUpdatesWindow... OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine); settings.beginGroup(checkForUpdatesWindow.objectName()); checkForUpdatesWindow.loadSettings(&settings); settings.endGroup(); checkForUpdatesWindow.exec(); settings.beginGroup(checkForUpdatesWindow.objectName()); checkForUpdatesWindow.saveSettings(&settings); settings.endGroup(); } else { delete checkForUpdatesEngine; } } #endif // Initialise our colours by 'updating' them OpenCOR::updateColors(); // Create and show our splash screen, if we are not in debug mode #ifndef QT_DEBUG OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow(); splashScreen->show(); #endif // Create our main window OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate); // Keep track of our main window (required by QtSingleApplication so that it // can do what it's supposed to be doing) guiApp->setActivationWindow(win); // Handle our arguments win->handleArguments(arguments); // Show our main window win->show(); // By default, we can and should execute our application bool canExecuteAplication = true; // Close and delete our splash screen once our main window is visible, if we // are not in debug mode #ifndef QT_DEBUG splashScreen->closeAndDeleteAfter(win); // Make sure that our main window is in the foreground, unless the user // decided to close our main window while we were showing our splash screen // Note: indeed, on Linux, to show our splash screen may result in our main // window being shown in the background... if (!win->shuttingDown()) win->showSelf(); else canExecuteAplication = false; #endif // Execute our application, if possible int res; if (canExecuteAplication) res = guiApp->exec(); else res = 0; // Keep track of our application file and directory paths (in case we need // to restart OpenCOR) QString appFilePath = guiApp->applicationFilePath(); QString appDirPath = guiApp->applicationDirPath(); // Delete our main window delete win; // We use QtWebKit, and QWebPage in particular, which results in some leak // messages being generated on Windows when leaving OpenCOR. This is because // an object cache is shared between all QWebPage instances. So to destroy a // QWebPage instance doesn't clear the cache, hence the leak messages. // However, those messages are 'only' warnings, so we can safely live with // them. Still, it doesn't look 'good', so we clear the memory caches, thus // avoiding those leak messages... // Note: the below must absolutely be done after calling guiApp->exec() and // before deleting guiApp... #ifdef Q_OS_WIN QWebSettings::clearMemoryCaches(); #endif // Remove all 'global' instances that were created and used during this // session OpenCOR::removeGlobalInstances(); // Delete our application delete guiApp; // We are done with the execution of our application, so now the question is // whether we need to restart // Note: we do this here rather than 'within' the GUI because once we have // launched a new instance of OpenCOR, we want this instance of // OpenCOR to finish as soon as possible, which will be the case here // since all that remains to be done is to return the result of the // execution of our application... if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) { // We want to restart, so the question is whether we want a normal // restart or a clean one if (res == OpenCOR::CleanRestart) // We want a clean restart, so clear all the user settings (indeed, // this will ensure that the various windows are, for instance, // properly reset with regards to their dimensions) settings.clear(); // Restart OpenCOR, but without providing any of the arguments that were // originally passed to us since we want to reset everything QProcess::startDetached(appFilePath, QStringList(), appDirPath); } // We are done running the GUI version of OpenCOR, so leave return res; } //============================================================================== // End of file //==============================================================================
35.92562
115
0.624262
[ "object", "3d" ]
5c917c725994e6950039417962df7f65178de207
217
cpp
C++
Sudoku-cpp/main.cpp
Kmalechkanov/sudoku-cpp
93d5c99706228b9f48377f6780d742db5c8f4aed
[ "MIT" ]
1
2020-06-03T09:10:10.000Z
2020-06-03T09:10:10.000Z
Sudoku-cpp/main.cpp
Kmalechkanov/sudoku-cpp
93d5c99706228b9f48377f6780d742db5c8f4aed
[ "MIT" ]
null
null
null
Sudoku-cpp/main.cpp
Kmalechkanov/sudoku-cpp
93d5c99706228b9f48377f6780d742db5c8f4aed
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <string> #include "generator.h" #include "manager.h" #include "globalconstants.h" #include "menu.h" int main() { Menu menu; menu.Main(); }
13.5625
28
0.677419
[ "vector" ]
5c93df3c000298c0432b9a1e190fc0e44b137401
2,950
cpp
C++
src/wm_navigation/wm_fake_localization_node.cpp
fmrico/WaterMellon
5d61914d9597118735e933e6d61a7e7872d83f5a
[ "BSD-3-Clause" ]
1
2017-02-23T02:05:57.000Z
2017-02-23T02:05:57.000Z
src/wm_navigation/wm_fake_localization_node.cpp
fmrico/WaterMellon
5d61914d9597118735e933e6d61a7e7872d83f5a
[ "BSD-3-Clause" ]
null
null
null
src/wm_navigation/wm_fake_localization_node.cpp
fmrico/WaterMellon
5d61914d9597118735e933e6d61a7e7872d83f5a
[ "BSD-3-Clause" ]
null
null
null
/* * mapper_node.cpp * * Created on: 22/08/2015 * Author: paco */ #include "ros/ros.h" #include <string> #include "ros/ros.h" #include "gazebo_msgs/ModelStates.h" #include "geometry_msgs/PoseWithCovariance.h" #include "geometry_msgs/PoseWithCovarianceStamped.h" #include "geometry_msgs/Pose.h" #include "tf/transform_listener.h" #include "tf/transform_broadcaster.h" #include <iostream> #include <math.h> namespace wm_localization { class WmFakeLocalization { public: WmFakeLocalization() { posecov_pub = m_nh.advertise<geometry_msgs::PoseWithCovarianceStamped>("/wm_pose_cov", 1, true); pose_pub = m_nh.advertise<geometry_msgs::PoseStamped>("/wm_pose", 1, true); submodel = m_nh.subscribe("/gazebo/model_states", 1000, &WmFakeLocalization::groundtruthCB, this); } void step() { if(posecov_pub.getNumSubscribers() > 0) { geometry_msgs::PoseWithCovarianceStamped pose2send; pose2send.header.frame_id = "/map"; pose2send.header.stamp = ros::Time::now(); pose2send.pose = posecv; posecov_pub.publish(pose2send); } if(pose_pub.getNumSubscribers() > 0) { geometry_msgs::PoseStamped pose2send; pose2send.header.frame_id = "/map"; pose2send.header.stamp = ros::Time::now(); pose2send.pose = posecv.pose; pose_pub.publish(pose2send); } } void groundtruthCB(const gazebo_msgs::ModelStates::ConstPtr& states) { ROS_DEBUG("groundtruthCB Called"); geometry_msgs::Pose gt; for(int i=0; i< states->name.size(); i++) { //ROS_DEBUG("[%s]", states->name[i].c_str()); if(states->name[i].find("robot")!=std::string::npos) gt = states->pose[i]; } ////////////////////////////////////////////////////////// tf::Transform G2M; geometry_msgs::Transform gt_res; G2M.setOrigin(tf::Vector3(0.0f, 0.0f, 0.0f)); tf::Quaternion q; q.setEuler(0.0, 0.0, M_PI); G2M.setRotation(q); tf::Transform tf_gt; tf::poseMsgToTF(gt, tf_gt); tf_gt = G2M*tf_gt ; tf::transformTFToMsg(tf_gt, gt_res); gt.position.x = gt_res.translation.x; gt.position.y = gt_res.translation.y; gt.position.z = gt_res.translation.z; gt.orientation = gt_res.rotation; /////////////////////////////////////////////////////////// posecv.pose = gt; posecv.covariance[0] = 0.01; posecv.covariance[1 * 6 + 1] =0.01; posecv.covariance[5 * 6 + 5] = 0.01; } private: ros::Publisher posecov_pub; ros::Publisher pose_pub; ros::Subscriber submodel; ros::NodeHandle m_nh; geometry_msgs::PoseWithCovariance posecv; }; } int main(int argc, char **argv) { ros::init(argc, argv, std::string("wm_localization")); ros::NodeHandle n; ros::Rate loop_rate(5); wm_localization::WmFakeLocalization wmfakelocalization; try{ while ( ros::ok()) { wmfakelocalization.step(); ros::spinOnce(); loop_rate.sleep(); } }catch(std::runtime_error& e){ ROS_ERROR("wm_map_server exception: %s", e.what()); return -1; } return 0; }
21.851852
100
0.655254
[ "transform" ]
5c983dd2e90ea245ffbc4594f8657d07f6d0a74a
1,431
cpp
C++
src/graphics/Canvas.cpp
j0ntan/RayTracerChallenge
91e201b2d7f90032580101a1ccf18eb2d6e5b522
[ "Unlicense" ]
null
null
null
src/graphics/Canvas.cpp
j0ntan/RayTracerChallenge
91e201b2d7f90032580101a1ccf18eb2d6e5b522
[ "Unlicense" ]
null
null
null
src/graphics/Canvas.cpp
j0ntan/RayTracerChallenge
91e201b2d7f90032580101a1ccf18eb2d6e5b522
[ "Unlicense" ]
null
null
null
#include <cmath> #include <fstream> #include <graphics/Canvas.hpp> #include <string> Canvas::Canvas(size_t width, size_t height) : width{width}, height{height}, pixels{std::vector<std::vector<Color>>( height, std::vector<Color>(width, Color()))} {} Color Canvas::pixel(size_t x, size_t y) const { return pixels[y][x]; } void Canvas::write(size_t x, size_t y, const Color &color) { pixels[y][x] = color; } PPM Canvas::to_PPM(const MagicIdentifier &id) const { PPM ppm(width, height, id); for (size_t row = 0; row < height; ++row) for (size_t col = 0; col < width; ++col) ppm.write( row, col, Pixel{static_cast<size_t>(ppm.max_color * pixels[row][col].red()), static_cast<size_t>(ppm.max_color * pixels[row][col].green()), static_cast<size_t>(ppm.max_color * pixels[row][col].blue())}); return ppm; } void Canvas::write_PPM(const char *filename, const MagicIdentifier &id) const { const auto PPM = to_PPM(id); if (id == MagicIdentifier::ASCII) { std::ofstream output_file(std::string(filename) + ".ppm"); output_file << std::string(PPM); } else { std::ofstream output_file(std::string(filename) + ".ppm", std::ios_base::binary); for (const auto &BYTE : PPM.bytes()) output_file.put(static_cast<char>(BYTE)); } }
33.27907
79
0.59399
[ "vector" ]
5c9aaaef929f0f8e5faab7ef0baca78f9e1e2a22
338
cpp
C++
1.9_functions_and_recurs/1.9.4_two_points_distance.cpp
yoshi42/simple_but_important_algorythms
301b529cea13c121579901ddeffaa062a49f4caf
[ "MIT" ]
null
null
null
1.9_functions_and_recurs/1.9.4_two_points_distance.cpp
yoshi42/simple_but_important_algorythms
301b529cea13c121579901ddeffaa062a49f4caf
[ "MIT" ]
null
null
null
1.9_functions_and_recurs/1.9.4_two_points_distance.cpp
yoshi42/simple_but_important_algorythms
301b529cea13c121579901ddeffaa062a49f4caf
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include <vector> #include <iomanip> using namespace std; double distance(double x1, double y1, double x2, double y2) { return sqrt(pow((x2-x1), 2) + pow((y2-y1), 2)); } int main() { double a, b, c, d; cin >> a >> b >> c >> d; cout << distance(a, b, c, d) << endl; return 0; }
16.9
59
0.573964
[ "vector" ]
5c9b84e6c370383266bce5f3b601a4a22f4af98c
498
hpp
C++
include/GroupEditOperation.hpp
jianjieluo/MineCube
e3da815740b0e7297dcf05b8748988ce70236308
[ "MIT" ]
12
2019-10-07T19:01:12.000Z
2022-03-29T18:12:22.000Z
include/GroupEditOperation.hpp
jianjieluo/MineCube
e3da815740b0e7297dcf05b8748988ce70236308
[ "MIT" ]
12
2018-06-27T04:33:55.000Z
2019-01-28T07:19:30.000Z
include/GroupEditOperation.hpp
longjj/MineCube
e3da815740b0e7297dcf05b8748988ce70236308
[ "MIT" ]
3
2018-07-16T17:24:49.000Z
2018-07-22T04:00:48.000Z
#ifndef GroupEditOperation_hpp #define GroupEditOperation_hpp #include "EditOperationInterface.hpp" #include <vector> #include <memory> using std::vector; using std::shared_ptr; class GroupEditOperation: public EditOperationInterface { private: vector<shared_ptr<EditOperationInterface>> ops; public: GroupEditOperation(const vector<shared_ptr<EditOperationInterface>> & ops); // override void excute(); // override void undo(); }; #endif
22.636364
83
0.710843
[ "vector" ]
5ca89ec59de0e755b2929a8849be867ca0f60ef0
4,563
cpp
C++
main.cpp
grantrostig/combinatorics
2be6f7a9e91d07b7eb97e5692b26a4fa183eb2ef
[ "MIT" ]
1
2019-04-05T01:38:12.000Z
2019-04-05T01:38:12.000Z
main.cpp
grantrostig/combinatorics
2be6f7a9e91d07b7eb97e5692b26a4fa183eb2ef
[ "MIT" ]
null
null
null
main.cpp
grantrostig/combinatorics
2be6f7a9e91d07b7eb97e5692b26a4fa183eb2ef
[ "MIT" ]
null
null
null
/* copyright (c) Grant Rostig 2018 MIT license */ #include "../../Dropbox/src/utils/cpp_headers.h" #include "../../Dropbox/src/utils/math_grostig.h" #include <algorithm> #include <cmath> #include <iostream> #include <iterator> #include <vector> using namespace std; // template <typename T> // utility f() to print vectors // std::ostream &operator<<(std::ostream &out, const std::vector<T> &v) { // if (!v.empty()) { // out << '['; // std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", ")); // out << "\b\b]"; // } // return out; //} // double n_Choose_k(unsigned long const n, // unsigned long k) // copy of k is mutated. //{ // if (k > n) // return 0; // if (k * 2 > n) // k = n - k; // if (k == 0) // return 1; // double result = n; // for (unsigned long i = 2; i <= k; ++i) { // result *= (n - i + 1); // result /= i; // } // return result; //} // double factorial(unsigned long const x, unsigned long const result = 1) { // if (x == 1) // return result; // else // return factorial(x - 1, x * result); //} // double m_subH_max(unsigned long const n_uc, unsigned long const vc_dim) { // double sum = 0; // for (unsigned long i = 0; i <= vc_dim; i++) { // sum += n_Choose_k(n_uc, i); // } // return sum; //} int main(/*int argc, char *argv[]*/) { // cout << "\n 50 choose 3 is: "<< nChoosek(50, 3); // cout << "\n factorial(20) : " << // factorial(20)/*/factorial(3)*factorial(50-3)*/; // unsigned long n = 480000; // cout << "\n std::pow(n,2): " << std::pow(n,2); double delta = 0.05; unsigned long vc_dim = 10; // cout << "\n m_subH_max, approx N^VCdim: " << m_subH_max(n,vc_dim) << ", // " << pow(n,vc_dim); // double result1 = // std::sqrt((8.0/n)*log(4.0*(m_subH_max(2.0*n,vc_dim)/delta))); auto generalization_error_est = [vc_dim, delta](double n) { double z = std::sqrt((8.0 / n) * log(4.0 * (pow(2.0 * n, vc_dim) / delta))); return z; }; auto generalization_error = [vc_dim, delta](double n) { double z = std::sqrt((8.0 / n) * log(4.0 * (m_subH_max(2 * n, vc_dim) / delta))); return z; }; std::vector<double> n_tests = {400'000, 420'000, 440'000, 460'000, 480'000}; std::vector<double> ge_est; // trick to easily create destination for results. // todo better way to do that using auto?? ge_est.reserve(n_tests.size()); // coded here just for reference, not needed // due to small size. Don't do this when // push_back is to be used unless you know // eventual size??? todo std::vector<double> ge; // trick to easily create destination for results. // todo better way to do that using auto?? // https://www.fluentcpp.com/2017/02/13/transform-central-algorithm/ std::transform(n_tests.begin(), n_tests.end(), std::back_inserter(ge_est), generalization_error_est); std::transform(n_tests.begin(), n_tests.end(), std::back_inserter(ge), generalization_error); cout << "\n ge_est: " << ge_est; cout << "\n ge : " << ge; // another way to approach above problem: // http://nbviewer.jupyter.org/github/tournami/Learning-From-Data-MOOC/blob/master/Homework%204.html unsigned long n = 10000; vc_dim = 50; double result1 = std::sqrt((8.0 / n) * log(4.0 * (pow(2.0 * n, vc_dim) / delta))); double result1a = std::sqrt((8.0 / n) * log(4.0 * (m_subH_max(2.0 * n, vc_dim) / delta))); double result2 = std::sqrt(2 * log(2 * n * (m_subH_max(n, vc_dim)) / n)) + sqrt((2 / n) * log(1 / delta)) + 1 / n; double result3 = ge_converge1(vc_dim, n, delta); double result4 = ge_converge2(vc_dim, n, delta); cout << "\n result 1, 1a, 2, 3, 4 : " << result1 << ", " << result1a << ", " << result2 << ", " << result3 << ", " << result4; n = 5; vc_dim = 50; result1 = std::sqrt((8.0 / n) * log(4.0 * (pow(2.0 * n, vc_dim) / delta))); result1a = std::sqrt((8.0 / n) * log(4.0 * (m_subH_max(2.0 * n, vc_dim) / delta))); result2 = std::sqrt(2 * log(2 * n * (m_subH_max(n, vc_dim)) / n)) + sqrt((2 / n) * log(1 / delta)) + 1 / n; result3 = ge_converge1(vc_dim, n, delta); result4 = ge_converge2(vc_dim, n, delta); cout << "\n result 1, 1a, 2, 3, 4 : " << result1 << ", " << result1a << ", " << result2 << ", " << result3 << ", " << result4; cout << "\n ###" << endl; return 0; }
32.827338
102
0.544817
[ "vector", "transform" ]
5cab489fc31d4e9d4879b5d0d20864faa5960422
4,352
cpp
C++
collisions/Superposer.cpp
iomonad/deny-toolkit
b91b3fc89f94c6fef174b9b4f43c2d26871a7e2f
[ "MIT" ]
1
2020-09-28T10:47:13.000Z
2020-09-28T10:47:13.000Z
collisions/Superposer.cpp
iomonad/deny-toolkit
b91b3fc89f94c6fef174b9b4f43c2d26871a7e2f
[ "MIT" ]
null
null
null
collisions/Superposer.cpp
iomonad/deny-toolkit
b91b3fc89f94c6fef174b9b4f43c2d26871a7e2f
[ "MIT" ]
null
null
null
// // (c) 2020 iomonad - <iomonad@riseup.net> // See: https://github.com/iomonad/deny-toolkit // #include <list> #include <fstream> #include <iostream> #include <opencv2/core/core.hpp> #include "opencv2/imgproc/imgproc.hpp" #include <opencv2/highgui/highgui.hpp> #include "Superposer.hpp" // Basic constructor, load files into // fstream. Superposer::Superposer(std::vector<std::string> fpaths) { for (const auto path: fpaths) { std::ifstream *s = new std::ifstream; s->open(path); if (!s->good()) { s->close(); for (const auto f: fsw) f->close(); throw std::runtime_error( "File " + path + " don't exists."); } // // This break object lifecycle, take // care of ressource acquisition. // fsw.push_back(s); std::cout << "[OK] Loaded " << path << "." << std::endl; } // CV Setup mat = cv::Mat(cv::Size(500, 500), CV_8UC3, cv::Scalar(0, 0, 0)); cv::namedWindow(SUPERP_WIN, cv::WINDOW_AUTOSIZE | cv::WINDOW_GUI_NORMAL); } Superposer::~Superposer() { for (auto f: fsw) { if (f->is_open()) { f->close(); } } } // // Unpack each ifstream ref into exploitable // key struct. // void Superposer::unpack_files(std::function<void(std::string)> failure, std::function<void()> success) { for (auto f: fsw) { struct KeyHeader header; std::vector<cv::Rect> levers; std::vector<cv::Point> bitting; // Header f->read((char*)&header, sizeof(struct KeyHeader)); if (header.MAGIC != 0xde57de57) { throw std::runtime_error("File is corruputed."); } // Levers for (size_t i = 0; i < 3; i++) { struct KeyLever l; f->read((char*)&l, sizeof(struct KeyLever)); levers.push_back(cv::Rect(l.x, l.y, l.width, l.height)); } // Key Body struct KeyBody entry; while (f->read((char*)&entry, sizeof(struct KeyBody))) { bitting.push_back(cv::Point(entry.x, entry.y)); } struct Key k = { .header = header, .levers = levers, .bitting = bitting }; keys.push_back(k); } return success(); } // // Ensure keys share same props // void Superposer::ensure_assoc(std::function<void(std::string)> failure, std::function<void()> success) { unsigned short comb_type = 0; for (const auto &k : keys) { if (!comb_type) continue; if (k.header.combinaison_type != comb_type) { throw std::runtime_error("All files should have same combinaison size"); } } std::cout << "[OK] Key correlation correct, generating collision" << std::endl; return success(); } static void draw_bitting(cv::Mat mat, std::vector<cv::Point> bitting, cv::Scalar color) { for (std::size_t i = 0; i < bitting.size(); ++i) { if ((i + 1) != bitting.size()) { cv::line(mat, bitting[i], bitting[i+1], color); } } } static void draw_levers(cv::Mat mat, std::vector<cv::Rect> levers, cv::Scalar color) { cv::Scalar lc = cv::Scalar(150, color[1], color[3]); for (std::size_t i = 0; i < levers.size(); ++i) { cv::rectangle(mat, levers.at(i), lc, 1); } } // // Display each combinaison with shared materializer and // unificated genese // void Superposer::process_layered_display(std::function<void(std::string)> failure, std::function<void()> success) { char k; // TODO: Find smarter way to handle colors std::vector<cv::Scalar> colors { cv::Scalar (47, 255, 173), cv::Scalar (0, 255, 255), cv::Scalar (255, 255, 0), cv::Scalar (60, 20, 220), cv::Scalar (203, 192, 255), // Maybe add more scheme ? }; for (size_t i = 0; i < keys.size(); i++) { // cv::Scalar color = // cv::Scalar(0x0, 255 - (i * 2), 0x0); draw_bitting(mat, keys[i].bitting, colors[i]); draw_levers(mat, keys[i].levers, colors[i]); } for (;;) { cv::imshow(SUPERP_WIN, mat); k = cv::waitKey(100); if (k == 0x20 || k == 'q') break; } return success(); } static void raise_exception(std::string what) { throw std::runtime_error(what); } void Superposer::compute(int flow) { static constexpr void (Superposer::*flow_func[]) (std::function<void(std::string)>, std::function<void()>) = { &Superposer::unpack_files, &Superposer::ensure_assoc, &Superposer::process_layered_display }; static constexpr int n_func = sizeof(flow_func) / sizeof(*flow_func); if (flow < n_func) { return (this->*flow_func[flow])(raise_exception, [=]() { return (this->compute(flow + 1)); }); } }
22.905263
82
0.624081
[ "object", "vector" ]
5cb3f5bfbcd382eea270de74e2e0aa902469f621
32,591
cpp
C++
src/Engine/Engine.cpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
127
2018-12-09T18:40:02.000Z
2022-03-06T00:10:07.000Z
src/Engine/Engine.cpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
267
2019-02-26T22:16:48.000Z
2022-02-09T09:49:22.000Z
src/Engine/Engine.cpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
17
2019-02-26T20:45:34.000Z
2021-06-17T15:06:26.000Z
#ifdef _WIN32 // for Windows you'll need this to have M_PI defined #define _USE_MATH_DEFINES #endif #include <cmath> #include <ctime> #include <cwchar> #include <filesystem> #include <iomanip> #include <memory> #include <set> #include <string> #include <unordered_set> #include <squirrel.h> #include <ngf/Application.h> #include <ngf/Graphics/Colors.h> #include <ngf/System/Mouse.h> #include <engge/Util/RandomNumberGenerator.hpp> #include <engge/EnggeApplication.hpp> #include <engge/Engine/Engine.hpp> #include <engge/Engine/ActorIcons.hpp> #include <engge/Engine/Camera.hpp> #include <engge/Engine/Cutscene.hpp> #include <engge/Engine/Hud.hpp> #include <engge/Input/InputConstants.hpp> #include <engge/Dialog/DialogManager.hpp> #include <engge/Engine/Inventory.hpp> #include <engge/Engine/Preferences.hpp> #include <engge/Room/Room.hpp> #include <engge/Room/RoomScaling.hpp> #include <engge/Scripting/ScriptEngine.hpp> #include <engge/Scripting/ScriptExecute.hpp> #include <engge/Engine/Sentence.hpp> #include <engge/Audio/SoundDefinition.hpp> #include <engge/Audio/SoundManager.hpp> #include <engge/Graphics/SpriteSheet.hpp> #include <engge/Engine/TextDatabase.hpp> #include <engge/Engine/Verb.hpp> #include <engge/Scripting/VerbExecute.hpp> #include <engge/System/Logger.hpp> #include <engge/Engine/InputStateConstants.hpp> #include "EngineImpl.hpp" namespace fs = std::filesystem; namespace ng { Engine::Engine() : m_pImpl(std::make_unique<Impl>()) { m_pImpl->m_pEngine = this; m_pImpl->m_soundManager.setEngine(this); m_pImpl->m_dialogManager.setEngine(this); m_pImpl->m_actorIcons.setEngine(this); m_pImpl->m_camera.setEngine(this); m_pImpl->m_talkingState.setEngine(this); // load all messages std::stringstream s; auto lang = m_pImpl->m_preferences.getUserPreference<std::string>(PreferenceNames::Language, PreferenceDefaultValues::Language); s << "ThimbleweedText_" << lang << ".tsv"; Locator<TextDatabase>::get().load(s.str()); m_pImpl->m_optionsDialog.setSaveEnabled(true); m_pImpl->m_optionsDialog.setEngine(this); m_pImpl->m_optionsDialog.setCallback([this]() { showOptions(false); }); m_pImpl->m_startScreenDialog.setEngine(this); m_pImpl->m_startScreenDialog.setNewGameCallback([this]() { m_pImpl->m_state = EngineState::Game; m_pImpl->exitRoom(nullptr); ScriptEngine::call("start", true); }); m_pImpl->m_startScreenDialog.setSlotCallback([this](int slot) { m_pImpl->m_state = EngineState::Game; loadGame(slot); }); m_pImpl->m_preferences.subscribe([this](const std::string &name) { if (name == PreferenceNames::Language) { auto newLang = m_pImpl->m_preferences.getUserPreference<std::string>(PreferenceNames::Language, PreferenceDefaultValues::Language); m_pImpl->onLanguageChange(newLang); } else if (name == PreferenceNames::Fullscreen) { auto fullscreen = m_pImpl->m_preferences.getUserPreference(PreferenceNames::Fullscreen, PreferenceDefaultValues::Fullscreen); m_pImpl->m_pApp->getWindow().setFullscreen(fullscreen); } }); } Engine::~Engine() = default; int Engine::getFrameCounter() const { return m_pImpl->m_frameCounter; } void Engine::setApplication(ng::EnggeApplication *app) { m_pImpl->m_pApp = app; } const ng::EnggeApplication *Engine::getApplication() const { return m_pImpl->m_pApp; } ng::EnggeApplication *Engine::getApplication() { return m_pImpl->m_pApp; } ResourceManager &Engine::getResourceManager() { return m_pImpl->m_resourceManager; } Room *Engine::getRoom() { return m_pImpl->m_pRoom; } std::wstring Engine::getText(int id) { auto text = Locator<TextDatabase>::get().getText(id); removeFirstParenthesis(text); return text; } std::wstring Engine::getText(const std::string &text) { auto text2 = Locator<TextDatabase>::get().getText(text); removeFirstParenthesis(text2); return text2; } void Engine::addActor(std::unique_ptr<Actor> actor) { m_pImpl->m_actors.push_back(std::move(actor)); } void Engine::addRoom(std::unique_ptr<Room> room) { m_pImpl->m_rooms.push_back(std::move(room)); } std::vector<std::unique_ptr<Room>> &Engine::getRooms() { return m_pImpl->m_rooms; } void Engine::addFunction(std::unique_ptr<Function> function) { m_pImpl->m_newFunctions.push_back(std::move(function)); } void Engine::addCallback(std::unique_ptr<Callback> callback) { m_pImpl->m_callbacks.push_back(std::move(callback)); } void Engine::removeCallback(int id) { auto it = std::find_if(m_pImpl->m_callbacks.begin(), m_pImpl->m_callbacks.end(), [id](auto &callback) -> bool { return callback->getId() == id; }); if (it != m_pImpl->m_callbacks.end()) { m_pImpl->m_callbacks.erase(it); } } std::vector<std::unique_ptr<Actor>> &Engine::getActors() { return m_pImpl->m_actors; } Actor *Engine::getCurrentActor() { return m_pImpl->m_pCurrentActor; } const VerbUiColors *Engine::getVerbUiColors(const std::string &name) const { if (name.empty()) { auto index = m_pImpl->getCurrentActorIndex(); if (index == -1) return nullptr; return &m_pImpl->m_hud.getVerbUiColors(index); } for (int i = 0; i < static_cast<int>(m_pImpl->m_actorsIconSlots.size()); i++) { const auto &selectableActor = m_pImpl->m_actorsIconSlots.at(i); if (selectableActor.pActor && selectableActor.pActor->getKey() == name) { return &m_pImpl->m_hud.getVerbUiColors(i); } } return nullptr; } bool Engine::getInputActive() const { return m_pImpl->m_inputActive; } void Engine::setInputState(int state) { if ((state & InputStateConstants::UI_INPUT_ON) == InputStateConstants::UI_INPUT_ON) { m_pImpl->m_inputActive = true; } if ((state & InputStateConstants::UI_INPUT_OFF) == InputStateConstants::UI_INPUT_OFF) { m_pImpl->m_inputActive = false; } if ((state & InputStateConstants::UI_VERBS_ON) == InputStateConstants::UI_VERBS_ON) { m_pImpl->m_inputVerbsActive = true; } if ((state & InputStateConstants::UI_VERBS_OFF) == InputStateConstants::UI_VERBS_OFF) { m_pImpl->m_inputVerbsActive = false; } if ((state & InputStateConstants::UI_CURSOR_ON) == InputStateConstants::UI_CURSOR_ON) { m_pImpl->m_showCursor = true; } if ((state & InputStateConstants::UI_CURSOR_OFF) == InputStateConstants::UI_CURSOR_OFF) { m_pImpl->m_showCursor = false; } if ((state & InputStateConstants::UI_HUDOBJECTS_ON) == InputStateConstants::UI_HUDOBJECTS_ON) { m_pImpl->m_inputHUD = true; } if ((state & InputStateConstants::UI_HUDOBJECTS_OFF) == InputStateConstants::UI_HUDOBJECTS_OFF) { m_pImpl->m_inputHUD = false; } } int Engine::getInputState() const { int inputState = 0; inputState |= (m_pImpl->m_inputActive ? InputStateConstants::UI_INPUT_ON : InputStateConstants::UI_INPUT_OFF); inputState |= (m_pImpl->m_inputVerbsActive ? InputStateConstants::UI_VERBS_ON : InputStateConstants::UI_VERBS_OFF); inputState |= (m_pImpl->m_showCursor ? InputStateConstants::UI_CURSOR_ON : InputStateConstants::UI_CURSOR_OFF); inputState |= (m_pImpl->m_inputHUD ? InputStateConstants::UI_HUDOBJECTS_ON : InputStateConstants::UI_HUDOBJECTS_OFF); return inputState; } void Engine::follow(Actor *pActor) { m_pImpl->m_pFollowActor = pActor; if (!pActor) return; auto pos = pActor->getPosition(); auto pOldRoom = getRoom(); setRoom(pActor->getRoom()); if (pOldRoom != pActor->getRoom()) { m_pImpl->m_camera.at(pos); } } const Actor *Engine::getFollowActor() const { return m_pImpl->m_pFollowActor; } void Engine::setVerbExecute(std::unique_ptr<VerbExecute> verbExecute) { m_pImpl->m_pVerbExecute = std::move(verbExecute); } void Engine::setDefaultVerb() { m_pImpl->m_hud.setHoveredEntity(nullptr); auto index = m_pImpl->getCurrentActorIndex(); if (index == -1) return; const auto &verbSlot = m_pImpl->m_hud.getVerbSlot(index); m_pImpl->m_hud.setCurrentVerb(&verbSlot.getVerb(0)); m_pImpl->m_useFlag = UseFlag::None; m_pImpl->m_pUseObject = nullptr; m_pImpl->m_objId1 = 0; m_pImpl->m_pObj2 = nullptr; } void Engine::setScriptExecute(std::unique_ptr<ScriptExecute> scriptExecute) { m_pImpl->m_pScriptExecute = std::move(scriptExecute); } void Engine::addThread(std::unique_ptr<ThreadBase> thread) { m_pImpl->m_threads.push_back(std::move(thread)); } std::vector<std::unique_ptr<ThreadBase>> &Engine::getThreads() { return m_pImpl->m_threads; } glm::vec2 Engine::getMousePositionInRoom() const { return m_pImpl->m_mousePosInRoom; } Preferences &Engine::getPreferences() { return m_pImpl->m_preferences; } SoundManager &Engine::getSoundManager() { return m_pImpl->m_soundManager; } DialogManager &Engine::getDialogManager() { return m_pImpl->m_dialogManager; } Camera &Engine::getCamera() { return m_pImpl->m_camera; } ngf::TimeSpan Engine::getTime() const { return m_pImpl->m_time; } SQInteger Engine::setRoom(Room *pRoom) { if (!pRoom) return 0; auto pOldRoom = m_pImpl->m_pRoom; if (pRoom == pOldRoom) return 0; auto result = m_pImpl->exitRoom(nullptr); if (SQ_FAILED(result)) return result; m_pImpl->setCurrentRoom(pRoom); result = m_pImpl->enterRoom(pRoom, nullptr); if (SQ_FAILED(result)) return result; return 0; } SQInteger Engine::enterRoomFromDoor(Object *pDoor) { auto dir = pDoor->getUseDirection(); auto facing = toFacing(dir); auto pRoom = pDoor->getRoom(); // exit current room auto result = m_pImpl->exitRoom(nullptr); if (SQ_FAILED(result)) return result; // change current room m_pImpl->setCurrentRoom(pRoom); // move current actor to the new room auto actor = getCurrentActor(); actor->getCostume().setFacing(facing); actor->setRoom(pRoom); auto pos = pDoor->getPosition(); auto usePos = pDoor->getUsePosition().value_or(glm::vec2()); pos += usePos; actor->setPosition(pos); // move camera to the actor if not closeup room if (pRoom->getFullscreen() != 1) { m_pImpl->m_camera.at(pos); } // enter current room return m_pImpl->enterRoom(pRoom, pDoor); } void Engine::setInputHUD(bool on) { m_pImpl->m_inputHUD = on; } void Engine::setInputActive(bool active) { if (inCutscene()) return; m_pImpl->m_inputActive = active; m_pImpl->m_showCursor = active; } void Engine::inputSilentOff() { m_pImpl->m_inputActive = false; } void Engine::setInputVerbs(bool on) { m_pImpl->m_inputVerbsActive = on; } void Engine::update(const ngf::TimeSpan &el) { if (m_pImpl->m_state == EngineState::Quit) return; roomEffect.RandomValue[0] = Locator<RandomNumberGenerator>::get().generateFloat(0, 1.f); roomEffect.iGlobalTime = fmod(m_pImpl->m_time.getTotalSeconds(), 1000.f); roomEffect.TimeLapse = roomEffect.iGlobalTime; auto gameSpeedFactor = getPreferences().getUserPreference(PreferenceNames::EnggeGameSpeedFactor, PreferenceDefaultValues::EnggeGameSpeedFactor); const ngf::TimeSpan elapsed(ngf::TimeSpan::seconds(el.getTotalSeconds() * gameSpeedFactor)); m_pImpl->stopThreads(); auto screenSize = m_pImpl->m_pRoom->getScreenSize(); auto view = ngf::View{ngf::frect::fromPositionSize({0, 0}, screenSize)}; m_pImpl->m_mousePos = m_pImpl->m_pApp->getRenderTarget()->mapPixelToCoords(ngf::Mouse::getPosition(), view); if (m_pImpl->m_pRoom && m_pImpl->m_pRoom->getName() != "Void") { auto screenMouse = toDefaultView((glm::ivec2) m_pImpl->m_mousePos, screenSize); m_pImpl->m_hud.setMousePosition(screenMouse); m_pImpl->m_dialogManager.setMousePosition(screenMouse); } if (m_pImpl->m_state == EngineState::Options) { m_pImpl->m_optionsDialog.update(elapsed); } else if (m_pImpl->m_state == EngineState::StartScreen) { m_pImpl->m_startScreenDialog.update(elapsed); if (m_pImpl->m_state == EngineState::Quit) return; } if (m_pImpl->m_state == EngineState::Paused) { m_pImpl->updateKeys(); return; } // update fade effect m_pImpl->m_fadeEffect.elapsed += elapsed; m_pImpl->m_talkingState.update(elapsed); m_pImpl->m_frameCounter++; auto &io = ImGui::GetIO(); auto wasMouseDown = m_pImpl->m_isMouseDown && !io.WantCaptureMouse; auto wasMouseRightDown = m_pImpl->m_isMouseRightDown; m_pImpl->m_isMouseDown = ngf::Mouse::isButtonPressed(ngf::Mouse::Button::Left) && !io.WantCaptureMouse; if (!wasMouseDown || !m_pImpl->m_isMouseDown) { m_pImpl->m_mouseDownTime = ngf::TimeSpan::seconds(0); m_pImpl->run(false); } else { m_pImpl->m_mouseDownTime += elapsed; if (m_pImpl->m_mouseDownTime > ngf::TimeSpan::seconds(0.5f)) { m_pImpl->run(true); } } m_pImpl->m_isMouseRightDown = ngf::Mouse::isButtonPressed(ngf::Mouse::Button::Right) && !io.WantCaptureMouse; bool isRightClick = wasMouseRightDown != m_pImpl->m_isMouseRightDown && !m_pImpl->m_isMouseRightDown; auto isMouseClick = wasMouseDown != m_pImpl->m_isMouseDown && !m_pImpl->m_isMouseDown; m_pImpl->m_time += elapsed; m_pImpl->m_noOverrideElapsed += elapsed; m_pImpl->m_camera.update(elapsed); m_pImpl->m_soundManager.update(elapsed); m_pImpl->updateCutscene(elapsed); m_pImpl->updateFunctions(elapsed); m_pImpl->updateSentence(elapsed); m_pImpl->updateKeys(); if (!m_pImpl->m_pRoom || m_pImpl->m_pRoom->getName() == "Void") return; m_pImpl->updateRoomScalings(); m_pImpl->m_pRoom->update(elapsed); for (auto &pActor : m_pImpl->m_actors) { if (!pActor || pActor->getRoom() == m_pImpl->m_pRoom) continue; pActor->update(elapsed); } m_pImpl->updateActorIcons(elapsed); if (m_pImpl->m_state == EngineState::Options) return; m_pImpl->m_cursorDirection = CursorDirection::None; m_pImpl->updateMouseCursor(); auto mousePos = glm::vec2(m_pImpl->m_mousePos.x, m_pImpl->m_pRoom->getScreenSize().y - m_pImpl->m_mousePos.y); m_pImpl->m_mousePosInRoom = mousePos + m_pImpl->m_camera.getRect().getTopLeft(); m_pImpl->m_dialogManager.update(elapsed); m_pImpl->m_hud.setActive( m_pImpl->m_inputVerbsActive && m_pImpl->m_dialogManager.getState() == DialogManagerState::None && m_pImpl->m_pRoom->getFullscreen() != 1); m_pImpl->m_hud.setHoveredEntity(m_pImpl->getHoveredEntity(m_pImpl->m_mousePosInRoom)); m_pImpl->updateHoveredEntity(isRightClick); if (m_pImpl->m_pCurrentActor) { auto &objects = m_pImpl->m_pCurrentActor->getObjects(); for (auto &object : objects) { object->update(elapsed); } } m_pImpl->m_hud.update(elapsed); if (m_pImpl->m_actorIcons.isMouseOver()) return; if (isMouseClick && m_pImpl->clickedAt(m_pImpl->m_mousePosInRoom)) return; if (!m_pImpl->m_inputActive) return; m_pImpl->updateKeyboard(); if (m_pImpl->m_dialogManager.getState() != DialogManagerState::None) { auto rightClickSkipsDialog = getPreferences().getUserPreference(PreferenceNames::RightClickSkipsDialog, PreferenceDefaultValues::RightClickSkipsDialog); if (rightClickSkipsDialog && isRightClick) { m_pImpl->skipText(); } return; } if (!m_pImpl->m_pCurrentActor) return; if (!isMouseClick && !isRightClick && !m_pImpl->m_isMouseDown) return; m_pImpl->m_hud.setVisible(true); m_pImpl->m_actorIcons.setVisible(true); m_pImpl->m_cursorVisible = true; stopSentence(); const auto *pVerb = m_pImpl->getHoveredVerb(); // input click on a verb ? if (m_pImpl->m_hud.getActive() && pVerb) { m_pImpl->onVerbClick(pVerb); return; } if (!isMouseClick && !isRightClick) { if (!pVerb && !m_pImpl->m_hud.getHoveredEntity()) m_pImpl->m_pCurrentActor->walkTo(m_pImpl->m_mousePosInRoom); return; } if (m_pImpl->m_hud.getHoveredEntity()) { ScriptEngine::rawCall("onObjectClick", m_pImpl->m_hud.getHoveredEntity()); auto pVerbOverride = m_pImpl->m_hud.getVerbOverride(); if (!pVerbOverride) { pVerbOverride = m_pImpl->m_hud.getCurrentVerb(); } pVerbOverride = m_pImpl->overrideVerb(pVerbOverride); auto pObj1 = EntityManager::getScriptObjectFromId<Entity>(m_pImpl->m_objId1); pObj1 = pVerbOverride->id == VerbConstants::VERB_TALKTO ? m_pImpl->getEntity(pObj1) : pObj1; auto pObj2 = pVerbOverride->id == VerbConstants::VERB_GIVE ? m_pImpl->getEntity(m_pImpl->m_pObj2) : m_pImpl->m_pObj2; if (pObj1) { m_pImpl->m_pVerbExecute->execute(pVerbOverride, pObj1, pObj2); } return; } if (m_pImpl->m_hud.isMouseOver()) return; m_pImpl->m_pCurrentActor->walkTo(m_pImpl->m_mousePosInRoom); setDefaultVerb(); } void Engine::setCurrentActor(Actor *pCurrentActor, bool userSelected) { m_pImpl->m_pCurrentActor = pCurrentActor; int currentActorIndex = m_pImpl->getCurrentActorIndex(); m_pImpl->m_hud.setCurrentActorIndex(currentActorIndex); m_pImpl->m_hud.setCurrentActor(m_pImpl->m_pCurrentActor); ScriptEngine::rawCall("onActorSelected", pCurrentActor, userSelected); auto pRoom = pCurrentActor ? pCurrentActor->getRoom() : nullptr; if (pRoom) { if (ScriptEngine::rawExists(pRoom, "onActorSelected")) { ScriptEngine::rawCall(pRoom, "onActorSelected", pCurrentActor, userSelected); } } if (m_pImpl->m_pCurrentActor) { follow(m_pImpl->m_pCurrentActor); } } void Engine::draw(ngf::RenderTarget &target, bool screenshot) const { if (!m_pImpl->m_pRoom) return; // update room shader if necessary ngf::RenderStates states; auto effect = m_pImpl->m_pRoom->getEffect(); if (m_pImpl->m_roomEffect != effect) { if (effect == RoomEffectConstants::EFFECT_BLACKANDWHITE) { m_pImpl->m_roomShader.load(Shaders::vertexShader, Shaders::bwFragmentShader); } else if (effect == RoomEffectConstants::EFFECT_EGA) { m_pImpl->m_roomShader.load(Shaders::vertexShader, Shaders::egaFragmenShader); } else if (effect == RoomEffectConstants::EFFECT_GHOST) { m_pImpl->m_roomShader.load(Shaders::vertexShader, Shaders::ghostFragmentShader); } else if (effect == RoomEffectConstants::EFFECT_SEPIA) { m_pImpl->m_roomShader.load(Shaders::vertexShader, Shaders::sepiaFragmentShader); } else if (effect == RoomEffectConstants::EFFECT_VHS) { m_pImpl->m_roomShader.load(Shaders::vertexShader, Shaders::vhsFragmentShader); } m_pImpl->m_roomEffect = effect; } states.shader = &m_pImpl->m_roomShader; if (effect == RoomEffectConstants::EFFECT_GHOST) { // don't remove the fmod function or you will have float overflow with the shader and the effect will look strange m_pImpl->m_roomShader.setUniform("iGlobalTime", roomEffect.iGlobalTime); m_pImpl->m_roomShader.setUniform("iFade", roomEffect.iFade); m_pImpl->m_roomShader.setUniform("wobbleIntensity", roomEffect.wobbleIntensity); m_pImpl->m_roomShader.setUniform("shadows", roomEffect.shadows); m_pImpl->m_roomShader.setUniform("midtones", roomEffect.midtones); m_pImpl->m_roomShader.setUniform("highlights", roomEffect.highlights); } else if (effect == RoomEffectConstants::EFFECT_SEPIA) { m_pImpl->m_roomShader.setUniform("sepiaFlicker", roomEffect.sepiaFlicker); m_pImpl->m_roomShader.setUniformArray("RandomValue", roomEffect.RandomValue.data(), 5); m_pImpl->m_roomShader.setUniform("TimeLapse", roomEffect.TimeLapse); } else if (effect == RoomEffectConstants::EFFECT_VHS) { m_pImpl->m_roomShader.setUniform("iGlobalTime", roomEffect.iGlobalTime); m_pImpl->m_roomShader.setUniform("iNoiseThreshold", roomEffect.iNoiseThreshold); } else if (effect == RoomEffectConstants::EFFECT_NONE) { states.shader = nullptr; } // render the room to a texture, this allows to create a post process effect: room effect ngf::RenderTexture roomTexture(target.getSize()); auto screenSize = m_pImpl->m_pRoom->getScreenSize(); ngf::View view(ngf::frect::fromPositionSize({0, 0}, screenSize)); roomTexture.setView(view); roomTexture.clear(); m_pImpl->m_pRoom->draw(roomTexture, m_pImpl->m_camera.getRect().getTopLeft()); roomTexture.display(); // then render a sprite with this texture and apply the room effect ngf::RenderTexture roomWithEffectTexture(target.getSize()); roomWithEffectTexture.clear(); ngf::Sprite sprite(roomTexture.getTexture()); sprite.draw(roomWithEffectTexture, states); // and render overlay ngf::RectangleShape fadeShape; fadeShape.setSize(roomWithEffectTexture.getSize()); fadeShape.setColor(m_pImpl->m_pRoom->getOverlayColor()); fadeShape.draw(roomWithEffectTexture, {}); roomWithEffectTexture.display(); // render fade ngf::Sprite fadeSprite; float fade = m_pImpl->m_fadeEffect.effect == FadeEffect::None ? 0.f : std::clamp( m_pImpl->m_fadeEffect.elapsed.getTotalSeconds() / m_pImpl->m_fadeEffect.duration.getTotalSeconds(), 0.f, 1.f); ngf::RenderTexture roomTexture2(target.getSize()); roomTexture2.setView(view); roomTexture2.clear(); if (m_pImpl->m_fadeEffect.effect == FadeEffect::Wobble) { m_pImpl->m_fadeEffect.room->draw(roomTexture2, m_pImpl->m_fadeEffect.cameraTopLeft); } roomTexture2.display(); ngf::RenderTexture roomTexture3(target.getSize()); ngf::Sprite sprite2(roomTexture2.getTexture()); sprite2.draw(roomTexture3, {}); roomTexture3.display(); const ngf::Texture *texture1{nullptr}; const ngf::Texture *texture2{nullptr}; switch (m_pImpl->m_fadeEffect.effect) { case FadeEffect::Wobble: case FadeEffect::In:texture1 = &roomTexture3.getTexture(); texture2 = &roomWithEffectTexture.getTexture(); break; case FadeEffect::Out:texture1 = &roomWithEffectTexture.getTexture(); texture2 = &roomTexture3.getTexture(); break; default:texture1 = &roomWithEffectTexture.getTexture(); texture2 = &roomWithEffectTexture.getTexture(); break; } fadeSprite.setTexture(*texture1); m_pImpl->m_fadeShader.setUniform("u_texture2", *texture2); m_pImpl->m_fadeShader.setUniform("u_fade", fade); // fade value between [0.f,1.f] m_pImpl->m_fadeShader.setUniform("u_fadeToSep", m_pImpl->m_fadeEffect.fadeToSepia ? 1 : 0); // 1 to fade to sepia m_pImpl->m_fadeShader.setUniform("u_movement", sinf(M_PI * fade) * m_pImpl->m_fadeEffect.movement); // movement for wobble effect m_pImpl->m_fadeShader.setUniform("u_timer", m_pImpl->m_fadeEffect.elapsed.getTotalSeconds()); states.shader = &m_pImpl->m_fadeShader; // apply the room rotation auto pos = target.getView().getSize() / 2.f; fadeSprite.getTransform().setOrigin(pos); fadeSprite.getTransform().setPosition(pos); fadeSprite.getTransform().setRotation(m_pImpl->m_pRoom->getRotation()); fadeSprite.draw(target, states); // if we take a screenshot (for savegame) then stop drawing if (screenshot) return; // draw dialogs, hud m_pImpl->m_dialogManager.draw(target, {}); m_pImpl->drawHud(target); // draw walkboxes, actor texts auto orgView = target.getView(); target.setView(view); m_pImpl->drawWalkboxes(target); m_pImpl->drawActorHotspot(target); const auto &objects = m_pImpl->m_pRoom->getObjects(); std::for_each(objects.begin(), objects.end(), [this, &target](const auto &pObj) { m_pImpl->drawObjectHotspot(*pObj, target); m_pImpl->drawDebugHotspot(*pObj, target); }); ngf::RenderStates statesObjects; auto &lightingShader = m_pImpl->m_pRoom->getLightingShader(); statesObjects.shader = &lightingShader; lightingShader.setNumberLights(0); lightingShader.setAmbientColor(ngf::Colors::White); std::for_each(objects.begin(), objects.end(), [this, &target, statesObjects](const auto &pObj) { m_pImpl->drawScreenSpace(*pObj, target, statesObjects); }); m_pImpl->m_talkingState.draw(target, {}); m_pImpl->m_pRoom->drawForeground(target, m_pImpl->m_camera.getAt()); target.setView(orgView); // draw actor icons if ((m_pImpl->m_dialogManager.getState() == DialogManagerState::None) && m_pImpl->m_inputActive) { m_pImpl->m_actorIcons.draw(target, {}); } // draw options or startscreen if necessary if (m_pImpl->m_state == EngineState::Options) { m_pImpl->m_optionsDialog.draw(target, {}); } else if (m_pImpl->m_state == EngineState::StartScreen) { m_pImpl->m_startScreenDialog.draw(target, {}); } // draw pause, cursor and no override icon m_pImpl->drawPause(target); m_pImpl->drawCursor(target); m_pImpl->drawCursorText(target); m_pImpl->drawNoOverride(target); } void Engine::setWalkboxesFlags(WalkboxesFlags show) { m_pImpl->m_showDrawWalkboxes = show; } WalkboxesFlags Engine::getWalkboxesFlags() const { return m_pImpl->m_showDrawWalkboxes; } void Engine::startDialog(const std::string &dialog, const std::string &node) { std::string actor; if (m_pImpl->m_pCurrentActor) actor = m_pImpl->m_pCurrentActor->getKey(); m_pImpl->m_dialogManager.start(actor, dialog, node); } void Engine::execute(const std::string &code) { m_pImpl->m_pScriptExecute->execute(code); } SoundDefinition *Engine::getSoundDefinition(const std::string &name) { return m_pImpl->m_pScriptExecute->getSoundDefinition(name); } bool Engine::executeCondition(const std::string &code) { return m_pImpl->m_pScriptExecute->executeCondition(code); } std::string Engine::executeDollar(const std::string &code) { return m_pImpl->m_pScriptExecute->executeDollar(code); } void Engine::addSelectableActor(int index, Actor *pActor) { m_pImpl->m_actorsIconSlots.at(index - 1).selectable = true; m_pImpl->m_actorsIconSlots.at(index - 1).pActor = pActor; } void Engine::actorSlotSelectable(Actor *pActor, bool selectable) { auto it = std::find_if(m_pImpl->m_actorsIconSlots.begin(), m_pImpl->m_actorsIconSlots.end(), [&pActor](auto &selectableActor) -> bool { return selectableActor.pActor == pActor; }); if (it != m_pImpl->m_actorsIconSlots.end()) { it->selectable = selectable; } } void Engine::actorSlotSelectable(int index, bool selectable) { m_pImpl->m_actorsIconSlots.at(index - 1).selectable = selectable; } bool Engine::isActorSelectable(Actor *pActor) const { for (auto &&slot : m_pImpl->m_actorsIconSlots) { if (slot.pActor == pActor) return slot.selectable; } return false; } ActorSlotSelectableMode Engine::getActorSlotSelectable() const { return m_pImpl->m_actorIcons.getMode(); } void Engine::setActorSlotSelectable(ActorSlotSelectableMode mode) { m_pImpl->m_actorIcons.setMode(mode); } void Engine::setUseFlag(UseFlag flag, Entity *object) { m_pImpl->m_useFlag = flag; m_pImpl->m_pUseObject = object; } void Engine::cutsceneOverride() { if (!m_pImpl->m_pCutscene) return; m_pImpl->m_pCutscene->cutsceneOverride(); } void Engine::cutscene(std::unique_ptr<Cutscene> function) { m_pImpl->m_pCutscene = function.get(); addThread(std::move(function)); } Cutscene *Engine::getCutscene() const { return m_pImpl->m_pCutscene; } bool Engine::inCutscene() const { return m_pImpl->m_pCutscene && !m_pImpl->m_pCutscene->isElapsed(); } HSQOBJECT &Engine::getDefaultObject() { return m_pImpl->m_pDefaultObject; } void Engine::flashSelectableActor(bool on) { m_pImpl->m_actorIcons.flash(on); } const Verb *Engine::getActiveVerb() const { return m_pImpl->m_hud.getCurrentVerb(); } void Engine::fadeTo(FadeEffect effect, const ngf::TimeSpan &duration) { m_pImpl->m_fadeEffect.effect = effect; m_pImpl->m_fadeEffect.room = getRoom(); m_pImpl->m_fadeEffect.cameraTopLeft = m_pImpl->m_camera.getRect().getTopLeft(); m_pImpl->m_fadeEffect.duration = duration; m_pImpl->m_fadeEffect.movement = effect == FadeEffect::Wobble ? 0.005f : 0.f; m_pImpl->m_fadeEffect.elapsed = ngf::TimeSpan::seconds(0); } FadeEffectParameters &Engine::getFadeParameters() { return m_pImpl->m_fadeEffect; } void Engine::pushSentence(int id, Entity *pObj1, Entity *pObj2) { const Verb *pVerb = m_pImpl->m_hud.getVerb(id); if (!pVerb) return; m_pImpl->m_pVerbExecute->execute(pVerb, pObj1, pObj2); } void Engine::setSentence(std::unique_ptr<Sentence> sentence) { m_pImpl->m_pSentence = std::move(sentence); } void Engine::stopSentence() { if (!m_pImpl->m_pSentence) return; m_pImpl->m_pSentence->stop(); m_pImpl->m_pSentence.reset(); } void Engine::keyDown(const Input &key) { m_pImpl->m_newKeyDowns.insert(key); } void Engine::keyUp(const Input &key) { auto it = m_pImpl->m_newKeyDowns.find(key); if (it == m_pImpl->m_newKeyDowns.end()) return; m_pImpl->m_newKeyDowns.erase(it); } void Engine::sayLineAt(glm::ivec2 pos, ngf::Color color, ngf::TimeSpan duration, const std::string &text) { m_pImpl->m_talkingState.setTalkColor(color); auto size = getRoom()->getRoomSize(); m_pImpl->m_talkingState.setPosition(toDefaultView(pos, size)); m_pImpl->m_talkingState.setText(getText(text)); m_pImpl->m_talkingState.setDuration(duration); } void Engine::sayLineAt(glm::ivec2 pos, Entity &entity, const std::string &text) { auto size = getRoom()->getRoomSize(); m_pImpl->m_talkingState.setPosition(toDefaultView(pos, size)); m_pImpl->m_talkingState.loadLip(text, &entity); } void Engine::showOptions(bool visible) { m_pImpl->m_state = visible ? EngineState::Options : EngineState::Game; } void Engine::quit() { m_pImpl->m_pApp->quit(); m_pImpl->m_state = EngineState::Quit; } void Engine::run() { std::ifstream is("engge.nut"); if (is.is_open()) { info("execute engge.nut"); m_pImpl->m_state = EngineState::Game; ScriptEngine::executeScript("engge.nut"); return; } ng::info("execute boot script"); ScriptEngine::executeNutScript("Defines.nut"); ScriptEngine::executeNutScript("Boot.nut"); execute("cameraInRoom(StartScreen)"); } Inventory &Engine::getInventory() { return m_pImpl->m_hud.getInventory(); } Hud &Engine::getHud() { return m_pImpl->m_hud; } void Engine::saveGame(int slot) { Impl::SaveGameSystem saveGameSystem(m_pImpl.get()); auto path = Impl::SaveGameSystem::getSlotPath(slot); std::filesystem::path screenshotPath(path); screenshotPath.replace_extension(".png"); m_pImpl->captureScreen(screenshotPath.string()); saveGameSystem.saveGame(path); } void Engine::loadGame(int slot) { Impl::SaveGameSystem saveGameSystem(m_pImpl.get()); saveGameSystem.loadGame(Impl::SaveGameSystem::getSlotPath(slot).string()); } void Engine::setAutoSave(bool autoSave) { m_pImpl->m_autoSave = autoSave; } bool Engine::getAutoSave() const { return m_pImpl->m_autoSave; } void Engine::allowSaveGames(bool allow) { m_pImpl->m_optionsDialog.setSaveEnabled(allow); } Entity *Engine::getEntity(const std::string &name) { if (name == "agent" || name == "player") return m_pImpl->m_pCurrentActor; Entity *pEntity = nullptr; ScriptEngine::get(name.data(), pEntity); return pEntity; } void Engine::getSlotSavegames(std::vector<SavegameSlot> &slots) { for (int i = 1; i <= 9; ++i) { auto path = Impl::SaveGameSystem::getSlotPath(i); SavegameSlot slot; slot.slot = i; slot.path = path; if (std::filesystem::exists(path)) { Impl::SaveGameSystem::getSlot(slot); } slots.push_back(slot); } } void Engine::stopTalking() const { m_pImpl->stopTalking(); } void Engine::stopTalkingExcept(Entity *pEntity) const { m_pImpl->stopTalkingExcept(pEntity); } std::wstring SavegameSlot::getSaveTimeString() const { tm *ltm = localtime(&savetime); wchar_t buffer[120]; // time format: "%b %d at %H:%M" auto format = Locator<TextDatabase>::get().getText(99944); wcsftime(buffer, 120, format.data(), ltm); return buffer; } std::wstring SavegameSlot::getGameTimeString() const { wchar_t buffer[120]; auto min = static_cast<int>(gametime.getTotalSeconds() / 60.0); if (min < 2) { // "%d minute" auto format = Locator<TextDatabase>::get().getText(99945); swprintf(buffer, 120, format.data(), min); } else if (min < 60) { // "%d minutes" auto format = Locator<TextDatabase>::get().getText(99946); swprintf(buffer, 120, format.data(), min); } else { int format; int hour = min / 60; min = min % 60; if (hour < 2 && min < 2) { // "%d hour %d minute" format = 99947; } else if (hour < 2 && min >= 2) { // "%d hour %d minutes"; format = 99948; } else if (hour >= 2 && min < 2) { // "%d hours %d minute"; format = 99949; } else { // "%d hours %d minutes"; format = 99950; } swprintf(buffer, 120, Locator<TextDatabase>::get().getText(format).data(), hour, min); } std::wstring s(buffer); return s; } } // namespace ng
35.006445
120
0.711515
[ "render", "object", "vector" ]
5cb91c864c2353ddb25ad71555abb944bb1407dd
15,199
cpp
C++
IrisLangLibrary/src/IrisExportAPIs/IrisExportForC.cpp
yuwenhuisama/Iris-Language
d2cabe4bb89628a33bc34e429d1fdce6f3f076e6
[ "Apache-2.0" ]
13
2016-03-15T06:44:57.000Z
2021-06-13T16:37:48.000Z
IrisLangLibrary/src/IrisExportAPIs/IrisExportForC.cpp
yuwenhuisama/Iris-Language
d2cabe4bb89628a33bc34e429d1fdce6f3f076e6
[ "Apache-2.0" ]
null
null
null
IrisLangLibrary/src/IrisExportAPIs/IrisExportForC.cpp
yuwenhuisama/Iris-Language
d2cabe4bb89628a33bc34e429d1fdce6f3f076e6
[ "Apache-2.0" ]
5
2016-03-15T07:31:49.000Z
2017-02-01T04:30:45.000Z
#include "IrisExportAPIs\IrisExportForC.h" #include "stdafx.h" #include "IrisDevelopUtil.h" #include "IrisInterpreter/IrisStructure/IrisClass.h" #include "IrisInterpreter/IrisStructure/IrisModule.h" #include "IrisInterpreter.h" #include "IrisInterpreter/IrisNativeClasses/IrisInteger.h" #include "IrisInterpreter/IrisNativeClasses/IrisFloat.h" #include "IrisInterpreter/IrisNativeClasses/IrisString.h" #include "IrisInterpreter/IrisNativeClasses/IrisUniqueString.h" #include "IrisInterpreter/IrisNativeModules/IrisGC.H" #include "IrisFatalErrorHandler.h" FatalErrorMessageFunctionForC g_pfFatalErrorMessageFunctionForC; ExitConditionFunctionForC g_pfExitConditionFunctionForC; #define IMPLEMENT_IRISDEV_CLASS_CHECK(klass) IRISLANGLIBRARY_API bool IrisDev_CheckClassIs##klass(CIrisValue ivValue) { return IrisDevUtil::CheckClassIs##klass(*((IrisValue*)&(ivValue))); } IMPLEMENT_IRISDEV_CLASS_CHECK(Class) IMPLEMENT_IRISDEV_CLASS_CHECK(Module) IMPLEMENT_IRISDEV_CLASS_CHECK(Interface) IMPLEMENT_IRISDEV_CLASS_CHECK(Object) IMPLEMENT_IRISDEV_CLASS_CHECK(String) IMPLEMENT_IRISDEV_CLASS_CHECK(UniqueString) IMPLEMENT_IRISDEV_CLASS_CHECK(Integer) IMPLEMENT_IRISDEV_CLASS_CHECK(Float) IMPLEMENT_IRISDEV_CLASS_CHECK(Array) IMPLEMENT_IRISDEV_CLASS_CHECK(Hash) IMPLEMENT_IRISDEV_CLASS_CHECK(Range) IMPLEMENT_IRISDEV_CLASS_CHECK(Block) #define CAST_AS_IrisValue(value) (*((IrisValue*)&(value))) #define CAST_AS_CIrisValue(value) (*((CIrisValue*)&(value))) #define CAST_AS_IIrisObject(value) ((IIrisObject*)(value)) #define CAST_AS_IIrisValues(value) ((IIrisValues*)(value)) #define CAST_AS_IIrisClass(value) ((IIrisClass*)(value)) #define CAST_AS_IIrisModule(value) ((IIrisModule*)(value)) #define CAST_AS_IIrisInterface(value) ((IIrisInterface*)(value)) #define CAST_AS_IIrisContextEnvironment(value) ((IIrisContextEnvironment*)(value)) #define CAST_AS_IIrisClosureBlock(value) ((IIrisClosureBlock*)(value)) IRISLANGLIBRARY_API void* _IrisDev_InnerGetNativePointerWithValue(CIrisValue ivValue) { return IrisDevUtil::_InnerGetNativePointer(CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API void* _IrisDev_InnerGetNativePointerWithObject(CIIrisObject pObject) { return IrisDevUtil::_InnerGetNativePointer(CAST_AS_IIrisObject(pObject)); } IRISLANGLIBRARY_API int IrisDev_CheckClass(CIrisValue ivValue, char * szClassName) { return IrisDevUtil::CheckClass(CAST_AS_IrisValue(ivValue), szClassName) ? 1 : 0; } IRISLANGLIBRARY_API void IrisDev_GroanIrregularWithString(char * szIrregularString) { IrisDevUtil::GroanIrregularWithString(szIrregularString); } IRISLANGLIBRARY_API int IrisDev_GetInt(CIrisValue ivValue) { return IrisDevUtil::GetInt(CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API double IrisDev_GetFloat(CIrisValue ivValue) { return IrisDevUtil::GetFloat(CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API char * IrisDev_GetString(CIrisValue ivValue) { return (char*)(IrisDevUtil::GetString(CAST_AS_IrisValue(ivValue))); } IRISLANGLIBRARY_API CIrisValue IrisDev_CallMethod(CIrisValue ivObj, char * szMethodName, CIIrisValues pParameters) { return CAST_AS_CIrisValue((IrisDevUtil::CallMethod(CAST_AS_IrisValue(ivObj), szMethodName, CAST_AS_IIrisValues(pParameters)))); } IRISLANGLIBRARY_API CIrisValue IrisDev_CallClassClassMethod(CIIrisClass pClass, char * szMethodName, CIIrisValues * pParameters) { return CAST_AS_CIrisValue((IrisDevUtil::CallClassMethod(CAST_AS_IIrisClass(pClass), szMethodName, CAST_AS_IIrisValues(pParameters)))); } IRISLANGLIBRARY_API CIrisValue IrisDev_CallClassModuleMethod(CIIrisModule pModule, char * szMethodName, CIIrisValues * pParameters) { return CAST_AS_CIrisValue((IrisDevUtil::CallClassMethod(CAST_AS_IIrisModule(pModule), szMethodName, CAST_AS_IIrisValues(pParameters)))); } IRISLANGLIBRARY_API CIIrisClass IrisDev_GetClass(char * strClassPathName) { return IrisDevUtil::GetClass(strClassPathName); } IRISLANGLIBRARY_API CIIrisModule IrisDev_GetModule(char * strClassPathName) { return IrisDevUtil::GetModule(strClassPathName); } IRISLANGLIBRARY_API CIIrisInterface IrisDev_GetInterface(char * strClassPathName) { return IrisDevUtil::GetInterface(strClassPathName); } IRISLANGLIBRARY_API int IrisDev_ObjectIsFixed(CIrisValue ivObj) { return IrisDevUtil::ObjectIsFixed(CAST_AS_IrisValue(ivObj)) ? 1 : 0; } IRISLANGLIBRARY_API CIIrisClosureBlock IrisDev_GetClosureBlock(CIIrisContextEnvironment pContextEnvironment) { return IrisDevUtil::GetClosureBlock(CAST_AS_IIrisContextEnvironment(pContextEnvironment)); } IRISLANGLIBRARY_API CIrisValue IrisDev_ExcuteClosureBlock(CIIrisClosureBlock pClosureBlock, CIIrisValues * pParameters) { return CAST_AS_CIrisValue(IrisDevUtil::ExcuteClosureBlock(CAST_AS_IIrisClosureBlock(pClosureBlock), CAST_AS_IIrisValues(pParameters))); } IRISLANGLIBRARY_API void IrisDev_ContextEnvironmentSetClosureBlock(CIIrisContextEnvironment pContextEnvironment, CIIrisClosureBlock pBlock) { return IrisDevUtil::ContextEnvironmentSetClosureBlock(CAST_AS_IIrisContextEnvironment(pContextEnvironment), CAST_AS_IIrisClosureBlock(pBlock)); } IRISLANGLIBRARY_API CIIrisObject IrisDev_GetNativeObjectPointer(CIrisValue ivObj) { return IrisDevUtil::GetNativeObjectPointer(CAST_AS_IrisValue(ivObj)); } IRISLANGLIBRARY_API int IrisDev_GetObjectID(CIrisValue ivObj) { return IrisDevUtil::GetObjectID(CAST_AS_IrisValue(ivObj)); } IRISLANGLIBRARY_API CIIrisClass IrisDev_GetClassOfObject(CIrisValue ivObj) { return IrisDevUtil::GetClassOfObject(CAST_AS_IrisValue(ivObj)); } IRISLANGLIBRARY_API char * IrisDev_GetNameOfClass(CIIrisClass pClass) { return const_cast<char*>(IrisDevUtil::GetNameOfClass(CAST_AS_IIrisClass(pClass))); } IRISLANGLIBRARY_API char * IrisDev_GetNameOfModule(CIIrisModule pModule) { return const_cast<char*>(IrisDevUtil::GetNameOfModule(CAST_AS_IIrisModule(pModule))); } IRISLANGLIBRARY_API char * IrisDev_GetNameOfInterface(CIIrisInterface pInterface) { return const_cast<char*>(IrisDevUtil::GetNameOfInterface(CAST_AS_IIrisInterface(pInterface))); } IRISLANGLIBRARY_API void IrisDev_MarkObject(CIrisValue ivObject) { IrisDevUtil::MarkObject(CAST_AS_IrisValue(ivObject)); } IRISLANGLIBRARY_API void IrisDev_MarkClosureBlock(CIIrisClosureBlock pClosureBlock) { IrisDevUtil::MarkClosureBlock(CAST_AS_IIrisClosureBlock(pClosureBlock)); } IRISLANGLIBRARY_API CIrisValue IrisDev_Nil() { return CAST_AS_CIrisValue(IrisDevUtil::Nil()); } IRISLANGLIBRARY_API CIrisValue IrisDev_False() { return CAST_AS_CIrisValue(IrisDevUtil::False()); } IRISLANGLIBRARY_API CIrisValue IrisDev_True() { return CAST_AS_CIrisValue(IrisDevUtil::True()); } IRISLANGLIBRARY_API int IrisDev_RegistClass(char * szPath, CIIrisClass pClass) { return IrisInterpreter::CurrentInterpreter()->RegistClass(szPath, CAST_AS_IIrisClass(pClass)); } IRISLANGLIBRARY_API int IrisDev_RegistModule(char * szPath, CIIrisModule pModule) { return IrisInterpreter::CurrentInterpreter()->RegistModule(szPath, CAST_AS_IIrisModule(pModule)); } IRISLANGLIBRARY_API int IrisDev_RegistInterface(char * szPath, CIIrisInterface pInterface) { return IrisInterpreter::CurrentInterpreter()->RegistInterface(szPath, CAST_AS_IIrisInterface(pInterface)); } IRISLANGLIBRARY_API void IrisDev_ClassAddInstanceMethod(CIIrisClass pClass, char * szMethodName, CIrisNativeFunction pfFunction, size_t nParamCount, int bIsWithVariableParameter) { IrisDevUtil::AddInstanceMethod(CAST_AS_IIrisClass(pClass), szMethodName, (IrisNativeFunction)pfFunction, nParamCount, bIsWithVariableParameter ? true : false); } IRISLANGLIBRARY_API void IrisDev_ClassAddClassMethod(CIIrisClass pClass, char * szMethodName, CIrisNativeFunction pfFunction, size_t nParamCount, int bIsWithVariableParameter) { IrisDevUtil::AddClassMethod(CAST_AS_IIrisClass(pClass), szMethodName, (IrisNativeFunction)pfFunction, nParamCount, bIsWithVariableParameter ? true : false); } IRISLANGLIBRARY_API void IrisDev_ModuleAddInstanceMethod(CIIrisModule pModule, char * szMethodName, CIrisNativeFunction pfFunction, size_t nParamCount, int bIsWithVariableParameter) { IrisDevUtil::AddInstanceMethod(CAST_AS_IIrisModule(pModule), szMethodName, (IrisNativeFunction)pfFunction, nParamCount, bIsWithVariableParameter ? true : false); } IRISLANGLIBRARY_API void IrisDev_ModuleAddClassMethod(CIIrisModule pModule, char * szMethodName, CIrisNativeFunction pfFunction, size_t nParamCount, int bIsWithVariableParameter) { IrisDevUtil::AddClassMethod(CAST_AS_IIrisModule(pModule), szMethodName, (IrisNativeFunction)pfFunction, nParamCount, bIsWithVariableParameter ? true : false); } IRISLANGLIBRARY_API void IrisDev_AddGetter(CIIrisClass pClass, char * szInstanceVariableName, CIrisNativeFunction pfFunction) { IrisDevUtil::AddGetter(CAST_AS_IIrisClass(pClass), szInstanceVariableName, (IrisNativeFunction)pfFunction); } IRISLANGLIBRARY_API void IrisDev_AddSetter(CIIrisClass pClass, char * szInstanceVariableName, CIrisNativeFunction pfFunction) { IrisDevUtil::AddSetter(CAST_AS_IIrisClass(pClass), szInstanceVariableName, (IrisNativeFunction)pfFunction); } IRISLANGLIBRARY_API void IrisDev_ClassAddConstance(CIIrisClass pClass, char * szConstanceName, CIrisValue ivValue) { IrisDevUtil::AddConstance(CAST_AS_IIrisClass(pClass), szConstanceName, CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API void IrisDev_ModuleAddConstance(CIIrisModule pModule, char * szConstanceName, CIrisValue ivValue) { IrisDevUtil::AddConstance(CAST_AS_IIrisModule(pModule), szConstanceName, CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API void IrisDev_ClassAddClassVariable(CIIrisClass pClass, char * szVariableName, CIrisValue ivValue) { IrisDevUtil::AddClassVariable(CAST_AS_IIrisClass(pClass), szVariableName, CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API void IrisDev_ModuleAddClassVariable(CIIrisModule pModule, char * szVariableName, CIrisValue ivValue) { IrisDevUtil::AddClassVariable(CAST_AS_IIrisModule(pModule), szVariableName, CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API void IrisDev_ClassAddModule(CIIrisClass pClass, CIIrisModule pTargetModule) { IrisDevUtil::AddModule(CAST_AS_IIrisClass(pClass), CAST_AS_IIrisModule(pTargetModule)); } IRISLANGLIBRARY_API void IrisDev_ModuleAddModule(CIIrisModule pModule, CIIrisModule pTargetModule) { IrisDevUtil::AddModule(CAST_AS_IIrisModule(pModule), CAST_AS_IIrisModule(pTargetModule)); } IRISLANGLIBRARY_API CIrisValue IrisDev_CreateNormalInstance(CIIrisClass pClass, CIIrisValues ivsParams, CIIrisContextEnvironment pContexEnvironment) { return CAST_AS_CIrisValue(IrisDevUtil::CreateInstance(CAST_AS_IIrisClass(pClass), CAST_AS_IIrisValues(ivsParams), CAST_AS_IIrisContextEnvironment(pContexEnvironment))); } IRISLANGLIBRARY_API CIrisValue IrisDev_CreateStringInstanceByInstantValue(char * szString) { return CAST_AS_CIrisValue(IrisDevUtil::CreateString(szString)); } IRISLANGLIBRARY_API CIrisValue IrisDev_CreateFloatInstanceByInstantValue(double dFloat) { return CAST_AS_CIrisValue(IrisDevUtil::CreateFloat(dFloat)); } IRISLANGLIBRARY_API CIrisValue IrisDev_CreateIntegerInstanceByInstantValue(int nInteger) { return CAST_AS_CIrisValue(IrisDevUtil::CreateInt(nInteger)); } IRISLANGLIBRARY_API CIrisValue IrisDev_CreateUniqueStringInstanceByUniqueIndex(size_t nIndex) { return CAST_AS_CIrisValue(IrisDevUtil::CreateUniqueStringInstanceByUniqueIndex(nIndex)); } IRISLANGLIBRARY_API void IrisDev_SetObjectInstanceVariable(CIrisValue & ivObj, char * szInstanceVariableName, CIrisValue ivValue) { IrisDevUtil::SetObjectInstanceVariable(CAST_AS_IrisValue(ivObj), szInstanceVariableName, CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API CIrisValue IrisDev_GetObjectInstanceVariable(CIrisValue & ivObj, char * szInstanceVariableName) { return CAST_AS_CIrisValue(IrisDevUtil::GetObjectInstanceVariable(CAST_AS_IrisValue(ivObj), szInstanceVariableName)); } IRISLANGLIBRARY_API int IrisDev_IrregularHappened() { return IrisDevUtil::IrregularHappened() ? 1 : 0; } IRISLANGLIBRARY_API int IrisDev_FatalErrorHappened() { return IrisDevUtil::FatalErrorHappened() ? 1 : 0; } IRISLANGLIBRARY_API CIIrisValues IrisDev_CreateIrisValuesList(size_t nSize) { return nSize > 0 ? new IrisValues(nSize) : nullptr; } IRISLANGLIBRARY_API CIrisValue IrisDev_GetValue(CIIrisValues pValues, size_t nIndex) { return CAST_AS_CIrisValue((static_cast<IrisValues*>(pValues))->GetValue(nIndex)); } IRISLANGLIBRARY_API void IrisDev_SetValue(CIIrisValues pValues, size_t nIndex, CIrisValue ivValue) { static_cast<IrisValues*>(pValues)->SetValue(nIndex, CAST_AS_IrisValue(ivValue)); } IRISLANGLIBRARY_API void IrisDev_ReleaseIrisValuesList(CIIrisValues pValues) { delete (IrisValues*)pValues; } void _InternFatalErrorMessageFunctionForC(const string& pMessage) { g_pfFatalErrorMessageFunctionForC(const_cast<char*>(pMessage.c_str())); } bool _InternExitConditionFunctionForC() { return g_pfExitConditionFunctionForC(); } IRISLANGLIBRARY_API int IR_Initialize(PIrisInitializeStructForC pInitializeStruct) { IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); g_pfExitConditionFunctionForC = pInitializeStruct->m_pfExitConditionFunction; g_pfFatalErrorMessageFunctionForC = pInitializeStruct->m_pfFatalErrorMessageFunction; IrisFatalErrorHandler::CurrentFatalHandler()->SetFatalErrorMessageFuncton(_InternFatalErrorMessageFunctionForC); pInterpreter->SetExitConditionFunction(_InternExitConditionFunctionForC); pInterpreter->SetCompiler(pCompiler); // Run IrisGC::CurrentGC()->SetGCFlag(false); if (!pInterpreter->Initialize()) { return false; } IrisGC::CurrentGC()->ResetNextThreshold(); IrisGC::CurrentGC()->SetGCFlag(true); return true; } IRISLANGLIBRARY_API int IR_Run() { IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); if (!pInterpreter->Run()) { return 0; } return 1; } IRISLANGLIBRARY_API int IR_ShutDown() { IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); return pInterpreter->ShutDown() ? 1 : 0; } IRISLANGLIBRARY_API int IR_LoadScriptFromPath(char * pScriptFilePath) { string strOrgFileName(pScriptFilePath); string strDestFileName; auto nPos = strOrgFileName.find_last_of("."); if (nPos != std::string::npos) { strDestFileName.assign(strOrgFileName, 0, nPos); } strDestFileName += ".irc"; IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); if (!pCompiler->LoadScript(pScriptFilePath)) { return false; } bool bCompileResult = pCompiler->Generate(); if (!bCompileResult) { remove(strDestFileName.c_str()); } return bCompileResult ? 1 : 0; } IRISLANGLIBRARY_API int IR_LoadScriptFromVirtualPathAndText(char* pPath, char * pScriptText) { string strDestFileName(pPath); strDestFileName += ".irc"; IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); if (!pCompiler->LoadScriptFromVirtualPathAndText(pPath, pScriptText)) { return false; } bool bCompileResult = pCompiler->Generate(); if (!bCompileResult) { remove(strDestFileName.c_str()); } return bCompileResult ? 1 : 0; } IRISLANGLIBRARY_API int IR_LoadExtention(char * pExtentionPath) { IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); return pInterpreter->LoadExtension(pExtentionPath) ? 1 : 0; }
36.71256
190
0.836042
[ "object" ]
5cbeab4c0ba04ab04ce2c5a86011d154119a248f
3,006
cpp
C++
25mt/src/dfexplike.cpp
johnoel/tagest
be0a6b164683c448c90f0c3952343f5963eece3d
[ "BSD-2-Clause" ]
3
2015-08-26T17:14:02.000Z
2015-11-17T04:18:56.000Z
25mt/src/dfexplike.cpp
johnoel/tagest
be0a6b164683c448c90f0c3952343f5963eece3d
[ "BSD-2-Clause" ]
10
2015-08-20T00:51:05.000Z
2016-11-16T19:14:48.000Z
25mt/src/dfexplike.cpp
johnoel/tagest
be0a6b164683c448c90f0c3952343f5963eece3d
[ "BSD-2-Clause" ]
3
2016-11-16T00:52:23.000Z
2021-09-10T02:17:40.000Z
//$Id: dfexplike.cpp 2754 2011-01-02 20:57:07Z jsibert $ #include "par_t.h" #include "trace.h" void getreturns(dmatrix& returns, const int fleet, const year_month& date, const int cohort, const recaptype_vector& recaps, const int nrec, const int m, const int n); extern ofstream clogf; extern int _global_report_flag; template <typename D3_ARRAY, typename MATRIX, typename VECTOR, typename DOUBLE> void df_exp_like(double& dflike, dmatrix& pred_tags, dmatrix& dfpred_tags, year_month& date, int cohort, recaptype_vector& recaps, int nrec, par_t<D3_ARRAY,MATRIX,VECTOR,DOUBLE>& param, par_t<d3_array,dmatrix,dvector,double>& dfparam, dmatrix& z, dmatrix& dfz, ivector& effort_occured, d3_array& fmort, d3_array& dffmort) { double tobs = 0.0; double tpred = 0.0; double dftpred = 0.0; //double dflatp = 0.0; //double dfa = 0.0; double dftemp = 0.0; int _m = param.get_m(); int _n = param.get_n(); ivector& jlb = param.get_jlb(); ivector& jub = param.get_jub(); dmatrix obs(1, _m, jlb, jub); dmatrix pred(1, _m, jlb, jub); dmatrix dfpred(1,_m, jlb, jub); dfpred.initialize(); int nf = param.get_nfleet(); for (int f = nf; f >= 1; f--) { if (effort_occured(f)) { getreturns(obs, f, date, cohort, recaps, nrec, _m, _n); // recompute param.pred_recapture_comp(pred, pred_tags, z, fmort, f, date); for (int i=_m; i >=1; i--) { int lb = jlb(i); int ub = jub(i); for (int j=ub; j >= lb; j--) { // recompute tobs = obs(i,j); tpred = pred(i,j); if (tpred > 0.0) { //like +=temp; dftemp += dflike; //temp = -(tobs/tpred + log(tpred)); dftpred += dftemp*tobs/(tpred*tpred); // OK dftpred -= dftemp/tpred; //OK dftemp = 0.0; } //tpred = pred(i,j); dfpred(i,j) += dftpred; dftpred = 0.0; } // j loop } // i loop //param.pred_recapture_comp(pred, pred_tags, z, fmort, f, date); param.df_pred_recapture_comp(dfparam, pred, dfpred, pred_tags, dfpred_tags, z, dfz, fmort, dffmort, f, date); } // if (effort_occured(f)) } // fleet loop } template void df_exp_like(double& dflike, dmatrix& pred_tags, dmatrix& dfpred_tags, year_month& date, int cohort, recaptype_vector& recaps, int nrec, par_t<d3_array,dmatrix,dvector,double>& param, par_t<d3_array,dmatrix,dvector,double>& dfparam, dmatrix& z, dmatrix& dfz, ivector& effort_occured, d3_array& fmort, d3_array& dffmort); template<> void df_exp_like(double& dflike, dmatrix& pred_tags, dmatrix& dfpred_tags, year_month& date, int cohort, recaptype_vector& recaps, int nrec, par_t<dvar3_array,dvar_matrix,dvar_vector,dvariable>& param, par_t<d3_array,dmatrix,dvector,double>& dfparam, dmatrix& z, dmatrix& dfz, ivector& effort_occured, d3_array& fmort, d3_array& dffmort) {}
38.538462
352
0.621756
[ "vector" ]
5cbec1734fdf2ff7ecb4697bda76ac20b4189bcc
11,520
cpp
C++
src/autotune.cpp
kit-algo/TCPSPSuite
01499b4fb0f28bda72115a699cd762c70d7fff63
[ "MIT" ]
3
2018-05-02T11:45:57.000Z
2020-09-14T08:35:43.000Z
src/autotune.cpp
kit-algo/TCPSPSuite
01499b4fb0f28bda72115a699cd762c70d7fff63
[ "MIT" ]
null
null
null
src/autotune.cpp
kit-algo/TCPSPSuite
01499b4fb0f28bda72115a699cd762c70d7fff63
[ "MIT" ]
null
null
null
#include "main.hpp" #include <assert.h> // for assert #include <execinfo.h> // for backtrace #include <stdio.h> // for fprintf #include <algorithm> // for find #include <cstdlib> // for abort, exit #include <exception> // for rethrow_ex... #include <iostream> // for operator<< #include <stdexcept> // for runtime_error #include <string> // for string #include <vector> // for vector #include "contrib/tinydir.h" // for tinydir_dir #include "datastructures/maybe.hpp" // for Maybe #include "generated_config.hpp" // for CATCH_EXCE... #if defined(GUROBI_FOUND) #include "gurobi_c++.h" // for GRBException #endif #include "instance/instance.hpp" // for Instance #include "io/jsonreader.hpp" // for JsonReader #include "db/storage.hpp" // for Storage #include "util/log.hpp" // for Log #include "manager/selector.hpp" // for Selector #include "util/configuration.hpp" // for Configuration #include "util/git.hpp" // for GIT_SHA1 #include "util/randomizer.hpp" // for Randomizer #include "util/solverconfig.hpp" // for SolverConfig #include "util/autotuneconfig.hpp" // for Config #include "manager/parallelizer.hpp" #ifdef CAIRO_FOUND #include "visualization/visualizer.hpp" #endif #define BACKTRACE_SIZE 20 void *backtrace_buffer[BACKTRACE_SIZE]; class ArgumentException : public std::runtime_error { public: explicit ArgumentException(const char *what) : std::runtime_error(what) {} }; void print_help() { std::cout << "Usage: autotune -s <storage> [ -f <instance file> | -d <instance directory> ] OPTIONS \n"; std::cout << "\n"; std::cout << "At least three options are mandatory:\n\n"; std::cout << " -s <storage>: Specifies the path to a sqlite3 database which will store\n"; std::cout << " the results of the computations. The database will be created\n"; std::cout << " if it does not exist.\n"; std::cout << "\n"; std::cout << " -d <instance directory>\n"; std::cout << " : Specifies the path to a directory containing JSON\n"; std::cout << " instance files. The directory will be recursively\n"; std::cout << " scanned for JSON files. All instances found will be\n"; std::cout << " computed on one after the other. May not be specified\n"; std::cout << " if the -f option (see below) is used.\n"; std::cout << "\n"; std::cout << " -f <instance file>\n"; std::cout << " : Specifies the path to a single JSON instance file. Only this\n"; std::cout << " instance will be solved. May not be used if -d is used.\n"; std::cout << "\n"; std::cout << " -c <autotune config file>\n"; std::cout << " : Specifies the path to a single JSON autotune configuration\n"; std::cout << " All variations specified in the config file will be executed "; std::cout << " on all instances.\n"; std::cout << "\n\n"; std::cout << "Additionally, there are optional parameters: \n\n"; std::cout << " -l <seconds>: Limits the maximum computation time to <seconds> seconds. After \n"; std::cout << " that time, all solvers will be asked to quit. If -c is used, the per-algorithm\n"; std::cout << " time limit supersedes this option.\n"; std::cout << "\n"; std::cout << " -t <count> : Sets the number of threads that solvers should use, if they can use multithreading. \n"; std::cout << " Defaults to 1.\n"; std::cout << "\n"; std::cout << " -r <run ID> : Sets the run ID, which may be any string. This string can then later \n"; std::cout << " be used to associate the results with a specific run.\n"; std::cout << "\n"; std::cout << " -u : Asks the software to compute only results which are not yet in the database. \n"; std::cout << " An instance / solver combination is skipped if this combination was already\n"; std::cout << " computed for the specified run (see -r).\n"; std::cout << "\n"; std::cout << " -i <seed> : Forces the 'instance seed' to be <seed>. Note that if you use this in combination\n"; std::cout << " with -d (see above), all found instances will be computed with the exact same seed!\n"; std::cout << " This is useful for reproducing specific results. If -c is used, the per-algorithm\n"; std::cout << " instance seed may supersede this option.\n"; std::cout << "\n"; std::cout << " -g <seed> : Forces the 'global seed' to be <seed>. All instance seeds are generated from this global\n"; std::cout << " seed. This is useful to deterministically reproduce a whole run of the suite.\n"; std::cout << "\n"; std::cout << " -o <logdir> : Sets <logdir> as path to the log directory. If this is given, the suite will write a \n"; std::cout << " separate log for every solver run into this directory.\n"; std::cout << "\n"; std::cout << " -x <resdir> : Sets <resdir> as path to the result dump directory. If this is given, the suite will write a \n"; std::cout << " separate JSON file for every algorithm run on every instance, dumping the result in JSON format.\n"; std::cout << "\n\nExamples:\n\n"; std::cout << " Read all instances from /tmp/instances, write results to /tmp/db.sqlite:\n"; std::cout << " > auotune -d /tmp/instances -s /tmp/db.sdlite\n"; std::cout << "\n"; std::cout << " Read a single instance from /tmp/instance.json, write results to /tmp/db.sqlite, name the run 'testrun':\n"; std::cout << " > autotune -f /tmp/instance.json -s /tmp/db.sdlite -r testrun\n"; std::cout << "\n"; std::cout << " Read all instances from /tmp/instances, write results to /tmp/db.sqlite, stop solving after 15 minutes and do\n"; std::cout << " not duplicate results:\n"; std::cout << " > autotune -d /tmp/instances -s /tmp/db.sdlite -l 900 -u\n"; std::cout << "\n"; } void handle_uncaught() { std::cout << std::flush; std::cerr << std::flush; auto exc = std::current_exception(); try { std::rethrow_exception (exc); } catch (const ArgumentException &) { print_help(); exit(-1); } catch (...) { // do nothing } std::cout << "============= WHOOPS ================\n"; std::cout << "Hi, I'm your friendly crash handler.\n"; std::cout << "It looks like an exception was thrown that has not been caught.\n"; std::cout << "I'm trying to print it now:\n\n"; std::cout << "#########################\n"; try { std::rethrow_exception (exc); } catch (const std::exception& e) { std::cout << e.what() << '\n'; } // TODO move this to ilp.cpp #if defined(GUROBI_FOUND) catch (const GRBException& e) { std::cout << e.getMessage() << '\n'; } #endif #if defined(CPLEX_FOUND) catch (const IloException & e) { std::cout << e << '\n'; } #endif catch (const char *e) { std::cout << e << "\n"; } catch (...) { std::cout << "Sorry, unknown exception type.\n"; } std::cout << "#########################\n\n"; std::cout << "Depending on the sanity of your compiler and libc, I will be\nable to show you a backtrace of the point where \nthe exception was thrown.\n"; std::cout << "If the addr2line tool is avaialble on your system, I might even\nbe able to resolve the code lines.\n"; std::cout << "Here we go:\n\n"; std::cout << "============ BACKTRACE ===============\n"; size_t trace_size = (size_t)backtrace(backtrace_buffer, BACKTRACE_SIZE); /* * The following has in large parts been borrowed from * https://stackoverflow.com/questions/3151779/how-its-better-to-invoke-gdb-from-program-to-print-its-stacktrace/4611112#4611112 * * And... oh god is it hacky! */ char **messages = backtrace_symbols(backtrace_buffer, (int)trace_size); /* skip first stack frame (points here) */ fprintf(stdout, "[bt] Execution path:\n"); for (size_t i=1; i<trace_size; ++i) { fprintf(stdout, "[bt] #%zu %s\n", i, messages[i]); /* find first occurence of '(' or ' ' in message[i] and assume * everything before that is the file name. (Don't go beyond 0 though * (string terminator)*/ size_t p = 0; while(messages[i][p] != '(' && messages[i][p] != ' ' && messages[i][p] != 0) ++p; char syscom[256]; int precision = (int) p; sprintf(syscom,"addr2line %p -e %.*s", backtrace_buffer[i], precision, messages[i]); //last parameter is the file name of the symbol int result = system(syscom); assert(result == 0); } std::cerr << "============ BACKTRACE ===============\n"; std::cerr << "\n"; std::cerr << "Hope that helped. Have a nice day.\n"; std::abort(); } int main(int argc, const char **argv) { #ifdef CATCH_EXCEPTIONS std::set_terminate(&handle_uncaught); #endif // Set up console logging Log::setup(); Log l("MAIN"); BOOST_LOG(l.i()) << "Starting up."; AutotuneConfig & acfg = * AutotuneConfig::get(); if (!acfg.parse_cmdline(argc, argv)) { return 1; } Configuration & cfg = * Configuration::get(); Randomizer randomizer(cfg.get_global_seed()); BOOST_LOG(l.d()) << "Global seed is: " << randomizer.get_global_seed() ; Storage::initialize(cfg.get_storage_path(), argc, argv); Storage store(cfg.get_storage_path()); std::vector<std::string> instances; if (cfg.get_instance_file().valid()) { instances.push_back(cfg.get_instance_file()); } else { tinydir_dir dir; std::vector<std::string> directories; directories.push_back(cfg.get_instance_dir().value()); while (!directories.empty()) { std::string directory = directories.back(); directories.pop_back(); tinydir_open(&dir, directory.c_str()); while (dir.has_next) { tinydir_file file; tinydir_readfile(&dir, &file); std::string filename(file.path); if (filename.substr(filename.size() - 1, 1) == ".") { tinydir_next(&dir); continue; } if (file.is_dir) { directories.push_back(filename); } else { std::string extension = filename.substr(filename.size() - 5, 5); if (extension.compare(".json") == 0) { instances.push_back(filename); BOOST_LOG(l.i()) << "Instance found: " << filename; } } tinydir_next(&dir); } } } std::vector<SolverConfig> configs; do { configs.push_back(acfg.generateConfig()); } while (acfg.nextConfig()); cfg.set_solver_configs(configs); Parallelizer para(store, cfg.get_run(), randomizer); para.run_in_parallel(instances, cfg.solver_configs(), cfg.get_parallelism()); BOOST_LOG(l.i()) << "Finished normally"; return 0; }
41.890909
157
0.572222
[ "vector" ]
5cbf70bd6edb57a37bbc20346fceed70866cb855
794
cpp
C++
leetcode/two_sum/leetcode_40.cpp
HuangJingGitHub/PracMakePert_C
94e570c55d9e391913ccd9c5c72026ab926809b2
[ "Apache-2.0" ]
1
2019-10-17T03:13:29.000Z
2019-10-17T03:13:29.000Z
leetcode/two_sum/leetcode_40.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
null
null
null
leetcode/two_sum/leetcode_40.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
null
null
null
class Solution { private: vector<int> candidates; vector<vector<int>> res; vector<int> path; public: void backtrack(int start, int target){ if (target == 0){ res.push_back(path); return; } for (int i = start; i < candidates.size() && target - candidates[i] >= 0; i++){ if (i > start && candidates[i] == candidates[i-1]) continue; path.push_back(candidates[i]); backtrack(i+1, target - candidates[i]); path.pop_back(); } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); this->candidates = candidates; backtrack(0, target); return res; } };
26.466667
87
0.535264
[ "vector" ]
5cd2e6702979c75bc44eb94d8304cf5cd8630bc0
1,474
cpp
C++
Common/Processes/src/scalerefProcess.cpp
slaclab/gdml
017d19c6488128ad6f663013cfb1be597c556d51
[ "BSD-3-Clause-LBNL" ]
1
2017-04-19T05:43:30.000Z
2017-04-19T05:43:30.000Z
Common/Processes/src/scalerefProcess.cpp
slaclab/gdml
017d19c6488128ad6f663013cfb1be597c556d51
[ "BSD-3-Clause-LBNL" ]
1
2017-04-10T23:15:21.000Z
2017-04-11T02:31:45.000Z
Common/Processes/src/scalerefProcess.cpp
slaclab/gdml
017d19c6488128ad6f663013cfb1be597c556d51
[ "BSD-3-Clause-LBNL" ]
1
2020-12-13T00:05:47.000Z
2020-12-13T00:05:47.000Z
#include "Processes/ReferenceTypeProcess.h" #include "Schema/BooleanSolidType.h" #include "Schema/SinglePlacementType.h" #include <cstdlib> #include <iostream> class scalerefProcess : public ReferenceTypeProcess { public: scalerefProcess( const ProcessingContext* context = 0 ) : ReferenceTypeProcess( context ) { } virtual ~scalerefProcess() { } // Analogical to SAX startElement callback virtual void StartElement( const std::string& name, const ASCIIAttributeList& attrs ) { SAXObject** obj = Context()->GetTopObject(); std::string parent = Context()->GetParentState(); if( parent == "physvol" ) { SinglePlacementType::scaleref* co = new SinglePlacementType::scaleref; *obj = co; m_obj = co; } else if( parent == "union" || parent == "subtraction" || parent == "intersection" ) { BooleanSolidType::scaleref* co = new BooleanSolidType::scaleref; *obj = co; m_obj = co; } ReferenceTypeProcess::StartElement( name, attrs ); } // Analogical to SAX endElement callback virtual void EndElement( const std::string& name ) { ReferenceTypeProcess::EndElement( name ); } // The name of the state this object will process virtual const std::string& State() const { static std::string tag = "scaleref"; return tag; } }; DECLARE_PROCESS_FACTORY(scalerefProcess)
26.321429
89
0.636364
[ "object" ]
5cdbc932f57bf845d7a11a1844f46d6135eed002
44,366
cc
C++
src/ix/ix.cc
moophis/CS222-Simple-Data-Management-System
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
[ "Apache-2.0" ]
null
null
null
src/ix/ix.cc
moophis/CS222-Simple-Data-Management-System
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
[ "Apache-2.0" ]
null
null
null
src/ix/ix.cc
moophis/CS222-Simple-Data-Management-System
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
[ "Apache-2.0" ]
null
null
null
#include "ix.h" #define PRIMARY_SUFFIX ".pp" #define OVERFLOW_SUFFIX ".op" ActivityManager *ActivityManager::_instance = 0; IndexManager* IndexManager::_index_manager = 0; IndexManager* IndexManager::instance() { if(!_index_manager) _index_manager = new IndexManager(); return _index_manager; } IndexManager::IndexManager() { _pfm = PagedFileManager::instance(); _am = ActivityManager::instance(); } IndexManager::~IndexManager() { } RC IndexManager::createFile(const string &fileName, const unsigned &numberOfPages) { RC err; string primary = fileName + PRIMARY_SUFFIX; string overflow = fileName + OVERFLOW_SUFFIX; // Initial bucket should be power of 2 if (numberOfPages & (numberOfPages - 1)) { __trace(); return ERR_INV_INIT_BUCKET; } if ((err = _pfm->createFile(primary.c_str())) != SUCCESSFUL) { __trace(); return err; } if ((err = _pfm->createFile(overflow.c_str())) != SUCCESSFUL) { __trace(); return err; } FileHandle h2; if ((err = _pfm->openFile(overflow.c_str(), h2)) != SUCCESSFUL) { __trace(); return err; } // __trace(); MetadataPage metadataPage(h2); metadataPage.initialize(numberOfPages); if ((err = metadataPage.flush()) != SUCCESSFUL) { __trace(); return err; } if ((err = _pfm->closeFile(h2)) != SUCCESSFUL) { __trace(); return err; } // __trace(); return SUCCESSFUL; } RC IndexManager::destroyFile(const string &fileName) { RC err; string primary = fileName + PRIMARY_SUFFIX; string overflow = fileName + OVERFLOW_SUFFIX; if ((err = _pfm->destroyFile(primary.c_str())) != SUCCESSFUL) { return err; } if ((err = _pfm->destroyFile(overflow.c_str())) != SUCCESSFUL) { return err; } return SUCCESSFUL; } RC IndexManager::openFile(const string &fileName, IXFileHandle &ixFileHandle) { RC err; string primary = fileName + PRIMARY_SUFFIX; string overflow = fileName + OVERFLOW_SUFFIX; if ((err = _pfm->openFile(primary.c_str(), ixFileHandle._primaryHandle)) != SUCCESSFUL) { __trace(); cout << "Cannot open: " << primary << endl; return err; } if ((err = _pfm->openFile(overflow.c_str(), ixFileHandle._overflowHandle)) != SUCCESSFUL) { __trace(); cout << "Cannot open: " << overflow << endl; return err; } return SUCCESSFUL; } RC IndexManager::closeFile(IXFileHandle &ixfileHandle) { RC err; if ((err = _pfm->closeFile(ixfileHandle._primaryHandle)) != SUCCESSFUL) { return err; } if ((err = _pfm->closeFile(ixfileHandle._overflowHandle)) != SUCCESSFUL) { return err; } return SUCCESSFUL; } RC IndexManager::insertEntry(IXFileHandle &ixfileHandle, const Attribute &attribute, const void *key, const RID &rid) { RC err; KeyValue keyValue(key, attribute.type); MetadataPage metadata(ixfileHandle._overflowHandle); if (!metadata.isInitialized()) { return ERR_METADATA_MISSING; } // Count the bucket number unsigned bucket = calcBucketNumber(keyValue, attribute, metadata); // __trace(); // cout << "bucket number: " << bucket << endl; // Check if the current bucket has been initialized, if not grow the bucket if (ixfileHandle._primaryHandle.getNumberOfPages() == 0) { if ((err = growToFit(ixfileHandle, metadata.getPrimaryPageCount(), attribute.type)) != SUCCESSFUL) { __trace(); return err; } } // __trace(); // Load all pages within this bucket vector<DataPage *> cachedPages; loadBucketChain(cachedPages, ixfileHandle, bucket, attribute.type); // __trace(); // Check whether the same <key, RID> pair already exists in the bucket for (size_t i = 0; i < cachedPages.size(); i++) { DataPage *curPage = cachedPages[i]; if (curPage->doExist(keyValue, rid)) { return ERR_DUPLICATE_ENTRY; } } // __trace(); // Check whether we need to insert a new overflow page // If not, just insert the entry bool inserted = false; if ((err = insertInternal(cachedPages, keyValue, rid, inserted)) != SUCCESSFUL) { __trace(); return err; } // cout << "Inserted in existing pages? " << inserted << endl; if (!inserted) { // Debug // cout << "Last Page: PageType: " << cachedPages.back()->getPageType() << ", Num: " // << cachedPages.back()->getPageNum() << ", Next: " << cachedPages.back()->getNextPageNum() << endl; // cout << "Bucket # to insert: " << bucket << endl; // Split bucket // Update metadata vector<DataPage *> oldCache; vector<DataPage *> newCache; unsigned p = metadata.getNextSplitBucket(); unsigned n = metadata.getCurrentBucketCount(); unsigned total = metadata.getPrimaryPageCount(); unsigned from = p, to = p + n; // two buckets we need to redistribute entries between if (++p == n) { p = 0; n = n << 1; } total++; metadata.setNextSplitBucket(p); metadata.setCurrentBucketCount(n); metadata.setPrimaryPageCount(total); // Load bucket to be split and reserve new spill bucket. loadBucketChain(oldCache, ixfileHandle, from, attribute.type); DataPage *newBucketPage = new DataPage(ixfileHandle._primaryHandle, PRIMARY_PAGE, attribute.type, total - 1, true); newCache.push_back(newBucketPage); // Redistribute entries between two buckets if ((err = rebalanceBetween(ixfileHandle, from, oldCache, to, newCache, metadata, attribute)) != SUCCESSFUL) { __trace(); return err; } // Check whether the bucket we split is the one we should insert entry into. if (from != bucket) { if ((err = appendInternal(cachedPages, keyValue, rid, metadata, ixfileHandle, attribute)) != SUCCESSFUL) { __trace(); return err; } } else { // Discard previous bucket cache for (unsigned i = 0; i < cachedPages.size(); i++) { cachedPages[i]->discard(); } // Recalculate bucket number according to updated metadata unsigned bkt = calcBucketNumber(keyValue, attribute, metadata); // cout << "New bucket # to insert: " << bkt << endl; if (bkt == from) { // __trace(); if ((err = insertIntoBucket(oldCache, keyValue, rid, metadata, ixfileHandle, attribute)) != SUCCESSFUL) { __trace(); return err; } // __trace(); } else if (bkt == to) { // __trace(); if ((err = insertIntoBucket(newCache, keyValue, rid, metadata, ixfileHandle, attribute)) != SUCCESSFUL) { __trace(); return err; } // __trace(); } else { __trace(); metadata.printMetadata(); return ERR_BAD_PAGE; } } // __trace(); // flush split and new bucket if ((err = flushBucketChain(oldCache)) != SUCCESSFUL) { __trace(); return err; } // __trace(); if ((err = flushBucketChain(newCache)) != SUCCESSFUL) { __trace(); metadata.printMetadata(); return err; } // __trace(); } if ((err = flushBucketChain(cachedPages)) != SUCCESSFUL) { __trace(); return err; } // __trace(); // Update total entries count metadata.setEntryCount(metadata.getEntryCount() + 1); // __trace(); // cout << "Inserted: " << keyValue.toString() << endl; // metadata.flush(); // __trace(); // printIndexEntriesInAPage(ixfileHandle, attribute, bucket); return SUCCESSFUL; } RC IndexManager::deleteEntry(IXFileHandle &ixfileHandle, const Attribute &attribute, const void *key, const RID &rid) { RC err; KeyValue keyValue(key, attribute.type); MetadataPage metadata(ixfileHandle._overflowHandle); if (!metadata.isInitialized()) { __trace(); return ERR_METADATA_MISSING; } // Count the bucket number unsigned bucket = calcBucketNumber(keyValue, attribute, metadata); // Check if the current bucket has been initialized, if not grow the bucket if (ixfileHandle._primaryHandle.getNumberOfPages() == 0) { if ((err = growToFit(ixfileHandle, metadata.getPrimaryPageCount(), attribute.type)) != SUCCESSFUL) { __trace(); return err; } } // Load all pages within this bucket and delete bool deleted = false; vector<DataPage *> cachedPages; loadBucketChain(cachedPages, ixfileHandle, bucket, attribute.type); for (size_t i = 0; i < cachedPages.size(); i++) { DataPage *p = cachedPages[i]; if ((err = p->remove(keyValue, rid)) == SUCCESSFUL) { deleted = true; break; } if (err != ERR_ENTRY_NOT_FOUND) { __trace(); return err; } } if (!deleted) { __trace(); return ERR_ENTRY_NOT_FOUND; } // Rearrange pages within a page once finding an empty page bool emptyBucket = false; rebalanceWithin(ixfileHandle, bucket, cachedPages, emptyBucket, metadata); // flush bucket if ((err = flushBucketChain(cachedPages)) != SUCCESSFUL) { __trace(); return err; } // Update metadata and shrink buckets if possible unsigned p = metadata.getNextSplitBucket(); unsigned n = metadata.getCurrentBucketCount(); unsigned total = metadata.getPrimaryPageCount(); unsigned init = metadata.getInitialBucketCount(); for (unsigned i = total - 1; i >= init; i--) { vector<DataPage *> cache; loadBucketChain(cache, ixfileHandle, i, attribute.type); bool empty = isEmptyBucket(cache); if ((err = flushBucketChain(cache)) != SUCCESSFUL) { __trace(); return err; } if (!empty) { break; } else { __trace(); // Shrink the bucket total--; if (p == 0) { n >>= 1; p = n - 1; } else { p--; } } } metadata.setNextSplitBucket(p); metadata.setCurrentBucketCount(n); metadata.setPrimaryPageCount(total); metadata.setEntryCount(metadata.getEntryCount() - 1); return SUCCESSFUL; } unsigned IndexManager::hash(const Attribute &attribute, const void *key) { KeyValue keyVal(key, attribute.type); return keyVal.hashCode(); } RC IndexManager::printIndexEntriesInAPage(IXFileHandle &ixfileHandle, const Attribute &attribute, const unsigned &primaryPageNumber) { // __trace(); RC err; MetadataPage metadata(ixfileHandle._overflowHandle); unsigned total = metadata.getPrimaryPageCount(); if (primaryPageNumber >= total) { return ERR_OUT_OF_BOUND; } vector<DataPage *> cachedPages; loadBucketChain(cachedPages, ixfileHandle, primaryPageNumber, attribute.type); // Total entries cout << "Number of total entries: " << metadata.getEntryCount() << endl; // Print primary page DataPage *primary = cachedPages[0]; cout << "Primary Page No. " << primary->getPageNum() << endl; if ((err = printEntries(primary)) != SUCCESSFUL) { __trace(); return err; } // Print overflow pages bool lastPrimary = true; unsigned lastPage = primary->getPageNum(); for (unsigned i = 1; i < cachedPages.size(); i++) { DataPage *overflow = cachedPages[i]; cout << "Overflow Page No. " << overflow->getPageNum() << " lined to "; if (lastPrimary) { cout << "primary page " << lastPage << endl; lastPrimary = false; } else { cout << "overflow page " << lastPage << endl; } lastPage = overflow->getPageNum(); if ((err = printEntries(overflow)) != SUCCESSFUL) { __trace(); return err; } } return SUCCESSFUL; } RC IndexManager::printEntries(DataPage *page) { RC err; cout << "\ta. # of entries: " << page->getEntriesCount() << endl; cout << "\tb. entries: "; for (unsigned i = 0; i < page->getEntriesCount(); i++) { KeyValue key; RID rid; if ((err = page->keyAt(i, key)) != SUCCESSFUL) { __trace(); return err; } if ((err = page->ridAt(i, rid)) != SUCCESSFUL) { __trace(); return err; } cout << "[" << key.toString() << "|" << rid.pageNum << "," << rid.slotNum << "] "; } cout << endl; return SUCCESSFUL; } RC IndexManager::getNumberOfPrimaryPages(IXFileHandle &ixfileHandle, unsigned &numberOfPrimaryPages) { MetadataPage metadata(ixfileHandle._overflowHandle); numberOfPrimaryPages = metadata.getPrimaryPageCount(); return SUCCESSFUL; } RC IndexManager::getNumberOfAllPages(IXFileHandle &ixfileHandle, unsigned &numberOfAllPages) { MetadataPage metadata(ixfileHandle._overflowHandle); numberOfAllPages = metadata.getPrimaryPageCount(); if (metadata.getOverflowPageCount() < metadata.getDelOverflowPageCount()) { __trace(); cout << "Overflow page #: " << metadata.getOverflowPageCount() << " Deleted #: " << metadata.getDelOverflowPageCount() << endl; return ERR_METADATA_ERROR; } numberOfAllPages += metadata.getOverflowPageCount() - metadata.getDelOverflowPageCount(); numberOfAllPages++; // metadata page return SUCCESSFUL; } RC IndexManager::scan(IXFileHandle &ixfileHandle, const Attribute &attribute, const void *lowKey, const void *highKey, bool lowKeyInclusive, bool highKeyInclusive, IX_ScanIterator &ix_ScanIterator) { RC err; MetadataPage metadata(ixfileHandle._overflowHandle); if (!metadata.isInitialized()) { return ERR_METADATA_MISSING; } // Check if the current bucket has been initialized, if not grow the bucket if (ixfileHandle._primaryHandle.getNumberOfPages() == 0) { if ((err = growToFit(ixfileHandle, metadata.getPrimaryPageCount(), attribute.type)) != SUCCESSFUL) { return err; } } ix_ScanIterator._ixm = IndexManager::instance(); ix_ScanIterator._active = true; ix_ScanIterator._ixFileHandle = ixfileHandle; ix_ScanIterator._lowInclusive = lowKeyInclusive; ix_ScanIterator._highInclusive = highKeyInclusive; ix_ScanIterator._hasLowerBound = (lowKey != nullptr); ix_ScanIterator._hasUpperBound = (highKey != nullptr); if (ix_ScanIterator._hasLowerBound) { ix_ScanIterator._lowKey = KeyValue(lowKey, attribute.type); } if (ix_ScanIterator._hasUpperBound) { ix_ScanIterator._highKey = KeyValue(highKey, attribute.type); } ix_ScanIterator._keyType = attribute.type; if ((lowKeyInclusive == highKeyInclusive) && ix_ScanIterator._hasLowerBound && ix_ScanIterator._hasUpperBound && ix_ScanIterator._lowKey.compare(ix_ScanIterator._highKey) == 0) { ix_ScanIterator._scanType = HASH_SCAN; ix_ScanIterator._curBucketNum = calcBucketNumber(ix_ScanIterator._lowKey, attribute, metadata); ix_ScanIterator._curPageIndex = 0; ix_ScanIterator._curHashIndex = 0; } else { ix_ScanIterator._scanType = RANGE_SCAN; ix_ScanIterator._curBucketNum = 0; ix_ScanIterator._curPageIndex = 0; ix_ScanIterator._curRangeIndex = 0; } ix_ScanIterator._totalBucketNum = metadata.getPrimaryPageCount(); ix_ScanIterator._curBucket.clear(); return SUCCESSFUL; } void IndexManager::loadBucketChain(vector<DataPage *> &buf, IXFileHandle &ixfileHandle, unsigned bucketNum, const AttrType &keyType) { // __trace(); // cout << "Load bucket: " << bucketNum << endl; DataPage *primary = new DataPage(ixfileHandle._primaryHandle, PRIMARY_PAGE, keyType, bucketNum, false); buf.push_back(primary); // cout << "\tPushed a primary page: pageNum: " << bucketNum << endl; DataPage *curPage = primary; unsigned nextPageNum = PAGE_END; while ((nextPageNum = curPage->getNextPageNum()) != PAGE_END) { // cout << "\tPushed an overflow page: pageNum: " << nextPageNum; DataPage *overflow = new DataPage(ixfileHandle._overflowHandle, OVERFLOW_PAGE, keyType, nextPageNum, false); buf.push_back(overflow); curPage = overflow; // cout << " (Pushed)" << endl; } } RC IndexManager::flushBucketChain(vector<DataPage *> &buf) { // __trace(); // cout << "We have " << buf.size() << " page(s) to flush" << endl; RC err; for (size_t i = 0; i < buf.size(); i++) { // buf[i]->printMetadata(); if ((err = buf[i]->flush()) != SUCCESSFUL) { __trace(); cout << "Error: flush page (i = " << i << " of " << buf.size() << ")" << endl; cout << "Dump the whole bucket: " << endl; for (size_t j = 0; j < buf.size(); j++) { cout << "*** i = " << j << endl; buf[j]->printMetadata(); } return err; } delete buf[i]; } return SUCCESSFUL; } RC IndexManager::rebalanceBetween(IXFileHandle &ixfileHandle, unsigned oldBucket, vector<DataPage *> &oldCache, unsigned newBucket, vector<DataPage *> &newCache, MetadataPage &metadata, const Attribute &attribute) { // __trace(); // cout << "Old bucket #" << oldBucket << ", newBucket #" << newBucket << endl; RC err; unsigned cur = 0; vector<DataPage *> updatedCache; // Create an empty old primary page DataPage *op = oldCache[cur]; AttrType keyType = op->getKeyType(); updatedCache.push_back(new DataPage(ixfileHandle._primaryHandle, PRIMARY_PAGE, keyType, op->getPageNum(), true)); // Redistribute data for (size_t i = 0; i < oldCache.size(); i++) { DataPage *curPage = oldCache[i]; // cout << "PageType: " << curPage->getPageType() << ", pageNum: " // << curPage->getPageNum() << endl; unsigned entriesCount = curPage->getEntriesCount(); for (unsigned j = 0; j < entriesCount; j++) { KeyValue key; RID rid; curPage->keyAt(j, key); curPage->ridAt(j, rid); unsigned bucket = calcBucketNumber(key, attribute, metadata); // cout << "key: " << key.toString() << ", hash: " << key.hashCode() << " new: " << bucket << endl; // cout << " ** [" << key.toString() << "|" << rid.pageNum // << "," << rid.slotNum << "] redistribute to " << bucket << endl; if (bucket == oldBucket) { if (!updatedCache[cur]->hasSpace(key)) { DataPage *dp = oldCache[++cur]; // Index should not be out of bound here updatedCache.back()->setNextPageNum(dp->getPageNum()); updatedCache.push_back(new DataPage(ixfileHandle._overflowHandle, OVERFLOW_PAGE, keyType, dp->getPageNum(), true)); } updatedCache[cur]->insert(key, rid); } else if (bucket == newBucket) { if (!newCache.back()->hasSpace(key)) { unsigned overflowPageCount = metadata.getOverflowPageCount(); DataPage *dp = new DataPage(ixfileHandle._overflowHandle, OVERFLOW_PAGE, keyType, ++overflowPageCount, true); newCache.back()->setNextPageNum(dp->getPageNum()); newCache.push_back(dp); metadata.setOverflowPageCount(overflowPageCount); } newCache.back()->insert(key, rid); } else { __trace(); metadata.printMetadata(); cout << "New bucket: " << bucket << endl; cout << "key: " << key.toString() << ", hash: " << key.hashCode() << endl; curPage->printMetadata(); return ERR_BAD_PAGE; } } curPage->discard(); } // Discard old cache using new cache instead // Count the deleted overflow pages unsigned deleted = metadata.getDelOverflowPageCount(); deleted += oldCache.size() - updatedCache.size(); metadata.setDelOverflowPageCount(deleted); if ((err = flushBucketChain(oldCache)) != SUCCESSFUL) { __trace(); return err; } oldCache = updatedCache; // __trace(); return SUCCESSFUL; } RC IndexManager::rebalanceWithin(IXFileHandle &ixfileHandle, unsigned bucket, vector<DataPage *> &cache, bool &emptyBucket, MetadataPage &metadata) { unsigned deleted = 0; // Check whether the bucket is empty emptyBucket = isEmptyBucket(cache); if (emptyBucket) { return SUCCESSFUL; } // Redistribute data if (cache.size() > 1) { DataPage *before = cache[0], *after = cache[1]; if (before->getEntriesCount() == 0) { __trace(); // cout << "Before rebalance: before->next: " << before->getNextPageNum() // << ", after->count: " << after->getEntriesCount() << endl; before->_keys = after->_keys; before->_rids = after->_rids; before->setNextPageNum(after->getNextPageNum()); before->setEntriesCount(after->getEntriesCount()); before->setEntriesSize(after->getEntriesSize()); after->discard(); deleted++; // cout << "After rebalance: before->next: " << before->getNextPageNum() // << ", before->count: " << before->getEntriesCount() << endl; } else { for (size_t i = 1; i < cache.size(); i++) { if (cache[i]->getEntriesCount() == 0) { // __trace(); cache[i-1]->setNextPageNum(cache[i]->getNextPageNum()); cache[i]->discard(); deleted++; break; } } } } metadata.setDelOverflowPageCount(metadata.getDelOverflowPageCount() + deleted); return SUCCESSFUL; } RC IndexManager::insertInternal(vector<DataPage *> &cachedPages, KeyValue &keyValue, const RID &rid, bool &inserted) { RC err; inserted = false; for (size_t i = 0; i < cachedPages.size(); i++) { DataPage *curPage = cachedPages[i]; // cout << "+ i = " << i << " Cached Page #" << curPage->getPageNum() << endl; if (curPage->hasSpace(keyValue)) { if ((err = curPage->insert(keyValue, rid)) != SUCCESSFUL) { return err; } else { inserted = true; break; } } } return SUCCESSFUL; } RC IndexManager::appendInternal(vector<DataPage *> &cachedPages, KeyValue &keyValue, const RID &rid, MetadataPage &metadata, IXFileHandle &ixfileHandle, const Attribute &attribute) { RC err; unsigned overflowPageCount = metadata.getOverflowPageCount(); DataPage *newPage = new DataPage(ixfileHandle._overflowHandle, OVERFLOW_PAGE, attribute.type, ++overflowPageCount, true); cachedPages.back()->setNextPageNum(overflowPageCount); cachedPages.push_back(newPage); metadata.setOverflowPageCount(overflowPageCount); if ((err = newPage->insert(keyValue, rid)) != SUCCESSFUL) { return err; } return SUCCESSFUL; } RC IndexManager::insertIntoBucket(vector<DataPage *> &cachedPages, KeyValue &keyValue, const RID &rid, MetadataPage &metadata, IXFileHandle &ixfileHandle, const Attribute &attribute) { RC err; bool ins = false; if ((err = insertInternal(cachedPages, keyValue, rid, ins)) != SUCCESSFUL) { __trace(); return err; } if (!ins) { if ((err = appendInternal(cachedPages, keyValue, rid, metadata, ixfileHandle, attribute)) != SUCCESSFUL) { __trace(); return err; } } return SUCCESSFUL; } bool IndexManager::isEmptyBucket(vector<DataPage *> &cache) { for (unsigned i = 0; i < cache.size(); i++) { if (cache[i]->getEntriesCount() != 0) { return false; } if (cache[i]->getNextPageNum() == PAGE_END) { return true; } } __trace(); // Not reach (pages should end with PAGE_END) return true; } RC IndexManager::growToFit(IXFileHandle &ixfileHandle, unsigned pageNum, const AttrType &keyType) { unsigned start = ixfileHandle._primaryHandle.getNumberOfPages(); // __trace(); // cout << "start: " << start << " pageNum: " << pageNum << endl; RC err; for (unsigned i = start; i < pageNum; i++) { // cout << "Initializing " << i << endl; DataPage dp(ixfileHandle._primaryHandle, PRIMARY_PAGE, (AttrType &) keyType, i, true); if ((err = dp.flush()) != SUCCESSFUL) { __trace(); return err; } } return SUCCESSFUL; } unsigned IndexManager::calcBucketNumber(KeyValue &keyValue, const Attribute &attribute, MetadataPage &metadata) { unsigned hashVal = keyValue.hashCode(); unsigned p = metadata.getNextSplitBucket(); unsigned n = metadata.getCurrentBucketCount(); unsigned bucket = hashVal & (n - 1); if (bucket < p) { bucket = hashVal & ((n << 1) - 1); } return bucket; } // IX Scan Iterator implementations IX_ScanIterator::IX_ScanIterator() { this->_active = true; } IX_ScanIterator::~IX_ScanIterator() { } RC IX_ScanIterator::getNextEntry(RID &rid, void *key) { if (_scanType == HASH_SCAN) { return getNextHashMatch(rid, key); } else if (_scanType == RANGE_SCAN) { return getNextRangeMatch(rid, key); } else { return IX_EOF; } } RC IX_ScanIterator::close() { this->_active = false; return SUCCESSFUL; } RC IX_ScanIterator::getNextHashMatch(RID &rid, void *key) { RC err; if (_curBucket.empty()) { _ixm->loadBucketChain(_curBucket, _ixFileHandle, _curBucketNum, _keyType); } while (_curPageIndex < _curBucket.size()) { DataPage *page = _curBucket[_curPageIndex]; vector<int> indexes; page->findKeyIndexes(_lowKey, indexes); if (_curHashIndex >= indexes.size()) { _curHashIndex = 0; _curPageIndex++; } else { // found one entry _lowKey.getRaw(key); if (page->ridAt(indexes[_curHashIndex++], rid) != SUCCESSFUL) { // error should not happen __trace(); return IX_EOF; } return SUCCESSFUL; } } if ((err = _ixm->flushBucketChain(_curBucket)) != SUCCESSFUL) { __trace(); return err; } _curBucket.clear(); return IX_EOF; } RC IX_ScanIterator::getNextRangeMatch(RID &rid, void *key) { RC err; while (_curBucketNum < _totalBucketNum) { if (_curBucket.empty()) { _ixm->loadBucketChain(_curBucket, _ixFileHandle, _curBucketNum, _keyType); } while (_curPageIndex < _curBucket.size()) { DataPage *page = _curBucket[_curPageIndex]; unsigned count = page->getEntriesCount(); bool found = false; for (; _curRangeIndex < count && !found; _curRangeIndex++) { KeyValue keyVal; // Fetch the key if (page->keyAt(_curRangeIndex, keyVal) != SUCCESSFUL) { __trace(); return IX_EOF; } // Compare with lower bound if (_hasLowerBound) { if ((_lowInclusive && _lowKey.compare(keyVal) > 0) || (!_lowInclusive && _lowKey.compare(keyVal) >= 0)) { continue; } } // Compare with upper bound if (_hasUpperBound) { if ((_highInclusive && _highKey.compare(keyVal) < 0) || (!_highInclusive && _highKey.compare(keyVal) <= 0)) { continue; } } // OK now the key is within the range keyVal.getRaw(key); if (page->ridAt(_curRangeIndex, rid) != SUCCESSFUL) { // error should not happen __trace(); return IX_EOF; } found = true; } if (found) { return SUCCESSFUL; } else { _curPageIndex++; _curRangeIndex = 0; } } if ((err = _ixm->flushBucketChain(_curBucket)) != SUCCESSFUL) { __trace(); return err; } _curBucket.clear(); _curBucketNum++; _curPageIndex = 0; } return IX_EOF; } IXFileHandle::IXFileHandle() { } IXFileHandle::~IXFileHandle() { } RC IXFileHandle::collectCounterValues(unsigned &readPageCount, unsigned &writePageCount, unsigned &appendPageCount) { unsigned rc = 0, wc = 0, ac = 0; readPageCount = writePageCount = appendPageCount = 0; _primaryHandle.collectCounterValues(rc, wc, ac); // __trace(); // cout << "Primary: rc " << rc << " wc " << wc << " ac " << ac << endl; readPageCount += rc; writePageCount += wc; appendPageCount += ac; _overflowHandle.collectCounterValues(rc, wc, ac); // cout << "Overflow: rc " << rc << " wc " << wc << " ac " << ac << endl; readPageCount += rc; writePageCount += wc; appendPageCount += ac; return SUCCESSFUL; } void IX_PrintError (RC rc) { } // MetadataPage implementations MetadataPage::MetadataPage(FileHandle &handle) : _fileHandle(handle), _dirty(false) { // __trace(); if (_fileHandle.getNumberOfPages() == 0) { // __trace(); _initialized = false; } else { _initialized = true; RC rc = load(); assert(rc == SUCCESSFUL); } // __trace(); } MetadataPage::~MetadataPage() { // __trace(); if (_dirty) { RC err = flush(); assert(err == SUCCESSFUL); } // __trace(); } RC MetadataPage::initialize(const unsigned &numberOfPages) { if (_initialized) { return ERR_INV_OPERATION; } _entryCount = 0; _primaryPageCount = numberOfPages; _overflowPageCount = 0; _delOverflowPageCount = 0; _currentBucketCount = numberOfPages; _nextSplitBucket = 0; _initialBucketCount = numberOfPages; _initialized = true; _dirty = true; return SUCCESSFUL; } RC MetadataPage::load() { // __trace(); RC err; char page[PAGE_SIZE]; if ((err = _fileHandle.readPage(0, page)) != SUCCESSFUL) { __trace(); return err; } int offset = 0; memcpy((char *) &_entryCount, page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &_primaryPageCount, page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &_overflowPageCount, page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &_delOverflowPageCount, page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &_currentBucketCount, page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &_nextSplitBucket, page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &_initialBucketCount, page + offset, sizeof(int)); offset += sizeof(int); // printMetadata(); return SUCCESSFUL; } RC MetadataPage::flush() { if (_dirty) { RC err; char page[PAGE_SIZE]; int offset = 0; memcpy(page + offset, (char *) &_entryCount, sizeof(int)); offset += sizeof(int); memcpy(page + offset, (char *) &_primaryPageCount, sizeof(int)); offset += sizeof(int); memcpy(page + offset, (char *) &_overflowPageCount, sizeof(int)); offset += sizeof(int); memcpy(page + offset, (char *) &_delOverflowPageCount, sizeof(int)); offset += sizeof(int); memcpy(page + offset, (char *) &_currentBucketCount, sizeof(int)); offset += sizeof(int); memcpy(page + offset, (char *) &_nextSplitBucket, sizeof(int)); offset += sizeof(int); memcpy(page + offset, (char *) &_initialBucketCount, sizeof(int)); offset += sizeof(int); if ((err = _fileHandle.writePage(0, page)) != SUCCESSFUL) { __trace(); return err; } _dirty = false; } return SUCCESSFUL; } void MetadataPage::printMetadata() { cout << "===== Metadata =====" << endl; cout << "_entryCount: " << _entryCount << endl; cout << "_primaryPageCount: " << _primaryPageCount << endl; cout << "_overflowPageCount: " << _overflowPageCount << endl; cout << "_delOverflowPageCount: " << _delOverflowPageCount << endl; cout << "_currentBucketCount: " << _currentBucketCount << endl; cout << "_nextSplitBucket: " << _nextSplitBucket << endl; cout << "_initialBucketCount: " << _initialBucketCount << endl; cout << "====================" << endl; } unsigned MetadataPage::getEntryCount() { return _entryCount; } void MetadataPage::setEntryCount(unsigned entryCount) { _dirty = true; _entryCount = entryCount; } unsigned MetadataPage::getPrimaryPageCount() { return _primaryPageCount; } void MetadataPage::setPrimaryPageCount(unsigned primaryPageCount) { _dirty = true; _primaryPageCount = primaryPageCount; } unsigned MetadataPage::getOverflowPageCount() { return _overflowPageCount; } void MetadataPage::setOverflowPageCount(unsigned overflowPageCount) { _dirty = true; _overflowPageCount = overflowPageCount; } unsigned MetadataPage::getDelOverflowPageCount() { return _delOverflowPageCount; } void MetadataPage::setDelOverflowPageCount(unsigned delOverflowPageCount) { _dirty = true; _delOverflowPageCount = delOverflowPageCount; } unsigned MetadataPage::getCurrentBucketCount() { return _currentBucketCount; } void MetadataPage::setCurrentBucketCount(unsigned currentBucketCount) { _dirty = true; _currentBucketCount = currentBucketCount; } unsigned MetadataPage::getNextSplitBucket() { return _nextSplitBucket; } void MetadataPage::setNextSplitBucket(unsigned nextSplitBucket) { _dirty = true; _nextSplitBucket = nextSplitBucket; } unsigned MetadataPage::getInitialBucketCount() { return _initialBucketCount; } bool MetadataPage::isInitialized() { return _initialized; } void MetadataPage::setInitialized(bool initialized) { _dirty = true; _initialized = initialized; } // Implementations of class DataPage DataPage::DataPage(FileHandle &fileHandle, PageType pageType, AttrType keyType, unsigned pageNum, bool newPage) : _fileHandle(fileHandle), _pageType(pageType), _keyType(keyType), _pageNum(pageNum), _dirty(false), _discarded(false) { RC err; // __trace(); if (newPage) { // __trace(); initialize(); } else { // __trace(); err = load(); assert(err == SUCCESSFUL); } // __trace(); } DataPage::~DataPage() { // __trace(); RC err = flush(); assert(err == SUCCESSFUL); // __trace(); } RC DataPage::initialize() { _entriesCount = 0; _entriesSize = 0; _nextPageNum = PAGE_END; _keys.clear(); _rids.clear(); _entryMap.clear(); _dirty = true; _discarded = false; return SUCCESSFUL; } RC DataPage::load() { RC err; char page[PAGE_SIZE]; if ((err = _fileHandle.readPage(_pageNum, page)) != SUCCESSFUL) { __trace(); return err; } // load all information from the page loadMetadata(page); deserializeData(page); // build the hash map for (size_t i = 0; i < _keys.size(); i++) { _entryMap[_keys[i].toString()].push_back(i); } // printMetadata(); return SUCCESSFUL; } RC DataPage::flush() { if (!_dirty || _discarded) { // __trace(); return SUCCESSFUL; } RC err; char page[PAGE_SIZE]; wireMetadata(page); serializeData(page); if ((err = _fileHandle.writePage(_pageNum, page)) != SUCCESSFUL) { __trace(); return err; } _dirty = false; return SUCCESSFUL; } void DataPage::discard() { _discarded = true; } RC DataPage::keyAt(unsigned index, KeyValue &key) { if (index >= _entriesCount) { return ERR_OUT_OF_BOUND; } key = _keys[index]; return SUCCESSFUL; } RC DataPage::ridAt(unsigned index, RID &rid) { if (index >= _entriesCount) { return ERR_OUT_OF_BOUND; } rid = _rids[index]; return SUCCESSFUL; } RC DataPage::findKeyIndexes(KeyValue &key, vector<int> &indexes) { string keystr = key.toString(); if (_entryMap.count(keystr) != 0) { indexes = _entryMap[keystr]; } return SUCCESSFUL; } bool DataPage::hasSpace(KeyValue &key) { // __trace(); size_t esize = entrySize(key); // cout << "\tCurrentEntrySize: " << _entriesSize << ", new: " << esize << endl; return esize + _entriesSize < PAGE_SIZE - 6 * META_UNIT; } bool DataPage::doExist(KeyValue &key, const RID &rid) { string keystr = key.toString(); if (_entryMap.count(keystr) != 0) { vector<int> &indexes = _entryMap[keystr]; for (size_t i = 0; i < indexes.size(); i++) { if (_rids[indexes[i]] == rid) { return true; } } } return false; } RC DataPage::insert(KeyValue &key, const RID &rid) { int idx = static_cast<int>(_keys.size()); size_t esize = entrySize(key); if (!hasSpace(key)) { return ERR_NO_SPACE; } _keys.push_back(key); _rids.push_back(rid); _entryMap[key.toString()].push_back(idx); _entriesSize += esize; _entriesCount++; _dirty = true; return SUCCESSFUL; } RC DataPage::remove(KeyValue &key, const RID &rid) { vector<int> indexes; string keyStr = key.toString(); if (_entryMap.count(keyStr) > 0) { indexes = _entryMap[keyStr]; } bool found = false; int idx; for (size_t i = 0; i < indexes.size(); i++) { if (_rids[indexes[i]] == rid) { idx = static_cast<int>(i); found = true; break; } } if (!found) { return ERR_ENTRY_NOT_FOUND; } _keys.erase(_keys.begin() + indexes[idx]); _rids.erase(_rids.begin() + indexes[idx]); _entryMap[keyStr].erase(_entryMap[keyStr].begin() + idx); if (_entryMap[keyStr].size() == 0) { _entryMap.erase(keyStr); } size_t esize = entrySize(key); _entriesSize -= esize; _entriesCount--; _dirty = true; return SUCCESSFUL; } void DataPage::printMetadata() { cout << "===== DataPage =====" << endl; cout << "_pageType: " << _pageType << endl; cout << "_keyType: " << _keyType << endl; cout << "_pageNum: " << _pageNum << endl; cout << "_entriesCount: " << _entriesCount << endl; cout << "_entriesSize: " << _entriesSize << endl; cout << "_nextPageNum: " << _nextPageNum << endl; cout << "====================" << endl; } PageType DataPage::getPageType() { return _pageType; } void DataPage::setPageType(PageType pageType) { _dirty = true; _pageType = pageType; } AttrType DataPage::getKeyType() { return _keyType; } void DataPage::setKeyType(AttrType keyType) { _dirty = true; _keyType = keyType; } unsigned DataPage::getPageNum() { return _pageNum; } void DataPage::setPageNum(unsigned pageNum) { _dirty = true; _pageNum = pageNum; } unsigned DataPage::getEntriesCount() { return _entriesCount; } void DataPage::setEntriesCount(unsigned entriesCount) { _dirty = true; _entriesCount = entriesCount; } unsigned DataPage::getEntriesSize() { return _entriesSize; } void DataPage::setEntriesSize(unsigned entriesSize) { _dirty = true; _entriesSize = entriesSize; } unsigned DataPage::getNextPageNum() { return _nextPageNum; } void DataPage::setNextPageNum(unsigned nextPageNum) { _dirty = true; _nextPageNum = nextPageNum; } void DataPage::wireMetadata(void *page) { memcpy((char *) page + (PAGE_SIZE - META_UNIT), (char *) &_pageType, META_UNIT); memcpy((char *) page + (PAGE_SIZE - META_UNIT * 2), (char *) &_keyType, META_UNIT); memcpy((char *) page + (PAGE_SIZE - META_UNIT * 3), (char *) &_pageNum, META_UNIT); memcpy((char *) page + (PAGE_SIZE - META_UNIT * 4), (char *) &_entriesCount, META_UNIT); memcpy((char *) page + (PAGE_SIZE - META_UNIT * 5), (char *) &_entriesSize, META_UNIT); memcpy((char *) page + (PAGE_SIZE - META_UNIT * 6), (char *) &_nextPageNum, META_UNIT); } void DataPage::loadMetadata(void *page) { memcpy((char *) &_pageType, (char *) page + (PAGE_SIZE - META_UNIT), META_UNIT); memcpy((char *) &_keyType, (char *) page + (PAGE_SIZE - META_UNIT * 2), META_UNIT); memcpy((char *) &_pageNum, (char *) page + (PAGE_SIZE - META_UNIT * 3), META_UNIT); memcpy((char *) &_entriesCount, (char *) page + (PAGE_SIZE - META_UNIT * 4), META_UNIT); memcpy((char *) &_entriesSize, (char *) page + (PAGE_SIZE - META_UNIT * 5), META_UNIT); memcpy((char *) &_nextPageNum, (char *) page + (PAGE_SIZE - META_UNIT * 6), META_UNIT); } void DataPage::serializeData(void *page) { size_t offset = 0; // Here we assume that # of keys and RIDs are the same. (It should be!) for (size_t i = 0; i < _keys.size(); i++) { char buf[PAGE_SIZE]; // key size_t keysize = _keys[i].size(); _keys[i].getRaw(buf); memcpy((char *) page + offset, (char *) buf, keysize); offset += keysize; // RID RID rid = _rids[i]; memcpy((char *) page + offset, (char *) &(rid.pageNum), sizeof(int)); offset += sizeof(int); memcpy((char *) page + offset, (char *) &(rid.slotNum), sizeof(int)); offset += sizeof(int); } if (offset > PAGE_SIZE - 6 * META_UNIT) { __trace(); // error case } } void DataPage::deserializeData(void *page) { size_t offset = 0; for (size_t i = 0; i < _entriesCount; i++) { char buf[PAGE_SIZE]; // key switch (_keyType) { case TypeInt: memcpy((char *) &buf, (char *) page + offset, sizeof(int)); offset += sizeof(int); break; case TypeReal: memcpy((char *) &buf, (char *) page + offset, sizeof(float)); offset += sizeof(float); break; case TypeVarChar: int size; memcpy((char *) &size, (char *) page + offset, sizeof(int)); if (size < 0 || size > PAGE_SIZE) { __trace(); cout << "Invalid size: " << size << " at i = " << i << endl; } memcpy((char *) buf, (char *) page + offset, sizeof(int) + size); // copy whole data offset += (sizeof(int) + size); break; default: __trace(); break; } // rid RID rid; memcpy((char *) &(rid.pageNum), (char *) page + offset, sizeof(int)); offset += sizeof(int); memcpy((char *) &(rid.slotNum), (char *) page + offset, sizeof(int)); offset += sizeof(int); _keys.push_back(KeyValue(buf, _keyType)); _rids.push_back(rid); } } size_t DataPage::entrySize(KeyValue &key) { size_t keysize = key.size(); return keysize + 2 * sizeof(int); }
30.471154
132
0.584073
[ "vector" ]
5ce053aa0c45af3f93224d04398317beb8ed7a81
1,414
cpp
C++
day06/part_2.cpp
jgriemsmann/adventofcode
415c0e74100045281e88fc3034bca489f07f337f
[ "MIT" ]
null
null
null
day06/part_2.cpp
jgriemsmann/adventofcode
415c0e74100045281e88fc3034bca489f07f337f
[ "MIT" ]
null
null
null
day06/part_2.cpp
jgriemsmann/adventofcode
415c0e74100045281e88fc3034bca489f07f337f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <set> unsigned calcSumOfCommonGroupAnswers(const std::set<char>& uniqueGroupAnswers, const std::vector<std::string>& personAnswers) { unsigned sumOfCommonGroupAnswers = 0; for (auto it_group = uniqueGroupAnswers.begin(); it_group != uniqueGroupAnswers.end(); ++it_group) { unsigned commonAnswers = 0; for (auto it_person = personAnswers.begin(); it_person != personAnswers.end(); ++it_person) { if ((*it_person).find(*it_group) != std::string::npos) { commonAnswers++; } } if (commonAnswers == personAnswers.size()) { sumOfCommonGroupAnswers++; } } return sumOfCommonGroupAnswers; } int main() { std::string line; std::set<char> uniqueGroupAnswers; unsigned sumOfCommonGroupAnswers = 0; std::vector<std::string> personAnswers; while(getline(std::cin, line)) { if (line.empty()) { sumOfCommonGroupAnswers += calcSumOfCommonGroupAnswers(uniqueGroupAnswers, personAnswers); uniqueGroupAnswers.clear(); personAnswers.clear(); } else { personAnswers.push_back(line); for (auto it = line.begin(); it != line.end(); ++it) { uniqueGroupAnswers.insert(*it); } } } sumOfCommonGroupAnswers += calcSumOfCommonGroupAnswers(uniqueGroupAnswers, personAnswers); std::cout << "Sum of group answers: " << sumOfCommonGroupAnswers << std::endl; return 0; }
33.666667
127
0.682461
[ "vector" ]
5ce54782a5687a2c83ada4c6ffdded51f5477768
6,826
cpp
C++
SSLServer/SSLServer/main.cpp
shanpark/Shan.Lib
a57de39a026788ddf67e5c2dbb4cae2f3ec62396
[ "BSD-2-Clause" ]
1
2017-05-05T03:05:18.000Z
2017-05-05T03:05:18.000Z
SSLServer/SSLServer/main.cpp
shanpark/Shan.Lib
a57de39a026788ddf67e5c2dbb4cae2f3ec62396
[ "BSD-2-Clause" ]
null
null
null
SSLServer/SSLServer/main.cpp
shanpark/Shan.Lib
a57de39a026788ddf67e5c2dbb4cae2f3ec62396
[ "BSD-2-Clause" ]
null
null
null
// // main.cpp // SSLServer // // Created by Sung Han Park on 2017. 4. 10.. // Copyright © 2017 Sung Han Park. All rights reserved. // #include <iostream> #include <stdio.h> #include <iostream> #include <ctime> #include <shan/net_ssl.h> #include <shan/util/pool.h> using namespace std; using namespace shan::net; class unix_time : public shan::object { public: unix_time(std::time_t time) { _time = time; } std::time_t get_time() { return _time; } public: std::time_t _time; }; std::mutex _mutex; int exc = 0; int accpt = 0; int conn = 0; int dis_conn = 0; int wt = 0; class acpt_handler_s : public acceptor_handler { virtual void user_event(acceptor_context* ctx) override { std::lock_guard<std::mutex> _lock(_mutex); cout << "acpt_handler::" << "user_event() called" << endl; } virtual void exception_caught(acceptor_context* ctx, const std::exception& e) override { std::lock_guard<std::mutex> _lock(_mutex); cout << "acpt_handler::" << "exception_caught() - " << e.what() << "@@@@@@@@@@@@@@@@@@@@@" << endl; exc++; } virtual void channel_accepted(acceptor_context* ctx, const std::string& address, uint16_t port) override { std::lock_guard<std::mutex> _lock(_mutex); cout << "acpt_handler::" << "channel_accepted() - " << "connection from '" << address << ":" << port << "'" << endl; accpt++; } }; class channel_coder_s : public tcp_channel_handler { virtual void channel_read(tcp_channel_context_base* ctx, shan::object_ptr& data) override { std::lock_guard<std::mutex> _lock(_mutex); auto sb_ptr = static_cast<shan::util::streambuf*>(data.get()); if (sb_ptr->in_size() < sizeof(std::time_t)) { // not enough data ctx->done(true); return; } std::time_t time; if (sizeof(std::time_t) == 4) time = sb_ptr->read_int32(); else time = sb_ptr->read_int64(); data = std::make_shared<unix_time>(time); } virtual void channel_write(tcp_channel_context_base* ctx, shan::object_ptr& data) override { std::lock_guard<std::mutex> _lock(_mutex); auto time_ptr = static_cast<unix_time*>(data.get()); auto sb_ptr = std::make_shared<shan::util::streambuf>(sizeof(std::time_t)); if (sizeof(std::time_t) == 4) sb_ptr->write_int32(static_cast<int32_t>(time_ptr->get_time())); else sb_ptr->write_int64(static_cast<int32_t>(time_ptr->get_time())); data = sb_ptr; // return new converted object. } }; class serv_ch_handler_s : public tcp_channel_handler { public: virtual ~serv_ch_handler_s() { std::lock_guard<std::mutex> _lock(_mutex); cout << ">>>> serv_ch_handler destroyed!!!!" << endl; }; virtual void user_event(tcp_channel_context_base* ctx, int64_t id, shan::object_ptr data_ptr) override { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "user_event() called" << endl; } virtual void exception_caught(tcp_channel_context_base* ctx, const std::exception& e) override { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "exception_caught() - " << e.what() << "@@@@@@@@@@@@@@@@@@@@@" << endl; } virtual void channel_connected(tcp_channel_context_base* ctx) override { { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "channel_connected(" << ctx->channel_id() << ") called" << endl; conn++; } auto data = std::make_shared<unix_time>(3000); ctx->write(data); } virtual void channel_read(tcp_channel_context_base* ctx, shan::object_ptr& data) override { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "channel_read()" << endl; } virtual void channel_rdbuf_empty(tcp_channel_context_base* ctx) override { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "channel_rdbuf_empty() called" << endl; } virtual void channel_write(tcp_channel_context_base* ctx, shan::object_ptr& data) override { { std::lock_guard<std::mutex> _lock(_mutex); auto sb_ptr = static_cast<shan::util::streambuf*>(data.get()); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "channel_write() - " << sb_ptr->in_size() << endl; } } virtual void channel_written(tcp_channel_context_base* ctx, std::size_t bytes_transferred) override { { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "channel_written() - " << bytes_transferred << endl; wt++; } ctx->close(); } virtual void channel_disconnected(tcp_channel_context_base* ctx) override { static int c = 0; { std::lock_guard<std::mutex> _lock(_mutex); cout << static_cast<ssl_channel_context*>(ctx)->channel_id() << ":serv_ch_handler::" << "channel_disconnected() called:" << ++c << endl; dis_conn++; } } }; std::string get_password(std::size_t max_length, ssl_password_purpose purpose) { return "test"; } bool verify_certificate(bool preverified, X509_STORE_CTX* ctx) { // 미리 기본 인증 과정을 태워서 preverified 값을 결정하는 것 같음. // 따라서 상용인 경우 true로, 사설인 경우 false로 오는 것 같음... // In this example we will simply print the certificate's subject name. char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(ctx); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "Verifying " << subject_name << "\n"; return true; // 여기서 true를 반환하면 사설, 상용 상관없이 통과됨. } int main(int argc, const char * argv[]) { shan::net::ssl_server serv(TLSV12); // shan::net::tcp_server serv; serv.set_options(DEF_OPT | SINGLE_DH_USE | NO_SSLV2); serv.set_password_callback(get_password); #ifdef RASPI_TEST serv.use_certificate_chain_file("/home/pi/Shan.Lib_test/Shan.Net/server.pem"); serv.use_private_key_file("/home/pi/Shan.Lib_test/Shan.Net/server.pem", PEM); serv.use_tmp_dh_file("/home/pi/Shan.Lib_test/Shan.Net/dh2048.pem"); #endif #ifdef MACOS_TEST serv.use_certificate_chain_file("/Users/shanpark/Documents/Shan.Lib/Shan.Net/server.pem"); serv.use_private_key_file("/Users/shanpark/Documents/Shan.Lib/Shan.Net/server.pem", PEM); serv.use_tmp_dh_file("/Users/shanpark/Documents/Shan.Lib/Shan.Net/dh2048.pem"); #endif #ifdef WIN64_TEST serv.use_certificate_chain_file("server.pem"); serv.use_private_key_file("server.pem", PEM); serv.use_tmp_dh_file("dh2048.pem"); #endif serv.add_acceptor_handler(new acpt_handler_s()); // 이 핸들러는 serv가 destroy될 때 같이 해제된다. 걱정마라.. serv.add_channel_handler(new channel_coder_s()); // serv.add_channel_handler(new serv_ch_handler_s()); // serv.start(10888); cout << "SSLServer started()" << endl; serv.wait_stop(); }
34.13
161
0.701875
[ "object" ]
5ceb11d7fb1c3fa9b2781b3f37b495ddb909905c
6,014
cpp
C++
src/caffe/gpi_communicator_diff.cpp
cc-hpc-itwm/caffeGPI
85c57a91ec99fb1419fc281585cf54b0e3c97fb8
[ "BSD-2-Clause" ]
1
2017-09-07T07:32:29.000Z
2017-09-07T07:32:29.000Z
src/caffe/gpi_communicator_diff.cpp
cc-hpc-itwm/CaffeGPI
85c57a91ec99fb1419fc281585cf54b0e3c97fb8
[ "BSD-2-Clause" ]
null
null
null
src/caffe/gpi_communicator_diff.cpp
cc-hpc-itwm/CaffeGPI
85c57a91ec99fb1419fc281585cf54b0e3c97fb8
[ "BSD-2-Clause" ]
null
null
null
#include "caffe/gpi_communicator_diff.hpp" namespace caffe { template <typename Dtype> void CommunicatorDiff<Dtype>::operator()(void) { for (long i = 0; i < com_buffers_diff_read_.size(); i++) { RingBufferRead<Dtype>& buffer = com_buffers_diff_read_[i]; while (com_buffers_diff_read_status_[i] < calculated_blobs_.size()) { Blob<Dtype>& blob = *calculated_blobs_[com_buffers_diff_read_status_[i]]; if (buffer.Add(blob.mutable_cpu_diff(), blob.count())) { break; } else { com_buffers_diff_read_status_[i]++; } } } for (long i = 0; i < com_buffers_diff_write_.size(); i++) { RingBufferWrite<Dtype>& buffer = com_buffers_diff_write_[i]; while ((com_buffers_diff_write_status_[i] < calculated_blobs_.size()) && CommunicateLayerDiffReadFinished(com_buffers_diff_write_status_[i])) { Blob<Dtype>& blob = *calculated_blobs_[com_buffers_diff_write_status_[i]]; //todo aggregate diffs from other cpu too if (buffer.Write(blob.cpu_diff(), blob.count())) { break; } else { com_buffers_diff_write_status_[i]++; } } } } template <typename Dtype> bool CommunicatorDiff<Dtype>::CommunicateLayerDiffFinished() { int running = !CommunicateLayerDiffReadFinished(calculated_blobs_.size() - 1); for (long i = 0; i < com_buffers_diff_write_status_.size(); i++) { running |= (com_buffers_diff_write_status_[i] < calculated_blobs_.size()); } return !running; } template <typename Dtype> bool CommunicatorDiff<Dtype>::CommunicateLayerDiffReadFinished(int index) { int running = 0; for (long i = 0; i < com_buffers_diff_read_status_.size(); i++) { running |= (com_buffers_diff_read_status_[i] <= index); } return !running; } template <typename Dtype> void CommunicatorDiff<Dtype>::AddCalculatedBlob(Blob<Dtype>* blob) { calculated_blobs_.push_back(blob); } template <typename Dtype> void CommunicatorDiff<Dtype>::ResetCommunicationStatus(void) { for (int i = 0; i < com_buffers_diff_read_status_.size(); i++) com_buffers_diff_read_status_[i] = 0; for (int i = 0; i < com_buffers_diff_write_status_.size(); i++) com_buffers_diff_write_status_[i] = 0; calculated_blobs_.resize(0); } template <typename Dtype> CommunicatorDiff<Dtype>::CommunicatorDiff( const long buffer_size, const gaspi_notification_id_t notification_id_base, const gaspi_segment_id_t segment_id, const gaspi_queue_id_t queue, const gaspi_rank_t rank, const gaspi_rank_t num_ranks) : segment_id_(segment_id), rank_(rank), num_ranks_(num_ranks) { const int bf = GetDiffTreeBranchingFactor(); std::vector<gaspi_rank_t> ranks_read = GetDiffTreeReadRanks(rank_, bf); std::vector<gaspi_rank_t> ranks_write = GetDiffTreeWriteRanks(rank_, bf); const long diff_segment_size = std::max(buffer_size * (ranks_read.size() + ranks_write.size()), 1ul); SUCCESS_OR_DIE(gaspi_segment_create(segment_id_, diff_segment_size * sizeof(Dtype), GASPI_GROUP_ALL, GASPI_BLOCK, GASPI_MEM_UNINITIALIZED)); long buffer_index = 0; for (int i = 0; i < ranks_write.size(); i++) { const int rank_remote = ranks_write[i]; std::vector<gaspi_rank_t> ranks_read_remote = GetDiffTreeReadRanks(rank_remote, bf); std::vector<gaspi_rank_t> ranks_write_remote = GetDiffTreeWriteRanks(rank_remote, bf); const long buffer_index_remote = ranks_write_remote.size() + std::find(ranks_read_remote.begin(), ranks_read_remote.end(), rank_) - ranks_read_remote.begin(); com_buffers_diff_write_.push_back(RingBufferWrite<Dtype>( buffer_size, segment_id_, notification_id_base + buffer_index, buffer_index * buffer_size * sizeof(Dtype), rank_remote, segment_id_, notification_id_base + buffer_index_remote, buffer_index_remote * buffer_size * sizeof(Dtype), queue)); com_buffers_diff_write_status_.push_back(0); buffer_index++; } for (int i = 0; i < ranks_read.size(); i++) { const int rank_remote = ranks_read[i]; std::vector<gaspi_rank_t> ranks_write_remote = GetDiffTreeWriteRanks(rank_remote, bf); long buffer_index_remote = 0; for (int j = 0; (j < ranks_write_remote.size()) && (ranks_write_remote[j] != rank_); j++) { buffer_index_remote++; } com_buffers_diff_read_.push_back(RingBufferRead<Dtype>( buffer_size, segment_id_, notification_id_base + buffer_index, buffer_index * buffer_size * sizeof(Dtype), ranks_read[i], segment_id_, notification_id_base + buffer_index_remote, buffer_index_remote * buffer_size * sizeof(Dtype), queue)); com_buffers_diff_read_status_.push_back(0); buffer_index ++; } } template <typename Dtype> CommunicatorDiff<Dtype>::~CommunicatorDiff() { SUCCESS_OR_DIE(gaspi_segment_delete(segment_id_)); } template <typename Dtype> int CommunicatorDiff<Dtype>::GetDiffTreeBranchingFactor() const { return 2; } template <typename Dtype> std::vector<gaspi_rank_t> CommunicatorDiff<Dtype>::GetDiffTreeWriteRanks( gaspi_rank_t rank, int branching_factor) const { std::vector<gaspi_rank_t> r; if (rank > 0) { long power = 1; // = branching_factor ** 0 while((power * branching_factor) <= long(rank)) { power *= branching_factor; } r.push_back(long(rank) % power); } return r; } template <typename Dtype> std::vector<gaspi_rank_t> CommunicatorDiff<Dtype>::GetDiffTreeReadRanks( gaspi_rank_t rank, int branching_factor) const { std::vector<gaspi_rank_t> r; long power = 1; while (power < long(num_ranks_)) { if (power > long(rank)) { for(long i = 1; i < branching_factor; i++) { long n = i * power + long(rank); if (n < long(num_ranks_)) { r.push_back(n); } } } power *= branching_factor; } return r; } template class CommunicatorDiff<float>; template class CommunicatorDiff<double>; }
34.365714
95
0.695211
[ "vector" ]
5cee11b47f1bfbba29e7d0984baa3cf54c99dcc3
3,334
cc
C++
services/native_viewport/viewport_surface.cc
rafaelw/mojo
d3495a129dcbe679e2d5ac729c85a58acf38f8c4
[ "BSD-3-Clause" ]
5
2015-04-30T00:13:21.000Z
2019-07-10T02:17:24.000Z
services/native_viewport/viewport_surface.cc
rafaelw/mojo
d3495a129dcbe679e2d5ac729c85a58acf38f8c4
[ "BSD-3-Clause" ]
null
null
null
services/native_viewport/viewport_surface.cc
rafaelw/mojo
d3495a129dcbe679e2d5ac729c85a58acf38f8c4
[ "BSD-3-Clause" ]
1
2019-05-12T13:53:44.000Z
2019-05-12T13:53:44.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/native_viewport/viewport_surface.h" #include "base/bind.h" #include "mojo/converters/geometry/geometry_type_converters.h" #include "mojo/converters/surfaces/surfaces_type_converters.h" #include "mojo/services/surfaces/public/cpp/surfaces_utils.h" #include "ui/gfx/transform.h" using mojo::Size; using mojo::SurfaceId; static uint32_t kGLES2BoundSurfaceLocalId = 1u; namespace native_viewport { ViewportSurface::ViewportSurface(mojo::SurfacePtr surface, mojo::Gpu* gpu_service, const gfx::Size& size, cc::SurfaceId child_id) : surface_(surface.Pass()), gpu_service_(gpu_service), widget_id_(0u), size_(size), gles2_bound_surface_created_(false), child_id_(child_id), weak_factory_(this) { } ViewportSurface::~ViewportSurface() { } void ViewportSurface::SetWidgetId(uint64_t widget_id) { widget_id_ = widget_id; BindSurfaceToNativeViewport(); } void ViewportSurface::SetSize(const gfx::Size& size) { if (size_ == size) return; size_ = size; if (!gles2_bound_surface_created_) return; surface_->DestroySurface(kGLES2BoundSurfaceLocalId); if (widget_id_) BindSurfaceToNativeViewport(); } void ViewportSurface::SetChildId(cc::SurfaceId child_id) { child_id_ = child_id; SubmitFrame(); } void ViewportSurface::BindSurfaceToNativeViewport() { mojo::ViewportParameterListenerPtr listener; auto listener_request = GetProxy(&listener); mojo::CommandBufferPtr command_buffer; gpu_service_->CreateOnscreenGLES2Context(widget_id_, Size::From(size_), GetProxy(&command_buffer), listener.Pass()); gles2_bound_surface_created_ = true; surface_->CreateGLES2BoundSurface(command_buffer.Pass(), kGLES2BoundSurfaceLocalId, Size::From(size_), listener_request.Pass()); SubmitFrame(); } void ViewportSurface::SubmitFrame() { if (child_id_.is_null() || !gles2_bound_surface_created_) return; auto surface_quad_state = mojo::SurfaceQuadState::New(); surface_quad_state->surface = SurfaceId::From(child_id_); gfx::Rect bounds(size_); auto surface_quad = mojo::Quad::New(); surface_quad->material = mojo::Material::MATERIAL_SURFACE_CONTENT; surface_quad->rect = mojo::Rect::From(bounds); surface_quad->opaque_rect = mojo::Rect::From(bounds); surface_quad->visible_rect = mojo::Rect::From(bounds); surface_quad->needs_blending = true; surface_quad->shared_quad_state_index = 0; surface_quad->surface_quad_state = surface_quad_state.Pass(); auto pass = CreateDefaultPass(1, *mojo::Rect::From(bounds)); pass->quads.push_back(surface_quad.Pass()); pass->shared_quad_states.push_back(CreateDefaultSQS( *mojo::Size::From(size_))); auto frame = mojo::Frame::New(); frame->passes.push_back(pass.Pass()); frame->resources.resize(0u); surface_->SubmitFrame(kGLES2BoundSurfaceLocalId, frame.Pass(), mojo::Closure()); } } // namespace native_viewport
31.158879
80
0.689862
[ "geometry", "transform" ]
5cf4e5ab2ca6b1c574ca11c2af93a99270cd5fe7
1,352
cc
C++
codes/raulcr-p3727-Accepted-s1209647.cc
raulcr98/coj-solutions
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
[ "MIT" ]
1
2020-03-17T01:44:21.000Z
2020-03-17T01:44:21.000Z
codes/raulcr-p3727-Accepted-s1209647.cc
raulcr98/coj-solutions
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
[ "MIT" ]
null
null
null
codes/raulcr-p3727-Accepted-s1209647.cc
raulcr98/coj-solutions
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int> ady[2000005]; bool visited[2000005], construct[2000005]; int N,M; int BFS(int a){ queue<int>cola; cola.push(a); visited[a]=true; cola.push(1); int citi,b; int sol=0; while(!cola.empty()){ sol++; citi=cola.front(); cola.pop(); b=cola.front(); cola.pop(); construct[citi]=(b==1); for(int i=0, c=ady[citi].size(); i<c; i++) if(!visited[ady[citi][i]]){ visited[ady[citi][i]]=true; cola.push(ady[citi][i]); cola.push(b*-1); } // sol+=DFS(ady[citi][i],!tipo); } return sol; } bool loca() { for(int i=1; i<=N; i++) if(!visited[i]) { if(BFS(i)==1) return false; } return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>N>>M; int a,b; for(int i=0; i<M; i++) { cin>>a>>b; ady[a].push_back(b); ady[b].push_back(a); } if(!loca()) cout<<"Impossible\n"; else { cout<<"Possible\n"; for(int i=1; i<=N; i++) { if(construct[i]) cout<<"1\n"; else cout<<"2\n"; } } return 0; }
18.27027
47
0.428994
[ "vector" ]
5cf88f484ce8458d25386a1f8d09ddbf3678d05f
17,373
hh
C++
cc/tree.hh
acorg/acmacs-tal
13da33bb8ed456ac1f968b8b86df295467ee5429
[ "MIT" ]
null
null
null
cc/tree.hh
acorg/acmacs-tal
13da33bb8ed456ac1f968b8b86df295467ee5429
[ "MIT" ]
null
null
null
cc/tree.hh
acorg/acmacs-tal
13da33bb8ed456ac1f968b8b86df295467ee5429
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <tuple> #include <optional> #include <algorithm> #include "acmacs-base/log.hh" #include "acmacs-base/named-type.hh" #include "acmacs-base/counter.hh" #include "acmacs-base/date.hh" #include "acmacs-base/color.hh" #include "acmacs-base/flat-set.hh" #include "acmacs-base/string-from-chars.hh" #include "seqdb-3/seqdb.hh" #include "acmacs-tal/aa-transition.hh" #include "acmacs-tal/error.hh" // ---------------------------------------------------------------------- namespace acmacs::chart { class Chart; } namespace acmacs::tal::inline v3 { class Node; using seq_id_t = acmacs::seqdb::seq_id_t; // string, not string_view to support populate_with_nuc_duplicates using EdgeLength = named_double_from_string_t<struct acmacs_tal_EdgeLength_tag>; // class EdgeLength : public named_double_from_string_t<struct acmacs_tal_EdgeLength_tag> // { // public: // }; using NodePath = acmacs::named_vector_t<const Node*, struct acmacs_tal_NodePath_tag>; constexpr const EdgeLength EdgeLengthNotSet{-1.0}; struct ladderize_helper_t { EdgeLength edge{EdgeLengthNotSet}; std::string_view date; seq_id_t seq_id; }; struct node_id_t { using value_type = unsigned short; constexpr static const value_type NotSet{static_cast<value_type>(-1)}; value_type vertical{NotSet}; value_type horizontal{NotSet}; constexpr bool empty() const { return vertical == NotSet; } constexpr bool operator<(const node_id_t& rhs) const { return vertical < rhs.vertical; } }; namespace draw_tree { struct AATransitionsParameters; // draw-tree.hh } // ---------------------------------------------------------------------- class Node { public: using Subtree = std::vector<Node>; Node() = default; Node(const seq_id_t& a_seq_id, EdgeLength a_edge) : edge_length{a_edge}, seq_id{a_seq_id} {} bool is_leaf() const noexcept { return subtree.empty(); } // seq_id may contain generated node name used for debugging Node& add_leaf(const seq_id_t& a_seq_id, EdgeLength a_edge) { return subtree.emplace_back(a_seq_id, a_edge); } Node& add_subtree() { return subtree.emplace_back(); } const Node& find_first_leaf() const; // all nodes EdgeLength edge_length{0.0}; mutable EdgeLength cumulative_edge_length{EdgeLengthNotSet}; bool hidden{false}; // leaf node only seq_id_t seq_id; acmacs::seqdb::ref ref; acmacs::seqdb::sequence_aligned_ref_t aa_sequence; acmacs::seqdb::sequence_aligned_ref_t nuc_sequence; std::string_view strain_name; // from seqdb std::string_view date; std::string_view continent; std::string_view country; std::vector<std::string_view> hi_names; acmacs::flat_set_t<std::string> clades; // branch node only Subtree subtree; std::vector<std::string_view> aa_substs; // -> export double edge_line_width_scale{1.0}; Color color_edge_line{BLACK}; double label_scale{1.0}; std::optional<Color> label_color; // -------------------- not exported -------------------- Node* first_prev_leaf{nullptr}; // first leaf for non-leaf nodes, prev leaf for leaves, nullptr for the top of the tree Node* last_next_leaf{nullptr}; // last leaf for non-leaf nodes, next leaf for leaves, nullptr for the last leaf enum class leaf_position { first, middle, last, single }; leaf_position leaf_pos{leaf_position::middle}; node_id_t node_id; // includes vertical leaf number for leaves seqdb::SeqdbSeq::gisaid_data_t gisaid; // from seqdb // all nodes ladderize_helper_t ladderize_helper_; // leaf node only mutable std::optional<size_t> antigen_index_in_chart_; struct serum_from_chart_t { size_t serum_no; bool reassortant_matches; bool passage_type_matches; bool passage_matches; }; mutable std::vector<serum_from_chart_t> serum_index_in_chart_; Subtree to_populate; // populate_with_nuc_duplicates() // -------------------- AA transitions (branch node only) -------------------- AA_Transitions aa_transitions_; // 20200514 std::vector<const Node*> closest_leaves{}; // child leaves with minimal cumulative_edge_length, multiple leaves necessary because closest one may have X at some positions // before_20200513 CommonAA_Ptr common_aa_; const Node* node_for_left_aa_transitions_{nullptr}; // -------------------- drawing support -------------------- mutable double cumulative_vertical_offset_{0.0}; constexpr static const double default_vertical_offset{1.0}; mutable double vertical_offset_{default_vertical_offset}; // mutalbe for adjusting via const Node* in clade sections bool children_are_shown() const { return !hidden && (subtree.empty() || std::any_of(std::begin(subtree), std::end(subtree), [](const auto& node) { return node.children_are_shown(); })); } void remove_aa_transition(seqdb::pos0_t pos, char right); void replace_aa_transition(seqdb::pos0_t pos, char right); std::vector<const Node*> shown_children() const; void hide(); void populate(const acmacs::seqdb::ref& a_ref, const acmacs::seqdb::Seqdb& seqdb); size_t number_leaves_in_subtree() const { if (!is_leaf()) { if (!first_prev_leaf || !last_next_leaf) { // AD_WARNING("first_prev_leaf or last_next_leaf is null, all subtree is hidden?", subtree.size(), fmt::ptr(subtree[0].first_prev_leaf)); return 0; } else return last_next_leaf->node_id.vertical - first_prev_leaf->node_id.vertical + 1; } else return 1; } // char aa_at(seqdb::pos0_t pos0) const { return is_leaf() ? aa_sequence.at(pos0) : common_aa_.at(pos0); } // double distance_from_previous = -1; // for hz sections auto-detection // std::string aa_at; // see make_aa_at() // AA_Transitions aa_transitions; // size_t hz_section_index = HzSectionNoIndex; // Color mark_with_line = ColorNoChange; // Pixels mark_with_line_width{0}; // std::optional<size_t> chart_antigen_index; // size_t matched_antigens = 0; // for parent nodes only // std::optional<size_t> mark_with_label; }; // class Node // ---------------------------------------------------------------------- template <typename N> class NodeSetT : public std::vector<N> { public: NodeSetT() = default; NodeSetT(size_t reserve) : std::vector<N>(reserve, nullptr) {} void add(const NodeSetT<N>& another) { std::copy(std::begin(another), std::end(another), std::back_inserter(*this)); } void filter(const NodeSetT<N>& another) { this->erase(std::remove_if(this->begin(), this->end(), [&another](const auto& en) { return std::find(std::begin(another), std::end(another), en) == std::end(another); }), this->end()); } }; using NodeSet = NodeSetT<Node*>; // using NodeConstSet = NodeSetT<const Node*>; // ---------------------------------------------------------------------- class Tree : public Node { public: void erase(); void data_buffer(std::string&& data) { data_buffer_ = std::move(data); } std::string_view data_buffer() const { return data_buffer_; } std::string_view virus_type() const { return virus_type_; } std::string_view lineage() const { return lineage_; } void virus_type(std::string_view virus_type) { virus_type_.assign(virus_type); } void lineage(std::string_view lineage) { lineage_.assign(lineage); } bool has_sequences() const; NodePath find_path_by_seq_id(const seq_id_t& look_for) const; const Node* find_node_by_seq_id(const seq_id_t& look_for) const; void match_seqdb(std::string_view seqdb_filename); void populate_with_nuc_duplicates(); std::string report_cumulative(size_t max) const; std::string report_by_edge(size_t max, size_t max_names_per_row) const; void cumulative_calculate(bool recalculate = false) const; // void cumulative_reset() const; void branches_by_edge(); void branches_by_cumulative_edge(); enum class Select { init, update }; enum class Descent { no, yes }; void select_if_cumulative_more_than(NodeSet& nodes, Select update, double cumulative_min, Descent descent = Descent::no); void select_if_edge_more_than(NodeSet& nodes, Select update, double edge_min); void select_if_edge_more_than_mean_edge_of(NodeSet& nodes, Select update, double fraction_or_number); void select_by_top_cumulative_gap(NodeSet& nodes, Select update, double top_gap_rel); EdgeLength max_cumulative_shown() const; void select_all(NodeSet& nodes, Select update); void select_all_and_intermediate(NodeSet& nodes, Select update); void select_intermediate(NodeSet& nodes, Select update, size_t min_subtree_size); // select only intermediate nodes if their subtree size >= min_subtree_size void select_by_date(NodeSet& nodes, Select update, std::string_view start, std::string_view end); void select_by_seq_id(NodeSet& nodes, Select update, std::string_view regexp); void select_by_country(NodeSet& nodes, Select update, std::string_view country); void select_by_continent(NodeSet& nodes, Select update, std::string_view continent); void select_by_location(NodeSet& nodes, Select update, std::string_view location); void select_by_aa(NodeSet& nodes, Select update, const acmacs::seqdb::amino_acid_at_pos1_eq_list_t& aa_at_pos1); void select_by_nuc(NodeSet& nodes, Select update, const acmacs::seqdb::nucleotide_at_pos1_eq_list_t& nuc_at_pos1); // ---------------------------------------------------------------------- enum class serum_match_t { name, reassortant, passage_type }; void select_matches_chart_antigens(NodeSet& nodes, Select update); void select_matches_chart_sera(NodeSet& nodes, Select update, serum_match_t match_type); acmacs::chart::PointIndexList chart_antigens_in_tree() const; acmacs::chart::PointIndexList chart_antigens_in_section(const Node* first, const Node* last) const; acmacs::chart::PointIndexList chart_sera_in_tree(serum_match_t match_type) const; acmacs::chart::PointIndexList chart_sera_in_section(const Node* first, const Node* last) const; // ---------------------------------------------------------------------- enum class hide_if_too_many_leaves { no, yes }; void hide(const NodeSet& nodes, hide_if_too_many_leaves force); enum class Ladderize { None, MaxEdgeLength, NumberOfLeaves }; void ladderize(Ladderize method); // re-roots tree making the parent of the leaf node with the passed name root void re_root(const seq_id_t& new_root); void re_root(const NodePath& new_root); void report_first_last_leaves(size_t min_number_of_leaves) const; // ---------------------------------------------------------------------- std::vector<std::string_view> all_dates() const; enum class report_size { brief, detailed }; std::string report_aa_at(const std::vector<acmacs::seqdb::pos1_t>& pos, bool names) const; void aa_at_pos_report(size_t tolerance) const; void aa_at_pos_counter_report(double tolerance, bool positions_only) const; // ---------------------------------------------------------------------- struct clade_section_t { clade_section_t(const Node* node) : first{node}, last{node} {} const Node* first; const Node* last; }; struct clade_t { clade_t(std::string_view nam, std::string_view disp) : name{nam}, display_name{disp.empty() ? nam : disp} {} std::string name; std::string display_name; std::vector<clade_section_t> sections; }; using clades_t = std::vector<clade_t>; struct nodes_of_sera_t { std::vector<const Node*> nodes; }; using serum_to_node_t = std::vector<nodes_of_sera_t>; // constexpr clades_t& clades() { return clades_; } constexpr const clades_t& clades() const { return clades_; } void clades_reset(); void clade_set_by_aa_at_pos(std::string_view name, const acmacs::seqdb::amino_acid_at_pos1_eq_list_t& aa_at_pos, std::string_view display_name); void clade_set_by_nuc_at_pos(std::string_view name, const acmacs::seqdb::nucleotide_at_pos1_eq_list_t& nuc_at_pos, std::string_view display_name); void clade_report(std::string_view name = {}) const; // ---------------------------------------------------------------------- void match(const acmacs::chart::Chart& chart) const; // drawing support double compute_cumulative_vertical_offsets(); // returns tree height // gap is a fraction of tree height void set_top_gap(const Node& node, double gap) const; void set_bottom_gap(const Node& node, double gap) const; void add_clade(std::string_view name, std::string_view display_name); void make_clade_sections(); void set_first_last_next_node_id(); enum class leaves_only { no, yes }; std::vector<const Node*> sorted_by_cumulative_edge(leaves_only lo) const; // bigger cumul length first seqdb::pos0_t longest_aa_sequence() const; seqdb::pos0_t longest_nuc_sequence() const; void resize_common_aa(size_t longest_sequence); size_t longest_seq_id() const; void set_closest_leaf_for_intermediate(); // returns intermediate node set sorted by number of leaves in subtree NodeSet closest_leaf_subtree_size(size_t min_subtree_size); private: const clade_t* find_clade(std::string_view name) const; clade_t* find_clade(std::string_view name); std::vector<const Node*> sorted_by_edge() const; double mean_edge_of(double fraction_or_number, const std::vector<const Node*>& sorted) const; // nodes sorted by edge, longest nodes (fraction of all or by number) taken and their mean edge calculated double mean_cumulative_edge_of(double fraction_or_number, const std::vector<const Node*>& sorted) const; void structure_modified([[maybe_unused]] std::string_view on_action) { structure_modified_ = true; } // AD_DEBUG("structure_modified: {}", on_action); std::string data_buffer_; std::string virus_type_; std::string lineage_; clades_t clades_; mutable bool chart_matched_{false}; mutable serum_to_node_t serum_to_node_; // nodes matched for each serum index from the chart bool structure_modified_{true}; }; // class Tree // ---------------------------------------------------------------------- } // namespace acmacs::tal::inline v3 // ====================================================================== // {:4.3} -> {:>4d}.{:<3d} // {:.0} -> {:d} template <> struct fmt::formatter<acmacs::tal::node_id_t> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { auto it = ctx.begin(); if (it != ctx.end() && *it == ':') ++it; if (it != ctx.end() && *it != '}' && *it != '.') { const char* end{nullptr}; v_size_ = acmacs::string::from_chars_to_unsigned<size_t>(&*it, &end); it = std::next(it, end - &*it); } if (it != ctx.end() && *it == '.') ++it; if (it != ctx.end() && *it != '}') { const char* end{nullptr}; h_size_ = acmacs::string::from_chars_to_unsigned<size_t>(&*it, &end); it = std::next(it, end - &*it); } while (it != ctx.end() && *it != '}') ++it; return it; } template <typename FormatCtx> auto format(const acmacs::tal::node_id_t& node_id, FormatCtx& ctx) const { if (v_size_.has_value()) format_to(ctx.out(), "{:>{}d}", node_id.vertical, *v_size_); else format_to(ctx.out(), "{}", node_id.vertical); if (h_size_.has_value()) { if (*h_size_ > 0) format_to(ctx.out(), ".{:<{}d}", node_id.horizontal, *h_size_); } else format_to(ctx.out(), ".{}", node_id.horizontal); return ctx.out(); } std::optional<size_t> v_size_, h_size_; }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
40.496503
196
0.611811
[ "vector", "3d" ]
9dcf021fc3a79d0931071e01d6a90a43d29194fa
1,492
cpp
C++
Utilities/Utility.cpp
Dr-Dan/GOAP-Agent-System
fe888fb9e79e547116833c16b23698865dfd662e
[ "Apache-2.0" ]
2
2016-10-07T21:53:09.000Z
2017-12-31T12:39:16.000Z
Utilities/Utility.cpp
Dr-Dan/GOAP-Agent-System
fe888fb9e79e547116833c16b23698865dfd662e
[ "Apache-2.0" ]
null
null
null
Utilities/Utility.cpp
Dr-Dan/GOAP-Agent-System
fe888fb9e79e547116833c16b23698865dfd662e
[ "Apache-2.0" ]
null
null
null
// // Utility.cpp // AgentGOBGridTest // // Created by D J Clarke on 09/03/2015. // // #include "Utility.h" #include "GridCell.h" #include "AgentFact.h" int Utility::worldId = 0; ofVec2f Utility::GetGridPos(ofVec2f refPos, vector<GridCell>& cells){ ofVec2f posOut = ofVec2f(); for(int i = 0; i < cells.size(); i++){ if(cells[i].GetRect().inside(refPos)){ posOut = cells[i].GetGridPos(); } } return posOut; } int Utility::GetWorldId(){ worldId++; return worldId-1; } ofVec2f Utility::GetRandomGridPos(){ int randX = ofRandom(0,GridValues::GRID_DIMS[0]); int randY = ofRandom(0,GridValues::GRID_DIMS[1]); return ofVec2f(randX, randY); } ofVec2f Utility::GetGridDistance2d(ofVec2f startPos, ofVec2f endPos){ return endPos-startPos; } float Utility::GetGridDistance(ofVec2f startPos, ofVec2f endPos){ ofVec2f distOut = GetGridDistance2d(startPos, endPos); return distOut.length(); } bool Utility::PairDistCompare(pair<ofVec2f, float> a, pair<ofVec2f, float> b){ return a.second < b.second; } bool Utility::CellDistCompare(pair<GridCell*, float> a, pair<GridCell*, float> b){ return a.second < b.second; } bool Utility::CellFactFoodRatingComp(CellFact* a, CellFact* b){ return a->GetRatingAmt(WorldTypes::CELL_FOOD) > b->GetRatingAmt(WorldTypes::CELL_FOOD); } bool Utility::CellFactCombinedRatingComp(CellFact* a, CellFact* b){ return a->GetCombinedRating() > b->GetCombinedRating(); }
23.3125
88
0.684316
[ "vector" ]
9dd14cd5d6d9783437d5fc4f4647d5a4062323a2
16,772
cpp
C++
Direct3D_11_Exe/direct3d.cpp
Roy-Fokker/Direct3D_11_Eg
172bbb84f6a707911d6df69a8b2a709b3ac44636
[ "Unlicense" ]
null
null
null
Direct3D_11_Exe/direct3d.cpp
Roy-Fokker/Direct3D_11_Eg
172bbb84f6a707911d6df69a8b2a709b3ac44636
[ "Unlicense" ]
null
null
null
Direct3D_11_Exe/direct3d.cpp
Roy-Fokker/Direct3D_11_Eg
172bbb84f6a707911d6df69a8b2a709b3ac44636
[ "Unlicense" ]
null
null
null
#pragma comment(lib, "dxgi.lib") #pragma comment(lib, "d3d11.lib") #ifdef _DEBUG #pragma comment(lib, "dxguid.lib") #endif // DEBUG #include "direct3d.h" #include "vertex.h" #include <cassert> #include <cstdint> #include <array> #include <vector> #include <DirectXColors.h> using namespace direct3d_11_eg; using namespace direct3d_11_eg::direct3d_types; namespace { constexpr DXGI_FORMAT swap_chain_format = DXGI_FORMAT_R8G8B8A8_UNORM; constexpr uint16_t msaa_quality_level = 4U; constexpr uint32_t max_anisotropy = 16U; using element_desc = std::vector<D3D11_INPUT_ELEMENT_DESC>; constexpr D3D11_INPUT_ELEMENT_DESC position = { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }; constexpr D3D11_INPUT_ELEMENT_DESC normal = { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }; constexpr D3D11_INPUT_ELEMENT_DESC texcoord = { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }; const std::array<uint16_t, 2> get_window_size(HWND window_handle) { RECT rect{}; GetClientRect(window_handle, &rect); return { static_cast<uint16_t>(rect.right - rect.left), static_cast<uint16_t>(rect.bottom - rect.top) }; } const std::array<uint16_t, 2> get_swap_chain_size(swap_chain_t swap_chain) { DXGI_SWAP_CHAIN_DESC sd{}; auto hr = swap_chain->GetDesc(&sd); assert(hr == S_OK); return { static_cast<uint16_t>(sd.BufferDesc.Width), static_cast<uint16_t>(sd.BufferDesc.Height) }; } const DXGI_RATIONAL get_refresh_rate(CComPtr<IDXGIAdapter> dxgiAdapter, HWND window_handle, bool vSync = true) { DXGI_RATIONAL refresh_rate{ 0, 1 }; if (vSync) { HRESULT hr{}; CComPtr<IDXGIOutput> adapter_output; hr = dxgiAdapter->EnumOutputs(0, &adapter_output); assert(hr == S_OK); uint32_t display_modes_count{ 0 }; hr = adapter_output->GetDisplayModeList(swap_chain_format, DXGI_ENUM_MODES_INTERLACED, &display_modes_count, nullptr); assert(hr == S_OK); std::vector<DXGI_MODE_DESC> display_modes(display_modes_count); hr = adapter_output->GetDisplayModeList(swap_chain_format, DXGI_ENUM_MODES_INTERLACED, &display_modes_count, &display_modes[0]); assert(hr == S_OK); auto[width, height] = get_window_size(window_handle); for (auto &mode : display_modes) { if (mode.Width == width && mode.Height == height) { refresh_rate = mode.RefreshRate; } } } return refresh_rate; } const DXGI_SAMPLE_DESC get_msaa_level(device_t device) { DXGI_SAMPLE_DESC sd{ 1, 0 }; #ifdef _DEBUG return sd; #endif UINT msaa_level{ 0 }; auto hr = device->CheckMultisampleQualityLevels(swap_chain_format, msaa_quality_level, &msaa_level); assert(hr == S_OK); if (msaa_level > 0) { sd.Count = msaa_quality_level; sd.Quality = msaa_level - 1; } return sd; } } #pragma region "Device, Context and Swap Chain" direct3d::direct3d(HWND hWnd) : window_handle(hWnd) { make_device(); make_swap_chain(); } direct3d::~direct3d() {} void direct3d::resize_swap_chain() { auto hr = swap_chain->ResizeBuffers(NULL, NULL, NULL, DXGI_FORMAT_UNKNOWN, NULL); assert(hr == S_OK); } void direct3d::present(bool vSync) { swap_chain->Present((vSync ? TRUE : FALSE), NULL); } context_t direct3d::get_context() const { return context; } swap_chain_t direct3d::get_swap_chain() const { return swap_chain; } device_t direct3d::get_device() const { return device; } void direct3d::make_device() { uint32_t flags{}; flags |= D3D11_CREATE_DEVICE_BGRA_SUPPORT; // Needed for Direct 2D; #ifdef _DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif // _DEBUG std::array<D3D_FEATURE_LEVEL, 1> feature_levels{ D3D_FEATURE_LEVEL_11_0 }; auto hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, flags, feature_levels.data(), static_cast<uint32_t>(feature_levels.size()), D3D11_SDK_VERSION, &device, nullptr, &context); assert(hr == S_OK); } void direct3d::make_swap_chain() { HRESULT hr{}; CComPtr<IDXGIDevice> dxgi_device{}; hr = device->QueryInterface<IDXGIDevice>(&dxgi_device); assert(hr == S_OK); CComPtr<IDXGIAdapter> dxgi_adapter{}; hr = dxgi_device->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void **>(&dxgi_adapter)); assert(hr == S_OK); CComPtr<IDXGIFactory> dxgi_factory{}; hr = dxgi_adapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void **>(&dxgi_factory)); assert(hr == S_OK); auto [width, height] = get_window_size(window_handle); DXGI_SWAP_CHAIN_DESC sd{}; sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = swap_chain_format; sd.BufferDesc.RefreshRate = get_refresh_rate(dxgi_adapter, window_handle); sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = window_handle; sd.SampleDesc = get_msaa_level(device); sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; sd.Windowed = TRUE; hr = dxgi_factory->CreateSwapChain(device, &sd, &swap_chain); assert(hr == S_OK); dxgi_factory->MakeWindowAssociation(window_handle, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); } #pragma endregion #pragma region "Render Target" render_target::render_target(direct3d_types::device_t device, direct3d_types::swap_chain_t swap_chain) { auto [width, height] = get_swap_chain_size(swap_chain); make_target_view(device, swap_chain); make_stencil_view(device, {width, height}); viewport = {}; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; } render_target::~render_target() {} void render_target::activate(context_t context) { context->OMSetRenderTargets(1, &render_view.p, depth_view); context->RSSetViewports(1, &viewport); } void render_target::clear_views(context_t context, const std::array<float, 4> &clear_color) { context->ClearRenderTargetView(render_view, &clear_color[0]); context->ClearDepthStencilView(depth_view, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } void render_target::make_target_view(device_t device, swap_chain_t swap_chain) { texture_2d_t buffer = nullptr; auto hr = swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&buffer.p)); assert(hr == S_OK); hr = device->CreateRenderTargetView(buffer, 0, &render_view); assert(hr == S_OK); } void render_target::make_stencil_view(device_t device, const std::array<uint16_t, 2> &buffer_size) { auto [width, height] = buffer_size; D3D11_TEXTURE2D_DESC td{}; td.Width = width; td.Height = height; td.MipLevels = 1; td.ArraySize = 1; td.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; td.Usage = D3D11_USAGE_DEFAULT; td.BindFlags = D3D11_BIND_DEPTH_STENCIL; td.SampleDesc = get_msaa_level(device); auto hr = device->CreateTexture2D(&td, 0, &depth_buffer); assert(hr == S_OK); hr = device->CreateDepthStencilView(depth_buffer, 0, &depth_view); assert(hr == S_OK); } #pragma endregion #pragma region "Pipeline State" pipeline_state::pipeline_state(device_t device, const description &state_description) { make_blend_state(device, state_description.blend); make_depth_stencil_state(device, state_description.depth_stencil); make_rasterizer_state(device, state_description.rasterizer); make_sampler_state(device, state_description.sampler); make_input_layout(device, state_description.input_layout, state_description.vertex_shader_file); make_vertex_shader(device, state_description.vertex_shader_file); make_pixel_shader(device, state_description.pixel_shader_file); primitive_topology = state_description.primitive_topology; } pipeline_state::~pipeline_state() {} void pipeline_state::activate(context_t context) { context->OMSetBlendState(blend_state, DirectX::Colors::Transparent, 0xffff'ffff); context->OMSetDepthStencilState(depth_stencil_state, NULL); context->RSSetState(rasterizer_state); context->PSSetSamplers(0, 1, &sampler_state.p); context->IASetPrimitiveTopology(primitive_topology); context->IASetInputLayout(input_layout); context->VSSetShader(vertex_shader, nullptr, 0); context->PSSetShader(pixel_shader, nullptr, 0); } void pipeline_state::make_blend_state(device_t device, blend_e blend) { D3D11_BLEND src{}, dst{}; D3D11_BLEND_OP op{ D3D11_BLEND_OP_ADD }; switch (blend) { case blend_e::Opaque: src = D3D11_BLEND_ONE; dst = D3D11_BLEND_ZERO; break; case blend_e::Alpha: src = D3D11_BLEND_ONE; dst = D3D11_BLEND_INV_SRC_ALPHA; break; case blend_e::Additive: src = D3D11_BLEND_SRC_ALPHA; dst = D3D11_BLEND_ONE; break; case blend_e::NonPremultipled: src = D3D11_BLEND_SRC_ALPHA; dst = D3D11_BLEND_INV_SRC_ALPHA; break; } D3D11_BLEND_DESC bd{}; bd.RenderTarget[0].BlendEnable = ((src != D3D11_BLEND_ONE) || (dst != D3D11_BLEND_ONE)); bd.RenderTarget[0].SrcBlend = src; bd.RenderTarget[0].BlendOp = op; bd.RenderTarget[0].DestBlend = dst; bd.RenderTarget[0].SrcBlendAlpha = src; bd.RenderTarget[0].BlendOpAlpha = op; bd.RenderTarget[0].DestBlendAlpha = dst; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; auto hr = device->CreateBlendState(&bd, &blend_state); assert(hr == S_OK); } void pipeline_state::make_depth_stencil_state(device_t device, depth_stencil_e depth_stencil) { bool depth_enable{ false }, write_enable{ false }; switch (depth_stencil) { case depth_stencil_e::None: depth_enable = false; write_enable = false; break; case depth_stencil_e::ReadWrite: depth_enable = true; write_enable = true; break; case depth_stencil_e::ReadOnly: depth_enable = true; write_enable = false; break; } D3D11_DEPTH_STENCIL_DESC dsd{}; dsd.DepthEnable = depth_enable; dsd.DepthWriteMask = write_enable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; dsd.StencilEnable = false; dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; dsd.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; dsd.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; dsd.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsd.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsd.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; dsd.BackFace = dsd.FrontFace; auto hr = device->CreateDepthStencilState(&dsd, &depth_stencil_state); assert(hr == S_OK); } void pipeline_state::make_rasterizer_state(device_t device, rasterizer_e rasterizer) { D3D11_CULL_MODE cull_mode{}; D3D11_FILL_MODE fill_mode{}; switch (rasterizer) { case rasterizer_e::CullNone: cull_mode = D3D11_CULL_NONE; fill_mode = D3D11_FILL_SOLID; break; case rasterizer_e::CullClockwise: cull_mode = D3D11_CULL_FRONT; fill_mode = D3D11_FILL_SOLID; break; case rasterizer_e::CullAntiClockwise: cull_mode = D3D11_CULL_BACK; fill_mode = D3D11_FILL_SOLID; break; case rasterizer_e::Wireframe: cull_mode = D3D11_CULL_BACK; fill_mode = D3D11_FILL_WIREFRAME; break; } D3D11_RASTERIZER_DESC rd{}; rd.CullMode = cull_mode; rd.FillMode = fill_mode; rd.DepthClipEnable = true; rd.MultisampleEnable = true; auto hr = device->CreateRasterizerState(&rd, &rasterizer_state); assert(hr == S_OK); } void pipeline_state::make_sampler_state(device_t device, sampler_e sampler) { D3D11_FILTER filter{}; D3D11_TEXTURE_ADDRESS_MODE texture_address_mode{}; switch (sampler) { case sampler_e::PointWrap: filter = D3D11_FILTER_MIN_MAG_MIP_POINT; texture_address_mode = D3D11_TEXTURE_ADDRESS_WRAP; break; case sampler_e::PointClamp: filter = D3D11_FILTER_MIN_MAG_MIP_POINT; texture_address_mode = D3D11_TEXTURE_ADDRESS_CLAMP; break; case sampler_e::LinearWrap: filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; texture_address_mode = D3D11_TEXTURE_ADDRESS_WRAP; break; case sampler_e::LinearClamp: filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; texture_address_mode = D3D11_TEXTURE_ADDRESS_CLAMP; break; case sampler_e::AnisotropicWrap: filter = D3D11_FILTER_ANISOTROPIC; texture_address_mode = D3D11_TEXTURE_ADDRESS_WRAP; break; case sampler_e::AnisotropicClamp: filter = D3D11_FILTER_ANISOTROPIC; texture_address_mode = D3D11_TEXTURE_ADDRESS_CLAMP; break; } D3D11_SAMPLER_DESC sd{ }; sd.Filter = filter; sd.AddressU = texture_address_mode; sd.AddressV = texture_address_mode; sd.AddressW = texture_address_mode; sd.MaxAnisotropy = max_anisotropy; sd.MaxLOD = FLT_MAX; sd.ComparisonFunc = D3D11_COMPARISON_NEVER; auto hr = device->CreateSamplerState(&sd, &sampler_state); assert(hr == S_OK); } void pipeline_state::make_input_layout(device_t device, input_layout_e layout, const std::vector<byte> &vso) { element_desc elements; switch (layout) { case input_layout_e::position: elements = { position }; break; case input_layout_e::position_texcoord: elements = { position, texcoord }; break; } auto hr = device->CreateInputLayout(elements.data(), static_cast<uint32_t>(elements.size()), vso.data(), static_cast<uint32_t>(vso.size()), &input_layout); assert(hr == S_OK); } void pipeline_state::make_vertex_shader(device_t device, const std::vector<byte> &vso) { auto hr = device->CreateVertexShader(vso.data(), vso.size(), NULL, &vertex_shader); assert(hr == S_OK); } void pipeline_state::make_pixel_shader(device_t device, const std::vector<byte> &pso) { auto hr = device->CreatePixelShader(pso.data(), pso.size(), NULL, &pixel_shader); assert(hr == S_OK); } #pragma endregion #pragma region "Mesh Buffer" mesh_buffer::mesh_buffer(device_t device, const std::vector<vertex> &vertex_array, const std::vector<uint32_t> &index_array) { make_vertex_buffer(device, vertex_array); make_index_buffer(device, index_array); } mesh_buffer::~mesh_buffer() {} void mesh_buffer::activate(context_t context) { context->IASetVertexBuffers(0, 1, &(vertex_buffer.p), &vertex_size, &vertex_offset); context->IASetIndexBuffer(index_buffer, DXGI_FORMAT_R32_UINT, index_offset); } void mesh_buffer::draw(context_t context) { context->DrawIndexed(index_count, 0, 0); } void mesh_buffer::make_vertex_buffer(device_t device, const std::vector<vertex> &vertex_array) { vertex_size = sizeof(vertex_array.back()); D3D11_BUFFER_DESC bd{}; bd.Usage = D3D11_USAGE_DEFAULT; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = NULL; bd.ByteWidth = vertex_size * static_cast<uint32_t>(vertex_array.size()); D3D11_SUBRESOURCE_DATA vertex_data{}; vertex_data.pSysMem = reinterpret_cast<const void *>(vertex_array.data()); auto hr = device->CreateBuffer(&bd, &vertex_data, &vertex_buffer); assert(hr == S_OK); } void mesh_buffer::make_index_buffer(device_t device, const std::vector<uint32_t>& index_array) { index_count = static_cast<uint32_t>(index_array.size()); D3D11_BUFFER_DESC bd{}; bd.Usage = D3D11_USAGE_DEFAULT; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = NULL; bd.ByteWidth = sizeof(uint32_t) * index_count; D3D11_SUBRESOURCE_DATA index_data{}; index_data.pSysMem = reinterpret_cast<const void *>(index_array.data()); auto hr = device->CreateBuffer(&bd, &index_data, &index_buffer); assert(hr == S_OK); } #pragma endregion
27.360522
159
0.687992
[ "mesh", "render", "vector" ]
9dd470be09da6d0359fbe5d2849b55d1dbec2fec
2,047
cpp
C++
src/engine/texture-generator/method/PerlinNoise3D.cpp
stanfortonski/Procedural-Terrain-Generator-OpenGL
a88bf2d7a44e7efa10dd980147e2bad0d1a782bf
[ "MIT" ]
93
2020-03-06T21:40:48.000Z
2022-03-28T06:30:55.000Z
texture-generator/method/PerlinNoise3D.cpp
stanfortonski/3D-Engine-OpenGL-4
6086d006b5027bc43169605dc3bb5c9575335f51
[ "MIT" ]
1
2021-08-31T07:56:37.000Z
2021-08-31T16:06:35.000Z
src/engine/texture-generator/method/PerlinNoise3D.cpp
stanfortonski/Procedural-Terrain-Generator-OpenGL
a88bf2d7a44e7efa10dd980147e2bad0d1a782bf
[ "MIT" ]
10
2020-06-06T11:21:35.000Z
2022-03-24T01:55:20.000Z
/* Copyright (c) 2020 by Stan Fortoński */ /* Perlin noise from GLM library to generate 3d textures */ /* Based on: OpenGL 4 ShadingLanguage Cookbook Second Edition David Wolff */ #include "PerlinNoise3D.hpp" namespace Engine { PerlinNoise3D::PerlinNoise3D(const double & pFrequency, const double & pAmplitude, const double & pPersistance, const unsigned & pOctaves, const double & pMulitplier, const unsigned & pOffsetX, const unsigned & pOffsetY, const unsigned & pOffsetZ) : frequency(pFrequency), amplitude(pAmplitude), persistence(pPersistance), octaves(pOctaves), multiplier(pMulitplier), offsetX(pOffsetX), offsetY(pOffsetY), offsetZ(pOffsetZ){;} double PerlinNoise3D::octavePerlin(const double & x, const double & y, const double & z) const { double total = 0; double freq = frequency; double amp = amplitude; double maxValue = 0; for (unsigned i = 0; i < octaves; ++i) { glm::vec3 p((x * freq + offsetX) * multiplier, (y * freq + offsetY) * multiplier, (z * freq + offsetZ) * multiplier); total += ((glm::simplex(p) + 1.0)/2.0) * amp; maxValue += amp; amp *= persistence; freq *= 2; } return total/maxValue; } void PerlinNoise3D::fillData(std::vector<GLubyte> & data, const unsigned & width, const unsigned & height, const unsigned & depth) const { double xFactor = 1.0 / (width - 1); double yFactor = 1.0 / (height - 1); double zFactor = 1.0 / (depth - 1); for (unsigned w = 0; w < width; ++w) { for (unsigned h = 0; h < height; ++h) { for (unsigned d = 0; d < depth; ++d) { double x = xFactor * w; double y = yFactor * h; double z = zFactor * d; double perlin = octavePerlin(x, y, z); GLubyte result = (GLubyte)(perlin * 255); unsigned index = w*width*height*4 + h*height*4 + d*4; data[index] = result; data[index+1] = result; data[index+2] = result; data[index+3] = result; } } } } }
35.293103
249
0.608207
[ "vector", "3d" ]
9dd76285596ac91c14924dbb4e379f6b3bb9b2e0
1,368
cpp
C++
SubwayParis/subwayparismain.cpp
tenoriomatheus/AI_Search
d71e86c88c933d039ad1b14c2099910af2406de8
[ "MIT" ]
null
null
null
SubwayParis/subwayparismain.cpp
tenoriomatheus/AI_Search
d71e86c88c933d039ad1b14c2099910af2406de8
[ "MIT" ]
3
2016-02-20T19:32:23.000Z
2016-02-20T19:44:13.000Z
SubwayParis/subwayparismain.cpp
tenoriomatheus/AI_Search
d71e86c88c933d039ad1b14c2099910af2406de8
[ "MIT" ]
null
null
null
#include <SubwayParis/subwayparisstate.h> #include <solver.h> #include <bfs.h> #include <astar.h> #include <iterativedfs.h> using namespace AI_Search; int main2(int argc, char* argv[]) { int initialId = 8; int goalId = 7; State<int>* initialState = new SubwayParisState(initialId, nullptr, new SubwayParisOperator(nullptr, 0, LINE_COLOR::NONE), 0, 0, goalId); State<int>* finalState = new SubwayParisState(goalId, nullptr, new SubwayParisOperator(nullptr, 0, LINE_COLOR::NONE), 0, 0, 0); Solver<int>* solver = new Solver<int>(initialState, finalState, new AStar<int>(initialState), true, false); solver->solve(); std::vector<Operator<int>*> traceOfOperator = solver->getTraceOfOperators(); if (traceOfOperator.size() != 0) { std::cout << "\nInitial State: " << solver->getInitialState()->toString() << std::endl; std::cout << "\nFinal State: " << solver->getFinalState()->toString() << std::endl; std::cout << "\n--List of Operators--" << std::endl; for (Operator<int>* op : traceOfOperator) { SubwayParisOperator* op2 = dynamic_cast<SubwayParisOperator*>(op); if (op != nullptr) std::cout << op2->toString(); } std::cout << std::endl; } else { std::cout << "--No Solution--" << std::endl << std::endl; } return 0; }
34.2
141
0.620614
[ "vector" ]
9ddfae7cba0836cab95dae144aef3231845c8007
3,156
cpp
C++
FPSGame/src/Model.cpp
brizzbrett/ObjectiveBasedFPS
d29eb3885a4399f0e20556b0571a1bb7a55c3476
[ "MIT" ]
null
null
null
FPSGame/src/Model.cpp
brizzbrett/ObjectiveBasedFPS
d29eb3885a4399f0e20556b0571a1bb7a55c3476
[ "MIT" ]
null
null
null
FPSGame/src/Model.cpp
brizzbrett/ObjectiveBasedFPS
d29eb3885a4399f0e20556b0571a1bb7a55c3476
[ "MIT" ]
null
null
null
#include "Model.hpp" Model::Model(GLchar* path) { this->loadModel(path); } void Model::Render(Shader* s) { for (GLuint i = 0; i < this->meshes.size(); i++) this->meshes[i].Render(s); } void Model::loadModel(std::string path) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } this->directory = path.substr(0, path.find_last_of('/')); this->processNode(scene->mRootNode, scene); } void Model::processNode(aiNode* node, const aiScene* scene) { for (GLuint i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; this->meshes.push_back(this->processMesh(mesh, scene)); } for (GLuint i = 0; i < node->mNumChildren; i++) { this->processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector<Vertex> vertices; std::vector<GLuint> indices; std::vector<Texture> textures; for (GLuint i = 0; i < mesh->mNumVertices; i++) { Vertex temp; glm::vec3 vector; vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; temp.position = vector; vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; temp.normal = vector; if (mesh->mTextureCoords[0]) { glm::vec2 vec; vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; temp.texels = vec; } else { temp.texels = glm::vec2(0.0f, 0.0f); } vertices.push_back(temp); } for (GLuint i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (GLuint j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } if (mesh->mMaterialIndex >= 0) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; std::vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); std::vector<Texture> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); } return Mesh(vertices, indices, textures); } std::vector<Texture> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName) { std::vector<Texture> textures; for (GLuint i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); GLboolean skip = false; for (GLuint j = 0; j < textures_loaded.size(); j++) { if (std::strcmp(textures_loaded[j].path.C_Str(), str.C_Str()) == 0) { textures.push_back(textures_loaded[j]); skip = true; break; } } if (!skip) { Texture texture; texture.id = LoadTexture(str.C_Str(), true); texture.type = typeName; texture.path = str; textures.push_back(texture); this->textures_loaded.push_back(texture); } } return textures; }
23.552239
119
0.663181
[ "mesh", "render", "vector", "model" ]
9de0543ed022d61470daca895a6282b7e2bb5dd3
9,214
cpp
C++
methods/lexdfs/search/OverlappingEdgeColors.cpp
ix-labs/codacom
41b3a96d0f5efa15676810dfb0638f59226baf62
[ "CECILL-B" ]
1
2017-07-23T14:27:40.000Z
2017-07-23T14:27:40.000Z
methods/lexdfs/search/OverlappingEdgeColors.cpp
ix-labs/codacom
41b3a96d0f5efa15676810dfb0638f59226baf62
[ "CECILL-B" ]
null
null
null
methods/lexdfs/search/OverlappingEdgeColors.cpp
ix-labs/codacom
41b3a96d0f5efa15676810dfb0638f59226baf62
[ "CECILL-B" ]
null
null
null
// Copyright GREYC - UMR 6072 ; Université de Caen Normandie // Esplanade de la paix // CS 14032 // 14032 Caen CEDEX 5 // contributeur : // Jean Creusefond, 2015 // // jean.creusefond@unicaen.fr // // Ce logiciel est un programme informatique servant à la comparaison et à l'analyse d'outils de détection de communauté. // // Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". // // En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. // // A cet égard l'attention de l'utilisateur est attirée sur les risques // associés au chargement, à l'utilisation, à la modification et/ou au // développement et à la reproduction du logiciel par l'utilisateur étant // donné sa spécificité de logiciel libre, qui peut le rendre complexe à // manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. // // Le fait que vous puissiez accéder à cet en-tête signifie que vous avez // pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. // // ========================================================================== // // Copyright GREYC - UMR 6072 ; Université de Caen Normandie // Esplanade de la paix // CS 14032 // 14032 Caen CEDEX 5 // contributor(s) : // Jean Creusefond, 2015 // // jean.creusefond@unicaen.fr // // This software is a computer program whose purpose is to compare and analyse community detection tools. // // This software is governed by the CeCILL-B license under French law and // abiding by the rules of distribution of free software. You can use, // modify and/ or redistribute the software under the terms of the CeCILL-B // license as circulated by CEA, CNRS and INRIA at the following URL // "http://www.cecill.info". // // As a counterpart to the access to the source code and rights to copy, // modify and redistribute granted by the license, users are provided only // with a limited warranty and the software's author, the holder of the // economic rights, and the successive licensors have only limited // liability. // // In this respect, the user's attention is drawn to the risks associated // with loading, using, modifying and/or developing or reproducing the // software by the user in light of its specific status of free software, // that may mean that it is complicated to manipulate, and that also // therefore means that it is reserved for developers and experienced // professionals having in-depth computer knowledge. Users are therefore // encouraged to load and test the software's suitability as regards their // requirements in conditions enabling the security of their systems and/or // data to be ensured and, more generally, to use and operate it in the // same conditions as regards security. // // The fact that you are presently reading this means that you have had // knowledge of the CeCILL-B license and that you accept its terms. #include "OverlappingEdgeColors.hpp" #include <iostream> #include <fstream> #define UPPER_BOUND 100000 typedef boost::graph_traits<Graph>::edge_iterator edge_iter; EdgeCommunities::EdgeCommunities(Graph& _g) : g(_g) { communities.resize(g[boost::graph_bundle].m); } long domain(Graph& g) { //return g[boost::graph_bundle].m; return 10; } struct Constraint { long id_from; long id_to; bool equal; }; void write_constraints(std::string filepath, long m, long domain, double cost, std::list<Constraint> constraints) { std::ofstream outfile; outfile.open(filepath); outfile << "test " << m << " " << domain << " " << constraints.size() << " " << UPPER_BOUND << std::endl; for(long i = 0; i<m; i++) outfile << domain << " "; outfile << std::endl << std::endl; for(std::list<Constraint>::iterator it = constraints.begin(); it != constraints.end(); it++) { double default_cost, exception_cost; if(it->equal) { default_cost = 1; exception_cost = 0; } else { default_cost = 0; exception_cost = cost; } outfile << "2 " << it->id_from << " " << it->id_to << " " << default_cost << " " << domain << std::endl; for(long i =0; i<domain; i++) outfile << i << " " << i << " " << exception_cost << std::endl; outfile << std::endl; } outfile.close(); } void read_solution(std::string filepath, std::vector<long>& communities) { std::ifstream infile; infile.open(filepath); long edge_id = 0; long com_val; while(infile >> com_val) { communities[edge_id] = com_val; edge_id++; } infile.close(); } void EdgeCommunities::execute(std::string input_file, std::string output_file, std::string execute_command, double cost) { std::vector<bool> treated; treated.resize(g[boost::graph_bundle].m); std::list<Constraint> constraints; std::pair<edge_iter, edge_iter> iter; for (iter = edges(g); iter.first != iter.second; ++iter.first) treated[g[*(iter.first)].id] = false; for (iter = edges(g); iter.first != iter.second; ++iter.first) { long e1_id = g[*(iter.first)].id; treated[e1_id] = true; vertex_t u1 = boost::source(*(iter.first),g); vertex_t v1 = boost::target(*(iter.first), g); //std::cout << "edge id : " << e1_id << " u label : " << g[u1].label << " v label : " << g[v1].label << std::endl; typename boost::graph_traits<Graph>::out_edge_iterator out_i, out_end; //Loop over the out edges of both ends for(int i = 0; i<2; i++) { for (tie(out_i, out_end) = out_edges(u1, g); out_i != out_end; ++out_i) { edge_t e2 = *out_i; long e2_id = g[e2].id; if(!treated[e2_id]) { Constraint c; c.id_from = std::min(e1_id, e2_id); c.id_to = std::max(e1_id, e2_id); vertex_t u2 = boost::source(e2, g); vertex_t v2 = boost::target(e2, g); if(u2 == u1) u2 = v2; if((edge(v1, u2, g)).second) { //If an edge was found, there is a triangle c.equal = true; } else { c.equal = false; } //std::cout << c.id_from << " " << c.id_to << " " << c.equal << std::endl; constraints.push_back(c); } } vertex_t tmp = u1; u1 = v1; v1 = tmp; } } std::cout << "Finish constraints" << std::endl; write_constraints(input_file, g[boost::graph_bundle].m, domain(g), cost, constraints); std::cout << "Finish write" << std::endl; read_solution(output_file, communities); } void EdgeCommunities::apply() { std::pair<edge_iter, edge_iter> iter; for (iter = edges(g); iter.first != iter.second; ++iter.first) { long edge_id = g[*(iter.first)].id; g[*(iter.first)].community = communities[edge_id]; } } //Obsolete : first draft // void Coloring::update_edge(edge_t e, std::vector<std::vector<double> >& map) { // vertex_t u1 = boost::source(e,g); // vertex_t v1 = boost::target(e,g); // long edge_id = g[e].id; // std::vector<double> delta; // for(int i = 0; i<d; i++) // delta.push_back(0.0); // typename boost::graph_traits<Graph>::out_edge_iterator out_i, out_end; // for (tie(out_i, out_end) = out_edges(u1, g); out_i != out_end; ++out_i) { // edge_t e2 = *out_i; // vertex_t u2 = boost::source(e2, g); // vertex_t v2 = boost::target(e2, g); // if(u2 == u1) // u2 = v2; // if((edge(v1, u2, g)).second) { //If an edge was found, there is a triangle // for(int i = 0; i<d; i++) // delta[i] += (colors[g[e2].id][i] - colors[edge_id][i])/2; // } else { // for(int i = 0; i<d; i++) // delta[i] += (-colors[g[e2].id][i] + colors[edge_id][i])/2; // } // } // for (tie(out_i, out_end) = out_edges(v1, g); out_i != out_end; ++out_i) { // edge_t e2 = *out_i; // vertex_t u2 = boost::source(e2, g); // vertex_t v2 = boost::target(e2, g); // if(u2 == v1) // u2 = v2; // if((edge(v1, u2, g)).second) { //If an edge was found, there is a triangle // for(int i = 0; i<d; i++) // delta[i] += (colors[g[e2].id][i] - colors[edge_id][i])/2; // } else { // for(int i = 0; i<d; i++) // delta[i] += (-colors[g[e2].id][i] + colors[edge_id][i])/2; // } // } // for(int i = 0; i<d; i++) // map[edge_id].push_back(0.0); // for(int i = 0; i<d; i++) { // map[edge_id][i] = colors[edge_id][i] + delta[i]/(g[u1].degree + g[v1].degree - 2); // if(map[edge_id][i] > 1) // map[edge_id][i] = 1; // if(map[edge_id][i] < 0) // map[edge_id][i] = 0; // } // }
37.917695
428
0.648687
[ "vector" ]
9de543fe651172fa9294633f9fc53d315789d6d0
1,022
cpp
C++
Sliding Window/1423_Maximum-Points-You-Can-Obtain-from-Cards/1423_Maximum-Points-You-Can-Obtain-from-Cards.cpp
YunWGui/LeetCode
2587eca22195ec7d9263227554467ec4010cfe05
[ "MIT" ]
null
null
null
Sliding Window/1423_Maximum-Points-You-Can-Obtain-from-Cards/1423_Maximum-Points-You-Can-Obtain-from-Cards.cpp
YunWGui/LeetCode
2587eca22195ec7d9263227554467ec4010cfe05
[ "MIT" ]
null
null
null
Sliding Window/1423_Maximum-Points-You-Can-Obtain-from-Cards/1423_Maximum-Points-You-Can-Obtain-from-Cards.cpp
YunWGui/LeetCode
2587eca22195ec7d9263227554467ec4010cfe05
[ "MIT" ]
null
null
null
/******************************************************************************* * Title: * 1423. Maximum Points You Can Obtain from Cards * 1423. 可获得的最大点数 * Address: * https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards/ ******************************************************************************/ #include <iostream> #include <vector> #include <numeric> using namespace std; // 方法一:滑动窗口 class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int maxPoints = accumulate( cardPoints.begin(), cardPoints.begin() + k, 0 ); int sumPoints = maxPoints; // [1, 2, 3, 4, 5, 6, 1], k = 3 // <--i <--j # i, j 移动方向,使得窗口大小始终是 k int i = k - 1, j = cardPoints.size() - 1; while ( i >= 0 ) { sumPoints = sumPoints - cardPoints[i--] + cardPoints[j--]; maxPoints = max( maxPoints, sumPoints ); } return maxPoints; } }; int main() { return 0; }
25.55
84
0.460861
[ "vector" ]
9def4ba0d0b384cf87aaa243915d3d5f2cfcc86e
568
cpp
C++
aws-cpp-sdk-greengrass/source/model/DeleteFunctionDefinitionRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-greengrass/source/model/DeleteFunctionDefinitionRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-greengrass/source/model/DeleteFunctionDefinitionRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/greengrass/model/DeleteFunctionDefinitionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Greengrass::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest() : m_functionDefinitionIdHasBeenSet(false) { } Aws::String DeleteFunctionDefinitionRequest::SerializePayload() const { return {}; }
20.285714
69
0.769366
[ "model" ]
9dfb6185b36e91180fcd10f6ffbd2007a49f0b6e
4,417
cpp
C++
source/Library.Shared/ShadowcastedDirectionalEffect.cpp
DakkyDaWolf/OpenGL
628e9aed116022175cc0c59c88ace7688309628c
[ "MIT" ]
null
null
null
source/Library.Shared/ShadowcastedDirectionalEffect.cpp
DakkyDaWolf/OpenGL
628e9aed116022175cc0c59c88ace7688309628c
[ "MIT" ]
null
null
null
source/Library.Shared/ShadowcastedDirectionalEffect.cpp
DakkyDaWolf/OpenGL
628e9aed116022175cc0c59c88ace7688309628c
[ "MIT" ]
null
null
null
#include "pch.h" #include "ShadowcastedDirectionalEffect.h" #include "Mesh.h" #include "VertexDeclarations.h" using namespace glm; using namespace std; namespace Library { RTTI_DEFINITIONS(ShadowcastedDirectionalEffect) ShadowcastedDirectionalEffect::ShadowcastedDirectionalEffect() : SHADER_VARIABLE_INITIALIZATION(WorldViewProjection), SHADER_VARIABLE_INITIALIZATION(World), SHADER_VARIABLE_INITIALIZATION(AmbientColor), SHADER_VARIABLE_INITIALIZATION(LightColor), SHADER_VARIABLE_INITIALIZATION(LightLookDirection), SHADER_VARIABLE_INITIALIZATION(CameraPosition), SHADER_VARIABLE_INITIALIZATION(SpecularColor), SHADER_VARIABLE_INITIALIZATION(SpecularPower), SHADER_VARIABLE_INITIALIZATION(FogColor), SHADER_VARIABLE_INITIALIZATION(FogStart), SHADER_VARIABLE_INITIALIZATION(FogRange), SHADER_VARIABLE_INITIALIZATION(LightPosition), SHADER_VARIABLE_INITIALIZATION(LightInnerAngle), SHADER_VARIABLE_INITIALIZATION(LightOuterAngle), SHADER_VARIABLE_INITIALIZATION(LightFalloffRange) { } SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, WorldViewProjection) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, World) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, AmbientColor) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, LightColor) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, LightLookDirection) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, CameraPosition) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, SpecularColor) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, SpecularPower) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, FogColor) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, FogStart) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, FogRange) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, LightPosition) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, LightInnerAngle) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, LightOuterAngle) SHADER_VARIABLE_DEFINITION(ShadowcastedDirectionalEffect, LightFalloffRange) void ShadowcastedDirectionalEffect::Initialize(GLuint vertexArrayObject) { ShaderProgram::Initialize(vertexArrayObject); SHADER_VARIABLE_INSTANTIATE(WorldViewProjection) SHADER_VARIABLE_INSTANTIATE(World) SHADER_VARIABLE_INSTANTIATE(AmbientColor) SHADER_VARIABLE_INSTANTIATE(LightColor) SHADER_VARIABLE_INSTANTIATE(LightLookDirection) SHADER_VARIABLE_INSTANTIATE(CameraPosition) SHADER_VARIABLE_INSTANTIATE(SpecularColor) SHADER_VARIABLE_INSTANTIATE(SpecularPower) SHADER_VARIABLE_INSTANTIATE(FogColor) SHADER_VARIABLE_INSTANTIATE(FogStart) SHADER_VARIABLE_INSTANTIATE(FogRange) SHADER_VARIABLE_INSTANTIATE(LightPosition) SHADER_VARIABLE_INSTANTIATE(LightInnerAngle) SHADER_VARIABLE_INSTANTIATE(LightOuterAngle) SHADER_VARIABLE_INSTANTIATE(LightFalloffRange) glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::Position), 4, GL_FLOAT, GL_FALSE, sizeof(VertexPositionTextureNormalTangentBinormal), (void*)offsetof(VertexPositionTextureNormalTangentBinormal, Position)); glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::Position)); glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::TextureCoordinate), 2, GL_FLOAT, GL_FALSE, sizeof(VertexPositionTextureNormalTangentBinormal), (void*)offsetof(VertexPositionTextureNormalTangentBinormal, TextureCoordinates)); glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::TextureCoordinate)); glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::Normal), 3, GL_FLOAT, GL_FALSE, sizeof(VertexPositionTextureNormalTangentBinormal), (void*)offsetof(VertexPositionTextureNormalTangentBinormal, Normal)); glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::Normal)); glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::Tangent), 3, GL_FLOAT, GL_FALSE, sizeof(VertexPositionTextureNormalTangentBinormal), (void*)offsetof(VertexPositionTextureNormalTangentBinormal, Tangent)); glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::Tangent)); glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::Binormal), 3, GL_FLOAT, GL_FALSE, sizeof(VertexPositionTextureNormalTangentBinormal), (void*)offsetof(VertexPositionTextureNormalTangentBinormal, Binormal)); glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::Binormal)); } }
57.363636
237
0.876839
[ "mesh" ]
9dfdb24b11629b1c8301092f8c82581f1f34f5bf
55,310
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/CStrictMode.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/CStrictMode.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/CStrictMode.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/os/CStrictMode.h" #include "elastos/droid/os/CStrictModeSpan.h" #include "elastos/droid/os/CStrictModeViolationInfo.h" #include "elastos/droid/os/Build.h" #include "elastos/droid/os/Binder.h" #include "elastos/droid/os/Looper.h" #include "elastos/droid/os/Process.h" #include "elastos/droid/os/CHandler.h" #include "elastos/droid/os/SystemClock.h" #include "elastos/droid/os/ServiceManager.h" #include "elastos/droid/os/SystemProperties.h" #include "elastos/droid/os/CStrictModeVmPolicyBuilder.h" #include "elastos/droid/os/CStrictModeThreadPolicyBuilder.h" #include "elastos/droid/app/ActivityManagerNative.h" #include <elastos/core/AutoLock.h> #include <elastos/utility/logging/Logger.h> #include <elastos/core/StringUtils.h> #include <Elastos.Droid.Os.h> #include <Elastos.Droid.App.h> #include <Elastos.Droid.View.h> #include <Elastos.Droid.Utility.h> #include <Elastos.CoreLibrary.Utility.h> #include <Elastos.CoreLibrary.Utility.Concurrent.h> #include <pthread.h> using Elastos::Droid::Os::Build; using Elastos::Droid::Os::Binder; using Elastos::Droid::Os::Process; using Elastos::Droid::Os::ILooper; using Elastos::Droid::Os::Looper; using Elastos::Droid::Os::IHandler; using Elastos::Droid::Os::CHandler; using Elastos::Droid::Os::SystemClock; using Elastos::Droid::Os::ServiceManager; using Elastos::Droid::Os::SystemProperties; using Elastos::Droid::Os::IStrictModeSpan; using Elastos::Droid::Os::CStrictModeSpan; using Elastos::Droid::Os::IStrictModeViolationInfo; using Elastos::Droid::Os::CStrictModeViolationInfo; using Elastos::Droid::Os::IStrictModeThreadPolicyBuilder; using Elastos::Droid::Os::CStrictModeThreadPolicyBuilder; using Elastos::Droid::Os::IStrictModeVmPolicyBuilder; using Elastos::Droid::Os::CStrictModeVmPolicyBuilder; using Elastos::Droid::App::ActivityManagerNative; using Elastos::Droid::App::IIActivityManager; using Elastos::Core::StringUtils; using Elastos::Core::IBlockGuard; using Elastos::Core::CBlockGuard; using Elastos::Core::EIID_IBlockGuardPolicy; using Elastos::Core::ICloseGuard; using Elastos::Core::CCloseGuard; using Elastos::Core::EIID_ICloseGuardReporter; using Elastos::Core::ICloseGuardHelper; using Elastos::Core::CCloseGuardHelper; using Elastos::Utility::Concurrent::Atomic::CAtomicInteger32; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Os { static void ViolationInfosDestructor(void* st) { List<AutoPtr<IStrictModeViolationInfo> >* obj = static_cast<List<AutoPtr<IStrictModeViolationInfo> >*>(st); if (obj) { obj->Release(); } } static pthread_key_t InitSGatheredViolations() { pthread_key_t key; pthread_key_create(&key, ViolationInfosDestructor); return key; } static pthread_key_t InitSViolationsBeingTimed() { pthread_key_t key; pthread_key_create(&key, NULL); return key; } static void ThreadAndroidPolicyDestructor(void* st) { ICharSequence* callingPackage = static_cast<ICharSequence*>(st); if (callingPackage) { REFCOUNT_RELEASE(callingPackage) } } static void ThreadAndroidPolicyMakeKey() { ASSERT_TRUE(pthread_key_create(&CStrictMode::sThreadAndroidPolicyKey, ThreadAndroidPolicyDestructor) == 0); } const String CStrictMode::TAG("StrictMode"); const Boolean CStrictMode::LOG_V = FALSE; const Boolean CStrictMode::IS_USER_BUILD = Build::TYPE.Equals("user"); const Boolean CStrictMode::IS_ENG_BUILD = Build::TYPE.Equals("eng"); const Int64 CStrictMode::MIN_LOG_INTERVAL_MS = 1000; const Int64 CStrictMode::MIN_DIALOG_INTERVAL_MS = 30000; const Int32 CStrictMode::MAX_SPAN_TAGS = 20; const Int32 CStrictMode::MAX_OFFENSES_PER_LOOP = 10; const Int32 CStrictMode::ALL_THREAD_DETECT_BITS = IStrictMode::DETECT_DISK_WRITE | IStrictMode::DETECT_DISK_READ | IStrictMode::DETECT_NETWORK | IStrictMode::DETECT_CUSTOM; const Int32 CStrictMode::DETECT_VM_INSTANCE_LEAKS = 0x1000; const Int32 CStrictMode::DETECT_VM_FILE_URI_EXPOSURE = 0x4000; const Int32 CStrictMode::ALL_VM_DETECT_BITS = IStrictMode::DETECT_VM_CURSOR_LEAKS | IStrictMode::DETECT_VM_CLOSABLE_LEAKS | IStrictMode::DETECT_VM_ACTIVITY_LEAKS | DETECT_VM_INSTANCE_LEAKS | IStrictMode::DETECT_VM_REGISTRATION_LEAKS | DETECT_VM_FILE_URI_EXPOSURE; const Int32 CStrictMode::THREAD_PENALTY_MASK = IStrictMode::PENALTY_LOG | IStrictMode::PENALTY_DIALOG | IStrictMode::PENALTY_DEATH | IStrictMode::PENALTY_DROPBOX | IStrictMode::PENALTY_GATHER | IStrictMode::PENALTY_DEATH_ON_NETWORK | IStrictMode::PENALTY_FLASH; const Int32 CStrictMode::VM_PENALTY_MASK = IStrictMode::PENALTY_LOG | IStrictMode::PENALTY_DEATH | IStrictMode::PENALTY_DROPBOX; const AutoPtr<IAtomicInteger32> CStrictMode::sDropboxCallsInFlight = InitsDropboxCallsInFlight(); Int32 CStrictMode::sVmPolicyMask = 0; AutoPtr<CStrictMode::VmPolicy> CStrictMode::sVmPolicy = CStrictMode::VmPolicy::LAX; const HashMap<Handle32, Int32> CStrictMode::EMPTY_CLASS_LIMIT_MAP; const AutoPtr<CStrictMode::ThreadPolicy> CStrictMode::ThreadPolicy::LAX = new CStrictMode::ThreadPolicy(0); pthread_key_t CStrictMode::sThisThreadSpanStateKey; Boolean CStrictMode::sHaveThisThreadSpanStateKey = FALSE; pthread_key_t CStrictMode::sThreadHandlerKey; Boolean CStrictMode::sHaveThreadHandlerKey = FALSE; pthread_key_t CStrictMode::sThreadAndroidPolicyKey; pthread_once_t CStrictMode::sThreadAndroidPolicyKeyOnce = PTHREAD_ONCE_INIT; CAR_INTERFACE_IMPL(CStrictMode::ThreadPolicy, Object, IStrictModeThreadPolicy); CStrictMode::ThreadPolicy::ThreadPolicy(Int32 mask) : mMask(mask) { } ECode CStrictMode::ThreadPolicy::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = String("[StrictMode.ThreadPolicy; mask=") + StringUtils::ToString(mMask) + String("]"); return NOERROR; } const AutoPtr<CStrictMode::VmPolicy> CStrictMode::VmPolicy::LAX = new CStrictMode::VmPolicy(0, CStrictMode::EMPTY_CLASS_LIMIT_MAP); CAR_INTERFACE_IMPL(CStrictMode::VmPolicy, Object, IStrictModeVmPolicy); CStrictMode::VmPolicy::VmPolicy( /* [in] */ Int32 mask, /* [in] */ HashMap<Handle32, Int32> classInstanceLimit) : mMask(mask) , mClassInstanceLimit(classInstanceLimit) { // if (classInstanceLimit == null) { // throw new NullPointerException("classInstanceLimit == null"); // } } ECode CStrictMode::VmPolicy::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = String("[StrictMode.VmPolicy; mask=") + StringUtils::ToString(mMask) + "]"; return NOERROR; } pthread_key_t CStrictMode::sGatheredViolations = InitSGatheredViolations(); AutoPtr<IAtomicInteger32> CStrictMode::InitsDropboxCallsInFlight() { AutoPtr<IAtomicInteger32> ids; CAtomicInteger32::New(0, (IAtomicInteger32**)&ids); REFCOUNT_ADD(ids); return ids; } ECode CStrictMode::SetThreadPolicy( /* [in] */ IStrictModeThreadPolicy* policy) { CStrictMode::ThreadPolicy* tp = (CStrictMode::ThreadPolicy*)policy; SetThreadPolicyMask(tp->mMask); return NOERROR; } void CStrictMode::SetThreadPolicyMask( /* [in] */ Int32 policyMask) { // In addition to the Java-level thread-local in Dalvik's // BlockGuard, we also need to keep a native thread-local in // Binder in order to propagate the value across Binder calls, // even across native-only processes. The two are kept in // sync via the callback to onStrictModePolicyChange, below. SetBlockGuardPolicy(policyMask); // And set the Android native version... Binder::SetThreadStrictModePolicy(policyMask); } void CStrictMode::SetBlockGuardPolicy( /* [in] */ Int32 policyMask) { AutoPtr<IBlockGuard> helper; CBlockGuard::AcquireSingleton((IBlockGuard**)&helper); AutoPtr<IBlockGuardPolicy> policy; if (policyMask == 0) { helper->GetLaxPolicy((IBlockGuardPolicy**)&policy); helper->SetThreadPolicy(policy); return; } policy = NULL; helper->GetThreadPolicy((IBlockGuardPolicy**)&policy); AutoPtr<IAndroidBlockGuardPolicy> androidPolicy; if (IAndroidBlockGuardPolicy::Probe(policy)) { androidPolicy = IAndroidBlockGuardPolicy::Probe(policy); } else { pthread_once(&sThreadAndroidPolicyKeyOnce, ThreadAndroidPolicyMakeKey); androidPolicy = (IAndroidBlockGuardPolicy*)pthread_getspecific(sThreadAndroidPolicyKey); if (androidPolicy == NULL) { androidPolicy = new AndroidBlockGuardPolicy(0); ASSERT_TRUE(pthread_setspecific(sThreadAndroidPolicyKey, androidPolicy.Get()) == 0); androidPolicy->AddRef(); } helper->SetThreadPolicy(IBlockGuardPolicy::Probe(androidPolicy)); } androidPolicy->SetPolicyMask(policyMask); } void CStrictMode::SetCloseGuardEnabled( /* [in] */ Boolean enabled) { AutoPtr<ICloseGuardHelper> helper; CCloseGuardHelper::AcquireSingleton((ICloseGuardHelper**)&helper); AutoPtr<ICloseGuardReporter> reporter; helper->GetReporter((ICloseGuardReporter**)&reporter); if (reporter->Probe(EIID_IAndroidBlockGuardPolicy) != NULL) { AutoPtr<AndroidCloseGuardReporter> anRepoter = new AndroidCloseGuardReporter(); helper->SetReporter((ICloseGuardReporter*)anRepoter.Get()); } helper->SetEnabled(enabled); return; } CStrictMode::StrictModeViolation::StrictModeViolation( /* [in] */ Int32 policyState, /* [in] */ Int32 policyViolated, /* [in] */ const String& message) { // TODO: // super(policyState, policyViolated, message); } CStrictMode::StrictModeNetworkViolation::StrictModeNetworkViolation( /* [in] */ Int32 policyMask) : StrictModeViolation(policyMask, IStrictMode::DETECT_NETWORK, String(NULL)) { } CStrictMode::StrictModeDiskReadViolation::StrictModeDiskReadViolation( /* [in] */ Int32 policyMask) : StrictModeViolation(policyMask, IStrictMode::DETECT_DISK_READ, String(NULL)) { } CStrictMode::StrictModeDiskWriteViolation::StrictModeDiskWriteViolation( /* [in] */ Int32 policyMask) : StrictModeViolation(policyMask, IStrictMode::DETECT_DISK_WRITE, String(NULL)) { } CStrictMode::StrictModeCustomViolation::StrictModeCustomViolation( /* [in] */ Int32 policyMask, /* [in] */ const String& name) : StrictModeViolation(policyMask, IStrictMode::DETECT_CUSTOM, String(NULL)) { } ECode CStrictMode::GetThreadPolicyMask( /* [out] */ Int32* mask) { VALIDATE_NOT_NULL(mask); AutoPtr<IBlockGuard> helper; CBlockGuard::AcquireSingleton((IBlockGuard**)&helper); AutoPtr<IBlockGuardPolicy> policy; helper->GetThreadPolicy((IBlockGuardPolicy**)&policy); policy->GetPolicyMask(mask); return NOERROR; } ECode CStrictMode::GetThreadPolicy( /* [out] */ IStrictModeThreadPolicy** policy) { VALIDATE_NOT_NULL(policy) // TODO: this was a last minute Gingerbread API change (to // introduce VmPolicy cleanly) but this isn't particularly // optimal for users who might call this method often. This // should be in a thread-local and not allocate on each call. Int32 mask; GetThreadPolicyMask(&mask); AutoPtr<ThreadPolicy> tp = new ThreadPolicy(mask); *policy = (IStrictModeThreadPolicy*)tp.Get(); REFCOUNT_ADD(*policy); return NOERROR; } ECode CStrictMode::AllowThreadDiskWrites( /* [out] */ IStrictModeThreadPolicy** policy) { VALIDATE_NOT_NULL(policy); Int32 oldPolicyMask; GetThreadPolicyMask(&oldPolicyMask); Int32 newPolicyMask = oldPolicyMask & ~(IStrictMode::DETECT_DISK_WRITE | IStrictMode::DETECT_DISK_READ); if (newPolicyMask != oldPolicyMask) { SetThreadPolicyMask(newPolicyMask); } AutoPtr<ThreadPolicy> tp = new ThreadPolicy(oldPolicyMask); *policy = (IStrictModeThreadPolicy*)tp.Get(); REFCOUNT_ADD(*policy); return NOERROR; } ECode CStrictMode::AllowThreadDiskReads( /* [out] */ IStrictModeThreadPolicy** policy) { VALIDATE_NOT_NULL(policy) Int32 oldPolicyMask; GetThreadPolicyMask(&oldPolicyMask); Int32 newPolicyMask = oldPolicyMask & ~(IStrictMode::DETECT_DISK_READ); if (newPolicyMask != oldPolicyMask) { SetThreadPolicyMask(newPolicyMask); } AutoPtr<ThreadPolicy> tp = new ThreadPolicy(oldPolicyMask); *policy = (IStrictModeThreadPolicy*)tp.Get(); REFCOUNT_ADD(*policy); return NOERROR; } Boolean CStrictMode::AmTheSystemServerProcess() { // Fast path. Most apps don't have the system server's UID. if (Process::MyUid() != IProcess::SYSTEM_UID) { return FALSE; } // The settings app, though, has the system server's UID so // look up our stack to see if we came from the system server. //TODO: // Throwable stack = new Throwable(); // stack.fillInStackTrace(); // for (StackTraceElement ste : stack.getStackTrace()) { // String clsName = ste.getClassName(); // if (clsName != null && clsName.startsWith("com.android.server.")) { // return true; // } // } return FALSE; } ECode CStrictMode::ConditionallyEnableDebugLogging( /* [out] */ Boolean* isLogging) { VALIDATE_NOT_NULL(isLogging); Boolean doFlashes; SystemProperties::GetBoolean(VISUAL_PROPERTY, FALSE, &doFlashes); doFlashes = doFlashes && !AmTheSystemServerProcess(); Boolean suppress; SystemProperties::GetBoolean(DISABLE_PROPERTY, FALSE, &suppress); // For debug builds, log event loop stalls to dropbox for analysis. // Similar logic also appears in ActivityThread.java for system apps. if (!doFlashes && (IS_USER_BUILD || suppress)) { SetCloseGuardEnabled(FALSE); *isLogging = FALSE; return NOERROR; } // Eng builds have flashes on all the time. The suppression property // overrides this, so we force the behavior only after the short-circuit // check above. if (IS_ENG_BUILD) { doFlashes = TRUE; } // Thread policy controls BlockGuard. Int32 threadPolicyMask = IStrictMode::DETECT_DISK_WRITE | IStrictMode::DETECT_DISK_READ | IStrictMode::DETECT_NETWORK; if (!IS_USER_BUILD) { threadPolicyMask |= IStrictMode::PENALTY_DROPBOX; } if (doFlashes) { threadPolicyMask |= IStrictMode::PENALTY_FLASH; } SetThreadPolicyMask(threadPolicyMask); // VM Policy controls CloseGuard, detection of Activity leaks, // and instance counting. if (IS_USER_BUILD) { SetCloseGuardEnabled(FALSE); } else { AutoPtr<IStrictModeVmPolicyBuilder> policyBuilder; CStrictModeVmPolicyBuilder::New((IStrictModeVmPolicyBuilder**)&policyBuilder); policyBuilder->DetectAll(); policyBuilder->PenaltyDropBox(); if (IS_ENG_BUILD) { policyBuilder->PenaltyLog(); } AutoPtr<IStrictModeVmPolicy> policy; policyBuilder->Build((IStrictModeVmPolicy**)&policy); SetVmPolicy(policy.Get()); Boolean isEnable; SetCloseGuardEnabled((VmClosableObjectLeaksEnabled(&isEnable),isEnable)); } *isLogging = TRUE; return NOERROR; } ECode CStrictMode::EnableDeathOnNetwork() { Int32 oldPolicy; GetThreadPolicyMask(&oldPolicy); Int32 newPolicy = oldPolicy | IStrictMode::DETECT_NETWORK | IStrictMode::PENALTY_DEATH_ON_NETWORK; SetThreadPolicyMask(newPolicy); return NOERROR; } Int32 CStrictMode::ParsePolicyFromMessage( /* [in] */ const String& message) { if (message.IsNull() || !message.StartWith("policy=")) { return 0; } Int32 spaceIndex = message.IndexOf(' '); if (spaceIndex == -1) { return 0; } String policyString = message.Substring(7, spaceIndex); // try { return StringUtils::ParseInt32(policyString); // } catch (NumberFormatException e) { // return 0; // } } Int32 CStrictMode::ParseViolationFromMessage( /* [in] */ const String& message) { if (message.IsNull()) { return 0; } Int32 violationIndex = message.IndexOf("violation="); if (violationIndex == -1) { return 0; } Int32 numberStartIndex = violationIndex + String("violation=").GetLength(); Int32 numberEndIndex = message.IndexOf(' ', numberStartIndex); if (numberEndIndex == -1) { numberEndIndex = message.GetLength(); } String violationString = message.Substring(numberStartIndex, numberEndIndex); // try { return StringUtils::ParseInt32(violationString); // } catch (NumberFormatException e) { // return 0; // } } pthread_key_t CStrictMode::sViolationsBeingTimed = InitSViolationsBeingTimed(); static void HandlerDestructor(void* st) { IHandler* obj = static_cast<IHandler*>(st); if (obj) { obj->Release(); } } AutoPtr<IHandler> CStrictMode::GetThreadHandler() { if (!sHaveThreadHandlerKey) { ASSERT_TRUE(pthread_key_create(&sThreadHandlerKey, HandlerDestructor) == 0); sHaveThreadHandlerKey = TRUE; } AutoPtr<IHandler> instance = (IHandler*)pthread_getspecific(sThreadHandlerKey); if (instance == NULL) { CHandler::New((IHandler**)&instance); ASSERT_TRUE(pthread_setspecific(sThreadHandlerKey, instance.Get()) == 0); instance->AddRef(); } return instance; } Boolean CStrictMode::TooManyViolationsThisLoop() { AutoPtr<List<AutoPtr<IStrictModeViolationInfo> > > violations = (List<AutoPtr<IStrictModeViolationInfo> >*)pthread_getspecific(sViolationsBeingTimed); if (violations == NULL) { violations = new List<AutoPtr<IStrictModeViolationInfo> >(); violations->AddRef(); pthread_setspecific(sViolationsBeingTimed, violations.Get()); } return violations->GetSize() >= MAX_OFFENSES_PER_LOOP; } CAR_INTERFACE_IMPL_2(CStrictMode::AndroidBlockGuardPolicy, Object, IAndroidBlockGuardPolicy, IBlockGuardPolicy); CStrictMode::AndroidBlockGuardPolicy::AndroidBlockGuardPolicy( /* [in] */ Int32 policyMask) : mPolicyMask(policyMask) { } ECode CStrictMode::AndroidBlockGuardPolicy::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = String("AndroidBlockGuardPolicy; mPolicyMask=") + StringUtils::ToString(mPolicyMask); return NOERROR; } // Part of BlockGuard.Policy interface: ECode CStrictMode::AndroidBlockGuardPolicy::GetPolicyMask( /* [out] */ Int32* mask) { VALIDATE_NOT_NULL(mask); *mask = mPolicyMask; return NOERROR; } // Part of BlockGuard.Policy interface: ECode CStrictMode::AndroidBlockGuardPolicy::OnWriteToDisk() { if ((mPolicyMask & DETECT_DISK_WRITE) == 0) { return NOERROR; } if (TooManyViolationsThisLoop()) { return NOERROR; } //TODO: // BlockGuard.BlockGuardPolicyException e = new StrictModeDiskWriteViolation(mPolicyMask); // e.fillInStackTrace(); // startHandlingViolationException(e); return E_NOT_IMPLEMENTED; } ECode CStrictMode::AndroidBlockGuardPolicy::OnCustomSlowCall( /* [in] */ const String& name) { if ((mPolicyMask & DETECT_CUSTOM) == 0) { return NOERROR; } if (TooManyViolationsThisLoop()) { return NOERROR; } //TODO: // BlockGuard.BlockGuardPolicyException e = new StrictModeCustomViolation(mPolicyMask, name); // e.fillInStackTrace(); // StartHandlingViolationException(e); return E_NOT_IMPLEMENTED; } ECode CStrictMode::AndroidBlockGuardPolicy::OnReadFromDisk() { if ((mPolicyMask & DETECT_DISK_READ) == 0) { return NOERROR; } if (TooManyViolationsThisLoop()) { return NOERROR; } // BlockGuard.BlockGuardPolicyException e = new StrictModeDiskReadViolation(mPolicyMask); // e.fillInStackTrace(); // StartHandlingViolationException(e); return E_NOT_IMPLEMENTED; } ECode CStrictMode::AndroidBlockGuardPolicy::OnNetwork() { if ((mPolicyMask & DETECT_NETWORK) == 0) { return NOERROR; } if ((mPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) { //throw new NetworkOnMainThreadException(); return E_NETWORK_ERROR_EXCEPTION; } if (TooManyViolationsThisLoop()) { return NOERROR; } //TODO: // BlockGuard.BlockGuardPolicyException e = new StrictModeNetworkViolation(mPolicyMask); // e.fillInStackTrace(); // startHandlingViolationException(e); return E_NOT_IMPLEMENTED; } ECode CStrictMode::AndroidBlockGuardPolicy::SetPolicyMask( /* [in] */ Int32 policyMask) { mPolicyMask = policyMask; return NOERROR; } ECode CStrictMode::AndroidBlockGuardPolicy::HandleViolationWithTimingAttempt( /* [in] */ IStrictModeViolationInfo* info) { AutoPtr<ILooper> looper = Looper::GetMainLooper(); // Without a Looper, we're unable to time how long the // violation takes place. This case should be rare, as // most users will care about timing violations that // happen on their main UI thread. Note that this case is // also hit when a violation takes place in a Binder // thread, in "gather" mode. In this case, the duration // of the violation is computed by the ultimate caller and // its Looper, if any. // // Also, as a special short-cut case when the only penalty // bit is death, we die immediately, rather than timing // the violation's duration. This makes it convenient to // use in unit tests too, rather than waiting on a Looper. // // TODO: if in gather mode, ignore Looper.myLooper() and always // go into this immediate mode? CStrictModeViolationInfo* cinfo = (CStrictModeViolationInfo*)info; if (looper == NULL || (cinfo->mPolicy & THREAD_PENALTY_MASK) == IStrictMode::PENALTY_DEATH) { cinfo->mDurationMillis = -1; // unknown (redundant, already set) HandleViolation(info); return NOERROR; } AutoPtr<List<AutoPtr<IStrictModeViolationInfo> > > records = (List<AutoPtr<IStrictModeViolationInfo> >*)pthread_getspecific(sViolationsBeingTimed); if (records == NULL) { records = new List<AutoPtr<IStrictModeViolationInfo> >(); records->AddRef(); pthread_setspecific(sViolationsBeingTimed, records.Get()); } else if (records->GetSize() >= MAX_OFFENSES_PER_LOOP) { // Not worth measuring. Too many offenses in one loop. return NOERROR; } records->PushBack(info); if (records->GetSize() > 1) { // There's already been a violation this loop, so we've already // registered an idle handler to process the list of violations // at the end of this Looper's loop. return NOERROR; } if((cinfo->mPolicy & IStrictMode::PENALTY_FLASH) != 0) { if(sWindowManager == NULL) { AutoPtr<IInterface> service = ServiceManager::GetService(String("window")); sWindowManager = IIWindowManager::Probe(service);; } sWindowManager->ShowStrictModeViolation(TRUE); } else { sWindowManager = NULL; } // // We post a runnable to a Handler (== delay 0 ms) for // // measuring the end time of a violation instead of using // // an IdleHandler (as was previously used) because an // // IdleHandler may not run for quite a long period of time // // if an ongoing animation is happening and continually // // posting ASAP (0 ms) animation steps. Animations are // // throttled back to 60fps via SurfaceFlinger/View // // invalidates, _not_ by posting frame updates every 16 // // milliseconds. //TODO: threadHandler.get().postAtFrontOfQueue(new Runnable() { // public void run() { // long loopFinishTime = SystemClock.uptimeMillis(); // // Note: we do this early, before handling the // // violation below, as handling the violation // // may include PENALTY_DEATH and we don't want // // to keep the red border on. // if (sWindowManager != null) { // try { // sWindowManager.showStrictModeViolation(false); // } catch (RemoteException unused) { // } // } // for (int n = 0; n < records.size(); ++n) { // ViolationInfo v = records.get(n); // v.violationNumThisLoop = n + 1; // v.durationMillis = // (int) (loopFinishTime - v.violationUptimeMillis); // handleViolation(v); // } // records.clear(); // } // }); return E_NOT_IMPLEMENTED; } ECode CStrictMode::AndroidBlockGuardPolicy::HandleViolation( /* [in] */ IStrictModeViolationInfo* info) { if (info == NULL /*|| info.crashInfo == null || info.crashInfo.stackTrace == null*/) { //Log.wtf(TAG, "unexpected null stacktrace"); return NOERROR; } if (LOG_V) Logger::D(TAG, String("handleViolation; policy=") + StringUtils::ToString(((CStrictModeViolationInfo*)info)->mPolicy)); CStrictModeViolationInfo* cinfo = (CStrictModeViolationInfo*)info; if ((cinfo->mPolicy & PENALTY_GATHER) != 0) { AutoPtr< List<AutoPtr<IStrictModeViolationInfo> > > violations = (List<AutoPtr<IStrictModeViolationInfo> >*)pthread_getspecific(sGatheredViolations); if (violations == NULL) { violations = new List<AutoPtr<IStrictModeViolationInfo> >(); violations->AddRef(); pthread_setspecific(sGatheredViolations, violations.Get()); } else if (violations->GetSize() >= 5) { // Too many. In a loop or something? Don't gather them all. return NOERROR; } // for (ViolationInfo previous : violations) { // if (info.crashInfo.stackTrace.equals(previous.crashInfo.stackTrace)) { // // Duplicate. Don't log. // return; // } // } violations->PushBack(info); return NOERROR; } // Not perfect, but fast and good enough for dup suppression. Int32 crashFingerprint = Object::GetHashCode(info); Int64 lastViolationTime = 0; if (mLastViolationTime.Find(crashFingerprint) != mLastViolationTime.End()) { lastViolationTime = mLastViolationTime[crashFingerprint]; } Int64 now = SystemClock::GetUptimeMillis(); mLastViolationTime[crashFingerprint] = now; Int64 timeSinceLastViolationMillis = lastViolationTime == 0 ? 0x7FFFFFFFFFFFFFFFL /*Long.MAX_VALUE*/ : (now - lastViolationTime); if ((cinfo->mPolicy & PENALTY_LOG) != 0 && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) { if (cinfo->mDurationMillis != -1) { // Log.d(TAG, "StrictMode policy violation; ~duration=" + // info.durationMillis + " ms: " + info.crashInfo.stackTrace); } else { // Log.d(TAG, "StrictMode policy violation: " + info.crashInfo.stackTrace); } } // The violationMaskSubset, passed to ActivityManager, is a // subset of the original StrictMode policy bitmask, with // only the bit violated and penalty bits to be executed // by the ActivityManagerService remaining set. Int32 violationMaskSubset = 0; if ((cinfo->mPolicy & PENALTY_DIALOG) != 0 && timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) { violationMaskSubset |= PENALTY_DIALOG; } if ((cinfo->mPolicy & PENALTY_DROPBOX) != 0 && lastViolationTime == 0) { violationMaskSubset |= PENALTY_DROPBOX; } if (violationMaskSubset != 0) { Int32 violationBit = 0;//TODO ParseViolationFromMessage(info.crashInfo.exceptionMessage); violationMaskSubset |= violationBit; Int32 savedPolicyMask; AutoPtr<IStrictMode> helper; CStrictMode::AcquireSingleton((IStrictMode**)&helper); helper->GetThreadPolicyMask(&savedPolicyMask); const Boolean justDropBox = (cinfo->mPolicy & THREAD_PENALTY_MASK) == PENALTY_DROPBOX; if (justDropBox) { // If all we're going to ask the activity manager // to do is dropbox it (the common case during // platform development), we can avoid doing this // call synchronously which Binder data suggests // isn't always super fast, despite the implementation // in the ActivityManager trying to be mostly async. DropboxViolationAsync(violationMaskSubset, info); return NOERROR; } // Normal synchronous call to the ActivityManager. //try { // First, remove any policy before we call into the Activity Manager, // otherwise we'll infinite recurse as we try to log policy violations // to disk, thus violating policy, thus requiring logging, etc... // We restore the current policy below, in the finally block. SetThreadPolicyMask(0); //TODO: ActivityManagerNative.getDefault().handleApplicationStrictModeViolation( // RuntimeInit.getApplicationObject(), // violationMaskSubset, // info); //} catch (RemoteException e) { // Log.e(TAG, "RemoteException trying to handle StrictMode violation", e); //} finally { // Restore the policy. SetThreadPolicyMask(savedPolicyMask); //} } if ((cinfo->mPolicy & PENALTY_DEATH) != 0) { ExecuteDeathPenalty(info); } return NOERROR; } void CStrictMode::ExecuteDeathPenalty( /* [in] */ IStrictModeViolationInfo* info) { // int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage); // throw new StrictModeViolation(info.policy, violationBit, null); } CStrictMode::MyThread::MyThread( /* [in] */ const String& str) { Thread::constructor(str); } ECode CStrictMode::MyThread::Run() { Process::SetThreadPriority(IProcess::THREAD_PRIORITY_BACKGROUND); //try { AutoPtr<IIActivityManager> am = ActivityManagerNative::GetDefault(); if (am == NULL) { Logger::D(TAG, String("No activity manager; failed to Dropbox violation.")); } else { //TODO: am->HandleApplicationStrictModeViolation( // RuntimeInit.getApplicationObject(), // violationMaskSubset, // info); } //} catch (RemoteException e) { // Log.e(TAG, "RemoteException handling StrictMode violation", e); //} Int32 outstanding; sDropboxCallsInFlight->DecrementAndGet(&outstanding); if (LOG_V) Logger::D(TAG, String("Dropbox complete; in-flight=") + StringUtils::ToString(outstanding)); return NOERROR; } void CStrictMode::DropboxViolationAsync( /* [in] */ Int32 violationMaskSubset, /* [in] */ IStrictModeViolationInfo* info) { Int32 outstanding; sDropboxCallsInFlight->IncrementAndGet(&outstanding); if (outstanding > 20) { // What's going on? Let's not make make the situation // worse and just not log. Int32 outV; sDropboxCallsInFlight->DecrementAndGet(&outV); return; } if (LOG_V) Logger::D(TAG, String("Dropboxing async; in-flight=") + StringUtils::ToString(outstanding)); AutoPtr<IThread> myThread = new MyThread(String("callActivityManagerForStrictModeDropbox")); myThread->Start(); } CAR_INTERFACE_IMPL(CStrictMode::AndroidCloseGuardReporter, Object, ICloseGuardReporter); ECode CStrictMode::AndroidCloseGuardReporter::Report( /* [in] */ const String& message, /* [in] */ IThrowable* allocationSite) { AutoPtr<IStrictMode> sMode; CStrictMode::AcquireSingleton((IStrictMode**)&sMode); return sMode->OnVmPolicyViolation(message); } ECode CStrictMode::HasGatheredViolations( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); List<AutoPtr<IStrictModeViolationInfo> >* violations = (List<AutoPtr<IStrictModeViolationInfo> >*)pthread_getspecific(sGatheredViolations); *result = violations != NULL; return NOERROR; } ECode CStrictMode::ClearGatheredViolations() { List<AutoPtr<IStrictModeViolationInfo> >* violations = (List<AutoPtr<IStrictModeViolationInfo> >*)pthread_getspecific(sGatheredViolations); if (violations) { violations->Clear(); } return NOERROR; } ECode CStrictMode::ConditionallyCheckInstanceCounts() { AutoPtr<IStrictModeVmPolicy> obj; GetVmPolicy((IStrictModeVmPolicy**)&obj); CStrictMode::VmPolicy* policy = (CStrictMode::VmPolicy*)obj.Get(); if (policy->mClassInstanceLimit.GetSize() == 0) { return NOERROR; } // Runtime.getRuntime().gc(); // // Note: classInstanceLimit is immutable, so this is lock-free // for (Map.Entry<Class, Integer> entry : policy.classInstanceLimit.entrySet()) { // Class klass = entry.getKey(); // int limit = entry.getValue(); // long instances = VMDebug.countInstancesOfClass(klass, false); // if (instances <= limit) { // continue; // } // Throwable tr = new InstanceCountViolation(klass, instances, limit); // onVmPolicyViolation(tr.getMessage(), tr); // } return E_NOT_IMPLEMENTED; } Int64 CStrictMode::sLastInstanceCountCheckMillis = 0; Boolean CStrictMode::sIsIdlerRegistered = FALSE; AutoPtr<CStrictMode::MessageQueueIdleHandler> CStrictMode::sProcessIdleHandler; CAR_INTERFACE_IMPL(CStrictMode::MessageQueueIdleHandler, Object, IIdleHandler); CStrictMode::MessageQueueIdleHandler::MessageQueueIdleHandler( /* [in] */ CStrictMode* host) : mHost(host) { } ECode CStrictMode::MessageQueueIdleHandler::QueueIdle( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); Int64 now = SystemClock::GetUptimeMillis(); if (now - sLastInstanceCountCheckMillis > 30 * 1000) { sLastInstanceCountCheckMillis = now; mHost->ConditionallyCheckInstanceCounts(); } *result = TRUE; return NOERROR; } CAR_INTERFACE_IMPL(CStrictMode, Singleton, IStrictMode) CAR_SINGLETON_IMPL(CStrictMode) ECode CStrictMode::SetVmPolicy( /* [in] */ IStrictModeVmPolicy* policy) { AutoLock lock(classLock); { sVmPolicy = (CStrictMode::VmPolicy*)policy; sVmPolicyMask = sVmPolicy->mMask; Boolean isEnabled; VmClosableObjectLeaksEnabled(&isEnabled); SetCloseGuardEnabled(isEnabled); AutoPtr<ILooper> looper = Looper::GetMainLooper(); if (looper != NULL) { AutoPtr<IMessageQueue> mq; looper->GetQueue((IMessageQueue**)&mq); if (sVmPolicy->mClassInstanceLimit.GetSize() == 0 || (sVmPolicyMask & CStrictMode::VM_PENALTY_MASK) == 0) { mq->RemoveIdleHandler((IIdleHandler*)sProcessIdleHandler); sIsIdlerRegistered = FALSE; } else if (!sIsIdlerRegistered) { mq->AddIdleHandler((IIdleHandler*)sProcessIdleHandler); sIsIdlerRegistered = TRUE; } } } return NOERROR; } ECode CStrictMode::GetVmPolicy( /* [out] */ IStrictModeVmPolicy** policy) { VALIDATE_NOT_NULL(policy); AutoLock lock(classLock); { *policy = sVmPolicy.Get(); REFCOUNT_ADD(*policy) } return NOERROR; } ECode CStrictMode::EnableDefaults() { AutoPtr<IStrictModeThreadPolicyBuilder> stb; CStrictModeThreadPolicyBuilder::New((IStrictModeThreadPolicyBuilder**)&stb); stb->DetectAll(); stb->PenaltyLog(); AutoPtr<IStrictModeThreadPolicy> stp; stb->Build((IStrictModeThreadPolicy**)&stp); SetThreadPolicy(stp.Get()); AutoPtr<IStrictModeVmPolicyBuilder> svb; CStrictModeVmPolicyBuilder::New((IStrictModeVmPolicyBuilder**)&svb); svb->DetectAll(); svb->PenaltyLog(); AutoPtr<IStrictModeVmPolicy> svp; svb->Build((IStrictModeVmPolicy**)&svp); SetVmPolicy(svp.Get()); return NOERROR; } ECode CStrictMode::VmSqliteObjectLeaksEnabled( /* [out] */ Boolean* isEnabled) { VALIDATE_NOT_NULL(isEnabled); *isEnabled = (sVmPolicyMask & IStrictMode::DETECT_VM_CURSOR_LEAKS) != 0; return NOERROR; } ECode CStrictMode::VmClosableObjectLeaksEnabled( /* [out] */ Boolean* isEnabled) { VALIDATE_NOT_NULL(isEnabled); *isEnabled = (sVmPolicyMask & IStrictMode::DETECT_VM_CLOSABLE_LEAKS) != 0; return NOERROR; } ECode CStrictMode::VmRegistrationLeaksEnabled( /* [out] */ Boolean* isEnabled) { VALIDATE_NOT_NULL(isEnabled); *isEnabled = (sVmPolicyMask & IStrictMode::DETECT_VM_REGISTRATION_LEAKS) != 0; return NOERROR; } ECode CStrictMode::VmFileUriExposureEnabled( /* [out] */ Boolean* isEnabled) { VALIDATE_NOT_NULL(isEnabled); *isEnabled = (sVmPolicyMask & DETECT_VM_FILE_URI_EXPOSURE) != 0; return NOERROR; } ECode CStrictMode::OnSqliteObjectLeaked( /* [in] */ const String& message //, /* [in] */ /*Throwable originStack*/) { return OnVmPolicyViolation(message); } ECode CStrictMode::OnWebViewMethodCalledOnWrongThread( /* [in] */ /*Throwable originStack*/) { return OnVmPolicyViolation(String(NULL)); } ECode CStrictMode::OnIntentReceiverLeaked( /* [in] */ /*Throwable originStack*/) { return OnVmPolicyViolation(String(NULL)); } ECode CStrictMode::OnServiceConnectionLeaked( /* [in] */ /*Throwable originStack*/) { return OnVmPolicyViolation(String(NULL)); } ECode CStrictMode::OnFileUriExposed( /* [in] */ const String& location) { String message("file:// Uri exposed through "); message += location; return OnVmPolicyViolation(message/*, new Throwable(message)*/); } /*const*/ HashMap<Int32, Int64> CStrictMode::sLastVmViolationTime; ECode CStrictMode::OnVmPolicyViolation( /* [in] */ const String& message //, /* [in] */ /*Throwable originStack*/) { const Boolean penaltyDropbox = (sVmPolicyMask & IStrictMode::PENALTY_DROPBOX) != 0; const Boolean penaltyDeath = (sVmPolicyMask & IStrictMode::PENALTY_DEATH) != 0; const Boolean penaltyLog = (sVmPolicyMask & IStrictMode::PENALTY_LOG) != 0; AutoPtr<IStrictModeViolationInfo> info; CStrictModeViolationInfo::New(/*originStack, */sVmPolicyMask, (IStrictModeViolationInfo**)&info); // Erase stuff not relevant for process-wide violations CStrictModeViolationInfo* cinfo = (CStrictModeViolationInfo*)info.Get(); cinfo->mNumAnimationsRunning = 0; cinfo->mTags = NULL; cinfo->mBroadcastIntentAction = NULL; Int32 fingerprint = Object::GetHashCode(info); const Int64 now = SystemClock::GetUptimeMillis(); Int64 lastViolationTime = 0; Int64 timeSinceLastViolationMillis = 0x7FFFFFFFFFFFFFFFL; // Long.MAX_VALUE; { AutoLock lock(sLastVmViolationTimeLock); if (sLastVmViolationTime.Find(fingerprint) != sLastVmViolationTime.End()) { lastViolationTime = sLastVmViolationTime[fingerprint]; timeSinceLastViolationMillis = now - lastViolationTime; } if (timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) { sLastVmViolationTime[fingerprint] = now; } } if (penaltyLog && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) { //Log.e(TAG, message, originStack); } Int32 violationMaskSubset = IStrictMode::PENALTY_DROPBOX | (ALL_VM_DETECT_BITS & sVmPolicyMask); if (penaltyDropbox && !penaltyDeath) { // Common case for userdebug/eng builds. If no death and // just dropboxing, we can do the ActivityManager call // asynchronously. DropboxViolationAsync(violationMaskSubset, info); return NOERROR; } if (penaltyDropbox && lastViolationTime == 0) { // The violationMask, passed to ActivityManager, is a // subset of the original StrictMode policy bitmask, with // only the bit violated and penalty bits to be executed // by the ActivityManagerService remaining set. Int32 savedPolicyMask; GetThreadPolicyMask(&savedPolicyMask); //try { // First, remove any policy before we call into the Activity Manager, // otherwise we'll infinite recurse as we try to log policy violations // to disk, thus violating policy, thus requiring logging, etc... // We restore the current policy below, in the finally block. SetThreadPolicyMask(0); //TODO: ActivityManagerNative::GetDefault()->HandleApplicationStrictModeViolation( // RuntimeInit.getApplicationObject(), // violationMaskSubset, // info); //} catch (RemoteException e) { // Log.e(TAG, "RemoteException trying to handle StrictMode violation", e); //} finally { // Restore the policy. SetThreadPolicyMask(savedPolicyMask); //} } if (penaltyDeath) { //System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down."); Process::KillProcess(Process::MyPid()); //System::Exit(10); } return NOERROR; } ECode CStrictMode::WriteGatheredViolationsToParcel( /* [in] */ IParcel* p) { List<AutoPtr<IStrictModeViolationInfo> >* violations = (List<AutoPtr<IStrictModeViolationInfo> >*)pthread_getspecific(sGatheredViolations); if (violations == NULL) { p->WriteInt32(0); } else { p->WriteInt32(violations->GetSize()); List<AutoPtr<IStrictModeViolationInfo> >::Iterator it = violations->Begin(); for (Int32 i = 0; it != violations->End(); ++it) { Int32 start, end; p->GetDataPosition(&start); (*it)->WriteToParcel(p, 0 /* unused flags? */); p->GetDataPosition(&end); Int32 size = end - start; if (size > 10 * 1024) { Logger::D(TAG, "Wrote violation #%d of %d: %d bytes", i, violations->GetSize(), size); } ++i; } if (LOG_V) Logger::D(TAG, "wrote violations to response parcel; num=%d", violations->GetSize()); violations->Clear(); // somewhat redundant, as we're about to null the threadlocal } return NOERROR; } ECode CStrictMode::ReadAndHandleBinderCallViolations( /* [in] */ IParcel* p) { // Our own stack trace to append // TODO // StringWriter sw = new StringWriter(); // PrintWriter pw = new FastPrintWriter(sw, false, 256); // new LogStackTrace().printStackTrace(pw); // pw.flush(); // String ourStack = sw.toString(); Int32 policyMask; GetThreadPolicyMask(&policyMask); Boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0; Int32 numViolations; p->ReadInt32(&numViolations); for (Int32 i = 0; i < numViolations; ++i) { if (LOG_V) Logger::D(TAG, String("strict mode violation stacks read from binder call. i=") + StringUtils::ToString(i)); AutoPtr<IStrictModeViolationInfo> info; CStrictModeViolationInfo::New(p, !currentlyGathering, (IStrictModeViolationInfo**)&info); //TODO: // if (info.crashInfo.stackTrace != null && info.crashInfo.stackTrace.length() > 10000) { // String front = info.crashInfo.stackTrace.substring(256); // // 10000 characters is way too large for this to be any sane kind of // // strict mode collection of stacks. We've had a problem where we leave // // strict mode violations associated with the thread, and it keeps tacking // // more and more stacks on to the violations. Looks like we're in this casse, // // so we'll report it and bail on all of the current strict mode violations // // we currently are maintaining for this thread. // // First, drain the remaining violations from the parcel. // while (i < numViolations) { // info = new ViolationInfo(p, !currentlyGathering); // i++; // } // // Next clear out all gathered violations. // clearGatheredViolations(); // // Now report the problem. // Slog.wtfStack(TAG, "Stack is too large: numViolations=" + numViolations // + " policy=#" + Integer.toHexString(policyMask) // + " front=" + front); // return; // } // info.crashInfo.stackTrace += "# via Binder call with stack:\n" + ourStack; AutoPtr<IBlockGuard> helper; CBlockGuard::AcquireSingleton((IBlockGuard**)&helper); AutoPtr<IBlockGuardPolicy> policy; helper->GetThreadPolicy((IBlockGuardPolicy**)&policy); if(policy != NULL && policy->Probe(EIID_IAndroidBlockGuardPolicy) != NULL) { AutoPtr<IAndroidBlockGuardPolicy> androidPolicy = IAndroidBlockGuardPolicy::Probe(policy.Get()); androidPolicy->HandleViolationWithTimingAttempt(info); } } return NOERROR; } void CStrictMode::OnBinderStrictModePolicyChange( /* [in] */ Int32 newPolicy) { SetBlockGuardPolicy(newPolicy); } CAR_INTERFACE_IMPL(CStrictMode::NoOpSpan, Object, IStrictModeSpan); ECode CStrictMode::NoOpSpan::Finish() { // Do nothing. return NOERROR; } const AutoPtr<CStrictMode::NoOpSpan> CStrictMode::NO_OP_SPAN = new CStrictMode::NoOpSpan(); static void ThreadSpanStateDestructor(void* st) { CStrictMode::ThreadSpanState* obj = static_cast<CStrictMode::ThreadSpanState*>(st); if (obj) { obj->Release(); } } AutoPtr<CStrictMode::ThreadSpanState> CStrictMode::GetThisThreadSpanState() { if (!sHaveThisThreadSpanStateKey) { ASSERT_TRUE(pthread_key_create(&sThisThreadSpanStateKey, ThreadSpanStateDestructor) == 0); sHaveThisThreadSpanStateKey = TRUE; } AutoPtr<CStrictMode::ThreadSpanState> instance = (CStrictMode::ThreadSpanState*)pthread_getspecific(sThisThreadSpanStateKey); if (instance == NULL) { instance = new CStrictMode::ThreadSpanState(); instance->AddRef(); ASSERT_TRUE(pthread_setspecific(sThisThreadSpanStateKey, instance.Get()) == 0); } return instance; } AutoPtr<IIWindowManager> CStrictMode::sWindowManager; ECode CStrictMode::EnterCriticalSpan( /* [in] */ const String& name, /* [out] */ IStrictModeSpan** span) { VALIDATE_NOT_NULL(span); if (IS_USER_BUILD) { *span = (IStrictModeSpan*)NO_OP_SPAN.Get(); REFCOUNT_ADD(*span); return NOERROR; } if (name.IsNull() || name.IsEmpty()) { //throw new IllegalArgumentException("name must be non-null and non-empty"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<ThreadSpanState> state = GetThisThreadSpanState(); AutoPtr<IStrictModeSpan> _span; CStrictModeSpan* cspan; { AutoLock lock(stateLock); if (state->mFreeListHead != NULL) { _span = state->mFreeListHead; cspan = (CStrictModeSpan*)_span.Get(); state->mFreeListHead = cspan->mNext; state->mFreeListSize--; } else { // Shouldn't have to do this often. CStrictModeSpan::New((Handle32)state.Get(), (IStrictModeSpan**)&_span); cspan = (CStrictModeSpan*)_span.Get(); } cspan->mName = name; cspan->mCreateMillis = SystemClock::GetUptimeMillis(); cspan->mNext = state->mActiveHead; cspan->mPrev = NULL; state->mActiveHead = cspan; state->mActiveSize++; if (cspan->mNext != NULL) { cspan->mNext->mPrev = cspan; } if (LOG_V) Logger::D(TAG, String("Span enter=") + name + String("; size=") + StringUtils::ToString(state->mActiveSize)); } *span = _span; REFCOUNT_ADD(*span); return NOERROR; } ECode CStrictMode::NoteSlowCall( /* [in] */ const String& name) { AutoPtr<IBlockGuard> helper; CBlockGuard::AcquireSingleton((IBlockGuard**)&helper); AutoPtr<IBlockGuardPolicy> policy; helper->GetThreadPolicy((IBlockGuardPolicy**)&policy); if(policy == NULL || policy->Probe(EIID_IAndroidBlockGuardPolicy) == NULL) { // StrictMode not enabled. return NOERROR; } AutoPtr<IAndroidBlockGuardPolicy> androidPolicy = IAndroidBlockGuardPolicy::Probe(policy.Get()); androidPolicy->OnCustomSlowCall(name); return NOERROR; } ECode CStrictMode::NoteDiskRead() { AutoPtr<IBlockGuard> helper; CBlockGuard::AcquireSingleton((IBlockGuard**)&helper); AutoPtr<IBlockGuardPolicy> policy; helper->GetThreadPolicy((IBlockGuardPolicy**)&policy); AutoPtr<IAndroidBlockGuardPolicy> androidPolicy = IAndroidBlockGuardPolicy::Probe(policy.Get()); if(androidPolicy == NULL) { // StrictMode not enabled. return NOERROR; } policy->OnReadFromDisk(); return NOERROR; } ECode CStrictMode::NoteDiskWrite() { AutoPtr<IBlockGuard> helper; CBlockGuard::AcquireSingleton((IBlockGuard**)&helper); AutoPtr<IBlockGuardPolicy> policy; helper->GetThreadPolicy((IBlockGuardPolicy**)&policy); AutoPtr<IAndroidBlockGuardPolicy> androidPolicy = IAndroidBlockGuardPolicy::Probe(policy.Get()); if(androidPolicy == NULL) { // StrictMode not enabled. return NOERROR; } policy->OnWriteToDisk(); return NOERROR; } /*const */HashMap<ClassID*, AutoPtr<IInteger32> > CStrictMode::sExpectedActivityInstanceCount; ECode CStrictMode::TrackActivity( /* [in] */ IInterface* instance, /* [out] */ IInterface** act) { VALIDATE_NOT_NULL(act); AutoPtr<InstanceTracker> ins = new InstanceTracker(instance); *act = TO_IINTERFACE(ins); REFCOUNT_ADD(*act); return NOERROR; } ECode CStrictMode::IncrementExpectedActivityCount( /* [in] */ ClassID* klass) { if (klass == NULL) { return NOERROR; } AutoLock lock(classLock); { if ((sVmPolicy->mMask & IStrictMode::DETECT_VM_ACTIVITY_LEAKS) == 0) { return NOERROR; } HashMap<ClassID*, AutoPtr<IInteger32> >::Iterator it = sExpectedActivityInstanceCount.Find(klass); Int32 value; Int32 newExpected = (it != sExpectedActivityInstanceCount.End()) ? (it->mSecond->GetValue(&value), value + 1) : 1; AutoPtr<IInteger32> r; CInteger32::New(newExpected, (IInteger32**)&r); sExpectedActivityInstanceCount[klass] = r; } return NOERROR; } ECode CStrictMode::DecrementExpectedActivityCount( /* [in] */ ClassID* klass) { if (klass == NULL) { return NOERROR; } Int32 limit; AutoLock lock(classLock); { if ((sVmPolicy->mMask & IStrictMode::DETECT_VM_ACTIVITY_LEAKS) == 0) { return NOERROR; } HashMap<ClassID*, AutoPtr<IInteger32> >::Iterator it = sExpectedActivityInstanceCount.Find(klass); Int32 expected; Int32 newExpected = (it != sExpectedActivityInstanceCount.End() && (it->mSecond->GetValue(&expected), expected != 0)) ? (expected - 1) : 0; if (newExpected == 0 && it != sExpectedActivityInstanceCount.End()) { sExpectedActivityInstanceCount.Erase(it); } else { AutoPtr<IInteger32> r; CInteger32::New(newExpected, (IInteger32**)&r); sExpectedActivityInstanceCount[klass] = r; } // Note: adding 1 here to give some breathing room during // orientation changes. (shouldn't be necessary, though?) limit = newExpected + 1; } // Quick check. Int32 actual = CStrictMode::InstanceTracker::GetInstanceCount(klass); if (actual <= limit) { return NOERROR; } // Do a GC and explicit count to double-check. // This is the work that we are trying to avoid by tracking the object instances // explicity. Running an explicit GC can be expensive (80ms) and so can walking // the heap to count instance (30ms). This extra work can make the system feel // noticeably less responsive during orientation changes when activities are // being restarted. Granted, it is only a problem when StrictMode is enabled // but it is annoying. // TODO: // Runtime.getRuntime().gc(); // long instances = VMDebug.countInstancesOfClass(klass, false); // if (instances > limit) { // Throwable tr = new InstanceCountViolation(klass, instances, limit); // onVmPolicyViolation(tr.getMessage(), tr); // } return E_NOT_IMPLEMENTED; } CStrictMode::InstanceCountViolation::InstanceCountViolation( /* [in] */ Handle32 klass, /* [in] */ Int64 instances, /* [in] */ Int32 limit) : mClass(klass) , mInstances(instances) , mLimit(limit) { //TODO:super(klass.toString() + "; instances=" + instances + "; limit=" + limit); //setStackTrace(FAKE_STACK); } HashMap<ClassID*, AutoPtr<IInteger32> > CStrictMode::InstanceTracker::sInstanceCounts; CStrictMode::InstanceTracker::InstanceTracker( /* [in] */ IInterface* instance) { AutoPtr<IObject> obj = IObject::Probe(instance); obj->GetClassID(mKlass); { AutoLock lock(sInstanceCountsLock); HashMap<ClassID*, AutoPtr<IInteger32> >::Iterator it = sInstanceCounts.Find(mKlass); Int32 value; const Int32 newValue = (it != sInstanceCounts.End()) ? (it->mSecond->GetValue(&value), value + 1) : 1; AutoPtr<IInteger32> r; CInteger32::New(newValue, (IInteger32**)&r); sInstanceCounts[mKlass] = r; } } CStrictMode::InstanceTracker::~InstanceTracker() { // try { { AutoLock lock(sInstanceCountsLock); HashMap<ClassID*, AutoPtr<IInteger32> >::Iterator it = sInstanceCounts.Find(mKlass); if (it != sInstanceCounts.End()) { Int32 value; it->mSecond->GetValue(&value); const Int32 newValue = value - 1; if (newValue > 0) { AutoPtr<IInteger32> r; CInteger32::New(newValue, (IInteger32**)&r); sInstanceCounts[mKlass] = r; } else { sInstanceCounts.Erase(it); } } } // } finally { // super.finalize(); // } } Object CStrictMode::InstanceTracker::sInstanceCountsLock; Int32 CStrictMode::InstanceTracker::GetInstanceCount( /* [in] */ ClassID* klass) { { AutoLock lock(sInstanceCountsLock); HashMap<ClassID*, AutoPtr<IInteger32> >::Iterator it = sInstanceCounts.Find(klass); Int32 value; return it != sInstanceCounts.End() ? (it->mSecond->GetValue(&value),value) : 0; } } } // namespace Os } // namespace Droid } // namespace Elastos
35.050697
157
0.670005
[ "object" ]
3b02bcd34d9dbe81aea0745309607597fabd3985
14,102
cpp
C++
hphp/util/test/coro.cpp
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
1
2022-03-11T02:25:37.000Z
2022-03-11T02:25:37.000Z
hphp/util/test/coro.cpp
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
3
2022-02-17T04:00:03.000Z
2022-03-24T03:45:33.000Z
hphp/util/test/coro.cpp
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
1
2022-02-19T09:29:50.000Z
2022-02-19T09:29:50.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/util/coro.h" #include <folly/Format.h> #include <folly/executors/GlobalExecutor.h> #include <gtest/gtest.h> namespace HPHP { using namespace std::chrono_literals; namespace { struct Error {}; bool always_true() { return std::chrono::steady_clock::now().time_since_epoch().count() > 0; } coro::Task<int> make_task(int x) { HPHP_CORO_RETURN(x); } coro::Task<int> make_task_throws(int x) { if (always_true()) throw Error{}; HPHP_CORO_RETURN(x); } coro::Task<std::string> make_task(std::string x) { HPHP_CORO_RETURN(x); } coro::Task<void> make_task() { HPHP_CORO_RETURN_VOID; } coro::Task<void> make_task_throws() { if (always_true()) throw Error{}; HPHP_CORO_RETURN_VOID; } struct C { C() = default; C(const C&) = delete; C(C&&) = default; C& operator=(const C&) = delete; C& operator=(C&&) = default; int m_int{0}; }; coro::Task<C> make_task_move(int x) { C c; c.m_int = x; HPHP_CORO_MOVE_RETURN(c); } coro::Task<void> test_awaits() { EXPECT_EQ(HPHP_CORO_AWAIT(make_task(1)), 1); coro::Task<int> t1 = make_task(7); EXPECT_EQ(HPHP_CORO_AWAIT(std::move(t1)), 7); HPHP_CORO_AWAIT(make_task()); coro::Task<void> t2 = make_task(); HPHP_CORO_AWAIT(std::move(t2)); EXPECT_EQ(HPHP_CORO_AWAIT(make_task_move(5)).m_int, 5); coro::Task<C> t3 = make_task_move(9); EXPECT_EQ(HPHP_CORO_AWAIT(std::move(t3)).m_int, 9); try { HPHP_CORO_AWAIT(make_task_throws(123)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { coro::Task<int> x = make_task_throws(123); HPHP_CORO_AWAIT(std::move(x)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { HPHP_CORO_AWAIT(make_task_throws()); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { coro::Task<void> x = make_task_throws(); HPHP_CORO_AWAIT(std::move(x)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } HPHP_CORO_RETURN_VOID; } } TEST(Coro, Await) { coro::wait(test_awaits()); } TEST(Coro, Wait) { EXPECT_EQ(coro::wait(make_task(1)), 1); coro::Task<int> t1 = make_task(7); EXPECT_EQ(coro::wait(std::move(t1)), 7); coro::wait(make_task()); coro::Task<void> t2 = make_task(); static_assert( std::is_same<decltype(coro::wait(std::move(t2))), void>::value ); coro::wait(std::move(t2)); EXPECT_EQ(coro::wait(make_task_move(5)).m_int, 5); coro::Task<C> t3 = make_task_move(9); EXPECT_EQ(coro::wait(std::move(t3)).m_int, 9); try { coro::wait(make_task_throws(123)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { coro::Task<int> x = make_task_throws(123); coro::wait(std::move(x)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { coro::wait(make_task_throws()); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { coro::Task<void> x = make_task_throws(); coro::wait(std::move(x)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } } TEST(Coro, Collect) { coro::Task<std::tuple<int>> t1 = coro::collect(make_task(1)); std::tuple<int> t2 = coro::wait(std::move(t1)); EXPECT_EQ(std::get<0>(t2), 1); coro::Task<std::tuple<int, std::string, C, folly::Unit>> t3 = coro::collect( make_task(8), make_task("abc"), make_task_move(11), make_task() ); std::tuple<int, std::string, C, folly::Unit> t4 = coro::wait(std::move(t3)); EXPECT_EQ(std::get<0>(t4), 8); EXPECT_EQ(std::get<1>(t4), "abc"); EXPECT_EQ(std::get<2>(t4).m_int, 11); coro::Task<std::tuple<folly::Unit, folly::Unit>> t5 = coro::collect(make_task(), make_task()); std::tuple<folly::Unit, folly::Unit> t6 = coro::wait(std::move(t5)); (void)t6; try { coro::Task<std::tuple<int, int, C>> t = coro::collect( make_task(8), make_task_throws(9), make_task_move(11) ); coro::wait(std::move(t)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } } TEST(Coro, CollectRange) { for (size_t size = 0; size < 10; ++size) { std::vector<coro::Task<int>> tasks1; for (size_t i = 0; i < size; ++i) { tasks1.emplace_back(make_task(i)); } coro::Task<std::vector<int>> c1 = coro::collectRange(std::move(tasks1)); std::vector<int> ints = coro::wait(std::move(c1)); EXPECT_EQ(ints.size(), size); for (size_t i = 0; i < ints.size(); ++i) { EXPECT_EQ(ints[i], i); } std::vector<coro::Task<C>> tasks2; for (size_t i = 0; i < size; ++i) { tasks2.emplace_back(make_task_move(i)); } coro::Task<std::vector<C>> c2 = coro::collectRange(std::move(tasks2)); std::vector<C> cs = coro::wait(std::move(c2)); EXPECT_EQ(cs.size(), size); for (size_t i = 0; i < cs.size(); ++i) { EXPECT_EQ(cs[i].m_int, i); } try { std::vector<coro::Task<int>> tasks3; for (size_t i = 0; i < size; ++i) { tasks3.emplace_back(make_task_throws(i)); } coro::Task<std::vector<int>> c3 = coro::collectRange(std::move(tasks3)); coro::wait(std::move(c3)); EXPECT_FALSE(size > 0); } catch (const Error&) { EXPECT_TRUE(size > 0); } std::vector<coro::Task<void>> tasks4; for (size_t i = 0; i < size; ++i) { tasks4.emplace_back(make_task()); } coro::Task<void> c4 = coro::collectRange(std::move(tasks4)); static_assert( std::is_same<decltype(coro::wait(std::move(c4))), void>::value ); coro::wait(std::move(c4)); } } TEST(Coro, Invoke) { coro::Task<C> t1 = coro::invoke(&make_task_move, 101); EXPECT_EQ(coro::wait(std::move(t1)).m_int, 101); coro::Task<int> t2 = coro::invoke( [] (int x) -> coro::Task<int> { HPHP_CORO_RETURN(x); }, 123 ); EXPECT_EQ(coro::wait(std::move(t2)), 123); try { coro::Task<int> t = coro::invoke( [] (int x) -> coro::Task<int> { if (always_true()) throw Error{}; HPHP_CORO_RETURN(x); }, 123 ); coro::wait(std::move(t)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } auto const int1 = std::chrono::steady_clock::now().time_since_epoch().count(); auto const int2 = std::chrono::steady_clock::now().time_since_epoch().count() + 100; auto const int3 = std::chrono::steady_clock::now().time_since_epoch().count() + 200; auto const int4 = std::chrono::steady_clock::now().time_since_epoch().count() + 300; auto const takesRef = [] (const std::string& s) -> coro::Task<std::string> { HPHP_CORO_RETURN(folly::sformat("{}-{}", s, s)); }; coro::Task<std::string> t3 = coro::invoke(takesRef, std::to_string(int1)); coro::Task<std::string> t4 = coro::invoke(takesRef, std::to_string(int2)); coro::Task<std::string> t5 = coro::invoke(takesRef, std::to_string(int3)); coro::Task<std::string> t6 = coro::invoke(takesRef, std::to_string(int4)); coro::Task< std::tuple<std::string, std::string, std::string, std::string> > t7 = coro::collect(std::move(t6), std::move(t5), std::move(t4), std::move(t3)); std::tuple<std::string, std::string, std::string, std::string> t8 = coro::wait(std::move(t7)); EXPECT_EQ(std::get<0>(t8), folly::sformat("{}-{}", int4, int4)); EXPECT_EQ(std::get<1>(t8), folly::sformat("{}-{}", int3, int3)); EXPECT_EQ(std::get<2>(t8), folly::sformat("{}-{}", int2, int2)); EXPECT_EQ(std::get<3>(t8), folly::sformat("{}-{}", int1, int1)); } TEST(Coro, Sleep) { auto const sleeper = [] () -> coro::Task<void> { HPHP_CORO_AWAIT(coro::sleep(1s)); HPHP_CORO_RETURN_VOID; }; auto const before = std::chrono::steady_clock::now(); coro::wait(sleeper()); auto const secs = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::steady_clock::now() - before ).count(); EXPECT_TRUE(secs >= 1); } TEST(Coro, AsyncValue) { coro::AsyncValue<int> a1{ [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task(123))); }, folly::getGlobalCPUExecutor() }; coro::Task<const int*> t1 = *a1; EXPECT_EQ(*coro::wait(std::move(t1)), 123); coro::AsyncValue<int> a2{ [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task(456))); }, folly::getGlobalCPUExecutor() }; coro::Task<int> t2 = a2.getCopy(); EXPECT_EQ(coro::wait(std::move(t2)), 456); coro::AsyncValue<C> a3{ [] () -> coro::Task<C> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task_move(605))); }, folly::getGlobalCPUExecutor() }; coro::Task<const C*> t3 = *a3; const C* c1 = coro::wait(std::move(t3)); EXPECT_EQ(c1->m_int, 605); coro::AsyncValue<int> a4{ [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task_throws(1))); }, folly::getGlobalCPUExecutor() }; try { coro::Task<const int*> t = *a4; coro::wait(std::move(t)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } coro::AsyncValue<int> a5{ [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task_throws(1))); }, folly::getGlobalCPUExecutor() }; try { coro::Task<int> t = a5.getCopy(); coro::wait(std::move(t)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } } TEST(Coro, AsyncMap) { coro::AsyncMap<std::string, int> map; coro::Task<int> t1 = map.get( "123", [&] { return [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task(123))); }; }, folly::getGlobalCPUExecutor() ); EXPECT_EQ(coro::wait(std::move(t1)), 123); coro::Task<int> t2 = map.get( "123", [&] { return [] () -> coro::Task<int> { ADD_FAILURE(); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task(456))); }; }, folly::getGlobalCPUExecutor() ); EXPECT_EQ(coro::wait(std::move(t2)), 123); coro::Task<int> t3 = map.get( "456", [&] { return [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task(456))); }; }, folly::getGlobalCPUExecutor() ); EXPECT_EQ(coro::wait(std::move(t3)), 456); try { coro::Task<int> t4 = map.get( "789", [&] { return [] () -> coro::Task<int> { HPHP_CORO_AWAIT(coro::sleep(250ms)); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task_throws(789))); }; }, folly::getGlobalCPUExecutor() ); coro::wait(std::move(t4)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } try { coro::Task<int> t5 = map.get( "789", [&] { return [] () -> coro::Task<int> { ADD_FAILURE(); HPHP_CORO_RETURN(HPHP_CORO_AWAIT(make_task(789))); }; }, folly::getGlobalCPUExecutor() ); coro::wait(std::move(t5)); ADD_FAILURE(); } catch (const Error&) { SUCCEED(); } } TEST(Coro, AsyncScope) { auto const asyncSet = [] (int in, int* out) -> coro::Task<void> { HPHP_CORO_RESCHEDULE_ON_CURRENT_EXECUTOR; HPHP_CORO_AWAIT(coro::sleep(1s)); *out = in; HPHP_CORO_RETURN_VOID; }; coro::AsyncScope scope; int v1 = 0; int v2 = 0; int v3 = 0; scope.add(asyncSet(123, &v1).scheduleOn(folly::getGlobalCPUExecutor())); scope.add(asyncSet(456, &v2).scheduleOn(folly::getGlobalCPUExecutor())); scope.add(asyncSet(789, &v3).scheduleOn(folly::getGlobalCPUExecutor())); coro::wait(scope.joinAsync()); EXPECT_EQ(v1, 123); EXPECT_EQ(v2, 456); EXPECT_EQ(v3, 789); } TEST(Coro, TicketExecutor) { coro::TicketExecutor exec{ "coro-gtest", 0, 0, [] {}, [] {}, 24h }; EXPECT_EQ(exec.numThreads(), 0); std::vector<int> order; auto const async = [&] (int i1, int i2) -> coro::Task<void> { HPHP_CORO_RESCHEDULE_ON_CURRENT_EXECUTOR; order.emplace_back(i1); HPHP_CORO_RESCHEDULE_ON_CURRENT_EXECUTOR; order.emplace_back(i2); HPHP_CORO_RETURN_VOID; }; auto a1 = async(1, 10).scheduleOn(exec.sticky()); auto a2 = async(2, 20).scheduleOn(exec.sticky()); auto a3 = async(3, 30).scheduleOn(exec.sticky()); auto a4 = async(4, 40).scheduleOn(exec.sticky()); EXPECT_EQ(exec.getPendingTaskCount(), 0); coro::AsyncScope scope; scope.add(std::move(a4)); scope.add(std::move(a3)); scope.add(std::move(a2)); scope.add(std::move(a1)); EXPECT_EQ(exec.getPendingTaskCount(), coro::using_coros ? 4 : 0); exec.setNumThreads(1); EXPECT_EQ(exec.numThreads(), 1); coro::wait(scope.joinAsync()); EXPECT_EQ(exec.getPendingTaskCount(), 0); const std::vector<int> expected{1, 10, 2, 20, 3, 30, 4, 40}; EXPECT_EQ(order, expected); } TEST(Coro, CurrentExecutor) { auto const async = [&] () -> coro::Task<folly::Executor*> { HPHP_CORO_RETURN(HPHP_CORO_CURRENT_EXECUTOR); }; auto global = folly::getGlobalCPUExecutor(); auto executor = coro::wait(async().scheduleOn(global)); EXPECT_EQ(coro::using_coros ? global.get() : nullptr, executor); } }
26.507519
78
0.589987
[ "vector" ]
3b2960f3d549e29ff7523382e9ad33ba83b0f745
20,373
cpp
C++
spoopy/tools/vole/source/olderfiles/rbase/db_index_shida.cpp
rodrigobressan/PADify
362db2b3a33793ac53f938e89f90a6ecdf778e89
[ "MIT" ]
12
2019-11-26T07:44:08.000Z
2021-03-03T09:51:43.000Z
spoopy/tools/vole/source/rbase/db_index_shida.cpp
rodrigobressan/PADify
362db2b3a33793ac53f938e89f90a6ecdf778e89
[ "MIT" ]
13
2020-01-28T22:09:41.000Z
2022-03-11T23:43:37.000Z
spoopy/tools/vole/source/olderfiles/rbase/db_index_shida.cpp
rodrigobressan/PADify
362db2b3a33793ac53f938e89f90a6ecdf778e89
[ "MIT" ]
5
2020-01-02T09:52:42.000Z
2022-02-21T15:45:23.000Z
#include <sstream> #include <vector> #include <cassert> #include "db_index_shida.h" namespace iread { DbIndexShida::DbIndexShida(bool sharpenedPreMult, bool sharpenedPostMult) : nScenes(11), nLights(4), input_raw_data_path("/net/cv/illum/multi_shida/orig_tiff/"), raw_ground_truth_path("/net/cv/illum/multi_shida/orig_gt/"), descriptive_data_path("/net/cv/illum/multi_shida/img/"), descriptive_ground_truth_path("/net/cv/illum/multi_shida/gt/"), sharpenedPreMult(sharpenedPreMult), sharpenedPostMult(sharpenedPostMult) { this->mask_path = "/net/cv/illum/multi_shida/mask/"; if (sharpenedPreMult) { input_raw_data_path = "/net/cv/illum/multi_shida/orig_tiff_shpre/"; raw_ground_truth_path = "/net/cv/illum/multi_shida/orig_gt_shpre/"; descriptive_data_path = "/net/cv/illum/multi_shida/img_shpre/"; descriptive_ground_truth_path = "/net/cv/illum/multi_shida/gt_shpre/"; } else { if (sharpenedPostMult) { input_raw_data_path = "/net/cv/illum/multi_shida/orig_tiff_shpst/"; raw_ground_truth_path = "/net/cv/illum/multi_shida/orig_gt_shpst/"; descriptive_data_path = "/net/cv/illum/multi_shida/img_shpst/"; descriptive_ground_truth_path = "/net/cv/illum/multi_shida/gt_shpst/"; } } init(); initOffsets(); } DbIndexShida::DbIndexShida(std::string input_raw_data_path, std::string raw_gt_path, std::string descriptive_data_path, std::string descriptive_gt_path) : nScenes(11), nLights(4), input_raw_data_path(input_raw_data_path), raw_ground_truth_path(raw_gt_path), descriptive_data_path(descriptive_data_path), descriptive_ground_truth_path(descriptive_gt_path) { this->mask_path = "/net/cv/illum/multi_shida/mask/"; init(); initOffsets(); } DbIndexShida::~DbIndexShida() { for (int s = 0; s < nScenes; ++s) { for (int left = 0; left < nLights; ++left) { for (int right = 0; right < nLights; ++right) { if (table[s][left][right] != NULL) delete table[s][left][right]; for (int l2 = 0; l2 < nLights; ++l2) { for (int r2 = 0; r2 < nLights; ++r2) { if (offsets[s][left][right][l2][r2] != NULL) delete offsets[s][left][right][l2][r2]; } } } } } } void DbIndexShida::setRawDataPath(std::string raw_data_path) { this->input_raw_data_path = raw_data_path; } void DbIndexShida::setRawGroundTruthPath(std::string raw_ground_truth_path) { this->raw_ground_truth_path = raw_ground_truth_path; } void DbIndexShida::setDescriptiveDataPath(std::string descriptive_data_path) { this->descriptive_data_path = descriptive_data_path; } void DbIndexShida::setMaskPath(std::string mask_path) { this->mask_path = mask_path; } void DbIndexShida::setDescriptiveGroundTruthPath(std::string descriptive_ground_truth_path) { this->descriptive_ground_truth_path = descriptive_ground_truth_path; } std::string DbIndexShida::sceneToString(SCENE scene) { switch (scene) { case GT: return std::string("gt"); case MSPEC: return std::string("mspec"); case LION: return std::string("lion"); case DIFF: return std::string("diff"); case SPDIF: return std::string("spdif"); case YMUG: return std::string("ymug"); case PMUG: return std::string("pmug"); case BMUG: return std::string("bmug"); case BPMUG: return std::string("bpmug"); case BYMUG: return std::string("bymug"); case SPDIF2: return std::string("spdif2"); default: std::cerr << "DbIndexShida::sceneToString(): unknown scene " << scene << "!" << std::endl; return std::string("none"); }; } std::string DbIndexShida::illumToString(ILLUM illum) { switch (illum) { case NO: return std::string("n"); case W: return std::string("w"); case R: return std::string("r"); case B: return std::string("b"); default: std::cerr << "DbIndexShida::illumToString(): unknown illuminant " << illum << "!" << std::endl; return std::string("u"); }; } SCENE DbIndexShida::stringToScene(std::string scene) { if (scene.compare("gt") == 0) return GT; if (scene.compare("mspec") == 0) return MSPEC; if (scene.compare("lion") == 0) return LION; if (scene.compare("diff") == 0) return DIFF; if (scene.compare("spdif") == 0) return SPDIF; if (scene.compare("ymug") == 0) return YMUG; if (scene.compare("pmug") == 0) return PMUG; if (scene.compare("bmug") == 0) return BMUG; if (scene.compare("bpmug") == 0) return BPMUG; if (scene.compare("bymug") == 0) return BYMUG; if (scene.compare("spdif2") == 0) return SPDIF2; std::cerr << "DbIndexShida::stringToScene(): unknown scene " << scene << "!" << std::endl; return GT; // FIXME introduce "NONE" scene or so } ILLUM DbIndexShida::stringToIllum(std::string illum) { if (illum.compare("n") == 0) return NO; if (illum.compare("w") == 0) return W; if (illum.compare("r") == 0) return R; if (illum.compare("b") == 0) return B; std::cerr << "DbIndexShida::stringToIllum(): unknown illuminant " << illum << "!" << std::endl; return NO; } illumestimators::Illum DbIndexShida::getIllum(ILLUM illum) { assert((int)illum < 4); if (sharpenedPreMult) { return illums_shpre[(int)illum]; } else { if (sharpenedPostMult) { return illums_shpst[(int)illum]; } else { return illums[(int)illum]; } } } std::vector<SCENE> DbIndexShida::getScenes() { std::vector<SCENE> scenes; scenes.push_back(GT); scenes.push_back(MSPEC); scenes.push_back(LION); scenes.push_back(DIFF); scenes.push_back(SPDIF); scenes.push_back(YMUG); scenes.push_back(PMUG); scenes.push_back(BMUG); scenes.push_back(BPMUG); scenes.push_back(BYMUG); scenes.push_back(SPDIF2); return scenes; } std::vector<ILLUM> DbIndexShida::getIllums() { std::vector<ILLUM> illums; illums.push_back(NO); illums.push_back(W); illums.push_back(R); illums.push_back(B); return illums; } int DbIndexShida::getNumberScenes() { return nScenes; } int DbIndexShida::getNumberIlluminants() { return nLights; } cv::Point *DbIndexShida::offset(SCENE scene, ILLUM left1, ILLUM right1, ILLUM left2, ILLUM right2) { return offsets[scene][left1][right1][left2][right2]; } std::string DbIndexShida::gtLookupWithPath(SCENE scene, ILLUM left, ILLUM right, bool no_censorship) { if (table[scene][left][right] == NULL) return std::string(); if (!no_censorship) { if (((left == R) && (right == NO)) || ((left == NO) && (right == R))) return std::string(); // FIXME remove this when gt is available } std::stringstream full_path; full_path << raw_ground_truth_path << *table[scene][left][right]; return full_path.str(); } std::string DbIndexShida::descriptiveMaskLookupWithPath(SCENE scene, ILLUM left, ILLUM right) { if (table[scene][left][right] == NULL) return std::string(); if (((left == R) && (right == NO)) || ((left == NO) && (right == R))) return std::string(); // FIXME remove this when gt is available std::stringstream full_path; full_path << mask_path << "/" << DbIndexShida::sceneToString(scene) << "_mask.png"; return full_path.str(); } std::string *DbIndexShida::gtLookup(SCENE scene, ILLUM left, ILLUM right, bool no_censorship) { if (!no_censorship) { if (((left == R) && (right == NO)) || ((left == NO) && (right == R))) return NULL; // FIXME remove this when gt is available } return table[scene][left][right]; } std::string DbIndexShida::descriptiveGtLookup(SCENE scene, ILLUM left, ILLUM right) { std::stringstream s; if (descriptive_ground_truth_path.length() > 0) s << descriptive_ground_truth_path << "/"; s << DbIndexShida::sceneToString(scene) << "_" << DbIndexShida::illumToString(left) << "_" << DbIndexShida::illumToString(right) << "_gt.png"; return s.str(); } std::string DbIndexShida::descriptiveLookup(SCENE scene, ILLUM left, ILLUM right) { std::stringstream s; if (descriptive_data_path.length() > 0) s << descriptive_data_path << "/"; s << DbIndexShida::sceneToString(scene) << "_" << DbIndexShida::illumToString(left) << "_" << DbIndexShida::illumToString(right) << ".png"; return s.str(); } std::string DbIndexShida::lookupWithPath(SCENE scene, ILLUM left, ILLUM right) { if (table[scene][left][right] == NULL) return std::string(); std::stringstream full_path; full_path << input_raw_data_path << *table[scene][left][right]; return full_path.str(); } std::string *DbIndexShida::lookup(SCENE scene, ILLUM left, ILLUM right) { return table[scene][left][right]; } void DbIndexShida::init() { for (int s = 0; s < nScenes; ++s) { for (int left = 0; left < nLights; ++left) { for (int right = 0; right < nLights; ++right) { table[s][left][right] = NULL; } } } table[GT][NO][ W] = new std::string("IMG03221.tiff"); table[GT][NO][ R] = new std::string("IMG03222.tiff"); table[GT][NO][ B] = new std::string("IMG03223.tiff"); table[GT][ W][NO] = new std::string("IMG03224.tiff"); table[GT][ R][NO] = new std::string("IMG03225.tiff"); table[GT][ B][NO] = new std::string("IMG03226.tiff"); table[GT][ W][ W] = new std::string("IMG03227.tiff"); table[GT][ W][ B] = new std::string("IMG03228.tiff"); table[GT][ W][ R] = new std::string("IMG03229.tiff"); table[GT][ R][ B] = new std::string("IMG03231.tiff"); table[GT][ R][ W] = new std::string("IMG03232.tiff"); table[GT][ B][ W] = new std::string("IMG03233.tiff"); table[GT][ B][ R] = new std::string("IMG03234.tiff"); table[GT][ B][ B] = new std::string("IMG03390.tiff"); table[MSPEC][NO][ W] = new std::string("IMG03235.tiff"); table[MSPEC][NO][ R] = new std::string("IMG03236.tiff"); table[MSPEC][NO][ B] = new std::string("IMG03237.tiff"); table[MSPEC][ W][NO] = new std::string("IMG03238.tiff"); table[MSPEC][ R][NO] = new std::string("IMG03239.tiff"); table[MSPEC][ B][NO] = new std::string("IMG03240.tiff"); table[MSPEC][ W][ W] = new std::string("IMG03241.tiff"); table[MSPEC][ W][ B] = new std::string("IMG03242.tiff"); table[MSPEC][ W][ R] = new std::string("IMG03243.tiff"); table[MSPEC][ R][ B] = new std::string("IMG03244.tiff"); table[MSPEC][ R][ W] = new std::string("IMG03245.tiff"); table[MSPEC][ B][ W] = new std::string("IMG03246.tiff"); table[MSPEC][ B][ R] = new std::string("IMG03247.tiff"); table[MSPEC][ B][ B] = new std::string("IMG03248.tiff"); table[LION][NO][ W] = new std::string("IMG03249.tiff"); table[LION][NO][ R] = new std::string("IMG03250.tiff"); table[LION][NO][ B] = new std::string("IMG03251.tiff"); table[LION][ W][NO] = new std::string("IMG03252.tiff"); table[LION][ R][NO] = new std::string("IMG03253.tiff"); table[LION][ B][NO] = new std::string("IMG03254.tiff"); table[LION][ W][ W] = new std::string("IMG03255.tiff"); table[LION][ W][ B] = new std::string("IMG03257.tiff"); table[LION][ W][ R] = new std::string("IMG03256.tiff"); table[LION][ R][ B] = new std::string("IMG03258.tiff"); table[LION][ R][ W] = new std::string("IMG03259.tiff"); table[LION][ B][ W] = new std::string("IMG03260.tiff"); table[LION][ B][ R] = new std::string("IMG03261.tiff"); table[LION][ B][ B] = new std::string("IMG03262.tiff"); table[DIFF][NO][ W] = new std::string("IMG03263.tiff"); table[DIFF][NO][ R] = new std::string("IMG03264.tiff"); table[DIFF][NO][ B] = new std::string("IMG03265.tiff"); table[DIFF][ W][NO] = new std::string("IMG03266.tiff"); table[DIFF][ R][NO] = new std::string("IMG03267.tiff"); table[DIFF][ B][NO] = new std::string("IMG03268.tiff"); table[DIFF][ W][ W] = new std::string("IMG03269.tiff"); table[DIFF][ W][ B] = new std::string("IMG03272.tiff"); table[DIFF][ W][ R] = new std::string("IMG03271.tiff"); table[DIFF][ R][ B] = new std::string("IMG03273.tiff"); table[DIFF][ R][ W] = new std::string("IMG03274.tiff"); table[DIFF][ B][ W] = new std::string("IMG03275.tiff"); table[DIFF][ B][ R] = new std::string("IMG03276.tiff"); table[DIFF][ B][ B] = new std::string("IMG03277.tiff"); table[SPDIF][NO][ W] = new std::string("IMG03278.tiff"); table[SPDIF][NO][ R] = new std::string("IMG03279.tiff"); table[SPDIF][NO][ B] = new std::string("IMG03280.tiff"); table[SPDIF][ W][NO] = new std::string("IMG03281.tiff"); table[SPDIF][ R][NO] = new std::string("IMG03282.tiff"); table[SPDIF][ B][NO] = new std::string("IMG03283.tiff"); table[SPDIF][ W][ W] = new std::string("IMG03284.tiff"); table[SPDIF][ W][ B] = new std::string("IMG03286.tiff"); table[SPDIF][ W][ R] = new std::string("IMG03285.tiff"); table[SPDIF][ R][ B] = new std::string("IMG03287.tiff"); table[SPDIF][ R][ W] = new std::string("IMG03288.tiff"); table[SPDIF][ B][ W] = new std::string("IMG03289.tiff"); table[SPDIF][ B][ R] = new std::string("IMG03290.tiff"); table[SPDIF][ B][ B] = new std::string("IMG03291.tiff"); table[YMUG][NO][ W] = new std::string("IMG03295.tiff"); table[YMUG][NO][ R] = new std::string("IMG03296.tiff"); table[YMUG][NO][ B] = new std::string("IMG03297.tiff"); table[YMUG][ W][NO] = new std::string("IMG03298.tiff"); table[YMUG][ R][NO] = new std::string("IMG03299.tiff"); table[YMUG][ B][NO] = new std::string("IMG03300.tiff"); table[YMUG][ W][ W] = new std::string("IMG03301.tiff"); table[YMUG][ W][ B] = new std::string("IMG03303.tiff"); table[YMUG][ W][ R] = new std::string("IMG03302.tiff"); table[YMUG][ R][ B] = new std::string("IMG03304.tiff"); table[YMUG][ R][ W] = new std::string("IMG03305.tiff"); table[YMUG][ B][ W] = new std::string("IMG03306.tiff"); table[YMUG][ B][ R] = new std::string("IMG03307.tiff"); table[YMUG][ B][ B] = new std::string("IMG03308.tiff"); // table[PMUG][NO][ W] = new std::string("IMG03313.tiff"); // file appears to be damaged table[PMUG][NO][ R] = new std::string("IMG03314.tiff"); table[PMUG][NO][ B] = new std::string("IMG03315.tiff"); table[PMUG][ W][NO] = new std::string("IMG03316.tiff"); table[PMUG][ R][NO] = new std::string("IMG03317.tiff"); table[PMUG][ B][NO] = new std::string("IMG03318.tiff"); table[PMUG][ W][ W] = new std::string("IMG03319.tiff"); table[PMUG][ W][ B] = new std::string("IMG03321.tiff"); table[PMUG][ W][ R] = new std::string("IMG03320.tiff"); table[PMUG][ R][ B] = new std::string("IMG03323.tiff"); table[PMUG][ R][ W] = new std::string("IMG03324.tiff"); table[PMUG][ B][ W] = new std::string("IMG03325.tiff"); table[PMUG][ B][ R] = new std::string("IMG03326.tiff"); table[PMUG][ B][ B] = new std::string("IMG03327.tiff"); table[BMUG][NO][ W] = new std::string("IMG03329.tiff"); table[BMUG][NO][ R] = new std::string("IMG03330.tiff"); table[BMUG][NO][ B] = new std::string("IMG03331.tiff"); table[BMUG][ W][NO] = new std::string("IMG03332.tiff"); table[BMUG][ R][NO] = new std::string("IMG03333.tiff"); table[BMUG][ B][NO] = new std::string("IMG03334.tiff"); table[BMUG][ W][ W] = new std::string("IMG03335.tiff"); table[BMUG][ W][ B] = new std::string("IMG03337.tiff"); table[BMUG][ W][ R] = new std::string("IMG03336.tiff"); table[BMUG][ R][ B] = new std::string("IMG03338.tiff"); table[BMUG][ R][ W] = new std::string("IMG03339.tiff"); table[BMUG][ B][ W] = new std::string("IMG03340.tiff"); table[BMUG][ B][ R] = new std::string("IMG03341.tiff"); table[BMUG][ B][ B] = new std::string("IMG03342.tiff"); table[BPMUG][NO][ W] = new std::string("IMG03344.tiff"); table[BPMUG][NO][ R] = new std::string("IMG03345.tiff"); table[BPMUG][NO][ B] = new std::string("IMG03346.tiff"); table[BPMUG][ W][NO] = new std::string("IMG03347.tiff"); table[BPMUG][ R][NO] = new std::string("IMG03348.tiff"); table[BPMUG][ B][NO] = new std::string("IMG03349.tiff"); table[BPMUG][ W][ W] = new std::string("IMG03350.tiff"); table[BPMUG][ W][ B] = new std::string("IMG03352.tiff"); table[BPMUG][ W][ R] = new std::string("IMG03351.tiff"); table[BPMUG][ R][ B] = new std::string("IMG03353.tiff"); table[BPMUG][ R][ W] = new std::string("IMG03354.tiff"); table[BPMUG][ B][ W] = new std::string("IMG03355.tiff"); table[BPMUG][ B][ R] = new std::string("IMG03356.tiff"); table[BPMUG][ B][ B] = new std::string("IMG03357.tiff"); table[BYMUG][NO][ W] = new std::string("IMG03362.tiff"); table[BYMUG][NO][ R] = new std::string("IMG03363.tiff"); table[BYMUG][NO][ B] = new std::string("IMG03364.tiff"); table[BYMUG][ W][NO] = new std::string("IMG03365.tiff"); table[BYMUG][ R][NO] = new std::string("IMG03366.tiff"); table[BYMUG][ B][NO] = new std::string("IMG03367.tiff"); table[BYMUG][ W][ W] = new std::string("IMG03368.tiff"); table[BYMUG][ W][ B] = new std::string("IMG03370.tiff"); table[BYMUG][ W][ R] = new std::string("IMG03369.tiff"); table[BYMUG][ R][ B] = new std::string("IMG03371.tiff"); table[BYMUG][ R][ W] = new std::string("IMG03372.tiff"); table[BYMUG][ B][ W] = new std::string("IMG03373.tiff"); table[BYMUG][ B][ R] = new std::string("IMG03374.tiff"); table[BYMUG][ B][ B] = new std::string("IMG03375.tiff"); table[SPDIF2][NO][ W] = new std::string("IMG03376.tiff"); table[SPDIF2][NO][ R] = new std::string("IMG03377.tiff"); table[SPDIF2][NO][ B] = new std::string("IMG03378.tiff"); table[SPDIF2][ W][NO] = new std::string("IMG03379.tiff"); table[SPDIF2][ R][NO] = new std::string("IMG03380.tiff"); table[SPDIF2][ B][NO] = new std::string("IMG03381.tiff"); table[SPDIF2][ W][ W] = new std::string("IMG03382.tiff"); table[SPDIF2][ W][ B] = new std::string("IMG03384.tiff"); table[SPDIF2][ W][ R] = new std::string("IMG03383.tiff"); table[SPDIF2][ R][ B] = new std::string("IMG03385.tiff"); table[SPDIF2][ R][ W] = new std::string("IMG03386.tiff"); table[SPDIF2][ B][ W] = new std::string("IMG03387.tiff"); table[SPDIF2][ B][ R] = new std::string("IMG03388.tiff"); table[SPDIF2][ B][ B] = new std::string("IMG03389.tiff"); illums[(int)NO] = illumestimators::Illum(); // no illum illums[(int) W] = illumestimators::Illum(0.395077, 0.347945, 0.256978); // white illums[(int) R] = illumestimators::Illum(0.439926, 0.339551, 0.220523); // red illums[(int) B] = illumestimators::Illum(0.353101, 0.353849, 0.293049); // blue // FIXME manually determined from bright pixels: illums[(int) W] = illumestimators::Illum(0.404475, 0.344234, 0.251291); // white illums[(int) R] = illumestimators::Illum(0.458194, 0.334448, 0.207358); // red illums[(int) B] = illumestimators::Illum(0.365217, 0.347826, 0.286956); // blue // FIXME manually determined from darker pixels: illums[(int) W] = illumestimators::Illum(0.393728, 0.348432, 0.257840); // white illums[(int) R] = illumestimators::Illum(0.440678, 0.338983, 0.220339); // red illums[(int) B] = illumestimators::Illum(0.350877, 0.357895, 0.291228); // blue // FIXME SUPER MANUALLY determined from OUTPUT IMAGES: illums[(int) W] = illumestimators::Illum(0.388728, 0.348432, 0.262840); // white illums[(int) R] = illumestimators::Illum(0.428678, 0.343983, 0.227339); // red illums[(int) B] = illumestimators::Illum(0.340877, 0.357895, 0.301228); // blue illums[(int) W] = illumestimators::Illum(0.388728, 0.348432, 0.262840); // white illums[(int) R] = illumestimators::Illum(0.428678, 0.343983, 0.227339); // red illums[(int) B] = illumestimators::Illum(0.340877, 0.357895, 0.301228); // blue // SHARPENED PRE-MULTIPLICATION illums_shpre[(int)NO] = illumestimators::Illum(); // no illum illums_shpre[(int) W] = illumestimators::Illum(0.368662, 0.22628, 0.405059); // white illums_shpre[(int) R] = illumestimators::Illum(0.412981, 0.224986, 0.362033); // red illums_shpre[(int) B] = illumestimators::Illum(0.303797, 0.226448, 0.469756); // blue // SHARPENED POST-MULTIPLICATION illums_shpst[(int)NO] = illumestimators::Illum(); // no illum illums_shpst[(int) W] = illumestimators::Illum(0.453566, 0.28388, 0.262554); // white illums_shpst[(int) R] = illumestimators::Illum(0.559823, 0.226087, 0.21409); // red illums_shpst[(int) B] = illumestimators::Illum(0.26809, 0.376353, 0.355557); // blue } void DbIndexShida::setOffset(SCENE scene, ILLUM left1, ILLUM right1, ILLUM left2, ILLUM right2, int xOffset, int yOffset) { offsets[scene][left1][right1][left2][right2] = new cv::Point(); offsets[scene][left1][right1][left2][right2]->x = xOffset; offsets[scene][left1][right1][left2][right2]->y = yOffset; offsets[scene][left2][right2][left1][right1] = new cv::Point(); offsets[scene][left2][right2][left1][right1]->x = -xOffset; offsets[scene][left2][right2][left1][right1]->y = -yOffset; } void DbIndexShida::initOffsets() { for (int s = 0; s < nScenes; ++s) { for (int left = 0; left < nLights; ++left) { for (int right = 0; right < nLights; ++right) { for (int l2 = 0; l2 < nLights; ++l2) { for (int r2 = 0; r2 < nLights; ++r2) { offsets[s][left][right][l2][r2] = NULL; } } } } } // offsets[SPDIF2][ B][ B][ B][ B] = new cv::Point(1, 1); } }
40.422619
152
0.6595
[ "vector" ]
3b3610e466dd5b88c4b78f625c8d528ba57abf81
5,278
hpp
C++
include/cnn/neural_network.hpp
Matumba/CNN-Library
09c2214a8bbc901da132253e2175b6a5579c4477
[ "Apache-2.0" ]
1
2019-08-27T22:19:19.000Z
2019-08-27T22:19:19.000Z
include/cnn/neural_network.hpp
Matumba/CNN-Library
09c2214a8bbc901da132253e2175b6a5579c4477
[ "Apache-2.0" ]
null
null
null
include/cnn/neural_network.hpp
Matumba/CNN-Library
09c2214a8bbc901da132253e2175b6a5579c4477
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 by Glukhov V. O. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "util.hpp" #include "image_loader.hpp" #include "input_layer.hpp" #include "activation_function.hpp" #include "cost_function.hpp" #include "softmax_layer.hpp" #include "fully_connected_layer.hpp" #include "pooling_layer.hpp" #include "convolutional_layer.hpp" #include <armadillo> #include <memory> #include <vector> #include <fstream> #include <cstddef> namespace cnn { namespace nn { class NeuralNetwork { public: NeuralNetwork(std::unique_ptr<BaseImageLoader> loader, std::unique_ptr<BaseCostFunction> costFunction); void AppendLayer(std::unique_ptr<BaseLayer> layer); std::size_t Size() const noexcept; const std::wstring& LabelName(std::size_t id) const; void InitWeights() noexcept; bool is_initialized() const noexcept; bool LoadWeights(std::ifstream& in); bool SaveWeights(std::ofstream& out) const; bool LoadTestImage(); bool LoadTrainImage(); void SetInputImage(std::shared_ptr<arma::Cube<double>> image); std::shared_ptr<arma::Cube<double>> Hypothesis() const noexcept;; std::shared_ptr<arma::Cube<double>> Output(std::size_t layerIdx) const noexcept; std::shared_ptr<arma::Cube<double>> ReceptiveField(std::size_t layerIdx) const noexcept; double Error(); tensor4d& Weights(std::size_t layerIdx) noexcept { return layers_[layerIdx]->Weights(); } tensor4d& BiasWeights(std::size_t layerIdx) noexcept { return layers_[layerIdx]->BiasWeights(); } //propagate signals from bottom void Forward(); // compute Gradient std::vector<std::pair<tensor4d, tensor4d>> Backpropagation(); // compute Hessian std::vector<std::pair<tensor4d, tensor4d>> Backpropagation_2nd(); private: std::vector<std::unique_ptr<BaseLayer>> layers_; std::unique_ptr<BaseCostFunction> costFunc_; std::unique_ptr<InputLayer> in_; bool initialized_; }; inline NeuralNetwork::NeuralNetwork(std::unique_ptr<BaseImageLoader> loader, std::unique_ptr<BaseCostFunction> costFunction) : in_(std::make_unique<InputLayer>(std::move(loader))), costFunc_(std::move(costFunction)), initialized_(false) {} inline void NeuralNetwork::AppendLayer(std::unique_ptr<BaseLayer> layer) { layers_.emplace_back(std::move(layer)); } inline std::size_t NeuralNetwork::Size() const noexcept { return layers_.size(); } inline const std::wstring& NeuralNetwork::LabelName(std::size_t id) const { return in_->LabelName(id); } inline void NeuralNetwork::InitWeights() noexcept { for(std::unique_ptr<BaseLayer> & item : layers_) item->InitWeights(); initialized_ = true; } inline bool NeuralNetwork::is_initialized() const noexcept { return initialized_; } inline bool NeuralNetwork::LoadWeights(std::ifstream& in) { bool flag = true; for (std::unique_ptr<BaseLayer> & item : layers_) { flag = item->LoadWeights(in); if (!flag) return flag; } initialized_ = true; return flag; } inline bool NeuralNetwork::SaveWeights(std::ofstream& out) const { if (!initialized_ || layers_.empty()) return false; bool flag = true; for (const std::unique_ptr<BaseLayer> & item : layers_) { flag = item->SaveWeights(out); if (!flag) return flag; } return flag; } inline bool NeuralNetwork::LoadTestImage() { return in_->LoadTestImage(); } inline bool NeuralNetwork::LoadTrainImage() { return in_->LoadTrainImage(); } inline void NeuralNetwork::SetInputImage(std::shared_ptr<arma::Cube<double>> image) { in_->SetCustomImage(std::move(image)); } inline std::shared_ptr<arma::Cube<double>> NeuralNetwork::Hypothesis() const noexcept { return layers_.back()->Output(); } inline std::shared_ptr<arma::Cube<double>> NeuralNetwork::ReceptiveField( std::size_t layerIdx) const noexcept { #ifndef NDEBUG assert(layerIdx < layers_.size()); assert(initialized_); #endif return layers_[layerIdx]->ReceptiveField(); } inline std::shared_ptr<arma::Cube<double>> NeuralNetwork::Output(arma::uword layerIdx) const noexcept { #ifndef NDEBUG assert(layerIdx < layers_.size()); assert(initialized_); #endif return layers_[layerIdx]->Output(); } inline double NeuralNetwork::Error() { #ifndef NDEBUG assert(!in_->Labels().empty()); #endif if (SoftMaxLayer *output = dynamic_cast<SoftMaxLayer*>(layers_.back().get())) { return costFunc_->Compute(in_->Labels(), layers_.back()->ReceptiveField()->slice(0).col(0)); } else { return costFunc_->Compute(in_->Labels(), layers_.back()->Output()->slice(0).col(0)); } } } }
26.39
96
0.69875
[ "vector" ]
3b41efba333c859a76372d04a8388d829cb89a3c
3,037
cpp
C++
person.cpp
annykyforu/PRG2_SocialMediaApplication
67059bda6ca0e6a32856ea94f72e2f73fcf59b83
[ "MIT" ]
null
null
null
person.cpp
annykyforu/PRG2_SocialMediaApplication
67059bda6ca0e6a32856ea94f72e2f73fcf59b83
[ "MIT" ]
null
null
null
person.cpp
annykyforu/PRG2_SocialMediaApplication
67059bda6ca0e6a32856ea94f72e2f73fcf59b83
[ "MIT" ]
1
2019-12-02T11:57:39.000Z
2019-12-02T11:57:39.000Z
// // person.cpp // Social Media Application // // Created by annykyforu on 21.11.18. // Copyright © 2018 PRG2_ws18. All rights reserved. // #include <algorithm> #include "person.h" #include "social_media_account.h" Person::Person() : name{"Example Examplerius"} {} Person::Person(string n) { if(n == "") throw runtime_error("Error! Empty name is not allowed."); name = n; } string Person::get_name() const { return name; } int Person::add_account(string acc, int modus = 1) { if(modus == 1){ auto vip_acc = make_shared<VipAccount>(acc, shared_from_this()); media_accounts.push_back(vip_acc); return vip_acc->get_accountnumber(); } else { auto norm_acc = make_shared<NormalAccount>(acc, shared_from_this()); media_accounts.emplace_back(norm_acc); return norm_acc->get_accountnumber(); } } bool Person::remove_account(int numb) { auto result = find_if(media_accounts.begin(), media_accounts.end(), [&numb](const shared_ptr<SocialMediaAccount>& ptr) { return numb == ptr->get_accountnumber(); } ); if(result != media_accounts.end()) { media_accounts.erase(result); return true; } else { return false; } } bool Person::share(shared_ptr<Person> _pers, shared_ptr<SocialMediaAccount> _sma) { //check if this has an Account to share auto this_acc = find_if(media_accounts.begin(), media_accounts.end(), [&_sma](const shared_ptr<SocialMediaAccount> ptr_acc) { return _sma == ptr_acc; } ); if(this_acc == media_accounts.end()) { throw runtime_error(get_name() + " doesn't have an Account to share!"); return false; } //check if other Person doesn't already have the sharable Account auto _pers_acc = find_if(_pers->media_accounts.begin(), _pers->media_accounts.end(), [&_sma](const shared_ptr<SocialMediaAccount> ptr_acc) { return _sma == ptr_acc; } ); if (_pers_acc != _pers->media_accounts.end()) { throw runtime_error(_pers->get_name() + " is already an Owner of this account!"); return false; } _sma->add_person(_pers); _pers->media_accounts.push_back(_sma); return true; } ostream& Person::print(ostream& os) const { os << "[Name: " << name << ", "; os << "Account: {"; size_t count_accounts = media_accounts.size(); for_each(media_accounts.begin(), media_accounts.end(), [&os, &count_accounts](const shared_ptr<SocialMediaAccount>& ptr) { --count_accounts; ptr->print_small(os); if(count_accounts > 0) os << ", "; } ); os << "}]"; return os; } ostream& Person::print_small(ostream& os) const { os << name; return os; } const vector<shared_ptr<SocialMediaAccount>>& Person::get_accounts() const { return media_accounts; } ostream& operator<<(ostream& o, const Person& pers) { return pers.print(o); }
29.485437
101
0.621008
[ "vector" ]
3b46d1143d16f0af0eaceb777f4df9eaafb84cb0
13,119
cpp
C++
UnitTests/Physics/CollidePointTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
1,311
2021-08-16T07:37:05.000Z
2022-03-31T21:13:39.000Z
UnitTests/Physics/CollidePointTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
102
2021-08-28T14:41:32.000Z
2022-03-31T20:25:55.000Z
UnitTests/Physics/CollidePointTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
65
2021-08-16T07:59:04.000Z
2022-03-28T06:18:49.000Z
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include "UnitTestFramework.h" #include "PhysicsTestContext.h" #include "Layers.h" #include <Physics/Collision/Shape/BoxShape.h> #include <Physics/Collision/Shape/SphereShape.h> #include <Physics/Collision/Shape/CapsuleShape.h> #include <Physics/Collision/Shape/CylinderShape.h> #include <Physics/Collision/Shape/TaperedCapsuleShape.h> #include <Physics/Collision/Shape/ConvexHullShape.h> #include <Physics/Collision/Shape/RotatedTranslatedShape.h> #include <Physics/Collision/Shape/ScaledShape.h> #include <Physics/Collision/Shape/OffsetCenterOfMassShape.h> #include <Physics/Collision/Shape/StaticCompoundShape.h> #include <Physics/Collision/Shape/MutableCompoundShape.h> #include <Physics/Collision/Shape/MeshShape.h> #include <Physics/Collision/CollisionCollectorImpl.h> #include <Physics/Collision/CollidePointResult.h> TEST_SUITE("CollidePointTests") { // Probe directions in the direction of the faces static Vec3 cube_probes[] = { Vec3(-1.0f, 0, 0), Vec3(1.0f, 0, 0), Vec3(0, -1.0f, 0), Vec3(0, 1.0f, 0), Vec3(0, 0, -1.0f), Vec3(0, 0, 1.0f) }; // Probe directions in the direction of the faces static Vec3 cube_and_zero_probes[] = { Vec3(0, 0, 0), Vec3(-1.0f, 0, 0), Vec3(1.0f, 0, 0), Vec3(0, -1.0f, 0), Vec3(0, 1.0f, 0), Vec3(0, 0, -1.0f), Vec3(0, 0, 1.0f) }; // Probes in the xy-plane static Vec3 xy_probes[] = { Vec3(-1.0f, 0, 0), Vec3(1.0f, 0, 0), Vec3(0, 0, -1.0f), Vec3(0, 0, 1.0f) }; // Probes in the xy-plane and zero static Vec3 xy_and_zero_probes[] = { Vec3(0, 0, 0), Vec3(-1.0f, 0, 0), Vec3(1.0f, 0, 0), Vec3(0, 0, -1.0f), Vec3(0, 0, 1.0f) }; // Vertices of a cube static Vec3 cube_vertices[] = { Vec3(-1.0f, -1.0f, -1.0f), Vec3( 1.0f, -1.0f, -1.0f), Vec3(-1.0f, -1.0f, 1.0f), Vec3( 1.0f, -1.0f, 1.0f), Vec3(-1.0f, 1.0f, -1.0f), Vec3( 1.0f, 1.0f, -1.0f), Vec3(-1.0f, 1.0f, 1.0f), Vec3( 1.0f, 1.0f, 1.0f) }; static void sTestHit(const Shape *inShape, Vec3Arg inPosition) { AllHitCollisionCollector<CollidePointCollector> collector; inShape->CollidePoint(inPosition - inShape->GetCenterOfMass(), SubShapeIDCreator(), collector); CHECK(collector.mHits.size() == 1); } static void sTestHit(const NarrowPhaseQuery &inNarrowPhase, Vec3Arg inPosition, const BodyID &inBodyID) { AllHitCollisionCollector<CollidePointCollector> collector; inNarrowPhase.CollidePoint(inPosition, collector); CHECK(collector.mHits.size() == 1); CHECK(collector.mHits[0].mBodyID == inBodyID); } static void sTestMiss(const Shape *inShape, Vec3Arg inPosition) { AllHitCollisionCollector<CollidePointCollector> collector; inShape->CollidePoint(inPosition - inShape->GetCenterOfMass(), SubShapeIDCreator(), collector); CHECK(collector.mHits.empty()); } static void sTestMiss(const NarrowPhaseQuery &inNarrowPhase, Vec3Arg inPosition) { AllHitCollisionCollector<CollidePointCollector> collector; inNarrowPhase.CollidePoint(inPosition, collector); CHECK(collector.mHits.empty()); } TEST_CASE("TestCollidePointVsBox") { Vec3 half_box_size(0.1f, 0.2f, 0.3f); ShapeRefC shape = new BoxShape(half_box_size); // Hits for (Vec3 probe : cube_and_zero_probes) sTestHit(shape, 0.99f * half_box_size * probe); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, 1.01f * half_box_size * probe); } TEST_CASE("TestCollidePointVsSphere") { const float radius = 0.1f; ShapeRefC shape = new SphereShape(radius); // Hits for (Vec3 probe : cube_and_zero_probes) sTestHit(shape, 0.99f * Vec3::sReplicate(radius) * probe); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, 1.01f * Vec3::sReplicate(radius) * probe); } TEST_CASE("TestCollidePointVsCapsule") { const float half_height = 0.2f; const float radius = 0.1f; ShapeRefC shape = new CapsuleShape(half_height, radius); // Top hits for (Vec3 probe : xy_and_zero_probes) sTestHit(shape, 0.99f * radius * probe + Vec3(0, half_height, 0)); // Center hit sTestHit(shape, Vec3::sZero()); // Bottom hits for (Vec3 probe : xy_and_zero_probes) sTestHit(shape, 0.99f * radius * probe + Vec3(0, -half_height, 0)); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, 1.01f * Vec3(radius, half_height + radius, radius) * probe); } TEST_CASE("TestCollidePointVsTaperedCapsule") { const float half_height = 0.4f; const float top_radius = 0.1f; const float bottom_radius = 0.2f; TaperedCapsuleShapeSettings settings(half_height, top_radius, bottom_radius); ShapeRefC shape = settings.Create().Get(); // Top hits for (Vec3 probe : xy_and_zero_probes) sTestHit(shape, 0.99f * top_radius * probe + Vec3(0, half_height, 0)); // Center hit sTestHit(shape, Vec3::sZero()); // Bottom hits for (Vec3 probe : xy_and_zero_probes) sTestHit(shape, 0.99f * bottom_radius * probe + Vec3(0, -half_height, 0)); // Top misses sTestMiss(shape, Vec3(0, half_height + top_radius + 0.01f, 0)); for (Vec3 probe : xy_probes) sTestMiss(shape, 1.01f * top_radius * probe + Vec3(0, half_height, 0)); // Bottom misses sTestMiss(shape, Vec3(0, -half_height - bottom_radius - 0.01f, 0)); for (Vec3 probe : xy_probes) sTestMiss(shape, 1.01f * bottom_radius * probe + Vec3(0, -half_height, 0)); } TEST_CASE("TestCollidePointVsCylinder") { const float half_height = 0.2f; const float radius = 0.1f; ShapeRefC shape = new CylinderShape(half_height, radius); // Top hits for (Vec3 probe : xy_and_zero_probes) sTestHit(shape, 0.99f * (radius * probe + Vec3(0, half_height, 0))); // Center hit sTestHit(shape, Vec3::sZero()); // Bottom hits for (Vec3 probe : xy_and_zero_probes) sTestHit(shape, 0.99f * (radius * probe + Vec3(0, -half_height, 0))); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, 1.01f * Vec3(radius, half_height, radius) * probe); } TEST_CASE("TestCollidePointVsConvexHull") { Vec3 half_box_size(0.1f, 0.2f, 0.3f); Vec3 offset(10.0f, 11.0f, 12.0f); ConvexHullShapeSettings settings; for (uint i = 0; i < size(cube_vertices); ++i) settings.mPoints.push_back(offset + cube_vertices[i] * half_box_size); ShapeRefC shape = settings.Create().Get(); // Hits for (Vec3 probe : cube_and_zero_probes) sTestHit(shape, offset + 0.99f * half_box_size * probe); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, offset + 1.01f * half_box_size * probe); } TEST_CASE("TestCollidePointVsRotatedTranslated") { Vec3 translation(10.0f, 11.0f, 12.0f); Quat rotation = Quat::sRotation(Vec3(1, 2, 3).Normalized(), 0.3f * JPH_PI); Mat44 transform = Mat44::sRotationTranslation(rotation, translation); Vec3 half_box_size(0.1f, 0.2f, 0.3f); RotatedTranslatedShapeSettings settings(translation, rotation, new BoxShape(half_box_size)); ShapeRefC shape = settings.Create().Get(); // Hits for (Vec3 probe : cube_and_zero_probes) sTestHit(shape, transform * (0.99f * half_box_size * probe)); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, transform * (1.01f * half_box_size * probe)); } TEST_CASE("TestCollidePointVsScaled") { Vec3 scale(2.0f, 3.0f, -4.0f); Vec3 half_box_size(0.1f, 0.2f, 0.3f); ShapeRefC shape = new ScaledShape(new BoxShape(half_box_size), scale); // Hits for (Vec3 probe : cube_and_zero_probes) sTestHit(shape, scale * (0.99f * half_box_size * probe)); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, scale * (1.01f * half_box_size * probe)); } TEST_CASE("TestCollidePointVsOffsetCenterOfMass") { Vec3 offset(10.0f, 11.0f, 12.0f); Vec3 half_box_size(0.1f, 0.2f, 0.3f); OffsetCenterOfMassShapeSettings settings(offset, new BoxShape(half_box_size)); ShapeRefC shape = settings.Create().Get(); // Hits for (Vec3 probe : cube_and_zero_probes) sTestHit(shape, 0.99f * half_box_size * probe); // Misses for (Vec3 probe : cube_probes) sTestMiss(shape, 1.01f * half_box_size * probe); } TEST_CASE("TestCollidePointVsStaticCompound") { Vec3 translation1(10.0f, 11.0f, 12.0f); Quat rotation1 = Quat::sRotation(Vec3(1, 2, 3).Normalized(), 0.3f * JPH_PI); Mat44 transform1 = Mat44::sRotationTranslation(rotation1, translation1); Vec3 translation2(-1.0f, -2.0f, -3.0f); Quat rotation2 = Quat::sRotation(Vec3(4, 5, 6).Normalized(), 0.2f * JPH_PI); Mat44 transform2 = Mat44::sRotationTranslation(rotation2, translation2); Vec3 half_box_size(0.1f, 0.2f, 0.3f); ShapeRefC box = new BoxShape(half_box_size); StaticCompoundShapeSettings settings; settings.AddShape(translation1, rotation1, box); settings.AddShape(translation2, rotation2, box); ShapeRefC shape = settings.Create().Get(); // Hits for (Vec3 probe : cube_and_zero_probes) { Vec3 point = 0.99f * half_box_size * probe; sTestHit(shape, transform1 * point); sTestHit(shape, transform2 * point); } // Misses for (Vec3 probe : cube_probes) { Vec3 point = 1.01f * half_box_size * probe; sTestMiss(shape, transform1 * point); sTestMiss(shape, transform2 * point); } } TEST_CASE("TestCollidePointVsMutableCompound") { Vec3 translation1(10.0f, 11.0f, 12.0f); Quat rotation1 = Quat::sRotation(Vec3(1, 2, 3).Normalized(), 0.3f * JPH_PI); Mat44 transform1 = Mat44::sRotationTranslation(rotation1, translation1); Vec3 translation2(-1.0f, -2.0f, -3.0f); Quat rotation2 = Quat::sRotation(Vec3(4, 5, 6).Normalized(), 0.2f * JPH_PI); Mat44 transform2 = Mat44::sRotationTranslation(rotation2, translation2); Vec3 half_box_size(0.1f, 0.2f, 0.3f); ShapeRefC box = new BoxShape(half_box_size); MutableCompoundShapeSettings settings; settings.AddShape(translation1, rotation1, box); settings.AddShape(translation2, rotation2, box); ShapeRefC shape = settings.Create().Get(); // Hits for (Vec3 probe : cube_and_zero_probes) { Vec3 point = 0.99f * half_box_size * probe; sTestHit(shape, transform1 * point); sTestHit(shape, transform2 * point); } // Misses for (Vec3 probe : cube_probes) { Vec3 point = 1.01f * half_box_size * probe; sTestMiss(shape, transform1 * point); sTestMiss(shape, transform2 * point); } } TEST_CASE("TestCollidePointVsMesh") { // Face indices of a cube int indices[][3] = { { 0, 1, 3 }, { 0, 3, 2 }, { 4, 7, 5 }, { 4, 6, 7 }, { 2, 3, 6 }, { 3, 7, 6 }, { 1, 0, 4 }, { 1, 4, 5 }, { 1, 7, 3 }, { 1, 5, 7 }, { 0, 2, 6 }, { 0, 6, 4 } }; const int grid_size = 2; UnitTestRandom random; uniform_real_distribution<float> range(0.1f, 0.3f); // Create a grid of closed shapes MeshShapeSettings settings; settings.SetEmbedded(); int num_cubes = Cubed(2 * grid_size + 1); settings.mTriangleVertices.reserve(num_cubes * size(cube_vertices)); settings.mIndexedTriangles.reserve(num_cubes * size(indices)); for (int x = -grid_size; x <= grid_size; ++x) for (int y = -grid_size; y <= grid_size; ++y) for (int z = -grid_size; z <= grid_size; ++z) { Vec3 center((float)x, (float)y, (float)z); // Create vertices with randomness uint vtx = (uint)settings.mTriangleVertices.size(); settings.mTriangleVertices.resize(vtx + size(cube_vertices)); for (uint i = 0; i < size(cube_vertices); ++i) { Vec3 vertex(center + cube_vertices[i] * Vec3(range(random), range(random), range(random))); vertex.StoreFloat3(&settings.mTriangleVertices[vtx + i]); } // Flip inside out? (inside out shapes should act the same as normal shapes for CollidePoint) bool flip = (y & 1) == 0; // Create face indices uint idx = (uint)settings.mIndexedTriangles.size(); settings.mIndexedTriangles.resize(idx + size(indices)); for (uint i = 0; i < size(indices); ++i) settings.mIndexedTriangles[idx + i] = IndexedTriangle(vtx + indices[i][0], vtx + indices[i][flip? 2 : 1], vtx + indices[i][flip? 1 : 2]); } // Create body with random orientation PhysicsTestContext context; Body &mesh_body = context.CreateBody(&settings, Vec3::sRandom(random), Quat::sRandom(random), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, EActivation::DontActivate); // Get the shape ShapeRefC mesh_shape = mesh_body.GetShape(); // Get narrow phase const NarrowPhaseQuery &narrow_phase = context.GetSystem()->GetNarrowPhaseQuery(); // Get transform Mat44 body_transform = mesh_body.GetWorldTransform(); CHECK(body_transform != Mat44::sIdentity()); // Test points for (int x = -grid_size; x <= grid_size; ++x) for (int y = -grid_size; y <= grid_size; ++y) for (int z = -grid_size; z <= grid_size; ++z) { Vec3 center((float)x, (float)y, (float)z); // The center point should hit sTestHit(mesh_shape, center); sTestHit(narrow_phase, body_transform * center, mesh_body.GetID()); // Points outside the hull should not hit for (Vec3 probe : cube_probes) { Vec3 point = center + 0.4f * probe; sTestMiss(mesh_shape, point); sTestMiss(narrow_phase, body_transform * point); } } } }
30.368056
190
0.683741
[ "shape", "transform" ]
8dc9d2a94eb3e2dbb65e2bb4a20cddfce5fabab3
63,137
cpp
C++
RenderCore/OpenGLES/Metal/InputLayout.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
3
2018-05-17T08:39:39.000Z
2020-12-09T13:20:26.000Z
RenderCore/OpenGLES/Metal/InputLayout.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
null
null
null
RenderCore/OpenGLES/Metal/InputLayout.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
1
2021-11-14T08:50:15.000Z
2021-11-14T08:50:15.000Z
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "InputLayout.h" #include "Shader.h" #include "ShaderIntrospection.h" #include "Format.h" #include "TextureView.h" #include "PipelineLayout.h" #include "State.h" #include "Resource.h" #include "DeviceContext.h" #include "GPUSyncedAllocator.h" #include "../../Types.h" #include "../../Format.h" #include "../../BufferView.h" #include "../../../ConsoleRig/Log.h" #include "../../../Core/SelectConfiguration.h" #include "../../../Utility/StringUtils.h" #include "../../../Utility/StringFormat.h" #include "../../../Utility/PtrUtils.h" #include "../../../Utility/ArithmeticUtils.h" #include "IncludeGLES.h" #include <set> #include <unordered_set> #include <cctype> // #define EXTRA_INPUT_LAYOUT_LOGGING namespace RenderCore { namespace Metal_OpenGLES { std::unordered_set<std::string> g_whitelistedAttributesForBinding; bool BoundInputLayout::_warnOnMissingVertexAttribute = true; BoundInputLayout::BoundInputLayout(IteratorRange<const InputElementDesc*> layout, const ShaderProgram& program) { // // For each entry in "layout", we need to compare its name // with the names of the attributes in "shader". // // When we find a match, write the details into a binding object. // The binding object will be used to call glVertexAttribPointer. // const InputElementDesc* elements = layout.begin(); size_t elementsCount = layout.size(); _bindings.reserve(elementsCount); _attributeState = 0; _allAttributesBound = false; _vaoBindingHash = 0; unsigned vbMax = 0; for (const auto&l:layout) vbMax = std::max(l._inputSlot, vbMax); auto programIndex = program.GetUnderlying(); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, (GLint*)&_maxVertexAttributes); for (unsigned vbIndex = 0; vbIndex <= vbMax; ++vbIndex) { auto bindingStart = _bindings.size(); size_t vertexStride = 0; { unsigned lastElementEnd = 0; for (size_t c=0; c<elementsCount; ++c) { if (elements[c]._inputSlot != vbIndex) continue; const unsigned elementSize = BitsPerPixel(elements[c]._nativeFormat) / 8; const unsigned elementStart = (elements[c]._alignedByteOffset != ~unsigned(0x0))?elements[c]._alignedByteOffset:lastElementEnd; vertexStride = std::max(vertexStride, size_t(elementStart + elementSize)); lastElementEnd = elementStart + elementSize; } } unsigned lastElementEnd = 0; for (size_t c=0; c<elementsCount; ++c) { if (elements[c]._inputSlot != vbIndex) continue; char buffer[64]; XlCopyString(buffer, elements[c]._semanticName.c_str()); XlCatString(buffer, dimof(buffer), char('0' + elements[c]._semanticIndex)); GLint attribute = glGetAttribLocation(programIndex->AsRawGLHandle(), buffer); const unsigned elementSize = BitsPerPixel(elements[c]._nativeFormat) / 8; const unsigned elementStart = (elements[c]._alignedByteOffset != ~unsigned(0x0)) ? elements[c]._alignedByteOffset : lastElementEnd; // // The index can be left off the string for the first // one // if (attribute == -1 && elements[c]._semanticIndex == 0) { attribute = glGetAttribLocation(programIndex->AsRawGLHandle(), elements[c]._semanticName.c_str()); } if (attribute < 0) { // Binding failure! Write a warning, but ignore it. The binding is // still valid even if one or more attributes fail Log(Warning) << "Failure during vertex attribute binding. Attribute (" << buffer << ") cannot be found in the program. Ignoring" << std::endl; } else { const auto componentType = GetComponentType(elements[c]._nativeFormat); _bindings.push_back({ unsigned(attribute), GetComponentCount(GetComponents(elements[c]._nativeFormat)), AsGLVertexComponentType(elements[c]._nativeFormat), (componentType == FormatComponentType::UNorm) || (componentType == FormatComponentType::SNorm) || (componentType == FormatComponentType::UNorm_SRGB), unsigned(vertexStride), elementStart, elements[c]._inputSlotClass == InputDataRate::PerVertex ? 0 : elements[c]._instanceDataStepRate }); assert(!(_attributeState & 1<<unsigned(attribute))); _attributeState |= 1<<unsigned(attribute); } lastElementEnd = elementStart + elementSize; } if (bindingStart != (unsigned)_bindings.size()) _bindingsByVertexBuffer.push_back(unsigned(_bindings.size() - bindingStart)); } _allAttributesBound = CalculateAllAttributesBound(program); CheckGLError("Construct BoundInputLayout"); } BoundInputLayout::BoundInputLayout(IteratorRange<const SlotBinding*> layouts, const ShaderProgram& program) { _attributeState = 0; _allAttributesBound = false; _vaoBindingHash = 0; auto programHandle = program.GetUnderlying()->AsRawGLHandle(); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, (GLint*)&_maxVertexAttributes); int activeAttributeCount = 0, activeAttributeMaxLength = 0; glGetProgramiv(programHandle, GL_ACTIVE_ATTRIBUTES, &activeAttributeCount); glGetProgramiv(programHandle, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &activeAttributeMaxLength); GLchar buffer[activeAttributeMaxLength]; if (!layouts.empty()) { std::vector<Binding> workingBindings[layouts.size()]; unsigned vertexStrides[layouts.size()]; for (unsigned c=0; c<layouts.size(); ++c) vertexStrides[c] = CalculateVertexStride(layouts[c]._elements, false); for (int attrIndex=0; attrIndex<activeAttributeCount; ++attrIndex) { GLint size; GLenum type; GLsizei nameLen; glGetActiveAttrib(programHandle, attrIndex, activeAttributeMaxLength, &nameLen, &size, &type, buffer); if (!nameLen) continue; // ignore "gl" system attributes if (!strncmp(buffer, "gl_", 3)) continue; GLint attrLoc = glGetAttribLocation(programHandle, buffer); auto semanticIdx = nameLen; while (std::isdigit(buffer[semanticIdx-1])) --semanticIdx; uint64_t hash = Hash64(buffer, &buffer[semanticIdx]); hash += std::atoi(&buffer[semanticIdx]); bool foundBinding = false; for (auto l=layouts.begin(); l!=layouts.end(); ++l) { auto i = std::find_if(l->_elements.begin(), l->_elements.end(), [hash](const MiniInputElementDesc&e) { return e._semanticHash == hash; }); if (i == l->_elements.end()) continue; const auto elementStart = CalculateVertexStride(MakeIteratorRange(l->_elements.begin(), i), false); unsigned slotIdx = (unsigned)std::distance(layouts.begin(), l); const auto componentType = GetComponentType(i->_nativeFormat); workingBindings[slotIdx].push_back({ unsigned(attrLoc), GetComponentCount(GetComponents(i->_nativeFormat)), AsGLVertexComponentType(i->_nativeFormat), (componentType == FormatComponentType::UNorm) || (componentType == FormatComponentType::SNorm) || (componentType == FormatComponentType::UNorm_SRGB), vertexStrides[slotIdx], elementStart, l->_instanceStepDataRate }); foundBinding = true; break; } if (foundBinding) { assert(!(_attributeState & 1 << unsigned(attrLoc))); _attributeState |= 1 << unsigned(attrLoc); } } for (unsigned c=0; c<layouts.size(); ++c) { _bindings.insert(_bindings.end(), workingBindings[c].begin(), workingBindings[c].end()); _bindingsByVertexBuffer.push_back(unsigned(workingBindings[c].size())); } assert(_bindings.size() <= _maxVertexAttributes); } _allAttributesBound = CalculateAllAttributesBound(program); CheckGLError("Construct BoundInputLayout"); } bool BoundInputLayout::CalculateAllAttributesBound(const ShaderProgram& program) { #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) _unboundAttributesNames = std::vector<std::string>(); #endif auto programHandle = program.GetUnderlying()->AsRawGLHandle(); int activeAttributeCount = 0, activeAttributeMaxLength = 0; glGetProgramiv(programHandle, GL_ACTIVE_ATTRIBUTES, &activeAttributeCount); glGetProgramiv(programHandle, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &activeAttributeMaxLength); GLchar buffer[activeAttributeMaxLength]; for (unsigned attrIndex = 0; attrIndex < activeAttributeCount; ++attrIndex) { GLint size; GLenum type; GLsizei nameLen; glGetActiveAttrib(programHandle, attrIndex, activeAttributeMaxLength, &nameLen, &size, &type, buffer); // ignore "gl" system attributes if (!strncmp(buffer, "gl_", 3)) continue; // ignore whitelisted attributes if (g_whitelistedAttributesForBinding.find(std::string(buffer)) != g_whitelistedAttributesForBinding.end()) { continue; } auto location = glGetAttribLocation(programHandle, buffer); bool hasBoundAttribute = false; for (const auto&b:_bindings) { if (b._attributeLocation == location) { hasBoundAttribute = true; break; } } if (!hasBoundAttribute) { if (_warnOnMissingVertexAttribute) { Log(Warning) << "Failure during vertex attribute binding. Attribute (" << (const char*)buffer << ") cannot be found in the input binding." << std::endl; } #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) _unboundAttributesNames.emplace_back(std::string(buffer)); #else // return early if not keeping track of unbound attributes return false; #endif } } #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) return _unboundAttributesNames.empty(); #else // since it didn't return early, no attributes are missing return true; #endif } #if defined(_DEBUG) && PLATFORMOS == PLATFORMOS_IOS static void ArrayBufferCanaryCheck() { // // On IOS, we've run into a case where array buffers created in background contexts // will not be valid for use with glVertexAttribPointer. It appears to be a particular // bug or restriction within the driver. When it happens, we just get an error code // back from glVertexAttribPointer. // // However, in this case, we will also get a crash if we try to call glMapBufferRange // on the buffer in question. Given than IOS has a shared memory model, we are normally // always able to map a buffer for reading. So we can check for this condition by // calling glMapBufferRange() before the call to glVertexAttribPointer(). If we hit // the particular driver bug, we will crash there. Even though it's upgrading a GL // error code to a crash, it's makes it easier to distinguish this particular issue // from other errors in the glVertexAttribPointer() and can help highlight the // problem sooner. // static unsigned canaryCheckCount = 32; if (canaryCheckCount != 32) { ++canaryCheckCount; return; } canaryCheckCount = 0; GLint arrayBufferBinding0 = 0; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBufferBinding0); assert(glIsBuffer(arrayBufferBinding0)); GLint bufferSize = 0, bufferMapped = 0, bufferUsage = 0; glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bufferSize); glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_MAPPED, &bufferMapped); glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_USAGE, &bufferUsage); void* mappedData = glMapBufferRange(GL_ARRAY_BUFFER, 0, bufferSize, GL_MAP_READ_BIT); assert(mappedData); (void)mappedData; glUnmapBuffer(GL_ARRAY_BUFFER); } #else inline void ArrayBufferCanaryCheck() {} #endif uint32_t BoundInputLayout::UnderlyingApply(DeviceContext& devContext, IteratorRange<const VertexBufferView*> vertexBuffers, bool cancelOnError) const never_throws { if (cancelOnError) { auto error = glGetError(); if (error != GL_NO_ERROR) { return error; } } auto featureSet = devContext.GetFeatureSet(); uint32_t instanceFlags = 0u; uint32_t instanceDataRate[32]; unsigned attributeIterator = 0; for (unsigned b=0; b<unsigned(_bindingsByVertexBuffer.size()); ++b) { auto bindingCount = _bindingsByVertexBuffer[b]; assert(b < vertexBuffers.size()); if (!bindingCount) continue; const auto& vb = vertexBuffers[b]; glBindBuffer(GL_ARRAY_BUFFER, GetBufferRawGLHandle(*vb._resource)); ArrayBufferCanaryCheck(); for(auto ai=attributeIterator; ai<(attributeIterator+bindingCount); ++ai) { const auto& i = _bindings[ai]; glVertexAttribPointer( i._attributeLocation, i._size, i._type, i._isNormalized, i._stride, (const void*)(size_t)(vb._offset + i._offset)); instanceFlags |= ((i._instanceDataRate!=0)<<i._attributeLocation); instanceDataRate[i._attributeLocation] = i._instanceDataRate; } attributeIterator += bindingCount; } if (cancelOnError) { auto error = glGetError(); if (error != GL_NO_ERROR) { return error; } } auto* capture = devContext.GetCapturedStates(); if (capture) { if (featureSet & FeatureSet::GLES300) { auto differences = (capture->_instancedVertexAttrib & _attributeState) | instanceFlags; if (differences) { int firstActive = xl_ctz4(differences); int lastActive = 32u - xl_clz4(differences); for (int c=firstActive; c<lastActive; ++c) if (_attributeState & (1<<c)) glVertexAttribDivisor(c, instanceDataRate[c]); capture->_instancedVertexAttrib = (capture->_instancedVertexAttrib & ~_attributeState) | instanceFlags; } } else { auto differences = (capture->_instancedVertexAttrib & _attributeState) | instanceFlags; if (differences) { #if GL_ARB_instanced_arrays int firstActive = xl_ctz4(differences); int lastActive = 32u - xl_clz4(differences); for (int c=firstActive; c<lastActive; ++c) if (_attributeState & (1<<c)) glVertexAttribDivisorARB(c, instanceDataRate[c]); capture->_instancedVertexAttrib = (capture->_instancedVertexAttrib & ~_attributeState) | instanceFlags; #else assert(0); // no hardware support for variable rate input attributes #endif } } // set enable/disable flags -- // Note that this method cannot support more than 32 vertex attributes auto differences = capture->_activeVertexAttrib ^ _attributeState; if (differences) { int firstActive = xl_ctz4(differences); int lastActive = 32u - xl_clz4(differences); for (int c=firstActive; c<lastActive; ++c) if (_attributeState & (1<<c)) { glEnableVertexAttribArray(c); } else { glDisableVertexAttribArray(c); } capture->_activeVertexAttrib = _attributeState; } } else { if (featureSet & FeatureSet::GLES300) { for (int c=0; c<std::min(32u, _maxVertexAttributes); ++c) if (_attributeState & (1<<c)) glVertexAttribDivisor(c, instanceDataRate[c]); } else { #if GL_ARB_instanced_arrays for (int c=0; c<std::min(32u, _maxVertexAttributes); ++c) if (_attributeState & (1<<c)) glVertexAttribDivisorARB(c, instanceDataRate[c]); #else for (int c=0; c<std::min(32u, _maxVertexAttributes); ++c) if (_attributeState & (1<<c)) { assert(instanceDataRate[c] == 0); // no hardware support for variable rate input attributes } #endif } for (int c=0; c<std::min(32u, _maxVertexAttributes); ++c) if (_attributeState & (1<<c)) { glEnableVertexAttribArray(c); } else { glDisableVertexAttribArray(c); } } if (cancelOnError) { auto error = glGetError(); if (error != GL_NO_ERROR) { return error; } } CheckGLError("Apply BoundInputLayout"); return GL_NO_ERROR; } static void UnderlyingBindVAO(DeviceContext& devContext, RawGLHandle vao) { auto featureSet = devContext.GetFeatureSet(); if (featureSet & FeatureSet::GLES300) { glBindVertexArray(vao); } else { #if GL_APPLE_vertex_array_object glBindVertexArrayAPPLE(vao); #else glBindVertexArrayOES(vao); #endif } } static void BindVAO(DeviceContext& devContext, RawGLHandle vao) { auto* capture = devContext.GetCapturedStates(); if (capture) { capture->VerifyIntegrity(); if (capture->_boundVAO == vao) return; capture->_boundVAO = vao; } UnderlyingBindVAO(devContext, vao); } static uint64_t Hash(IteratorRange<const VertexBufferView*> vertexBuffers) { auto hash = DefaultSeed64; for (auto& vbv:vertexBuffers) { hash = HashCombine(hash, vbv._resource->GetGUID()); if (vbv._offset) hash = HashCombine(hash, vbv._offset); } return hash; } #if defined(_DEBUG) && !PGDROID void BoundInputLayout::ValidateVAO(DeviceContext& devContext, IteratorRange<const VertexBufferView*> vertexBuffers) const { GLint prevVAO = 0; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &prevVAO); auto featureSet = devContext.GetFeatureSet(); if (featureSet & FeatureSet::GLES300) { assert(glIsVertexArray(_vao->AsRawGLHandle())); } else { #if GL_APPLE_vertex_array_object assert(glIsVertexArrayAPPLE(_vao->AsRawGLHandle())); #else assert(glIsVertexArrayOES(_vao->AsRawGLHandle())); #endif } UnderlyingBindVAO(devContext, _vao->AsRawGLHandle()); for (unsigned c=0; c<_maxVertexAttributes; ++c) { GLint isEnabled = 0; glGetVertexAttribiv(c, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &isEnabled); assert(!!(_attributeState & (1<<c)) == isEnabled); if (!isEnabled) continue; auto i = std::find_if( _bindings.begin(), _bindings.end(), [c](const Binding& binding) { return binding._attributeLocation == c; }); assert(i!=_bindings.end()); size_t bindingIdx = std::distance(_bindings.begin(), i); auto vb=_bindingsByVertexBuffer.begin(); for (; vb!=_bindingsByVertexBuffer.end(); ++i) { if (bindingIdx < *vb) break; bindingIdx -= *vb; } assert(vb != _bindingsByVertexBuffer.end()); size_t vbIdx = std::distance(_bindingsByVertexBuffer.begin(), vb); assert(vbIdx < vertexBuffers.size()); GLint arrayBufferBinding = 0; glGetVertexAttribiv(c, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &arrayBufferBinding); assert(arrayBufferBinding == GetBufferRawGLHandle(*vertexBuffers[vbIdx]._resource)); GLint size = 0, stride = 0, type = 0, normalized = 0; glGetVertexAttribiv(c, GL_VERTEX_ATTRIB_ARRAY_SIZE, &size); glGetVertexAttribiv(c, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &stride); glGetVertexAttribiv(c, GL_VERTEX_ATTRIB_ARRAY_TYPE, &type); glGetVertexAttribiv(c, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &normalized); assert(size == i->_size); assert(stride == i->_stride); assert(type == i->_type); assert(normalized == i->_isNormalized); GLvoid *pointer = nullptr; glGetVertexAttribPointerv(c, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer); assert(pointer == (const void*)(size_t)(vertexBuffers[vbIdx]._offset + i->_offset)); } UnderlyingBindVAO(devContext, prevVAO); } #endif void BoundInputLayout::Apply(DeviceContext& devContext, IteratorRange<const VertexBufferView*> vertexBuffers) const never_throws { if (_vao) { // The "vao" binds this input layout to a specific set of vertex buffers (passed to CreateVAO()) // If you hit this assert, it means that the vertex buffers passed to CreateVAO don't match what's // passed to this function. That won't work; you need to either clone the BoundInputLayout for // each set of vertex buffers you want to use, or just don't call CreateVAO at all. assert(_vaoBindingHash == Hash(vertexBuffers)); #if defined(_DEBUG) && !PGDROID ValidateVAO(devContext, vertexBuffers); #endif BindVAO(devContext, _vao->AsRawGLHandle()); } else { BindVAO(devContext, 0); UnderlyingApply(devContext, vertexBuffers, false); } } void BoundInputLayout::CreateVAO(DeviceContext& devContext, IteratorRange<const VertexBufferView*> vertexBuffers) { _vao = nullptr; _vao = GetObjectFactory(devContext).CreateVAO(); if (!_vao) return; auto* originalCapture = devContext.GetCapturedStates(); if (originalCapture) devContext.EndStateCapture(); BindVAO(devContext, _vao->AsRawGLHandle()); auto error = UnderlyingApply(devContext, vertexBuffers, true); if (error != GL_NO_ERROR) { Log(Warning) << "Encountered OpenGL error (0x" << std::hex << error << std::dec << ") while attempt to create VAO. Dropping back to non-VAO path. Note that without VAOs performance will be severely impacted." << std::endl; _vao = nullptr; _vaoBindingHash = 0; } else { _vaoBindingHash = Hash(vertexBuffers); } // Reset cached state in devContext // When a vao other than 0 is bound, it's unclear to me how calls to glEnableVertexAttribArray, etc, // affect VAO 0. Let's just play safe, and reset everything to default, and clear out the cached values // in DeviceContext BindVAO(devContext, 0); if (originalCapture) devContext.BeginStateCapture(*originalCapture); } //////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderProgramCapturedState { public: struct Structs { uint64_t _cbNameHash; uint64_t _boundContents; unsigned _deviceContextCaptureGUID; }; std::vector<Structs> _structs; struct UniformBuffers { uint64_t _cbNameHash; unsigned _boundBuffer; unsigned _deviceContextCaptureGUID; unsigned _rangeBegin = 0; unsigned _rangeEnd = 0; uint64_t _boundContents; }; std::vector<UniformBuffers> _uniformBuffers; unsigned GetCBIndex(uint64_t hashName) { auto i = std::find_if( _structs.begin(), _structs.end(), [hashName](const Structs& cb) { return cb._cbNameHash == hashName; }); if (i == _structs.end()) return ~0u; return (unsigned)std::distance(_structs.begin(), i); } ShaderProgramCapturedState(const ShaderIntrospection& introspection) { _structs.reserve(introspection.GetStructs().size()); for (const auto&s:introspection.GetStructs()) { _structs.push_back(Structs{s.first, 0, 0}); } _uniformBuffers.reserve(introspection.GetUniformBlocks().size()); for (const auto&s:introspection.GetUniformBlocks()) { _uniformBuffers.push_back(UniformBuffers{s.first, 0, 0}); } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// unsigned BoundUniforms::s_uniformSetAccumulator = 0; unsigned BoundUniforms::s_redundantUniformSetAccumulator = 0; bool BoundUniforms::s_doRedundantUniformSetReduction = true; void BoundUniforms::Apply( DeviceContext& context, unsigned streamIdx, const UniformsStream& stream) const { // this could be improved by ordering _cbs, _srvs by stream idx -- that way we wouldn't // have to spend so much time searching through for the right bindings for (const auto&cb:_cbs) { if (cb._stream != streamIdx) continue; #if defined(_DEBUG) if (cb._slot >= stream._constantBuffers.size()) Throw(::Exceptions::BasicLabel("Uniform stream does not include Constant Buffer for bound resource. Expected CB bound at index (%u) of stream (%u). Only (%u) CBs were provided in the UniformsStream passed to BoundUniforms::Apply", cb._slot, cb._stream, stream._constantBuffers.size())); #endif assert(!cb._commandGroup._commands.empty()); const auto& cbv = stream._constantBuffers[cb._slot]; const auto& pkt = cbv._packet; IteratorRange<const void*> pktData; uint64_t pktHash = 0; if (pkt.size() != 0) { pktHash = pkt.GetHash(); pktData = MakeIteratorRange(pkt.begin(), pkt.end()); assert(cbv._prebuiltRangeBegin == 0 && cbv._prebuiltRangeEnd == 0); // we don't support using partial parts of the constant buffer in this case } else { pktHash = ((Resource*)cbv._prebuiltBuffer)->GetConstantBufferHash(); pktData = ((Resource*)cbv._prebuiltBuffer)->GetConstantBuffer(); pktData.first = std::min(pktData.end(), PtrAdd(pktData.begin(), cbv._prebuiltRangeBegin)); pktData.second = std::min(pktData.end(), PtrAdd(pktData.begin(), cbv._prebuiltRangeEnd)); } if (!pktData.empty()) { assert(cb._capturedStateIndex < _capturedState->_structs.size()); auto& capturedState = _capturedState->_structs[cb._capturedStateIndex]; bool redundantSet = false; if (pktHash != 0 && context.GetCapturedStates() && s_doRedundantUniformSetReduction) { redundantSet = capturedState._boundContents == pktHash && capturedState._deviceContextCaptureGUID == context.GetCapturedStates()->_captureGUID; capturedState._boundContents = pktHash; capturedState._deviceContextCaptureGUID = context.GetCapturedStates()->_captureGUID; } if (!redundantSet) { s_uniformSetAccumulator += Bind(context, cb._commandGroup, pktData); } else { s_redundantUniformSetAccumulator += (unsigned)cb._commandGroup._commands.size(); } } } auto* capture = context.GetCapturedStates(); for (const auto&srv:_srvs) { if (srv._stream != streamIdx) continue; #if defined(_DEBUG) if (srv._slot >= stream._resources.size()) Throw(::Exceptions::BasicLabel("Uniform stream does not include SRV for bound resource. Expected SRV bound at index (%u) of stream (%u). Only (%u) SRVs were provided in the UniformsStream passed to BoundUniforms::Apply", srv._slot, srv._stream, stream._resources.size())); #endif const auto& res = *(ShaderResourceView*)stream._resources[srv._slot]; const auto& sampler = *(SamplerState*)stream._samplers[srv._slot]; if (res.GetResource()) { if (capture) { if (capture->_activeTextureIndex != srv._textureUnit) { glActiveTexture(GL_TEXTURE0 + srv._textureUnit); capture->_activeTextureIndex = srv._textureUnit; } glBindTexture(srv._dimensionality, res.GetUnderlying()->AsRawGLHandle()); sampler.Apply(*capture, srv._textureUnit, srv._dimensionality, res.GetResource().get(), res.HasMipMaps()); } else { glActiveTexture(GL_TEXTURE0 + srv._textureUnit); glBindTexture(srv._dimensionality, res.GetUnderlying()->AsRawGLHandle()); sampler.Apply(srv._textureUnit, srv._dimensionality, res.HasMipMaps()); } } else { #if 0 // defined(_DEBUG) Log(Warning) << "Null resource while binding SRV to texture uniform (" << srv._name << ")" << std::endl; #endif } } #if defined(GL_ES_VERSION_3_0) && !PGDROID if (GetObjectFactory().GetFeatureSet() & FeatureSet::GLES300) { auto& reusableTemporarySpace = GetObjectFactory().GetReusableCBSpace(); for (const auto&uniformBuffer:_uniformBuffer) { if (uniformBuffer._stream != streamIdx) continue; assert(uniformBuffer._slot < stream._constantBuffers.size()); assert(uniformBuffer._uniformBlockIdx < _capturedState->_uniformBuffers.size()); auto& capturedState = _capturedState->_uniformBuffers[uniformBuffer._uniformBlockIdx]; const auto& cbv = stream._constantBuffers[uniformBuffer._slot]; const auto& pkt = cbv._packet; if (pkt.size() != 0) { unsigned offset = reusableTemporarySpace.Write(context, pkt.AsIteratorRange()); if (offset != ~0u) { assert(pkt.size() >= uniformBuffer._blockSize); // the provided buffer must be large enough, or we can get GPU crashes on IOS auto hash = pkt.GetHash(); bool redundantSet = false; if (hash != 0 && context.GetCapturedStates() && s_doRedundantUniformSetReduction) { redundantSet = capturedState._boundContents == hash && capturedState._deviceContextCaptureGUID == context.GetCapturedStates()->_captureGUID; capturedState._boundContents = hash; capturedState._deviceContextCaptureGUID = context.GetCapturedStates()->_captureGUID; } if (!redundantSet) { glBindBufferRange( GL_UNIFORM_BUFFER, uniformBuffer._uniformBlockIdx, // mapped 1:1 with uniform buffer binding points reusableTemporarySpace.GetBuffer().GetUnderlying()->AsRawGLHandle(), offset, pkt.size()); capturedState._boundBuffer = 0; } else { s_redundantUniformSetAccumulator += (unsigned)pkt.size(); } } else { Log(Error) << "Allocation failed on dynamic CB buffer. Cannot write uniform values." << std::endl; } } else { assert(((IResource*)cbv._prebuiltBuffer)->QueryInterface(typeid(Resource).hash_code())); auto* res = checked_cast<const Resource*>(cbv._prebuiltBuffer); if (!res->GetConstantBuffer().empty()) { // note -- we don't do redundant change checking in this case. The wrapping // behaviour in the DynamicBuffer class makes it more difficult -- because // we can overwrite the part of the buffer that was previously bound and // thereby mark some updates as incorrectly redundant. auto data = res->GetConstantBuffer(); if (cbv._prebuiltRangeBegin != 0 || cbv._prebuiltRangeEnd != 0) { auto base = data; data.first = std::min(base.second, PtrAdd(base.first, cbv._prebuiltRangeBegin)); data.second = std::min(base.second, PtrAdd(base.first, cbv._prebuiltRangeEnd)); } unsigned offset = reusableTemporarySpace.Write(context, data); assert(data.size() >= uniformBuffer._blockSize); // the provided buffer must be large enough, or we can get GPU crashes on IOS glBindBufferRange( GL_UNIFORM_BUFFER, uniformBuffer._uniformBlockIdx, // mapped 1:1 with uniform buffer binding points reusableTemporarySpace.GetBuffer().GetUnderlying()->AsRawGLHandle(), offset, data.size()); capturedState._boundBuffer = 0; capturedState._boundContents = 0; } else { auto glHandle = res->GetBuffer()->AsRawGLHandle(); bool isRedundant = false; if (context.GetCapturedStates()) { isRedundant = capturedState._boundBuffer == glHandle && capturedState._deviceContextCaptureGUID == context.GetCapturedStates()->_captureGUID && capturedState._rangeBegin == cbv._prebuiltRangeBegin && capturedState._rangeEnd == cbv._prebuiltRangeEnd; if (!isRedundant) { capturedState._boundBuffer = res->GetBuffer()->AsRawGLHandle(); capturedState._deviceContextCaptureGUID = context.GetCapturedStates()->_captureGUID; capturedState._rangeBegin = cbv._prebuiltRangeBegin; capturedState._rangeEnd = cbv._prebuiltRangeEnd; capturedState._boundContents = 0; } } if (!isRedundant) { if (cbv._prebuiltRangeBegin != 0 || cbv._prebuiltRangeEnd != 0) { assert((cbv._prebuiltRangeEnd-cbv._prebuiltRangeBegin) >= uniformBuffer._blockSize); // the provided buffer must be large enough, or we can get GPU crashes on IOS glBindBufferRange( GL_UNIFORM_BUFFER, uniformBuffer._uniformBlockIdx, glHandle, cbv._prebuiltRangeBegin, cbv._prebuiltRangeEnd-cbv._prebuiltRangeBegin); } else { assert(res->GetDesc()._linearBufferDesc._sizeInBytes >= uniformBuffer._blockSize); // the provided buffer must be large enough, or we can get GPU crashes on IOS glBindBufferBase(GL_UNIFORM_BUFFER, uniformBuffer._uniformBlockIdx, glHandle); } } } } } if (streamIdx == 0) { for (const auto&block:_unboundUniformBuffers) { assert(block._uniformBlockIdx < _capturedState->_uniformBuffers.size()); auto& capturedState = _capturedState->_uniformBuffers[block._uniformBlockIdx]; std::vector<uint8_t> tempBuffer(block._blockSize, 0); unsigned offset = reusableTemporarySpace.Write(context, MakeIteratorRange(tempBuffer)); if (offset != ~0u) { glBindBufferRange( GL_UNIFORM_BUFFER, block._uniformBlockIdx, // mapped 1:1 with uniform buffer binding points reusableTemporarySpace.GetBuffer().GetUnderlying()->AsRawGLHandle(), offset, tempBuffer.size()); capturedState._boundBuffer = 0; } else { Log(Error) << "Allocation failed on dynamic CB buffer. Cannot write uniform values." << std::endl; } } } } #endif // Commit changes to texture uniforms // This must be done separately to the texture binding, because when using array uniforms, // a single uniform set operation can be used for multiple texture bindings if (streamIdx == 0) { if (!_textureAssignmentCommands._commands.empty()) { Bind(context, _textureAssignmentCommands, MakeIteratorRange(_textureAssignmentByteData)); if (_standInTexture2DUnit != ~0u) { if (capture) { if (capture->_activeTextureIndex != _standInTexture2DUnit) { glActiveTexture(GL_TEXTURE0 + _standInTexture2DUnit); capture->_activeTextureIndex = _standInTexture2DUnit; } glBindTexture(GL_TEXTURE_2D, GetObjectFactory(context).StandIn2DTexture()); SamplerState().Apply(*capture, _standInTexture2DUnit, GL_TEXTURE_2D, nullptr, false); } else { glActiveTexture(GL_TEXTURE0 + _standInTexture2DUnit); glBindTexture(GL_TEXTURE_2D, GetObjectFactory(context).StandIn2DTexture()); SamplerState().Apply(_standInTexture2DUnit, GL_TEXTURE_2D, false); } } if (_standInTextureCubeUnit != ~0u) { if (capture) { if (capture->_activeTextureIndex != _standInTextureCubeUnit) { glActiveTexture(GL_TEXTURE0 + _standInTextureCubeUnit); capture->_activeTextureIndex = _standInTextureCubeUnit; } glBindTexture(GL_TEXTURE_CUBE_MAP, GetObjectFactory(context).StandInCubeTexture()); SamplerState().Apply(*capture, _standInTextureCubeUnit, GL_TEXTURE_2D, nullptr, false); } else { glActiveTexture(GL_TEXTURE0 + _standInTextureCubeUnit); glBindTexture(GL_TEXTURE_CUBE_MAP, GetObjectFactory(context).StandInCubeTexture()); SamplerState().Apply(_standInTextureCubeUnit, GL_TEXTURE_CUBE_MAP, false); } } } } CheckGLError("Apply BoundUniforms"); } static GLenum DimensionalityForUniformType(GLenum uniformType) { switch (uniformType) { case GL_SAMPLER_2D: case GL_SAMPLER_2D_SHADOW: case GL_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D: return GL_TEXTURE_2D; case GL_SAMPLER_CUBE: case GL_SAMPLER_CUBE_SHADOW: case GL_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE: return GL_TEXTURE_CUBE_MAP; // array types: // case GL_SAMPLER_2D_ARRAY: // case GL_SAMPLER_2D_ARRAY_SHADOW: // case GL_INT_SAMPLER_2D_ARRAY: // case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: // 3D texture types: case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: default: return GL_NONE; } } //////////////////////////////////////////////////////////////////////////////////////////////////// static bool HasCBBinding(IteratorRange<const UniformsStreamInterface**> interfaces, uint64_t hash) { for (auto interf:interfaces) { auto i = std::find_if( interf->_cbBindings.begin(), interf->_cbBindings.end(), [hash](const UniformsStreamInterface::RetainedCBBinding& b) { return b._hashName == hash; }); if (i!=interf->_cbBindings.end()) return true; } return false; } static bool HasSRVBinding(IteratorRange<const UniformsStreamInterface**> interfaces, uint64_t hash) { for (auto interf:interfaces) { auto i = std::find(interf->_srvBindings.begin(), interf->_srvBindings.end(), hash); if (i!=interf->_srvBindings.end()) return true; } return false; } static std::string AdaptNameForIndex(const std::string& name, unsigned elementIdx, unsigned uniformElementCount) { // If the input uniform name already has [], then modify the string to insert the particular // element idx we're actually interested in... // Otherwise we will just append the indexor to the end of the string name if (name.size() >= 2 && name[name.size()-1] == ']') { auto i = name.begin() + (name.size()-2); while (i > name.begin() && *i >= '0' && *i <= '9') --i; if (*i == '[') return std::string(name.begin(), i+1) + std::to_string(elementIdx) + "]"; } if (elementIdx != 0 || uniformElementCount > 1) return name + "[" + std::to_string(elementIdx) + "]"; return name; } //////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(_DEBUG) static const std::string s_memberNamedDisabled = "<<introspection named disabled>>"; static void ValidateCBElements( IteratorRange<const ConstantBufferElementDesc*> elements, const ShaderIntrospection::UniformBlock& block) { // Every member of the struct must be in the "elements", and offsets and types must match for (const auto& member:block._uniforms) { std::string memberName; #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) memberName = member._name; #else memberName = s_memberNamedDisabled; #endif auto hashName = member._bindingName; auto i = std::find_if( elements.begin(), elements.end(), [hashName](const ConstantBufferElementDesc& t) { return t._semanticHash == hashName; }); if (i == elements.end()) Throw(::Exceptions::BasicLabel("Missing CB binding for element name (%s)", memberName.c_str())); if (i->_offset != member._location) Throw(::Exceptions::BasicLabel("CB element offset is incorrect for member (%s). It's (%i) in the shader, but (%i) in the binding provided", memberName.c_str(), member._location, i->_offset)); if (std::max(1u, i->_arrayElementCount) != std::max(1u, unsigned(member._elementCount))) Throw(::Exceptions::BasicLabel("CB element array element count is incorrect for member (%s). It's (%i) in the shader, but (%i) in the binding provided", memberName.c_str(), member._elementCount, i->_arrayElementCount)); auto f = AsFormat(GLUniformTypeAsTypeDesc(member._type)); if (i->_nativeFormat != f) Throw(::Exceptions::BasicLabel("CB element type is incorrect for member (%s). It's (%s) in the shader, but (%s) in the binding provided", memberName.c_str(), AsString(f), AsString(i->_nativeFormat))); } } #endif //////////////////////////////////////////////////////////////////////////////////////////////////// BoundUniforms::BoundUniforms( const ShaderProgram& shader, const PipelineLayoutConfig& pipelineLayout, const UniformsStreamInterface& interface0, const UniformsStreamInterface& interface1, const UniformsStreamInterface& interface2, const UniformsStreamInterface& interface3) { for (auto&v:_boundUniformBufferSlots) v = 0u; for (auto&v:_boundResourceSlots) v = 0u; auto introspection = ShaderIntrospection(shader); _capturedState = shader._capturedState; if (!_capturedState) { _capturedState = shader._capturedState = std::make_shared<ShaderProgramCapturedState>(introspection); } unsigned textureUnitAccumulator = 0; struct UniformSet { int _location; unsigned _index, _value; GLenum _type; int _elementCount; }; std::vector<UniformSet> srvUniformSets; #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) std::set<uint64_t> boundGlobalUniforms; std::set<uint64_t> boundUniformStructs; #endif const UniformsStreamInterface* inputInterface[] = { &interface0, &interface1, &interface2, &interface3 }; auto streamCount = (unsigned)dimof(inputInterface); // We bind the 4 streams with reversed order, so that material textures can be bound before global textures // (ex. shadowmap). This can help avoid the situation where shadowmap end up being bound at texture unit 0, // which is prone to GL errors caused by shader bugs (one example is when a shader mistakenly sample from // unbound texture samplers, which has default binding 0, and shadowmap happens to be bound at texture unit 0 // but with a comparison sampler). for (int s=streamCount-1; s>=0; --s) { const auto& interf = *inputInterface[s]; for (unsigned slot=0; slot<interf._cbBindings.size(); ++slot) { const auto& binding = interf._cbBindings[slot]; // Ensure it's not shadowed by bindings from streams with higher index // Note that we don't enforce this for bindings to global uniforms. This allows the client to // provide multiple bindings for global, wherein each only binds a subset of all of the global uniforms if (binding._hashName != 0) { if (HasCBBinding(MakeIteratorRange(&inputInterface[s+1], &inputInterface[dimof(inputInterface)]), binding._hashName)) continue; #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) assert(boundUniformStructs.find(binding._hashName) == boundUniformStructs.end()); boundUniformStructs.insert(binding._hashName); #endif } // Try binding either as a command group or as a uniform block if (!binding._elements.empty()) { auto cmdGroup = introspection.MakeBinding(binding._hashName, MakeIteratorRange(binding._elements)); if (!cmdGroup._commands.empty()) { _cbs.emplace_back(CB{(unsigned)s, slot, std::move(cmdGroup), _capturedState->GetCBIndex(binding._hashName) #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) , cmdGroup._name #endif }); _boundUniformBufferSlots[s] |= (1ull << uint64_t(slot)); } } auto block = introspection.FindUniformBlock(binding._hashName); if (block._blockIdx != ~0u) { _uniformBuffer.emplace_back(UniformBuffer{ (unsigned)s, slot, block._blockIdx, block._blockSize #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) , block._name #endif }); _boundUniformBufferSlots[s] |= (1ull << uint64_t(slot)); #if defined(_DEBUG) ValidateCBElements(MakeIteratorRange(binding._elements), block); #endif } } for (unsigned slot=0; slot<interf._srvBindings.size(); ++slot) { auto binding = interf._srvBindings[slot]; if (!binding) continue; // ensure it's not shadowed by bindings from streams with higher index if (HasSRVBinding(MakeIteratorRange(&inputInterface[s+1], &inputInterface[dimof(inputInterface)]), binding)) continue; auto uniform = introspection.FindUniform(binding); if (uniform._elementCount != 0) { #if defined(_DEBUG) boundGlobalUniforms.insert(uniform._bindingName); #endif // assign a texture unit for this binding auto textureUnit = pipelineLayout.GetFixedTextureUnit(binding); if (textureUnit == ~0u) { textureUnit = pipelineLayout.GetFlexibleTextureUnit(textureUnitAccumulator); textureUnitAccumulator++; } auto dim = DimensionalityForUniformType(uniform._type); auto elementIndex = unsigned(binding - uniform._bindingName); assert(dim != GL_NONE); _srvs.emplace_back(SRV{(unsigned)s, slot, textureUnit, dim #if defined(_DEBUG) , AdaptNameForIndex(uniform._name, elementIndex, uniform._elementCount) #endif }); #if defined(_DEBUG) && defined(EXTRA_INPUT_LAYOUT_LOGGING) Log(Verbose) << "Selecting texunit (" << textureUnit << ") for uniform " << AdaptNameForIndex(uniform._name, elementIndex, uniform._elementCount) << " in stream " << s << ", slot " << slot << std::endl; #endif // Record the command to set the uniform. Note that this // is made a little more complicated due to array uniforms. assert((binding - uniform._bindingName) < uniform._elementCount); srvUniformSets.push_back({uniform._location, elementIndex, textureUnit, uniform._type, uniform._elementCount}); _boundResourceSlots[s] |= (1ull << uint64_t(slot)); } } } auto globalsStruct = introspection.FindStruct(0); #if defined(_DEBUG) for (const auto&u:globalsStruct._uniforms) { if (boundGlobalUniforms.find(u._bindingName) == boundGlobalUniforms.end()) { Log(Verbose) << "Didn't get binding for global uniform (" << u._name << ") in BoundUniforms constructor" << std::endl; _unboundUniforms.push_back(u); /*if (DimensionalityForUniformType(u._type) != GL_NONE) { auto textureUnit = pipelineLayout.GetFlexibleTextureUnit(textureUnitAccumulator); textureUnitAccumulator++; srvUniformSets.push_back({u._location, 0, textureUnit, u._type, u._elementCount}); }*/ } } for (auto s:introspection.GetStructs()) { if (s.first != 0 && boundUniformStructs.find(s.first) == boundUniformStructs.end()) { Log(Verbose) << "Didn't get binding for uniform struct (" << s.second._name << ") in BoundUniforms constructor" << std::endl; _unboundUniforms.insert(_unboundUniforms.end(), s.second._uniforms.begin(), s.second._uniforms.end()); } } #endif // Ensure all sampler uniforms got some assignment. If they don't have a valid assignment, // we should set them to a dummy resource. This helps avoid problems related to texture // bindings (maybe from previous draw calls) getting bound to incorrect sampler types // (which triggers a GL error and skips the draw) for (const auto&u:globalsStruct._uniforms) { auto dim = DimensionalityForUniformType(u._type); bool isSampler = dim != GL_NONE; if (!isSampler) continue; for (unsigned elementIndex=0; elementIndex<u._elementCount; ++elementIndex) { auto existing = std::find_if( srvUniformSets.begin(), srvUniformSets.end(), [&u, elementIndex](const UniformSet& us) { return us._location == u._location && us._index == elementIndex; }); if (existing != srvUniformSets.end()) continue; // If we got here, there is no existing binding. We must bind a dummy texture here unsigned textureUnit = 0; if (dim == GL_TEXTURE_CUBE_MAP) { if (_standInTextureCubeUnit == ~0u) { _standInTextureCubeUnit = pipelineLayout.GetFlexibleTextureUnit(textureUnitAccumulator); textureUnitAccumulator++; } textureUnit = _standInTextureCubeUnit; } else { // assuming 2D, 3D textures not supported if (_standInTexture2DUnit == ~0u) { _standInTexture2DUnit = pipelineLayout.GetFlexibleTextureUnit(textureUnitAccumulator); textureUnitAccumulator++; } textureUnit = _standInTexture2DUnit; } srvUniformSets.push_back({u._location, elementIndex, textureUnit, u._type, u._elementCount}); } } for (const auto&uniformBlock:introspection.GetUniformBlocks()) { auto blockIdx = uniformBlock.second._blockIdx; auto existing = std::find_if( _uniformBuffer.begin(), _uniformBuffer.end(), [blockIdx](const UniformBuffer& ub) { return ub._uniformBlockIdx == blockIdx; }); if (existing != _uniformBuffer.end()) continue; _unboundUniformBuffers.push_back(UnboundUniformBuffer{blockIdx, uniformBlock.second._blockSize #if defined(EXTRA_INPUT_LAYOUT_PROPERTIES) , uniformBlock.second._name #endif }); } // sort the uniform sets to collect up sequential sets on the same uniforms std::sort( srvUniformSets.begin(), srvUniformSets.end(), [](const UniformSet& lhs, const UniformSet& rhs) { if (lhs._location < rhs._location) return true; if (lhs._location > rhs._location) return false; return lhs._index < rhs._index; }); #if defined(_DEBUG) // ensure that we are not writing to the same uniform more than once if (!srvUniformSets.empty()) { for (auto i=srvUniformSets.begin(); (i+1)!=srvUniformSets.end(); ++i) { assert(i->_location != (i+1)->_location || i->_index != (i+1)->_index); } } #endif // Now generate the set commands that will assign the uniforms as required for (auto i = srvUniformSets.begin(); i!=srvUniformSets.end();) { auto i2 = i+1; while (i2 != srvUniformSets.end() && i2->_location == i->_location) { ++i2; }; // unsigned maxIndex = (i2-1)->_index; unsigned elementCount = i->_elementCount; auto dataOffsetStart = _textureAssignmentByteData.size(); _textureAssignmentByteData.resize(dataOffsetStart+sizeof(GLuint)*elementCount, 0u); GLuint* dst = (GLuint*)&_textureAssignmentByteData[dataOffsetStart]; for (auto q=i; q<i2; ++q) { assert(q->_index < elementCount); assert(q->_type == i->_type); dst[q->_index] = q->_value; } _textureAssignmentCommands._commands.push_back( SetUniformCommandGroup::SetCommand{i->_location, i->_type, elementCount, dataOffsetStart}); i = i2; } CheckGLError("Construct BoundUniforms"); #if defined(_DEBUG) && defined(EXTRA_INPUT_LAYOUT_LOGGING) { Log(Verbose) << "Building bound uniforms for program: " << shader << std::endl; for (auto c=_cbs.begin(); c!=_cbs.end(); ++c) { Log(Verbose) << "CB[" << std::distance(_cbs.begin(), c) << "]: " << c->_name << " (" << c->_stream << ", " << c->_slot << "):" << std::endl; Log(Verbose) << c->_commandGroup << std::endl; } Log(Verbose) << "Texture assignment:" << std::endl; Log(Verbose) << _textureAssignmentCommands << std::endl; } #endif } BoundUniforms::~BoundUniforms() {} BoundUniforms::BoundUniforms() { for (unsigned c=0; c<dimof(_boundUniformBufferSlots); ++c) { _boundUniformBufferSlots[c] = 0ull; _boundResourceSlots[c] = 0ull; } } BoundUniforms::BoundUniforms(BoundUniforms&& moveFrom) never_throws : _cbs(std::move(moveFrom._cbs)) , _srvs(std::move(moveFrom._srvs)) , _uniformBuffer(std::move(moveFrom._uniformBuffer)) , _unboundUniformBuffers(std::move(moveFrom._unboundUniformBuffers)) , _textureAssignmentCommands(std::move(moveFrom._textureAssignmentCommands)) , _textureAssignmentByteData(std::move(moveFrom._textureAssignmentByteData)) #if defined(_DEBUG) , _unboundUniforms(std::move(moveFrom._unboundUniforms)) #endif , _capturedState(std::move(moveFrom._capturedState)) , _standInTexture2DUnit(moveFrom._standInTexture2DUnit) , _standInTextureCubeUnit(moveFrom._standInTextureCubeUnit) { for (unsigned c=0; c<dimof(_boundUniformBufferSlots); ++c) { _boundUniformBufferSlots[c] = moveFrom._boundUniformBufferSlots[c]; _boundResourceSlots[c] = moveFrom._boundResourceSlots[c]; moveFrom._boundUniformBufferSlots[c] = 0ull; moveFrom._boundResourceSlots[c] = 0ull; } } BoundUniforms& BoundUniforms::operator=(BoundUniforms&& moveFrom) never_throws { _cbs = std::move(moveFrom._cbs); _srvs = std::move(moveFrom._srvs); _uniformBuffer = std::move(moveFrom._uniformBuffer); _unboundUniformBuffers = std::move(moveFrom._unboundUniformBuffers); _textureAssignmentCommands = std::move(moveFrom._textureAssignmentCommands); _textureAssignmentByteData = std::move(moveFrom._textureAssignmentByteData); for (unsigned c=0; c<dimof(_boundUniformBufferSlots); ++c) { _boundUniformBufferSlots[c] = moveFrom._boundUniformBufferSlots[c]; _boundResourceSlots[c] = moveFrom._boundResourceSlots[c]; moveFrom._boundUniformBufferSlots[c] = 0ull; moveFrom._boundResourceSlots[c] = 0ull; } #if defined(_DEBUG) _unboundUniforms = std::move(moveFrom._unboundUniforms); #endif _standInTexture2DUnit = moveFrom._standInTexture2DUnit; _standInTextureCubeUnit = moveFrom._standInTextureCubeUnit; _capturedState = std::move(moveFrom._capturedState); return *this; } }}
48.417945
306
0.561335
[ "object", "vector", "model", "3d" ]
8dcbd55e08085d442674fb620a8e251edd6f6e4d
781
hpp
C++
libs/core/include/fcppt/optional/is_object.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/optional/is_object.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/optional/is_object.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // 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 FCPPT_OPTIONAL_IS_OBJECT_HPP_INCLUDED #define FCPPT_OPTIONAL_IS_OBJECT_HPP_INCLUDED #include <fcppt/optional/object_fwd.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace optional { /** \brief Checks if a given type is an #fcppt::optional::object. \ingroup fcpptoptional */ template< typename T > struct is_object : std::false_type { }; template< typename Type > struct is_object< fcppt::optional::object< Type > > : std::true_type { }; } } #endif
15.019231
61
0.731114
[ "object" ]
8dceef16e62de72ec733969c5efa798f4abe6e8a
1,130
cpp
C++
dataset/test/modification/1480_rename/14/transformation_1.cpp
Karina5005/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
3
2022-02-15T00:29:39.000Z
2022-03-15T08:36:44.000Z
dataset/test/modification/1480_rename/14/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
dataset/test/modification/1480_rename/14/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
/** * Author: Fau * Time: 2021-12-31 23:22 **/ #include <bits/stdc++.h> #define rep(i, n) for (int i = 1; i <= (n); ++i) using namespace std; typedef long long ll; const int t = 1E5 + 10; int r_ah[t]; vector<int> i[t]; int main() { #ifdef CODE_Fau Fau_Begin #endif //--------------------------------------------------CODE BEGIN-------------------------------------------------- int e_y; cin >> e_y; rep(i, n) scanf("%d", &r_ah[i]), i[r_ah[i]].push_back(i); rep(i, n) i[i].push_back(0x3f3f3f3f); i[0].push_back(0x3f3f3f3f); int qap_qyc = e_y; int vea = 0, xh_wr = 0; rep(i, n) { if (r_ah[i] == vea and r_ah[i] == xh_wr) vea = r_ah[i], qap_qyc--; else if (r_ah[i] == vea) xh_wr = r_ah[i]; else if (r_ah[i] == xh_wr) vea = r_ah[i]; else { int ae = *lower_bound(i[vea].begin(), i[vea].end(), i); int jba_k = *lower_bound(i[xh_wr].begin(), i[xh_wr].end(), i); auto& i = ae < jba_k ? vea : xh_wr; i = r_ah[i]; } } cout << qap_qyc << endl; //---------------------------------------------------CODE END--------------------------------------------------- #ifdef CODE_Fau Fau_End #endif return 0; }
24.042553
112
0.476106
[ "vector" ]
8dd033c5544be87c54132f450b85f93d02c77d1a
1,244
cpp
C++
geeksforgeeks/product-of-primes5328/main.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
geeksforgeeks/product-of-primes5328/main.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
geeksforgeeks/product-of-primes5328/main.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
vector<long long> prime; class Solution{ public: long long primeProduct(long long L, long long R){ vector<bool> smaller(sqrt(R), true); for (long long i{2}; i <= sqrt(R); ++i) { if (smaller[i]) { prime.push_back(i); for (long long j{i * i}; j <= sqrt(R); j += i) { smaller[j] = false; } } } vector<bool> isPrime(R - L + 1, true); for (long long divisor: prime) { long long start{L / divisor * divisor}; if (start < L) { start += divisor; } if (start == divisor) { start += divisor; } //std::cout << "c " << start << " " << divisor << "\n"; for (long long i{start}; i <= R; i += divisor) { //std::cout << i << " " << start << "\n"; isPrime[i - L] = false; } } long long ans{1}; for (long long i{L}; i <= R; ++i) { if (isPrime[i - L] == true) { //std::cout << ans <<" " << i <<"\n"; ans *= i; ans %= 1000000007; } } return ans; } };
30.341463
67
0.369775
[ "vector" ]
8dd160eef71128c5ed5d066c6cded2c52dc69c98
222
cpp
C++
cloud-disk/zmq_server.cpp
G-Club/c-cpp
e89f8efae357fc8349d0d66f1aef703a6a287bef
[ "Apache-2.0" ]
null
null
null
cloud-disk/zmq_server.cpp
G-Club/c-cpp
e89f8efae357fc8349d0d66f1aef703a6a287bef
[ "Apache-2.0" ]
1
2017-02-07T00:49:21.000Z
2017-02-16T00:55:28.000Z
cloud-disk/zmq_server.cpp
G-Club/c-cpp
e89f8efae357fc8349d0d66f1aef703a6a287bef
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <zmq.h> #include <vector> #include <zmq.h> using namespace std; int main(int argc,char *argv[]) { std::cout<<"hello world"<<std::endl; return 0; }
13.875
44
0.599099
[ "vector" ]
8de4d8b0d2c0591a53e6e7985897906cc22eed2c
497
cpp
C++
test/GridBFS.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
null
null
null
test/GridBFS.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
6
2021-01-05T07:39:05.000Z
2021-01-05T07:44:31.000Z
test/GridBFS.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/problems/0558" #include "./../Utility/Point.cpp" #include "./../search/GridBFS.cpp" #include <iostream> #include <vector> #include <string> using namespace std; int main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); int h, w, n; cin >> h >> w >> n; vector<string> s(h); for (auto& i : s) cin >> i; int ans = 0; for (int i = 0; i < n; ++i) { ans += GridBFS(s, i == 0 ? 'S' : '0' + i, '1' + i, 'X'); } cout << ans << '\n'; }
21.608696
64
0.573441
[ "vector" ]
8debedfd64062e4d38914d240aa5ea238fe7a7af
1,891
cpp
C++
BasicCPP/C2-1/C2-1/C2-1.cpp
Angorithm4/AdvancedCPP
e1b3c844efaa2b179c043cfbd9b910b153fbd3d1
[ "MIT" ]
null
null
null
BasicCPP/C2-1/C2-1/C2-1.cpp
Angorithm4/AdvancedCPP
e1b3c844efaa2b179c043cfbd9b910b153fbd3d1
[ "MIT" ]
null
null
null
BasicCPP/C2-1/C2-1/C2-1.cpp
Angorithm4/AdvancedCPP
e1b3c844efaa2b179c043cfbd9b910b153fbd3d1
[ "MIT" ]
null
null
null
// C2-1.cpp : This file contains the 'main' function. Program execution begins and ends there. // 20201121 Jiawei Wang #include <iostream> int main() { std::cout << "Hello World!\n"; // types transformation bool b = 42; std::cout << "b = " << b << std::endl; // output: b = 1 bool t = true; int i = t; std::cout << "i = " << i << std::endl; // output: i = 1 int j = 3.14; std::cout << "j = " << j << std::endl; // output: j = 3 double p = j; std::cout << "p = " << p << std::endl; // output: p = 3.0 signed char c = 256; std::cout << "c = " << c << std::endl; // c is undefined unsigned u = 10; int in = -42; std::cout << u + in << std::endl; // output: 4294967264 (2^32 - 42 + 10) // when oprations between int and unsigned(int), int -> unsigned unsigned u1 = 42, u2 = 10; std::cout << u2 - u1 << std::endl; // output: 4294967264 // u2 + (-u1) which means we transform unsigned number to an integer -> -u1 = 2^32 - 42 = 4294967254 std::cout << "\7"; // Bell! std::cout << L'a' << u8"hi!" << 42ULL << 3e-2F << std::endl; // output: 97hi!420.03 std::cout << 'a' << " " << L'a' << " " << "a" << " " << L"a" << std::endl; // output: a 97 a 00349C1C return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
36.365385
135
0.584876
[ "transform" ]
8dec34020fee2aa17ef0fa058fb6036c261ddb32
6,168
cpp
C++
test/meta_mnemonic.cpp
fengjixuchui/xbyak_aarch64
7427c0c3baf5a13807c50c07acfe2f2c27f311bd
[ "Apache-2.0" ]
134
2019-12-09T22:40:27.000Z
2022-03-12T09:07:52.000Z
test/meta_mnemonic.cpp
fengjixuchui/xbyak_aarch64
7427c0c3baf5a13807c50c07acfe2f2c27f311bd
[ "Apache-2.0" ]
29
2019-12-13T13:27:07.000Z
2022-03-21T23:31:38.000Z
test/meta_mnemonic.cpp
fengjixuchui/xbyak_aarch64
7427c0c3baf5a13807c50c07acfe2f2c27f311bd
[ "Apache-2.0" ]
29
2019-12-10T03:13:50.000Z
2022-03-12T09:06:19.000Z
/******************************************************************************* * Copyright 2019-2020 FUJITSU LIMITED * * 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. *******************************************************************************/ // clang-format off #define TEST_NUM 1 #include "../xbyak_aarch64/xbyak_aarch64.h" #include <cstring> using namespace Xbyak_aarch64; class GeneratorAdd : public CodeGenerator { template <typename T> void genAddFuncCore(const T imm) { add_imm(x0, x0, imm, x9, x10); // x9, x10 are temporary registers. ret(); } public: template <typename T> GeneratorAdd(T i) { genAddFuncCore(i); } }; class GeneratorSub : public CodeGenerator { template <typename T> void genSubFuncCore(const T imm) { sub_imm(x0, x0, imm, x9, x10); // x9, x10 are temporary registers. ret(); } public: template <typename T> GeneratorSub(T i) { genSubFuncCore(i); } }; template <typename T> void test_add(std::vector<T> &v) { for (const auto &e : v) { GeneratorAdd s(e); s.ready(); uint64_t (*f)(T a) = (uint64_t(*)(T a))s.getCode(); uint64_t retVal = f(TEST_NUM); if (typeid(e) == typeid(int32_t) || typeid(e) == typeid(int64_t)) { int64_t tmp = TEST_NUM + static_cast<int64_t>(e); // std::cout << std::hex << "e :" << e << std::endl; // std::cout << std::hex << "tmp:" << tmp << std::endl; // std::cout << std::hex << "ret:" << retVal << std::endl; std::cout << "add:" << TEST_NUM << " + " << e << " = " << static_cast<int64_t>(retVal) << std::endl; assert(std::memcmp(&retVal, &tmp, sizeof(uint64_t)) == 0); } else { uint64_t tmp = TEST_NUM + static_cast<uint64_t>(e); // std::cout << std::hex << "e :" << e << std::endl; // std::cout << std::hex << "tmp:" << tmp << std::endl; // std::cout << std::hex << "ret:" << retVal << std::endl; std::cout << "add:" << TEST_NUM << " + " << e << " = " << static_cast<int64_t>(retVal) << std::endl; assert(std::memcmp(&retVal, &tmp, sizeof(uint64_t)) == 0); } } } template <typename T> void test_sub(std::vector<T> &v) { for (const auto &e : v) { GeneratorSub s(e); s.ready(); uint64_t (*f)(T a) = (uint64_t(*)(T a))s.getCode(); uint64_t retVal = f(TEST_NUM); if (typeid(e) == typeid(int32_t) || typeid(e) == typeid(int64_t)) { int64_t tmp = TEST_NUM - static_cast<int64_t>(e); // std::cout << std::hex << "e :" << e << std::endl; // std::cout << std::hex << "tmp:" << tmp << std::endl; // std::cout << std::hex << "ret:" << retVal << std::endl; std::cout << "sub:" << std::hex << TEST_NUM << " - " << e << " = " << static_cast<int64_t>(retVal) << std::endl; assert(std::memcmp(&retVal, &tmp, sizeof(uint64_t)) == 0); } else { uint64_t tmp = TEST_NUM - static_cast<uint64_t>(e); // std::cout << std::hex << "e :" << e << std::endl; // std::cout << std::hex << "tmp:" << tmp << std::endl; // std::cout << std::hex << "ret:" << retVal << std::endl; std::cout << "sub:" << std::hex << TEST_NUM << " - " << e << " = " << static_cast<int64_t>(retVal) << std::endl; assert(std::memcmp(&retVal, &tmp, sizeof(uint64_t)) == 0); } } } int main() { std::vector<int32_t> v_int32 = {std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min() + 1, -2048, -2047, -2046, -1, 0, 1, 2046, 2047, 2048, std::numeric_limits<int32_t>::max() - 1, std::numeric_limits<int32_t>::max()}; std::vector<uint32_t> v_uint32 = {0, 1, 2046, 2047, 2048, 2049, std::numeric_limits<uint32_t>::max() - 1, std::numeric_limits<uint32_t>::max()}; std::vector<int64_t> v_int64 = {std::numeric_limits<int64_t>::min(), std::numeric_limits<int64_t>::min() + 1, -2048, -2047, -2046, -1, 0, 1, 2046, 2047, 2048, std::numeric_limits<int64_t>::max() - 1, std::numeric_limits<int64_t>::max()}; std::vector<uint64_t> v_uint64_t = {0, 1, 2046, 2047, 2048, 2049, std::numeric_limits<uint64_t>::max() - 1, std::numeric_limits<uint64_t>::max()}; test_add(v_int32); test_add(v_uint32); test_add(v_int64); test_add(v_uint64_t); test_sub(v_int32); test_sub(v_uint32); test_sub(v_int64); test_sub(v_uint64_t); return 0; }
38.074074
81
0.445363
[ "vector" ]
8dfe197fc84debc260773cb4d8b9c918d5b6f575
8,153
cpp
C++
RobWork/gtest/proximity/ProximityStrategyTest.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/gtest/proximity/ProximityStrategyTest.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/gtest/proximity/ProximityStrategyTest.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2017 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 <rw/core/Exception.hpp> #include <rw/geometry/Geometry.hpp> #include <rw/geometry/Sphere.hpp> #include <rw/kinematics/MovableFrame.hpp> #include <rw/kinematics/StateStructure.hpp> #include <rw/models/RigidObject.hpp> #include <rw/proximity/ProximityStrategy.hpp> #include <rw/core/Ptr.hpp> #include <gtest/gtest.h> using rw::core::ownedPtr; using namespace rw::geometry; using namespace rw::kinematics; using namespace rw::models; using namespace rw::proximity; namespace { class ProximityStrategyTest : public ::testing::TestWithParam< std::string > { protected: void SetUp () { strategy = ProximityStrategy::Factory::makeStrategy (GetParam ()); ASSERT_FALSE (strategy.isNull ()); } ProximityStrategy::Ptr strategy; }; std::vector< std::string > strategies = ProximityStrategy::Factory::getStrategies (); } // namespace TEST (Factory, ProximityStrategy) { EXPECT_GT (strategies.size (), 0u); for (std::size_t i = 0; i < strategies.size (); i++) { EXPECT_TRUE (ProximityStrategy::Factory::hasStrategy (strategies[i])); EXPECT_FALSE (ProximityStrategy::Factory::makeStrategy (strategies[i]).isNull ()); } EXPECT_FALSE (ProximityStrategy::Factory::hasStrategy ("dfjgkjfgæah")); EXPECT_TRUE (ProximityStrategy::Factory::makeStrategy ("dfjgkjfgæah").isNull ()); } INSTANTIATE_TEST_CASE_P (ProximityStrategy, ProximityStrategyTest, ::testing::ValuesIn (strategies)); TEST_P (ProximityStrategyTest, Interface) { // Setup test structures std::vector< Frame* > frames; frames.push_back (new MovableFrame ("Frame1")); frames.push_back (new MovableFrame ("Frame2")); frames.push_back (new MovableFrame ("Frame3")); StateStructure sstruct; sstruct.addFrame (frames[0]); sstruct.addFrame (frames[1]); sstruct.addFrame (frames[2]); const Geometry::Ptr geom1A = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo1A")); const Geometry::Ptr geom1B = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo1B")); const Geometry::Ptr geom1C = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo1C")); const Geometry::Ptr geom2A = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo2A")); const Geometry::Ptr geom2B = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo2B")); const Geometry::Ptr geom3A = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo3A")); const Geometry::Ptr geom3B = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo3B")); geom1A->setFrame (frames[0]); geom1B->setFrame (frames[0]); geom1C->setFrame (frames[0]); geom2A->setFrame (frames[1]); geom2B->setFrame (frames[1]); geom3A->setFrame (frames[2]); geom3B->setFrame (frames[2]); std::vector< Geometry::Ptr > objectGeoms; objectGeoms.push_back (geom1B); objectGeoms.push_back (geom1C); objectGeoms.push_back (geom3B); const Object::Ptr object = ownedPtr (new RigidObject (frames, objectGeoms)); // Test interface where ProximityModels are stored internally in the ProximityStrategy. EXPECT_FALSE (strategy->hasModel (frames[0])); strategy->addModel (frames[0], geom1A); EXPECT_TRUE (strategy->hasModel (frames[0])); strategy->clearFrame (frames[0]); EXPECT_FALSE (strategy->hasModel (frames[0])); strategy->addModel (frames[0], *geom1A); strategy->addModel (frames[1], *geom2A); strategy->clearFrames (); EXPECT_FALSE (strategy->hasModel (frames[0])); EXPECT_FALSE (strategy->hasModel (frames[1])); EXPECT_TRUE (strategy->getModel (frames[0]).isNull ()); strategy->addModel (frames[0], *geom1A); EXPECT_FALSE (strategy->getModel (frames[0]).isNull ()); strategy->clearFrames (); strategy->addModel (object); EXPECT_TRUE (strategy->hasModel (frames[0])); EXPECT_FALSE (strategy->hasModel (frames[1])); EXPECT_TRUE (strategy->hasModel (frames[2])); const ProximityModel::Ptr model1 = strategy->getModel (frames[0]); const ProximityModel::Ptr model3 = strategy->getModel (frames[2]); // EXPECT_EQ(frames[0],model1->getFrame()); // EXPECT_EQ(frames[2],model3->getFrame()); ASSERT_NO_THROW (model1->getGeometryIDs ()); ASSERT_EQ (2u, model1->getGeometryIDs ().size ()); ASSERT_EQ (1u, model3->getGeometryIDs ().size ()); EXPECT_EQ ("Geo1B", model1->getGeometryIDs ()[0]); EXPECT_EQ ("Geo1C", model1->getGeometryIDs ()[1]); EXPECT_EQ ("Geo3B", model3->getGeometryIDs ()[0]); EXPECT_EQ (strategy.get (), model1->owner); EXPECT_EQ (strategy.get (), model3->owner); strategy->clearFrames (); // Interface where ProximityModels are stored externally from the ProximityStrategy. const ProximityModel::Ptr modelA = strategy->createModel (); const ProximityModel::Ptr modelB = strategy->createModel (); EXPECT_FALSE (modelA.isNull ()); EXPECT_FALSE (modelB.isNull ()); // Raw access to model modelA->addGeometry (*geom1A); EXPECT_FALSE (strategy->hasModel (frames[0])); modelA->addGeometry (*geom1C); modelA->setFrame (frames[0]); EXPECT_EQ (frames[0], modelA->getFrame ()); ASSERT_EQ (2u, modelA->getGeometryIDs ().size ()); EXPECT_EQ ("Geo1A", modelA->getGeometryIDs ()[0]); EXPECT_EQ ("Geo1C", modelA->getGeometryIDs ()[1]); EXPECT_EQ (strategy.get (), modelA->owner); EXPECT_FALSE (modelA->removeGeometry ("asdasd")); EXPECT_TRUE (modelA->removeGeometry ("Geo1A")); ASSERT_EQ (1u, modelA->getGeometryIDs ().size ()); EXPECT_EQ ("Geo1C", modelA->getGeometryIDs ()[0]); // Proxy methods on strategy strategy->addGeometry (modelB.get (), geom3A); strategy->addGeometry (modelB.get (), *geom3B); EXPECT_FALSE (strategy->hasModel (frames[0])); EXPECT_EQ (NULL, modelB->getFrame ()); ASSERT_EQ (2u, strategy->getGeometryIDs (modelB.get ()).size ()); EXPECT_EQ ("Geo3A", strategy->getGeometryIDs (modelB.get ())[0]); EXPECT_EQ ("Geo3B", strategy->getGeometryIDs (modelB.get ())[1]); EXPECT_EQ (strategy.get (), modelB->owner); EXPECT_FALSE (strategy->removeGeometry (modelB.get (), "asdasd")); EXPECT_TRUE (strategy->removeGeometry (modelB.get (), "Geo3A")); ASSERT_EQ (1u, strategy->getGeometryIDs (modelB.get ()).size ()); EXPECT_EQ ("Geo3B", strategy->getGeometryIDs (modelB.get ())[0]); strategy->destroyModel (modelB.get ()); strategy->clear (); } TEST_P (ProximityStrategyTest, GeometryIDs) { Frame* frame = new MovableFrame ("Frame1"); StateStructure sstruct; sstruct.addFrame (frame); Geometry::Ptr geom1A = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo1")); Geometry::Ptr geom1B = ownedPtr (new Geometry (ownedPtr (new Sphere (1)), "Geo1")); geom1A->setFrame(frame); geom1B->setFrame(frame); strategy->clearFrames(); strategy->addModel (frame, geom1A); bool error_raised = false; try { error_raised = !strategy->addModel (frame, geom1B); } catch (rw::core::Exception& e) { error_raised = true; } //TODO(kalor) find ud af om den skal være false eller true EXPECT_TRUE (error_raised) << "a Geometry with Same ID was added twice with no exception. " << "Neither was a false returned to indicate failure. "; }
42.243523
95
0.668588
[ "geometry", "object", "vector", "model" ]
8dfeab068a005636f4dc90098bffece701e5a01f
1,916
cpp
C++
src/process.cpp
kaipomauli/CppND-System-Monitor
bb6390229a98b92bf78cb9eb271d4d4fad21b747
[ "MIT" ]
null
null
null
src/process.cpp
kaipomauli/CppND-System-Monitor
bb6390229a98b92bf78cb9eb271d4d4fad21b747
[ "MIT" ]
null
null
null
src/process.cpp
kaipomauli/CppND-System-Monitor
bb6390229a98b92bf78cb9eb271d4d4fad21b747
[ "MIT" ]
null
null
null
#include "process.h" using std::string; using std::to_string; using std::vector; int Process::getPid() { return pid_; } // TODO: Return this process's CPU utilization void Process::setCpuUtilization() { unsigned long int utime, stime, cutime, cstime, starttime,TotTime, PrevTotTime, PrevSeconds, Seconds, totald, secsld,Sys_uptime; vector<unsigned long> new_data = LinuxParser::CpuUtil(pid_); Sys_uptime = LinuxParser::UpTime(); utime = new_data[0]; stime = new_data[1]; cutime = new_data[2]; cstime = new_data[3]; starttime = new_data[4]; PrevTotTime = prev_utime + prev_stime + prev_cutime + prev_cstime; TotTime = utime + stime + cutime + cstime; totald = TotTime - PrevTotTime; PrevSeconds = prev_Sys_uptime - prev_starttime; Seconds = Sys_uptime - starttime; secsld = Seconds - PrevSeconds; prev_utime = utime; prev_stime = stime; prev_cutime = cutime; prev_cstime = cstime; prev_starttime = starttime; prev_Sys_uptime = Sys_uptime; float cpuPercentage = secsld > 0 ? float(totald) / float(secsld):float(0.0); util_ = cpuPercentage; } string Process::Command() { return cmd_; } string Process::Ram() { return ram_; } long int Process::UpTime() { return proc_uptime_; } bool Process::operator<(Process& a ) { bool cpuEqu = this->CpuUtilization() == a.CpuUtilization(); float ramThis=0.0; float ram_a=0.0; try { ramThis = std::stof(LinuxParser::trim(this->Ram())); ram_a = std::stof(LinuxParser::trim(a.Ram())); } catch (std::invalid_argument& e) { std::cout << "fault in stof in < operator" << std::endl; } bool ramSmOEqu = ramThis <= ram_a; bool cpuSmaller = this->CpuUtilization() < a.CpuUtilization(); bool finalAns = cpuEqu ? ramSmOEqu : cpuSmaller; return finalAns; }
25.210526
80
0.640919
[ "vector" ]
5c0b76022c2efc8e282dc1f38b347d567449dd6c
1,419
hpp
C++
source/system/Input.hpp
Godlike/Xanthus
f35a5fd8b7aa974f5fcb37bf5bb8df3f2602847d
[ "MIT" ]
null
null
null
source/system/Input.hpp
Godlike/Xanthus
f35a5fd8b7aa974f5fcb37bf5bb8df3f2602847d
[ "MIT" ]
null
null
null
source/system/Input.hpp
Godlike/Xanthus
f35a5fd8b7aa974f5fcb37bf5bb8df3f2602847d
[ "MIT" ]
null
null
null
#ifndef XANTHUS_SYSTEM_INPUT_HPP #define XANTHUS_SYSTEM_INPUT_HPP #include "entity/Entity.hpp" #include <unicorn/system/Window.hpp> #include <unicorn/UnicornRender.hpp> #include <set> namespace xanthus { class WorldTime; namespace assemblage { class Factory; } namespace system { class Intent; class Render; class Time; class Input { public: Input(unicorn::UnicornRender& render , WorldTime& worldTime , Time& timeSystem , Intent& intents , Render& renderSystem , assemblage::Factory& factory ); ~Input(); void Init(); void Update(); private: using Window = unicorn::system::Window; void CreateProjectile(); void DropProjectile(entity::Entity entity) const; void CompleteProjectile(entity::Entity entity); void IterateProjectile(entity::Entity entity); void BindWindow(Window* pWindow); void UnbindWindow(Window* pWindow); void OnWindowCreated(Window* pWindow); void OnWindowDestroyed(Window* pWindow); void OnWindowMousePosition(Window* pWindow, std::pair<double, double> pos); unicorn::UnicornRender& m_unicornRender; WorldTime& m_worldTime; Time& m_timeSystem; Intent& m_intents; Render& m_renderSystem; assemblage::Factory& m_factory; std::vector<Window*> m_windows; std::set<unicorn::system::input::Key> m_lastKeys; }; } } #endif // XANTHUS_SYSTEM_INPUT_HPP
17.962025
79
0.701903
[ "render", "vector" ]
5c1081e2e0b835a7ec8a9f37af65a37e8061a980
9,526
cpp
C++
Source/SystemQOR/MSWindows/winpthreads/MSW_clock.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/winpthreads/MSW_clock.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/winpthreads/MSW_clock.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//MSW_clock.cpp // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. /** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the w64 mingw-runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #include "SystemQOR.h" #if (QOR_SYS_OS == QOR_SYS_MSW) #include "WinQL/System/Performance/WinQLPerformanceHelper.h" #include "WinQL/System/Clock/WinQLTime.h" #include "WinQL/Application/Process/WinQLProcess.h" #include "WinQL/Application/Threading/WinQLThread.h" #include <errno.h> #define __STDC_CONSTANT_MACROS #include <stdint.h> #include <time.h> #include <pthread.h> #define POW10_7 10000000 #define POW10_9 1000000000 /* Number of 100ns-seconds between the beginning of the Windows epoch * (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970) */ #define DELTA_EPOCH_IN_100NS __QCMP_LONG_SUFFIX(116444736000000000) //-------------------------------------------------------------------------------- namespace nsWin32 { //-------------------------------------------------------------------------------- static __QCMP_INLINE int lc_set_errno( int result ) { if (result != 0) { errno = result; return -1; } return 0; } //-------------------------------------------------------------------------------- /** * Get the resolution of the specified clock clock_id and * stores it in the struct timespec pointed to by res. * @param clock_id The clock_id argument is the identifier of the particular * clock on which to act. The following clocks are supported: * <pre> * CLOCK_REALTIME System-wide real-time clock. Setting this clock * requires appropriate privileges. * CLOCK_MONOTONIC Clock that cannot be set and represents monotonic * time since some unspecified starting point. * CLOCK_PROCESS_CPUTIME_ID High-resolution per-process timer from the CPU. * CLOCK_THREAD_CPUTIME_ID Thread-specific CPU-time clock. * </pre> * @param res The pointer to a timespec structure to receive the time * resolution. * @return If the function succeeds, the return value is 0. * If the function fails, the return value is -1, * with errno set to indicate the error. */ int clock_getres( clockid_t clock_id, timespec* res) { switch(clock_id) { case CLOCK_MONOTONIC: { nsWin32::LARGE_INTEGER pf; nsWin32::CPerformanceHelper PerformanceHelper; if( PerformanceHelper.QueryFrequency( pf ) == 0 ) { return lc_set_errno( EINVAL ); } res->tv_sec = 0; res->tv_nsec = (int)( ( POW10_9 + ( pf.QuadPart >> 1 ) ) / pf.QuadPart ); if( res->tv_nsec < 1 ) { res->tv_nsec = 1; } return 0; } case CLOCK_REALTIME: case CLOCK_PROCESS_CPUTIME_ID: case CLOCK_THREAD_CPUTIME_ID: { unsigned long timeAdjustment, timeIncrement; int isTimeAdjustmentDisabled; nsWin32::CTimeHelper TimeHelper; TimeHelper.GetSystemTimeAdjustment( &timeAdjustment, &timeIncrement, &isTimeAdjustmentDisabled ); res->tv_sec = 0; res->tv_nsec = timeIncrement * 100; return 0; } default: break; } return lc_set_errno( EINVAL ); } //-------------------------------------------------------------------------------- /** * Get the time of the specified clock clock_id and stores it in the struct * timespec pointed to by tp. * @param clock_id The clock_id argument is the identifier of the particular * clock on which to act. The following clocks are supported: * <pre> * CLOCK_REALTIME System-wide real-time clock. Setting this clock * requires appropriate privileges. * CLOCK_MONOTONIC Clock that cannot be set and represents monotonic * time since some unspecified starting point. * CLOCK_PROCESS_CPUTIME_ID High-resolution per-process timer from the CPU. * CLOCK_THREAD_CPUTIME_ID Thread-specific CPU-time clock. * </pre> * @param tp The pointer to a timespec structure to receive the time. * @return If the function succeeds, the return value is 0. * If the function fails, the return value is -1, * with errno set to indicate the error. */ int clock_gettime( clockid_t clock_id, timespec* tp ) { unsigned __int64 t; nsWin32::LARGE_INTEGER pf, pc; union { unsigned __int64 u64; nsWin32::FILETIME ft; } ct, et, kt, ut; switch( clock_id ) { case CLOCK_REALTIME: { nsWin32::CTimeHelper TimeHelper; TimeHelper.GetSystemTimeAsFileTime( &ct.ft ); t = ct.u64 - DELTA_EPOCH_IN_100NS; tp->tv_sec = t / POW10_7; tp->tv_nsec = ((int) (t % POW10_7)) * 100; return 0; } case CLOCK_MONOTONIC: { nsWin32::CPerformanceHelper PerformanceHelper; if( PerformanceHelper.QueryFrequency(pf) == 0 ) { return lc_set_errno( EINVAL ); } if( PerformanceHelper.QueryCounter(pc) == 0 ) { return lc_set_errno( EINVAL ); } tp->tv_sec = pc.QuadPart / pf.QuadPart; tp->tv_nsec = (int)( ( ( pc.QuadPart % pf.QuadPart ) * POW10_9 + ( pf.QuadPart >> 1 ) ) / pf.QuadPart ); if( tp->tv_nsec >= POW10_9 ) { tp->tv_sec ++; tp->tv_nsec -= POW10_9; } return 0; } case CLOCK_PROCESS_CPUTIME_ID: { nsWin32::CProcess* pProcess = nsWin32::ThisProcess(); if( 0 == pProcess->GetTimes( ct.ft, et.ft, kt.ft, ut.ft ) ) { return lc_set_errno( EINVAL ); } t = kt.u64 + ut.u64; tp->tv_sec = t / POW10_7; tp->tv_nsec = ( (int)( t % POW10_7 ) ) * 100; return 0; } case CLOCK_THREAD_CPUTIME_ID: { if( 0 == nsWin32::GetCurrentWin32Thread()->GetTimes( &ct.ft, &et.ft, &kt.ft, &ut.ft ) ) { return lc_set_errno(EINVAL); } t = kt.u64 + ut.u64; tp->tv_sec = t / POW10_7; tp->tv_nsec = ( (int)( t % POW10_7 ) ) * 100; return 0; } default: break; } return lc_set_errno( EINVAL ); } //-------------------------------------------------------------------------------- /** * Sleep for the specified time. * @param clock_id This argument should always be CLOCK_REALTIME (0). * @param flags 0 for relative sleep interval, others for absolute waking up. * @param request The desired sleep interval or absolute waking up time. * @param remain The remain amount of time to sleep. * The current implemention just ignore it. * @return If the function succeeds, the return value is 0. * If the function fails, the return value is -1, * with errno set to indicate the error. */ int clock_nanosleep( clockid_t clock_id, int flags, const timespec* request, timespec* remain ) { timespec tp; if( clock_id != CLOCK_REALTIME ) { return lc_set_errno( EINVAL ); } if( flags == 0 ) { return nanosleep( request, remain ); } // TIMER_ABSTIME = 1 clock_gettime( CLOCK_REALTIME, &tp ); tp.tv_sec = request->tv_sec - tp.tv_sec; tp.tv_nsec = request->tv_nsec - tp.tv_nsec; if( tp.tv_nsec < 0 ) { tp.tv_nsec += POW10_9; tp.tv_sec --; } return nanosleep( &tp, remain ); } //-------------------------------------------------------------------------------- /** * Set the time of the specified clock clock_id. * @param clock_id This argument should always be CLOCK_REALTIME (0). * @param tp The requested time. * @return If the function succeeds, the return value is 0. * If the function fails, the return value is -1, * with errno set to indicate the error. */ int clock_settime( clockid_t clock_id, const timespec* tp ) { nsWin32::CTimeHelper TimeHelper; nsWin32::SystemTime st; union { unsigned __int64 u64; nsWin32::FILETIME ft; }t; if( clock_id != CLOCK_REALTIME ) { return lc_set_errno( EINVAL ); } t.u64 = tp->tv_sec * (__int64) POW10_7 + tp->tv_nsec / 100 + DELTA_EPOCH_IN_100NS; if ( TimeHelper.FileTimeToSystemTime(&t.ft, &st) == 0) { return lc_set_errno(EINVAL); } if( TimeHelper.SetSystemTime( &st ) == 0 ) { return lc_set_errno(EPERM); } return 0; } }//nsWin32 #endif//(QOR_SYS_OS == QOR_SYS_MSW)
30.24127
108
0.636889
[ "object" ]
5c14eb7d0578d4ee0381449b26df4189cb2e367b
2,041
hxx
C++
include/moneta/traits/fixed_values.hxx
madera/Moneta
4c0da911bceb511d7d1133699b0d85216bb63d74
[ "BSL-1.0" ]
2
2015-10-09T12:11:54.000Z
2016-01-20T15:34:33.000Z
include/moneta/traits/fixed_values.hxx
madera/Moneta
4c0da911bceb511d7d1133699b0d85216bb63d74
[ "BSL-1.0" ]
5
2015-07-04T20:31:32.000Z
2015-07-04T20:44:58.000Z
include/moneta/traits/fixed_values.hxx
madera/Moneta
4c0da911bceb511d7d1133699b0d85216bb63d74
[ "BSL-1.0" ]
null
null
null
// [===========================================================================] // [ M o n e t a ] // [---------------------------------------------------------------------------] // [ ] // [ Copyright (C) 2005-2015 ] // [ Rodrigo Madera <madera@acm.org> ] // [ ] // [---------------------------------------------------------------------------] // [ Distributed under the Boost Software License, Version 1.0 ] // [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ] // [===========================================================================] #pragma once #include "members.hxx" #include "detail/member_trait_base.hxx" #include "detail/has_member_trait.hxx" #include <boost/mpl/copy_if.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/back_inserter.hpp> #include <boost/preprocessor/tuple/push_back.hpp> MONETA_DECLARE_TRAIT(fixed_value) #define MONETA_FIXED_VALUE(member, value) \ namespace moneta { namespace traits { \ template <> \ struct fixed_value<member> : boost::true_type { \ typedef member::result_type trait_type; \ static trait_type get() { \ return value; \ } \ }; \ }} #define MONETA_FIXED_VALUE_MEMBER(entity, type, name, value) \ MONETA_FIXED_VALUE(MONETA_MEMBER(entity, type, name), value) namespace moneta { namespace traits { template <class Entity> struct fixed_value_members : boost::mpl::copy_if< typename traits::members<Entity>::type, traits::fixed_value<boost::mpl::_1>, boost::mpl::back_inserter<boost::mpl::vector<> > > {}; }}
41.653061
80
0.419892
[ "vector" ]
5c203aa308aad171fabd91fcbbe0535ef421f4a0
9,462
cpp
C++
liquidfun/liquidfun/Box2D/lfjs/jsBindings/jsBindings.cpp
subatomicglue/fluid
c85376f86828a1c234bcd9535b9030cfb1a1e8bd
[ "MIT" ]
17
2017-04-02T00:17:47.000Z
2021-11-23T21:42:48.000Z
liquidfun/liquidfun/Box2D/lfjs/jsBindings/jsBindings.cpp
subatomicglue/fluid
c85376f86828a1c234bcd9535b9030cfb1a1e8bd
[ "MIT" ]
1
2022-01-09T17:14:54.000Z
2022-01-16T12:35:06.000Z
liquidfun/liquidfun/Box2D/lfjs/jsBindings/jsBindings.cpp
subatomicglue/fluid
c85376f86828a1c234bcd9535b9030cfb1a1e8bd
[ "MIT" ]
5
2017-08-06T12:47:18.000Z
2020-08-14T14:16:22.000Z
/* The pure C function declarations need to be externed or they get mangled by the compiler*/ extern "C" { #include "Collision/b2CollisionJsBindings.h" #include "Collision/Shapes/b2ChainShapeJsBindings.h" #include "Collision/Shapes/b2CircleShapeJsBindings.h" #include "Collision/Shapes/b2EdgeShapeJsBindings.h" #include "Collision/Shapes/b2PolygonShapeJsBindings.h" #include "Dynamics/b2BodyJsBindings.h" #include "Dynamics/b2FixtureJsBindings.h" #include "Dynamics/b2WorldJsBindings.h" #include "Dynamics/Contacts/b2ContactJsBindings.h" #include "Dynamics/Joints/b2DistanceJointJsBindings.h" #include "Dynamics/Joints/b2FrictionJointJsBindings.h" #include "Dynamics/Joints/b2GearJointJsBindings.h" #include "Dynamics/Joints/b2JointJsBindings.h" #include "Dynamics/Joints/b2MotorJointJsBindings.h" #include "Dynamics/Joints/b2MouseJointJsBindings.h" #include "Dynamics/Joints/b2PrismaticJointJsBindings.h" #include "Dynamics/Joints/b2PulleyJointJsBindings.h" #include "Dynamics/Joints/b2RevoluteJointJsBindings.h" #include "Dynamics/Joints/b2RopeJointJsBindings.h" #include "Dynamics/Joints/b2WeldJointJsBindings.h" #include "Dynamics/Joints/b2WheelJointJsBindings.h" #include "Particle/b2ParticleGroupJsBindings.h" #include "Particle/b2ParticleSystemJsBindings.h" void GenerateOffsets(); } #include "Collision/b2CollisionJsBindings.cpp" #include "Collision/Shapes/b2ChainShapeJsBindings.cpp" #include "Collision/Shapes/b2CircleShapeJsBindings.cpp" #include "Collision/Shapes/b2EdgeShapeJsBindings.cpp" #include "Collision/Shapes/b2PolygonShapeJsBindings.cpp" #include "Dynamics/b2BodyJsBindings.cpp" #include "Dynamics/b2FixtureJsBindings.cpp" #include "Dynamics/b2WorldJsBindings.cpp" #include "Dynamics/Contacts/b2ContactJsBindings.cpp" #include "Dynamics/Joints/b2DistanceJointJsBindings.cpp" #include "Dynamics/Joints/b2FrictionJointJsBindings.cpp" #include "Dynamics/Joints/b2GearJointJsBindings.cpp" #include "Dynamics/Joints/b2JointJsBindings.cpp" #include "Dynamics/Joints/b2MotorJointJsBindings.cpp" #include "Dynamics/Joints/b2MouseJointJsBindings.cpp" #include "Dynamics/Joints/b2PrismaticJointJsBindings.cpp" #include "Dynamics/Joints/b2PulleyJointJsBindings.cpp" #include "Dynamics/Joints/b2RevoluteJointJsBindings.cpp" #include "Dynamics/Joints/b2RopeJointJsBindings.cpp" #include "Dynamics/Joints/b2WeldJointJsBindings.cpp" #include "Dynamics/Joints/b2WheelJointJsBindings.cpp" #include "Particle/b2ParticleGroupJsBindings.cpp" #include "Particle/b2ParticleSystemJsBindings.cpp" /* // TODO clean all of this up, and/or make it auto generated from the // header files void PrintOffsets(b2Body* b) { printf("\tb2Body: {\n"); printf("\t\ttype: %u,\n", (unsigned int)&b->m_type - (unsigned int)b); printf("\t\tislandIndex: %u,\n", (unsigned int)&b->m_islandIndex - (unsigned int)b); printf("\t\txf: %u,\n", (unsigned int)&b->m_xf - (unsigned int)b); printf("\t\txf0: %u,\n", (unsigned int)&b->m_xf0 - (unsigned int)b); printf("\t\tsweep: %u,\n", (unsigned int)&b->m_sweep - (unsigned int)b); printf("\t\tlinearVelocity: %u,\n", (unsigned int)&b->m_linearVelocity - (unsigned int)b); printf("\t\tangularVelocity: %u,\n", (unsigned int)&b->m_angularVelocity - (unsigned int)b); printf("\t\tforce: %u,\n", (unsigned int)&b->m_force - (unsigned int)b); printf("\t\ttorque: %u,\n", (unsigned int)&b->m_torque - (unsigned int)b); printf("\t\tworld: %u,\n", (unsigned int)&b->m_world - (unsigned int)b); printf("\t\tprev: %u,\n", (unsigned int)&b->m_prev - (unsigned int)b); printf("\t\tnext: %u,\n", (unsigned int)&b->m_next - (unsigned int)b); printf("\t\tfixtureList: %u,\n", (unsigned int)&b->m_fixtureList - (unsigned int)b); printf("\t\tfixtureCount: %u,\n", (unsigned int)&b->m_fixtureCount - (unsigned int)b); printf("\t\tjointList: %u,\n", (unsigned int)&b->m_jointList - (unsigned int)b); printf("\t\tcontactList: %u,\n", (unsigned int)&b->m_contactList - (unsigned int)b); printf("\t\tmass: %u,\n", (unsigned int)&b->m_mass - (unsigned int)b); printf("\t\tinvMass: %u,\n", (unsigned int)&b->m_invMass - (unsigned int)b); printf("\t\tI: %u,\n", (unsigned int)&b->m_I - (unsigned int)b); printf("\t\tinvI: %u,\n", (unsigned int)&b->m_invI - (unsigned int)b); printf("\t\tlinearDamping: %u,\n", (unsigned int)&b->m_linearDamping - (unsigned int)b); printf("\t\tangularDamping: %u,\n", (unsigned int)&b->m_angularDamping - (unsigned int)b); printf("\t\tgravityScale: %u,\n", (unsigned int)&b->m_gravityScale - (unsigned int)b); printf("\t\tsleepTime: %u,\n", (unsigned int)&b->m_sleepTime - (unsigned int)b); printf("\t\tuserData: %u\n", (unsigned int)&b->m_userData - (unsigned int)b); printf("\t}\n"); } void PrintOffsets(b2Contact* c) { printf("\tb2Contact: {\n"); printf("\t\tflags: %u,\n", (unsigned int)&c->m_flags - (unsigned int)c); printf("\t\tprev: %u,\n", (unsigned int)&c->m_prev - (unsigned int)c); printf("\t\tnext: %u,\n", (unsigned int)&c->m_next - (unsigned int)c); printf("\t\tnodeA: %u,\n", (unsigned int)&c->m_nodeA - (unsigned int)c); printf("\t\tnodeB: %u,\n", (unsigned int)&c->m_nodeB - (unsigned int)c); printf("\t\tfixtureA: %u,\n", (unsigned int)&c->m_fixtureA - (unsigned int)c); printf("\t\tfixtureB: %u,\n", (unsigned int)&c->m_fixtureB - (unsigned int)c); printf("\t\tindexA: %u,\n", (unsigned int)&c->m_indexA - (unsigned int)c); printf("\t\tindexB: %u,\n", (unsigned int)&c->m_indexB - (unsigned int)c); printf("\t\tmanifold: %u,\n", (unsigned int)&c->m_manifold - (unsigned int)c); printf("\t\ttoiCount: %u,\n", (unsigned int)&c->m_toiCount - (unsigned int)c); printf("\t\ttoi: %u,\n", (unsigned int)&c->m_toi - (unsigned int)c); printf("\t\tfriction: %u,\n", (unsigned int)&c->m_friction - (unsigned int)c); printf("\t\trestitution: %u,\n", (unsigned int)&c->m_restitution - (unsigned int)c); printf("\t\ttangentSpeed: %u\n", (unsigned int)&c->m_tangentSpeed - (unsigned int)c); printf("\t},\n"); } void PrintOffsets(b2Fixture* f) { printf("\tb2Fixture: {\n"); printf("\t\tdensity: %u,\n", (unsigned int)&f->m_density - (unsigned int)f); printf("\t\tnext: %u,\n", (unsigned int)&f->m_next - (unsigned int)f); printf("\t\tbody: %u,\n", (unsigned int)&f->m_body - (unsigned int)f); printf("\t\tshape: %u,\n", (unsigned int)&f->m_shape - (unsigned int)f); printf("\t\tfriction: %u,\n", (unsigned int)&f->m_friction - (unsigned int)f); printf("\t\trestitution: %u,\n", (unsigned int)&f->m_restitution - (unsigned int)f); printf("\t\tproxies: %u,\n", (unsigned int)&f->m_proxies - (unsigned int)f); printf("\t\tproxyCount: %u,\n", (unsigned int)&f->m_proxyCount - (unsigned int)f); printf("\t\tfilter: %u,\n", (unsigned int)&f->m_filter - (unsigned int)f); printf("\t\tisSensor: %u,\n", (unsigned int)&f->m_isSensor - (unsigned int)f); printf("\t\tuserData: %u\n", (unsigned int)&f->m_userData - (unsigned int)f); printf("\t},\n"); } void PrintOffsets(b2ParticleGroup* p) { printf("\tb2ParticleGroup: {\n"); printf("\t\tsystem: %u,\n", (unsigned int)&p->m_system - (unsigned int)p); printf("\t\tfirstIndex: %u,\n", (unsigned int)&p->m_firstIndex - (unsigned int)p); printf("\t\tlastIndex: %u,\n", (unsigned int)&p->m_lastIndex - (unsigned int)p); printf("\t\tgroupFlags: %u,\n", (unsigned int)&p->m_groupFlags - (unsigned int)p); printf("\t\tstrength: %u,\n", (unsigned int)&p->m_strength - (unsigned int)p); printf("\t\tprev: %u,\n", (unsigned int)&p->m_prev - (unsigned int)p); printf("\t\tnext: %u,\n", (unsigned int)&p->m_next - (unsigned int)p); printf("\t\ttimestamp: %u,\n", (unsigned int)&p->m_timestamp - (unsigned int)p); printf("\t\tmass: %u,\n", (unsigned int)&p->m_mass - (unsigned int)p); printf("\t\tinertia: %u,\n", (unsigned int)&p->m_inertia - (unsigned int)p); printf("\t\tcenter: %u,\n", (unsigned int)&p->m_center - (unsigned int)p); printf("\t\tlinearVelocity: %u,\n", (unsigned int)&p->m_linearVelocity - (unsigned int)p); printf("\t\tangularVelocity: %u,\n", (unsigned int)&p->m_angularVelocity - (unsigned int)p); printf("\t\ttransform: %u,\n", (unsigned int)&p->m_transform - (unsigned int)p); printf("\t\tuserData: %u\n", (unsigned int)&p->m_userData - (unsigned int)p); printf("\t},\n"); } void PrintOffsets(b2World* w) { printf("\tb2World: {\n"); printf("\t\tbodyList: %u\n", (unsigned int)&w->m_bodyList - (unsigned int)w); printf("\t},\n"); } void PrintOffsets(b2WorldManifold* wm) { printf("\tb2WorldManifold: {\n"); printf("\t\tnormal: %u,\n", (unsigned int)&wm->normal - (unsigned int)wm); printf("\t\tpoints: %u,\n", (unsigned int)&wm->points - (unsigned int)wm); printf("\t\tseparations: %u\n", (unsigned int)&wm->separations - (unsigned int)wm); printf("\t},\n"); } #include <stdio.h> extern "C" { void GenerateOffsets() { printf("{\n"); //create dummy body to generate offsets b2World world(b2Vec2(0, 0)); b2BodyDef def; b2Body* body1 = world.CreateBody(&def); b2CircleShape s; b2FixtureDef d; d.shape = &s; b2Fixture* f =body1->CreateFixture(&d); b2ParticleSystemDef psd; b2ParticleSystem* ps = world.CreateParticleSystem(&psd); b2ParticleGroupDef pgd; b2ParticleGroup* pg = ps->CreateParticleGroup(pgd); b2WorldManifold worldManifold; PrintOffsets(body1); PrintOffsets(f); PrintOffsets(pg); PrintOffsets(&world); PrintOffsets(&worldManifold); // need to instantiate contact differently //b2Contact contact; //PrintOffsets(&contact); printf("};\n"); } }*/
49.28125
94
0.69573
[ "shape" ]
5c2b5cd0006d3dad2a66f1e1aeffdb2052faabd0
4,152
cpp
C++
PizzaSeparator.cpp
Loniowsky/GoogleHashCodeTestRound
95c101981fc6b180d5ce9b20a782df132e32c575
[ "MIT" ]
null
null
null
PizzaSeparator.cpp
Loniowsky/GoogleHashCodeTestRound
95c101981fc6b180d5ce9b20a782df132e32c575
[ "MIT" ]
null
null
null
PizzaSeparator.cpp
Loniowsky/GoogleHashCodeTestRound
95c101981fc6b180d5ce9b20a782df132e32c575
[ "MIT" ]
null
null
null
#include "PizzaSeparator.h" #include "PrintVector.h" #include <iostream> #include <fstream> #include <cstdlib> #include "Point.h" #include "Parser.h" using namespace std; PizzaSeparator::PizzaSeparator(std::vector<std::vector<bool>>* v){ for(unsigned int i = 0; i < columns; ++i){ isTaken.emplace_back(); for(unsigned int j = 0; j < rows; ++j){ isTaken[i].push_back(false); } } toSlice=v; } void PizzaSeparator::SlicePizza(){ int counter=0; while((startingP=FindStartingPoint()).IsValid()){ endP=startingP; if((*toSlice)[startingP.GetX()][startingP.GetY()])actMus++; else actTom++; while(actTom<::min or actMus<::min or FieldSize()>::max){ if(ExpandVertically()); else if(!ExpandHorizontally()){ if(FieldSize()<=::max){ isTaken[startingP.GetX()][startingP.GetY()]=true; break; } } if(FieldSize()>::max){ if(!ExpandHorizontally()){ isTaken[startingP.GetX()][startingP.GetY()]=true; break; } } while(FieldSize()>::max)DecreaseVertically(); if(FieldSize()<=1){ isTaken[startingP.GetX()][startingP.GetY()]=true; break; } } if(actMus>=::min and actTom>=::min and endP.IsValid() and startingP.IsValid() and FieldSize()<=::max){ SetTaken(); AddToResults(); counter++; } if(counter%500==0)cout<<counter<<endl; actMus=0; actTom=0; } } PizzaSeparator::~PizzaSeparator(){ delete toSlice; } Point PizzaSeparator::FindStartingPoint(){ for(unsigned int i = 0; i < columns; ++i){ for(unsigned int j = 0 ; j < rows; ++j){ if(isTaken[i][j]==0) return Point(i, j, validity::valid); } } return Point(0,0,validity::notvalid); } bool PizzaSeparator::IsValid(const Point& upperLeft, const Point& lowerRight) { if(lowerRight.GetX()>=columns or lowerRight.GetY()>=rows)return false; for (unsigned int i=upperLeft.GetX(); i<=lowerRight.GetX(); ++i) { for (unsigned int j=upperLeft.GetY(); j<=lowerRight.GetY(); ++j) { if (isTaken[i][j]==true) return false; } } return true; } unsigned int PizzaSeparator::FieldSize(){ return (endP.GetX()-startingP.GetX()+1)*(endP.GetY()-startingP.GetY()+1); } bool PizzaSeparator::ExpandVertically(){ if((IsValid( Point(startingP.GetX(),endP.GetY()) , Point(endP.GetX() , endP.GetY() + 1) ) ) and endP.GetY() + 1 < rows){ endP.SetY( endP.GetY() + 1); for(unsigned int i = startingP.GetX(); i <= endP.GetX(); ++i){ if((*toSlice)[i][endP.GetY()]==0)actTom++; else actMus++; } return true; } return false; } bool PizzaSeparator::ExpandHorizontally(){ if((IsValid(Point(endP.GetX(),startingP.GetY() ) , Point(endP.GetX() +1 , endP.GetY() ) ) )and endP.GetX() + 1 < columns){ endP.SetX( endP.GetX() + 1); for(unsigned int j = startingP.GetY(); j <= endP.GetY(); ++j){ if((*toSlice)[endP.GetX()][j]==0)actTom++; else actMus++; } return true; } return false; } void PizzaSeparator::SetTaken(){ for(unsigned int i = startingP.GetX(); i<=endP.GetX() ; ++i){ for(unsigned int j = startingP.GetY(); j<=endP.GetY(); ++j){ isTaken[i][j]=1; } } } void PizzaSeparator::DecreaseVertically(){ for(unsigned int i = startingP.GetX(); i <= endP.GetX(); ++i){ if((*toSlice)[i][endP.GetY()]==0)actTom--; else actMus--; } endP.SetY( endP.GetY() - 1); } void PizzaSeparator::AddToResults() { auto added = std::make_pair(startingP, endP); m_result.push_back(added); } void PizzaSeparator::PrintResults() { for (std::vector<std::pair<Point, Point>>::iterator i = m_result.begin(); i!=m_result.end(); ++i) { std::cout<<(*i).first.GetY()<<" "; std::cout<<(*i).first.GetX()<<" "; std::cout<<(*i).second.GetY()<<" "; std::cout<<(*i).second.GetX()<<std::endl; } } void PizzaSeparator::SaveToFile() { std::ofstream outputFile("medium.out");; if (!outputFile.is_open()) { std::cout<<"Could not open a file"<<std::endl; exit(-1); } outputFile<<m_result.size()<<std::endl; for (std::vector<std::pair<Point, Point>>::iterator i = m_result.begin(); i!=m_result.end(); ++i) { outputFile<<(*i).first.GetY()<<" "; outputFile<<(*i).first.GetX()<<" "; outputFile<<(*i).second.GetY()<<" "; outputFile<<(*i).second.GetX()<<std::endl; } }
24.568047
124
0.627649
[ "vector" ]
5c3468d5687d592168353213d78ec820693a8cec
11,725
cpp
C++
src/server/chatservice.cpp
Robust-Jay/JayChat
e59071b7b3f37e3e24ffb99583d37cf650d8d184
[ "MIT" ]
1
2022-03-02T03:44:20.000Z
2022-03-02T03:44:20.000Z
src/server/chatservice.cpp
Robust-Jay/JayChat
e59071b7b3f37e3e24ffb99583d37cf650d8d184
[ "MIT" ]
null
null
null
src/server/chatservice.cpp
Robust-Jay/JayChat
e59071b7b3f37e3e24ffb99583d37cf650d8d184
[ "MIT" ]
null
null
null
/* * @Author: Han Liu * @Date: 2022-02-27 18:31:35 * @LastEditTime: 2022-03-02 16:49:08 * @LastEditors: Han Liu * @Description: * @FilePath: /JayChat/src/server/chatservice.cpp * 不积跬步 无以至千里 */ #include "chatservice.hpp" namespace JayChat { /** * @description: 获取单例对象的接口函数 * @param {*} * @return {ChatService *} */ ChatService *ChatService::instance() { static ChatService service; return &service; } /** * @description: 构造函数 * @param {*} * @return {ChatService} */ ChatService::ChatService() { __msgHandlerMap.insert({LOGIN_MSG, std::bind(&ChatService::login, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); __msgHandlerMap.insert({REG_MSG, std::bind(&ChatService::reg, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); __msgHandlerMap.insert({ONE_CHAT_MSG, std::bind(&ChatService::oneChat, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); __msgHandlerMap.insert({ADD_FRIEND_MSG, std::bind(&ChatService::addFriend, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); __msgHandlerMap.insert({CREATE_GROUP_MSG, std::bind(&ChatService::createGroup, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); __msgHandlerMap.insert({ADD_GROUP_MSG, std::bind(&ChatService::addGroup, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); __msgHandlerMap.insert({GROUP_CHAT_MSG, std::bind(&ChatService::groupChat, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}); } /** * @description: 获取消息对应的处理器 * @param {int} msgid * @return {std::function<void(const TcpConnectionPtr &, json &, Timestamp)>} */ MsgHandler ChatService::getHandler(int msgid) { auto it = __msgHandlerMap.find(msgid); if (it == __msgHandlerMap.end()) { return [=](const TcpConnectionPtr &conn, json &js, Timestamp time) { LOG_ERROR << "msgid:" << msgid << " can not find handler!"; }; } else { return __msgHandlerMap[msgid]; } } /** * @description: 处理登录业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::login(const TcpConnectionPtr &conn, json &js, Timestamp time) { int id = js["id"].get<int>(); std::string password = js["password"]; User user = __userModel.query(id); if (user.getId() != -1 && user.getPassword() == password) { if (user.getState() == "online") { // 该用户已经登录,不允许重复登录 json response; response["msgid"] = LOGIN_MSG_ACK; response["errno"] = 2; response["errmsg"] = "this account is using, input another!"; conn->send(response.dump()); } else { // 登录成功 { std::lock_guard<std::mutex> lock(__connMutex); __userConnctionMap.insert({id, conn}); // 记录用户连接 } user.setState("online"); __userModel.updateState(user); // 更新用户状态信息 json response; response["msgid"] = LOGIN_MSG_ACK; response["errno"] = 0; response["id"] = user.getId(); response["name"] = user.getName(); // 查询该用户是否有离线消息 std::vector<std::string> vec = __offlinemsgModel.query(id); if (!vec.empty()) { response["offlinemsg"] = vec; __offlinemsgModel.remove(id); } // 查询该用户的好友信息并返回 std::vector<User> userVec = __friendModel.query(id); if (!userVec.empty()) { std::vector<string> u_js_vec; for (User user : userVec) { json u_js; u_js["id"] = user.getId(); u_js["name"] = user.getName(); u_js["state"] = user.getState(); u_js_vec.push_back(u_js.dump()); } response["friends"] = u_js_vec; } // 查询用户的群组消息 std::vector<Group> groupuserVec = __groupModel.queryGroups(id); if (!groupuserVec.empty()) { std::vector<std::string> groupV; for (Group &group : groupuserVec) { json grpjson; grpjson["id"] = group.getId(); grpjson["groupname"] = group.getName(); grpjson["groupdesc"] = group.getDesc(); std::vector<std::string> userV; for (GroupUser &user : group.getUsers()) { json ujson; ujson["id"] = user.getId(); ujson["name"] = user.getName(); ujson["state"] = user.getState(); ujson["role"] = user.getRole(); userV.push_back(ujson.dump()); } grpjson["users"] = userV; groupV.push_back(grpjson.dump()); } response["groups"] = groupV; } conn->send(response.dump()); } } else { // 该用户不存在,登录失败 json response; response["msgid"] = LOGIN_MSG_ACK; response["errno"] = 1; response["errmsg"] = "name or password is invalid!"; conn->send(response.dump()); } } /** * @description: 处理注册业务,提供name、password * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::reg(const TcpConnectionPtr &conn, json &js, Timestamp time) { std::string name = js["name"]; std::string password = js["password"]; User user; user.setName(name); user.setPassword(password); bool flag = __userModel.insert(user); if (flag) { // 注册成功 json response; response["msgid"] = REG_MSG_ACK; response["errno"] = 0; response["id"] = user.getId(); conn->send(response.dump()); } else { // 注册失败 json response; response["msgid"] = REG_MSG_ACK; response["errno"] = 1; conn->send(response.dump()); } } /** * @description: 处理注销业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::logout(const TcpConnectionPtr &conn, json &js, Timestamp time) { int userid = js["id"].get<int>(); { std::lock_guard<std::mutex> lock(__connMutex); auto it = __userConnctionMap.find(userid); if (it != __userConnctionMap.end()) { __userConnctionMap.erase(it); } } // 更新用户的状态信息 User user(userid, "", "", "offline"); __userModel.updateState(user); } /** * @description: 处理客户端异常退出 * @param {TcpConnectionPtr} &conn * @return {*} */ void ChatService::clientCloseException(const TcpConnectionPtr &conn) { User user; { std::lock_guard<std::mutex> lock(__connMutex); for (auto it = __userConnctionMap.begin(); it != __userConnctionMap.end(); ++it) { if (it->second == conn) { // 从map表中删除用户的连接信息 user.setId(it->first); __userConnctionMap.erase(it); break; } } } // 更新用户的状态信息 if (user.getId() != -1) { user.setState("offline"); __userModel.updateState(user); } } /** * @description: 一对一聊天业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::oneChat(const TcpConnectionPtr &conn, json &js, Timestamp time) { int toid = js["to"].get<int>(); { std::lock_guard<std::mutex> lock(__connMutex); auto it = __userConnctionMap.find(toid); if (it != __userConnctionMap.end()) { // toid在线,转发消息 服务器中转消息 it->second->send(js.dump()); return; } } // toid不在线,存储离线消息 __offlinemsgModel.insert(toid, js.dump()); } /** * @description: 服务器异常,业务重置方法 * @param {*} * @return {*} */ void ChatService::reset() { // 把online的用户,设置成offline __userModel.resetState(); } /** * @description: 添加好友业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::addFriend(const TcpConnectionPtr &conn, json &js, Timestamp time) { int userid = js["id"].get<int>(); int friendid = js["friendid"].get<int>(); // 存储好友信息 __friendModel.insert(userid, friendid); } /** * @description: 创建群组业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::createGroup(const TcpConnectionPtr &conn, json &js, Timestamp time) { int userid = js["id"].get<int>(); std::string name = js["groupname"]; std::string desc = js["groupdesc"]; // 存储新创建的群组信息 Group group(-1, name, desc); if (__groupModel.createGroup(group)) { // 存储群组创建人信息 __groupModel.addGroup(userid, group.getId(), "creator"); } } /** * @description: 加入群组业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::addGroup(const TcpConnectionPtr &conn, json &js, Timestamp time) { int userid = js["id"].get<int>(); int groupid = js["groupid"].get<int>(); __groupModel.addGroup(userid, groupid, "normal"); } /** * @description: 群组聊天业务 * @param {TcpConnectionPtr} &conn * @param {json} &js * @param {Timestamp} time * @return {*} */ void ChatService::groupChat(const TcpConnectionPtr &conn, json &js, Timestamp time) { int userid = js["id"].get<int>(); int groupid = js["groupid"].get<int>(); std::vector<int> idVec = __groupModel.queryGroupUsers(userid, groupid); std::lock_guard<std::mutex> lock(__connMutex); for(int id : idVec) { auto it = __userConnctionMap.find(id); if (it != __userConnctionMap.end()) { // 转发消息 it->second->send(js.dump()); } else { // 存储离线消息 __offlinemsgModel.insert(id, js.dump()); } } } } // namespace JayChat
31.100796
164
0.490405
[ "vector" ]
5c3dfe92f578d18c885e76032bbd6955c1b2edbd
4,468
hpp
C++
src/cs-scene/CelestialAnchor.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cs-scene/CelestialAnchor.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cs-scene/CelestialAnchor.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef CS_SCENE_CELESTIAL_ANCHOR_HPP #define CS_SCENE_CELESTIAL_ANCHOR_HPP #include "cs_scene_export.hpp" #include <glm/glm.hpp> #include <glm/gtc/quaternion.hpp> #include <string> namespace cs::scene { class CelestialObserver; /// This class is the root class for all objects which have a location in the Universe. It uses /// the SPICE coordinate system, which means that the transformation of this object is defined by /// two parameters: /// - The center of the coordinate system: /// This is the origin of the coordinate system. The transformation of the object describes the /// difference from the objects location relative this center. /// An example for this could be the center of the Earth. /// - The frame of reference: /// This defines how the position is calculated relative to the origin. For example with /// "J2000" the location would be calculated relative to the equatorial plane, but the rotation /// of the earth would not be factored into the position, but with "IAU_Earth" the location /// would be relative to the current longitude and thus the object would spin with the Earth. /// /// /// This class also provides methods for getting the transformation components in the coordinate /// system of other entities. class CS_SCENE_EXPORT CelestialAnchor { public: explicit CelestialAnchor(std::string const& sCenterName = "Solar System Barycenter", std::string const& sFrameName = "J2000"); /// Returns the position of "other" in the coordinate system defined by this CelestialAnchor - the /// result is not affected by the additional rotation and scale of "other", as these do not change /// it's position. virtual glm::dvec3 getRelativePosition(double tTime, CelestialAnchor const& other) const; /// Returns the rotation which aligns the coordinate system of this CelestialAnchor with "other" - /// the calculation depends on both frames and additional rotations. virtual glm::dquat getRelativeRotation(double tTime, CelestialAnchor const& other) const; /// Returns the how much "other" is larger than this, i.e. other.GetAnchorScale() / /// GetAnchorScale(). virtual double getRelativeScale(CelestialAnchor const& other) const; /// Returns the entire transformation of "other" in the coordinate system defined by this /// CelestialAnchor. virtual glm::dmat4 getRelativeTransform(double tTime, CelestialAnchor const& other) const; /// SPICE name of the frame. virtual std::string const& getFrameName() const; virtual void setFrameName(std::string const& sFrameName, bool keepTransform = false); /// SPICE name of the center body. /// A reference frame’s center must be a SPICE ephemeris object whose location is coincident with /// the origin (0, 0, 0) of the frame. virtual std::string const& getCenterName() const; virtual void setCenterName(std::string const& sCenterName, bool keepTransform = false); /// Additional translation in meters, relative to center in frame coordinates additional scaling /// and rotation is applied afterwards and will not change the position relative to the center. virtual glm::dvec3 const& getAnchorPosition() const; virtual void setAnchorPosition(glm::dvec3 const& vPos); /// Additional rotation around the point center + position in frame coordinates. virtual glm::dquat const& getAnchorRotation() const; virtual void setAnchorRotation(glm::dquat const& qRot); /// Additional uniform scaling around the point center + position. virtual double getAnchorScale() const; virtual void setAnchorScale(double dScale); /// Called regularly by the Universe if registered. virtual void update(double tTime, CelestialObserver const& oObs) { } protected: glm::dvec3 mPosition; glm::dquat mRotation; double mScale; std::string mCenterName; std::string mFrameName; }; } // namespace cs::scene #endif // CS_SCENE_CELESTIAL_ANCHOR_HPP
46.061856
100
0.690018
[ "object" ]
5c4e56689b299005e7e0641300b4e6a1bcaf68ac
1,878
hh
C++
packages/spatial/Cartesian_Overlay.hh
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
2
2020-04-13T20:06:41.000Z
2021-02-12T17:55:54.000Z
packages/spatial/Cartesian_Overlay.hh
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
1
2018-10-22T21:03:35.000Z
2018-10-22T21:03:35.000Z
packages/spatial/Cartesian_Overlay.hh
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
3
2019-04-03T02:15:37.000Z
2022-01-04T05:50:23.000Z
#ifndef Cartesian_Overlay_hh #define Cartesian_Overlay_hh #include <memory> #include <vector> #include "Indexing.hh" class Distance; class Cartesian_Overlay { public: enum Cell_Error { LOWER_BOUND = -1, UPPER_BOUND = -2 }; Cartesian_Overlay(int dimension, std::vector<int> const &number_of_cells_per_dimension, std::vector<double> const &cartesian_bounds, std::shared_ptr<Distance> distance); int number_of_points() const { return number_of_points_; } void add_point(std::vector<double> const &position); int get_cell(std::vector<double> const &position) const; // void nearest_points(int number_of_points, // std::vector<double> const &position, // std::vector<int> &indices, // std::vector<double> &distances) const; bool has_neighbor(double minimum_distance, std::vector<double> const &position) const; void get_cells_to_check(int cell, std::vector<int> const &number_of_cells_to_check, std::vector<int> &cells_to_check) const; virtual void check_class_invariants() const; private: // Static variables int dimension_; int number_of_cells_; std::vector<int> number_of_cells_per_dimension_; std::vector<double> cell_length_; std::vector<double> cartesian_bounds_; std::shared_ptr<Distance> distance_; std::shared_ptr<Indexing<int> > indexing_; // Dynamic variables int number_of_points_; std::vector<int> cell_by_index_; // which cell each point is in std::vector<std::vector<int> > indices_by_cell_; // points that are in each cell std::vector<std::vector<double> > position_by_index_; }; #endif
29.809524
84
0.627263
[ "vector" ]
5c52973a66ba072cd49e81c3aeb6cd4ea6f3be39
1,669
cpp
C++
dsa_problemset_cn/7-3.cpp
sonaspy/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
1
2018-11-28T09:38:23.000Z
2018-11-28T09:38:23.000Z
dsa_problemset_cn/7-3.cpp
NewGuonx/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
null
null
null
dsa_problemset_cn/7-3.cpp
NewGuonx/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
null
null
null
// author -sonaspy@outlook.com // coding - utf_8 #include <bits/stdc++.h> #define test() freopen("in", "r", stdin) using namespace std; struct TreeNode { char data; TreeNode *left = nullptr, *right = nullptr; TreeNode(char x) : data(x) {} }; typedef vector<TreeNode *> Tree; TreeNode *BulidTree(Tree &T) { int N, check[20] = {0}; char cl, cr; cin >> N; for (int i = 0; i < N; i++) T[i] = new TreeNode('-'); for (int i = 0; i < N; i++) { cin >> T[i]->data >> cl >> cr; if (cl != '-') { T[i]->left = T[cl - '0']; check[cl - '0'] = 1; } if (cr != '-') { T[i]->right = T[cr - '0']; check[cr - '0'] = 1; } } for (int i = 0; i < N; i++) if (!check[i]) return T[i]; return nullptr; } int Isomprphic(TreeNode *root1, TreeNode *root2) { if (!root1 && !root2) return 1; if (!root1 || !root2) return 0; if (root1->data != root2->data) return 0; if (!root1->left && !root2->left) return Isomprphic(root1->right, root2->right); if (root1->left && root2->left && root1->left->data == root2->left->data) return (Isomprphic(root1->left, root2->left) && Isomprphic(root1->right, root2->right)); else return (Isomprphic(root1->left, root2->right) && Isomprphic(root1->right, root2->left)); } int main() { //test(); TreeNode *root1, *root2; Tree T1(20), T2(20); root1 = BulidTree(T1); root2 = BulidTree(T2); if (Isomprphic(root1, root2)) cout << "Yes"; else cout << "No"; return 0; }
23.507042
96
0.494907
[ "vector" ]
5c552061f2d4d9d869de1028b7810b662a71bc0b
9,801
cpp
C++
Common/source/ipc/TriPlayer.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
null
null
null
Common/source/ipc/TriPlayer.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
null
null
null
Common/source/ipc/TriPlayer.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
null
null
null
#include "ipc/Command.hpp" #include "ipc/TriPlayer.hpp" #include <string.h> #include <switch.h> namespace TriPlayer { static Service * service = nullptr; // Service object used for communication bool initialize() { // Return true if already initialized if (service != nullptr) { return true; } // Check if service exists SmServiceName name = smEncodeName("tri"); uint8_t exists; Result rc = serviceDispatchInOut(smGetServiceSession(), 65100, name, exists); if (!(R_SUCCEEDED(rc) && exists)) { return false; } // Acquire service object service = new Service; rc = smGetServiceWrapper(service, name); if (R_FAILED(rc)) { delete service; service = nullptr; } return (service != nullptr); } void exit() { if (service != nullptr) { serviceClose(service); delete service; service = nullptr; } } bool getVersion(std::string & outVersion) { // Permits xx.xx.xx (i.e. 2 digits each) char version[10] = {0}; Result rc = serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::Version), version); if (R_FAILED(rc)) { return false; } outVersion = std::string(version); return true; } bool resume() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Resume)))); } bool pause() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Pause)))); } bool previous() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Previous)))); } bool next() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Next)))); } bool getVolume(double & outVolume) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::GetVolume), outVolume))); } bool setVolume(const double volume) { return (R_SUCCEEDED(serviceDispatchIn(service, static_cast<uint32_t>(Ipc::Command::SetVolume), volume))); } bool mute() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Mute)))); } bool unmute(double & outVolume) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::Unmute), outVolume))); } bool getSubQueue(std::vector<int> & outIDs) { // Request queue in groups of 100 constexpr size_t count = 100; outIDs.clear(); // Repeatedly request groups until we run out size_t offset = 0; while (true) { // Prepare to handle received data const struct { size_t index; size_t count; } in = {offset, count}; outIDs.resize(offset + count); // Request data size_t returned = 0; Result rc = serviceDispatchInOut(service, static_cast<uint32_t>(Ipc::Command::GetSubQueue), in, returned, .buffer_attrs = {SfBufferAttr_Out | SfBufferAttr_HipcMapAlias}, .buffers = {{&outIDs[offset], count * sizeof(int)}}, ); offset += returned; if (R_FAILED(rc)) { return false; } // Stop if we didn't receive the amount requested (means we've got the entire sub queue) if (returned != count) { outIDs.resize(offset); break; } } return true; } bool getSubQueueSize(size_t & outCount) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::SubQueueSize), outCount))); } bool addToSubQueue(const int ID) { return (R_SUCCEEDED(serviceDispatchIn(service, static_cast<uint32_t>(Ipc::Command::AddToSubQueue), ID))); } bool removeFromSubQueue(const size_t pos) { return (R_SUCCEEDED(serviceDispatchIn(service, static_cast<uint32_t>(Ipc::Command::RemoveFromSubQueue), pos))); } bool skipSubQueueSongs(const size_t count) { size_t skipped; Result rc = serviceDispatchInOut(service, static_cast<uint32_t>(Ipc::Command::SkipSubQueueSongs), count, skipped); return (R_SUCCEEDED(rc)); } bool getQueue(std::vector<int> & outIDs) { // Request queue in groups of 100 constexpr size_t count = 100; outIDs.clear(); // Repeatedly request groups until we run out size_t offset = 0; while (true) { // Prepare to handle received data const struct { size_t index; size_t count; } in = {offset, count}; outIDs.resize(offset + count); // Request data size_t returned = 0; Result rc = serviceDispatchInOut(service, static_cast<uint32_t>(Ipc::Command::GetQueue), in, returned, .buffer_attrs = {SfBufferAttr_Out | SfBufferAttr_HipcMapAlias}, .buffers = {{&outIDs[offset], count * sizeof(int)}}, ); offset += returned; if (R_FAILED(rc)) { return false; } // Stop if we didn't receive the amount requested (means we've got the entire sub queue) if (returned != count) { outIDs.resize(offset); break; } } return true; } bool getQueueSize(size_t & outCount) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::QueueSize), outCount))); } bool setQueue(const std::vector<int> & IDs) { size_t count; Result rc = serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::SetQueue), count, .buffer_attrs = {SfBufferAttr_In | SfBufferAttr_HipcMapAlias}, .buffers = {{&IDs[0], IDs.size() * sizeof(int)}}, ); return (R_SUCCEEDED(rc)); } bool getQueueIdx(size_t & outPos) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::QueueIdx), outPos))); } bool setQueueIdx(const size_t pos) { size_t newIdx = 0; Result rc = serviceDispatchInOut(service, static_cast<uint32_t>(Ipc::Command::SetQueueIdx), pos, newIdx); if (R_FAILED(rc) || newIdx != pos) { return false; } return true; } bool removeFromQueue(const size_t pos) { return (R_SUCCEEDED(serviceDispatchIn(service, static_cast<uint32_t>(Ipc::Command::RemoveFromQueue), pos))); } bool getRepeatMode(Repeat & outMode) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::GetRepeat), outMode))); } bool setRepeatMode(const Repeat mode) { return (R_SUCCEEDED(serviceDispatchIn(service, static_cast<uint32_t>(Ipc::Command::SetRepeat), mode))); } bool getShuffleMode(Shuffle & outMode) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::GetShuffle), outMode))); } bool setShuffleMode(const Shuffle mode) { return (R_SUCCEEDED(serviceDispatchIn(service, static_cast<uint32_t>(Ipc::Command::SetShuffle), mode))); } bool getSongID(int & outID) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::GetSong), outID))); } bool getStatus(Status & outStatus) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::GetStatus), outStatus))); } bool getPosition(double & outPos) { return (R_SUCCEEDED(serviceDispatchOut(service, static_cast<uint32_t>(Ipc::Command::GetPosition), outPos))); } bool setPosition(const double pos) { double newPos; return (R_SUCCEEDED(serviceDispatchInOut(service, static_cast<uint32_t>(Ipc::Command::SetPosition), pos, newPos))); } bool getPlayingFromText(std::string & outText) { char text[101] = {0}; Result rc = serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::GetPlayingFrom), .buffer_attrs = {SfBufferAttr_Out | SfBufferAttr_HipcMapAlias}, .buffers = {{text, sizeof(text)}}, ); if (R_FAILED(rc)) { return false; } outText = std::string(text); return true; } bool setPlayingFromText(const std::string & text) { // Copy string into format suitable for transmitting char * str = strndup(text.c_str(), 100); size_t len = strlen(str); Result rc = serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::SetPlayingFrom), .buffer_attrs = {SfBufferAttr_In | SfBufferAttr_HipcMapAlias}, .buffers = {{str, len + 1}}, ); free(str); if (R_FAILED(rc)) { return false; } return true; } bool requestDatabaseLock() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::RequestDBLock)))); } bool releaseDatabaseLock() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::ReleaseDBLock)))); } bool reloadConfig() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::ReloadConfig)))); } bool reset() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Reset)))); } bool stopSysmodule() { return (R_SUCCEEDED(serviceDispatch(service, static_cast<uint32_t>(Ipc::Command::Quit)))); } };
33.680412
123
0.607591
[ "object", "vector" ]