hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5921ea0546f73efec76a67380f329551a7c3ef1c
| 82,290
|
cpp
|
C++
|
src/main.cpp
|
bkentel/boken-old
|
8967856be5f283989d0c10843bcb739728423152
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
bkentel/boken-old
|
8967856be5f283989d0c10843bcb739728423152
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
bkentel/boken-old
|
8967856be5f283989d0c10843bcb739728423152
|
[
"MIT"
] | 1
|
2020-04-11T12:20:00.000Z
|
2020-04-11T12:20:00.000Z
|
#include "algorithm.hpp"
#include "allocator.hpp"
#include "catch.hpp" // for run_unit_tests
#include "command.hpp"
#include "data.hpp"
#include "entity.hpp" // for entity
#include "entity_properties.hpp"
#include "events.hpp"
#include "format.hpp"
#include "hash.hpp" // for djb2_hash_32
#include "inventory.hpp"
#include "item.hpp"
#include "item_list.hpp"
#include "item_properties.hpp"
#include "level.hpp" // for level, placement_result, make_level, etc
#include "math.hpp" // for vec2i32, floor_as, point2f, basic_2_tuple, etc
#include "message_log.hpp" // for message_log
#include "names.hpp"
#include "random.hpp" // for random_state, make_random_state
#include "random_algorithm.hpp"
#include "rect.hpp"
#include "render.hpp" // for game_renderer
#include "scope_guard.hpp"
#include "system.hpp" // for system, kb_modifiers, mouse_event, etc
#include "text.hpp" // for text_layout, text_renderer
#include "tile.hpp" // for tile_map
#include "timer.hpp"
#include "types.hpp" // for value_cast, tag_size_type_x, etc
#include "utility.hpp" // for BK_OFFSETOF
#include "world.hpp" // for world, make_world
#include <algorithm> // for move
#include <chrono> // for microseconds, operator-, duration, etc
#include <deque>
#include <functional> // for function
#include <memory> // for unique_ptr, allocator
#include <ratio> // for ratio
#include <string> // for string, to_string
#include <utility> // for pair, make_pair
#include <vector> // for vector
#include <cstdint> // for uint16_t, uint32_t, uintptr_t
#include <cstdio> // for printf
#include <cinttypes>
namespace boken {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
struct game_state {
//--------------------------------------------------------------------------
// Player functions
//--------------------------------------------------------------------------
entity_id player_definition() const noexcept {
return find(the_world, player_id()).definition();
}
static constexpr entity_instance_id player_id() noexcept {
return entity_instance_id {1u};
}
point2i32 player_location() const noexcept {
return require(current_level().find(player_id()));
}
const_entity_descriptor player_descriptor() const noexcept {
return {ctx, player_id()};
}
entity_descriptor player_descriptor() noexcept {
return {ctx, player_id()};
}
//--------------------------------------------------------------------------
// Level functions
//--------------------------------------------------------------------------
level& current_level() noexcept {
return the_world.current_level();
}
level const& current_level() const noexcept {
return the_world.current_level();
}
//! hard fail if the entity doesn't exist on the given level.
point2i32 require_entity_on_level(const_entity_descriptor const e, level const& lvl) const {
return require(lvl.find(e->instance()));
}
//--------------------------------------------------------------------------
// Message functions
//--------------------------------------------------------------------------
void println(string_buffer_base const& buffer) {
println(buffer.to_string());
}
void println(std::string msg) {
message_window.println(std::move(msg));
r_message_log.show();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Types
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using clock_t = std::chrono::high_resolution_clock;
using timepoint_t = clock_t::time_point;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Special member functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
game_state() {
bind_event_handlers_();
r_map.set_tile_maps({
{tile_map_type::base, database.get_tile_map(tile_map_type::base)}
, {tile_map_type::entity, database.get_tile_map(tile_map_type::entity)}
, {tile_map_type::item, database.get_tile_map(tile_map_type::item)}
});
r_map.set_pile_id(get_pile_id(database));
init_item_list();
init_equip_list();
generate();
reset_view_to_player();
// resize the message log to fit the current window size
{
auto const r_win = os.get_client_rect();
auto const r = message_window.bounds();
message_window.resize_to({r.top_left(), r_win.width(), r.height()});
}
}
void init_item_list() {
using col_t = item_list_controller::column_type;
item_list.add_columns(
ctx, {col_t::icon, col_t::name, col_t::weight, col_t::count});
item_list.layout();
item_list.hide();
item_list.set_on_focus_change([&](bool const is_focused) {
r_item_list.set_focus(is_focused);
if (is_focused) {
tool_tip.visible(false);
}
});
item_list.set_on_selection_change([&](int const row) {
});
}
void init_equip_list() {
using col_t = item_list_controller::column_type;
equip_list.add_columns(
ctx, {col_t::icon, col_t::name, col_t::weight, col_t::count});
equip_list.layout();
equip_list.hide();
equip_list.set_on_focus_change([&](bool const is_focused) {
r_equip_list.set_focus(is_focused);
if (is_focused) {
tool_tip.visible(false);
}
});
equip_list.set_on_selection_change([&](int const row) {
});
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Utility / Helpers
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
point2i32 window_to_world(point2i32 const p) const noexcept {
auto const& tmap = database.get_tile_map(tile_map_type::base);
return underlying_cast_unsafe<int32_t>(
floor(current_view.window_to_world(
p, tmap.tile_width(), tmap.tile_height())));
}
point2i32 world_to_window(point2i32 const p) const noexcept {
auto const& tmap = database.get_tile_map(tile_map_type::base);
//TODO: round?
return underlying_cast_unsafe<int32_t>(current_view.world_to_window(
p, tmap.tile_width(), tmap.tile_height()));
}
//! Debug command to create a corridor at the give position.
//! @param p Position in world coordinates
void debug_create_corridor_at(point2i32 const p) {
if (!intersects(p, the_world.current_level().bounds())) {
return;
}
tile_data_set const data {
tile_data {}
, tile_flags {0}
, tile_id::tunnel
, tile_type::tunnel
, region_id {}
};
update_tile_at(p, data);
}
//! Change the properties of the tile for the current level at the given
//! position.
//! @param p Position in world coordinates
void update_tile_at(point2i32 const p, tile_data_set const& data) {
auto& lvl = the_world.current_level();
BK_ASSERT(intersects(lvl.bounds(), p));
r_map.update_map_data(lvl.update_tile_at(rng_superficial, p, data));
}
//! Show the toolip for the 'view' command
//! @param p Position in world coordinates
void show_view_tool_tip(point2i32 const p) {
auto const& lvl = the_world.current_level();
auto const& tile = lvl.at(p);
static_string_buffer<256> buffer;
auto const print_entity_info = [&](const_entity_descriptor const e) {
return buffer.append("%s", name_of_decorated(ctx, e).data());
};
auto const print_item_info = [&](const_item_descriptor const i) {
return buffer.append("%s", name_of_decorated(ctx, i).data());
};
auto const print_entity = [&]() noexcept {
return result_of_or(lvl.entity_at(p), true
, [&](entity_instance_id const id) {
return print_entity_info({ctx, id}); });
};
auto const print_items = [&]() noexcept {
auto const ptr = lvl.item_at(p);
if (!ptr) {
return !!buffer;
}
auto const& pile = *ptr;
auto i = pile.size();
buffer.append("\n");
for (auto const& id : pile) {
if (!print_item_info({ctx, id})) {
return false;
}
if ((i && --i) && !buffer.append(", ")) {
return false;
}
}
return buffer.append("\n");
};
auto const result =
buffer.append("You see here: %s\n"
, enum_to_string(lvl.at(p).id).data())
&& print_entity()
&& print_items();
tool_tip.set_text(buffer.to_string());
}
//! @param p Position in window coordinates
void debug_show_tool_tip(point2i32 const p) {
auto const p0 = window_to_world(p);
auto const q = window_to_world({last_mouse_x, last_mouse_y});
auto const was_visible = tool_tip.visible(true);
tool_tip.set_position(p);
if (was_visible && p0 == q) {
return; // the tile the mouse points to is unchanged from last time
}
auto const& lvl = current_level();
auto const& tile = lvl.at(p0);
static_string_buffer<512> buffer;
auto const print_entity_info = [&](const_entity_descriptor const e) {
return buffer.append(
"Entity:\n"
" Instance : %0#10x\n"
" Definition: %0#10x (%s)\n"
" Name : %s\n"
, value_cast(get_instance(e))
, value_cast(get_id(e)), id_string(e).data()
, name_of(ctx, e).data());
};
auto const print_item_info = [&](const_item_descriptor const i) {
return buffer.append(
" Instance : %0#10x\n"
" Definition: %0#10x (%s)\n"
" Name : %s\n"
, value_cast(get_instance(i))
, value_cast(get_id(i)), id_string(i).data()
, name_of(ctx, i).data());
};
auto const print_entity = [&] {
return result_of_or(lvl.entity_at(p0), true
, [&](entity_instance_id const id) {
return print_entity_info({ctx, id}); });
};
auto const print_items = [&] {
auto const ptr = lvl.item_at(p0);
if (!ptr) {
return !!buffer;
}
auto const& pile = *ptr;
buffer.append("Items (%d):\n"
, static_cast<int>(pile.size()));
for (auto const& id : pile) {
if (!print_item_info({ctx, id})) {
return false;
}
}
return true;
};
auto const has_los = lvl.has_line_of_sight(player_location(), p0);
auto const result =
buffer.append(
"Position: %d, %d (%s)\n"
"Region : %d\n"
"Tile : %s\n"
, value_cast(p0.x), value_cast(p0.y), (has_los ? "seen" : "unseen")
, value_cast<int>(tile.rid)
, enum_to_string(lvl.at(p0).id).data())
&& print_entity()
&& print_items();
tool_tip.set_text(buffer.to_string());
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialization / Generation
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void generate_player() {
auto& lvl = current_level();
auto const& def = *find(database, make_id<entity_id>("player"));
create_object_at(
def, {lvl, lvl.stair_up(0)}, rng_substantive);
}
void generate_entities() {
weight_list<int, item_id> const w {
{6, item_id {}}
, {3, make_id<item_id>("coin")}
, {1, make_id<item_id>("potion_health_small")}
};
auto const w_max = w.max();
auto& rng = rng_substantive;
auto& lvl = current_level();
auto const def_ptr = database.find(make_id<entity_id>("rat_small"));
BK_ASSERT(!!def_ptr);
auto const& def = *def_ptr;
for (size_t i = 0; i < lvl.region_count(); ++i) {
auto const& region = lvl.region(i);
if (region.tile_count <= 0) {
continue;
}
auto const result = lvl.find_valid_entity_placement_neareast(
rng, center_of(region.bounds), 3);
if (result.second != placement_result::ok) {
continue;
}
auto const p = result.first;
auto instance_id = create_object_at(def, {lvl, p}, rng);
auto& new_entity = find(the_world, instance_id);
auto const id = random_weighted(rng, w);
if (id == item_id {}) {
continue;
}
auto* const idef = database.find(id);
if (!idef) {
BK_ASSERT(false);
continue; //TODO
}
new_entity.add_item(create_object(*idef, rng));
}
}
void generate_items() {
auto& lvl = current_level();
auto& rng = rng_substantive;
auto const container_def_id = make_id<item_id>("container_chest");
auto const dagger_def_id = make_id<item_id>("weapon_dagger");
BK_ASSERT(find(database, container_def_id)
&& find(database, dagger_def_id));
auto const& container_def = *find(database, container_def_id);
auto const& dagger_def = *find(database, dagger_def_id);
for (size_t i = 0; i < lvl.region_count(); ++i) {
auto const& region = lvl.region(i);
if (region.tile_count <= 0) {
continue;
}
auto const result = lvl.find_valid_item_placement_neareast(
rng, center_of(region.bounds), 3);
if (result.second != placement_result::ok) {
continue;
}
auto const p = result.first;
auto const container_id = create_object_at(container_def, {lvl, p}, rng);
create_object(dagger_def, container_id, rng);
renderer_update_pile(p);
}
}
void generate_level(level* const parent, size_t const id) {
auto const level_w = 50;
auto const level_h = 40;
the_world.add_new_level(parent
, make_level(rng_substantive, the_world, sizei32x {level_w}, sizei32y {level_h}, id));
the_world.change_level(id);
}
void generate(size_t const id = 0) {
BK_ASSERT(!the_world.has_level(id));
if (id == 0) {
generate_level(nullptr, id);
generate_player();
} else {
generate_level(&the_world.current_level(), id);
}
generate_entities();
generate_items();
set_current_level(id, true);
}
void set_current_level(size_t const level_id, bool const is_new) {
BK_ASSERT(the_world.has_level(level_id));
r_map.set_level(the_world.change_level(level_id));
r_map.update_map_data();
auto& lvl = the_world.current_level();
lvl.for_each_entity([&](entity_instance_id const id, point2i32 const p) {
r_map.add_object_at(p, find(the_world, id).definition());
});
lvl.for_each_pile([&](item_pile const& pile, point2i32 const p) {
r_map.add_object_at(p, get_pile_id(ctx, pile));
});
}
void reset_view_to_player() {
auto const& tmap = database.get_tile_map(tile_map_type::base);
auto const win_r = os.get_client_rect();
auto const q = current_view.center_window_on_world(
player_location(), tmap.tile_width(), tmap.tile_height()
, win_r.width(), win_r.height());
update_view({1.0f, 1.0f}, q);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Events
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//! Process events (see docs)
template <typename... Args0, typename... Args1>
void process_event(
bool (game_state::* ui_handler)(Args0...)
, event_result (input_context::* ctx_handler)(Args0...)
, void (game_state::* base_handler)(Args0...)
, Args1&&... args
) {
// first allow the ui a chance to process the event
if (!(this->*ui_handler)(std::forward<Args1>(args)...)) {
return; // ui filtered the event
}
// then allow the input contexts a chance to process the event
if (!context_stack.process(ctx_handler, std::forward<Args1>(args)...)) {
return; // an input context filtered the event
}
// lastly, allow the default handler to process the event
(this->*base_handler)(std::forward<Args1>(args)...);
}
void bind_event_handlers_() {
os.on_resize([&](int32_t const w, int32_t const h) {
auto const r = message_window.bounds();
message_window.resize_to({r.top_left(), sizei32x {w}, r.height()});
});
os.on_key([&](kb_event const event, kb_modifiers const kmods) {
process_event(&game_state::ui_on_key
, &input_context::on_key
, &game_state::on_key
, event, kmods);
cmd_translator.translate(event, kmods);
});
os.on_text_input([&](text_input_event const event) {
process_event(&game_state::ui_on_text_input
, &input_context::on_text_input
, &game_state::on_text_input
, event);
cmd_translator.translate(event);
});
os.on_mouse_move([&](mouse_event const event, kb_modifiers const kmods) {
process_event(&game_state::ui_on_mouse_move
, &input_context::on_mouse_move
, &game_state::on_mouse_move
, event, kmods);
last_mouse_x = event.x;
last_mouse_y = event.y;
});
os.on_mouse_button([&](mouse_event const event, kb_modifiers const kmods) {
process_event(&game_state::ui_on_mouse_button
, &input_context::on_mouse_button
, &game_state::on_mouse_button
, event, kmods);
});
os.on_mouse_wheel([&](int const wx, int const wy, kb_modifiers const kmods) {
process_event(&game_state::ui_on_mouse_wheel
, &input_context::on_mouse_wheel
, &game_state::on_mouse_wheel
, wx, wy, kmods);
});
cmd_translator.on_command([&](command_type const type, uint64_t const data) {
process_event(&game_state::ui_on_command
, &input_context::on_command
, &game_state::on_command
, type, data);
});
}
bool ui_on_key(kb_event const event, kb_modifiers const kmods) {
return item_list.on_key(event, kmods)
&& equip_list.on_key(event, kmods);
}
bool ui_on_text_input(text_input_event const event) {
return item_list.on_text_input(event)
&& equip_list.on_text_input(event);
}
bool ui_on_mouse_button(mouse_event const event, kb_modifiers const kmods) {
return item_list.on_mouse_button(event, kmods)
&& equip_list.on_mouse_button(event, kmods);
}
bool ui_on_mouse_move(mouse_event const event, kb_modifiers const kmods) {
return item_list.on_mouse_move(event, kmods)
&& equip_list.on_mouse_move(event, kmods)
&& [&] {
if (!intersects(message_window.bounds(), point2i32 {event.x, event.y})) {
return true;
}
r_message_log.show();
return true;
}();
}
bool ui_on_mouse_wheel(int const wy, int const wx, kb_modifiers const kmods) {
return item_list.on_mouse_wheel(wy, wx, kmods)
&& equip_list.on_mouse_wheel(wy, wx, kmods);
}
bool ui_on_command(command_type const type, uintptr_t const data) {
return item_list.on_command(type, data)
&& equip_list.on_command(type, data);
}
void on_key(kb_event const event, kb_modifiers const kmods) {
auto const is_shift =
(!kmods.any(kb_mod::shift))
&& ((event.scancode == kb_scancode::k_lshift)
|| (event.scancode == kb_scancode::k_rshift));
if (is_shift&& !event.went_down) {
if (highlighted_tile == point2i32 {-1, -1}) {
tool_tip.visible(false);
} else {
update_highlighted_tile({});
}
}
}
void on_text_input(text_input_event const event) {
}
void on_mouse_button(mouse_event const event, kb_modifiers const kmods) {
using mbc = mouse_event::button_change_t;
switch (event.button_state_bits()) {
case 0b0000 :
if (event.button_change[1] == mbc::went_up) {
do_follow_path(
player_location()
, window_to_world({event.x, event.y}));
}
break;
case 0b0001 :
if (event.button_change[0] == mbc::went_down) {
if (kmods.exclusive_any(kb_mod::alt)) {
debug_create_corridor_at(
window_to_world({event.x, event.y}));
}
}
break;
case 0b0010 : break;
case 0b0100 : break;
case 0b1000 : break;
default :
break;
}
}
void on_mouse_move(mouse_event const event, kb_modifiers const kmods) {
switch (event.button_state_bits()) {
case 0b0000 :
if (kmods.exclusive_any(kb_mod::shift)) {
debug_show_tool_tip({event.x, event.y});
}
break;
case 0b0001 : break;
case 0b0010 : break;
case 0b0100 :
if (kmods.none()) {
update_view_trans(
current_view.x_off + static_cast<float>(event.dx)
, current_view.y_off + static_cast<float>(event.dy));
}
break;
case 0b1000 : break;
default :
break;
}
}
void on_mouse_wheel(int const wy, int const wx, kb_modifiers const kmods) {
auto const p_window = point2i32 {last_mouse_x, last_mouse_y};
auto const p_world = current_view.window_to_world(p_window);
auto const scale = current_view.scale_x * (wy > 0 ? 1.1f : 0.9f);
update_view_scale(scale, scale);
auto const p_window_new = current_view.world_to_window(p_world);
auto const dx = current_view.x_off
+ value_cast_unsafe<float>(p_window.x) - value_cast(p_window_new.x);
auto const dy = current_view.y_off
+ value_cast_unsafe<float>(p_window.y) - value_cast(p_window_new.y);
update_view_trans(dx, dy);
}
void on_command(command_type const type, uint64_t const data) {
using ct = command_type;
switch (type) {
case ct::none : break;
case ct::move_here : advance(1); break;
case ct::move_n : do_player_move_by({ 0, -1}); break;
case ct::move_ne : do_player_move_by({ 1, -1}); break;
case ct::move_e : do_player_move_by({ 1, 0}); break;
case ct::move_se : do_player_move_by({ 1, 1}); break;
case ct::move_s : do_player_move_by({ 0, 1}); break;
case ct::move_sw : do_player_move_by({-1, 1}); break;
case ct::move_w : do_player_move_by({-1, 0}); break;
case ct::move_nw : do_player_move_by({-1, -1}); break;
case ct::run_n : do_player_run({ 0, -1}); break;
case ct::run_ne : do_player_run({ 1, -1}); break;
case ct::run_e : do_player_run({ 1, 0}); break;
case ct::run_se : do_player_run({ 1, 1}); break;
case ct::run_s : do_player_run({ 0, 1}); break;
case ct::run_sw : do_player_run({-1, 1}); break;
case ct::run_w : do_player_run({-1, 0}); break;
case ct::run_nw : do_player_run({-1, -1}); break;
case ct::move_down : do_change_level(ct::move_down); break;
case ct::move_up : do_change_level(ct::move_up); break;
case ct::get_all_items : do_get_all_items(); break;
case ct::get_items : do_get_items(); break;
case ct::toggle_show_inventory : do_toggle_inventory(); break;
case ct::toggle_show_equipment : do_toggle_equipment(); break;
case ct::reset_view : reset_view_to_player(); break;
case ct::reset_zoom:
BK_ASSERT(false); // TODO
break;
case ct::debug_toggle_regions :
r_map.debug_toggle_show_regions();
r_map.update_map_data();
break;
case ct::debug_teleport_self : do_debug_teleport_self(); break;
case ct::cancel : do_cancel(); break;
case ct::confirm : break;
case ct::toggle : break;
case ct::drop_one : do_drop_one(); break;
case ct::drop_some : do_drop_some(); break;
case ct::open : do_open(); break;
case ct::view : do_view(); break;
case ct::alt_get_items : break;
case ct::alt_drop_some : break;
case ct::alt_open : break;
case ct::alt_insert : break;
case ct::alt_equip : break;
default:
BK_ASSERT(false);
break;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Helpers
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//! updates the window space position of the tooltip associated with the
//! view command.
void update_highlight_tile() {
auto const p = highlighted_tile;
if (p == point2i32 {-1, -1}) {
return;
}
auto const q = world_to_window(p + vec2i32 {1, 0});
tool_tip.set_position(q);
}
void set_highlighted_tile(point2i32 const p) {
auto const bounds = the_world.current_level().bounds();
auto const q = clamp(bounds, p);
highlighted_tile = q;
r_map.highlight(&q, &q + 1);
show_view_tool_tip(q);
update_highlight_tile();
tool_tip.visible(true);
adjust_view_to_player(q);
}
void update_highlighted_tile(vec2i32 const v) {
set_highlighted_tile(highlighted_tile + v);
}
template <typename OnCommand>
void impl_choose_items_(
int const n
, std::string&& title
, OnCommand on_command
) {
item_list.set_title(std::move(title));
item_list.set_modal(true);
item_list.set_multiselect(n > 1);
item_list.show();
item_list.set_on_command([=](command_type const cmd) {
return on_command(cmd);
});
}
template <typename OnCommand>
void choose_multiple_items(std::string title, OnCommand on_command) {
impl_choose_items_(2, std::move(title), on_command);
}
template <typename OnCommand>
void choose_single_item(std::string title, OnCommand on_command) {
impl_choose_items_(1, std::move(title), on_command);
}
//! Common implementation for dropping exactly one, or multiple items.
//! This is used for dropping items directly from the game, not from a
//! container or the inventory, etc.
//!
//! For n > 1, drop multiple (0 - N) items.
//! For n == 1, drop exactly zero or one item.
//!
//! @pre n > 0
void impl_do_drop_items_(int const n) {
BK_ASSERT(n > 0);
auto const player = player_descriptor();
if (auto const& player_items = items(player)) {
item_list.assign(player_items);
} else {
println("You have nothing to drop.");
return;
}
using ct = command_type;
auto const handler = [=](command_type const cmd) {
if (cmd == ct::cancel && item_list.get().selection_clear() <= 0) {
println("Nevermind.");
} else if ((cmd == ct::confirm) || (cmd == ct::alt_drop_some)) {
player_drop_selected_items(p_from(player));
} else {
return event_result::filter;
}
return event_result::filter_detach;
};
if (n > 1) {
choose_multiple_items("Drop which item(s)?", handler);
} else {
choose_single_item("Drop which item?", handler);
}
}
//! Common implementation for getting all items, or a selection of multiple
//! items from the player's current location.
//! This is used for getting items directly from the field (not from a
//! container etc).
//!
//! For n > 1, get all items.
//! For n < 0, get zero or more items.
//!
//! @pre n != 0
void impl_do_get_items_(int const n) {
BK_ASSERT(n != 0);
auto const from = level_location {current_level(), player_location()};
if (auto* const pile = from.lvl.item_at(from.p)) {
item_list.assign(*pile);
} else {
println("There is nothing here to get.");
return;
}
// get all items
if (n < 0) {
player_get_items(p_from(from));
return;
}
// get a selection of items
using ct = command_type;
auto const handler = [=](command_type const cmd) {
if (cmd == ct::cancel && item_list.get().selection_clear() <= 0) {
println("Nevermind.");
} else if ((cmd == ct::confirm) || (cmd == ct::alt_get_items)) {
player_get_selected_items(p_from(from));
} else {
return event_result::filter;
}
return event_result::filter_detach;
};
choose_multiple_items("Get which item(s)?", handler);
}
//! Capture input until the player makes a yes / no choice and invoke the
//! callback with either command_type::confirm for "yes", or
//! command_type::cancel for "no".
template <typename UnaryF>
void query_yes_no(UnaryF callback) {
input_context c(__func__);
using ct = command_type;
c.on_command_handler = [=](command_type const cmd, uint64_t) {
if (cmd == ct::cancel || cmd == ct::confirm) {
callback(cmd);
return event_result::filter_detach;
}
return event_result::filter;
};
c.on_text_input_handler = [=](text_input_event const event) {
if (event.text.size() != 1u) {
return event_result::filter;
}
auto const ch = event.text[0];
if (ch == 'y' || ch == 'Y') {
callback(command_type::confirm);
return event_result::filter_detach;
}
if (ch == 'n' || ch == 'N') {
callback(command_type::cancel);
return event_result::filter_detach;
}
return event_result::filter;
};
context_stack.push(std::move(c));
}
//! Inserts items from the player's inventory into container.
//! The item list is populated with the items in the players inventory
//! excluding the container itself if the player is holding it.
//! @pre container must be an item that is a container.
void insert_into_container(item_descriptor const container) {
auto const player = player_descriptor();
auto const fill_list = [=, cid = container.obj.instance()] {
return item_list.assign_if_not(items(player), cid) > 0;
};
if (!items(player) || !fill_list()) {
println("You have nothing to insert.");
return;
}
using ct = command_type;
auto const handler = [=](command_type const cmd) {
if (cmd == ct::cancel && item_list.get().selection_clear() <= 0) {
println("Nevermind.");
return event_result::filter_detach;
} else if ((cmd == ct::confirm) || (cmd == ct::alt_insert)) {
auto const indicated = item_list.get().indicated();
auto const result = player_insert_selected_items(p_to(container));
if (result > 0 && !fill_list()) {
return event_result::filter_detach;
}
item_list.get().indicate(indicated);
}
return event_result::filter;
};
choose_multiple_items("Insert which item(s)?", handler);
}
//! Opens the indicated item from the item list if it is a container,
//! otherwise does nothing. The list is populated with the contents of the
//! indicated container.
bool insert_into_indicated_container() {
return item_list.with_indicated([&](item_instance_id const id) {
auto const i = item_descriptor {ctx, id};
if (is_container(i)) {
insert_into_container(i);
}
});
}
void message_insert_item(
string_buffer_base& buffer
, const_entity_descriptor const subject
, const_entity_descriptor const from
, const_item_descriptor const itm
, const_item_descriptor const container
) {
buffer.append("%s insert the %s into the %s."
, name_of_decorated(ctx, subject).data()
, name_of_decorated(ctx, itm).data()
, name_of_decorated(ctx, container).data());
}
void message_drop_item(
string_buffer_base& buffer
, const_entity_descriptor const subject
, const_entity_descriptor const from
, const_item_descriptor const itm
) {
buffer.append("%s drop the %s."
, name_of_decorated(ctx, subject).data()
, name_of_decorated(ctx, itm).data());
}
void message_drop_item(
string_buffer_base& buffer
, const_entity_descriptor const subject
, const_item_descriptor const from
, const_item_descriptor const itm
) {
buffer.append("%s remove the %s from the %s and drop it."
, name_of_decorated(ctx, subject).data()
, name_of_decorated(ctx, itm).data()
, name_of_decorated(ctx, from).data());
}
void message_get_item(
string_buffer_base& buffer
, const_entity_descriptor const subject
, const_level_location const from
, const_item_descriptor const itm
) {
buffer.append("%s pick up the %s."
, name_of_decorated(ctx, subject).data()
, name_of_decorated(ctx, itm).data());
}
void message_get_item(
string_buffer_base& buffer
, const_entity_descriptor const subject
, const_item_descriptor const from
, const_item_descriptor const itm
) {
buffer.append("%s remove the %s from the %s."
, name_of_decorated(ctx, subject).data()
, name_of_decorated(ctx, itm).data()
, name_of_decorated(ctx, from).data());
}
template <typename To>
int player_insert_selected_items(to_t<To> to) {
auto const player = player_descriptor();
using It = int const*;
return item_list.with_selected_range([=](It const first, It const last) {
static_string_buffer<128> buffer;
return move_items(buffer, first, last
, p_subject(player), p_from(player), to, always_true {}
, [&](bool const ok, const_item_descriptor const itm, int const i) {
if (ok) {
message_insert_item(buffer, player, player, itm, to);
}
println(buffer);
});
});
}
template <typename From>
int player_drop_selected_items(from_t<From> from) {
auto const to = level_location {current_level(), player_location()};
auto const player = player_descriptor();
using It = int const*;
return item_list.with_selected_range([=](It const first, It const last) {
static_string_buffer<128> buffer;
auto const result = move_items(buffer, first, last
, p_subject(player), from, p_to(to), always_true {}
, [&](bool const ok, const_item_descriptor const itm, int const i) {
if (ok) {
message_drop_item(buffer, player, from, itm);
}
println(buffer);
});
if (result > 0) {
renderer_update_pile(to);
}
return result;
});
}
template <typename From, typename FwdIt = int const*>
int player_get_items(
from_t<From> from
, FwdIt const first = FwdIt {}
, FwdIt const last = FwdIt {}
) {
auto const player = player_descriptor();
static_string_buffer<128> buffer;
auto const result = move_items(buffer, first, last
, p_subject(player), from, p_to(player), always_true {}
, [&](bool const ok, const_item_descriptor const itm, int const i) {
if (ok) {
message_get_item(buffer, player, from, itm);
}
println(buffer);
});
if (result > 0) {
renderer_update_pile(from);
}
return result;
}
template <typename From>
int player_get_selected_items(from_t<From> from) {
using It = int const*;
return item_list.with_selected_range([=](It const first, It const last) {
return player_get_items(from, first, last);
});
}
//! @pre container must actually be a container
void view_container(item_descriptor const container) {
BK_ASSERT(is_container(container));
if (!is_identified(container)) {
// viewing a container updates the id status to level 1
set_identified(container, 1);
}
{
static_string_buffer<128> buffer;
buffer.append("You open the %s."
, name_of_decorated(ctx, container).data());
println(buffer);
}
using ft = item_list_controller::flag_type;
using ct = command_type;
auto const setup_list = [=] {
item_list.set_title(name_of_decorated(ctx, container));
item_list.assign(items(container));
};
item_list.set_flags({ft::modal, ft::multiselect, ft::visible});
item_list.set_on_command([=, i = 0](command_type const cmd) mutable {
BK_DISABLE_WSWITCH_ENUM_BEGIN
switch (cmd) {
case ct::none:
setup_list();
break;
case ct::alt_get_items:
if (player_get_selected_items(p_from(container))) {
setup_list();
}
break;
case ct::alt_drop_some:
if (player_drop_selected_items(p_from(container))) {
setup_list();
}
break;
case ct::alt_insert:
insert_into_container(container);
break;
case ct::cancel:
if (item_list.cancel_selection()) {
break;
}
return event_result::filter_detach;
default:
break;
}
BK_DISABLE_WSWITCH_ENUM_END
return event_result::filter;
});
}
bool view_indicated_container() {
return item_list.with_indicated([&](item_instance_id const id) {
auto const i = item_descriptor {ctx, id};
if (is_container(i)) {
view_container(i);
}
});
}
void adjust_view_to_player(point2i32 const p) noexcept {
constexpr int tile_distance_x = 5;
constexpr int tile_distance_y = 5;
auto const& tmap = database.get_tile_map(tile_map_type::base);
auto const tw = tmap.tile_width();
auto const th = tmap.tile_height();
auto const win_r = underlying_cast_unsafe<float>(
os.get_client_rect());
auto const win_w = win_r.width();
auto const win_h = win_r.height();
auto const limit = current_view.world_to_window(
make_2_tuple(tile_distance_x * tw, tile_distance_y * th));
auto const w_center = make_2_tuple(
win_r.x0 + win_w / 2.0f, win_r.y0 + win_h / 2.0f);
// center of the tile at the player's position in window coordinates
auto const q = current_view.world_to_window(
underlying_cast_unsafe<float>(p) + vec2f {0.5f, 0.5f}, tw, th);
auto const left = q.x - win_r.x0;
auto const top = q.y - win_r.y0;
auto const right = win_r.x1 - q.x;
auto const bottom = win_r.y1 - q.y;
auto const dx = magnitude_x(limit) * 2.0f > win_w ? value_cast((w_center - q).x)
: (left < limit.x) ? value_cast(limit.x - left)
: (right < limit.x) ? value_cast(right - limit.x)
: 0.0f;
auto const dy = magnitude_y(limit) * 2.0f > win_h ? value_cast((w_center - q).y)
: (top < limit.y) ? value_cast(limit.y - top)
: (bottom < limit.y) ? value_cast(bottom - limit.y)
: 0.0f;
update_view_trans(current_view.x_off + dx, current_view.y_off + dy);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Item transfer
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//! Helper functions to implement move_items
//@{
template <typename FwdIt, typename Predicate>
int impl_move_items(level_location const l, FwdIt const first, FwdIt const last, Predicate pred) {
return l.lvl.move_items(l.p, first, last, pred).second;
}
template <typename Obj, typename FwdIt, typename Predicate>
int impl_move_items(Obj const obj, FwdIt const first, FwdIt const last, Predicate pred, int) {
return obj->items().remove_if(first, last
, [&](int const i) noexcept { return item_list.get().row_data(i); }
, pred);
}
template <typename FwdIt, typename Predicate>
int impl_move_items(item_descriptor const i, FwdIt const first, FwdIt const last, Predicate pred) {
return impl_move_items(i, first, last, pred, 0);
}
template <typename FwdIt, typename Predicate>
int impl_move_items(entity_descriptor const e, FwdIt const first, FwdIt const last, Predicate pred) {
return impl_move_items(e, first, last, pred, 0);
}
//@}
bool update_items(const_entity_descriptor const e) {
auto const player = player_descriptor();
return (e == player) && (update_item_list(player), true);
}
template <typename From, typename To>
static void update_items(From&&, To&&) {
}
template <typename From, typename To>
void update_items(from_t<descriptor_base<From, entity_definition>> const from, To&&) {
update_items(from);
}
template <typename From, typename To>
void update_items(From&&, to_t<descriptor_base<To, entity_definition>> const to) {
update_items(to);
}
template <typename From, typename To>
void update_items(
from_t<descriptor_base<From, entity_definition>> const from
, to_t<descriptor_base<To, entity_definition>> const to
) {
update_items(from) || update_items(to);
}
//! The @p subject attempts to move items from @p from to @p to.
//! @returns The number of items successfully moved.
//! @tparam Predicate bool (const_item_descriptor, FwdIt::value_type)
//! @tparam Callback void (bool, item_descriptor, FwdIt::value_type)
template <typename FwdIt, typename From, typename To, typename Predicate
, typename Callback>
int move_items(
string_buffer_base& result
, FwdIt const first
, FwdIt const last
, subject_t<entity_descriptor> const subject
, from_t<From> const from
, to_t<To> const to
, Predicate pred
, Callback callback
) {
using I = std::decay_t<decltype(*first)>;
auto const n = impl_move_items(from, first, last, [&](unique_item&& itm, I const i) {
auto const id = itm.get();
auto const obj = p_object(item_descriptor {ctx, id});
result.clear();
if (!pred(const_item_descriptor {obj}, i)
|| !can_remove_item(ctx, subject, from, obj, result)
|| !can_add_item(ctx, subject, obj, to, result)
) {
callback(false, obj, i);
return false;
}
callback(true, obj, i);
merge_into_pile(ctx, std::move(itm), obj, to);
return true;
});
if (n > 0) {
update_items(from, to);
}
return n;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Commands
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void do_follow_path(point2i32 const from, point2i32 const to) {
auto const& path = current_level().find_path(from, to);
if (path.empty()) {
println("You don't know how to get there from here.");
return;
}
player_path_.assign(begin(path), end(path));
constexpr auto timer_name = djb2_hash_32c("do_follow_path timer");
// add an input context that automatically terminates the run on
// player input
input_context c {__func__};
c.on_mouse_button_handler = [=](auto, auto) {
timers.remove(timer_name);
return event_result::filter_detach;
};
c.on_command_handler = [=](auto, auto) {
timers.remove(timer_name);
return event_result::filter_detach;
};
auto const context_id = context_stack.push(std::move(c));
using namespace std::chrono;
constexpr auto delay = duration_cast<nanoseconds>(seconds {1}) / 100;
auto& lvl = current_level();
auto p = player_location();
auto it = begin(player_path_);
auto const last = end(player_path_);
BK_ASSERT(it != last && p == *it);
timers.add(timer_name, timer::duration {0}
, [=, &lvl]
(timer::duration, timer::timer_data) mutable -> timer::duration {
if (++it == last) {
context_stack.pop(context_id);
return timer::duration {};
}
auto const next_p = *it;
// TODO: this could be "slow"
auto const player = player_descriptor();
auto const result = impl_player_move_by_(lvl, player, p, next_p - p);
if (result != placement_result::ok) {
context_stack.pop(context_id);
return timer::duration {};
}
p = next_p;
return delay;
});
}
void do_view() {
auto const p = player_location();
set_highlighted_tile(p);
input_context c;
c.on_mouse_button_handler =
[&](mouse_event const event, kb_modifiers const kmods) {
using mbc = mouse_event::button_change_t;
auto const ok =
(event.button_change[0] == mbc::went_down)
&& (kmods.none());
if (ok) {
set_highlighted_tile(
window_to_world({event.x, event.y}));
}
return event_result::filter;
};
c.on_command_handler =
[=](command_type const type, uint64_t) {
using ct = command_type;
BK_DISABLE_WSWITCH_ENUM_BEGIN
switch (type) {
case ct::reset_view : BK_ATTRIBUTE_FALLTHROUGH;
case ct::reset_zoom :
return event_result::pass_through;
case ct::cancel :
highlighted_tile = point2i32 {-1, -1}; // TODO
r_map.highlight_clear();
tool_tip.visible(false);
adjust_view_to_player(p);
return event_result::filter_detach;
case ct::move_n : update_highlighted_tile({ 0, -1}); break;
case ct::move_ne : update_highlighted_tile({ 1, -1}); break;
case ct::move_e : update_highlighted_tile({ 1, 0}); break;
case ct::move_se : update_highlighted_tile({ 1, 1}); break;
case ct::move_s : update_highlighted_tile({ 0, 1}); break;
case ct::move_sw : update_highlighted_tile({-1, 1}); break;
case ct::move_w : update_highlighted_tile({-1, 0}); break;
case ct::move_nw : update_highlighted_tile({-1, -1}); break;
default:
break;
}
BK_DISABLE_WSWITCH_ENUM_END
return event_result::filter;
};
context_stack.push(std::move(c));
}
void do_cancel() {
item_list.cancel_modal() || item_list.cancel_selection()
|| item_list.cancel_all()
|| equip_list.cancel_modal()
|| equip_list.cancel_selection()
|| equip_list.cancel_all();
}
void do_toggle_inventory() {
if (item_list.is_visible()) {
if (!item_list.is_modal()) {
item_list.set_modal(true);
}
return;
}
if (!item_list.toggle_visible()) {
return;
}
do_view_inventory();
}
void do_toggle_equipment() {
if (equip_list.is_visible()) {
if (!equip_list.is_modal()) {
equip_list.set_modal(true);
}
return;
}
if (!equip_list.toggle_visible()) {
return;
}
do_view_equipment();
}
//! Update the equipment list window
//! TODO: currently this just repopulates the window from scratch each time
//! this could be implemented more intelligently to only add / remove
//! what is actually required.
void update_equipment_list(const_entity_descriptor const e) {
if (!equip_list.is_visible()) {
return;
}
auto const i = equip_list.get().indicated();
equip_list.clear();
equip_list.append_if(e->body_begin(), e->body_end()
, [&](body_part const& p) { return !p.is_free(); }
, [&](body_part const& p) { return p.equip; }
);
equip_list.layout();
equip_list.get().indicate(i);
}
//! Update the item list window
//! TODO: currently this just repopulates the window from scratch each time
//! this could be implemented more intelligently to only add / remove
//! what is actually required.
void update_item_list(const_entity_descriptor const e, int indicated = -1) {
if (!item_list.is_visible()) {
return;
}
if (indicated < 0) {
indicated = item_list.get().indicated();
}
item_list.assign(e->items());
item_list.get().indicate(indicated);
}
void do_view_equipment() {
auto const player = player_descriptor();
using ct = command_type;
using ft = item_list_controller::flag_type;
equip_list.set_properties(
"Equipment", {ft::visible, ft::multiselect, ft::modal});
update_equipment_list(player);
equip_list.set_on_command([=](command_type const cmd) {
if (cmd == ct::confirm) {
if (try_unequip_selected_items(player)) {
update_equipment_list(player);
update_item_list(player);
}
} else if (cmd == ct::cancel) {
if (!equip_list.cancel_modal()
&& !equip_list.cancel_selection()
) {
return event_result::filter_detach;
}
}
return event_result::filter;
});
}
// Attempt to equip the items currently selected in the item list.
int try_equip_selected_items(entity_descriptor const subject) {
static_string_buffer<128> buffer;
auto const result = item_list.for_each_selected([&](item_instance_id const id) {
auto const itm = item_descriptor {ctx, id};
buffer.clear();
auto const ok = boken::try_equip_item(ctx
, p_subject(subject)
, p_from(subject)
, p_object(itm)
, p_to(subject)
, buffer);
println(buffer);
return ok;
});
return result;
}
// Attempt to unequip the items currently selected in the item list.
int try_unequip_selected_items(entity_descriptor const subject) {
static_string_buffer<128> buffer;
auto const result = equip_list.for_each_selected([&](item_instance_id const id) {
auto const itm = item_descriptor {ctx, id};
buffer.clear();
auto const ok = boken::try_unequip_item(ctx
, p_subject(subject)
, p_from(subject)
, p_object(itm)
, p_to(subject)
, buffer);
println(buffer);
return ok;
});
return result;
}
void do_view_inventory() {
auto const player = player_descriptor();
using ct = command_type;
using ft = item_list_controller::flag_type;
item_list.set_properties(
"Inventory", {ft::modal, ft::multiselect, ft::visible});
item_list.set_on_command([=](command_type const cmd) mutable {
BK_DISABLE_WSWITCH_ENUM_BEGIN
switch (cmd) {
case ct::none:
update_item_list(player);
break;
case ct::alt_drop_some:
if (player_drop_selected_items(p_from(player))) {
update_item_list(player);
}
break;
case ct::cancel:
if (item_list.cancel_modal() || item_list.cancel_selection()) {
break;
}
return event_result::filter_detach;
case ct::alt_open:
view_indicated_container();
break;
case ct::alt_insert:
insert_into_indicated_container();
break;
case ct::alt_equip:
if (try_equip_selected_items(player)) {
update_equipment_list(player);
update_item_list(player);
}
break;
default:
break;
}
BK_DISABLE_WSWITCH_ENUM_END
return event_result::filter;
});
}
//! Pickup 0..N items from a list at the player's current position.
void do_get_items() {
impl_do_get_items_(2);
}
//! Pickup all items at the player's current position.
void do_get_all_items() {
impl_do_get_items_(-1);
}
//! Drop zero or one items from the player's inventory at the player's
//! current position.
void do_drop_one() {
impl_do_drop_items_(1);
}
//! Drop zero or more items from the player's inventory at the player's
//! current position.
void do_drop_some() {
impl_do_drop_items_(2);
}
void do_open() {
auto const is_container = [&](item_instance_id const id) noexcept {
return boken::is_container({ctx, id}) > 0;
};
auto const find_containers = [&](item_pile const* const pile) noexcept {
return find_matching_items(pile, is_container);
};
auto const choose_container = [=](auto const first, auto const second, auto const last) {
item_list.clear();
item_list.append({*first, *second});
item_list.append_if(std::next(second), last, is_container);
item_list.layout();
auto const handler = [&](command_type const cmd) {
if (cmd == command_type::cancel) {
println("Nevermind.");
return event_result::filter_detach;
}
bool const do_open = (cmd == command_type::confirm)
|| (cmd == command_type::alt_open);
if (!do_open) {
return event_result::filter;
}
view_indicated_container();
return event_result::filter_detach;
};
choose_single_item("Open which container?", handler);
};
auto const check_floor = [&] {
// First, check for containers on the floor at the player's position.
auto& lvl = current_level();
auto const result = find_containers(lvl.item_at(player_location()));
auto const matches = std::get<0>(result);
auto const first = std::get<1>(result);
auto const second = std::get<2>(result);
auto const last = std::get<3>(result);
if (matches == 1) {
// Just one match; view it
view_container({ctx, *first});
} else if (matches == 2) {
// There are at least two containers here; build a list and let
// the player decide which to view.
choose_container(first, second, last);
}
return matches;
};
if (check_floor()) {
return;
}
println("There is nothing here to open.");
// There are no containers on the floor, but check if the player is
// holding any.
auto const player = player_descriptor();
auto const result = find_containers(&items(player));
auto const matches = std::get<0>(result);
auto const first = std::get<1>(result);
auto const second = std::get<2>(result);
auto const last = std::get<3>(result);
if (matches == 1) {
// The player has just one container; ask if they want to open it.
auto const container = item_descriptor {ctx, *first};
static_string_buffer<128> buffer;
buffer.append("Open the %s in your inventory? y/n"
, name_of_decorated(ctx, container).data());
println(buffer);
query_yes_no([=](command_type const cmd) {
if (cmd == command_type::confirm) {
view_container(container);
}
});
} else if (matches == 2) {
// The player has more than one container; ask whether they want to
// open one of those instead.
println("Open a container in your inventory? y/n");
query_yes_no([=](command_type const cmd) {
if (cmd == command_type::confirm) {
choose_container(first, second, last);
}
});
} else {
BK_ASSERT(matches == 0);
}
}
void do_debug_teleport_self() {
println("Teleport where?");
input_context c;
c.on_mouse_button_handler =
[&](mouse_event const event, kb_modifiers const kmods) {
if (event.button_state_bits() != 1u) {
return event_result::filter;
}
auto const result =
do_player_move_to(window_to_world({event.x, event.y}));
if (result != placement_result::ok) {
println("Invalid destination. Choose another.");
return event_result::filter;
}
println("Done.");
return event_result::filter_detach;
};
c.on_command_handler =
[&](command_type const type, uint64_t) {
if (type == command_type::debug_teleport_self) {
println("Already teleporting.");
return event_result::filter;
} else if (type == command_type::cancel) {
println("Canceled teleporting.");
return event_result::filter_detach;
}
return event_result::filter;
};
context_stack.push(std::move(c));
}
int get_entity_loot(entity_descriptor const e, level_location const loc) {
auto const result = e->items().remove_if([&](unique_item&& itm, int) {
auto const i = item_descriptor {ctx, itm.get()};
merge_into_pile(ctx, std::move(itm), i, loc);
return true;
});
if (result > 0 && &loc.lvl == ¤t_level()) {
renderer_update_pile(loc);
}
return result;
}
void do_kill(level& lvl, entity_descriptor const e, point2i32 const p) {
auto const ent = lvl.remove_entity_at(p);
BK_ASSERT(!!ent && ent.get() == e->instance());
static_string_buffer<128> buffer;
buffer.append("The %s dies.", name_of_decorated(ctx, e).data());
println(buffer);
get_entity_loot(e, {current_level(), p});
if (&lvl == ¤t_level()) {
r_map.remove_entity_at(p);
}
}
void do_combat(point2i32 const att_pos, point2i32 const def_pos) {
auto& lvl = the_world.current_level();
auto ents = lvl.entities_at(att_pos, def_pos);
auto const att = entity_descriptor {ctx, require(ents[0])};
auto const def = entity_descriptor {ctx, require(ents[1])};
def.obj.modify_health(-1);
if (!def.obj.is_alive()) {
do_kill(lvl, def, def_pos);
}
advance(1);
}
//! Attempt to change levels at the current player position.
//! @param type Must be either command_type::move_down or
//! command_type::move_up.
void do_change_level(command_type const type) {
BK_ASSERT(type == command_type::move_down
|| type == command_type::move_up);
auto& cur_lvl = the_world.current_level();
auto const delta = [&]() noexcept {
auto const tile = cur_lvl.at(player_location());
auto const tile_code = (tile.id == tile_id::stair_down) ? 0b01
: (tile.id == tile_id::stair_up) ? 0b10
: 0b00;
auto const move_code = (type == command_type::move_down) ? 0b01
: (type == command_type::move_up) ? 0b10
: 0b00;
switch ((move_code << 2) | tile_code) {
case 0b0100 : // move_down & other
case 0b1000 : // move_up & other
println("There are no stairs here.");
break;
case 0b0101 : // move_down & stair_down
return 1;
case 0b1010 : // move_up & stair_up
return -1;
case 0b0110 : // move_down & stair_up
println("You can't go down here.");
break;
case 0b1001 : // move_up & stair_down
println("You can't go up here.");
break;
default:
BK_ASSERT(false); // some other command was given
break;
}
return 0;
}();
if (delta == 0) {
return;
}
auto const id = static_cast<ptrdiff_t>(cur_lvl.id());
if (id + delta < 0) {
println("You can't leave.");
return;
}
auto const next_id = static_cast<size_t>(id + delta);
auto player_ent = cur_lvl.remove_entity(player_id());
BK_ASSERT(!!player_ent);
if (!the_world.has_level(next_id)) {
generate(next_id);
} else {
set_current_level(next_id, false);
}
// the level has been changed at this point; cur_lvl will have been
// invalidated
auto& nxt_lvl = current_level();
BK_ASSERT(&cur_lvl != &nxt_lvl);
auto const p = (delta > 0)
? nxt_lvl.stair_up(0)
: nxt_lvl.stair_down(0);
add_object_near(std::move(player_ent), {nxt_lvl, p}, 5, rng_substantive);
reset_view_to_player();
}
void do_player_run(vec2i32 const v) {
BK_ASSERT(value_cast(abs(v.x)) <= 1
&& value_cast(abs(v.y)) <= 1
&& v != vec2i32 {});
constexpr auto timer_name = djb2_hash_32c("run timer");
// add an input context that automatically terminates the run on
// player input
input_context c {__func__};
c.on_mouse_button_handler = [=](auto, auto) {
timers.remove(timer_name);
return event_result::filter_detach;
};
c.on_command_handler = [=](auto, auto) {
timers.remove(timer_name);
return event_result::filter_detach;
};
auto const context_id = context_stack.push(std::move(c));
using namespace std::chrono;
constexpr auto delay = duration_cast<nanoseconds>(seconds {1}) / 100;
auto& lvl = current_level();
auto p = player_location();
timers.add(timer_name, timer::duration {0}
, [=, &lvl, count = 0]
(timer::duration, timer::timer_data) mutable -> timer::duration {
// TODO: this could be "slow"
auto const player = player_descriptor();
auto const result = impl_player_move_by_(lvl, player, p, v);
// continue running
if (result == placement_result::ok) {
++count;
p += v;
return delay;
}
// hit something before even moving one tile
if (result == placement_result::failed_obstacle && count == 0) {
auto const q = p + v;
if (lvl.at(q).type == tile_type::door) {
interact_door(player, p, q);
}
}
context_stack.pop(context_id);
return timer::duration {};
});
}
placement_result impl_player_move_by_(
level& lvl
, entity_descriptor const player
, point2i32 const p
, vec2i32 const v
) {
auto const result = lvl.move_by(player.obj.instance(), v);
if (result != placement_result::ok) {
return result;
}
auto const p0 = p + v;
BK_ASSERT(player_location() == p0);
adjust_view_to_player(p0);
r_map.move_object(p, p0, player.obj.definition());
advance(1);
return result;
}
placement_result do_player_move_by(vec2i32 const v) {
BK_ASSERT(value_cast(abs(v.x)) <= 1
&& value_cast(abs(v.y)) <= 1
&& v != vec2i32 {});
auto const player = player_descriptor();
auto const p_cur = player_location();
auto const p_dst = p_cur + v;
auto const result = impl_player_move_by_(current_level(), player, p_cur, v);
switch (result) {
case placement_result::ok:
break;
case placement_result::failed_entity:
do_combat(p_cur, p_dst);
break;
case placement_result::failed_obstacle:
interact_obstacle(player, p_cur, p_dst);
break;
case placement_result::failed_bounds:
break;
case placement_result::failed_bad_id:
// the player id should always be valid
BK_ATTRIBUTE_FALLTHROUGH;
default :
BK_ASSERT(false);
break;
}
return result;
}
placement_result do_player_move_to(point2i32 const p) {
auto const p_cur = player_location();
auto const p_dst = p;
auto const player = player_descriptor();
auto const result = current_level().move_by(player_id(), p_dst - p_cur);
switch (result) {
case placement_result::ok:
r_map.move_object(p_cur, p_dst, player.obj.definition());
break;
case placement_result::failed_entity: BK_ATTRIBUTE_FALLTHROUGH;
case placement_result::failed_obstacle: BK_ATTRIBUTE_FALLTHROUGH;
case placement_result::failed_bounds: BK_ATTRIBUTE_FALLTHROUGH;
case placement_result::failed_bad_id:
break;
default:
BK_ASSERT(false);
break;
}
return result;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Object creation
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
unique_entity create_object(entity_definition const& def, random_state& rng) {
return boken::create_object(database, the_world, def, rng);
}
unique_item create_object(item_definition const& def, random_state& rng) {
return boken::create_object(database, the_world, def, rng);
}
entity_instance_id create_object_at(entity_definition const& def, level_location const loc, random_state& rng) {
return loc->add_object_at(create_object(def, rng), loc);
}
item_instance_id create_object_at(item_definition const& def, level_location const loc, random_state& rng) {
return loc->add_object_at(create_object(def, rng), loc);
}
void create_object(item_definition const& def, item_instance_id const container, random_state& rng) {
auto i = create_object(def, rng);
auto const itm = item_descriptor {ctx, i.get()};
auto const dst = item_descriptor {ctx, container};
merge_into_pile(ctx, std::move(i), itm, dst);
}
point2i32 add_object_near(
unique_entity&& e
, level_location const loc
, int32_t const distance
, random_state& rng
) {
auto const result =
loc->find_valid_entity_placement_neareast(rng, loc, distance);
BK_ASSERT(result.second == placement_result::ok);
auto const p = result.first;
if (&loc.lvl == ¤t_level()) {
const_entity_descriptor const ent {ctx, e.get()};
r_map.add_object_at(p, ent->definition());
}
loc->add_object_at(std::move(e), p);
return p;
}
item_instance_id add_object_at(unique_item&& i, level_location const loc) {
BK_ASSERT(!!i);
if (&loc.lvl == ¤t_level()) {
auto const itm = const_item_descriptor {ctx, i.get()};
r_map.add_object_at(loc.p, itm->definition());
}
return loc->add_object_at(std::move(i), loc);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void interact_door(
entity_descriptor const e
, point2i32 const cur_pos
, point2i32 const obstacle_pos
) {
auto& lvl = the_world.current_level();
auto const tile = lvl.at(obstacle_pos);
BK_ASSERT(tile.type == tile_type::door);
auto const id = (tile.id == tile_id::door_ns_closed)
? tile_id::door_ns_open
: tile_id::door_ew_open;
tile_data_set const data {
tile_data {}
, tile_flags {0}
, id
, tile.type
, region_id {}
};
update_tile_at(obstacle_pos, data);
}
void interact_obstacle(
entity_descriptor const e
, point2i32 const cur_pos
, point2i32 const obstacle_pos
) {
auto& lvl = the_world.current_level();
auto const tile = lvl.at(obstacle_pos);
if (tile.type == tile_type::door) {
interact_door(e, cur_pos, obstacle_pos);
}
}
//! Advance the game time by @p steps
void advance(int const steps) {
turn_number += steps;
auto const player = player_id();
auto& lvl = current_level();
lvl.transform_entities(
[&](entity_instance_id const id, point2i32 const p) noexcept {
auto const e = entity_descriptor {ctx, id};
// don't allow the player to move in this fashion
if (id == player) {
return std::make_pair(e, p);
}
// 9 out of 10 times, do nothing
if (random_chance_in_x(rng_superficial, 9, 10)) {
return std::make_pair(e, p);
}
// check for nearby entities
auto const range = lvl.entities_near(p, 5);
// and choose a random one to move toward
auto const it = random_value_in_range(
rng_superficial, range.first, range.second);
// if there are no nearby entities, or the entity picked is
// this very entity, just choose a random direction to move.
if (it == range.second || it->second == id) {
return std::make_pair(e, p + random_dir8(rng_superficial));
}
// move toward a random nearby entity
return std::make_pair(e, p + signof(it->first - p));
}
, [&](entity_descriptor const e
, placement_result const result
, point2i32 const p_before
, point2i32 const p_after
) {
if (result != placement_result::ok) {
return;
}
r_map.move_object(p_before, p_after, e.obj.definition());
});
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Rendering
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//! Update the rendering scale.
//! @pre sx > 0 && sy > 0
void update_view_scale(float const sx, float const sy) noexcept {
update_view(sx, sy, current_view.x_off, current_view.y_off);
}
void update_view_scale(point2f const scale) noexcept {
update_view_scale(value_cast(scale.x), value_cast(scale.y));
}
//! Update the rendering offset (translation).
void update_view_trans(float const dx, float const dy) {
update_view(current_view.scale_x, current_view.scale_y, dx, dy);
}
void update_view_trans(point2f const trans) noexcept {
update_view_trans(value_cast(trans.x), value_cast(trans.y));
}
//! Update the rendering transformation matrix.
//! @pre sx > 0 && sy > 0
void update_view(float const sx, float const sy
, float const dx, float const dy
) noexcept {
BK_ASSERT(sx > 0.0f && sy > 0.0f);
current_view.scale_x = sx;
current_view.scale_y = sy;
current_view.x_off = dx;
current_view.y_off = dy;
update_highlight_tile();
}
void update_view(point2f const scale, point2f const trans) noexcept {
update_view(value_cast(scale.x), value_cast(scale.y)
, value_cast(trans.x), value_cast(trans.y));
}
void renderer_update_pile(point2i32 const p) {
auto const pile = current_level().item_at(p);
if (!pile) {
r_map.remove_item_at(p);
return;
}
r_map.update_object_at(p, get_pile_id(ctx, *pile));
}
void renderer_update_pile(const_level_location const& loc, std::true_type) {
renderer_update_pile(loc.p);
}
template <typename T>
void renderer_update_pile(T&&, std::false_type) {
}
template <typename T>
void renderer_update_pile(T&& t) {
renderer_update_pile(
std::forward<T>(t)
, std::is_convertible<std::decay_t<T>, const_level_location> {});
}
//! Render the game
void render(timepoint_t const last_frame) {
using namespace std::chrono;
constexpr auto frame_time =
duration_cast<nanoseconds>(seconds {1}) / 60;
auto const now = clock_t::now();
auto const delta = now - last_frame;
if (delta < frame_time) {
return;
}
renderer.render(delta, current_view);
last_frame_time = now;
}
//! The main game loop
void run() {
while (os.is_running()) {
timers.update();
os.do_events();
render(last_frame_time);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Data
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
struct state_t {
template <typename T>
using up = std::unique_ptr<T> const;
up<system> system_ptr = make_system();
up<random_state> rng_substantive_ptr = make_random_state();
up<random_state> rng_superficial_ptr = make_random_state();
up<game_database> database_ptr = make_game_database();
up<world> world_ptr = make_world();
up<text_renderer> trender_ptr = make_text_renderer();
up<game_renderer> renderer_ptr = make_game_renderer(*system_ptr, *trender_ptr);
up<command_translator> cmd_translator_ptr = make_command_translator();
up<message_log> messsage_window_ptr = make_message_log(*trender_ptr);
context const ctx = context {*world_ptr, *database_ptr};
up<item_list_controller> item_list_ptr
= make_item_list_controller(make_inventory_list(ctx, *trender_ptr));
up<item_list_controller> equip_list_ptr
= make_item_list_controller(make_inventory_list(ctx, *trender_ptr));
} state {};
system& os = *state.system_ptr;
random_state& rng_substantive = *state.rng_substantive_ptr;
random_state& rng_superficial = *state.rng_superficial_ptr;
game_database& database = *state.database_ptr;
world& the_world = *state.world_ptr;
game_renderer& renderer = *state.renderer_ptr;
text_renderer& trender = *state.trender_ptr;
command_translator& cmd_translator = *state.cmd_translator_ptr;
message_log& message_window = *state.messsage_window_ptr;
item_list_controller& item_list = *state.item_list_ptr;
item_list_controller& equip_list = *state.equip_list_ptr;
context const ctx = context {the_world, database};
timer timers;
map_renderer& r_map = renderer.add_task(
"map renderer", make_map_renderer(), 0);
message_log_renderer& r_message_log = renderer.add_task(
"message log", make_message_log_renderer(trender, message_window), 0);
item_list_renderer& r_equip_list = renderer.add_task(
"equip list", make_item_list_renderer(trender, equip_list.get()), 0);
item_list_renderer& r_item_list = renderer.add_task(
"item list", make_item_list_renderer(trender, item_list.get()), 0);
tool_tip_renderer& tool_tip = renderer.add_task(
"tool tip", make_tool_tip_renderer(trender), 0);
input_context_stack context_stack;
view current_view;
int last_mouse_x = 0;
int last_mouse_y = 0;
point2i32 highlighted_tile {-1, -1};
std::vector<point2i32> player_path_;
int32_t turn_number = 0;
timepoint_t last_frame_time {};
};
} // namespace boken
namespace {
#if defined(BK_NO_TESTS)
void run_tests() {
}
#else
void run_tests() {
using namespace std::chrono;
auto const beg = high_resolution_clock::now();
boken::run_unit_tests();
auto const end = high_resolution_clock::now();
std::printf("Tests took %" PRId64 " microseconds.\n",
duration_cast<microseconds>(end - beg).count());
}
#endif // BK_NO_TESTS
} // namespace
int main(int const argc, char const* argv[]) try {
run_tests();
boken::game_state game;
game.run();
return 0;
} catch (std::exception const& e) {
std::printf("Failed: %s.\n", e.what());
return 1;
} catch (...) {
std::printf("Unexpected failure.\n");
return 1;
}
| 33.587755
| 116
| 0.539081
|
bkentel
|
5925c02a3d9cf6bfdc9156bf666040b79d82ca72
| 4,106
|
cpp
|
C++
|
Chat Homework/ModuleNetworking.cpp
|
MarcFly/Networks-and-Online-Games
|
ba291cbba47eea230f7a52f58625069878f832ec
|
[
"MIT"
] | null | null | null |
Chat Homework/ModuleNetworking.cpp
|
MarcFly/Networks-and-Online-Games
|
ba291cbba47eea230f7a52f58625069878f832ec
|
[
"MIT"
] | null | null | null |
Chat Homework/ModuleNetworking.cpp
|
MarcFly/Networks-and-Online-Games
|
ba291cbba47eea230f7a52f58625069878f832ec
|
[
"MIT"
] | null | null | null |
#include "Networks.h"
#include "ModuleNetworking.h"
static uint8 NumModulesUsingWinsock = 0;
void ModuleNetworking::reportError(const char* inOperationDesc)
{
LPVOID lpMsgBuf;
DWORD errorNum = WSAGetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorNum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL);
ELOG("Error %s: %d- %s", inOperationDesc, errorNum, lpMsgBuf);
}
void ModuleNetworking::disconnect()
{
for (SOCKET socket : sockets)
{
shutdown(socket, 2);
closesocket(socket);
}
sockets.clear();
}
bool ModuleNetworking::init()
{
if (NumModulesUsingWinsock == 0)
{
NumModulesUsingWinsock++;
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0)
{
reportError("ModuleNetworking::init() - WSAStartup");
return false;
}
}
return true;
}
bool ModuleNetworking::preUpdate()
{
if (sockets.empty()) return true;
int err_ret;
// NOTE(jesus): You can use this temporary buffer to store data from recv()
const uint32 incomingDataBufferSize = Kilobytes(1);
byte incomingDataBuffer[incomingDataBufferSize];
// TODO(jesus): select those sockets that have a read operation available
fd_set readSet;
FD_ZERO(&readSet);
for (int i = 0; i < sockets.size(); ++i) FD_SET(sockets[i], &readSet);
fd_set writeSet(readSet);
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
err_ret = select(0, &readSet, &writeSet, nullptr, &timeout);
if (err_ret == SOCKET_ERROR)
{
reportError("Error Selecting Sockets to read Data.");
return false;
}
// TODO(jesus): for those sockets selected, check wheter or not they are
// a listen socket or a standard socket and perform the corresponding
std::vector<SOCKET> connected;
for (int i= 0; i < sockets.size(); ++i)
{
SOCKET s = sockets[i];
connected.push_back(s);
if (FD_ISSET(s, &readSet))
{
if (isListenSocket(s))
{
// On accept() success, communicate the new connected socket to the
// subclass (use the callback onSocketConnected()), and add the new
// connected socket to the managed list of sockets.
sockaddr_in in;
int len = sizeof(in);
SOCKET ret_sock = accept(s, (sockaddr*)&in, &len);
if (ret_sock == INVALID_SOCKET)
{
reportError("Error Accepting Incoming Connection.");
continue;
}
addSocket(ret_sock);
onSocketConnected(ret_sock, in);
}
else
{
// On recv() success, communicate the incoming data received to the
// subclass (use the callback onSocketReceivedData()).
// TODO(jesus): handle disconnections. Remember that a socket has been
// disconnected from its remote end either when recv() returned 0,
// or when it generated some errors such as ECONNRESET.
// Communicate detected disconnections to the subclass using the callback
// onSocketDisconnected().
InputMemoryStream packet;
err_ret = recv(s, packet.GetBufferPtr(),packet.GetCapacity(),0);
if (err_ret > 0)
{
packet.SetSize((uint32)err_ret);
onSocketReceivedData(s, packet);
}
else
{
if (err_ret == SOCKET_ERROR)
{
reportError("Error Receiving data from a socket.");
}
connected.pop_back();
onSocketDisconnected(s);
}
}
}
}
// TODO(jesus): Finally, remove all disconnected sockets from the list
// of managed sockets.
sockets.swap(connected);
return true;
}
bool ModuleNetworking::cleanUp()
{
disconnect();
NumModulesUsingWinsock--;
if (NumModulesUsingWinsock == 0)
{
if (WSACleanup() != 0)
{
reportError("ModuleNetworking::cleanUp() - WSACleanup");
return false;
}
}
return true;
}
void ModuleNetworking::addSocket(SOCKET socket)
{
sockets.push_back(socket);
}
// Packet Sending Properly
bool ModuleNetworking::sendPacket(const OutputMemoryStream & packet, SOCKET socket)
{
int err_ret = send(socket, packet.GetBufferPtr(), packet.GetSize(), 0);
if (err_ret == SOCKET_ERROR)
{
LOG("Error Sending Packet.");
return false;
}
return true;
}
| 22.437158
| 83
| 0.688261
|
MarcFly
|
59269fe836386ebcf2c11b1f62195a2dec0e695a
| 5,205
|
cpp
|
C++
|
test/hash_trie_test.cpp
|
MatsuTaku/dynpdt_Correction
|
10605c1dc8ae6196741bee0e991935e8877b930a
|
[
"MIT"
] | 47
|
2018-02-24T09:56:24.000Z
|
2022-02-13T12:10:00.000Z
|
test/hash_trie_test.cpp
|
MatsuTaku/dynpdt_Correction
|
10605c1dc8ae6196741bee0e991935e8877b930a
|
[
"MIT"
] | 4
|
2018-03-08T03:28:05.000Z
|
2021-09-29T06:38:25.000Z
|
test/hash_trie_test.cpp
|
MatsuTaku/dynpdt_Correction
|
10605c1dc8ae6196741bee0e991935e8877b930a
|
[
"MIT"
] | 5
|
2018-03-07T06:34:43.000Z
|
2022-02-12T19:54:18.000Z
|
/**
* MIT License
*
* Copyright (c) 2018–2019 Shunsuke Kanda
*
* 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 <gtest/gtest.h>
#include <poplar.hpp>
#include "test_common.hpp"
namespace {
using namespace poplar;
using namespace poplar::test;
template <typename Trie>
void insert_keys(Trie& ht, const std::vector<std::string>& keys, std::vector<uint64_t>& ids) {
ASSERT_FALSE(keys.empty());
ids.resize(ht.capa_size(), UINT64_MAX);
ht.add_root();
auto num_nodes = ht.size();
if constexpr (Trie::trie_type_id == trie_type_ids::FKHASH_TRIE) {
ASSERT_EQ(ht.get_root(), 0);
}
for (uint64_t i = 0; i < keys.size(); ++i) {
auto node_id = ht.get_root();
for (auto c : keys[i]) {
if (ht.add_child(node_id, static_cast<uint8_t>(c))) {
if constexpr (Trie::trie_type_id == trie_type_ids::FKHASH_TRIE) {
ASSERT_EQ(node_id, num_nodes);
}
++num_nodes;
if constexpr (Trie::trie_type_id == trie_type_ids::BONSAI_TRIE) {
if (!ht.needs_to_expand()) {
continue;
}
auto node_map = ht.expand();
node_id = node_map[node_id];
std::vector<uint64_t> new_ids(ht.capa_size(), UINT64_MAX);
for (uint64_t j = 0; j < node_map.size(); ++j) {
if (node_map[j] != UINT64_MAX) {
new_ids[node_map[j]] = ids[j];
}
}
ids = std::move(new_ids);
} else {
if (ids.size() < ht.capa_size()) {
ids.resize(ht.capa_size());
}
}
}
}
ids[node_id] = i;
}
ASSERT_EQ(num_nodes, ht.size());
}
template <typename Trie>
void search_keys(const Trie& ht, const std::vector<std::string>& keys, const std::vector<uint64_t>& ids) {
ASSERT_FALSE(keys.empty());
for (uint64_t i = 0; i < keys.size(); ++i) {
auto node_id = ht.get_root();
for (auto c : keys[i]) {
node_id = ht.find_child(node_id, static_cast<uint8_t>(c));
ASSERT_NE(node_id, Trie::nil_id);
}
ASSERT_EQ(i, ids[node_id]);
}
}
template <typename Trie>
void restore_keys(const Trie& ht, const std::vector<std::string>& keys, const std::vector<uint64_t>& ids) {
ASSERT_FALSE(keys.empty());
if constexpr (Trie::trie_type_id == trie_type_ids::BONSAI_TRIE) {
std::string restore;
for (uint64_t i = 0; i < ids.size(); ++i) {
if (ids[i] == UINT64_MAX) {
continue;
}
restore.clear();
uint64_t node_id = i;
while (node_id != ht.get_root()) {
auto ps = ht.get_parent_and_symb(node_id);
ASSERT_NE(ps.first, Trie::nil_id);
node_id = ps.first;
restore += static_cast<char>(ps.second);
}
std::reverse(restore.begin(), restore.end());
ASSERT_EQ(restore, keys[ids[i]]);
}
}
}
template <typename>
class hash_trie_test : public ::testing::Test {};
using hash_trie_types =
::testing::Types<plain_fkhash_trie<>, plain_bonsai_trie<>, compact_fkhash_trie<>, compact_bonsai_trie<>>;
TYPED_TEST_CASE(hash_trie_test, hash_trie_types);
TYPED_TEST(hash_trie_test, tiny) {
TypeParam ht{0, 8};
auto keys = make_tiny_keys();
std::vector<uint64_t> ids;
insert_keys(ht, keys, ids);
search_keys(ht, keys, ids);
restore_keys(ht, keys, ids);
}
TYPED_TEST(hash_trie_test, words) {
TypeParam ht{20, 8};
auto keys = load_keys("words.txt");
std::vector<uint64_t> ids;
insert_keys(ht, keys, ids);
search_keys(ht, keys, ids);
restore_keys(ht, keys, ids);
}
TYPED_TEST(hash_trie_test, words_ex) {
TypeParam ht{0, 8};
auto keys = load_keys("words.txt");
std::vector<uint64_t> ids;
insert_keys(ht, keys, ids);
search_keys(ht, keys, ids);
restore_keys(ht, keys, ids);
}
} // namespace
| 31.737805
| 109
| 0.593084
|
MatsuTaku
|
592def4ca2fbc6e4352cc3a5e43b85d3dedadc88
| 11,158
|
cpp
|
C++
|
tf2_src/game/server/tf/bot_npc/bot_npc_archer.cpp
|
IamIndeedGamingAsHardAsICan03489/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | 4
|
2021-10-03T05:16:55.000Z
|
2021-12-28T16:49:27.000Z
|
tf2_src/game/server/tf/bot_npc/bot_npc_archer.cpp
|
Counter2828/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | null | null | null |
tf2_src/game/server/tf/bot_npc/bot_npc_archer.cpp
|
Counter2828/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | 3
|
2022-02-02T18:09:58.000Z
|
2022-03-06T18:54:39.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
// bot_npc_archer.cpp
// A NextBot non-player derived archer
// Michael Booth, November 2010
#include "cbase.h"
#include "tf_player.h"
#include "tf_gamerules.h"
#include "tf_team.h"
#include "tf_projectile_arrow.h"
#include "tf_weapon_grenade_pipebomb.h"
#include "nav_mesh/tf_nav_area.h"
#include "bot_npc_archer.h"
#include "NextBot/Path/NextBotChasePath.h"
#include "econ_wearable.h"
#include "team_control_point_master.h"
#include "particle_parse.h"
#include "CRagdollMagnet.h"
#include "NextBot/Behavior/BehaviorMoveTo.h"
ConVar tf_bot_npc_archer_health( "tf_bot_npc_archer_health", "100", FCVAR_CHEAT );
ConVar tf_bot_npc_archer_speed( "tf_bot_npc_archer_speed", "100", FCVAR_CHEAT );
ConVar tf_bot_npc_archer_shoot_interval( "tf_bot_npc_archer_shoot_interval", "2", FCVAR_CHEAT ); // 2
ConVar tf_bot_npc_archer_arrow_damage( "tf_bot_npc_archer_arrow_damage", "75", FCVAR_CHEAT );
//-----------------------------------------------------------------
// The Bot NPC
//-----------------------------------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( bot_npc_archer, CBotNPCArcher );
PRECACHE_REGISTER( bot_npc_archer );
//-----------------------------------------------------------------------------------------------------
CBotNPCArcher::CBotNPCArcher()
{
ALLOCATE_INTENTION_INTERFACE( CBotNPCArcher );
m_locomotor = new NextBotGroundLocomotion( this );
m_body = new CBotNPCBody( this );
m_eyeOffset = vec3_origin;
m_homePos = vec3_origin;
}
//-----------------------------------------------------------------------------------------------------
CBotNPCArcher::~CBotNPCArcher()
{
DEALLOCATE_INTENTION_INTERFACE;
if ( m_locomotor )
delete m_locomotor;
if ( m_body )
delete m_body;
}
//-----------------------------------------------------------------------------------------------------
void CBotNPCArcher::Precache()
{
BaseClass::Precache();
PrecacheModel( "models/player/sniper.mdl" );
PrecacheModel( "models/weapons/c_models/c_bow/c_bow.mdl" );
}
//-----------------------------------------------------------------------------------------------------
void CBotNPCArcher::Spawn( void )
{
BaseClass::Spawn();
SetModel( "models/player/sniper.mdl" );
m_bow = (CBaseAnimating *)CreateEntityByName( "prop_dynamic" );
if ( m_bow )
{
m_bow->SetModel( "models/weapons/c_models/c_bow/c_bow.mdl" );
// bonemerge into our model
m_bow->FollowEntity( this, true );
}
int health = tf_bot_npc_archer_health.GetInt();
SetHealth( health );
SetMaxHealth( health );
ChangeTeam( TF_TEAM_RED );
Vector headPos;
QAngle headAngles;
if ( GetAttachment( "head", headPos, headAngles ) )
{
m_eyeOffset = headPos - GetAbsOrigin();
}
m_homePos = GetAbsOrigin();
}
//---------------------------------------------------------------------------------------------
unsigned int CBotNPCArcher::PhysicsSolidMaskForEntity( void ) const
{
// Only collide with the other team
int teamContents = ( GetTeamNumber() == TF_TEAM_RED ) ? CONTENTS_BLUETEAM : CONTENTS_REDTEAM;
return BaseClass::PhysicsSolidMaskForEntity() | teamContents;
}
//---------------------------------------------------------------------------------------------
bool CBotNPCArcher::ShouldCollide( int collisionGroup, int contentsMask ) const
{
if ( collisionGroup == COLLISION_GROUP_PLAYER_MOVEMENT )
{
switch( GetTeamNumber() )
{
case TF_TEAM_RED:
if ( !( contentsMask & CONTENTS_REDTEAM ) )
return false;
break;
case TF_TEAM_BLUE:
if ( !( contentsMask & CONTENTS_BLUETEAM ) )
return false;
break;
}
}
return BaseClass::ShouldCollide( collisionGroup, contentsMask );
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
class CBotNPCArcherSurrender : public Action< CBotNPCArcher >
{
public:
virtual ActionResult< CBotNPCArcher > OnStart( CBotNPCArcher *me, Action< CBotNPCArcher > *priorAction );
virtual const char *GetName( void ) const { return "Surrender"; } // return name of this action
};
inline ActionResult< CBotNPCArcher > CBotNPCArcherSurrender::OnStart( CBotNPCArcher *me, Action< CBotNPCArcher > *priorAction )
{
CBaseAnimating *bow = me->GetBow();
if ( bow )
{
bow->AddEffects( EF_NODRAW );
}
me->GetBodyInterface()->StartActivity( ACT_MP_STAND_LOSERSTATE );
return Continue();
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
class CBotNPCArcherShootBow : public Action< CBotNPCArcher >
{
public:
CBotNPCArcherShootBow( CTFPlayer *target )
{
m_target = target;
}
virtual ActionResult< CBotNPCArcher > OnStart( CBotNPCArcher *me, Action< CBotNPCArcher > *priorAction );
virtual ActionResult< CBotNPCArcher > Update( CBotNPCArcher *me, float interval );
virtual const char *GetName( void ) const { return "ShootBow"; } // return name of this action
private:
CHandle< CTFPlayer > m_target;
};
//---------------------------------------------------------------------------------------------
ActionResult< CBotNPCArcher > CBotNPCArcherShootBow::OnStart( CBotNPCArcher *me, Action< CBotNPCArcher > *priorAction )
{
if ( !m_target )
{
return Done( "No target" );
}
me->GetLocomotionInterface()->FaceTowards( m_target->WorldSpaceCenter() );
me->AddGesture( ACT_MP_ATTACK_STAND_ITEM2 );
// fire arrow
const float arrowSpeed = 2000.0f;
const float arrowGravity = 0.2f;
Vector muzzleOrigin;
QAngle muzzleAngles;
if ( me->GetBow()->GetAttachment( "muzzle", muzzleOrigin, muzzleAngles ) == false )
{
return Done( "No muzzle attachment!" );
}
// lead target
float range = me->GetRangeTo( m_target->EyePosition() );
float flightTime = range / arrowSpeed;
Vector aimSpot = m_target->EyePosition() + m_target->GetAbsVelocity() * flightTime;
Vector to = aimSpot - muzzleOrigin;
VectorAngles( to, muzzleAngles );
CTFProjectile_Arrow *arrow = CTFProjectile_Arrow::Create( muzzleOrigin, muzzleAngles, arrowSpeed, arrowGravity, TF_PROJECTILE_ARROW, me, me );
if ( arrow )
{
arrow->SetLauncher( me );
arrow->SetCritical( false );
arrow->SetDamage( tf_bot_npc_archer_arrow_damage.GetFloat() );
me->EmitSound( "Weapon_CompoundBow.Single" );
}
return Continue();
}
//---------------------------------------------------------------------------------------------
ActionResult< CBotNPCArcher > CBotNPCArcherShootBow::Update( CBotNPCArcher *me, float interval )
{
if ( me->IsSequenceFinished() )
{
return Done();
}
return Continue();
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
class CBotNPCArcherGuardSpot : public Action< CBotNPCArcher >
{
public:
virtual ActionResult< CBotNPCArcher > OnStart( CBotNPCArcher *me, Action< CBotNPCArcher > *priorAction )
{
me->GetBodyInterface()->StartActivity( ACT_MP_STAND_ITEM2 );
return Continue();
}
CTFPlayer *GetVictim( CBotNPCArcher *me )
{
CUtlVector< CTFPlayer * > playerVector;
CollectPlayers( &playerVector, TF_TEAM_BLUE, COLLECT_ONLY_LIVING_PLAYERS );
CTFPlayer *closeVictim = NULL;
float victimRangeSq = FLT_MAX;
for( int i=0; i<playerVector.Count(); ++i )
{
float rangeSq = me->GetRangeSquaredTo( playerVector[i] );
if ( rangeSq < victimRangeSq )
{
if ( playerVector[i]->m_Shared.IsStealthed() )
{
continue;
}
if ( me->IsLineOfSightClear( playerVector[i] ) )
{
closeVictim = playerVector[i];
victimRangeSq = rangeSq;
}
}
}
return closeVictim;
}
virtual ActionResult< CBotNPCArcher > Update( CBotNPCArcher *me, float interval )
{
if ( TFGameRules()->GetActiveBoss() == NULL )
{
// the Boss has been defeated - give up
return ChangeTo( new CBotNPCArcherSurrender, "The Boss is dead! I give up!" );
}
CTFPlayer *victim = GetVictim( me );
if ( victim )
{
// look at visible victim out of range
me->GetLocomotionInterface()->FaceTowards( victim->WorldSpaceCenter() );
if ( m_shootTimer.IsElapsed() )
{
m_shootTimer.Start( tf_bot_npc_archer_shoot_interval.GetFloat() );
return SuspendFor( new CBotNPCArcherShootBow( victim ), "Fire!" );
}
}
if ( me->GetLocomotionInterface()->IsAttemptingToMove() )
{
// play running animation
if ( !me->GetBodyInterface()->IsActivity( ACT_MP_DEPLOYED_IDLE_ITEM2 ) )
{
me->GetBodyInterface()->StartActivity( ACT_MP_DEPLOYED_IDLE_ITEM2 );
}
}
else
{
// standing still
if ( !me->GetBodyInterface()->IsActivity( ACT_MP_STAND_ITEM2 ) )
{
me->GetBodyInterface()->StartActivity( ACT_MP_STAND_ITEM2 );
}
}
return Continue();
}
virtual const char *GetName( void ) const { return "GuardSpot"; } // return name of this action
private:
CountdownTimer m_shootTimer;
};
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
class CBotNPCArcherMoveToMark : public Action< CBotNPCArcher >
{
public:
virtual ActionResult< CBotNPCArcher > OnStart( CBotNPCArcher *me, Action< CBotNPCArcher > *priorAction )
{
ShortestPathCost cost;
m_path.Compute( me, me->GetHomePosition(), cost );
me->GetBodyInterface()->StartActivity( ACT_MP_RUN_ITEM2 );
return Continue();
}
virtual ActionResult< CBotNPCArcher > Update( CBotNPCArcher *me, float interval )
{
m_path.Update( me );
if ( !m_path.IsValid() )
{
return ChangeTo( new CBotNPCArcherGuardSpot, "Reached my mark" );
}
return Continue();
}
virtual const char *GetName( void ) const { return "MoveToMark"; } // return name of this action
private:
PathFollower m_path;
};
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
class CBotNPCArcherBehavior : public Action< CBotNPCArcher >
{
public:
virtual Action< CBotNPCArcher > *InitialContainedAction( CBotNPCArcher *me )
{
return new CBotNPCArcherMoveToMark;
}
virtual ActionResult< CBotNPCArcher > Update( CBotNPCArcher *me, float interval )
{
return Continue();
}
virtual EventDesiredResult< CBotNPCArcher > OnKilled( CBotNPCArcher *me, const CTakeDamageInfo &info )
{
// Calculate death force
Vector forceVector = me->CalcDamageForceVector( info );
// See if there's a ragdoll magnet that should influence our force.
CRagdollMagnet *magnet = CRagdollMagnet::FindBestMagnet( me );
if ( magnet )
{
forceVector += magnet->GetForceVector( me );
}
me->BecomeRagdoll( info, forceVector );
return TryDone();
}
virtual const char *GetName( void ) const { return "Behavior"; } // return name of this action
};
IMPLEMENT_INTENTION_INTERFACE( CBotNPCArcher, CBotNPCArcherBehavior );
| 27.687345
| 143
| 0.595358
|
IamIndeedGamingAsHardAsICan03489
|
593866676dfae769f1ddc8f8b6bb3e7d815471c6
| 2,003
|
cc
|
C++
|
test/test_timecode.cc
|
ke6jjj/r-dat
|
1e0b55af5f3f71b7a843835804330de0152258e1
|
[
"BSD-2-Clause"
] | 3
|
2020-05-07T02:18:28.000Z
|
2021-08-03T14:00:12.000Z
|
test/test_timecode.cc
|
ke6jjj/r-dat
|
1e0b55af5f3f71b7a843835804330de0152258e1
|
[
"BSD-2-Clause"
] | null | null | null |
test/test_timecode.cc
|
ke6jjj/r-dat
|
1e0b55af5f3f71b7a843835804330de0152258e1
|
[
"BSD-2-Clause"
] | null | null | null |
//
// Copyright 2018, Jeremy Cooper
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "tests.h"
#include "TimeCode.h"
static const int absolute_tests[] = {
0,
99,
100,
101,
1000,
1999,
119999,
};
static const size_t absolute_tests_count =
sizeof(absolute_tests) / sizeof(absolute_tests[0]);
void
test_timecode(TestSession& ts)
{
for (size_t i = 0; i < absolute_tests_count; i++) {
ts.BeginTest("Timecode absolute %d", absolute_tests[i]);
TimeCode t(static_cast<uint32_t>(absolute_tests[i]));
bool result = t.AbsoluteFrame() == absolute_tests[i];
ts.EndTest(result);
}
}
| 31.296875
| 71
| 0.740889
|
ke6jjj
|
86cccfdb22c8c035291ff39414badbf6e1102d7f
| 14,039
|
hpp
|
C++
|
mapA/map.hpp
|
q4x3/dsHomework
|
0097bb7d9e08c68fb782afc0e3e5c348f212ceb5
|
[
"MIT"
] | null | null | null |
mapA/map.hpp
|
q4x3/dsHomework
|
0097bb7d9e08c68fb782afc0e3e5c348f212ceb5
|
[
"MIT"
] | null | null | null |
mapA/map.hpp
|
q4x3/dsHomework
|
0097bb7d9e08c68fb782afc0e3e5c348f212ceb5
|
[
"MIT"
] | null | null | null |
/**
* implement a container like std::map
*/
#ifndef SJTU_MAP_HPP
#define SJTU_MAP_HPP
// only for std::less<T>
#include <functional>
#include <cstddef>
#include "utility.hpp"
#include "exceptions.hpp"
namespace sjtu {
enum color_type {RED, BLACK};
template<
class Key,
class T,
class Compare = std::less<Key>
> class map {
public:
typedef pair<const Key, T> value_type;
private:
struct node {
value_type *data;
node *left, *right, *parent;
color_type color;
node():data(nullptr), left(nullptr), right(nullptr), parent(nullptr), color(RED) {}
node(const value_type &obj,
node* l = nullptr, node* r = nullptr, node* p = nullptr,
color_type co = RED):left(l), right(r), parent(p), color(co) {
data = new value_type(obj);
}
~node() {
if(data) delete(data);
}
// find the nextNode of p
node* nextNode(node* p, node* n, int size) {
if(size == 0) return nullptr;
if(p == n) return nullptr;
if(p->right == n) {
while(p->parent->right == p && p != n) p = p->parent;
return p->parent;
}
p = p->right;
while(p->left != n) p = p->left;
return p;
}
// find the prevNode of p
node* prevNode(node* p, node* n, node* rt, int size) {
if(size == 0) return nullptr;
if(p == n) {
while(rt->right != n) rt = rt->right;
return rt;
}
if(p->left == n) {
while(p->parent->left == p && p != n) p = p->parent;
if(p->parent == n) return nullptr;
return p->parent;
}
p = p->left;
while(p->right != n) p = p->right;
return p;
}
};
// start of data members of map
node *_root, *_nil;
Compare _comparator;
int _size;
// end of data members of map
// start of utilities of map
// if l < r, return -1, l == r, return 0, l > r, return 1
inline int compare(const Key &left, const Key &right) const {
if(_comparator(left, right)) return -1;
else if(_comparator(right, left)) return 1;
else return 0;
}
// if the key exists, return the corresponding node
// if doesn't, return nil
inline node* searchNode(node* rt, const Key &key) const {
int sig;
while(1) {
if(rt == _nil) return rt;
sig = compare(key, rt->data->first);
if(sig == 0) return rt;
else if(sig < 0) rt = rt->left;
else rt = rt->right;
}
}
// a util for fix-up
inline void leftRotate(node* x) {
node* y = x->right;
if(y == _nil) return;
x->right = y->left;
if(y->left != _nil) y->left->parent = x;
y->parent = x->parent;
if(x->parent == _nil) _root = y;
else if(x == x->parent->left) x->parent->left = y;
else x->parent->right = y;
y->left = x;
x->parent = y;
}
// a util for fix-up
inline void rightRotate(node* x) {
node* y = x->left;
if(y == _nil) return;
x->left = y->right;
if(y->right != _nil) y->right->parent = x;
y->parent = x->parent;
if(x->parent == _nil) _root = y;
else if(x == x->parent->left) x->parent->left = y;
else x->parent->right = y;
y->right = x;
x->parent = y;
}
// the fix-up for insert operation
inline void insertFixUp(node* z) {
while(z->parent->color == RED) {
if(z->parent == z->parent->parent->left) {
node *y = z->parent->parent->right;
// case 1
if(y->color == RED) {
z->parent->color = BLACK;
y->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
}
else {
// case 2
if(z == z->parent->right) {
z = z->parent;
leftRotate(z);
}
// case 3
z->parent->color = BLACK;
z->parent->parent->color = RED;
rightRotate(z->parent->parent);
}
}
else {
node *y = z->parent->parent->left;
// case 1
if(y->color == RED) {
z->parent->color = BLACK;
y->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
}
else {
// case 2
if (z == z->parent->left) {
z = z->parent;
rightRotate(z);
}
// case 3
z->parent->color = BLACK;
z->parent->parent->color = RED;
leftRotate(z->parent->parent);
}
}
}
_root->color = BLACK;
}
// if the key already exists, return the corresponding node
// if doesn't, return the inserted node
inline pair<node*, bool> _insert(const value_type &obj) {
node *y = _nil, *x = _root;
Key key = obj.first;
while(x != _nil) {
y = x;
int sig = compare(key, x->data->first);
if(sig == 0) return pair<node*, bool>(x, 0);
else if(sig < 0) x = x->left;
else x = x->right;
}
node *z = new node(obj, nullptr, nullptr, y, RED);
if(y == _nil) _root = z;
else if(compare(key, y->data->first) == -1) y->left = z;
else y->right = z;
z->left = _nil;
z->right = _nil;
insertFixUp(z);
return pair<node*, bool>(z, 1);
}
// a util to delete the sons of node u
inline void _clear(node* u) {
if(u == _nil) return;
_clear(u->left);
_clear(u->right);
delete(u);
}
// a util for erase
// replace u with v
inline void transplant(node* u, node* v) {
node *_u = u;
if(u->parent == _nil) _root = v;
else if(u == u->parent->left) u->parent->left = v;
else u->parent->right = v;
v->parent = u->parent;
}
// the fix-up for erase operation
inline void eraseFixUp(node* x) {
while(x != _root && x->color == BLACK) {
if(x == x->parent->left) {
node *w = x->parent->right;
// case 1
if(w->color == RED) {
w->color = BLACK;
x->parent->color = RED;
leftRotate(x->parent);
w = x->parent->right;
}
// case 2
if(w->left->color == BLACK && w->right->color == BLACK) {
w->color = RED;
x = x->parent;
} else {
// case 3
if(w->right->color == BLACK) {
w->left->color = BLACK;
w->color = RED;
rightRotate(w);
w = x->parent->right;
}
// case 4
w->color = x->parent->color;
x->parent->color = BLACK;
w->right->color = BLACK;
leftRotate(x->parent);
x = _root;
}
} else {
node *w = x->parent->left;
if(w->color == RED) {
w->color = BLACK;
x->parent->color = RED;
rightRotate(x->parent);
w = x->parent->left;
}
if(w->right->color == BLACK && w->left->color == BLACK) {
w->color = RED;
x = x->parent;
} else {
if(w->left->color == BLACK) {
w->right->color = BLACK;
w->color = RED;
leftRotate(w);
w = x->parent->left;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->left->color = BLACK;
rightRotate(x->parent);
x = _root;
}
}
}
x->color = BLACK;
}
// erase operation
inline void _erase(node* z) {
node *y = z, *x;
color_type yOriginalColor = y->color;
if(z->left == _nil) {
x = z->right;
transplant(z, z->right);
}
else if(z->right == _nil) {
x = z->left;
transplant(z, z->left);
}
else {
y = z->right;
while(y->left != _nil) y = y->left;
yOriginalColor = y->color;
x = y->right;
if(y->parent == z) x->parent = y;
else {
transplant(y, y->right);
y->right = z->right;
y->right->parent = y;
}
transplant(z, y);
y->left = z->left;
y->left->parent = y;
y->color = z->color;
}
delete(z);
if(yOriginalColor == BLACK) eraseFixUp(x);
}
// a util for copy operation
inline void copy(node* rt, node* obj, node* nilO) {
if(obj->left) {
if(obj->left == nilO) rt->left = _nil;
else {
rt->left = new node(*(obj->left->data), nullptr, nullptr, rt, obj->left->color);
copy(rt->left, obj->left, nilO);
}
}
if(obj->right) {
if(obj->right == nilO) rt->right = _nil;
else {
rt->right = new node(*(obj->right->data), nullptr, nullptr, rt, obj->right->color);
copy(rt->right, obj->right, nilO);
}
}
}
// end of utilities of map
public:
class const_iterator;
class iterator {
friend class const_iterator;
private:
map* self;
node* pos;
public:
iterator():self(nullptr), pos(nullptr) {}
iterator(const iterator &other):self(other.self), pos(other.pos) {}
iterator(map* _self, node* _pos):self(_self), pos(_pos) {}
iterator operator++(int) {
node *tmp = pos;
pos = pos->nextNode(pos, self->_nil, self->_size);
if(pos == nullptr) throw invalid_iterator();
return iterator(self, tmp);
}
iterator & operator++() {
pos = pos->nextNode(pos, self->_nil, self->_size);
if(pos == nullptr) throw invalid_iterator();
return *this;
}
iterator operator--(int) {
node *tmp = pos;
pos = pos->prevNode(pos, self->_nil, self->_root, self->_size);
if(pos == nullptr) throw invalid_iterator();
return iterator(self, tmp);
}
iterator & operator--() {
pos = pos->prevNode(pos, self->_nil, self->_root, self->_size);
if(pos == nullptr) throw invalid_iterator();
return *this;
}
value_type & operator*() const {
return *(pos->data);
}
bool operator==(const iterator &rhs) const {
return (self == rhs.self) && (pos == rhs.pos);
}
bool operator==(const const_iterator &rhs) const {
return (self == rhs.self) && (pos == rhs.pos);
}
bool operator!=(const iterator &rhs) const {
return (pos != rhs.pos) || (self != rhs.self);
}
bool operator!=(const const_iterator &rhs) const {
return (pos != rhs.pos) || (self != rhs.self);
}
value_type* operator->() const noexcept {
return pos->data;
}
map* getSelf() {
return self;
}
node* getPos() {
return pos;
}
};
class const_iterator {
friend class iterator;
private:
const map* self;
node* pos;
public:
const_iterator():self(nullptr), pos(nullptr) {}
const_iterator(const const_iterator &other):self(other.self), pos(other.pos) {}
const_iterator(const iterator &other):self(other.self), pos(other.pos) {}
const_iterator(const map* _self, node* _pos):self(_self), pos(_pos) {}
const_iterator operator++(int) {
node *tmp = pos;
pos = pos->nextNode(pos, self->_nil, self->_size);
if(pos == nullptr) throw invalid_iterator();
return const_iterator(self, tmp);
}
const_iterator & operator++() {
pos = pos->nextNode(pos, self->_nil, self->_size);
if(pos == nullptr) throw invalid_iterator();
return *this;
}
const_iterator operator--(int) {
node *tmp = pos;
pos = pos->prevNode(pos, self->_nil, self->_root, self->_size);
if(pos == nullptr) throw invalid_iterator();
return const_iterator(self, tmp);
}
const_iterator & operator--() {
pos = pos->prevNode(pos, self->_nil, self->_root, self->_size);
if(pos == nullptr) throw invalid_iterator();
return *this;
}
value_type & operator*() const {
return *(pos->data);
}
bool operator==(const iterator &rhs) const {
return (self == rhs.self) && (pos == rhs.pos);
}
bool operator==(const const_iterator &rhs) const {
return (self == rhs.self) && (pos == rhs.pos);
}
bool operator!=(const iterator &rhs) const {
return (pos != rhs.pos) || (self != rhs.self);
}
bool operator!=(const const_iterator &rhs) const {
return (pos != rhs.pos) || (self != rhs.self);
}
value_type* operator->() const noexcept {
return pos->data;
}
};
map() {
_root = _nil = new node;
_root->parent = _nil;
_nil->left = _nil->right = _nil;
_root->color = BLACK;
_nil->color = BLACK;
_size = 0;
}
map(const map &other) {
_comparator = other._comparator;
_size = other._size;
_root = _nil = new node;
_root->parent = _nil;
_nil->left = _nil->right = _nil;
if(other._root != other._nil) {
_root = new node(*(other._root->data), nullptr, nullptr, _nil, BLACK);
copy(_root, other._root, other._nil);
}
}
map & operator=(const map &other) {
if(&other == this) return *this;
if(_root != _nil) _clear(_root);
_root = _nil;
_root->parent = _nil;
_nil->left = _nil->right = _nil;
if(other._root != other._nil) {
_root = new node(*(other._root->data), nullptr, nullptr, _nil, BLACK);
copy(_root, other._root, other._nil);
}
_size = other._size;
_comparator = other._comparator;
}
~map() {
if(_root != _nil) _clear(_root);
delete(_nil);
}
T & at(const Key &key) {
node *tmp = searchNode(_root, key);
if(tmp == _nil) throw index_out_of_bound();
else return tmp->data->second;
}
const T & at(const Key &key) const {
node *tmp = searchNode(_root, key);
if(tmp == _nil) throw index_out_of_bound();
else return tmp->data->second;
}
T & operator[](const Key &key) {
node *tmp = searchNode(_root, key);
if(tmp == _nil) {
++ _size;
pair<node*, bool> res = _insert(value_type(key, T()));
return (res.first)->data->second;
}
else return tmp->data->second;
}
const T & operator[](const Key &key) const {
node *tmp = searchNode(_root, key);
if(tmp == _nil) throw index_out_of_bound();
else return tmp->data->second;
}
iterator begin() {
if(_size == 0) return iterator(this, _nil);
else {
node *p = _root;
while(p->left != _nil) p = p->left;
return iterator(this, p);
}
}
const_iterator cbegin() const {
if(_size == 0) return const_iterator(this, _nil);
else {
node *p = _root;
while(p->left != _nil) p = p->left;
return const_iterator(this, p);
}
}
iterator end() {
return iterator(this, _nil);
}
const_iterator cend() const {
return const_iterator(this, _nil);
}
bool empty() const {
return _size == 0;
}
size_t size() const {
return _size;
}
void clear() {
if(_root != _nil) _clear(_root);
_root = _nil;
_root->left = nullptr;
_root->right = nullptr;
_size = 0;
}
pair<iterator, bool> insert(const value_type &value) {
node *tmp = searchNode(_root, value.first);
if(tmp == _nil) {
++ _size;
pair<node*, bool> res = _insert(value);
return pair<iterator, bool>(iterator(this, res.first), 1);
}
else return pair<iterator, bool>(iterator(this, tmp), 0);
}
void erase(iterator pos) {
if(pos.getSelf() != this || pos.getPos() == this->_nil) throw invalid_iterator();
-- _size;
_erase(pos.getPos());
}
size_t count(const Key &key) const {
return searchNode(_root, key) != _nil;
}
iterator find(const Key &key) {
return iterator(this, searchNode(_root, key));
}
const_iterator find(const Key &key) const {
return const_iterator(this, searchNode(_root, key));
}
};
}
#endif
| 25.950092
| 87
| 0.588788
|
q4x3
|
86cd1d606a9356bf9909a3667d88fd433cdbce76
| 4,751
|
cpp
|
C++
|
host/display/controller.cpp
|
wmax351/airball-embedded
|
204189922415b0f3cbef5dda14fa137e3c806a7d
|
[
"MIT"
] | null | null | null |
host/display/controller.cpp
|
wmax351/airball-embedded
|
204189922415b0f3cbef5dda14fa137e3c806a7d
|
[
"MIT"
] | null | null | null |
host/display/controller.cpp
|
wmax351/airball-embedded
|
204189922415b0f3cbef5dda14fa137e3c806a7d
|
[
"MIT"
] | null | null | null |
#include "controller.h"
#include "settings.h"
#include "airdata.h"
#include "display.h"
#include "delay_timer.h"
#include "system_status.h"
#include "units.h"
#include "../telemetry/airdata_reduced_sample.h"
#include "file_write_watch.h"
#include "sound_scheme.h"
#include "stallfence_scheme.h"
#include "flyonspeed_scheme.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <vector>
namespace airball {
constexpr static std::chrono::duration<unsigned int, std::milli>
kPaintDelay(33);
const static std::string kStallfenceScheme = "stallfence";
const static std::string kFlyonspeedScheme = "flyonspeed";
template <class T>
class InputQueue {
public:
void put(T t) {
std::lock_guard<std::mutex> guard(mu_);
entries_.push_back(std::move(t));
}
std::vector<T> get() {
std::lock_guard<std::mutex> guard(mu_);
std::vector<T> result;
for (auto it = entries_.begin(); it < entries_.end(); ++it) {
result.push_back(std::move(*it));
}
entries_.clear();
return result;
}
private:
std::mutex mu_;
std::vector<T> entries_;
};
std::chrono::duration<double, std::milli> since(
const std::chrono::steady_clock::time_point t) {
return std::chrono::steady_clock::now() - t;
}
std::ostream& operator<<(
std::ostream &out,
const std::chrono::duration<double, std::milli> &duration) {
out << duration.count();
}
Controller::Controller(Screen* screen,
const std::string& settings_path,
const std::string& audio_device,
TelemetryClient* telemetry)
: screen_(screen),
settings_path_(settings_path),
audio_device_(audio_device),
telemetry_(telemetry) {}
void Controller::run() {
InputQueue<std::unique_ptr<sample>> data;
InputQueue<bool> settings_read;
InputQueue<std::string> log;
bool running = true;
std::thread data_thread([&]() {
while (true) {
data.put(std::move(telemetry_->get()));
if (!running) { break; }
}
});
std::thread settings_thread([&]() {
airball::file_write_watch w(settings_path_);
while (true) {
w.next_event();
settings_read.put(true);
if (!running) { break; }
}
});
std::thread paint_thread([&]() {
Settings settings;
SystemStatus status;
Airdata airdata;
Display display(screen_, &airdata, &settings, &status);
settings.load(settings_path_);
std::unique_ptr<sound_scheme> sound_scheme;
if (settings.sound_scheme() == kStallfenceScheme) {
sound_scheme.reset(new stallfence_scheme(audio_device_,
&settings,
&airdata));
} else if (settings.sound_scheme() == kFlyonspeedScheme) {
sound_scheme.reset(new flyonspeed_scheme(audio_device_,
&settings,
&airdata));
} else {
std::cerr << "Unrecognized sound scheme "
<< settings.sound_scheme() << std::endl;
std::exit(-1);
}
if (!sound_scheme->start()) {
std::cerr << "Sound scheme failed to start" << std::endl;
std::exit(-1);
}
while (true) {
std::vector<bool> settings_reads = settings_read.get();
std::vector<std::unique_ptr<sample>> cycle_data = data.get();
if (settings_reads.size() > 0) {
settings.load(settings_path_);
}
for (auto it = cycle_data.begin(); it < cycle_data.end(); ++it) {
const sample* d = (*it).get();
status.update(d);
const double qnh = kPascalsPerInHg * settings.baro_setting();
// TODO(ihab): Deprecate and remove all "raw airdata" operations from
// the user interface.
auto ad = dynamic_cast<const airdata_sample*>(d);
if (ad != nullptr) {
airdata.update(ad,
qnh,
settings.ball_smoothing_factor(),
settings.vsi_smoothing_factor());
} else {
auto adr = dynamic_cast<const airdata_reduced_sample *>(d);
if (adr != nullptr) {
airdata.update(adr,
qnh,
settings.ball_smoothing_factor(),
settings.vsi_smoothing_factor());
}
}
}
sound_scheme->update();
display.paint();
// TODO(ihab): Build an interrupt triggered paint loop rather than merely
// sleeping for a fixed delay.
std::this_thread::sleep_for(kPaintDelay);
if (!running) { break; }
}
});
data_thread.join();
settings_thread.join();
paint_thread.join();
}
} // namespace airball
| 28.279762
| 79
| 0.588508
|
wmax351
|
86cddbbb23a1fc53e82a2c1f0593350790157699
| 1,259
|
cpp
|
C++
|
products/BellHybrid/apps/application-bell-settings/presenter/FrontlightPresenter.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | 369
|
2021-11-10T09:20:29.000Z
|
2022-03-30T06:36:58.000Z
|
products/BellHybrid/apps/application-bell-settings/presenter/FrontlightPresenter.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | 149
|
2021-11-10T08:38:35.000Z
|
2022-03-31T23:01:52.000Z
|
products/BellHybrid/apps/application-bell-settings/presenter/FrontlightPresenter.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | 41
|
2021-11-10T08:30:37.000Z
|
2022-03-29T08:12:46.000Z
|
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "FrontlightPresenter.hpp"
namespace app::bell_settings
{
FrontlightPresenter::FrontlightPresenter(std::shared_ptr<FrontlightListItemProvider> &&provider,
std::unique_ptr<AbstractFrontlightModel> &&frontlightModel)
: provider{std::move(provider)}, frontlightModel{std::move(frontlightModel)}
{
this->frontlightModel->onReady = [this]() {
for (const auto &item : this->provider->getListItems()) {
item->setValue();
}
};
}
FrontlightPresenter::~FrontlightPresenter()
{
revertUnsavedChanges();
}
auto FrontlightPresenter::getPagesProvider() const -> std::shared_ptr<gui::ListItemProvider>
{
return provider;
}
void FrontlightPresenter::eraseProviderData()
{
provider->clearData();
}
void FrontlightPresenter::saveChanges()
{
frontlightModel->setChangesSaved();
}
void FrontlightPresenter::revertUnsavedChanges()
{
frontlightModel->revertUnsavedChanges();
}
} // namespace app::bell_settings
| 28.613636
| 104
| 0.637014
|
buk7456
|
86ce288813f98e86cbab4bfad2c16ff07d513d0c
| 6,694
|
cpp
|
C++
|
VideoPlayer/src/qtvideowidget.cpp
|
Embedfire/ebf_debian_qt_demo
|
91cd3e9328d7df1e481d2fc12bd83165ad025a80
|
[
"MIT"
] | 1
|
2020-06-19T00:58:32.000Z
|
2020-06-19T00:58:32.000Z
|
VideoPlayer/src/qtvideowidget.cpp
|
Embedfire/ebf_debian_qt_demo
|
91cd3e9328d7df1e481d2fc12bd83165ad025a80
|
[
"MIT"
] | null | null | null |
VideoPlayer/src/qtvideowidget.cpp
|
Embedfire/ebf_debian_qt_demo
|
91cd3e9328d7df1e481d2fc12bd83165ad025a80
|
[
"MIT"
] | null | null | null |
/******************************************************************
Copyright (C) 2019 - All Rights Reserved by
文 件 名 : videowidget.cpp --- VideoWidget
作 者 : Niyh(lynnhua)
论 坛 : http://www.firebbs.cn
编写日期 : 2019
说 明 :
历史纪录 :
<作者> <日期> <版本> <内容>
Niyh 2019 1.0.0 1 文件创建
*******************************************************************/
#include "qtvideowidget.h"
#include "appconfig.h"
#include <QPainter>
#include <QDebug>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QApplication>
#include <QFileInfo>
#include <QApplication>
//////////////////////////////////////////////////////////////////////////////////////
QtVideoWidget::QtVideoWidget(QWidget *parent) : QtWidgetBase(parent)
{
m_urlMedia = QUrl();
m_bToolBarShow = false;
m_nDuration = 0;
m_nPostion = 0;
m_player = new QMediaPlayer(this);
surface = new QtVideoWidgetSurface(this);
m_player->setVideoOutput(surface);
m_playList = new MediaPlayListWidget(this);
m_playList->setVisible(false);
m_player->setPlaylist(m_playList->palyList());
connect(m_player, SIGNAL(durationChanged(qint64)), this, SLOT(SltDurationChanged(qint64)));
connect(m_player, SIGNAL(positionChanged(qint64)), this, SLOT(SltPostionChanged(qint64)));
m_titleBar = new PlayTitleBarWidget(this);
connect(m_playList, SIGNAL(signalMediaChanged(QString)), m_titleBar, SLOT(SetText(QString)));
connect(m_titleBar, SIGNAL(signalBack()), this, SLOT(SltBackClicked()));
m_playBar = new PlayerBarWidget(this);
connect(m_playBar, SIGNAL(signalPlay(bool)), this, SLOT(SltBtnPlayClicked(bool)));
connect(m_playBar, SIGNAL(currentPostionChanged(int)), this, SLOT(SltChangePostion(int)));
connect(m_playBar, SIGNAL(signalPrev()), m_playList->palyList(), SLOT(previous()));
connect(m_playBar, SIGNAL(signalNext()), m_playList->palyList(), SLOT(next()));
connect(m_playBar, SIGNAL(signalMuenList()), this, SLOT(SltShowMenuList()));
connect(m_playBar, SIGNAL(signalVolume()), this, SLOT(SltChangeVolume()));
m_timerShow = new QTimer(this);
m_timerShow->setSingleShot(true);
m_timerShow->setInterval(5000);
connect(m_timerShow, SIGNAL(timeout()), this, SLOT(SltAutoCloseToolBar()));
m_volumeSlider = new QtSliderBar(this);
m_volumeSlider->SetHorizontal(false);
m_volumeSlider->SetValue(100);
m_volumeSlider->hide();
connect(m_volumeSlider, SIGNAL(currentValueChanged(int)), m_player, SLOT(setVolume(int)));
}
QtVideoWidget::~QtVideoWidget()
{
if (m_timerShow->isActive()) {
m_timerShow->stop();
}
AppConfig::m_bPlayVideo = false;
}
void QtVideoWidget::setMedia(const QString &name, int index)
{
m_titleBar->SetText(name);
if (index == m_playList->palyList()->currentIndex()) {
if (m_player->state() == QMediaPlayer::PausedState) {
m_player->play();
} else {
m_player->play();
}
} else {
m_playList->palyList()->setCurrentIndex(index);
m_player->play();
}
AppConfig::m_bPlayVideo = true;
this->setCursor(m_player->state() == QMediaPlayer::PlayingState ?
Qt::BlankCursor : Qt::ArrowCursor);
// 设置播放状态
m_playBar->setPlayState(m_player->state() == QMediaPlayer::PlayingState);
}
void QtVideoWidget::ShowToolBar()
{
m_playList->setVisible(false);
m_volumeSlider->setVisible(false);
m_bToolBarShow = !m_bToolBarShow;
if (m_bToolBarShow) {
m_titleBar->SetAnimation(QPoint(0, -m_titleBar->height()), QPoint(0, 0));
m_playBar->SetAnimation(QPoint(0, this->height()), QPoint(0, this->height() - m_playBar->height()));
} else {
m_titleBar->SetAnimation(QPoint(0, 0), QPoint(0, -m_titleBar->height()));
m_playBar->SetAnimation(QPoint(0, this->height() - m_playBar->height()), QPoint(0, this->height()));
}
this->setCursor(m_bToolBarShow ? Qt::ArrowCursor : Qt::BlankCursor);
}
void QtVideoWidget::SltAutoCloseToolBar()
{
m_playList->setVisible(false);
m_volumeSlider->setVisible(false);
if (m_bToolBarShow) {
ShowToolBar();
}
}
void QtVideoWidget::SltBackClicked()
{
if (m_player->state() == QMediaPlayer::PlayingState) {
m_player->pause();
}
AppConfig::m_bPlayVideo = false;
this->hide();
}
void QtVideoWidget::SltBtnPlayClicked(bool bOk)
{
if (bOk) {
m_player->play();
} else {
m_player->pause();
}
}
void QtVideoWidget::SltPostionChanged(qint64 postion)
{
m_nPostion = postion;
m_playBar->setPostion(postion / 1000);
}
void QtVideoWidget::SltDurationChanged(qint64 duration)
{
m_nDuration = duration;
m_playBar->setDuration(duration / 1000);
}
void QtVideoWidget::SltChangePostion(int postion)
{
m_player->setPosition(postion * 1000);
}
void QtVideoWidget::SltShowMenuList()
{
m_playList->setVisible(!m_playList->isVisible());
m_volumeSlider->setVisible(false);
}
void QtVideoWidget::SltChangeVolume()
{
// QPoint pos = m_titleBar->geometry().topRight();
// m_volumeSlider->move(pos.x() - 80, pos.y() - m_volumeSlider->height() + 20);
m_volumeSlider->setVisible(!m_volumeSlider->isVisible());
}
void QtVideoWidget::resizeEvent(QResizeEvent *event)
{
SetScaleValue();
surface->updateVideoRect();
m_titleBar->resize(this->width(), 50 * m_scaleY);
m_titleBar->move(0, -m_titleBar->height());
m_playBar->resize(this->width(), 102 * m_scaleY);
m_playBar->move(0, this->height() + m_playBar->height());
m_playList->resize(405 * m_scaleX, 328 * m_scaleY);
m_playList->move(this->width() - m_playList->width() + 5, m_titleBar->height() + 2);
m_volumeSlider->resize(36 * m_scaleX, 136 * m_scaleY);
int nW = 4 * m_scaleX;
m_volumeSlider->SetSliderSize(nW < 1 ? 1 : nW, 36 * m_scaleX);
m_volumeSlider->SetValue(m_volumeSlider->value());
m_volumeSlider->move(670 * m_scaleX, 258 * m_scaleY);
QWidget::resizeEvent(event);
}
void QtVideoWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(event->rect(), Qt::black);
if (surface->isActive()) {
surface->paint(&painter);
}
}
void QtVideoWidget::mousePressEvent(QMouseEvent *)
{
m_volumeSlider->setVisible(false);
ShowToolBar();
if (m_timerShow->isActive()) {
m_timerShow->stop();
}
// 有点击重新响应
if (m_bToolBarShow) {
m_timerShow->start();
}
}
| 30.427273
| 109
| 0.623394
|
Embedfire
|
86ce501dacd675dca7cce1979d49b7ede31e287a
| 2,750
|
cc
|
C++
|
src/solv_simple/fn_xor/bdd2specfn_xor.cc
|
nerdling/SBSAT
|
6328c6aa105b75693d06bf0dae4a3b5ca220318b
|
[
"Unlicense"
] | 4
|
2015-03-08T07:56:29.000Z
|
2017-10-12T04:19:27.000Z
|
src/solv_simple/fn_xor/bdd2specfn_xor.cc
|
nerdling/SBSAT
|
6328c6aa105b75693d06bf0dae4a3b5ca220318b
|
[
"Unlicense"
] | null | null | null |
src/solv_simple/fn_xor/bdd2specfn_xor.cc
|
nerdling/SBSAT
|
6328c6aa105b75693d06bf0dae4a3b5ca220318b
|
[
"Unlicense"
] | null | null | null |
#include "sbsat.h"
#include "sbsat_solver.h"
#include "solver.h"
void *CreateXORState(int *arrElts, int nNumElts, BDDNode *pCurrentBDD, XORStateEntry *pStartState) {
check_SmurfStatesTableSize(sizeof(XORStateEntry));
ite_counters[SMURF_STATES]+=1;
pStartState = (XORStateEntry *)SimpleSmurfProblemState->pSmurfStatesTableTail;
SimpleSmurfProblemState->pSmurfStatesTableTail = (void *)(pStartState + 1);
pStartState->cType = FN_XOR;
pStartState->pnTransitionVars = arrElts;
pStartState->nSize = nNumElts;
BDDNode *tmp_bdd;
for(tmp_bdd = pCurrentBDD; !IS_TRUE_FALSE(tmp_bdd); tmp_bdd = tmp_bdd->thenCase){}
pStartState->bParity = tmp_bdd == false_ptr;
if((nNumElts&0x1) == 1)
pStartState->bParity -= 1;
// fprintf(stderr, "\nb=%d\n", pStartState->bParity);
// printBDDerr(pCurrentBDD);
// fprintf(stderr, "\n");
// PrintAllSmurfStateEntries();
pCurrentBDD->pState = (void *)pStartState;
pStartState->pXORStateBDD = pCurrentBDD;
if(nNumElts == 2) return (void *)pStartState;
XORCounterStateEntry *pCurrXORCounter=NULL;
void *pPrevXORCounter = (void *)pStartState;
for(int x = 2; x < nNumElts; x++) {
// fprintf(stderr, "%d, %d, %d: ", x, arrElts[x], arrSimpleSolver2IteVarMap[arrElts[x]]);
check_SmurfStatesTableSize(sizeof(XORCounterStateEntry));
ite_counters[SMURF_STATES]+=1;
pCurrXORCounter = (XORCounterStateEntry *)SimpleSmurfProblemState->pSmurfStatesTableTail;
SimpleSmurfProblemState->pSmurfStatesTableTail = (void *)(pCurrXORCounter + 1);
pCurrXORCounter->cType = FN_XOR_COUNTER;
pCurrXORCounter->pTransition = pPrevXORCounter;
pCurrXORCounter->pXORState = pStartState;
pCurrXORCounter->nSize = x+1;
pPrevXORCounter = (void *)pCurrXORCounter;
}
return pCurrentBDD->pState = (void *)pCurrXORCounter;
}
void *CreateXORGElimState(int *arrElts, int nNumElts, BDDNode *pCurrentBDD, XORGElimStateEntry *pStartState) {
check_SmurfStatesTableSize(sizeof(XORGElimStateEntry));
ite_counters[SMURF_STATES]+=1;
pStartState = (XORGElimStateEntry *)SimpleSmurfProblemState->pSmurfStatesTableTail;
SimpleSmurfProblemState->pSmurfStatesTableTail = (void *)(pStartState + 1);
pStartState->cType = FN_XOR_GELIM;
pStartState->pnTransitionVars = arrElts;
pStartState->nSize = nNumElts;
pStartState->pXORGElimStateBDD = pCurrentBDD;
BDDNode *tmp_bdd;
for(tmp_bdd = pCurrentBDD; !IS_TRUE_FALSE(tmp_bdd); tmp_bdd = tmp_bdd->thenCase){}
bool bParity = tmp_bdd == false_ptr;
if((nNumElts&0x1) == 1)
bParity -= 1;
pStartState->pVector = createXORGElimTableVector(nNumElts, arrElts, bParity);
// fprintf(stderr, "\nb=%d\n", pStartState->bParity);
// printBDDerr(pCurrentBDD);
// fprintf(stderr, "\n");
// PrintAllSmurfStateEntries();
return pCurrentBDD->pState = (void *)pStartState;
}
| 37.671233
| 110
| 0.752727
|
nerdling
|
86ce8dc16dd074aa9af8352d64b6aa48cdc57170
| 1,022
|
cpp
|
C++
|
STL/Associative Containers/8 map in c++ stl.cpp
|
arvindr19/cppnuts
|
3814a00348e0eb8588711bab751d3db1b6af6a25
|
[
"MIT"
] | null | null | null |
STL/Associative Containers/8 map in c++ stl.cpp
|
arvindr19/cppnuts
|
3814a00348e0eb8588711bab751d3db1b6af6a25
|
[
"MIT"
] | null | null | null |
STL/Associative Containers/8 map in c++ stl.cpp
|
arvindr19/cppnuts
|
3814a00348e0eb8588711bab751d3db1b6af6a25
|
[
"MIT"
] | null | null | null |
// TOPIC: Map In C++
// NOTES:
// 1. Syntax: map<T1, T2> obj; // where T1 is key type and T2 is value type.
// 2. std::map is associative container that store elements in key value combination
// where key should be unique, otherwise it overrides the previous value.
// 3. It is implement using Self-Balance Binary Search Tree (AVL/Red Black Tree) .
// 4. It store key value pair in sorted order on the basis of key (assending/decending).
// 5. std::map is generally used in Dictionay type problems.
// EXAMPLE: Dictionary
#include <iostream>
#include <map>
#include <functional>
#include <vector>
using namespace std;
class Person{
public:
float age;
string name;
bool operator < (const Person& rhs) const { return age<rhs.age; }
bool operator > (const Person& rhs) const { return age>rhs.age; }
};
int main() {
std::map<Person, int, std::less<>> Map;
Person p1, p2;
Map[p1] = 1;
Map[p2] = 2;
cout << Map[p1] << endl;
cout << Map[p2] << endl;
return 0;
}
| 28.388889
| 88
| 0.650685
|
arvindr19
|
86d0ee65da11b320db1f2f1c1dc9fe0c66b6dce1
| 6,232
|
cpp
|
C++
|
Vic2ToHoI4/Source/V2World/Countries/Country.cpp
|
gawquon/Vic2ToHoI4
|
8371cfb1fd57cf81d854077963135d8037e754eb
|
[
"MIT"
] | 3
|
2019-12-31T19:51:21.000Z
|
2020-01-23T18:20:57.000Z
|
Vic2ToHoI4/Source/V2World/Countries/Country.cpp
|
gawquon/Vic2ToHoI4
|
8371cfb1fd57cf81d854077963135d8037e754eb
|
[
"MIT"
] | 52
|
2021-12-22T01:23:44.000Z
|
2022-03-24T01:26:37.000Z
|
Vic2ToHoI4/Source/V2World/Countries/Country.cpp
|
Osariusz/Vic2ToHoI4
|
9738b52c7602b1fe187c3820660c58a8d010d87e
|
[
"MIT"
] | null | null | null |
#include "Country.h"
#include "Log.h"
#include "V2World/Culture/CultureGroups.h"
#include "V2World/Localisations/Vic2Localisations.h"
#include "V2World/Pops/Pop.h"
#include "V2World/Provinces/Province.h"
#include "V2World/States/State.h"
#include <ranges>
void Vic2::Country::eatCountry(Country& target, bool debug)
{
if (target.tag == tag)
{
return;
}
for (auto& state: target.states)
{
state.setOwner(tag);
states.push_back(std::move(state));
}
for (auto& core: target.cores)
{
core->addCore(tag);
core->removeCore(target.tag);
addCore(core);
}
for (auto& provinceItr: target.provinces)
{
provinceItr.second->setOwner(tag);
provinces.insert(provinceItr);
}
technologiesAndInventions.insert(target.technologiesAndInventions.begin(), target.technologiesAndInventions.end());
armies.insert(armies.end(), target.armies.begin(), target.armies.end());
if (debug)
{
Log(LogLevel::Debug) << "Merged " << target.tag << " into " << tag;
}
}
void Vic2::Country::mergeStates(const StateDefinitions& stateDefinitions)
{
for (auto state = states.begin(); state != states.end(); ++state)
{
if (!state->isPartialState())
{
continue;
}
auto state2 = state;
++state2;
while (state2 != states.end())
{
if (state->getStateID() != state2->getStateID())
{
++state2;
continue;
}
state->eatState(*state2, stateDefinitions);
state2 = states.erase(state2);
}
}
}
void Vic2::Country::putProvincesInStates()
{
for (auto& state: states)
{
for (auto provinceNum: state.getProvinceNumbers())
{
auto province = provinces.find(provinceNum);
if (province == provinces.end())
{
Log(LogLevel::Warning) << "State (" << state.getStateID() << ") owned by " << tag << " had province ("
<< provinceNum << ") that " << tag << " did not";
continue;
}
state.addProvince(province->second);
}
}
}
void Vic2::Country::determineEmployedWorkers()
{
for (auto& state: states)
{
state.determineEmployedWorkers();
}
}
void Vic2::Country::setLocalisationNames(Localisations& vic2Localisations)
{
if (!domainName.empty())
{
vic2Localisations.updateDomainCountry(tag, domainName);
}
auto nameInAllLanguages = vic2Localisations.getTextInEachLanguage(tag);
for (const auto& [language, name]: nameInAllLanguages)
{
setLocalisationName(language, name);
}
}
void Vic2::Country::setLocalisationName(const std::string& language, const std::string& name)
{
if (!domainName.empty())
{
namesByLanguage[language] = domainName;
}
else if (!name.empty())
{
namesByLanguage[language] = name;
}
}
void Vic2::Country::setLocalisationAdjectives(const Localisations& vic2Localisations)
{
auto adjectiveInAllLanguages = vic2Localisations.getTextInEachLanguage(tag + "_ADJ");
for (const auto& [language, adjective]: adjectiveInAllLanguages)
{
setLocalisationAdjective(language, adjective);
}
}
void Vic2::Country::setLocalisationAdjective(const std::string& language, const std::string& adjective)
{
if (!domainAdjective.empty()) // Domains have their adjective set from domain_region
{
adjectivesByLanguage[language] = domainAdjective;
}
else if (!adjective.empty())
{
adjectivesByLanguage[language] = adjective;
}
}
void Vic2::Country::handleMissingCulture(const CultureGroups& theCultureGroups)
{
if (primaryCulture == "no_culture")
{
const auto cultureSizes = determineCultureSizes();
primaryCulture = selectLargestCulture(cultureSizes);
auto cultureGroupOption = theCultureGroups.getGroup(primaryCulture);
if (cultureGroupOption)
{
primaryCultureGroup = *cultureGroupOption;
}
}
}
std::map<std::string, int> Vic2::Country::determineCultureSizes()
{
std::map<std::string, int> cultureSizes;
for (auto province: provinces | std::views::values)
{
for (const auto& pop: province->getPops())
{
const auto& popSize = pop.getSize();
const auto& popCulture = pop.getCulture();
auto [existing, inserted] = cultureSizes.insert(std::make_pair(popCulture, popSize));
if (!inserted)
{
existing->second += pop.getSize();
}
}
}
return cultureSizes;
}
std::string Vic2::Country::selectLargestCulture(const std::map<std::string, int>& cultureSizes)
{
std::string largestCulture = "no_culture";
auto largestCultureSize = 0;
for (const auto& [culture, size]: cultureSizes)
{
if (size > largestCultureSize)
{
largestCulture = culture;
largestCultureSize = size;
}
}
return largestCulture;
}
bool Vic2::Country::hasCoreOnCapital() const
{
for (const auto& core: cores)
{
if (core->getNumber() == capital)
{
return true;
}
}
return false;
}
int32_t Vic2::Country::getEmployedWorkers() const
{
int32_t employedWorkers = 0;
for (const auto& state: states)
{
employedWorkers += state.getEmployedWorkers();
}
return employedWorkers;
}
float Vic2::Country::getAverageIssueSupport(const std::string& issueName) const
{
float totalPopulation = 0.0;
float totalSupport = 0.0;
for (const auto& province: provinces | std::views::values)
{
for (const auto& pop: province->getPops())
{
const auto size = static_cast<float>(pop.getSize());
totalSupport += pop.getIssueSupport(issueName) * size;
totalPopulation += size;
}
}
if (totalPopulation == 0.0F)
{
return 0.0F;
}
return totalSupport / totalPopulation;
}
bool Vic2::operator==(const Country& one, const Country& other)
{
return one.getTag() == other.getTag();
}
std::optional<std::string> Vic2::Country::getName(const std::string& language) const
{
const auto& nameInLanguage = namesByLanguage.find(language);
if (nameInLanguage == namesByLanguage.end())
{
return std::nullopt;
}
return nameInLanguage->second;
}
std::optional<std::string> Vic2::Country::getAdjective(const std::string& language) const
{
const auto& adjectiveInLanguage = adjectivesByLanguage.find(language);
if (adjectiveInLanguage == adjectivesByLanguage.end())
{
return std::nullopt;
}
return adjectiveInLanguage->second;
}
std::vector<std::string> Vic2::Country::getShipNames(const std::string& category) const
{
const auto foundShipNames = shipNames.find(category);
if (foundShipNames == shipNames.end())
{
return {};
}
return foundShipNames->second;
}
| 21.415808
| 116
| 0.702343
|
gawquon
|
86d12c1e94292093f49dfa19b52dff28b52f1462
| 869
|
cpp
|
C++
|
src/system/Runner.cpp
|
bkozdras/picosdkal
|
1830a2b0296510a5d40a69d22d9a21618d664528
|
[
"MIT"
] | null | null | null |
src/system/Runner.cpp
|
bkozdras/picosdkal
|
1830a2b0296510a5d40a69d22d9a21618d664528
|
[
"MIT"
] | null | null | null |
src/system/Runner.cpp
|
bkozdras/picosdkal
|
1830a2b0296510a5d40a69d22d9a21618d664528
|
[
"MIT"
] | null | null | null |
/**********************************************************************************/
/* Copyright by @bkozdras <b.kozdras@gmail.com> */
/* Version: 1.0 */
/* Licence: MIT */
/**********************************************************************************/
#include <rpipicosdkal/system/Runner.hpp>
#include <pico/platform.h>
#include <rpipicosdkal/context/Context.hpp>
#include <rpipicosdkal/system/IApplication.hpp>
namespace rpipicosdkal
{
namespace system
{
void run(IApplicationPtr&& application)
{
auto context = context::Context::create();
application->setup(*context);
for (;;)
{
tight_loop_contents();
}
}
} // namespace system
} // namespace rpipicosdkal
| 28.032258
| 84
| 0.420023
|
bkozdras
|
86d1d4e9a3877ab3c3ebc284d1be8e8199be97b0
| 4,390
|
cpp
|
C++
|
src/game/shared/sdk/sdk_playerclass_info_parse.cpp
|
vxsd/refraction
|
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
|
[
"MIT"
] | 14
|
2021-02-16T14:13:50.000Z
|
2022-03-17T18:29:19.000Z
|
src/game/shared/sdk/sdk_playerclass_info_parse.cpp
|
undbsd/refraction
|
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
|
[
"MIT"
] | 7
|
2021-08-06T18:40:37.000Z
|
2022-03-09T18:05:08.000Z
|
src/game/shared/sdk/sdk_playerclass_info_parse.cpp
|
undbsd/refraction
|
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
|
[
"MIT"
] | 2
|
2021-08-05T16:03:03.000Z
|
2021-11-26T00:11:27.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "sdk_playerclass_info_parse.h"
#include "weapon_sdkbase.h"
#include <KeyValues.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//Tony; due to the nature of the base code.. I must do this !
FilePlayerClassInfo_t* CreatePlayerClassInfo()
{
#if defined ( SDK_USE_PLAYERCLASSES )
return new CSDKPlayerClassInfo;
#else
return new FilePlayerClassInfo_t;
#endif
}
#if defined ( SDK_USE_PLAYERCLASSES )
CSDKPlayerClassInfo::CSDKPlayerClassInfo()
{
m_iTeam= TEAM_UNASSIGNED;
m_iPrimaryWeapon= WEAPON_NONE;
m_iSecondaryWeapon= WEAPON_NONE;
m_iMeleeWeapon= WEAPON_NONE;
m_iNumGrensType1 = 0;
m_iGrenType1 = WEAPON_NONE;
m_iNumGrensType2 = 0;
m_iGrenType2 = WEAPON_NONE;
m_szLimitCvar[0] = '\0';
m_flRunSpeed = SDK_DEFAULT_PLAYER_RUNSPEED;
m_flSprintSpeed = SDK_DEFAULT_PLAYER_RUNSPEED;
m_flProneSpeed = SDK_DEFAULT_PLAYER_RUNSPEED;
m_iArmor = 0;
}
void CSDKPlayerClassInfo::Parse( KeyValues *pKeyValuesData, const char *szWeaponName )
{
BaseClass::Parse( pKeyValuesData, szWeaponName );
m_iTeam= pKeyValuesData->GetInt( "team", TEAM_UNASSIGNED );
// Figure out what team can have this player class
m_iTeam = TEAM_UNASSIGNED;
//Tony; don't check for teams unless we're using teams. You could do a free for all, but class / character based game if you wanted.
#ifdef SDK_USE_TEAMS
const char *pTeam = pKeyValuesData->GetString( "team", NULL );
if ( pTeam )
{
if ( Q_stricmp( pTeam, "BLUE" ) == 0 )
{
m_iTeam = SDK_TEAM_BLUE;
}
else if ( Q_stricmp( pTeam, "RED" ) == 0 )
{
m_iTeam = SDK_TEAM_RED;
}
else
{
Assert( false );
}
}
else
{
Assert( false );
}
#endif
const char *pszPrimaryWeapon = pKeyValuesData->GetString( "primaryweapon", NULL );
m_iPrimaryWeapon = AliasToWeaponID( pszPrimaryWeapon );
Assert( m_iPrimaryWeapon != WEAPON_NONE ); // require player to have a primary weapon
const char *pszSecondaryWeapon = pKeyValuesData->GetString( "secondaryweapon", NULL );
if ( pszSecondaryWeapon )
{
m_iSecondaryWeapon = AliasToWeaponID( pszSecondaryWeapon );
// Assert( m_iSecondaryWeapon != WEAPON_NONE );
}
else
m_iSecondaryWeapon = WEAPON_NONE;
const char *pszMeleeWeapon = pKeyValuesData->GetString( "meleeweapon", NULL );
if ( pszMeleeWeapon )
{
m_iMeleeWeapon = AliasToWeaponID( pszMeleeWeapon );
// Assert( m_iMeleeWeapon != WEAPON_NONE );
}
else
m_iMeleeWeapon = WEAPON_NONE;
m_iNumGrensType1 = pKeyValuesData->GetInt( "numgrens", 0 );
if ( m_iNumGrensType1 > 0 )
{
const char *pszGrenType1 = pKeyValuesData->GetString( "grenadetype", NULL );
m_iGrenType1 = AliasToWeaponID( pszGrenType1 );
// Assert( m_iGrenType1 != WEAPON_NONE );
}
m_iNumGrensType2 = pKeyValuesData->GetInt( "numgrens2", 0 );
if ( m_iNumGrensType2 > 0 )
{
const char *pszGrenType2 = pKeyValuesData->GetString( "grenadetype2", NULL );
m_iGrenType2 = AliasToWeaponID( pszGrenType2 );
// Assert( m_iGrenType2 != WEAPON_NONE );
}
Q_strncpy( m_szLimitCvar, pKeyValuesData->GetString( "limitcvar", "!! Missing limit cvar on Player Class" ), sizeof(m_szLimitCvar) );
Assert( Q_strlen( m_szLimitCvar ) > 0 && "Every class must specify a limitcvar" );
// HUD player status health images (when the player is hurt)
Q_strncpy( m_szClassImage, pKeyValuesData->GetString( "classimage", "white" ), sizeof( m_szClassImage ) );
Q_strncpy( m_szClassImageBG, pKeyValuesData->GetString( "classimagebg", "white" ), sizeof( m_szClassImageBG ) );
m_flRunSpeed = pKeyValuesData->GetFloat( "RunSpeed", SDK_DEFAULT_PLAYER_RUNSPEED );
m_flSprintSpeed = pKeyValuesData->GetFloat( "SprintSpeed", SDK_DEFAULT_PLAYER_RUNSPEED );
m_flProneSpeed = pKeyValuesData->GetFloat( "ProneSpeed", SDK_DEFAULT_PLAYER_RUNSPEED );
m_iArmor = pKeyValuesData->GetInt( "armor", 0 );
}
#endif // SDK_USE_PLAYERCLASSES
| 31.811594
| 137
| 0.657175
|
vxsd
|
86d8cd9a5692354e7e01ffd84a8ca14ad6b3a46b
| 35,836
|
cc
|
C++
|
server/core/routingworker.cc
|
woopstar/MaxScale
|
e88b7f56f96ac2567582d1707fe0a23f92ac8e11
|
[
"MIT"
] | null | null | null |
server/core/routingworker.cc
|
woopstar/MaxScale
|
e88b7f56f96ac2567582d1707fe0a23f92ac8e11
|
[
"MIT"
] | 1
|
2019-07-02T09:59:27.000Z
|
2019-07-02T09:59:49.000Z
|
server/core/routingworker.cc
|
woopstar/MaxScale
|
e88b7f56f96ac2567582d1707fe0a23f92ac8e11
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2022-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include <maxscale/routingworker.hh>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
#include <vector>
#include <sstream>
#include <maxbase/atomic.hh>
#include <maxbase/semaphore.hh>
#include <maxscale/alloc.h>
#include <maxscale/config.h>
#include <maxscale/clock.h>
#include <maxscale/limits.h>
#include <maxscale/json_api.h>
#include <maxscale/utils.hh>
#include <maxscale/statistics.hh>
#include "internal/dcb.h"
#include "internal/modules.h"
#include "internal/poll.hh"
#include "internal/service.hh"
#define WORKER_ABSENT_ID -1
using maxbase::Semaphore;
using maxbase::Worker;
using maxbase::WorkerLoad;
using maxscale::RoutingWorker;
using maxscale::Closer;
using std::vector;
using std::stringstream;
namespace
{
/**
* Unit variables.
*/
struct this_unit
{
bool initialized; // Whether the initialization has been performed.
int nWorkers; // How many routing workers there are.
RoutingWorker** ppWorkers; // Array of routing worker instances.
int next_worker_id; // Next worker id
// DEPRECATED in 2.3, remove in 2.4.
int number_poll_spins; // Maximum non-block polls
// DEPRECATED in 2.3, remove in 2.4.
int max_poll_sleep; // Maximum block time
int epoll_listener_fd; // Shared epoll descriptor for listening descriptors.
int id_main_worker; // The id of the worker running in the main thread.
int id_min_worker; // The smallest routing worker id.
int id_max_worker; // The largest routing worker id.
} this_unit =
{
false, // initialized
0, // nWorkers
NULL, // ppWorkers
0, // next_worker_id
0, // number_poll_spins
0, // max_poll_sleep
-1, // epoll_listener_fd
WORKER_ABSENT_ID, // id_main_worker
WORKER_ABSENT_ID, // id_min_worker
WORKER_ABSENT_ID, // id_max_worker
};
int next_worker_id()
{
return mxb::atomic::add(&this_unit.next_worker_id, 1, mxb::atomic::RELAXED);
}
thread_local struct this_thread
{
int current_worker_id; // The worker id of the current thread
} this_thread =
{
WORKER_ABSENT_ID
};
/**
* Calls thread_init on all loaded modules.
*
* @return True, if all modules were successfully initialized.
*/
bool modules_thread_init()
{
bool initialized = false;
MXS_MODULE_ITERATOR i = mxs_module_iterator_get(NULL);
MXS_MODULE* module = NULL;
while ((module = mxs_module_iterator_get_next(&i)) != NULL)
{
if (module->thread_init)
{
int rc = (module->thread_init)();
if (rc != 0)
{
break;
}
}
}
if (module)
{
// If module is non-NULL it means that the initialization failed for
// that module. We now need to call finish on all modules that were
// successfully initialized.
MXS_MODULE* failed_module = module;
i = mxs_module_iterator_get(NULL);
while ((module = mxs_module_iterator_get_next(&i)) != failed_module)
{
if (module->thread_finish)
{
(module->thread_finish)();
}
}
}
else
{
initialized = true;
}
return initialized;
}
/**
* Calls thread_finish on all loaded modules.
*/
void modules_thread_finish()
{
MXS_MODULE_ITERATOR i = mxs_module_iterator_get(NULL);
MXS_MODULE* module = NULL;
while ((module = mxs_module_iterator_get_next(&i)) != NULL)
{
if (module->thread_finish)
{
(module->thread_finish)();
}
}
}
}
namespace maxscale
{
// static
maxbase::Duration RoutingWorker::s_watchdog_interval {0};
// static
maxbase::TimePoint RoutingWorker::s_watchdog_next_check;
class RoutingWorker::WatchdogNotifier
{
WatchdogNotifier(const WatchdogNotifier&) = delete;
WatchdogNotifier& operator=(const WatchdogNotifier&) = delete;
public:
WatchdogNotifier(mxs::RoutingWorker* pOwner)
: m_owner(*pOwner)
, m_nClients(0)
, m_terminate(false)
{
m_thread = std::thread([this] {
uint32_t interval = mxs::RoutingWorker::s_watchdog_interval.secs();
timespec timeout = { interval, 0 };
while (!mxb::atomic::load(&m_terminate, mxb::atomic::RELAXED))
{
// We will wakeup when someone wants the notifier to run,
// or when MaxScale is going down.
m_sem_start.wait();
if (!mxb::atomic::load(&m_terminate, mxb::atomic::RELAXED))
{
// If MaxScale is not going down...
do
{
// we check the systemd watchdog...
m_owner.check_systemd_watchdog();
} while (!m_sem_stop.timedwait(timeout));
// until the semaphore is actually posted, which it will be
// once the notification should stop.
}
}
});
}
~WatchdogNotifier()
{
mxb_assert(m_nClients == 0);
mxb::atomic::store(&m_terminate, true, mxb::atomic::RELAXED);
m_sem_start.post();
m_thread.join();
}
void start()
{
Guard guard(m_lock);
mxb::atomic::add(&m_nClients, 1, mxb::atomic::RELAXED);
if (m_nClients == 1)
{
m_sem_start.post();
}
}
void stop()
{
Guard guard(m_lock);
mxb::atomic::add(&m_nClients, -1, mxb::atomic::RELAXED);
mxb_assert(m_nClients >= 0);
if (m_nClients == 0)
{
m_sem_stop.post();
}
}
private:
using Guard = std::lock_guard<std::mutex>;
mxs::RoutingWorker& m_owner;
int m_nClients;
bool m_terminate;
std::thread m_thread;
std::mutex m_lock;
mxb::Semaphore m_sem_start;
mxb::Semaphore m_sem_stop;
};
RoutingWorker::RoutingWorker()
: m_id(next_worker_id())
, m_alive(true)
, m_pWatchdog_notifier(nullptr)
{
MXB_POLL_DATA::handler = &RoutingWorker::epoll_instance_handler;
MXB_POLL_DATA::owner = this;
if (s_watchdog_interval.count() != 0)
{
m_pWatchdog_notifier = new WatchdogNotifier(this);
}
}
RoutingWorker::~RoutingWorker()
{
delete m_pWatchdog_notifier;
}
// static
bool RoutingWorker::init()
{
mxb_assert(!this_unit.initialized);
this_unit.number_poll_spins = config_nbpolls();
this_unit.max_poll_sleep = config_pollsleep();
this_unit.epoll_listener_fd = epoll_create(MAX_EVENTS);
if (this_unit.epoll_listener_fd != -1)
{
int nWorkers = config_threadcount();
RoutingWorker** ppWorkers = new(std::nothrow) RoutingWorker* [MXS_MAX_THREADS](); // 0-inited
// array
if (ppWorkers)
{
int id_main_worker = WORKER_ABSENT_ID;
int id_min_worker = INT_MAX;
int id_max_worker = INT_MIN;
int i;
for (i = 0; i < nWorkers; ++i)
{
RoutingWorker* pWorker = RoutingWorker::create(this_unit.epoll_listener_fd);
if (pWorker)
{
int id = pWorker->id();
// The first created worker will be the main worker.
if (id_main_worker == WORKER_ABSENT_ID)
{
id_main_worker = id;
}
if (id < id_min_worker)
{
id_min_worker = id;
}
if (id > id_max_worker)
{
id_max_worker = id;
}
ppWorkers[i] = pWorker;
}
else
{
for (int j = i - 1; j >= 0; --j)
{
delete ppWorkers[j];
}
delete[] ppWorkers;
ppWorkers = NULL;
break;
}
}
if (ppWorkers)
{
this_unit.ppWorkers = ppWorkers;
this_unit.nWorkers = nWorkers;
this_unit.id_main_worker = id_main_worker;
this_unit.id_min_worker = id_min_worker;
this_unit.id_max_worker = id_max_worker;
this_unit.initialized = true;
}
}
else
{
MXS_OOM();
close(this_unit.epoll_listener_fd);
}
}
else
{
MXS_ALERT("Could not allocate an epoll instance.");
}
if (this_unit.initialized)
{
// When the initialization has successfully been performed, we set the
// current_worker_id of this thread to 0. That way any connections that
// are made during service startup (after this function returns, but
// bofore the workes have been started) will be handled by the worker
// that will be running in the main thread.
this_thread.current_worker_id = 0;
if (s_watchdog_interval.count() != 0)
{
MXS_NOTICE("The systemd watchdog is Enabled. Internal timeout = %s\n",
to_string(s_watchdog_interval).c_str());
}
}
return this_unit.initialized;
}
void RoutingWorker::finish()
{
mxb_assert(this_unit.initialized);
for (int i = this_unit.id_max_worker; i >= this_unit.id_min_worker; --i)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
delete pWorker;
this_unit.ppWorkers[i] = NULL;
}
delete[] this_unit.ppWorkers;
this_unit.ppWorkers = NULL;
close(this_unit.epoll_listener_fd);
this_unit.epoll_listener_fd = 0;
this_unit.initialized = false;
}
// static
bool RoutingWorker::add_shared_fd(int fd, uint32_t events, MXB_POLL_DATA* pData)
{
bool rv = true;
// This must be level-triggered. Since this is intended for listening
// sockets and each worker will call accept() just once before going
// back the epoll_wait(), using EPOLLET would mean that if there are
// more clients to be accepted than there are threads returning from
// epoll_wait() for an event, then some clients would be accepted only
// when a new client has connected, thus causing a new EPOLLIN event.
events &= ~EPOLLET;
struct epoll_event ev;
ev.events = events;
ev.data.ptr = pData;
pData->owner = RoutingWorker::get(RoutingWorker::MAIN);
if (epoll_ctl(this_unit.epoll_listener_fd, EPOLL_CTL_ADD, fd, &ev) != 0)
{
Worker::resolve_poll_error(fd, errno, EPOLL_CTL_ADD);
rv = false;
}
return rv;
}
// static
bool RoutingWorker::remove_shared_fd(int fd)
{
bool rv = true;
struct epoll_event ev = {};
if (epoll_ctl(this_unit.epoll_listener_fd, EPOLL_CTL_DEL, fd, &ev) != 0)
{
Worker::resolve_poll_error(fd, errno, EPOLL_CTL_DEL);
rv = false;
}
return rv;
}
bool mxs_worker_should_shutdown(MXB_WORKER* pWorker)
{
return static_cast<RoutingWorker*>(pWorker)->should_shutdown();
}
RoutingWorker* RoutingWorker::get(int worker_id)
{
if (worker_id == MAIN)
{
worker_id = this_unit.id_main_worker;
}
mxb_assert((worker_id >= this_unit.id_min_worker) && (worker_id <= this_unit.id_max_worker));
return this_unit.ppWorkers[worker_id];
}
RoutingWorker* RoutingWorker::get_current()
{
RoutingWorker* pWorker = NULL;
int worker_id = get_current_id();
if (worker_id != WORKER_ABSENT_ID)
{
pWorker = RoutingWorker::get(worker_id);
}
return pWorker;
}
int RoutingWorker::get_current_id()
{
return this_thread.current_worker_id;
}
// static
bool RoutingWorker::start_threaded_workers()
{
bool rv = true;
for (int i = this_unit.id_min_worker; i <= this_unit.id_max_worker; ++i)
{
// The main RoutingWorker will run in the main thread, so
// we exclude that.
if (i != this_unit.id_main_worker)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
if (!pWorker->start())
{
MXS_ALERT("Could not start routing worker %d of %d.", i, config_threadcount());
rv = false;
// At startup, so we don't even try to clean up.
break;
}
}
}
return rv;
}
// static
void RoutingWorker::join_threaded_workers()
{
for (int i = this_unit.id_min_worker; i <= this_unit.id_max_worker; i++)
{
if (i != this_unit.id_main_worker)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
pWorker->join();
}
}
}
// static
void RoutingWorker::set_nonblocking_polls(unsigned int nbpolls)
{
this_unit.number_poll_spins = nbpolls;
}
// static
void RoutingWorker::set_maxwait(unsigned int maxwait)
{
this_unit.max_poll_sleep = maxwait;
}
RoutingWorker::SessionsById& RoutingWorker::session_registry()
{
return m_sessions;
}
void RoutingWorker::register_zombie(DCB* pDcb)
{
mxb_assert(pDcb->poll.owner == this);
m_zombies.push_back(pDcb);
}
void RoutingWorker::delete_zombies()
{
// An algorithm cannot be used, as the final closing of a DCB may cause
// other DCBs to be registered in the zombie queue.
while (!m_zombies.empty())
{
DCB* pDcb = m_zombies.back();
m_zombies.pop_back();
dcb_final_close(pDcb);
}
}
bool RoutingWorker::pre_run()
{
this_thread.current_worker_id = m_id;
bool rv = modules_thread_init() && service_thread_init() && qc_thread_init(QC_INIT_SELF);
if (!rv)
{
MXS_ERROR("Could not perform thread initialization for all modules. Thread exits.");
this_thread.current_worker_id = WORKER_ABSENT_ID;
}
return rv;
}
void RoutingWorker::post_run()
{
modules_thread_finish();
qc_thread_end(QC_INIT_SELF);
// TODO: Add service_thread_finish().
this_thread.current_worker_id = WORKER_ABSENT_ID;
}
/**
* Creates a worker instance.
* - Allocates the structure.
* - Creates a pipe.
* - Adds the read descriptor to the polling mechanism.
*
* @param epoll_listener_fd The file descriptor of the epoll set to which listening
* sockets will be placed.
*
* @return A worker instance if successful, otherwise NULL.
*/
// static
RoutingWorker* RoutingWorker::create(int epoll_listener_fd)
{
RoutingWorker* pThis = new(std::nothrow) RoutingWorker();
if (pThis)
{
struct epoll_event ev;
ev.events = EPOLLIN;
MXB_POLL_DATA* pData = pThis;
ev.data.ptr = pData; // Necessary for pointer adjustment, otherwise downcast will not work.
// The shared epoll instance descriptor is *not* added using EPOLLET (edge-triggered)
// because we want it to be level-triggered. That way, as long as there is a single
// active (accept() can be called) listening socket, epoll_wait() will return an event
// for it. It must be like that because each worker will call accept() just once before
// calling epoll_wait() again. The end result is that as long as the load of different
// workers is roughly the same, the client connections will be distributed evenly across
// the workers. If the load is not the same, then a worker with less load will get more
// clients that a worker with more load.
if (epoll_ctl(pThis->m_epoll_fd, EPOLL_CTL_ADD, epoll_listener_fd, &ev) == 0)
{
MXS_INFO("Epoll instance for listening sockets added to worker epoll instance.");
}
else
{
MXS_ERROR("Could not add epoll instance for listening sockets to "
"epoll instance of worker: %s",
mxs_strerror(errno));
delete pThis;
pThis = NULL;
}
}
else
{
MXS_OOM();
}
return pThis;
}
void RoutingWorker::epoll_tick()
{
dcb_process_idle_sessions(m_id);
m_state = ZPROCESSING;
delete_zombies();
check_systemd_watchdog();
}
/**
* Callback for events occurring on the shared epoll instance.
*
* @param pData Will point to a Worker instance.
* @param wid The worker id.
* @param events The events.
*
* @return What actions were performed.
*/
// static
uint32_t RoutingWorker::epoll_instance_handler(MXB_POLL_DATA* pData, MXB_WORKER* pWorker, uint32_t events)
{
RoutingWorker* pThis = static_cast<RoutingWorker*>(pData);
mxb_assert(pThis == pWorker);
return pThis->handle_epoll_events(events);
}
/**
* Handler for events occurring in the shared epoll instance.
*
* @param events The events.
*
* @return What actions were performed.
*/
uint32_t RoutingWorker::handle_epoll_events(uint32_t events)
{
struct epoll_event epoll_events[1];
// We extract just one event
int nfds = epoll_wait(this_unit.epoll_listener_fd, epoll_events, 1, 0);
uint32_t actions = MXB_POLL_NOP;
if (nfds == -1)
{
MXS_ERROR("epoll_wait failed: %s", mxs_strerror(errno));
}
else if (nfds == 0)
{
MXS_DEBUG("No events for worker %d.", m_id);
}
else
{
MXS_DEBUG("1 event for worker %d.", m_id);
MXB_POLL_DATA* pData = static_cast<MXB_POLL_DATA*>(epoll_events[0].data.ptr);
actions = pData->handler(pData, this, epoll_events[0].events);
}
return actions;
}
// static
size_t RoutingWorker::broadcast(Task* pTask, Semaphore* pSem)
{
// No logging here, function must be signal safe.
size_t n = 0;
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
Worker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
if (pWorker->execute(pTask, pSem, EXECUTE_AUTO))
{
++n;
}
}
return n;
}
// static
size_t RoutingWorker::broadcast(std::unique_ptr<DisposableTask> sTask)
{
DisposableTask* pTask = sTask.release();
Worker::inc_ref(pTask);
size_t n = 0;
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
if (pWorker->post_disposable(pTask, EXECUTE_AUTO))
{
++n;
}
}
Worker::dec_ref(pTask);
return n;
}
// static
size_t RoutingWorker::broadcast(std::function<void ()> func,
mxb::Semaphore* pSem,
mxb::Worker::execute_mode_t mode)
{
size_t n = 0;
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
if (pWorker->execute(func, pSem, mode))
{
++n;
}
}
return n;
}
// static
size_t RoutingWorker::execute_serially(Task& task)
{
Semaphore sem;
size_t n = 0;
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
if (pWorker->execute(&task, &sem, EXECUTE_AUTO))
{
sem.wait();
++n;
}
}
return n;
}
// static
size_t RoutingWorker::execute_concurrently(Task& task)
{
Semaphore sem;
return sem.wait_n(RoutingWorker::broadcast(&task, &sem));
}
// static
size_t RoutingWorker::broadcast_message(uint32_t msg_id, intptr_t arg1, intptr_t arg2)
{
// NOTE: No logging here, this function must be signal safe.
size_t n = 0;
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
Worker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
if (pWorker->post_message(msg_id, arg1, arg2))
{
++n;
}
}
return n;
}
// static
void RoutingWorker::shutdown_all()
{
// NOTE: No logging here, this function must be signal safe.
mxb_assert((this_unit.next_worker_id == 0) || (this_unit.ppWorkers != NULL));
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
RoutingWorker* pWorker = this_unit.ppWorkers[i];
mxb_assert(pWorker);
pWorker->shutdown();
}
}
namespace
{
std::vector<Worker::STATISTICS> get_stats()
{
std::vector<Worker::STATISTICS> rval;
int nWorkers = this_unit.next_worker_id;
for (int i = 0; i < nWorkers; ++i)
{
RoutingWorker* pWorker = RoutingWorker::get(i);
mxb_assert(pWorker);
rval.push_back(pWorker->statistics());
}
return rval;
}
}
// static
Worker::STATISTICS RoutingWorker::get_statistics()
{
auto s = get_stats();
STATISTICS cs;
cs.n_read = mxs::sum(s, &STATISTICS::n_read);
cs.n_write = mxs::sum(s, &STATISTICS::n_write);
cs.n_error = mxs::sum(s, &STATISTICS::n_error);
cs.n_hup = mxs::sum(s, &STATISTICS::n_hup);
cs.n_accept = mxs::sum(s, &STATISTICS::n_accept);
cs.n_polls = mxs::sum(s, &STATISTICS::n_polls);
cs.n_pollev = mxs::sum(s, &STATISTICS::n_pollev);
cs.evq_avg = mxs::avg(s, &STATISTICS::evq_avg);
cs.evq_max = mxs::max(s, &STATISTICS::evq_max);
cs.maxqtime = mxs::max(s, &STATISTICS::maxqtime);
cs.maxexectime = mxs::max(s, &STATISTICS::maxexectime);
cs.n_fds = mxs::sum_element(s, &STATISTICS::n_fds);
cs.n_fds = mxs::min_element(s, &STATISTICS::n_fds);
cs.n_fds = mxs::max_element(s, &STATISTICS::n_fds);
cs.qtimes = mxs::avg_element(s, &STATISTICS::qtimes);
cs.exectimes = mxs::avg_element(s, &STATISTICS::exectimes);
return cs;
}
// static
int64_t RoutingWorker::get_one_statistic(POLL_STAT what)
{
auto s = get_stats();
int64_t rv = 0;
switch (what)
{
case POLL_STAT_READ:
rv = mxs::sum(s, &STATISTICS::n_read);
break;
case POLL_STAT_WRITE:
rv = mxs::sum(s, &STATISTICS::n_write);
break;
case POLL_STAT_ERROR:
rv = mxs::sum(s, &STATISTICS::n_error);
break;
case POLL_STAT_HANGUP:
rv = mxs::sum(s, &STATISTICS::n_hup);
break;
case POLL_STAT_ACCEPT:
rv = mxs::sum(s, &STATISTICS::n_accept);
break;
case POLL_STAT_EVQ_AVG:
rv = mxs::avg(s, &STATISTICS::evq_avg);
break;
case POLL_STAT_EVQ_MAX:
rv = mxs::max(s, &STATISTICS::evq_max);
break;
case POLL_STAT_MAX_QTIME:
rv = mxs::max(s, &STATISTICS::maxqtime);
break;
case POLL_STAT_MAX_EXECTIME:
rv = mxs::max(s, &STATISTICS::maxexectime);
break;
default:
mxb_assert(!true);
}
return rv;
}
// static
bool RoutingWorker::get_qc_stats(int id, QC_CACHE_STATS* pStats)
{
class Task : public Worker::Task
{
public:
Task(QC_CACHE_STATS* pStats)
: m_stats(*pStats)
{
}
void execute(Worker&)
{
qc_get_cache_stats(&m_stats);
}
private:
QC_CACHE_STATS& m_stats;
};
RoutingWorker* pWorker = RoutingWorker::get(id);
if (pWorker)
{
Semaphore sem;
Task task(pStats);
pWorker->execute(&task, &sem, EXECUTE_AUTO);
sem.wait();
}
return pWorker != nullptr;
}
// static
void RoutingWorker::get_qc_stats(std::vector<QC_CACHE_STATS>& all_stats)
{
class Task : public Worker::Task
{
public:
Task(std::vector<QC_CACHE_STATS>* pAll_stats)
: m_all_stats(*pAll_stats)
{
m_all_stats.resize(config_threadcount());
}
void execute(Worker& worker)
{
int id = mxs::RoutingWorker::get_current_id();
mxb_assert(id >= 0);
QC_CACHE_STATS& stats = m_all_stats[id];
qc_get_cache_stats(&stats);
}
private:
std::vector<QC_CACHE_STATS>& m_all_stats;
};
Task task(&all_stats);
mxs::RoutingWorker::execute_concurrently(task);
}
namespace
{
json_t* qc_stats_to_json(const char* zHost, int id, const QC_CACHE_STATS& stats)
{
json_t* pStats = json_object();
json_object_set_new(pStats, "size", json_integer(stats.size));
json_object_set_new(pStats, "inserts", json_integer(stats.inserts));
json_object_set_new(pStats, "hits", json_integer(stats.hits));
json_object_set_new(pStats, "misses", json_integer(stats.misses));
json_object_set_new(pStats, "evictions", json_integer(stats.evictions));
json_t* pAttributes = json_object();
json_object_set_new(pAttributes, "stats", pStats);
json_t* pSelf = mxs_json_self_link(zHost, "qc_stats", std::to_string(id).c_str());
json_t* pJson = json_object();
json_object_set_new(pJson, CN_ID, json_string(std::to_string(id).c_str()));
json_object_set_new(pJson, CN_TYPE, json_string("qc_stats"));
json_object_set_new(pJson, CN_ATTRIBUTES, pAttributes);
json_object_set_new(pJson, CN_LINKS, pSelf);
return pJson;
}
}
// static
std::unique_ptr<json_t> RoutingWorker::get_qc_stats_as_json(const char* zHost, int id)
{
std::unique_ptr<json_t> sStats;
QC_CACHE_STATS stats;
if (get_qc_stats(id, &stats))
{
json_t* pJson = qc_stats_to_json(zHost, id, stats);
stringstream self;
self << MXS_JSON_API_QC_STATS << id;
sStats.reset(mxs_json_resource(zHost, self.str().c_str(), pJson));
}
return sStats;
}
// static
std::unique_ptr<json_t> RoutingWorker::get_qc_stats_as_json(const char* zHost)
{
vector<QC_CACHE_STATS> all_stats;
get_qc_stats(all_stats);
std::unique_ptr<json_t> sAll_stats(json_array());
int id = 0;
for (const auto& stats : all_stats)
{
json_t* pJson = qc_stats_to_json(zHost, id, stats);
json_array_append_new(sAll_stats.get(), pJson);
++id;
}
return std::unique_ptr<json_t>(mxs_json_resource(zHost, MXS_JSON_API_QC_STATS, sAll_stats.release()));
}
// static
RoutingWorker* RoutingWorker::pick_worker()
{
static int id_generator = 0;
int id = this_unit.id_min_worker
+ (mxb::atomic::add(&id_generator, 1, mxb::atomic::RELAXED) % this_unit.nWorkers);
return get(id);
}
// static
void maxscale::RoutingWorker::set_watchdog_interval(uint64_t microseconds)
{
// Do not call anything from here, assume nothing has been initialized (like logging).
// The internal timeout is 2/3 of the systemd configured interval.
double seconds = 1.0 * microseconds / 2000000;
s_watchdog_interval = maxbase::Duration(seconds);
s_watchdog_next_check = maxbase::Clock::now();
}
void maxscale::RoutingWorker::start_watchdog_workaround()
{
if (m_pWatchdog_notifier)
{
m_pWatchdog_notifier->start();
}
}
void maxscale::RoutingWorker::stop_watchdog_workaround()
{
if (m_pWatchdog_notifier)
{
m_pWatchdog_notifier->stop();
}
}
// A note about the below code. While the main worker is turning the "m_alive" values to false,
// it is a possibility that another RoutingWorker sees the old value of "s_watchdog_next_check"
// but its new "m_alive==false" value, marks itself alive and promptly hangs. This would cause a
// watchdog kill delay of about "s_watchdog_interval" time.
// Release-acquire would fix that, but is an unneccesary expense.
void RoutingWorker::check_systemd_watchdog()
{
if (s_watchdog_interval.count() == 0) // not turned on
{
return;
}
maxbase::TimePoint now = maxbase::Clock::now();
if (now > s_watchdog_next_check)
{
if (m_id == this_unit.id_main_worker)
{
m_alive.store(true, std::memory_order_relaxed);
bool all_alive = std::all_of(this_unit.ppWorkers, this_unit.ppWorkers + this_unit.nWorkers,
[](RoutingWorker* rw) {
return rw->m_alive.load(std::memory_order_relaxed);
});
if (all_alive)
{
s_watchdog_next_check = now + s_watchdog_interval;
#ifdef HAVE_SYSTEMD
MXS_DEBUG("systemd watchdog keep-alive ping: sd_notify(false, \"WATCHDOG=1\")");
sd_notify(false, "WATCHDOG=1");
#endif
std::for_each(this_unit.ppWorkers, this_unit.ppWorkers + this_unit.nWorkers,
[](RoutingWorker* rw) {
rw->m_alive.store(false, std::memory_order_relaxed);
});
}
}
else
{
if (m_alive.load(std::memory_order_relaxed) == false)
{
m_alive.store(true, std::memory_order_relaxed);
}
}
}
}
}
size_t mxs_rworker_broadcast_message(uint32_t msg_id, intptr_t arg1, intptr_t arg2)
{
return RoutingWorker::broadcast_message(msg_id, arg1, arg2);
}
bool mxs_rworker_register_session(MXS_SESSION* session)
{
RoutingWorker* pWorker = RoutingWorker::get_current();
mxb_assert(pWorker);
return pWorker->session_registry().add(session);
}
bool mxs_rworker_deregister_session(uint64_t id)
{
RoutingWorker* pWorker = RoutingWorker::get_current();
mxb_assert(pWorker);
return pWorker->session_registry().remove(id);
}
MXS_SESSION* mxs_rworker_find_session(uint64_t id)
{
RoutingWorker* pWorker = RoutingWorker::get_current();
mxb_assert(pWorker);
return pWorker->session_registry().lookup(id);
}
MXB_WORKER* mxs_rworker_get(int worker_id)
{
return RoutingWorker::get(worker_id);
}
MXB_WORKER* mxs_rworker_get_current()
{
return RoutingWorker::get_current();
}
int mxs_rworker_get_current_id()
{
return RoutingWorker::get_current_id();
}
namespace
{
using namespace maxscale;
class WorkerInfoTask : public Worker::Task
{
public:
WorkerInfoTask(const char* zHost, uint32_t nThreads)
: m_zHost(zHost)
{
m_data.resize(nThreads);
}
void execute(Worker& worker)
{
RoutingWorker& rworker = static_cast<RoutingWorker&>(worker);
json_t* pStats = json_object();
const Worker::STATISTICS& s = rworker.statistics();
json_object_set_new(pStats, "reads", json_integer(s.n_read));
json_object_set_new(pStats, "writes", json_integer(s.n_write));
json_object_set_new(pStats, "errors", json_integer(s.n_error));
json_object_set_new(pStats, "hangups", json_integer(s.n_hup));
json_object_set_new(pStats, "accepts", json_integer(s.n_accept));
json_object_set_new(pStats, "avg_event_queue_length", json_integer(s.evq_avg));
json_object_set_new(pStats, "max_event_queue_length", json_integer(s.evq_max));
json_object_set_new(pStats, "max_exec_time", json_integer(s.maxexectime));
json_object_set_new(pStats, "max_queue_time", json_integer(s.maxqtime));
uint32_t nCurrent;
uint64_t nTotal;
rworker.get_descriptor_counts(&nCurrent, &nTotal);
json_object_set_new(pStats, "current_descriptors", json_integer(nCurrent));
json_object_set_new(pStats, "total_descriptors", json_integer(nTotal));
json_t* load = json_object();
json_object_set_new(load, "last_second", json_integer(rworker.load(Worker::Load::ONE_SECOND)));
json_object_set_new(load, "last_minute", json_integer(rworker.load(Worker::Load::ONE_MINUTE)));
json_object_set_new(load, "last_hour", json_integer(rworker.load(Worker::Load::ONE_HOUR)));
json_object_set_new(pStats, "load", load);
json_t* qc = qc_get_cache_stats_as_json();
if (qc)
{
json_object_set_new(pStats, "query_classifier_cache", qc);
}
json_t* pAttr = json_object();
json_object_set_new(pAttr, "stats", pStats);
int idx = rworker.id();
stringstream ss;
ss << idx;
json_t* pJson = json_object();
json_object_set_new(pJson, CN_ID, json_string(ss.str().c_str()));
json_object_set_new(pJson, CN_TYPE, json_string(CN_THREADS));
json_object_set_new(pJson, CN_ATTRIBUTES, pAttr);
json_object_set_new(pJson, CN_LINKS, mxs_json_self_link(m_zHost, CN_THREADS, ss.str().c_str()));
mxb_assert((size_t)idx < m_data.size());
m_data[idx] = pJson;
}
json_t* resource()
{
json_t* pArr = json_array();
for (auto it = m_data.begin(); it != m_data.end(); it++)
{
json_array_append_new(pArr, *it);
}
return mxs_json_resource(m_zHost, MXS_JSON_API_THREADS, pArr);
}
json_t* resource(int id)
{
stringstream self;
self << MXS_JSON_API_THREADS << id;
return mxs_json_resource(m_zHost, self.str().c_str(), m_data[id]);
}
private:
vector<json_t*> m_data;
const char* m_zHost;
};
class FunctionTask : public Worker::DisposableTask
{
public:
FunctionTask(std::function<void ()> cb)
: m_cb(cb)
{
}
void execute(Worker& worker)
{
m_cb();
}
protected:
std::function<void ()> m_cb;
};
}
size_t mxs_rworker_broadcast(void (* cb)(void* data), void* data)
{
std::unique_ptr<FunctionTask> task(new FunctionTask([cb, data]() {
cb(data);
}));
return RoutingWorker::broadcast(std::move(task));
}
uint64_t mxs_rworker_create_key()
{
return RoutingWorker::create_key();
}
void mxs_rworker_set_data(uint64_t key, void* data, void (* callback)(void*))
{
RoutingWorker::get_current()->set_data(key, data, callback);
}
void* mxs_rworker_get_data(uint64_t key)
{
return RoutingWorker::get_current()->get_data(key);
}
void mxs_rworker_delete_data(uint64_t key)
{
auto func = [key]() {
RoutingWorker::get_current()->delete_data(key);
};
std::unique_ptr<FunctionTask> task(new FunctionTask(func));
RoutingWorker::broadcast(std::move(task));
}
json_t* mxs_rworker_to_json(const char* zHost, int id)
{
Worker* target = RoutingWorker::get(id);
WorkerInfoTask task(zHost, id + 1);
Semaphore sem;
target->execute(&task, &sem, Worker::EXECUTE_AUTO);
sem.wait();
return task.resource(id);
}
json_t* mxs_rworker_list_to_json(const char* host)
{
WorkerInfoTask task(host, config_threadcount());
RoutingWorker::execute_concurrently(task);
return task.resource();
}
namespace
{
class WatchdogTask : public Worker::Task
{
public:
WatchdogTask()
{
}
void execute(Worker& worker)
{
// Success if this is called.
}
};
}
void mxs_rworker_watchdog()
{
MXS_INFO("MaxScale watchdog called.");
WatchdogTask task;
RoutingWorker::execute_concurrently(task);
}
| 26.157664
| 107
| 0.612792
|
woopstar
|
86dab5549f3705d52d47065af2d8620098d40e2d
| 30,926
|
cpp
|
C++
|
annonet_train_main.cpp
|
reunanen/annonet
|
4767f4dee850d78e7c214ffdcc8002d7de8c683c
|
[
"MIT"
] | 7
|
2019-01-20T07:33:44.000Z
|
2022-01-17T09:41:33.000Z
|
annonet_train_main.cpp
|
reunanen/annonet
|
4767f4dee850d78e7c214ffdcc8002d7de8c683c
|
[
"MIT"
] | 5
|
2017-11-09T07:22:11.000Z
|
2020-05-08T14:09:12.000Z
|
annonet_train_main.cpp
|
reunanen/annonet
|
4767f4dee850d78e7c214ffdcc8002d7de8c683c
|
[
"MIT"
] | 2
|
2019-01-21T04:34:32.000Z
|
2019-02-27T17:41:13.000Z
|
/*
This example shows how to train a semantic segmentation net using images
annotated in the "anno" program (see https://github.com/reunanen/anno).
Instructions:
1. Use anno to label some data.
2. Build the annonet_train program.
3. Run:
./annonet_train /path/to/anno/data
4. Wait while the network is being trained.
5. Build the annonet_infer example program.
6. Run:
./annonet_infer /path/to/anno/data
*/
#include "annonet.h"
#include "annonet_train.h"
#include "cpp-read-file-in-memory/read-file-in-memory.h"
#include "cxxopts/include/cxxopts.hpp"
#include "lru-timday/shared_lru_cache_using_std.h"
#include "tuc/include/tuc/numeric.hpp"
#include <dlib/image_transforms.h>
#include <dlib/dir_nav.h>
#include <iostream>
#include <iterator>
#include <thread>
using namespace std;
using namespace dlib;
// ----------------------------------------------------------------------------------------
rectangle make_cropping_rect_around_defect(
int dim,
point center
)
{
return centered_rect(center, dim, dim);
}
// ----------------------------------------------------------------------------------------
namespace std {
template <>
struct hash<image_filenames_type> {
std::size_t operator()(const image_filenames_type& image_filenames) const {
return hash<string>()(image_filenames.image_filename + ", " + image_filenames.label_filename);
}
};
bool operator ==(const image_filenames_type& a, const image_filenames_type& b) {
return a.image_filename == b.image_filename
&& a.label_filename == b.label_filename;
}
}
// ----------------------------------------------------------------------------------------
struct crop
{
NetPimpl::input_type input_image;
NetPimpl::training_label_type label_image;
// prevent having to re-allocate memory constantly
dlib::matrix<uint16_t> temporary_unweighted_label_image;
std::string warning;
std::string error;
};
void add_random_noise(NetPimpl::input_type& image, double noise_level, dlib::rand& rnd)
{
const long long rounded_noise_level = static_cast<long long>(std::round(noise_level));
if (rounded_noise_level == 0) {
return;
}
const auto add_noise = [&rnd, rounded_noise_level](unsigned char old_value) {
int noise = static_cast<int>(rnd.get_integer_in_range(-rounded_noise_level, rounded_noise_level));
int new_value = static_cast<int>(old_value) + noise;
int new_value_clamped = std::max(0, std::min(new_value, static_cast<int>(std::numeric_limits<uint8_t>::max())));
return new_value_clamped;
};
const long nr = image.nr();
const long nc = image.nc();
for (long r = 0; r < nr; ++r) {
for (long c = 0; c < nc; ++c) {
#ifdef DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
image(r, c) = add_noise(image(r, c));
#else // DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
auto& pixel = image(r, c);
pixel.red = add_noise(pixel.red);
pixel.green = add_noise(pixel.green);
pixel.blue = add_noise(pixel.blue);
#endif // DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
}
}
}
struct randomly_crop_image_temp {
NetPimpl::input_type input_image;
dlib::matrix<uint16_t> label_image;
};
void randomly_crop_image(
int dim,
const sample_type& full_sample,
crop& crop,
dlib::rand& rnd,
const cxxopts::Options& options,
randomly_crop_image_temp& temp
)
{
DLIB_CASSERT(!full_sample.labeled_points_by_class.empty());
const size_t class_index = rnd.get_random_32bit_number() % full_sample.labeled_points_by_class.size();
auto i = full_sample.labeled_points_by_class.begin();
for (size_t j = 0; j < class_index; ++i, ++j) {
DLIB_CASSERT(i != full_sample.labeled_points_by_class.end());
}
DLIB_CASSERT(i != full_sample.labeled_points_by_class.end());
DLIB_CASSERT(!i->second.empty());
const size_t point_index = rnd.get_random_64bit_number() % i->second.size();
const double further_downscaling_factor = options["further-downscaling-factor"].as<double>();
const int dim_before_downscaling = std::round(dim * further_downscaling_factor);
const rectangle rect = random_rect_containing_point(rnd, i->second[point_index], dim_before_downscaling, dim_before_downscaling);
const chip_details chip_details(rect, chip_dims(dim_before_downscaling, dim_before_downscaling));
const dlib::rectangle valid_rect_in_full_image = rect.intersect(dlib::rectangle(0, 0, full_sample.input_image.nc() - 1, full_sample.input_image.nr() - 1));
const dlib::rectangle valid_rect_in_crop_image(
valid_rect_in_full_image.left() - rect.left(),
valid_rect_in_full_image.top() - rect.top(),
valid_rect_in_full_image.left() - rect.left() + valid_rect_in_full_image.width() - 1,
valid_rect_in_full_image.top() - rect.top() + valid_rect_in_full_image.height() - 1
);
const auto set_to_unknown_outside = [](dlib::matrix<uint16_t>& label_image, const rectangle& inside) {
for (long r = 0, nr = label_image.nr(); r < nr; ++r) {
for (long c = 0, nc = label_image.nc(); c < nc; ++c) {
if (!inside.contains(c, r)) {
label_image(r, c) = dlib::loss_multiclass_log_per_pixel_::label_to_ignore;
}
}
}
};
if (further_downscaling_factor > 1.0) {
extract_image_chip(full_sample.input_image, chip_details, temp.input_image, interpolate_bilinear());
extract_image_chip(full_sample.label_image, chip_details, temp.label_image, interpolate_nearest_neighbor());
dlib::image_view<NetPimpl::input_type> view(temp.input_image);
outpaint(view, valid_rect_in_crop_image);
set_to_unknown_outside(temp.label_image, valid_rect_in_crop_image);
crop.input_image.set_size(dim, dim);
crop.temporary_unweighted_label_image.set_size(dim, dim);
dlib::resize_image(temp.input_image, crop.input_image, interpolate_bilinear());
dlib::resize_image(temp.label_image, crop.temporary_unweighted_label_image, interpolate_nearest_neighbor());
}
else {
extract_image_chip(full_sample.input_image, chip_details, crop.input_image, interpolate_bilinear());
extract_image_chip(full_sample.label_image, chip_details, crop.temporary_unweighted_label_image, interpolate_nearest_neighbor());
dlib::image_view<NetPimpl::input_type> view(crop.input_image);
outpaint(view, valid_rect_in_crop_image);
set_to_unknown_outside(crop.temporary_unweighted_label_image, valid_rect_in_crop_image);
}
set_weights(crop.temporary_unweighted_label_image, crop.label_image, options["class-weight"].as<double>(), options["image-weight"].as<double>());
// Randomly flip the input image and the labels.
const bool allow_flip_left_right = options.count("allow-flip-left-right") > 0;
const bool allow_flip_upside_down = options.count("allow-flip-upside-down") > 0;
if (allow_flip_left_right && rnd.get_random_double() > 0.5) {
crop.input_image = fliplr(crop.input_image);
crop.label_image = fliplr(crop.label_image);
}
if (allow_flip_upside_down && rnd.get_random_double() > 0.5) {
crop.input_image = flipud(crop.input_image);
crop.label_image = flipud(crop.label_image);
}
const double multiplicative_brightness_change_probability = options["multiplicative-brightness-change-probability"].as<double>();
if (multiplicative_brightness_change_probability > 0.0 && rnd.get_double_in_range(0, 1) < multiplicative_brightness_change_probability) {
const double multiplicative_brightness_change_sigma = options["multiplicative-brightness-change-sigma"].as<double>();
const double multiplicative_brightness_change = exp(rnd.get_random_gaussian() * multiplicative_brightness_change_sigma);
const long nr = crop.input_image.nr();
const long nc = crop.input_image.nc();
const auto apply = [multiplicative_brightness_change](unsigned char value) {
return tuc::round<unsigned char>(tuc::clamp(value * multiplicative_brightness_change, 0.0, 255.0));
};
for (long r = 0; r < nr; ++r) {
for (long c = 0; c < nc; ++c) {
auto& pixel = crop.input_image(r, c);
#ifndef DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
pixel.red = apply(pixel.red);
pixel.green = apply(pixel.green);
pixel.blue = apply(pixel.blue);
#else // DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
pixel = apply(pixel);
#endif // DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
}
}
}
double noise_level_stddev = options["noise-level-stddev"].as<double>();
if (noise_level_stddev > 0.0) {
double noise_level = fabs(rnd.get_random_gaussian() * noise_level_stddev);
add_random_noise(crop.input_image, noise_level, rnd);
}
#ifndef DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
const bool allow_random_color_offset = options.count("allow-random-color-offset") > 0;
if (allow_random_color_offset) {
apply_random_color_offset(crop.input_image, rnd);
}
#endif // DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
}
// ----------------------------------------------------------------------------------------
std::string read_anno_classes_file(const std::string& folder)
{
const std::vector<file> files = get_files_in_directory_tree(folder,
[](const file& name) {
return name.name() == "anno_classes.json";
}, 0); // do not scan subdirectories - the file must be in the root
if (files.empty()) {
std::cout << "Warning: no anno_classes.json file found in " + folder << std::endl;
std::cout << " --> Using the default anno classes" << std::endl;
return "";
}
if (files.size() > 1) {
throw std::runtime_error("Found multiple anno_classes.json files - this shouldn't happen");
}
const std::string json = read_file_as_string(files.front());
return json;
}
// ----------------------------------------------------------------------------------------
int main(int argc, char** argv) try
{
if (argc == 1)
{
cout << "To run this program you need data annotated using the anno program." << endl;
cout << endl;
cout << "You call this program like this: " << endl;
cout << "./annonet_train /path/to/anno/data" << endl;
return 1;
}
cxxopts::Options options("annonet_train", "Train semantic-segmentation networks using data generated in anno");
std::ostringstream default_data_loader_thread_count;
default_data_loader_thread_count << std::thread::hardware_concurrency();
options.add_options()
("d,initial-downscaling-factor", "The initial downscaling factor (>= 1.0)", cxxopts::value<double>()->default_value("1.0"))
("f,further-downscaling-factor", "The further downscaling factor (>= 1.0)", cxxopts::value<double>()->default_value("1.0"))
("i,input-directory", "Input image directory", cxxopts::value<std::string>())
("u,allow-flip-upside-down", "Randomly flip input images upside down")
("l,allow-flip-left-right", "Randomly flip input images horizontally")
("multiplicative-brightness-change-probability", "Probability of random multiplicative brightness change", cxxopts::value<double>()->default_value("0.0"))
("multiplicative-brightness-change-sigma", "Sigma of random multiplicative brightness change (in the event that it occurs in the first place)", cxxopts::value<double>()->default_value("0.1"))
("n,noise-level-stddev", "Set the standard deviation of the noise to add", cxxopts::value<double>()->default_value("0.0"))
#ifndef DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
("o,allow-random-color-offset", "Randomly apply color offsets")
#endif // DLIB_DNN_PIMPL_WRAPPER_GRAYSCALE_INPUT
("ignore-class", "Ignore specific classes by index", cxxopts::value<std::vector<uint16_t>>())
("ignore-large-nonzero-regions-by-area", "Ignore large non-zero regions by area", cxxopts::value<double>())
("ignore-large-nonzero-regions-by-width", "Ignore large non-zero regions by width", cxxopts::value<double>())
("ignore-large-nonzero-regions-by-height", "Ignore large non-zero regions by height", cxxopts::value<double>())
("class-weight", "Try 0.0 for equally balanced pixels, and 1.0 for equally balanced classes", cxxopts::value<double>()->default_value("0.5"))
("image-weight", "Try 0.0 for equally balanced pixels, and 1.0 for equally balanced images", cxxopts::value<double>()->default_value("0.5"))
("b,minibatch-size", "Set minibatch size", cxxopts::value<size_t>()->default_value("100"))
("input-dimension-multiplier", "Size of input patches, relative to minimum required", cxxopts::value<double>()->default_value("3.0"))
("net-width-scaler", "Scaler of net width", cxxopts::value<double>()->default_value("1.0"))
("net-width-min-filter-count", "Minimum net width filter count", cxxopts::value<int>()->default_value("1"))
("initial-learning-rate", "Set initial learning rate", cxxopts::value<double>()->default_value("0.1"))
("learning-rate-shrink-factor", "Set learning rate shrink factor", cxxopts::value<double>()->default_value("0.1"))
("min-learning-rate", "Set minimum learning rate", cxxopts::value<double>()->default_value("1e-6"))
("save-interval", "Save the resulting inference network every this many steps", cxxopts::value<size_t>()->default_value("1000"))
("t,relative-training-length", "Relative training length", cxxopts::value<double>()->default_value("2.0"))
("max-total-steps", "Set the maximum total number of steps", cxxopts::value<size_t>())
("c,cached-image-count", "Cached image count", cxxopts::value<int>()->default_value("8"))
("data-loader-thread-count", "Number of data loader threads", cxxopts::value<unsigned int>()->default_value(default_data_loader_thread_count.str()))
("no-empty-label-image-warning", "Do not warn about empty label images")
("primary-cuda-device", "Set the primary CUDA device to use", cxxopts::value<int>())
;
try {
options.parse_positional("input-directory");
options.parse(argc, argv);
cxxopts::check_required(options, { "input-directory" });
std::cout << "Input directory = " << options["input-directory"].as<std::string>() << std::endl;
std::cout << "Initial downscaling factor = " << options["initial-downscaling-factor"].as<double>() << std::endl;
std::cout << "Further downscaling factor = " << options["further-downscaling-factor"].as<double>() << std::endl;
if (options["initial-downscaling-factor"].as<double>() <= 0.0 || options["further-downscaling-factor"].as<double>() <= 0.0) {
throw std::runtime_error("The downscaling factors have to be strictly positive.");
}
}
catch (std::exception& e) {
cerr << e.what() << std::endl;
cerr << std::endl;
cerr << options.help() << std::endl;
return 2;
}
const double initial_downscaling_factor = options["initial-downscaling-factor"].as<double>();
const double further_downscaling_factor = options["further-downscaling-factor"].as<double>();
const double ignore_large_nonzero_regions_by_area = options.count("ignore-large-nonzero-regions-by-area") ? options["ignore-large-nonzero-regions-by-area"].as<double>() : std::numeric_limits<double>::infinity();
const double ignore_large_nonzero_regions_by_width = options.count("ignore-large-nonzero-regions-by-width") ? options["ignore-large-nonzero-regions-by-width"].as<double>() : std::numeric_limits<double>::infinity();
const double ignore_large_nonzero_regions_by_height = options.count("ignore-large-nonzero-regions-by-height") ? options["ignore-large-nonzero-regions-by-height"].as<double>() : std::numeric_limits<double>::infinity();
const bool allow_flip_upside_down = options.count("allow-flip-upside-down") > 0;
const std::vector<uint16_t> classes_to_ignore = options["ignore-class"].as<std::vector<uint16_t>>();
const auto minibatch_size = options["minibatch-size"].as<size_t>();
const auto input_dimension_multiplier = options["input-dimension-multiplier"].as<double>();
const auto net_width_scaler = options["net-width-scaler"].as<double>();
const auto net_width_min_filter_count = options["net-width-min-filter-count"].as<int>();
const auto initial_learning_rate = options["initial-learning-rate"].as<double>();
const auto learning_rate_shrink_factor = options["learning-rate-shrink-factor"].as<double>();
const auto min_learning_rate = options["min-learning-rate"].as<double>();
const auto save_interval = options["save-interval"].as<size_t>();
const auto relative_training_length = std::max(0.01, options["relative-training-length"].as<double>());
const auto cached_image_count = options["cached-image-count"].as<int>();
const auto data_loader_thread_count = std::max(1U, options["data-loader-thread-count"].as<unsigned int>());
const bool warn_about_empty_label_images = options.count("no-empty-label-image-warning") == 0;
std::cout << "Allow flipping input images upside down = " << (allow_flip_upside_down ? "yes" : "no") << std::endl;
std::cout << "Minibatch size = " << minibatch_size << std::endl;
std::cout << "Net width scaler = " << net_width_scaler << ", min filter count = " << net_width_min_filter_count << std::endl;
std::cout << "Initial learning rate = " << initial_learning_rate << std::endl;
std::cout << "Learning rate shrink factor = " << learning_rate_shrink_factor << std::endl;
std::cout << "Min learning rate = " << min_learning_rate << std::endl;
std::cout << "Save interval = " << save_interval << std::endl;
std::cout << "Relative training length = " << relative_training_length << std::endl;
std::cout << "Cached image count = " << cached_image_count << std::endl;
std::cout << "Data loader thread count = " << data_loader_thread_count << std::endl;
if (!classes_to_ignore.empty()) {
std::cout << "Classes to ignore =";
for (uint16_t class_to_ignore : classes_to_ignore) {
std::cout << " " << class_to_ignore;
}
std::cout << std::endl;
}
const int required_input_dimension = NetPimpl::TrainingNet::GetRequiredInputDimension();
std::cout << "Required input dimension = " << required_input_dimension << std::endl;
const int requested_input_dimension = static_cast<int>(std::round(input_dimension_multiplier * required_input_dimension));
std::cout << "Requested input dimension = " << requested_input_dimension << std::endl;
const int actual_input_dimension = NetPimpl::RuntimeNet::GetRecommendedInputDimension(requested_input_dimension);
std::cout << "Actual input dimension = " << actual_input_dimension << std::endl;
const auto anno_classes_json = read_anno_classes_file(options["input-directory"].as<std::string>());
const auto anno_classes = parse_anno_classes(anno_classes_json);
const unsigned long iterations_without_progress_threshold = static_cast<unsigned long>(std::round(relative_training_length * 2000));
const unsigned long previous_loss_values_dump_amount = static_cast<unsigned long>(std::round(relative_training_length * 400));
const unsigned long batch_normalization_running_stats_window_size = static_cast<unsigned long>(std::round(relative_training_length * 100));
if (options.count("primary-cuda-device") > 0) {
dlib::cuda::set_device(options["primary-cuda-device"].as<int>());
}
NetPimpl::TrainingNet training_net;
std::vector<NetPimpl::input_type> samples;
std::vector<NetPimpl::training_label_type> labels;
training_net.Initialize();
training_net.SetNetWidth(net_width_scaler, net_width_min_filter_count);
training_net.SetSynchronizationFile("annonet_trainer_state_file.dat", std::chrono::seconds(10 * 60));
training_net.BeVerbose();
training_net.SetClassCount(anno_classes.size());
training_net.SetLearningRate(initial_learning_rate);
training_net.SetLearningRateShrinkFactor(learning_rate_shrink_factor);
training_net.SetIterationsWithoutProgressThreshold(iterations_without_progress_threshold);
training_net.SetPreviousLossValuesDumpAmount(previous_loss_values_dump_amount);
training_net.SetAllBatchNormalizationRunningStatsWindowSizes(batch_normalization_running_stats_window_size);
cout << "\nSCANNING ANNO DATASET\n" << endl;
const auto image_files = find_image_files(options["input-directory"].as<std::string>(), true);
cout << "images in dataset: " << image_files.size() << endl;
if (image_files.size() == 0)
{
cout << "Didn't find an anno dataset. " << endl;
return 1;
}
const auto ignore_classes_to_ignore = [&classes_to_ignore](sample_type& sample) {
for (const auto class_to_ignore : classes_to_ignore) {
const auto i = sample.labeled_points_by_class.find(class_to_ignore);
if (i != sample.labeled_points_by_class.end()) {
for (const dlib::point& point : i->second) {
sample.label_image(point.y(), point.x()) = dlib::loss_multiclass_log_per_pixel_::label_to_ignore;
}
sample.labeled_points_by_class.erase(class_to_ignore);
}
}
};
const auto ignore_large_nonzero_regions = [ignore_large_nonzero_regions_by_area, ignore_large_nonzero_regions_by_width, ignore_large_nonzero_regions_by_height](sample_type& sample) {
if (sample.labeled_points_by_class.empty()) {
return; // no annotations
}
if (sample.labeled_points_by_class.size() == 1 && sample.labeled_points_by_class.begin()->first == 0) {
return; // background only
}
const auto receptive_field_side = NetPimpl::TrainingNet::GetRequiredInputDimension();
const double receptive_field_area = receptive_field_side * receptive_field_side;
const double max_blob_point_count_to_keep = ignore_large_nonzero_regions_by_area * receptive_field_area;
const double max_blob_width_to_keep = ignore_large_nonzero_regions_by_width * receptive_field_side;
const double max_blob_height_to_keep = ignore_large_nonzero_regions_by_height * receptive_field_side;
if (max_blob_point_count_to_keep >= sample.label_image.nr() * sample.label_image.nc() && max_blob_width_to_keep >= sample.label_image.nc() && max_blob_height_to_keep >= sample.label_image.nr()) {
return; // would keep everything in any case
}
dlib::matrix<unsigned long> blobs;
const unsigned long blob_count = dlib::label_connected_blobs(sample.label_image, zero_and_ignored_pixels_are_background(), neighbors_8(), connected_if_equal(), blobs);
std::vector<std::deque<dlib::point>> blob_points(blob_count);
std::vector<std::pair<long, long>> blob_minmax_x(blob_count, std::make_pair(std::numeric_limits<long>::max(), std::numeric_limits<long>::min()));
std::vector<std::pair<long, long>> blob_minmax_y(blob_count, std::make_pair(std::numeric_limits<long>::max(), std::numeric_limits<long>::min()));
for (const auto& labeled_points : sample.labeled_points_by_class) {
for (const dlib::point& point : labeled_points.second) {
const unsigned long blob_index = blobs(point.y(), point.x());
blob_points[blob_index].push_back(point);
blob_minmax_x[blob_index].first = std::min(point.x(), blob_minmax_x[blob_index].first);
blob_minmax_x[blob_index].second = std::max(point.x(), blob_minmax_x[blob_index].second);
blob_minmax_y[blob_index].first = std::min(point.y(), blob_minmax_y[blob_index].first);
blob_minmax_y[blob_index].second = std::max(point.y(), blob_minmax_y[blob_index].second);
}
}
decltype(sample.labeled_points_by_class) labeled_points_to_keep;
for (unsigned long blob_index = 0; blob_index < blob_count; ++blob_index) {
const auto& points = blob_points[blob_index];
if (points.empty()) {
continue; // nothing to do
}
const auto ignore_blob_by_size = [&]() {
if (points.size() > max_blob_point_count_to_keep) {
return true;
}
const auto blob_width = [&]() { return blob_minmax_x[blob_index].second - blob_minmax_x[blob_index].first + 1; };
const auto blob_height = [&]() { return blob_minmax_y[blob_index].second - blob_minmax_y[blob_index].first + 1; };
if (blob_width() > max_blob_width_to_keep || blob_height() > max_blob_height_to_keep) {
return true;
}
return false;
};
if (blob_index == 0 || !ignore_blob_by_size()) {
// keep
const auto point = points.front();
const uint16_t label = sample.label_image(point.y(), point.x());
#ifdef _DEBUG
for (size_t i = 1, end = points.size(); i < end; ++i) {
assert(sample.label_image(point.y(), point.x()) == label);
}
#endif // _DEBUG
std::move(points.begin(), points.end(), std::back_inserter(labeled_points_to_keep[label]));
}
else {
// ignore
for (const auto& point : points) {
uint16_t& label = sample.label_image(point.y(), point.x());
label = dlib::loss_multiclass_log_per_pixel_::label_to_ignore;
}
}
}
std::swap(sample.labeled_points_by_class, labeled_points_to_keep);
};
shared_lru_cache_using_std<image_filenames_type, std::shared_ptr<sample_type>, std::unordered_map> full_images_cache(
[&](const image_filenames_type& image_filenames) {
auto sample = std::make_shared<sample_type>();
*sample = read_sample(image_filenames, anno_classes, true, initial_downscaling_factor);
ignore_classes_to_ignore(*sample);
return sample;
}, cached_image_count);
cout << endl << "Now training..." << endl;
set_low_priority();
// Start a bunch of threads that read images from disk and pull out random crops. It's
// important to be sure to feed the GPU fast enough to keep it busy. Using multiple
// thread for this kind of data preparation helps us do that. Each thread puts the
// crops into the data queue.
dlib::pipe<crop> data(2 * minibatch_size);
auto pull_crops = [&data, &full_images_cache, &image_files, actual_input_dimension, &options](time_t seed)
{
dlib::rand rnd(time(0)+seed);
NetPimpl::input_type input_image;
matrix<uint16_t> index_label_image;
crop crop;
randomly_crop_image_temp temp;
while (data.is_enabled())
{
crop.error.clear();
crop.warning.clear();
const size_t index = rnd.get_random_32bit_number() % image_files.size();
const auto& image_filenames = image_files[index];
const std::shared_ptr<sample_type> ground_truth_sample = full_images_cache(image_filenames);
if (!ground_truth_sample->error.empty()) {
crop.error = ground_truth_sample->error;
}
else if (ground_truth_sample->labeled_points_by_class.empty()) {
crop.warning = "Warning: no labeled points in " + ground_truth_sample->image_filenames.label_filename;
}
else {
randomly_crop_image(actual_input_dimension, *ground_truth_sample, crop, rnd, options, temp);
}
data.enqueue(crop);
}
};
std::vector<std::thread> data_loaders;
for (unsigned int i = 0; i < data_loader_thread_count; ++i) {
data_loaders.push_back(std::thread([pull_crops, i]() { pull_crops(i); }));
}
size_t minibatch = 0;
const auto save_inference_net = [&]() {
const NetPimpl::RuntimeNet runtime_net = training_net.GetRuntimeNet();
std::ostringstream serialized;
runtime_net.Serialize(serialized);
cout << "saving network" << endl;
serialize("annonet.dnn") << anno_classes_json << (initial_downscaling_factor * further_downscaling_factor) << serialized.str();
};
std::set<std::string> warnings_already_printed;
const auto should_continue_training = [&]() {
if (training_net.GetLearningRate() < min_learning_rate) {
return false;
}
if (options.count("max-total-steps") > 0 && minibatch >= options["max-total-steps"].as<size_t>()) {
return false;
}
return true;
};
int return_value = 0;
try {
// The main training loop. Keep making mini-batches and giving them to the trainer.
while (should_continue_training())
{
samples.clear();
labels.clear();
// make a mini-batch
crop crop;
while (samples.size() < minibatch_size)
{
data.dequeue(crop);
if (!crop.error.empty()) {
throw std::runtime_error(crop.error);
}
else if (!crop.warning.empty()) {
if (warn_about_empty_label_images && warnings_already_printed.find(crop.warning) == warnings_already_printed.end()) {
std::cout << crop.warning << std::endl;
warnings_already_printed.insert(crop.warning);
}
}
else {
samples.push_back(std::move(crop.input_image));
labels.push_back(std::move(crop.label_image));
}
}
training_net.StartTraining(samples, labels);
if (minibatch++ % save_interval == 0) {
save_inference_net();
}
}
}
catch (std::exception& e) {
cout << e.what() << endl;
return_value = 2;
exit(return_value);
}
// Training done: tell threads to stop.
data.disable();
const auto join = [](std::vector<thread>& threads)
{
for (std::thread& thread : threads) {
thread.join();
}
};
join(data_loaders);
if (return_value == 0) {
save_inference_net();
}
return return_value;
}
catch(std::exception& e)
{
cout << e.what() << endl;
return 1;
}
| 48.397496
| 221
| 0.655015
|
reunanen
|
86db2ae6fb4c2499f34b02ec7739df4bf58d8ce8
| 724
|
hpp
|
C++
|
include/ui/SidebarIcon.hpp
|
davidcorbin/mygcc-application
|
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
|
[
"MIT"
] | 2
|
2019-01-18T02:33:45.000Z
|
2019-02-01T23:44:05.000Z
|
include/ui/SidebarIcon.hpp
|
davidcorbin/mygcc-application
|
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
|
[
"MIT"
] | null | null | null |
include/ui/SidebarIcon.hpp
|
davidcorbin/mygcc-application
|
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
|
[
"MIT"
] | null | null | null |
/**
* Copyright 2018 <David Corbin, Mitchell Harvey>
*/
#ifndef INCLUDE_UI_SIDEBARICON_HPP_
#define INCLUDE_UI_SIDEBARICON_HPP_
#include <include/ui/Image.hpp>
#include <include/types/Course.hpp>
#include <QPixmap>
#include <string>
class SidebarIcon {
public:
explicit SidebarIcon(Course *course);
explicit SidebarIcon(const std::string *iconName);
QPixmap setup();
QPixmap normal;
QPixmap active;
QPixmap selected;
private:
std::string loadIcon(const std::string *filename);
QPixmap scaleImage(QPixmap original);
QPixmap FromSvgToPixmap(const QSize &ImageSize, const QString &SvgFile);
void setIcon(Course *course);
const std::string *svgFilename;
};
#endif // INCLUDE_UI_SIDEBARICON_HPP_
| 22.625
| 74
| 0.756906
|
davidcorbin
|
86dd30c9954fe09ec7656bea91f4216e73f7871b
| 5,745
|
cpp
|
C++
|
Dodo/src/Core/System/AsciiDataFile.cpp
|
quesswho/Dodo
|
75408374a73e1cceb3e41ec25493f2abbaa447ee
|
[
"MIT"
] | 1
|
2020-06-09T21:11:08.000Z
|
2020-06-09T21:11:08.000Z
|
Dodo/src/Core/System/AsciiDataFile.cpp
|
quesswho/Dodo
|
75408374a73e1cceb3e41ec25493f2abbaa447ee
|
[
"MIT"
] | 9
|
2020-11-17T07:54:06.000Z
|
2021-01-05T13:13:05.000Z
|
Dodo/src/Core/System/AsciiDataFile.cpp
|
quesswho/Dodo
|
75408374a73e1cceb3e41ec25493f2abbaa447ee
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "AsciiDataFile.h"
namespace Dodo {
AsciiDataFile::AsciiDataFile()
: m_CurrentLine(0), m_CurrentIndent(0), m_Indent({""})
{
m_CurrentLine = 0;
}
void AsciiDataFile::Clear()
{
m_File.clear();
m_CurrentIndent = 0;
}
void AsciiDataFile::Indent()
{
m_CurrentIndent++;
if (m_Indent.size()-1 < m_CurrentIndent)
{
std::string indent = "\t";
for (int i = 0; i < m_Indent.size() - 1; i++)
indent.append("\t");
m_Indent.push_back(indent);
}
}
void AsciiDataFile::UnIndent()
{
if(m_CurrentIndent > 0)
m_CurrentIndent--;
}
void AsciiDataFile::BeginRead(const char* path)
{
m_File.clear();
std::string temp;
std::stringstream ss(FileUtils::ReadTextFile(path));
while (std::getline(ss, temp, '\n'))
m_File.push_back(temp);
m_CurrentLine = 0;
}
std::string AsciiDataFile::GetEntryName(uint lineindex) const
{
std::string line = m_File[lineindex];
size_t index = line.find(':');
if (index == std::string::npos)
if (index = line.find('=') != std::string::npos)
return "";
line.erase(index);
if (line.find('\t') != std::string::npos)
return line.substr(line.find_last_of('\t') + 1, line.size());
else
return line.substr(0, line.size());
}
std::string AsciiDataFile::GetSection()
{
std::string line = m_File[m_CurrentLine];
m_CurrentLine++;
size_t index = line.find(':');
if (index == std::string::npos)
if(index = line.find('=') != std::string::npos)
return "";
line.erase(index);
if(line.find('\t') != std::string::npos)
return line.substr(line.find_last_of('\t') + 1, line.size());
else
return line.substr(0, line.size());
}
std::string AsciiDataFile::GetString()
{
std::string line = m_File[m_CurrentLine];
m_CurrentLine++;
size_t quote = line.find('"');
if (line[quote - 1] == '=')
{
line = line.substr(quote + 1);
line.erase(line.end() - 1);
return line;
}
DD_WARN("Not able to retrieve string at line: {}", m_CurrentLine-1);
return "";
}
int AsciiDataFile::GetInt()
{
std::string str = m_File[m_CurrentLine];
m_CurrentLine++;
try
{
size_t loc = str.find('=');
if(loc != std::string::npos)
return std::stoi(str.substr(loc + 1));
}
catch (...)
{}
DD_WARN("Not able to retrieve int at line: {}", m_CurrentLine-1);
return 0;
}
double AsciiDataFile::GetDouble()
{
std::string str = m_File[m_CurrentLine];
m_CurrentLine++;
try
{
size_t loc = str.find('=');
if (loc != std::string::npos)
return std::stod(str.substr(loc + 1));
}
catch (...)
{
}
DD_WARN("Not able to retrieve double at line: {}", m_CurrentLine-1);
return 0.0;
}
float AsciiDataFile::GetFloat()
{
std::string str = m_File[m_CurrentLine];
m_CurrentLine++;
try
{
size_t loc = str.find('=');
if (loc != std::string::npos)
return std::stof(str.substr(loc + 1));
}
catch (...)
{
}
DD_WARN("Not able to retrieve float at line: {}", m_CurrentLine-1);
return 0.0f;
}
Math::Vec2 AsciiDataFile::GetVec2()
{
std::string str = m_File[m_CurrentLine];
m_CurrentLine++;
try
{
size_t loc = str.find(',');
return Math::Vec2(std::stof(str.substr(str.find('=') + 1, loc - 1)), std::stof(str.substr(loc + 1, str.size())));
}
catch (...)
{
}
DD_WARN("Not able to retrieve vec2 at line: {}", m_CurrentLine-1);
return Math::Vec2(0.0f);
}
Math::Vec3 AsciiDataFile::GetVec3()
{
std::string str = m_File[m_CurrentLine];
m_CurrentLine++;
try
{
size_t loc = str.find(',');
float x = std::stof(str.substr(str.find('=') + 1, loc - 1));
size_t loc2 = str.find(',', loc + 1);
float y = std::stof(str.substr(loc + 1, loc2 - 1));
float z = std::stof(str.substr(loc2 + 1, str.size()));
return Math::Vec3(x, y, z);
}
catch (...)
{
}
DD_WARN("Not able to retrieve vec3 at line: {}", m_CurrentLine-1);
return Math::Vec3(0.0f);
}
Math::Vec4 AsciiDataFile::GetVec4()
{
std::string str = m_File[m_CurrentLine];
m_CurrentLine++;
try
{
size_t loc = str.find(',');
float x = std::stof(str.substr(str.find('=') + 1, loc - 1));
size_t loc2 = str.find(',', loc + 1);
float y = std::stof(str.substr(loc + 1, loc2 - 1));
loc = str.find(',', loc2 + 1);
float z = std::stof(str.substr(loc2 + 1, loc - 1));
float w = std::stof(str.substr(loc + 1, str.size()));
return Math::Vec4(x, y, z, w);
}
catch (...)
{
}
DD_WARN("Not able to retrieve vec4 at line: {}", m_CurrentLine-1);
return Math::Vec4(0.0f);
}
Math::Transformation AsciiDataFile::GetTransformation()
{
try
{
std::string str = m_File[m_CurrentLine];
size_t loc = str.find(',');
float posX = std::stof(str.substr(str.find('=') + 1, loc - 1));
size_t loc2 = str.find(',', loc + 1);
float posY = std::stof(str.substr(loc + 1 , loc2 - 1));
float posZ = std::stof(str.substr(loc2 + 1, str.size()));
str = m_File[m_CurrentLine + 1];
loc = str.find(',');
float scaleX = std::stof(str.substr(str.find('=') + 1, loc - 1));
loc2 = str.find(',', loc + 1);
float scaleY = std::stof(str.substr(loc + 1, loc2 - 1));
float scaleZ = std::stof(str.substr(loc2 + 1, str.size()));
str = m_File[m_CurrentLine + 2];
loc = str.find(',');
float rotateX = std::stof(str.substr(str.find('=') + 1, loc - 1));
loc2 = str.find(',', loc + 1);
float rotateY = std::stof(str.substr(loc + 1, loc2 - 1));
float rotateZ = std::stof(str.substr(loc2 + 1, str.size()));
m_CurrentLine+=3;
return Math::Transformation(posX, posY, posZ, scaleX, scaleY, scaleZ, rotateX, rotateY, rotateZ);
}
catch (...)
{}
m_CurrentLine += 3;
DD_WARN("Not able to retrieve transformation at line: {}", m_CurrentLine-3);
return Math::Transformation();
}
}
| 24.037657
| 116
| 0.602611
|
quesswho
|
86df8a0a242ebabf3cb77d3adc5ba6b5492faf2b
| 6,918
|
hpp
|
C++
|
tests/math_unit/math/serializer.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
tests/math_unit/math/serializer.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
tests/math_unit/math/serializer.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef TEST_UNIT_MATH_SERIALIZER_HPP
#define TEST_UNIT_MATH_SERIALIZER_HPP
#include "util.hpp"
#include <stan/math.hpp>
#include <string>
#include <vector>
namespace stan {
namespace test {
/**
* A class to store a sequence of values which can be deserialized
* back into structured objects such as scalars, vectors, and
* matrixes.
*
* @tparam T type of scalars
*/
template <typename T>
struct deserializer {
/**
* Type of scalars in all objects.
*/
typedef T scalar_t;
/**
* Current read position.
*/
size_t position_;
/**
* The sequence of values to deserialize.
*/
const std::vector<T> vals_;
/**
* Construct a deserializer from the specified sequence of values.
*
* @param vals values to deserialize
*/
explicit deserializer(const std::vector<T>& vals)
: position_(0), vals_(vals) {}
/**
* Construct a deserializer from the specified sequence of values.
*
* @param vals values to deserialize
*/
explicit deserializer(const Eigen::Matrix<T, -1, 1>& v_vals)
: position_(0), vals_(to_std_vector(v_vals)) {}
/**
* Read a scalar conforming to the shape of the specified argument,
* here a scalar. The specified argument is only used for its
* shape---there is no relationship between the type of argument and
* type of result.
*
* @tparam U type of pattern scalar
* @param x pattern argument to determine result shape and size
* @return deserialized value with shape and size matching argument
*/
template <typename U>
T read(const U& x) {
return vals_[position_++];
}
/**
* Read a standard vector conforming to the shape of the specified
* argument, here a standard vector. The specified argument is only
* used for its shape---there is no relationship between the type of
* argument and type of result.
*
* @tparam U type of pattern sequence elements
* @param x pattern argument to determine result shape and size
* @return deserialized value with shape and size matching argument
*/
template <typename U>
typename stan::math::promote_scalar_type<T, std::vector<U>>::type read(
const std::vector<U>& x) {
typename stan::math::promote_scalar_type<T, std::vector<U>>::type y;
y.reserve(x.size());
for (size_t i = 0; i < x.size(); ++i)
y.push_back(read(x[i]));
return y;
}
/**
* Read a standard vector conforming to the shape of the specified
* argument, here an Eigen matrix, vector, or row vector. The
* specified argument is only used for its shape---there is no
* relationship between the type of argument and type of result.
*
* @tparam U type of pattern scalar
* @tparam R row specification for Eigen container
* @tparam C column specification for Eigen container
* @param x pattern argument to determine result shape and size
* @return deserialized value with shape and size matching argument
*/
template <typename U, int R, int C>
Eigen::Matrix<T, R, C> read(const Eigen::Matrix<U, R, C>& x) {
Eigen::Matrix<T, R, C> y(x.rows(), x.cols());
for (int i = 0; i < x.size(); ++i)
y(i) = read(x(i));
return y;
}
};
/**
* A structure to serialize structures to an internall stored sequence
* of scalars.
*
* @tparam T underlying scalar type
*/
template <typename T>
struct serializer {
/**
* Scalar type of serializer.
*/
typedef T scalar_t;
/**
* Container for serialized values.
*/
std::vector<T> vals_;
/**
* Construct a serializer.
*/
serializer() : vals_() {}
/**
* Serialize the specified scalar.
*
* @tparam U type of specified scalar; must be assignable to T
* @param x scalar to serialize
*/
template <typename U>
void write(const U& x) {
vals_.push_back(x);
}
/**
* Serialize the specified standard vector.
*
* @tparam U type of scalars; must be assignable to T
* @param x vector to serialize
*/
template <typename U>
void write(const std::vector<U>& x) {
for (size_t i = 0; i < x.size(); ++i)
write(x[i]);
}
/**
* Serialize the specified Eigen container.
*
* @tparam U type of scalars; must be assignable to T
* @tparam R row specification of Eigen container
* @tparam C column specification of Eigen container
* @param x Eigen container to serialize.
*/
template <typename U, int R, int C>
void write(const Eigen::Matrix<U, R, C>& x) {
for (int i = 0; i < x.size(); ++i)
write(x(i));
}
/**
* Return the serialized values as a standard vector.
*
* @return serialized values
*/
const std::vector<T>& array_vals() { return vals_; }
/**
* Return the serialized values as an Eigen vector.
*
* @return serialized values
*/
const Eigen::Matrix<T, -1, 1>& vector_vals() {
return to_eigen_vector(vals_);
}
};
/**
* Return a deserializer based on the specified values.
*
* @tparam T type of scalars in argument container and return
* @param vals values to deserialize
* @return deserializer based on specified values
*/
template <typename T>
deserializer<T> to_deserializer(const std::vector<T>& vals) {
return deserializer<T>(vals);
}
/**
* Return a deserializer based on the specified values.
*
* @tparam T type of scalars in argument container and return
* @param vals values to deserialize
* @return deserializer based on specified values
*/
template <typename T>
deserializer<T> to_deserializer(const Eigen::Matrix<T, -1, 1>& vals) {
return deserializer<T>(vals);
}
template <typename U>
void serialize_helper(serializer<U>& s) {}
template <typename U, typename T, typename... Ts>
void serialize_helper(serializer<U>& s, const T& x, const Ts... xs) {
s.write(x);
serialize_helper(s, xs...);
}
/**
* Serialize the specified sequence of objects, which all must have
* scalar types assignable to the result scalar type.
*
* @tparam U type of scalar in result vector
* @tparam Ts argument types
* @param xs arguments
* @return serialized form of arguments
*/
template <typename U, typename... Ts>
std::vector<U> serialize(const Ts... xs) {
serializer<U> s;
serialize_helper(s, xs...);
return s.vals_;
}
/**
* Serialized the specified single argument.
*
* @tparam T type of argument
* @param x argument to serialize
* @return serialized argument
*/
template <typename T>
std::vector<typename scalar_type<T>::type> serialize_return(const T& x) {
return serialize<typename scalar_type<T>::type>(x);
}
/**
* Serialize the specified sequence of structured objects with
* double-based scalars into an Eigen vector of double values.
*
* @tparam Ts types of argument sequence
* @param xs arguments to serialize
* @return serialized form of arguments
*/
template <typename... Ts>
Eigen::VectorXd serialize_args(const Ts... xs) {
return to_eigen_vector(serialize<double>(xs...));
}
} // namespace test
} // namespace stan
#endif
| 26.304183
| 73
| 0.67187
|
alashworth
|
86e3e388d098e2d1b0ba05eba62e2db1d3310b95
| 4,271
|
cpp
|
C++
|
devices/testcases/test_Ws2812bStrip.cpp
|
PhischDotOrg/phisch-lib
|
26df59d78533d3220a46e077ead5a5180a84d57a
|
[
"MIT"
] | null | null | null |
devices/testcases/test_Ws2812bStrip.cpp
|
PhischDotOrg/phisch-lib
|
26df59d78533d3220a46e077ead5a5180a84d57a
|
[
"MIT"
] | null | null | null |
devices/testcases/test_Ws2812bStrip.cpp
|
PhischDotOrg/phisch-lib
|
26df59d78533d3220a46e077ead5a5180a84d57a
|
[
"MIT"
] | null | null | null |
/*-
* $Copyright$
-*/
#include <gmock/gmock.h>
#include <devices/Ws2812bStrip.hpp>
#include <spi/SpiDevice.hpp>
namespace devices {
/*******************************************************************************
*
******************************************************************************/
class Ws2812bStripTest : public ::testing::Test {
protected:
static const unsigned m_length = 3;
typedef Ws2812bStripT<m_length, spi::SpiDeviceMock> Ws2812bStrip;
static constexpr uint8_t WS2812B_ON = Ws2812bStrip::WS2812B_ON;
static constexpr uint8_t WS2812B_OFF = Ws2812bStrip::WS2812B_OFF;
static const unsigned NUMBER_OF_WS2812B_BITS_PER_PIXEL;
static const unsigned SPI_BYTES_PER_WS2812B_COLOR;
static const unsigned SPI_BYTES_PER_WS2812B_PIXEL;
Ws2812bStrip * m_device;
spi::SpiDeviceMock m_spi;
size_t getSizeOfSpiData(void) const {
return sizeof(m_device->m_spiData);
}
void testConstants(void) const {
EXPECT_EQ(4u, m_device->SPI_BYTES_PER_WS2812B_COLOR);
}
uint8_t getSpiByte(const unsigned p_offs) const {
return this->m_device->m_spiData[p_offs];
}
public:
Ws2812bStripTest() : m_device(NULL) {
m_device = new Ws2812bStrip(m_spi);
}
virtual ~Ws2812bStripTest() {
delete m_device;
}
};
const unsigned Ws2812bStripTest::NUMBER_OF_WS2812B_BITS_PER_PIXEL = Ws2812bStripTest::Ws2812bStrip::NUMBER_OF_WS2812B_BITS_PER_PIXEL;
const unsigned Ws2812bStripTest::SPI_BYTES_PER_WS2812B_COLOR = Ws2812bStripTest::Ws2812bStrip::SPI_BYTES_PER_WS2812B_COLOR;
const unsigned Ws2812bStripTest::SPI_BYTES_PER_WS2812B_PIXEL = Ws2812bStripTest::Ws2812bStrip::SPI_BYTES_PER_WS2812B_PIXEL;
/*******************************************************************************
*
******************************************************************************/
TEST_F(Ws2812bStripTest, CreateAndDelete) {
}
/*******************************************************************************
*
******************************************************************************/
TEST_F(Ws2812bStripTest, Constants) {
EXPECT_EQ(24u, NUMBER_OF_WS2812B_BITS_PER_PIXEL);
EXPECT_EQ(4u, SPI_BYTES_PER_WS2812B_COLOR);
EXPECT_EQ(12u, SPI_BYTES_PER_WS2812B_PIXEL);
}
/*******************************************************************************
*
******************************************************************************/
TEST_F(Ws2812bStripTest, SizesOfDataTypes) {
EXPECT_EQ(3u, sizeof(Pixel::RGB));
EXPECT_EQ(this->m_length * 3 * (8/2), getSizeOfSpiData());
}
/*******************************************************************************
*
******************************************************************************/
TEST_F(Ws2812bStripTest, SetFirstPixel) {
const uint8_t red = 0x12; // [7:0] = b00010010
const uint8_t green = 0x34; // [7:0] = b00110100
const uint8_t blue = 0x56; // [7:0] = b01010110
const unsigned number = 0;
const unsigned base = 12 * number;
Pixel::RGB pixel(red, green, blue);
m_device->setPixel(number, pixel);
/* Validate Green Bits */
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_OFF), this->getSpiByte(base + 0 + 0));
EXPECT_EQ((WS2812B_ON << 4) | (WS2812B_ON ), this->getSpiByte(base + 0 + 1));
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_ON ), this->getSpiByte(base + 0 + 2));
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_OFF), this->getSpiByte(base + 0 + 3));
/* Validate Red Bits */
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_OFF), this->getSpiByte(base + 4 + 0));
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_ON ), this->getSpiByte(base + 4 + 1));
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_OFF), this->getSpiByte(base + 4 + 2));
EXPECT_EQ((WS2812B_ON << 4) | (WS2812B_OFF), this->getSpiByte(base + 4 + 3));
/* Validate Blue Bits */
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_ON ), this->getSpiByte(base + 8 + 0));
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_ON ), this->getSpiByte(base + 8 + 1));
EXPECT_EQ((WS2812B_OFF << 4) | (WS2812B_ON ), this->getSpiByte(base + 8 + 2));
EXPECT_EQ((WS2812B_ON << 4) | (WS2812B_OFF), this->getSpiByte(base + 8 + 3));
}
} /* namespace devices */
| 37.13913
| 134
| 0.553266
|
PhischDotOrg
|
86ea1fdc3db566015bce7efaac793e093c81db21
| 757
|
hpp
|
C++
|
liblink/native/include/coin.hpp
|
oklink-dev/bitlink
|
69705ccd8469a11375ad3c08c00c9dc54773355e
|
[
"MIT"
] | null | null | null |
liblink/native/include/coin.hpp
|
oklink-dev/bitlink
|
69705ccd8469a11375ad3c08c00c9dc54773355e
|
[
"MIT"
] | null | null | null |
liblink/native/include/coin.hpp
|
oklink-dev/bitlink
|
69705ccd8469a11375ad3c08c00c9dc54773355e
|
[
"MIT"
] | null | null | null |
/*
* coin.hpp
*
* Created on: 2015年3月9日
* Author: Administrator
*/
#ifndef BITLINK_COIN_HPP
#define BITLINK_COIN_HPP
#include <set>
#include <vector>
#include <map>
#include "model.hpp"
#include "db.hpp"
inline bool operator<(const coin &A, const coin &B)
{
return A.get_coin_id() < B.get_coin_id();
}
class coin_manager
{
public:
void load(Db& db);
void remove(coin &coin, Db& db);
std::vector<coin> find(const int amount);
coin &get(const std::string &tx_hash, const int index);
bool get(const std::string &tx_hash, const int index, coin &coin_);
bool add(const coin &coin_);
bool add(const std::vector<coin> &coins_);
private:
std::set<coin> _coin_set;
std::map<std::string, coin> _coin_map;
};
#endif /* BITLINK_COIN_HPP */
| 18.463415
| 68
| 0.689564
|
oklink-dev
|
86ea4b155c16fd59ab79c0d46623461273cc0380
| 355
|
cpp
|
C++
|
loj/1010loj.cpp
|
Shisir/Online-Judge
|
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
|
[
"MIT"
] | null | null | null |
loj/1010loj.cpp
|
Shisir/Online-Judge
|
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
|
[
"MIT"
] | null | null | null |
loj/1010loj.cpp
|
Shisir/Online-Judge
|
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int test,m,n;
scanf("%d",&test);
test++;
for(int t=1; t<test; t++)
{
scanf("%d%d",&m,&n);
if(m>n) swap(m,n);
if(m==1) printf("Case %d: %d\n",t,n);
else if(m==2) printf("Case %d: %d\n",t,((n/4)*4+min(n%4,2)*2));
else printf("Case %d: %d\n",t,(m*n+1)>>1);
}
return 0;
}
| 15.434783
| 65
| 0.495775
|
Shisir
|
86f0db66d7d7470ea6f31a82271a3362d9c5a734
| 12,519
|
cpp
|
C++
|
Tests/KeyPerformanceMeasuresTests/DFPCs/Reconstruction3D/DenseRegistrationFromStereo.cpp
|
H2020-InFuse/cdff
|
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
|
[
"BSD-2-Clause"
] | 7
|
2019-02-26T15:09:50.000Z
|
2021-09-30T07:39:01.000Z
|
Tests/KeyPerformanceMeasuresTests/DFPCs/Reconstruction3D/DenseRegistrationFromStereo.cpp
|
H2020-InFuse/cdff
|
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
|
[
"BSD-2-Clause"
] | null | null | null |
Tests/KeyPerformanceMeasuresTests/DFPCs/Reconstruction3D/DenseRegistrationFromStereo.cpp
|
H2020-InFuse/cdff
|
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
|
[
"BSD-2-Clause"
] | 1
|
2020-12-06T12:09:05.000Z
|
2020-12-06T12:09:05.000Z
|
/* --------------------------------------------------------------------------
*
* (C) Copyright …
*
* ---------------------------------------------------------------------------
*/
/*!
* @file DenseRegistrationFromStereo.cpp
* @date 29/06/2018
* @author Alessandro Bianco
*/
/*!
* @addtogroup DFNsTest
*
* Validity Test 4.1.1.6 for DFPC implementation DenseRegistrationFromStereo.
* "Resulting point cloud should be within the expected bounds of error described in D5.2", and
* "Expected performance is no more than 10% outliers as estimated by a human inspecting the point cloud", and
* "position estimation less than 1% of R, where R is the maximum operational distance of the camera/sensor", and
* "90% similarity in shape to the object viewed with less than 10% error in dimensional analysis (only for components larger than 10% of the total size of the object)"
*
* @{
*/
/* --------------------------------------------------------------------------
*
* Includes
*
* --------------------------------------------------------------------------
*/
#include "ReconstructionExecutor.hpp"
#include <Reconstruction3D/DenseRegistrationFromStereo.hpp>
#include <Errors/Assert.hpp>
using namespace CDFF::DFPC;
using namespace CDFF::DFPC::Reconstruction3D;
/* --------------------------------------------------------------------------
*
* Test Cases
*
* --------------------------------------------------------------------------
*/
const std::string USAGE =
" \n \
The program has four usages depending on the first parameter: \n \
(i) 1st parameter is the mode of operation it can be one of (ComputePointCloud, EvaluateOutliers, EvaluateDistanceToCamera, EvaluateDimensions). The modes are explained one by one: \n \n \n \
Mode (a. ComputePointCloud) in this mode the stereo reconstruction dfn is executed and its result is saved to a ply file, you need 5 additional parameters: \n \
(a.ii) 2nd parameter is the configuration file path of the dfpc implementation RegistrationFromStereo; \n \
(a.iii) 3rd parameter is the folder containing the images list file; \n \
(a.iv) 4th is the image list file name (the file contains three blank lines, and then a triple for each line of the form: timeFloat pathToLeftImage pathToRightImage; \n \
(a.v) 5th is the output cloud file path, in ply format; \n \
(a.vi) 6th is the output poses file \n \n \
Example usage: ./quality_registration_from_stereo ComputePointCloud ../tests/ConfigurationFiles/DFPCs/Reconstruction3D/DfpcRegistrationFromStereo_DevonIsland.yaml \
../tests/Data/Images ImagesList.txt ../tests/Data/PointClouds/Road.ply \n \n \n \
After you run (a), you should open the result with the tool DataGenerator/detect_outliers. Using the tool, you should detect those cloud points which should not appear in the scene. \
The result is used by the second step of the program to assess the quality of the point cloud. \n \n \
Example call: ./detect_outliers ../tests/Data/PointClouds/Road.ply ../tests/Data/PointClouds/RoadOutliers.xml \n \n \n \
Mode (b. EvaluateOutliers) the program will assess whether the data meets the outliers required quality. In this case the parameters have the following meaning: \n \
(b.ii) 2nd parameter is the point cloud file produced by the application of the dfn, it is in ply format. \n \
(b.iii) 3rd parameter is the file containing the outliers in xml format \n \
Optionally you can add one more parameter: \n \
(b.iv) 4th optional parameter is outliers percentage threshold for the quality check. It must be a number between 0 and 1; The default is 0.10. \n \n \
Example usage: ./quality_registration_from_stereo EvaluateOutliers ../tests/Data/PointClouds/Road.ply ../tests/Data/PointClouds/RoadOutliers.xml \n \n \n \
Mode (c. EvaluateDistanceToCamera) the program will assess whether the data meets the required quality in terms of distances to the camera. In this case the parameters have the following meaning: \n \
(c.ii) 2nd parameter is the point cloud file produced by the application of the dfn, it is in ply format. \n \
(c.iii) 3rd parameter is the file containing the measures of the distances in xml format \n \
(c.iv) 4th parameter is the camera maximum operational distance expressed in meters \n \
Optionally you can add one more parameter: \n \
(c.v) 5th optional parameter is the camera distance percentage error with respect to the operating distance. It must be a number betwee 0 and 1; The default is 0.01. \n \n \
Example usage: ./quality_registration_from_stereo EvaluateDistanceToCamera ../tests/Data/PointClouds/Road.ply ../tests/Data/PointClouds/RoadMeasures.xml 10 \n \n \n \
Mode (d. EvaluateDimensions) the program will assess whether the data meets the required quality in terms of objects dimensions. In this case the parameters have the following meaning: \n \
(b.ii) 2nd parameter is the point cloud file produced by the application of the dfn, it is in ply format. \n \
(b.iii) 3rd parameter is the file containing the measures of the distances in xml format \n \
Optionally you can add three more parameters: \n \
(b.iv) 4th optional parameter is the shape similarity threshold. It must be a number betwee 0 and 1; The default is 0.90. \n \
(b.v) 5th optional parameter is the dimensional error threshold. It must be a number betwee 0 and 1; The default is 0.10. \n \
(b.vi) 6th optional parameter is the theshold on the object component that determines how large a component should be with respect to the whole object in order to be considered in the evaluation of the dimensional error. It must be a number betwee 0 and 1; The default is 0.10. \n \n \
Example usage: ./quality_sparse_registration_from_stereo EvaluateDimensions ../tests/Data/PointClouds/Road.ply ../tests/Data/PointClouds/RoadMeasures.xml \n";
float ExtractOutliersPercentageThreshold(char* argument)
{
const std::string errorMessage = "The 4th parameter numberPercentageThreshold has to be a floating point number between 0 and 1";
float outliersPercentageThreshold;
try
{
outliersPercentageThreshold = std::stof(argument);
}
catch (...)
{
ASSERT(false, errorMessage);
}
ASSERT(outliersPercentageThreshold >= 0 && outliersPercentageThreshold <= 1, errorMessage);
return outliersPercentageThreshold;
}
float ExtractCameraOperationaDistance(char* argument)
{
const std::string errorMessage = "The 4th parameter camera maximum operational distance has to be a floating point greater than 0";
float cameraOperationalDistance;
try
{
cameraOperationalDistance = std::stof(argument);
}
catch (...)
{
ASSERT(false, errorMessage);
}
ASSERT(cameraOperationalDistance >= 0, errorMessage);
return cameraOperationalDistance;
}
float ExtractCameraDistanceError(char* argument)
{
const std::string errorMessage = "The 5th parameter cameraDistanceError has to be a floating point number between 0 and 1";
float cameraDistanceError;
try
{
cameraDistanceError = std::stof(argument);
}
catch (...)
{
ASSERT(false, errorMessage);
}
ASSERT(cameraDistanceError >= 0 && cameraDistanceError <= 1, errorMessage);
return cameraDistanceError;
}
float ExtractShapeSimilarityThreshold(char* argument)
{
const std::string errorMessage = "The 4th parameter shapeSimilarityThreshold has to be a floating point number between 0 and 1";
float shapeSimilarityThreshold;
try
{
shapeSimilarityThreshold = std::stof(argument);
}
catch (...)
{
ASSERT(false, errorMessage);
}
ASSERT(shapeSimilarityThreshold >= 0 && shapeSimilarityThreshold <= 1, errorMessage);
return shapeSimilarityThreshold;
}
float ExtractDimensionalErrorThreshold(char* argument)
{
const std::string errorMessage = "The 5th parameter dimensionalErrorThreshold has to be a floating point number between 0 and 1";
float dimensionalErrorThreshold;
try
{
dimensionalErrorThreshold = std::stof(argument);
}
catch (...)
{
ASSERT(false, errorMessage);
}
ASSERT(dimensionalErrorThreshold >= 0 && dimensionalErrorThreshold <= 1, errorMessage);
return dimensionalErrorThreshold;
}
float ExtractComponentSizeThreshold(char* argument)
{
const std::string errorMessage = "The 6th parameter componentSizeThreshold has to be a floating point number between 0 and 1";
float componentSizeThreshold;
try
{
componentSizeThreshold = std::stof(argument);
}
catch (...)
{
ASSERT(false, errorMessage);
}
ASSERT(componentSizeThreshold >= 0 && componentSizeThreshold <= 1, errorMessage);
return componentSizeThreshold;
}
int mainComputePointCloudMode(int argc, char** argv, Reconstruction3DInterface* dfpc)
{
std::string configurationFilePath;
std::string inputImagesFolder;
std::string inputImagesListFileName;
std::string outputPointCloudFilePath;
std::string transformFilePath;
ASSERT(argc == 7, USAGE);
configurationFilePath = argv[2];
inputImagesFolder = argv[3];
inputImagesListFileName = argv[4];
outputPointCloudFilePath = argv[5];
transformFilePath = argv[6];
ReconstructionExecutor tester;
tester.SetDfpc(configurationFilePath, dfpc);
tester.SetInputFilesPaths(inputImagesFolder, inputImagesListFileName);
tester.ExecuteDfpc(transformFilePath);
tester.SaveOutputPointCloud(outputPointCloudFilePath);
return 0;
}
int mainEvaluateOutliersMode(int argc, char** argv)
{
std::string outputPointCloudFilePath;
std::string outliersReferenceFilePath;
float outliersPercentageThreshold = 0.10;
ASSERT(argc == 4 || argc == 5, USAGE);
outputPointCloudFilePath = argv[2];
outliersReferenceFilePath = argv[3];
if (argc == 5)
{
outliersPercentageThreshold = ExtractOutliersPercentageThreshold(argv[4]);
}
ReconstructionExecutor tester;
tester.SetOutputFilePath(outputPointCloudFilePath);
tester.SetOutliersFilePath(outliersReferenceFilePath);
bool success = tester.IsOutliersQualitySufficient(outliersPercentageThreshold);
VERIFY_REQUIREMENT(success, "Outliers Quality of reconstructed cloud requirement 4.1.1.6 failed on the input images");
return 0;
}
int mainEvaluateDistanceToCamera(int argc, char** argv)
{
std::string outputPointCloudFilePath;
std::string outliersMeasuresFilePath;
float cameraOperationDistance;
float cameraDistanceError = 0.01;
ASSERT(argc == 5 || argc == 6, USAGE);
outputPointCloudFilePath = argv[2];
outliersMeasuresFilePath = argv[3];
cameraOperationDistance = ExtractCameraOperationaDistance(argv[4]);
if (argc == 6)
{
cameraDistanceError = ExtractCameraDistanceError(argv[5]);
}
ReconstructionExecutor tester;
tester.SetOutputFilePath(outputPointCloudFilePath);
tester.SetMeasuresFilePath(outliersMeasuresFilePath);
bool success = tester.IsCameraDistanceQualitySufficient(cameraOperationDistance, cameraDistanceError);
VERIFY_REQUIREMENT(success, "Camera Distance Quality of reconstructed cloud requirement 4.1.1.6 failed on the input images");
return 0;
}
int mainEvaluateDimensions(int argc, char** argv)
{
std::string outputPointCloudFilePath;
std::string outliersMeasuresFilePath;
float shapeSimilarityThreshold = 0.90;
float dimensionalErrorThreshold = 0.10;
float componentSizeThreshold = 0.10;
ASSERT(argc >= 4 && argc <= 7, USAGE);
outputPointCloudFilePath = argv[2];
outliersMeasuresFilePath = argv[3];
if (argc == 5)
{
shapeSimilarityThreshold = ExtractShapeSimilarityThreshold(argv[4]);
}
if (argc == 6)
{
dimensionalErrorThreshold = ExtractDimensionalErrorThreshold(argv[5]);
}
if (argc == 7)
{
componentSizeThreshold = ExtractComponentSizeThreshold(argv[6]);
}
ReconstructionExecutor tester;
tester.SetOutputFilePath(outputPointCloudFilePath);
tester.SetMeasuresFilePath(outliersMeasuresFilePath);
bool success = tester.IsDimensionsQualitySufficient(shapeSimilarityThreshold, dimensionalErrorThreshold, componentSizeThreshold);
VERIFY_REQUIREMENT(success, "Dimensions Quality of reconstructed cloud requirement 4.1.1.6 failed on the input images");
return 0;
}
int main(int argc, char** argv)
{
ASSERT(argc >= 2, USAGE);
std::string mode = argv[1];
if (mode == "ComputePointCloud")
{
DenseRegistrationFromStereo* registrationFromStereo = new DenseRegistrationFromStereo();
return mainComputePointCloudMode(argc, argv, registrationFromStereo);
}
else if (mode == "EvaluateOutliers")
{
return mainEvaluateOutliersMode(argc, argv);
}
else if (mode == "EvaluateDistanceToCamera")
{
return mainEvaluateDistanceToCamera(argc, argv);
}
else if (mode == "EvaluateDimensions")
{
return mainEvaluateDimensions(argc, argv);
}
ASSERT(false, USAGE);
return 0;
}
/** @} */
| 38.52
| 285
| 0.738957
|
H2020-InFuse
|
86f1c54a66fce4aa622174ebcfa741670f523003
| 4,212
|
hpp
|
C++
|
Include/Extra/json_manage.hpp
|
JAOP1/GO
|
48c0275fd37bb552c0db4b968391a5a95ed6c860
|
[
"MIT"
] | null | null | null |
Include/Extra/json_manage.hpp
|
JAOP1/GO
|
48c0275fd37bb552c0db4b968391a5a95ed6c860
|
[
"MIT"
] | null | null | null |
Include/Extra/json_manage.hpp
|
JAOP1/GO
|
48c0275fd37bb552c0db4b968391a5a95ed6c860
|
[
"MIT"
] | 2
|
2019-12-12T18:55:35.000Z
|
2019-12-12T19:03:35.000Z
|
#pragma once
#include "External/json.hpp"
#include "Graph.hpp"
#include <fstream>
#include <iostream>
#include <tuple>
#include <vector>
using json = nlohmann::json;
namespace json_utils
{
// This give you the graph and positional vector.
template <class T>
std::tuple<Graph, std::vector<T>> get_json_to_graph_GUI(const std::string FileName)
{
std::cout << "Create graph with the name " << FileName << std::endl;
std::string Directory = "../Graphs/";
json j;
// write prettified JSON to another file
std::ifstream input_file;
input_file.open(Directory + FileName, std::ifstream::in);
input_file >> j;
int num_vertices = j["num vertices"];
Graph G(num_vertices);
std::vector<std::vector<int>> edges = j["edges"];
for (std::vector<int> edge : edges)
G.add_edge(edge[0], edge[1]);
int x, y;
std::vector<T> nodes_position;
for (int i = 0; i < num_vertices; ++i)
{
x = j["vertex " + std::to_string(i)]["x"];
y = j["vertex " + std::to_string(i)]["y"];
nodes_position.emplace_back(x, y);
}
input_file.close();
return std::make_tuple(G, nodes_position);
}
template <class T>
void save_graph_to_json(const std::string FileName, T graph_inf)
{
std::cout << "Saving graph with the name " << FileName << std::endl;
std::string Directory = "../Graphs/";
json j;
j["num vertices"] = graph_inf.num_vertices;
for (int i = 0; i < graph_inf.num_vertices; ++i)
{
j["vertex " + std::to_string(i)]["x"] = graph_inf.node_positions[i][0];
j["vertex " + std::to_string(i)]["y"] = graph_inf.node_positions[i][1];
}
j["edges"] = graph_inf.edges;
// write prettified JSON to another file
std::ofstream output_file;
output_file.open(Directory + FileName, std::ofstream::trunc);
output_file << j << std::endl;
output_file.close();
}
template <class game>
std::vector<game> get_json_to_game_data(const std::string FileName, bool is_training = true)
{
std::vector<game> games_played;
json J;
// write prettified JSON to another file
std::ifstream input_file;
input_file.open(FileName, std::ifstream::in);
input_file >> J;
std::string mode = "Test";
std::string Num_games = "Test_Games";
if(is_training)
{
mode = "Train";
Num_games = "Train_Games";
}
int total_recordings = J[Num_games];
for (int i = 0; i < total_recordings; ++i)
{
games_played.emplace_back(
J[mode]["Game " + std::to_string(i)]["state"],
// J["Game " + std::to_string(i)]["probabilities_by_action"],
J[mode]["Game " + std::to_string(i)]["valid_actions"],
J[mode]["Game " + std::to_string(i)]["black_reward"]);
}
input_file.close();
return games_played;
}
/*
Game structure has this attributes:
vector actions.
vector of probabilities vectors.
1 is the first player won the game.
*/
template <class episode>
void save_games_recordings_to_json(const std::string FileName,
std::vector<episode> games_played,
double training_percent = 1.0)
{
json JsonFile;
int total_games = games_played.size();
int train_games = total_games * training_percent;
int game_id = 0;
JsonFile["Train_Games"] = train_games;
JsonFile["Test_Games"] = total_games - train_games;
std::string mode = "Train";
for (auto G : games_played)
{
if(game_id == train_games && mode == "Train")
{
mode = "Test";
game_id = 0;
}
JsonFile[mode]["Game " + std::to_string(game_id)]["state"] = G.states;
JsonFile[mode]["Game " + std::to_string(game_id)]["valid_actions"] =
G.valid_actions;
//JsonFile["Game " + std::to_string(game_id)]["probabilities_by_action"] =
// G.probabilities;
JsonFile[mode]["Game " + std::to_string(game_id)]["black_reward"] =
G.black_reward;
game_id++;
}
std::ofstream output_file;
output_file.open(FileName, std::ofstream::trunc);
output_file << JsonFile << std::endl;
output_file.close();
}
} // namespace json_utils
| 28.653061
| 92
| 0.612773
|
JAOP1
|
86f2c6065e1604b1e069da765053ed225d6e0758
| 1,044
|
hpp
|
C++
|
Music/WaOn/SanWaOn/KyouWaOn/a_Body.hpp
|
p-adic/cpp
|
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
|
[
"MIT"
] | 2
|
2020-09-13T07:31:22.000Z
|
2022-03-26T08:37:32.000Z
|
Music/WaOn/SanWaOn/KyouWaOn/a_Body.hpp
|
p-adic/cpp
|
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
|
[
"MIT"
] | null | null | null |
Music/WaOn/SanWaOn/KyouWaOn/a_Body.hpp
|
p-adic/cpp
|
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
|
[
"MIT"
] | null | null | null |
// c:/Users/user/Documents/Programming/Music/WaOn/SanWaOn/KyouWaOn/a_Body.hpp
#pragma once
#include "a.hpp"
#include "../a_Body.hpp"
#include "../../../Chou/a_Body.hpp"
inline KyouWaOn::KyouWaOn( const Chou& N , const KaiMei& n ) noexcept : SanWaOn( N.OnMeiTable( n ) , N.OnMeiTable( n + 2 ) , N.OnMeiTable( n + 4 ) ) {}
inline bool KyouWaOn::IsValid() const noexcept { return OnDo( Pitch( GetOnMei( 0 ) , 0 ) , Pitch( GetOnMei( 2 ) , 1 ) ) != OnDo( Pitch( Ti() , 0 ) , Pitch( Fa() , 1 ) ); }
inline const OnMei& KyouWaOn::GetNeOn() const noexcept { return GetOnMei( 0 ); }
inline const OnMei& KyouWaOn::GetDaiSanOn() const noexcept { return GetOnMei( 1 ); }
inline const OnMei& KyouWaOn::GetDaiGoOn() const noexcept { return GetOnMei( 2 ); }
inline bool operator==( const KyouWaOn& H1 , const KyouWaOn& H2 ) noexcept { return H1.GetNeOn() == H2.GetNeOn() && H1.GetDaiSanOn() == H2.GetDaiSanOn() && H1.GetDaiGoOn() == H2.GetDaiGoOn(); }
inline bool operator!=( const KyouWaOn& H1 , const KyouWaOn& H2 ) noexcept { return !( H1 == H2 ); }
| 54.947368
| 193
| 0.665709
|
p-adic
|
86f355eefd383fda819260a388c9207232898057
| 823
|
cpp
|
C++
|
src/Leviathan/Leviathan.cpp
|
wakare/Leviathan
|
8a488f014d6235c5c6e6422c9f53c82635b7ebf7
|
[
"MIT"
] | 3
|
2019-03-05T13:05:30.000Z
|
2019-12-16T05:56:21.000Z
|
src/Leviathan/Leviathan.cpp
|
wakare/Leviathan
|
8a488f014d6235c5c6e6422c9f53c82635b7ebf7
|
[
"MIT"
] | null | null | null |
src/Leviathan/Leviathan.cpp
|
wakare/Leviathan
|
8a488f014d6235c5c6e6422c9f53c82635b7ebf7
|
[
"MIT"
] | null | null | null |
#include <memory>
#include <iostream>
#include "RenderService.h"
#include "EventListener.h"
#include "Event.h"
using namespace Leviathan;
class MyEventListener : public EventListener
{
public:
void Accept(Event& event);
};
inline void MyEventListener::Accept(Event & event)
{
if (event.m_action == Event::KEYDOWN && event.m_code == Event::KEY_Z)
{
LogLine("Z keydown for main");
}
}
bool _registerEventCallback()
{
LPtr<EventListener> eventListener = new MyEventListener();
EXIT_IF_FALSE(RenderService::Instance().AddEventListener(INPUT_EVENT, eventListener));
return true;
}
int main()
{
EXIT_IF_FALSE(_registerEventCallback());
/*EXIT_IF_FALSE(RenderService::Instance()->AttachNativeWin32Window(0));*/
EXIT_IF_FALSE(RenderService::Instance().Init(1920, 1080, NULL));
RenderService::Instance().Run();
}
| 21.657895
| 87
| 0.746051
|
wakare
|
86f3e739f4636f243773cbd08a97e1437858083e
| 860
|
cpp
|
C++
|
src/ogre3d/src/compile_OgreMain_0.cpp
|
werchou/ai-programming-with-lua
|
d9290fde56c01839e75bb2ea7d13c8f6c3594f5e
|
[
"Zlib"
] | 2
|
2021-03-13T03:53:28.000Z
|
2021-07-04T04:03:38.000Z
|
src/ogre3d/src/compile_OgreMain_0.cpp
|
werchou/ai-programming-with-lua
|
d9290fde56c01839e75bb2ea7d13c8f6c3594f5e
|
[
"Zlib"
] | null | null | null |
src/ogre3d/src/compile_OgreMain_0.cpp
|
werchou/ai-programming-with-lua
|
d9290fde56c01839e75bb2ea7d13c8f6c3594f5e
|
[
"Zlib"
] | 1
|
2021-02-22T04:38:57.000Z
|
2021-02-22T04:38:57.000Z
|
#include "OgreStableHeaders.h"
#include "OgreAlignedAllocator.cpp"
#include "OgreAnimable.cpp"
#include "OgreAnimation.cpp"
#include "OgreAnimationState.cpp"
#include "OgreAnimationTrack.cpp"
#include "OgreArchiveManager.cpp"
#include "OgreAtomicScalar.cpp"
#include "OgreAutoParamDataSource.cpp"
#include "OgreAxisAlignedBox.cpp"
#include "OgreBillboard.cpp"
#include "OgreBillboardChain.cpp"
#include "OgreBillboardParticleRenderer.cpp"
#include "OgreBillboardSet.cpp"
#include "OgreBone.cpp"
#include "OgreCamera.cpp"
#include "OgreCodec.cpp"
#include "OgreColourValue.cpp"
#include "OgreCommon.cpp"
#include "OgreCompositionPass.cpp"
#include "OgreCompositionTargetPass.cpp"
#include "OgreCompositionTechnique.cpp"
#include "OgreCompositor.cpp"
#include "OgreCompositorChain.cpp"
#include "OgreCompositorInstance.cpp"
#include "OgreCompositorManager.cpp"
| 30.714286
| 44
| 0.817442
|
werchou
|
86f7b97c5080b2d6174f4eb461f3da7e00597c89
| 2,309
|
hpp
|
C++
|
include/Gravity.hpp
|
dlasalle/gravitree
|
99a8ad2420216117bea4ec1e736b78a5c8fac737
|
[
"MIT"
] | null | null | null |
include/Gravity.hpp
|
dlasalle/gravitree
|
99a8ad2420216117bea4ec1e736b78a5c8fac737
|
[
"MIT"
] | 5
|
2018-08-04T17:44:33.000Z
|
2018-08-04T20:35:37.000Z
|
include/Gravity.hpp
|
dlasalle/gravitree
|
99a8ad2420216117bea4ec1e736b78a5c8fac737
|
[
"MIT"
] | null | null | null |
/**
* @file Gravity.hpp
* @brief The Gravity class.
* @author Dominique LaSalle <dominique@solidlake.com>
* Copyright 2018
* @version 1
* @date 2018-03-21
*/
#ifndef GRAVITREE_GRAVITY_HPP
#define GRAVITREE_GRAVITY_HPP
#include "Body.hpp"
namespace gravitree
{
class Gravity
{
public:
/**
* @brief The gravitational constant (in meters^3 / kg s^2).
*/
static constexpr double const G = 6.67408e-11;
/**
* @brief Calculate the acceleration of body of negligable mass towards a
* body of large mass.
*
* @param mass The mass of the large body.
* @param distance The distance of the small body from the large body.
*
* @return The acceleration (meters / second^2).
*/
inline static mps2_type acceleration(
kilo_type const mass,
meter_type const distance) noexcept
{
return force(1.0, mass, distance);
}
/**
* @brief Calculate the acceleration magnitude and direction of a neglibale
* mass towards a large mass.
*
* @param mass The large mass.
* @param offset The offset of the large mass.
*
* @return The acceleration in each dimension.
*/
inline static Vector3D acceleration(
kilo_type const mass,
Vector3D const offset)
{
return force(1.0, mass, offset);
}
/**
* @brief Get the force between two bodies.
*
* @param mass1 The mass of the first body.
* @param mass2 The mass of the second body.
* @param distance The distance between the center of mass of the two
* bodies.
*
* @return The force of attraction between the two bodies.
*/
inline static newton_type force(
kilo_type mass1,
kilo_type mass2,
meter_type distance) noexcept
{
return (G*mass1*mass2) / (distance*distance);
}
/**
* @brief Calculate the directional force between two bodies.
*
* @param mass1 The first mass.
* @param mass2 The second mass.
* @param offset The offset of the two masses.
*
* @return The force.
*/
inline static Vector3D force(
kilo_type const mass1,
kilo_type const mass2,
Vector3D const offset) noexcept
{
return -offset.normalized() * ((G*mass1*mass2) / offset.magnitude2());
}
};
}
#endif
| 22.861386
| 78
| 0.631442
|
dlasalle
|
86f7cca43b05099dbbd2bae838c441412c6737ef
| 1,205
|
hpp
|
C++
|
Light/include/light/rendering/mesh.hpp
|
R-Bread/Light
|
151308c0159c4fe0d795b3c16f205e4af68710d7
|
[
"MIT"
] | 1
|
2021-06-15T09:53:47.000Z
|
2021-06-15T09:53:47.000Z
|
Light/include/light/rendering/mesh.hpp
|
R-Bread/Light
|
151308c0159c4fe0d795b3c16f205e4af68710d7
|
[
"MIT"
] | 21
|
2021-06-10T09:07:19.000Z
|
2022-01-30T21:52:24.000Z
|
Light/include/light/rendering/mesh.hpp
|
R-Bread/Light
|
151308c0159c4fe0d795b3c16f205e4af68710d7
|
[
"MIT"
] | 9
|
2021-04-10T19:32:11.000Z
|
2021-05-19T16:29:25.000Z
|
#ifndef __MESH_H__
#define __MESH_H__
#include "core/base.hpp"
#include "light/rendering/vertexarray.hpp"
#include "glm/glm.hpp"
namespace Light
{
class Mesh
{
public:
Mesh(const std::vector<glm::vec3> &vertices,
const std::vector<glm::vec4> &colors,
const std::vector<glm::vec3> &normals,
const std::vector<unsigned int> &indices);
~Mesh() = default;
inline std::shared_ptr<VertexArray> getVao() const { return m_vao; }
private:
std::vector<glm::vec3> m_vertices;
std::vector<glm::vec4> m_colors;
std::vector<glm::vec3> m_normals;
std::vector<unsigned int> m_indices;
std::shared_ptr<VertexArray> m_vao;
};
class MeshLibrary
{
public:
void add(const std::string& name, std::shared_ptr<Mesh>& mesh);
void add(const std::string& name,
const std::vector<glm::vec3> &vertices,
const std::vector<glm::vec4> &colors,
const std::vector<glm::vec3> &normals,
const std::vector<unsigned int> &indices);
std::shared_ptr<Mesh> get(const std::string &name);
std::unordered_map<std::string, std::shared_ptr<Mesh>> getMeshMap() { return m_meshes; }
private:
std::unordered_map<std::string, std::shared_ptr<Mesh>> m_meshes;
};
}
#endif // __MESH_H__
| 23.627451
| 90
| 0.695436
|
R-Bread
|
86f8a1670a26ad1049af9038dbad80d5b4043385
| 23,798
|
cpp
|
C++
|
apps/RenderManagerOpenGLChessboard.cpp
|
sensics/OSVR-RenderManager
|
56f9db6279945a52327ffeac138b3ff81cf37438
|
[
"Apache-2.0"
] | 68
|
2016-02-16T13:40:01.000Z
|
2022-03-28T19:27:53.000Z
|
apps/RenderManagerOpenGLChessboard.cpp
|
sensics/OSVR-RenderManager
|
56f9db6279945a52327ffeac138b3ff81cf37438
|
[
"Apache-2.0"
] | 230
|
2016-02-16T13:41:56.000Z
|
2021-06-27T12:13:33.000Z
|
apps/RenderManagerOpenGLChessboard.cpp
|
sensics/OSVR-RenderManager
|
56f9db6279945a52327ffeac138b3ff81cf37438
|
[
"Apache-2.0"
] | 51
|
2016-02-20T15:37:37.000Z
|
2022-03-21T07:52:40.000Z
|
/** @file
@brief Example program that uses the OSVR direct-to-display interface
and the OpenGL Core profile to render a scene that has lots
of polygons. This can be used to do speed tests on various
cards, or regression tests on new versions.
@date 2015
@author
Russ Taylor <russ@sensics.com>
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/RenderKit/RenderManager.h>
// just where this header happens to be.
#include <osvr/Server/RegisterShutdownHandler.h>
// Library/third-party includes
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <GL/glew.h>
// Standard includes
#include <iostream>
#include <string>
#include <chrono>
#include <stdlib.h> // For exit()
// This must come after we include <GL/gl.h> so its pointer types are defined.
#include <osvr/RenderKit/GraphicsLibraryOpenGL.h>
#include <osvr/RenderKit/RenderKitGraphicsTransforms.h>
// normally you'd load the shaders from a file, but in this case, let's
// just keep things simple and load from memory.
static const GLchar* vertexShader = "#version 330 core\n"
"layout(location = 0) in vec3 position;\n"
"layout(location = 1) in vec3 vertexColor;\n"
"out vec3 fragmentColor;\n"
"uniform mat4 modelView;\n"
"uniform mat4 projection;\n"
"void main()\n"
"{\n"
" gl_Position = projection * modelView * vec4(position,1);\n"
" fragmentColor = vertexColor;\n"
"}\n";
static const GLchar* fragmentShader = "#version 330 core\n"
"in vec3 fragmentColor;\n"
"out vec3 color;\n"
"void main()\n"
"{\n"
" color = fragmentColor;\n"
"}\n";
class SampleShader {
public:
SampleShader() {}
~SampleShader() {
if (initialized) {
glDeleteProgram(programId);
}
}
void init() {
if (!initialized) {
GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
// vertex shader
glShaderSource(vertexShaderId, 1, &vertexShader, NULL);
glCompileShader(vertexShaderId);
checkShaderError(vertexShaderId, "Vertex shader compilation failed.");
// fragment shader
glShaderSource(fragmentShaderId, 1, &fragmentShader, NULL);
glCompileShader(fragmentShaderId);
checkShaderError(fragmentShaderId, "Fragment shader compilation failed.");
// linking program
programId = glCreateProgram();
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, fragmentShaderId);
glLinkProgram(programId);
checkProgramError(programId, "Shader program link failed.");
// once linked into a program, we no longer need the shaders.
glDeleteShader(vertexShaderId);
glDeleteShader(fragmentShaderId);
projectionUniformId = glGetUniformLocation(programId, "projection");
modelViewUniformId = glGetUniformLocation(programId, "modelView");
initialized = true;
}
}
void useProgram(const GLdouble projection[], const GLdouble modelView[]) {
init();
glUseProgram(programId);
GLfloat projectionf[16];
GLfloat modelViewf[16];
convertMatrix(projection, projectionf);
convertMatrix(modelView, modelViewf);
glUniformMatrix4fv(projectionUniformId, 1, GL_FALSE, projectionf);
glUniformMatrix4fv(modelViewUniformId, 1, GL_FALSE, modelViewf);
}
private:
SampleShader(const SampleShader&) = delete;
SampleShader& operator=(const SampleShader&) = delete;
bool initialized = false;
GLuint programId = 0;
GLuint projectionUniformId = 0;
GLuint modelViewUniformId = 0;
void checkShaderError(GLuint shaderId, const std::string& exceptionMsg) {
GLint result = GL_FALSE;
int infoLength = 0;
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result);
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLength);
if (result == GL_FALSE) {
std::vector<GLchar> errorMessage(infoLength + 1);
glGetProgramInfoLog(programId, infoLength, NULL, &errorMessage[0]);
std::cerr << &errorMessage[0] << std::endl;
throw std::runtime_error(exceptionMsg);
}
}
void checkProgramError(GLuint programId, const std::string& exceptionMsg) {
GLint result = GL_FALSE;
int infoLength = 0;
glGetProgramiv(programId, GL_LINK_STATUS, &result);
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLength);
if (result == GL_FALSE) {
std::vector<GLchar> errorMessage(infoLength + 1);
glGetProgramInfoLog(programId, infoLength, NULL, &errorMessage[0]);
std::cerr << &errorMessage[0] << std::endl;
throw std::runtime_error(exceptionMsg);
}
}
void convertMatrix(const GLdouble source[], GLfloat dest_out[]) {
if (nullptr == source || nullptr == dest_out) {
throw new std::logic_error("source and dest_out must be non-null.");
}
for (int i = 0; i < 16; i++) {
dest_out[i] = (GLfloat)source[i];
}
}
};
static SampleShader sampleShader;
inline size_t checkerBoard(size_t i, size_t j) { return (i % 2) ^ (j % 2); }
class MeshCube {
public:
MeshCube(GLfloat scale, size_t numTriangles = 6 * 2 * 15 * 15) {
// Figure out how many quads we have per edge. There
// is a minimum of 1.
size_t numQuads = numTriangles / 2;
size_t numQuadsPerFace = numQuads / 6;
size_t numQuadsPerEdge = static_cast<size_t>(sqrt(numQuadsPerFace));
if (numQuadsPerEdge < 1) {
numQuadsPerEdge = 1;
}
static const auto MAX_INTENSITY = 0.7f;
// Construct a white square with the specified number of
// quads as the +Z face of the cube. We'll copy this and
// then multiply by the correct face color, and we'll
// adjust the coordinates by rotation to match each face.
std::vector<GLfloat> whiteBufferData;
std::vector<GLfloat> faceBufferData;
auto getXorY = [&](size_t index) {
GLfloat val = -(2 * scale) + index * (4 * scale) / numQuadsPerEdge;
return val;
};
for (size_t i = 0; i < numQuadsPerEdge; i++) {
for (size_t j = 0; j < numQuadsPerEdge; j++) {
// Modulate the color of each quad by a random luminance,
// leaving all vertices the same color.
GLfloat color = checkerBoard(i, j) * MAX_INTENSITY;
const size_t numTris = 2;
const size_t numColors = 3;
const size_t numVerts = 3;
for (size_t c = 0; c < numColors * numTris * numVerts; c++) {
whiteBufferData.push_back(color);
}
// Send the two triangles that make up this quad, where the
// quad covers the appropriate fraction of the face from
// -scale to scale in X and Y.
GLfloat Z = scale;
GLfloat minX = getXorY(i);
GLfloat maxX = getXorY(i + 1);
GLfloat minY = getXorY(j);
GLfloat maxY = getXorY(j + 1);
faceBufferData.push_back(minX);
faceBufferData.push_back(maxY);
faceBufferData.push_back(Z);
faceBufferData.push_back(minX);
faceBufferData.push_back(minY);
faceBufferData.push_back(Z);
faceBufferData.push_back(maxX);
faceBufferData.push_back(minY);
faceBufferData.push_back(Z);
faceBufferData.push_back(maxX);
faceBufferData.push_back(maxY);
faceBufferData.push_back(Z);
faceBufferData.push_back(minX);
faceBufferData.push_back(maxY);
faceBufferData.push_back(Z);
faceBufferData.push_back(maxX);
faceBufferData.push_back(minY);
faceBufferData.push_back(Z);
}
}
std::array<GLfloat, 3> whiteModColor = {1.0f, 1.0f, 1.0f};
// Make a copy of the vertices for each face, then modulate
// the color by the face color and rotate the coordinates to
// put them on the correct cube face.
// -Z is in the opposite size from the
// original face (mirror all 3).
{
std::vector<GLfloat> myBufferData = colorModulate(whiteBufferData, whiteModColor);
// X = -X, Y = -Y, Z = -Z
std::array<GLfloat, 3> scales = {-1.0f, -1.0f, -1.0f};
std::array<size_t, 3> indices = {0, 1, 2};
std::vector<GLfloat> myFaceBufferData = vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(), myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(), myFaceBufferData.begin(), myFaceBufferData.end());
}
}
~MeshCube() {
if (initialized) {
glDeleteBuffers(1, &vertexBuffer);
glDeleteVertexArrays(1, &vertexArrayId);
}
}
void init() {
if (!initialized) {
// Vertex buffer
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexBufferData[0]) * vertexBufferData.size(), &vertexBufferData[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Color buffer
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(colorBufferData[0]) * colorBufferData.size(), &colorBufferData[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Vertex array object
glGenVertexArrays(1, &vertexArrayId);
glBindVertexArray(vertexArrayId);
{
// color
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
// VBO
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
}
glBindVertexArray(0);
initialized = true;
}
}
void draw(const GLdouble projection[], const GLdouble modelView[]) {
init();
sampleShader.useProgram(projection, modelView);
glBindVertexArray(vertexArrayId);
{ glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertexBufferData.size())); }
glBindVertexArray(0);
}
private:
MeshCube(const MeshCube&) = delete;
MeshCube& operator=(const MeshCube&) = delete;
bool initialized = false;
GLuint colorBuffer = 0;
GLuint vertexBuffer = 0;
GLuint vertexArrayId = 0;
std::vector<GLfloat> colorBufferData;
std::vector<GLfloat> vertexBufferData;
// Multiply each triple of colors by the specified color.
static std::vector<GLfloat> colorModulate(std::vector<GLfloat> const& inVec, std::array<GLfloat, 3> const& clr) {
std::vector<GLfloat> out;
size_t elements = inVec.size() / 3;
if (elements * 3 != inVec.size()) {
// We don't have an even multiple of 3 elements, so bail.
return out;
}
out = inVec;
for (size_t i = 0; i < elements; i++) {
for (size_t c = 0; c < 3; c++) {
out[3 * i + c] *= clr[c];
}
}
return out;
}
// Swizzle each triple of coordinates by the specified
// index and then multiply by the specified scale. This
// lets us implement a poor-man's rotation matrix, where
// we pick which element (0-2) and which polarity (-1 or
// 1) to use.
static std::vector<GLfloat> vertexRotate(std::vector<GLfloat> const& inVec, std::array<size_t, 3> const& indices,
std::array<GLfloat, 3> const& scales) {
std::vector<GLfloat> out;
size_t elements = inVec.size() / 3;
if (elements * 3 != inVec.size()) {
// We don't have an even multiple of 3 elements, so bail.
return out;
}
out.resize(inVec.size());
for (size_t i = 0; i < elements; i++) {
for (size_t p = 0; p < 3; p++) {
out[3 * i + p] = inVec[3 * i + indices[p]] * scales[p];
}
}
return out;
}
};
static std::unique_ptr<MeshCube> roomCube;
// Set to true when it is time for the application to quit.
typedef struct QuitStruct { volatile bool quit = false; } QuitStruct;
static QuitStruct quit;
// Note: On Windows, this runs in a different thread from
// the main application.
static void CtrlHandler() { quit.quit = true; }
// This callback sets a boolean value whose pointer is passed in to
// the state of the button that was pressed. This lets the callback
// be used to handle any button press that just needs to update state.
void myButtonCallback(void* userdata, const OSVR_TimeValue* /*timestamp*/, const OSVR_ButtonReport* report) {
QuitStruct* result = static_cast<QuitStruct*>(userdata);
result->quit = (report->state != 0);
}
bool SetupRendering(osvr::renderkit::GraphicsLibrary library) {
// Make sure our pointers are filled in correctly.
if (library.OpenGL == nullptr) {
std::cerr << "SetupRendering: No OpenGL GraphicsLibrary, this should "
"not happen"
<< std::endl;
return false;
}
osvr::renderkit::GraphicsLibraryOpenGL* glLibrary = library.OpenGL;
// Turn on depth testing, so we get correct ordering.
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
return true;
}
// Callback to set up a given display, which may have one or more eyes in it
void SetupDisplay(void* userData, //< Passed into SetDisplayCallback
osvr::renderkit::GraphicsLibrary library, //< Graphics library context to use
osvr::renderkit::RenderBuffer buffers //< Buffers to use
) {
// Make sure our pointers are filled in correctly. The config file selects
// the graphics library to use, and may not match our needs.
if (library.OpenGL == nullptr) {
std::cerr << "SetupDisplay: No OpenGL GraphicsLibrary, this should not happen" << std::endl;
return;
}
if (buffers.OpenGL == nullptr) {
std::cerr << "SetupDisplay: No OpenGL RenderBuffer, this should not happen" << std::endl;
return;
}
osvr::renderkit::GraphicsLibraryOpenGL* glLibrary = library.OpenGL;
// Clear the screen to black and clear depth
glClearColor(0, 0, 0, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
// Callback to set up for rendering into a given eye (viewpoint and projection).
void SetupEye(void* userData, //< Passed into SetViewProjectionCallback
osvr::renderkit::GraphicsLibrary library, //< Graphics library context to use
osvr::renderkit::RenderBuffer buffers, //< Buffers to use
osvr::renderkit::OSVR_ViewportDescription viewport, //< Viewport set by RenderManager
osvr::renderkit::OSVR_ProjectionMatrix projection, //< Projection matrix set by RenderManager
size_t whichEye //< Which eye are we setting up for?
) {
// Make sure our pointers are filled in correctly. The config file selects
// the graphics library to use, and may not match our needs.
if (library.OpenGL == nullptr) {
std::cerr << "SetupEye: No OpenGL GraphicsLibrary, this should not happen" << std::endl;
return;
}
if (buffers.OpenGL == nullptr) {
std::cerr << "SetupEye: No OpenGL RenderBuffer, this should not happen" << std::endl;
return;
}
// Set the viewport
glViewport(static_cast<GLint>(viewport.left), static_cast<GLint>(viewport.lower),
static_cast<GLint>(viewport.width), static_cast<GLint>(viewport.height));
}
// Callback to draw things in world space.
void DrawWorld(void* userData, //< Passed into AddRenderCallback
osvr::renderkit::GraphicsLibrary library, //< Graphics library context to use
osvr::renderkit::RenderBuffer buffers, //< Buffers to use
osvr::renderkit::OSVR_ViewportDescription viewport, //< Viewport we're rendering into
OSVR_PoseState pose, //< OSVR ModelView matrix set by RenderManager
osvr::renderkit::OSVR_ProjectionMatrix projection, //< Projection matrix set by RenderManager
OSVR_TimeValue deadline //< When the frame should be sent to the screen
) {
// Make sure our pointers are filled in correctly. The config file selects
// the graphics library to use, and may not match our needs.
if (library.OpenGL == nullptr) {
std::cerr << "DrawWorld: No OpenGL GraphicsLibrary, this should not happen" << std::endl;
return;
}
if (buffers.OpenGL == nullptr) {
std::cerr << "DrawWorld: No OpenGL RenderBuffer, this should not happen" << std::endl;
return;
}
osvr::renderkit::GraphicsLibraryOpenGL* glLibrary = library.OpenGL;
GLdouble projectionGL[16];
osvr::renderkit::OSVR_Projection_to_OpenGL(projectionGL, projection);
GLdouble viewGL[16];
osvr::renderkit::OSVR_PoseState_to_OpenGL(viewGL, pose);
/// Draw a cube with a 5-meter radius as the room we are floating in.
roomCube->draw(projectionGL, viewGL);
}
void Usage(std::string name) {
std::cerr << "Usage: " << name << " [TrianglesPerSide]" << std::endl;
std::cerr << " Default triangles per cube face = 1e3" << std::endl;
exit(-1);
}
int main(int argc, char* argv[]) {
// Parse the command line
double trianglesPerSide = 1e3;
int realParams = 0;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
Usage(argv[0]);
} else {
switch (++realParams) {
case 1:
trianglesPerSide = atof(argv[i]);
break;
default:
Usage(argv[0]);
}
}
}
if (realParams > 1) {
Usage(argv[0]);
}
size_t triangles = static_cast<size_t>(trianglesPerSide * 6);
roomCube.reset(new MeshCube(10.0, triangles));
std::cout << "Rendering " << trianglesPerSide << " triangles per cube face" << std::endl;
std::cout << "Rendering " << triangles << " triangles total" << std::endl;
// Get an OSVR client context to use to access the devices
// that we need.
osvr::clientkit::ClientContext context("org.osvr.renderManager.openGLChessboard");
// Open OpenGL and set up the context for rendering to
// an HMD. Do this using the OSVR RenderManager interface,
// which maps to the nVidia or other vendor direct mode
// to reduce the latency.
std::unique_ptr<osvr::renderkit::RenderManager> render(
osvr::renderkit::createRenderManager(context.get(), "OpenGL"));
if ((render == nullptr) || (!render->doingOkay())) {
std::cerr << "Could not create RenderManager" << std::endl;
return 1;
}
// Set callback to handle setting up rendering in an eye
render->SetViewProjectionCallback(SetupEye);
// Set callback to handle setting up rendering in a display
render->SetDisplayCallback(SetupDisplay);
// Register callback to render things in world space.
render->AddRenderCallback("/", DrawWorld);
// Set up a handler to cause us to exit cleanly.
osvr::server::registerShutdownHandler<&CtrlHandler>();
// Open the display and make sure this worked.
osvr::renderkit::RenderManager::OpenResults ret = render->OpenDisplay();
if (ret.status == osvr::renderkit::RenderManager::OpenStatus::FAILURE) {
std::cerr << "Could not open display" << std::endl;
return 2;
}
if (ret.library.OpenGL == nullptr) {
std::cerr << "Attempted to run an OpenGL program with a config file "
<< "that specified a different rendering library." << std::endl;
return 3;
}
// Set up the rendering state we need.
if (!SetupRendering(ret.library)) {
return 3;
}
glewExperimental = true;
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to initialize GLEW\n" << std::endl;
return -1;
}
// Clear any GL error that Glew caused. Apparently on Non-Windows
// platforms, this can cause a spurious error 1280.
glGetError();
// Frame timing
size_t countFrames = 0;
// Always render from the identity pose, not allowing head tracking to operate.
osvr::renderkit::RenderManager::RenderParams params;
OSVR_PoseState identity;
osvrPose3SetIdentity(&identity);
params.roomFromHeadReplace = &identity;
// Continue rendering until it is time to quit.
using ourClock = std::chrono::high_resolution_clock;
auto start = ourClock::now();
while (!quit.quit) {
// Update the context so we get our callbacks called and
// update tracker state.
context.update();
if (!render->Render(params)) {
std::cerr << "Render() returned false, maybe because it was asked to quit" << std::endl;
quit.quit = true;
}
// Print timing info
auto now = ourClock::now();
auto duration = std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
countFrames++;
if (duration >= 2.0) {
std::cout << "Rendering at " << countFrames / duration << " fps" << std::endl;
start = now;
countFrames = 0;
}
}
return 0;
}
| 39.077176
| 118
| 0.597487
|
sensics
|
86f910067f1ef2693f3e6fa60508bc70f69c7c3f
| 1,358
|
cpp
|
C++
|
examples/gpu-cuda/SimpleExample/SimpleExample.cpp
|
kmorel/MGARD
|
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
|
[
"Apache-2.0"
] | 19
|
2019-03-08T15:21:36.000Z
|
2022-02-11T04:02:50.000Z
|
examples/gpu-cuda/SimpleExample/SimpleExample.cpp
|
kmorel/MGARD
|
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
|
[
"Apache-2.0"
] | 100
|
2019-01-14T15:34:09.000Z
|
2022-03-29T13:39:30.000Z
|
examples/gpu-cuda/SimpleExample/SimpleExample.cpp
|
kmorel/MGARD
|
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
|
[
"Apache-2.0"
] | 22
|
2018-11-16T01:13:57.000Z
|
2022-03-14T23:53:28.000Z
|
#include "mgard/compress_cuda.hpp"
#include <iostream>
#include <vector>
int main() {
mgard_cuda::SIZE n1 = 10;
mgard_cuda::SIZE n2 = 20;
mgard_cuda::SIZE n3 = 30;
// prepare
std::cout << "Preparing data...";
double *in_array_cpu;
mgard_cuda::cudaMallocHostHelper((void **)&in_array_cpu,
sizeof(double) * n1 * n2 * n3);
//... load data into in_array_cpu
std::vector<mgard_cuda::SIZE> shape{n1, n2, n3};
mgard_cuda::Handle<3, double> handle(shape);
mgard_cuda::Array<3, double> in_array(shape);
in_array.loadData(in_array_cpu);
std::cout << "Done\n";
std::cout << "Compressing with MGARD-GPU...";
double tol = 0.01, s = 0;
mgard_cuda::Array<1, unsigned char> compressed_array = mgard_cuda::compress(
handle, in_array, mgard_cuda::error_bound_type::REL, tol, s);
size_t compressed_size =
compressed_array.getShape()[0]; // compressed size in number of bytes.
unsigned char *compressed_array_cpu = compressed_array.getDataHost();
std::cout << "Done\n";
std::cout << "Decompressing with MGARD-GPU...";
// decompression
mgard_cuda::Array<3, double> decompressed_array =
mgard_cuda::decompress(handle, compressed_array);
mgard_cuda::cudaFreeHostHelper(in_array_cpu);
double *decompressed_array_cpu = decompressed_array.getDataHost();
std::cout << "Done\n";
}
| 36.702703
| 78
| 0.683358
|
kmorel
|
86fa561371a79045e29796d5da1d3903d3427fea
| 4,058
|
cpp
|
C++
|
src/Customs/ForestActivatorScript3.cpp
|
fgagamedev/voID
|
37cd56fe2878d036c36dafcf595e48ed85408d02
|
[
"MIT"
] | null | null | null |
src/Customs/ForestActivatorScript3.cpp
|
fgagamedev/voID
|
37cd56fe2878d036c36dafcf595e48ed85408d02
|
[
"MIT"
] | null | null | null |
src/Customs/ForestActivatorScript3.cpp
|
fgagamedev/voID
|
37cd56fe2878d036c36dafcf595e48ed85408d02
|
[
"MIT"
] | null | null | null |
/**
@file ForestActivator3.hpp
@brief Class that defines methods and attributes for activating the forest script.
@copyright LGPL. MIT License.
*/
#include "Globals/EngineGlobals.hpp"
#include "Customs/ForestActivatorScript3.hpp"
#include "Customs/CentralLightScript4.hpp"
#include "Customs/MapScript.hpp"
// Constructor
ForestActivatorScript3::ForestActivatorScript3(GameObject *owner) : Script(owner) {
}
/**
@brief Initializes the forest script three.
That function starts the activion of the forest 3. Create the animation,
position, animator, controller, input and the map.
*/
void ForestActivatorScript3::Start() {
// Creates the animator.
CreateAnimations();
// Gets the position.
position = GetOwner()->GetPosition();
// Gets the animator.
animator = (Animator *)GetOwner()->GetComponent("Animator");
input = InputSystem::GetInstance();
// Gets the game controller.
gamecontroller = input->GetGameController(0);
GetOwner()->SetZoomProportion(Vector(0,0));
auto map = SceneManager::GetInstance()->GetScene("Gameplay")->
GetGameObject("Map");
if (map) {
GetOwner()->SetZoomProportion(Vector(map->originalWidth/GetOwner()
->originalWidth,
map->originalHeight/GetOwner()
->originalHeight));
}
}
/**
@brief That function create the image and animation of the forest three.
*/
void ForestActivatorScript3::CreateAnimations() {
// Creates the image.
auto forestactivatorSprite = new Image("assets/forestactivator.png", 0, 0,
832, 64);
// Creates and get the animation.
auto forestactivatorAnimation = new Animation(GetOwner(),
forestactivatorSprite);
for (int i = 0; i < 13; i++) {
forestactivatorAnimation->AddFrame(new Frame(i * 64, 0, 64, 64));
}
auto forestactivatorAnimation2 = new Animation(GetOwner(),
forestactivatorSprite);
forestactivatorAnimation2->AddFrame(new Frame(12 * 64, 0, 64, 64));
auto forestactivatorAnimator = new Animator(GetOwner());
forestactivatorAnimation->SetFramesPerSecond(9);
forestactivatorAnimator->AddAnimation("FOREST ACTIVATOR ANIMATION",
forestactivatorAnimation);
forestactivatorAnimator->AddAnimation("FOREST ACTIVATOR ANIMATION2",
forestactivatorAnimation2);
}
/**
@brief Updates the components of the forest three.
*/
void ForestActivatorScript3::ComponentUpdate() {
if (!animator->IsPlaying("FOREST ACTIVATOR ANIMATION") && activate == 0
&& runned == false) {
animator->PlayAnimation("FOREST ACTIVATOR ANIMATION");
activate = 1;
runned = true;
}
if (runned && !animator->IsPlaying("FOREST ACTIVATOR ANIMATION")) {
animator->PlayAnimation("FOREST ACTIVATOR ANIMATION2");
}
if (runned) {
auto script = (CentralLightScript4*)SceneManager::GetInstance()
->GetCurrentScene()->GetGameObject("CENTRAL LIGHT 4")
->GetComponent("CentralLightScript4");
script->Activate();
auto map = (MapScript*)SceneManager::GetInstance()->GetCurrentScene()
->GetGameObject("Map")->GetComponent("MapScript");
map->downWalls[48].m_x = 0;
map->downWalls[48].m_y = 0;
map->downWalls[48].m_w = 0;
map->downWalls[48].m_h = 0;
// map->downWallsAmmount-=1;
map->downWallsOriginal[48].m_x = 0;
map->downWallsOriginal[48].m_y = 0;
map->downWallsOriginal[48].m_w = 0;
map->downWallsOriginal[48].m_h = 0;
}
}
/**
@brief that function fixs the components updates of the forest three.
*/
void ForestActivatorScript3::FixedComponentUpdate() {
}
| 33.262295
| 86
| 0.608921
|
fgagamedev
|
86fbbb8c397bb64ee411e77f3a4e9fd093b32e4b
| 9,624
|
cpp
|
C++
|
venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multi_normal_cholesky_test.cpp
|
vchiapaikeo/prophet
|
e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7
|
[
"MIT"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multi_normal_cholesky_test.cpp
|
vchiapaikeo/prophet
|
e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7
|
[
"MIT"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
test/unit/math/prim/mat/prob/multi_normal_cholesky_test.cpp
|
riddell-stan/math
|
d84ee0d991400d6cf4b08a07a4e8d86e0651baea
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <vector>
using Eigen::Dynamic;
using Eigen::Matrix;
using std::vector;
TEST(ProbDistributionsMultiNormalCholesky, NotVectorized) {
boost::random::mt19937 rng;
Matrix<double, Dynamic, 1> y(3, 1);
y << 2.0, -2.0, 11.0;
Matrix<double, Dynamic, 1> mu(3, 1);
mu << 1.0, -1.0, 3.0;
Matrix<double, Dynamic, Dynamic> Sigma(3, 3);
Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;
Matrix<double, Dynamic, Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::math::multi_normal_cholesky_log(y, mu, L));
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_rng(mu, L, rng));
}
TEST(ProbDistributionsMultiNormalCholesky, Vectorized) {
boost::random::mt19937 rng;
vector<Matrix<double, Dynamic, 1> > vec_y(2);
vector<Matrix<double, 1, Dynamic> > vec_y_t(2);
Matrix<double, Dynamic, 1> y(3);
Matrix<double, 1, Dynamic> y_t(3);
y << 2.0, -2.0, 11.0;
vec_y[0] = y;
vec_y_t[0] = y;
y << 4.0, -2.0, 1.0;
vec_y[1] = y;
vec_y_t[1] = y;
y_t = y;
vector<Matrix<double, Dynamic, 1> > vec_mu(2);
vector<Matrix<double, 1, Dynamic> > vec_mu_t(2);
Matrix<double, Dynamic, 1> mu(3);
Matrix<double, 1, Dynamic> mu_t(3);
mu << 1.0, -1.0, 3.0;
vec_mu[0] = mu;
vec_mu_t[0] = mu;
mu << 2.0, -1.0, 4.0;
vec_mu[1] = mu;
vec_mu_t[1] = mu;
mu_t = mu;
Matrix<double, Dynamic, Dynamic> Sigma(3, 3);
Sigma << 10.0, -3.0, 0.0, -3.0, 5.0, 0.0, 0.0, 0.0, 5.0;
Matrix<double, Dynamic, Dynamic> L = Sigma.llt().matrixL();
// y and mu vectorized
EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,
stan::math::multi_normal_cholesky_log(vec_y, vec_mu, L));
EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,
stan::math::multi_normal_cholesky_log(vec_y_t, vec_mu, L));
EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,
stan::math::multi_normal_cholesky_log(vec_y, vec_mu_t, L));
EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,
stan::math::multi_normal_cholesky_log(vec_y_t, vec_mu_t, L));
// y vectorized
EXPECT_FLOAT_EQ(-10.44027 - 6.537833,
stan::math::multi_normal_cholesky_log(vec_y, mu, L));
EXPECT_FLOAT_EQ(-10.44027 - 6.537833,
stan::math::multi_normal_cholesky_log(vec_y_t, mu, L));
EXPECT_FLOAT_EQ(-10.44027 - 6.537833,
stan::math::multi_normal_cholesky_log(vec_y, mu_t, L));
EXPECT_FLOAT_EQ(-10.44027 - 6.537833,
stan::math::multi_normal_cholesky_log(vec_y_t, mu_t, L));
// mu vectorized
EXPECT_FLOAT_EQ(-6.26954 - 6.537833,
stan::math::multi_normal_cholesky_log(y, vec_mu, L));
EXPECT_FLOAT_EQ(-6.26954 - 6.537833,
stan::math::multi_normal_cholesky_log(y_t, vec_mu, L));
EXPECT_FLOAT_EQ(-6.26954 - 6.537833,
stan::math::multi_normal_cholesky_log(y, vec_mu_t, L));
EXPECT_FLOAT_EQ(-6.26954 - 6.537833,
stan::math::multi_normal_cholesky_log(y_t, vec_mu_t, L));
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_rng(vec_mu, L, rng));
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_rng(vec_mu_t, L, rng));
}
TEST(ProbDistributionsMultiNormalCholesky, MultiNormalOneRow) {
boost::random::mt19937 rng;
Matrix<double, 1, Dynamic> y(3);
y << 2.0, -2.0, 11.0;
Matrix<double, Dynamic, 1> mu(3);
mu << 1.0, -1.0, 3.0;
Matrix<double, Dynamic, Dynamic> Sigma(3, 3);
Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;
Matrix<double, Dynamic, Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::math::multi_normal_cholesky_log(y, mu, L));
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_rng(mu, L, rng));
}
TEST(ProbDistributionsMultiNormalCholesky, error_check) {
boost::random::mt19937 rng;
Matrix<double, Dynamic, 1> mu(3, 1);
mu << 2.0, -2.0, 11.0;
Matrix<double, Dynamic, Dynamic> sigma(3, 3);
sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;
Matrix<double, Dynamic, Dynamic> L = sigma.llt().matrixL();
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_rng(mu, L, rng));
mu << stan::math::positive_infinity(), -2.0, 11.0;
EXPECT_THROW(stan::math::multi_normal_cholesky_rng(mu, sigma, rng),
std::domain_error);
}
TEST(ProbDistributionsMultiNormalCholesky,
marginalOneChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double, Dynamic, Dynamic> sigma(3, 3);
sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;
Matrix<double, Dynamic, Dynamic> L = sigma.llt().matrixL();
std::vector<Matrix<double, Dynamic, 1> > mu(3);
mu[0].resize(3);
mu[1].resize(3);
mu[2].resize(3);
mu[0] << 2.0, -2.0, 11.0;
mu[1] << -5.0, 1.0, 2.0;
mu[2] << 0.0, -1.0, 7.0;
int N = 10000;
int K = stan::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<> dist(2.0, 3.0);
boost::math::chi_squared mydist(K - 1);
double loc[K - 1];
for (int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin[K];
double expect[K];
for (int i = 0; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu[0].rows());
while (count < N) {
a = stan::math::multi_normal_cholesky_rng(mu, L, rng)[0];
int i = 0;
while (i < K - 1 && a(0) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for (int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky,
marginalTwoChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double, Dynamic, Dynamic> sigma(3, 3);
sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;
Matrix<double, Dynamic, Dynamic> L = sigma.llt().matrixL();
std::vector<Matrix<double, 1, Dynamic> > mu(3);
mu[0].resize(3);
mu[1].resize(3);
mu[2].resize(3);
mu[0] << -5.0, 1.0, 2.0;
mu[1] << 2.0, -2.0, 11.0;
mu[2] << 0.0, -1.0, 7.0;
int N = 10000;
int K = stan::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<> dist(-2.0, 2.0);
boost::math::chi_squared mydist(K - 1);
double loc[K - 1];
for (int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin[K];
double expect[K];
for (int i = 0; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu[0].rows());
while (count < N) {
a = stan::math::multi_normal_cholesky_rng(mu, L, rng)[1];
int i = 0;
while (i < K - 1 && a(1) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for (int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky,
marginalThreeChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double, Dynamic, Dynamic> sigma(3, 3);
sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 16.0;
Matrix<double, Dynamic, Dynamic> L = sigma.llt().matrixL();
Matrix<double, Dynamic, 1> mu(3, 1);
mu << 2.0, -2.0, 11.0;
int N = 10000;
int K = stan::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<> dist(11.0, 4.0);
boost::math::chi_squared mydist(K - 1);
double loc[K - 1];
for (int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin[K];
double expect[K];
for (int i = 0; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::math::multi_normal_cholesky_rng(mu, L, rng);
int i = 0;
while (i < K - 1 && a(2) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for (int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky, WrongSize) {
vector<Matrix<double, Dynamic, 1> > y_3_3(3);
vector<Matrix<double, Dynamic, 1> > y_3_1(3);
vector<Matrix<double, Dynamic, 1> > y_3_2(3);
vector<Matrix<double, Dynamic, 1> > y_1_3(1);
vector<Matrix<double, Dynamic, 1> > y_2_3(2);
Matrix<double, Dynamic, 1> y_3(3);
Matrix<double, Dynamic, 1> y_2(2);
Matrix<double, Dynamic, 1> y_1(1);
y_3 << 2.0, -2.0, 11.0;
y_2 << 2.0, -2.0;
y_1 << 2.0;
y_3_3[0] = y_3;
y_3_3[1] = y_3;
y_3_3[2] = y_3;
y_3_1[0] = y_1;
y_3_1[1] = y_1;
y_3_1[2] = y_1;
y_3_2[0] = y_2;
y_3_2[1] = y_2;
y_3_2[2] = y_2;
y_1_3[0] = y_3;
y_2_3[0] = y_3;
y_2_3[1] = y_3;
vector<Matrix<double, Dynamic, 1> > mu_3_3(3);
Matrix<double, Dynamic, 1> mu_3(3);
mu_3 << 2.0, -2.0, 11.0;
mu_3_3[0] = mu_3;
mu_3_3[1] = mu_3;
mu_3_3[2] = mu_3;
Matrix<double, Dynamic, Dynamic> Sigma(3, 3);
Sigma << 10.0, -3.0, 0.0, -3.0, 5.0, 0.0, 0.0, 0.0, 5.0;
Matrix<double, Dynamic, Dynamic> L = Sigma.llt().matrixL();
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_lpdf(y_3_3, mu_3_3, L));
EXPECT_NO_THROW(stan::math::multi_normal_cholesky_lpdf(y_3, mu_3_3, L));
EXPECT_THROW(stan::math::multi_normal_cholesky_lpdf(y_1_3, mu_3_3, L),
std::invalid_argument);
EXPECT_THROW(stan::math::multi_normal_cholesky_lpdf(y_2_3, mu_3_3, L),
std::invalid_argument);
EXPECT_THROW(stan::math::multi_normal_cholesky_lpdf(y_3_1, mu_3_3, L),
std::invalid_argument);
EXPECT_THROW(stan::math::multi_normal_cholesky_lpdf(y_3_2, mu_3_3, L),
std::invalid_argument);
}
| 32.623729
| 79
| 0.604219
|
vchiapaikeo
|
86fbdc4e9c1f2a22f2330b735714449e9153b0d5
| 3,500
|
hpp
|
C++
|
solver/include/statetransitionmodel/StateTransitionModelFlat.hpp
|
laurimi/multiagent-prediction-reward
|
b89fa52f78bb49447fc0049a7314a87b2b3e903e
|
[
"MIT"
] | 9
|
2020-10-24T06:14:08.000Z
|
2021-07-13T13:08:30.000Z
|
solver/include/statetransitionmodel/StateTransitionModelFlat.hpp
|
laurimi/multiagent-prediction-reward
|
b89fa52f78bb49447fc0049a7314a87b2b3e903e
|
[
"MIT"
] | null | null | null |
solver/include/statetransitionmodel/StateTransitionModelFlat.hpp
|
laurimi/multiagent-prediction-reward
|
b89fa52f78bb49447fc0049a7314a87b2b3e903e
|
[
"MIT"
] | null | null | null |
#ifndef STATETRANSITIONMODELINDEXED_HPP
#define STATETRANSITIONMODELINDEXED_HPP
#include <map>
#include "StateTransitionModel.hpp"
#include "StateTransitionMatrix.hpp"
namespace npgi {
template <typename StateIndex, typename ActionIndex, typename Scalar, typename TimeStep>
class StateTransitionModelFlat;
template <typename StateIndex, typename ActionIndex, typename Scalar, typename TimeStep>
struct state_transition_model_traits<
StateTransitionModelFlat<StateIndex, ActionIndex, Scalar, TimeStep>> {
static_assert(std::is_integral<StateIndex>::value, "StateIndex must be integral type");
static_assert(std::is_integral<ActionIndex>::value,
"ActionIndex must be integral type");
static_assert(std::is_floating_point<Scalar>::value,
"Scalar must be floating point type");
using state_type = StateIndex;
using action_type = DiscreteJointAction<ActionIndex>;
using scalar_type = Scalar;
using pmf_type = std::vector<scalar_type>;
using timestep_type = TimeStep;
};
template <typename StateIndex = std::size_t, typename ActionIndex = std::size_t,
typename Scalar = double, typename TimeStep = int>
struct StateTransitionModelFlat
: public StateTransitionModel<
StateTransitionModelFlat<StateIndex, ActionIndex, Scalar, TimeStep>> {
using Derived = StateTransitionModelFlat<StateIndex, ActionIndex, Scalar, TimeStep>;
using state_type =
typename state_transition_model_traits<Derived>::state_type;
using pmf_type = typename state_transition_model_traits<Derived>::pmf_type;
using action_type =
typename state_transition_model_traits<Derived>::action_type;
using scalar_type =
typename state_transition_model_traits<Derived>::scalar_type;
using timestep_type =
typename state_transition_model_traits<Derived>::timestep_type;
using state_transition_matrix_type =
StateTransitionMatrix<action_type, StateIndex, Scalar>;
StateTransitionModelFlat(const state_transition_matrix_type& T)
: T_(T), custom_state_transition_m_() {}
void set_custom_state_transition_matrix(const timestep_type& t, const state_transition_matrix_type& a)
{
custom_state_transition_m_.insert_or_assign(t,a);
}
const state_transition_matrix_type& state_transition_matrix(const timestep_type& t) const
{
auto im = custom_state_transition_m_.find(t);
if (im == custom_state_transition_m_.end())
return T_;
else
return im->second;
}
scalar_type transition_probability(const state_type& next,
const state_type& old,
const action_type& a,
const timestep_type t) const {
return state_transition_matrix(t).transition_probability(next, old, a);
}
state_type sample_next_state(const state_type& old, const action_type& a,
const timestep_type t,
const scalar_type random01) const {
return state_transition_matrix(t).sample_next_state(old, a, random01);
}
pmf_type predict(const pmf_type& b, const action_type& a,
const timestep_type t) const {
return state_transition_matrix(t).predict(b, a);
}
std::size_t num_states() const { return T_.rows(); }
private:
state_transition_matrix_type T_;
std::map<timestep_type, state_transition_matrix_type> custom_state_transition_m_;
};
} // namespace npgi
#endif // STATETRANSITIONMODELINDEXED_HPP
| 38.888889
| 104
| 0.731429
|
laurimi
|
8102aa53a2d74c3b5125f6c09fc7d841cd4d35c1
| 1,738
|
cpp
|
C++
|
src/ConverterGuiProxy.cpp
|
Stivvo/qTsConverter
|
322c0a1fb70e829698728e7b1a40446531b9c46b
|
[
"MIT"
] | null | null | null |
src/ConverterGuiProxy.cpp
|
Stivvo/qTsConverter
|
322c0a1fb70e829698728e7b1a40446531b9c46b
|
[
"MIT"
] | 1
|
2021-07-09T12:54:05.000Z
|
2021-07-09T12:54:05.000Z
|
src/internal/ConverterGuiProxy.cpp
|
LeonardMontagna/qTsConverter
|
3a7c2b473bcfd9ff7ed29b1761a180b7a4c872ad
|
[
"MIT"
] | null | null | null |
#include "ConverterGuiProxy.hpp"
#include <QDebug>
ConverterGuiProxy::ConverterGuiProxy(QObject *parent) : QObject(parent) {}
void ConverterGuiProxy::convert(QConversionType type, QString input,
QString output, const QString &fieldSeparator,
const QString &stringSeparator,
const QString &tsVersion)
{
// Remove file:// on linux and file:/// on windows
input = QUrl::fromUserInput(input).toLocalFile();
output = QUrl::fromUserInput(output).toLocalFile();
auto converter = ConverterFactory::make_converter(
static_cast<ConverterFactory::ConversionType>(type), input, output,
fieldSeparator, stringSeparator, tsVersion);
const auto results = converter->process();
setConversionInfo(results.success, results.message,
results.detailedMessage);
}
bool ConverterGuiProxy::convSuccessfull() const
{
return m_convSuccessfull;
}
QString ConverterGuiProxy::convMsg() const
{
return m_convMsg;
}
QString ConverterGuiProxy::detailedConvMsg() const
{
return m_detailedConvMsg;
}
void ConverterGuiProxy::setConversionInfo(bool convSuccessfull,
const QString &errorMsg,
const QString &detailedConvMsg)
{
m_convSuccessfull = convSuccessfull;
m_convMsg = errorMsg;
m_detailedConvMsg = detailedConvMsg;
Q_EMIT conversionCompleted();
}
static_assert(static_cast<int>(ConverterGuiProxy::QConversionType::Dummy) ==
static_cast<int>(ConverterFactory::ConversionType::Dummy),
"enum proxy QConversionType is different than ConversionType");
| 32.792453
| 78
| 0.662255
|
Stivvo
|
8102d66abca2a7173b5799d219deaef45a5cedd9
| 9,002
|
cpp
|
C++
|
onviflibs/gsoap/gsoap-2.8/gsoap/samples/lu/luserver.cpp
|
KobeBryand/onvif-qt-server-client
|
ccc3193b3cbc1f45b1fd9ce7928ae99864d07708
|
[
"Apache-2.0"
] | 157
|
2016-08-03T11:49:59.000Z
|
2022-03-01T03:00:29.000Z
|
onviflibs/gsoap/gsoap-2.8/gsoap/samples/lu/luserver.cpp
|
ouzance/onvif-qt-server-client
|
ccc3193b3cbc1f45b1fd9ce7928ae99864d07708
|
[
"Apache-2.0"
] | 9
|
2017-02-03T15:00:27.000Z
|
2020-12-04T23:31:43.000Z
|
onviflibs/gsoap/gsoap-2.8/gsoap/samples/lu/luserver.cpp
|
ouzance/onvif-qt-server-client
|
ccc3193b3cbc1f45b1fd9ce7928ae99864d07708
|
[
"Apache-2.0"
] | 88
|
2016-08-29T10:54:39.000Z
|
2022-03-10T17:42:40.000Z
|
/*
luserver.h
LU factorization Web service.
--------------------------------------------------------------------------------
gSOAP XML Web services tools
Copyright (C) 2001-2008, Robert van Engelen, Genivia, Inc. All Rights Reserved.
This software is released under one of the following two licenses:
GPL or Genivia's license for commercial use.
--------------------------------------------------------------------------------
GPL license.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
Author contact information:
engelen@genivia.com / engelen@acm.org
--------------------------------------------------------------------------------
A commercial use license is available from Genivia, Inc., contact@genivia.com
--------------------------------------------------------------------------------
*/
#include "soapH.h"
#include <math.h>
////////////////////////////////////////////////////////////////////////////////
//
// main
//
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{ struct soap *soap;
int m, s;
soap = soap_new();
if (argc < 3)
soap_serve(soap); // run as CGI application over the Web
else // run as stand-alone server on machine given by argv[1] listening to port argv[2]
{ m = soap_bind(soap, argv[1], atoi(argv[2]), 100);
if (m < 0)
{ soap_print_fault(soap, stderr);
exit(-1);
}
fprintf(stderr, "Socket connection successful: master socket = %d\n", m);
for (int i = 1; ; i++)
{ s = soap_accept(soap);
if (s < 0)
{ soap_print_fault(soap, stderr);
exit(-1);
}
fprintf(stderr, "%d: accepted connection from IP = %d.%d.%d.%d socket = %d ... ", i, (int)(soap->ip>>24)&0xFF, (int)(soap->ip>>16)&0xFF, (int)(soap->ip>>8)&0xFF, (int)soap->ip&0xFF, s);
soap_serve(soap); // process request
fprintf(stderr, "request served\n");
soap_destroy(soap); // delete class instances
soap_end(soap); // clean up everything and close socket
}
}
soap_done(soap);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// LU decomposition: remote method interface
//
////////////////////////////////////////////////////////////////////////////////
int ludcmp(struct soap*, matrix&, ivector&, double&);
int ns1__ludcmp(struct soap *soap, matrix *a, struct ns1__ludcmpResponse &result)
{ result.a = a;
result.i = soap_new_ivector(soap, -1);
if (ludcmp(soap, *result.a, *result.i, result.d))
return soap_sender_fault(soap, "Singular matrix in routine ludcmp", NULL);
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// LU decomposition: algorithm
//
////////////////////////////////////////////////////////////////////////////////
int ludcmp(struct soap *soap, matrix &a, ivector &indx, double &d)
{ int i, imax = 0, j, k, n;
double big, dum, sum, temp;
n = a.size();
vector vv(soap);
vv.resize(n);
indx.resize(n);
d = 1.0;
for (i = 1; i <= n; i++)
{ big = 0.0;
a[i].resize(n);
for (j = 1; j <= n; j++)
if ((temp = fabs(a[i][j])) > big)
big = temp;
if (big == 0.0)
return -1;
vv[i] = 1.0/big;
}
for (j = 1; j <= n; j++)
{ for (i = 1; i < j; i++)
{ sum = a[i][j];
for (k = 1; k < i; k++)
sum -= a[i][k]*a[k][j];
a[i][j] = sum;
}
big = 0.0;
for (i = j; i <= n; i++)
{ sum = a[i][j];
for (k = 1; k < j; k++)
sum -= a[i][k]*a[k][j];
a[i][j] = sum;
if ((dum = vv[i]*fabs(sum)) >= big)
{ big = dum;
imax = i;
}
}
if (j != imax)
{ for (k = 1; k <= n; k++)
{ dum = a[imax][k];
a[imax][k] = a[j][k];
a[j][k] = dum;
}
d = -d;
vv[imax] = vv[j];
}
indx[j] = imax;
if (a[j][j] == 0.0)
a[j][j] = 1.0e-20;
if (j != n)
{ dum = 1.0/a[j][j];
for (i = j+1; i <= n; i++)
a[i][j] *= dum;
}
}
for (i = 1; i <= n; i++)
{ for (j = 1; j <= n; j++)
if (fabs(a[i][j]) > 1.0e-15)
break;
for (k = n; k > j; k--)
if (fabs(a[i][k]) > 1.0e-15)
break;
a[i].resize(j, k);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// Forward- and backsubstitution: remote method interface
//
////////////////////////////////////////////////////////////////////////////////
int lubksb(matrix&, ivector&, vector &b);
int ns1__lubksb(struct soap *soap, matrix *a, ivector *i, vector *b, vector *x)
{ lubksb(*a, *i, *b);
*x = *b;
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// Forward- and backsubstitution: algorithm
//
////////////////////////////////////////////////////////////////////////////////
int lubksb(matrix &a, ivector &indx, vector &b)
{ int i, j, k, ip, n, m, ii = 0;
double sum;
n = a.size();
b.resize(n);
for (i = 1; i <= n; i++)
{ ip = indx[i];
sum = b[ip];
b[ip] = b[i];
if (ii)
{ k = a[i].start();
if (ii > k)
k = ii;
m = a[i].end();
if (i-1 < m)
m = i-1;
for (j = k; j <= m; j++)
sum -= a[i][j]*b[j];
}
else if (sum)
ii = i;
b[i] = sum;
}
for (i = n; i >= 1; i--)
{ sum = b[i];
k = a[i].start();
if (i+1 > k)
k = i+1;
m = a[i].end();
if (n < m)
m = n;
for (j = k; j <= m; j++)
sum -= a[i][j]*b[j];
b[i] = sum/a[i][i];
}
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// LU solve: remote method interface
//
////////////////////////////////////////////////////////////////////////////////
int ns1__lusol(struct soap *soap, matrix *a, vector *b, vector *x)
{ ivector indx(soap);
double d;
if (ludcmp(soap, *a, indx, d))
return soap_sender_fault(soap, "Singular matrix in routine ludcmp", NULL);
lubksb(*a, indx, *b);
*x = *b;
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// LU solve multiple: remote method interface
//
////////////////////////////////////////////////////////////////////////////////
int ns1__lusols(struct soap *soap, matrix *a, matrix *b, matrix *x)
{ ivector indx(soap);
double d;
if (ludcmp(soap, *a, indx, d))
return soap_sender_fault(soap, "Singular matrix in routine ludcmp", NULL);
for (int i = 1; i <= b->size(); i++)
lubksb(*a, indx, (*b)[i]);
*x = *b;
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// LU inverse: remote method interface
//
////////////////////////////////////////////////////////////////////////////////
int ns1__luinv(struct soap *soap, matrix *a, matrix *b)
{ vector col(soap);
ivector indx(soap);
double d;
int i, j, k, n;
if (ludcmp(soap, *a, indx, d))
return soap_sender_fault(soap, "Singular matrix in routine ludcmp", NULL);
n = a->size();
col.resize(n);
b->resize(n, n);
for (j = 1; j <= n; j++)
{ for (i = 1; i <= n; i++)
col[i] = 0.0;
col[j] = 1.0;
lubksb(*a, indx, col);
for (i = 1; i <= n; i++)
(*b)[i][j] = col[i];
}
for (i = 1; i <= n; i++)
{ for (j = 1; j <= n; j++)
if (fabs((*b)[i][j]) > 1.0e-15)
break;
for (k = n; k > j; k--)
if (fabs((*b)[i][k]) > 1.0e-15)
break;
(*b)[i].resize(j, k);
}
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// LU determinant: remote method interface
//
////////////////////////////////////////////////////////////////////////////////
int ns1__ludet(struct soap *soap, matrix *a, double &d)
{ ivector indx(soap);
if (ludcmp(soap, *a, indx, d))
return soap_sender_fault(soap, "Singular matrix in routine ludcmp", NULL);
for (int i = 1; i <= a->__size; i++)
d *= (*a)[i][i];
return SOAP_OK;
}
struct Namespace namespaces[] =
{// "ns-prefix", "ns-name", "ns-pattern"
{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"},
{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"},
{"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://wwww.w3.org/*/XMLSchema-instance"},
{"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema"},
{"ns1", "urn:lu"},
{NULL, NULL}
};
| 28.852564
| 191
| 0.44379
|
KobeBryand
|
810524ae7a85978db57f55a2ab415cae11e3a282
| 7,199
|
hpp
|
C++
|
include/Player.hpp
|
AgostonSzepessy/oxshans-battle
|
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
|
[
"MIT"
] | null | null | null |
include/Player.hpp
|
AgostonSzepessy/oxshans-battle
|
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
|
[
"MIT"
] | null | null | null |
include/Player.hpp
|
AgostonSzepessy/oxshans-battle
|
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream>
#include <cstdlib>
#include <vector>
#include <memory>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include "Entity.hpp"
#include "Bullet.hpp"
#include "Enemy.hpp"
#include "Constants.hpp"
#include "AnimatedSprite.hpp"
#include "Frame.hpp"
#include "HealthBar.hpp"
#include "ParticleSystem.hpp"
/**
* @brief The Player class encapsulates the player. It has functions
* for updating, drawing, teleporting, and everything else that the
* player can do.
*/
class Player : public Entity
{
public:
/**
* @brief Player Creates a new Player object
* @param x The x position of the object
* @param y The y position of the object
* @param filename The path to the player's spritesheet
*/
Player(int x, int y, std::string filename);
~Player();
/**
* @brief update Updates the player's position, his animation
* frames, checks if he can shoot, or if he collided with the
* bricks.
* @param box The bounding box for the bricks.
*/
void update(const BoundingBox &box);
/**
* @brief draw Draws the player on the screen.
* @param window The window to draw him on
*/
void draw(sf::RenderWindow *window);
/**
* @brief hit Called when the player gets hit. It reduces
* his health by "damage".
* @param damage Amount to reduce player's health by
*/
void hit(int damage);
/**
* @brief heal Heals the player for 50 hitpoints.
*/
void heal();
/**
* @brief addInvincibilityPotion Adds an invincibility
* potion to the player.
*/
void addInvincibilityPotion();
/**
* @brief getNumInvincibilityPotions Gets how many invincibility
* potions the player can use.
* @return Number of invincibility potions player has
*/
int getNumInvincibilityPotions();
/**
* @brief setInvincible Makes the player invincible
*/
void setInvincible();
/**
* @brief isInvincible Checks if the player is invincible.
* @return True if player's invincible
*/
bool isInvincible();
/**
* @brief addHealthPotion Adds a health potion to the player
*/
void addHealthPotion();
/**
* @brief getNumHealthPotions Gets the number of health potions the
* player has remaining.
* @return Number of health potions player has left.
*/
int getNumHealthPotions();
/**
* @brief getDamage Gets the damage that the player deals
* @return How much damage the player deals
*/
int getDamage();
/**
* @brief isDead Checks if the player is dead.
* @return True if the player's dead.
*/
bool isDead();
bool hasDyingAnimationStarted();
void setTeleporting(bool b);
bool getTeleporting() const;
bool getTeleporting();
/**
* Get the staff x so the fireball can be fired
* from the center of the staff.
* @return The x position of the player's staff
*/
int getStaffX();
/**
* Get the staff y so the fireball can be fired
* from the center of the staff.
* @return The y position of the player's staff
*/
int getStaffY();
/**
* Sets the teleport destination.
*/
void teleport(int x, int y);
/**
* Check if the player is moving left.
* @return Whether the player is moving left
*/
bool getMovedLeft();
/**
* Check if the player is moving right.
* @return Whether player is moving right
*/
bool getMovedRight();
/**
* Check if the player is moving up.
* @return Whether the player is moving up
*/
bool getMovedUp();
/**
* Check if the player is moving down.
* @return Whether the player is moving down
*/
bool getMovedDown();
/**
* Make the player move right.
* @param b Set to true if player is moving right, false if not
*/
void setMovedRight(bool b);
/**
* Make the player move left.
* @param b Set to true if player is moving left, false if not
*/
void setMovedLeft(bool b);
/**
* Make the player move up.
* @param b Set to true if player is moving up, false if not
*/
void setMovedUp(bool b);
/**
* Make the player move down.
* @param b Set to true if player is moving down, false if not
*/
void setMovedDown(bool b);
protected:
private:
/**
* Moves the player to its next position. It also handles collision
* detection, animation changes, dying, and teleportation.
* @param box The box that is on the battlefield
*/
void move(const BoundingBox &box);
/**
* @brief invincibleTimer Checks if the player is still invincible; he
* can only be invincible for 3 seconds.
* @return True if player is invincible
*/
bool invincibleTimer();
/**
* The amount of time the player is invincible for. When the accumulator
* is greater than this, the player is vulnerable again.
*/
int invTime;
/**
* Used for holding the time from when invincibility was activated.
*/
int invPrevTime;
/**
* Holds the current time.
*/
int invCurrentTime;
/**
* Holds the total time. Each frame, more time gets
* added to it until it is greater or equal to delay.
* Then it gets reset.
*/
int invAccumulator;
const int maxSpeed = 5;
const int acceleration = 1;
Frame *standing;
Frame *walking;
Frame *dying;
/**
* First half of teleport animation. After that, player gets moved to desination
*/
Frame *teleportStart;
/**
* Second half of teleport animation that plays after
* the player gets moved to the new location.
*/
Frame *teleportEnd;
/**
* The health bar of the player. It shows how much
* health the player has left.
*/
HealthBar *healthBar;
/**
* The maximum health of the player. Health
* can't go above this.
*/
const int maxHealth = 100;
/**
* The current amount of healt the player has.
* It starts equal to maxHealth.
*/
int health;
int damage;
/**
* Teleportation destination x
*/
int teleportX;
/**
* Teleportation destination y.
*/
int teleportY;
/**
* Keeps track of which animation is currently playing.
*/
int currentAnimation;
const int STANDING = 0;
const int WALKING = 1;
const int DYING = 2;
const int TELEPORT_START = 3;
const int TELEPORT_END = 4;
/**
* True if player is facing right, and false if he is facing left.
* Used for checking whether the setScale() has to be called.
*/
bool facingRight;
/**
* Used for playing dying animation. If player is dying, then
* don't update him.
*/
bool isDying;
/**
* Signals game over.
*/
bool dead;
/**
* Used for playing player dying sound.
*/
bool dyingAnimationStarted;
/**
* True if player is teleporting and false if he is not. If it is
* true, then it blocks input.
*/
bool teleporting;
// moving stuff
/**
* Used to determine whether the player is moving left.
*/
bool movedLeft;
/**
* Used to determine whether the player is moving right.
*/
bool movedRight;
/**
* Used to determine whether the player is moving up.
*/
bool movedUp;
/**
* Used to determine whether the player is moving down.
*/
bool movedDown;
ParticleSystem *particleSystem;
int numHealthPotions;
int numInvincibilityPotions;
bool invincible;
};
| 23.680921
| 82
| 0.657869
|
AgostonSzepessy
|
81128e04d1a35b8987dcb8dc8790012b05c77e63
| 2,908
|
cpp
|
C++
|
HTWK_SD_FILTER/SD_LaneDetection/HoughAlgorithm.cpp
|
HTWKSmartDriving/aadc-2015
|
95ee77aa0f9ebbb541bbb1e3b99d3f044347d103
|
[
"BSD-2-Clause"
] | 2
|
2017-11-29T00:15:26.000Z
|
2017-11-29T01:45:54.000Z
|
HTWK_SD_FILTER/SD_LaneDetection/HoughAlgorithm.cpp
|
HTWKSmartDriving/aadc-2015
|
95ee77aa0f9ebbb541bbb1e3b99d3f044347d103
|
[
"BSD-2-Clause"
] | null | null | null |
HTWK_SD_FILTER/SD_LaneDetection/HoughAlgorithm.cpp
|
HTWKSmartDriving/aadc-2015
|
95ee77aa0f9ebbb541bbb1e3b99d3f044347d103
|
[
"BSD-2-Clause"
] | 2
|
2017-11-28T23:47:27.000Z
|
2019-07-19T08:04:50.000Z
|
/**
* Copyright (c) 2014-2015, HTWK SmartDriving
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* AUTHORS: Silvio Feig, Denny Hecht, Andreas Kluge, Lars Kollmann, Eike Florian Petersen, Artem Pokas
*
*/
#include "stdafx.h"
HoughAlgorithm::HoughAlgorithm(void)
{
setStrategy(HOUGH_DEFAULT);
}
HoughAlgorithm::HoughAlgorithm(const Hough &strategy)
{
setStrategy(strategy);
}
HoughAlgorithm::~HoughAlgorithm(void)
{
this->hough.release();
}
void HoughAlgorithm::resetStrategie(const Hough &strategy)
{
setStrategy(strategy);
}
void HoughAlgorithm::setStrategy(const Hough &strategy)
{
this->strategy = strategy;
switch (strategy)
{
case HOUGH_DEFAULT:
this->hough.reset(new HoughDefault());
break;
case HOUGH_FAST:
this->hough.reset(new HoughFast());
break;
default:
this->hough.reset(new HoughDefault());
break;
}
}
void HoughAlgorithm::getLines(cv::Mat &image, const int &threshold, vector<SD_Line> &lines)
{
if (this->strategy == HOUGH_OPENCV)
{
vector<Vec2f> cvLines;
HoughLines(image, cvLines, 1, CV_PI/180, 100, 0, 0 );
for(size_t i = 0; i < cvLines.size(); i++ )
{
float rho = cvLines[i][0];
float theta = cvLines[i][1];
double a = cos(theta);
double b = sin(theta);
double x0 = a * rho;
double y0 = b * rho;
static SD_Line line;
line.x1 = cvRound(x0 + 1000 * (-b));
line.y1 = cvRound(y0 + 1000 * (a));
line.x2 = cvRound(x0 - 1000 * (-b));
line.y2 = cvRound(y0 - 1000 * (a));
lines.push_back(line);
}
}
else
{
this->hough->setImage(image);
this->hough->transform();
lines = this->hough->getLines(threshold);
}
}
| 27.695238
| 102
| 0.711142
|
HTWKSmartDriving
|
8113515eccbb331048a356da8d2f29e6b6d04c00
| 2,412
|
cpp
|
C++
|
orb/XMLParser.cpp
|
ternarylabs/orb
|
8c89894dc1eabfd99743f16d35786ff354dcc4e5
|
[
"MIT"
] | null | null | null |
orb/XMLParser.cpp
|
ternarylabs/orb
|
8c89894dc1eabfd99743f16d35786ff354dcc4e5
|
[
"MIT"
] | null | null | null |
orb/XMLParser.cpp
|
ternarylabs/orb
|
8c89894dc1eabfd99743f16d35786ff354dcc4e5
|
[
"MIT"
] | 1
|
2020-05-21T14:00:46.000Z
|
2020-05-21T14:00:46.000Z
|
#include "XMLParser.h"
#include <string.h>
XMLParser::XMLParser()
{
callback = NULL;
reset();
}
void (*XMLParser::getCallback())(void*, bool, char*, char*, char*)
{
return callback;
}
void XMLParser::setCallback(void (*function)(void*, bool, char*, char*, char*), void* data)
{
context = data;
callback = function;
}
void XMLParser::reset()
{
fInAttribute = false;
fInValue = false;
fTagClosed = false;
memset(tag, 0, MAX_STRING_LEN);
memset(attribute, 0, MAX_STRING_LEN);
memset(value, 0, MAX_STRING_LEN);
memset(tmp, 0, MAX_STRING_LEN);
}
void XMLParser::addChar(char ch, char* str)
{
if (strlen(str) < MAX_STRING_LEN-1)
{
str[strlen(str)] = ch;
}
}
void XMLParser::parse(char in)
{
if (callback == NULL)
{
return;
}
switch (in)
{
case '<': // Tag starting
memset(tmp, 0, strlen(tmp));
break;
case ' ':
if (strlen(tag) == 0)
{
// Save tag name
strcpy(tag, tmp);
callback(context, false, tag, (char *)"", (char *)"");
}
if (fInValue)
{
addChar(in, tmp);
}
else
{
fInAttribute = true;
memset(tmp, 0, strlen(tmp));
}
break;
case '/':
if (fInValue)
{
addChar(in, tmp);
}
else
{
fTagClosed = true;
}
break;
case '>': // Tag ending
if (strlen(tag) == 0)
{
strcpy(tag, tmp);
}
callback(context, fTagClosed, tag, (char *)"", (char *)"");
reset();
break;
case '=':
if (fInValue)
{
addChar(in, tmp);
}
else if (fInAttribute)
{
strcpy(attribute, tmp);
memset(tmp, 0, strlen(tmp));
fInAttribute = false;
}
break;
case '"':
if (fInValue)
{
strcpy(value, tmp);
memset(tmp, 0, strlen(tmp));
fInValue = false;
// Process tag, attribute, value
callback(context, false, tag, attribute, value);
}
else
{
fInValue = true;
}
break;
case 10:
// New line, reset
reset();
break;
default:
addChar(in, tmp);
}
}
| 18
| 91
| 0.458541
|
ternarylabs
|
811803fdb28909e8d83e327b28915a5250a644a8
| 10,407
|
cpp
|
C++
|
shared/source/xe_hp_core/command_stream_receiver_hw_xe_hp_core.cpp
|
smorek-intel/compute-runtime
|
299e798159e55ccc198802b8eb114c91f8b8e85d
|
[
"Intel",
"MIT"
] | null | null | null |
shared/source/xe_hp_core/command_stream_receiver_hw_xe_hp_core.cpp
|
smorek-intel/compute-runtime
|
299e798159e55ccc198802b8eb114c91f8b8e85d
|
[
"Intel",
"MIT"
] | null | null | null |
shared/source/xe_hp_core/command_stream_receiver_hw_xe_hp_core.cpp
|
smorek-intel/compute-runtime
|
299e798159e55ccc198802b8eb114c91f8b8e85d
|
[
"Intel",
"MIT"
] | null | null | null |
/*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/xe_hp_core/hw_cmds.h"
#include "shared/source/xe_hp_core/hw_info.h"
using Family = NEO::XeHpFamily;
#include "shared/source/command_stream/command_stream_receiver_hw_tgllp_and_later.inl"
#include "shared/source/command_stream/command_stream_receiver_hw_xehp_and_later.inl"
#include "shared/source/helpers/blit_commands_helper_xehp_and_later.inl"
#include "shared/source/helpers/populate_factory.h"
namespace NEO {
static auto gfxCore = IGFX_XE_HP_CORE;
template <>
bool ImplicitFlushSettings<Family>::defaultSettingForNewResource = true;
template <>
bool ImplicitFlushSettings<Family>::defaultSettingForGpuIdle = true;
template class ImplicitFlushSettings<Family>;
template <>
void populateFactoryTable<CommandStreamReceiverHw<Family>>() {
extern CommandStreamReceiverCreateFunc commandStreamReceiverFactory[2 * IGFX_MAX_CORE];
commandStreamReceiverFactory[gfxCore] = DeviceCommandStreamReceiver<Family>::create;
}
template <>
MemoryCompressionState CommandStreamReceiverHw<Family>::getMemoryCompressionState(bool auxTranslationRequired, const HardwareInfo &hwInfo) const {
auto memoryCompressionState = MemoryCompressionState::NotApplicable;
auto &hwHelper = HwHelper::get(hwInfo.platform.eRenderCoreFamily);
if (hwHelper.allowStatelessCompression(hwInfo)) {
memoryCompressionState = auxTranslationRequired ? MemoryCompressionState::Disabled : MemoryCompressionState::Enabled;
}
return memoryCompressionState;
}
template <>
GraphicsAllocation *CommandStreamReceiverHw<Family>::getClearColorAllocation() {
constexpr uint32_t clearColorSize = 16u;
static uint8_t clearColorBuffer[clearColorSize];
if (DebugManager.flags.UseClearColorAllocationForBlitter.get()) {
if (clearColorAllocation == nullptr) {
auto lock = this->obtainUniqueOwnership();
if (clearColorAllocation == nullptr) {
AllocationProperties properties{rootDeviceIndex, clearColorSize, GraphicsAllocation::AllocationType::BUFFER, osContext->getDeviceBitfield()};
properties.flags.readOnlyMultiStorage = true;
properties.flags.flushL3RequiredForRead = properties.flags.flushL3RequiredForWrite = false;
clearColorAllocation = getMemoryManager()->allocateGraphicsMemoryWithProperties(properties, clearColorBuffer);
}
}
}
return clearColorAllocation;
}
template <>
void CommandStreamReceiverHw<Family>::programPerDssBackedBuffer(LinearStream &commandStream, Device &device, DispatchFlags &dispatchFlags) {
}
template <>
size_t CommandStreamReceiverHw<Family>::getCmdSizeForPerDssBackedBuffer(const HardwareInfo &hwInfo) {
return 0;
}
template <>
inline bool CommandStreamReceiverHw<Family>::isAdditionalPipeControlNeeded() const {
return DebugManager.flags.ProgramAdditionalPipeControlBeforeStateComputeModeCommand.get();
}
template <>
void CommandStreamReceiverHw<Family>::programComputeMode(LinearStream &stream, DispatchFlags &dispatchFlags, const HardwareInfo &hwInfo) {
using PIPE_CONTROL = typename Family::PIPE_CONTROL;
if (isComputeModeNeeded()) {
this->lastSentCoherencyRequest = static_cast<int8_t>(dispatchFlags.requiresCoherency);
if (DebugManager.flags.ProgramAdditionalPipeControlBeforeStateComputeModeCommand.get()) {
auto pc = stream.getSpaceForCmd<PIPE_CONTROL>();
*pc = Family::cmdInitPipeControl;
pc->setHdcPipelineFlush(true);
pc->setAmfsFlushEnable(true);
pc->setCommandStreamerStallEnable(true);
pc->setInstructionCacheInvalidateEnable(true);
pc->setTextureCacheInvalidationEnable(true);
pc->setDcFlushEnable(true);
pc->setConstantCacheInvalidationEnable(true);
pc->setStateCacheInvalidationEnable(true);
}
auto stateComputeMode = Family::cmdInitStateComputeMode;
EncodeStates<Family>::adjustStateComputeMode(stream, dispatchFlags.numGrfRequired, &stateComputeMode,
dispatchFlags.requiresCoherency, this->requiredThreadArbitrationPolicy, hwInfo);
if (csrSizeRequestFlags.hasSharedHandles) {
auto pc = stream.getSpaceForCmd<PIPE_CONTROL>();
*pc = Family::cmdInitPipeControl;
}
}
}
template <>
void BlitCommandsHelper<Family>::appendClearColor(const BlitProperties &blitProperties, typename Family::XY_COPY_BLT &blitCmd) {
using XY_COPY_BLT = typename Family::XY_COPY_BLT;
if (DebugManager.flags.UseClearColorAllocationForBlitter.get()) {
blitCmd.setSourceClearValueEnable(XY_COPY_BLT::CLEAR_VALUE_ENABLE::CLEAR_VALUE_ENABLE_ENABLE);
blitCmd.setDestinationClearValueEnable(XY_COPY_BLT::CLEAR_VALUE_ENABLE::CLEAR_VALUE_ENABLE_ENABLE);
auto clearColorAddress = blitProperties.clearColorAllocation->getGpuAddress();
blitCmd.setSourceClearAddressLow(static_cast<uint32_t>(clearColorAddress & 0xFFFFFFFFULL));
blitCmd.setSourceClearAddressHigh(static_cast<uint32_t>(clearColorAddress >> 32));
blitCmd.setDestinationClearAddressLow(static_cast<uint32_t>(clearColorAddress & 0xFFFFFFFFULL));
blitCmd.setDestinationClearAddressHigh(static_cast<uint32_t>(clearColorAddress >> 32));
}
}
template class CommandStreamReceiverHw<Family>;
template <>
void BlitCommandsHelper<Family>::appendExtraMemoryProperties(typename Family::XY_COPY_BLT &blitCmd, const RootDeviceEnvironment &rootDeviceEnvironment) {
using XY_COPY_BLT = typename Family::XY_COPY_BLT;
auto hwInfo = rootDeviceEnvironment.getHardwareInfo();
auto &hwHelper = HwHelperHw<Family>::get();
if (hwHelper.isWorkaroundRequired(REVISION_A0, REVISION_B, *hwInfo) && hwHelper.getLocalMemoryAccessMode(*hwInfo) == LocalMemoryAccessMode::CpuAccessAllowed) {
blitCmd.setSourceTargetMemory(XY_COPY_BLT::TARGET_MEMORY::TARGET_MEMORY_SYSTEM_MEM);
blitCmd.setDestinationTargetMemory(XY_COPY_BLT::TARGET_MEMORY::TARGET_MEMORY_SYSTEM_MEM);
}
}
template <>
void BlitCommandsHelper<Family>::appendExtraMemoryProperties(typename Family::XY_COLOR_BLT &blitCmd, const RootDeviceEnvironment &rootDeviceEnvironment) {
using XY_COLOR_BLT = typename Family::XY_COLOR_BLT;
auto hwInfo = rootDeviceEnvironment.getHardwareInfo();
auto &hwHelper = HwHelperHw<Family>::get();
if (hwHelper.isWorkaroundRequired(REVISION_A0, REVISION_B, *hwInfo) &&
hwHelper.getLocalMemoryAccessMode(*hwInfo) == LocalMemoryAccessMode::CpuAccessAllowed) {
blitCmd.setDestinationTargetMemory(XY_COLOR_BLT::DESTINATION_TARGET_MEMORY::DESTINATION_TARGET_MEMORY_SYSTEM_MEM);
}
}
template struct BlitCommandsHelper<Family>;
const Family::COMPUTE_WALKER Family::cmdInitGpgpuWalker = Family::COMPUTE_WALKER::sInit();
const Family::CFE_STATE Family::cmdInitCfeState = Family::CFE_STATE::sInit();
const Family::INTERFACE_DESCRIPTOR_DATA Family::cmdInitInterfaceDescriptorData = Family::INTERFACE_DESCRIPTOR_DATA::sInit();
const Family::MI_BATCH_BUFFER_START Family::cmdInitBatchBufferStart = Family::MI_BATCH_BUFFER_START::sInit();
const Family::MI_BATCH_BUFFER_END Family::cmdInitBatchBufferEnd = Family::MI_BATCH_BUFFER_END::sInit();
const Family::PIPE_CONTROL Family::cmdInitPipeControl = Family::PIPE_CONTROL::sInit();
const Family::STATE_COMPUTE_MODE Family::cmdInitStateComputeMode = Family::STATE_COMPUTE_MODE::sInit();
const Family::_3DSTATE_BINDING_TABLE_POOL_ALLOC Family::cmdInitStateBindingTablePoolAlloc =
Family::_3DSTATE_BINDING_TABLE_POOL_ALLOC::sInit();
const Family::MI_SEMAPHORE_WAIT Family::cmdInitMiSemaphoreWait = Family::MI_SEMAPHORE_WAIT::sInit();
const Family::RENDER_SURFACE_STATE Family::cmdInitRenderSurfaceState = Family::RENDER_SURFACE_STATE::sInit();
const Family::POSTSYNC_DATA Family::cmdInitPostSyncData = Family::POSTSYNC_DATA::sInit();
const Family::MI_SET_PREDICATE Family::cmdInitSetPredicate = Family::MI_SET_PREDICATE::sInit();
const Family::MI_LOAD_REGISTER_IMM Family::cmdInitLoadRegisterImm = Family::MI_LOAD_REGISTER_IMM::sInit();
const Family::MI_LOAD_REGISTER_REG Family::cmdInitLoadRegisterReg = Family::MI_LOAD_REGISTER_REG::sInit();
const Family::MI_LOAD_REGISTER_MEM Family::cmdInitLoadRegisterMem = Family::MI_LOAD_REGISTER_MEM::sInit();
const Family::MI_STORE_DATA_IMM Family::cmdInitStoreDataImm = Family::MI_STORE_DATA_IMM::sInit();
const Family::MI_STORE_REGISTER_MEM Family::cmdInitStoreRegisterMem = Family::MI_STORE_REGISTER_MEM::sInit();
const Family::MI_NOOP Family::cmdInitNoop = Family::MI_NOOP::sInit();
const Family::MI_REPORT_PERF_COUNT Family::cmdInitReportPerfCount = Family::MI_REPORT_PERF_COUNT::sInit();
const Family::MI_ATOMIC Family::cmdInitAtomic = Family::MI_ATOMIC::sInit();
const Family::PIPELINE_SELECT Family::cmdInitPipelineSelect = Family::PIPELINE_SELECT::sInit();
const Family::MI_ARB_CHECK Family::cmdInitArbCheck = Family::MI_ARB_CHECK::sInit();
const Family::STATE_BASE_ADDRESS Family::cmdInitStateBaseAddress = Family::STATE_BASE_ADDRESS::sInit();
const Family::MEDIA_SURFACE_STATE Family::cmdInitMediaSurfaceState = Family::MEDIA_SURFACE_STATE::sInit();
const Family::SAMPLER_STATE Family::cmdInitSamplerState = Family::SAMPLER_STATE::sInit();
const Family::BINDING_TABLE_STATE Family::cmdInitBindingTableState = Family::BINDING_TABLE_STATE::sInit();
const Family::MI_USER_INTERRUPT Family::cmdInitUserInterrupt = Family::MI_USER_INTERRUPT::sInit();
const Family::MI_CONDITIONAL_BATCH_BUFFER_END cmdInitConditionalBatchBufferEnd = Family::MI_CONDITIONAL_BATCH_BUFFER_END::sInit();
const Family::L3_CONTROL Family::cmdInitL3Control = Family::L3_CONTROL::sInit();
const Family::L3_FLUSH_ADDRESS_RANGE Family::cmdInitL3FlushAddressRange = Family::L3_FLUSH_ADDRESS_RANGE::sInit();
const Family::MI_FLUSH_DW Family::cmdInitMiFlushDw = Family::MI_FLUSH_DW::sInit();
const Family::XY_BLOCK_COPY_BLT Family::cmdInitXyCopyBlt = Family::XY_BLOCK_COPY_BLT::sInit();
const Family::XY_FAST_COLOR_BLT Family::cmdInitXyColorBlt = Family::XY_FAST_COLOR_BLT::sInit();
const Family::_3DSTATE_BTD Family::cmd3dStateBtd = Family::_3DSTATE_BTD::sInit();
const Family::_3DSTATE_BTD_BODY Family::cmd3dStateBtdBody = Family::_3DSTATE_BTD_BODY::sInit();
const Family::STATE_SIP Family::cmdInitStateSip = Family::STATE_SIP::sInit();
} // namespace NEO
| 55.356383
| 163
| 0.786586
|
smorek-intel
|
811edd45a2f58733b439e80adf7d287eb51b1366
| 3,773
|
cc
|
C++
|
src/shader.cc
|
WaldJohannaU/Classy3DViewer
|
2a3ccddc5f9a860a76a8293e9b2d41de72517096
|
[
"BSD-2-Clause"
] | 9
|
2018-08-19T21:26:27.000Z
|
2022-01-24T07:19:36.000Z
|
src/shader.cc
|
WaldJohannaU/Classy3DViewer
|
2a3ccddc5f9a860a76a8293e9b2d41de72517096
|
[
"BSD-2-Clause"
] | null | null | null |
src/shader.cc
|
WaldJohannaU/Classy3DViewer
|
2a3ccddc5f9a860a76a8293e9b2d41de72517096
|
[
"BSD-2-Clause"
] | 1
|
2021-08-10T07:32:44.000Z
|
2021-08-10T07:32:44.000Z
|
/*******************************************************
* Copyright (c) 2018, Johanna Wald
* All rights reserved.
*
* This file is distributed under the GNU Lesser General Public License v3.0.
* The complete license agreement can be obtained at:
* http://www.gnu.org/licenses/lgpl-3.0.html
********************************************************/
#include "shader.h"
void Shader::Init(const std::string& name, const std::string& vertex, const std::string fragment) {
if (!initalized_) {
shader_.init(name, vertex, fragment);
initalized_ = true;
}
}
void Shader2D::Init(const std::string& name) {
if (!initalized_) {
const std::string& vertex = "#version 330\n"
"layout(location = 0) in vec3 position;\n"
"layout(location = 1) in vec2 vertexUV;\n"
"out vec2 UV;\n"
"void main() {\n"
" gl_Position = vec4(position, 1.0);\n"
" UV = vertexUV;\n"
"}";
const std::string& fragment = "#version 330\n"
"in vec2 UV;\n"
"uniform sampler2D myTextureSampler;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(texture(myTextureSampler, UV).rgb, 1.0);\n"
"}";
shader_.init(name, vertex, fragment);
unsigned int indices[] = {0, 1, 2, 2, 3, 0};
float vertices[] = {-1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1};
float uvs[] = {0, 1, 1, 1, 1, 0, 0, 0};
float uvs_flipped[] = {1, 0, 0, 0, 0, 1, 1, 1};
Eigen::Map<nanogui::MatrixXf> v_vertices(vertices,3,4);
Eigen::Map<nanogui::MatrixXf> v_uvs(uvs,2,4);
Eigen::Map<nanogui::MatrixXf> v_uvs_flipped(uvs_flipped,2,4);
Eigen::Map<nanogui::MatrixXu> v_indices(indices,3,2);
shader_.bind();
shader_.uploadIndices(v_indices);
shader_.uploadAttrib("position", v_vertices);
shader_.uploadAttrib("vertexUV", v_uvs);
initalized_ = true;
}
}
void Shader3DColored::Init(const std::string& name) {
if (!initalized_) {
const std::string vertex{"#version 330\n"
"uniform mat4 model_view_projection;\n"
"layout(location = 0) in vec3 position;\n"
"layout(location = 1) in vec3 color;\n"
"out vec3 colorV;\n"
"void main() {\n"
" gl_Position = model_view_projection * vec4(position, 1.0);\n"
" colorV = color;\n"
"}"};
const std::string fragment{"#version 330\n"
"in vec3 colorV;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(colorV, 1.0);\n"
"}"};
shader_.init(name, vertex, fragment);
initalized_ = true;
}
}
void Shader3DTextured::Init(const std::string& name) {
if (!initalized_) {
const std::string& vertex{"#version 330\n"
"uniform mat4 model_view_projection;\n"
"layout(location = 0) in vec3 position;\n"
"layout(location = 1) in vec2 vertexUV;\n"
"layout(location = 2) in vec3 color;\n"
"out vec3 colorV;\n"
"out vec2 UV;\n"
"void main() {\n"
" gl_Position = model_view_projection * vec4(position, 1.0);\n"
" colorV = color;\n"
" UV = vec2(vertexUV.x, 1 - vertexUV.y);\n"
"}"};
const std::string& fragment{"#version 330\n"
"in vec2 UV;\n"
"in vec3 colorV;\n"
"uniform sampler2D myTextureSampler;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(texture(myTextureSampler, UV).rgb, 1.0);\n"
"}"};
shader_.init(name, vertex, fragment);
initalized_ = true;
}
}
| 34.614679
| 99
| 0.520806
|
WaldJohannaU
|
811ee9f4602c75735dc8487bcb34329a9798e1c7
| 7,178
|
cpp
|
C++
|
Core/CppMicroServices/src/util/usUtils.cpp
|
rfloca/MITK
|
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
|
[
"BSD-3-Clause"
] | null | null | null |
Core/CppMicroServices/src/util/usUtils.cpp
|
rfloca/MITK
|
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
|
[
"BSD-3-Clause"
] | null | null | null |
Core/CppMicroServices/src/util/usUtils.cpp
|
rfloca/MITK
|
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
|
[
"BSD-3-Clause"
] | null | null | null |
/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "usUtils_p.h"
#include "usLog_p.h"
#include "usModuleInfo.h"
#include "usModuleSettings.h"
#include <cstdio>
#include <cctype>
#include <algorithm>
#ifdef US_PLATFORM_POSIX
#include <errno.h>
#include <string.h>
#include <dlfcn.h>
#include <dirent.h>
#else
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <crtdbg.h>
#include "dirent_win32_p.h"
#endif
//-------------------------------------------------------------------
// Module auto-loading
//-------------------------------------------------------------------
namespace {
#if !defined(US_PLATFORM_LINUX)
std::string library_suffix()
{
#ifdef US_PLATFORM_WINDOWS
return ".dll";
#elif defined(US_PLATFORM_APPLE)
return ".dylib";
#else
return ".so";
#endif
}
#endif
#ifdef US_PLATFORM_POSIX
const char DIR_SEP = '/';
bool load_impl(const std::string& modulePath)
{
void* handle = dlopen(modulePath.c_str(), RTLD_NOW | RTLD_LOCAL);
return (handle != NULL);
}
#elif defined(US_PLATFORM_WINDOWS)
const char DIR_SEP = '\\';
bool load_impl(const std::string& modulePath)
{
void* handle = LoadLibrary(modulePath.c_str());
return (handle != NULL);
}
#else
#ifdef US_ENABLE_AUTOLOADING_SUPPORT
#error "Missing load_impl implementation for this platform."
#else
bool load_impl(const std::string&) { return false; }
#endif
#endif
}
US_BEGIN_NAMESPACE
void AutoLoadModulesFromPath(const std::string& absoluteBasePath, const std::string& subDir)
{
std::string loadPath = absoluteBasePath + DIR_SEP + subDir;
DIR* dir = opendir(loadPath.c_str());
#ifdef CMAKE_INTDIR
// Try intermediate output directories
if (dir == NULL)
{
std::size_t indexOfLastSeparator = absoluteBasePath.find_last_of(DIR_SEP);
if (indexOfLastSeparator != -1)
{
std::string intermediateDir = absoluteBasePath.substr(indexOfLastSeparator+1);
bool equalSubDir = intermediateDir.size() == std::strlen(CMAKE_INTDIR);
for (std::size_t i = 0; equalSubDir && i < intermediateDir.size(); ++i)
{
if (std::tolower(intermediateDir[i]) != std::tolower(CMAKE_INTDIR[i]))
{
equalSubDir = false;
}
}
if (equalSubDir)
{
loadPath = absoluteBasePath.substr(0, indexOfLastSeparator+1) + subDir + DIR_SEP + CMAKE_INTDIR;
dir = opendir(loadPath.c_str());
}
}
}
#endif
if (dir != NULL)
{
struct dirent *ent = NULL;
while ((ent = readdir(dir)) != NULL)
{
bool loadFile = true;
#ifdef _DIRENT_HAVE_D_TYPE
if (ent->d_type != DT_UNKNOWN && ent->d_type != DT_REG)
{
loadFile = false;
}
#endif
std::string entryFileName(ent->d_name);
// On Linux, library file names can have version numbers appended. On other platforms, we
// check the file ending. This could be refined for Linux in the future.
#if !defined(US_PLATFORM_LINUX)
if (entryFileName.rfind(library_suffix()) != (entryFileName.size() - library_suffix().size()))
{
loadFile = false;
}
#endif
if (!loadFile) continue;
std::string libPath = loadPath;
if (!libPath.empty() && libPath.find_last_of(DIR_SEP) != libPath.size() -1)
{
libPath += DIR_SEP;
}
libPath += entryFileName;
US_INFO << "Auto-loading module " << libPath;
if (!load_impl(libPath))
{
US_WARN << "Auto-loading of module " << libPath << " failed: " << GetLastErrorStr();
}
}
closedir(dir);
}
}
void AutoLoadModules(const ModuleInfo& moduleInfo)
{
if (moduleInfo.autoLoadDir.empty())
{
return;
}
ModuleSettings::PathList autoLoadPaths = ModuleSettings::GetAutoLoadPaths();
std::size_t indexOfLastSeparator = moduleInfo.location.find_last_of(DIR_SEP);
std::string moduleBasePath = moduleInfo.location.substr(0, indexOfLastSeparator);
for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin();
i != autoLoadPaths.end(); ++i)
{
if (*i == ModuleSettings::CURRENT_MODULE_PATH())
{
// Load all modules from a directory located relative to this modules location
// and named after this modules library name.
*i = moduleBasePath;
}
}
// We could have introduced a duplicate above, so remove it.
std::sort(autoLoadPaths.begin(), autoLoadPaths.end());
autoLoadPaths.erase(std::unique(autoLoadPaths.begin(), autoLoadPaths.end()), autoLoadPaths.end());
for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin();
i != autoLoadPaths.end(); ++i)
{
if (i->empty()) continue;
AutoLoadModulesFromPath(*i, moduleInfo.autoLoadDir);
}
}
US_END_NAMESPACE
//-------------------------------------------------------------------
// Error handling
//-------------------------------------------------------------------
US_BEGIN_NAMESPACE
std::string GetLastErrorStr()
{
#ifdef US_PLATFORM_POSIX
return std::string(strerror(errno));
#else
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
std::string errMsg((LPCTSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
return errMsg;
#endif
}
static MsgHandler handler = 0;
MsgHandler installMsgHandler(MsgHandler h)
{
MsgHandler old = handler;
handler = h;
return old;
}
void message_output(MsgType msgType, const char *buf)
{
if (handler)
{
(*handler)(msgType, buf);
}
else
{
fprintf(stderr, "%s\n", buf);
fflush(stderr);
}
if (msgType == ErrorMsg)
{
#if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR)
// get the current report mode
int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
_CrtSetReportMode(_CRT_ERROR, reportMode);
int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, CppMicroServices_VERSION_STR, buf);
if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW)
return; // ignore
else if (ret == 1)
_CrtDbgBreak();
#endif
#ifdef US_PLATFORM_POSIX
abort(); // trap; generates core dump
#else
exit(1); // goodbye cruel world
#endif
}
}
US_END_NAMESPACE
| 25.363958
| 104
| 0.639593
|
rfloca
|
812b4e82bb874fd5918f26670fb560f79f5a8e44
| 16,003
|
cc
|
C++
|
squid/squid3-3.3.8.spaceify/helpers/digest_auth/eDirectory/edir_ldapext.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-01-20T15:25:34.000Z
|
2017-12-20T06:47:42.000Z
|
squid/squid3-3.3.8.spaceify/helpers/digest_auth/eDirectory/edir_ldapext.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-05-15T09:32:55.000Z
|
2016-02-18T13:43:31.000Z
|
squid/squid3-3.3.8.spaceify/helpers/digest_auth/eDirectory/edir_ldapext.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | null | null | null |
/*
* NDS LDAP helper functions
* Copied From Samba-3.0.24 pdb_nds.c and trimmed down to the
* limited functionality needed to access the plain text password only
*
* Original copyright & license follows:
*
* Copyright (C) Vince Brimhall 2004-2005
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include "squid.h"
#include "digest_common.h"
#if _SQUID_MSWIN_ /* Native Windows port and MinGW */
#define snprintf _snprintf
#include <windows.h>
#include <winldap.h>
#include <winber.h>
#ifndef LDAPAPI
#define LDAPAPI __cdecl
#endif
#ifdef LDAP_VERSION3
#ifndef LDAP_OPT_X_TLS
#define LDAP_OPT_X_TLS 0x6000
#endif
#define ber_alloc() ber_alloc_t(0)
#endif /* LDAP_VERSION3 */
#else
#include <lber.h>
#include <ldap.h>
#endif
#include <wchar.h>
#include "edir_ldapext.h"
#define NMASLDAP_GET_LOGIN_CONFIG_REQUEST "2.16.840.1.113719.1.39.42.100.3"
#define NMASLDAP_GET_LOGIN_CONFIG_RESPONSE "2.16.840.1.113719.1.39.42.100.4"
#define NMASLDAP_SET_PASSWORD_REQUEST "2.16.840.1.113719.1.39.42.100.11"
#define NMASLDAP_SET_PASSWORD_RESPONSE "2.16.840.1.113719.1.39.42.100.12"
#define NMASLDAP_GET_PASSWORD_REQUEST "2.16.840.1.113719.1.39.42.100.13"
#define NMASLDAP_GET_PASSWORD_RESPONSE "2.16.840.1.113719.1.39.42.100.14"
#define NMAS_LDAP_EXT_VERSION 1
#define SMB_MALLOC_ARRAY(type, nelem) calloc(sizeof(type), nelem)
#define DEBUG(level, args)
/**********************************************************************
Take the request BER value and input data items and BER encodes the
data into the BER value
**********************************************************************/
static int berEncodePasswordData(
struct berval **requestBV,
const char *objectDN,
const char *password,
const char *password2)
{
int err = 0, rc=0;
BerElement *requestBer = NULL;
const char * utf8ObjPtr = NULL;
int utf8ObjSize = 0;
const char * utf8PwdPtr = NULL;
int utf8PwdSize = 0;
const char * utf8Pwd2Ptr = NULL;
int utf8Pwd2Size = 0;
/* Convert objectDN and tag strings from Unicode to UTF-8 */
utf8ObjSize = strlen(objectDN)+1;
utf8ObjPtr = objectDN;
if (password != NULL) {
utf8PwdSize = strlen(password)+1;
utf8PwdPtr = password;
}
if (password2 != NULL) {
utf8Pwd2Size = strlen(password2)+1;
utf8Pwd2Ptr = password2;
}
/* Allocate a BerElement for the request parameters. */
if ((requestBer = ber_alloc()) == NULL) {
err = LDAP_ENCODING_ERROR;
ber_free(requestBer, 1);
return err;
}
if (password != NULL && password2 != NULL) {
/* BER encode the NMAS Version, the objectDN, and the password */
rc = ber_printf(requestBer, "{iooo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize, utf8Pwd2Ptr, utf8Pwd2Size);
} else if (password != NULL) {
/* BER encode the NMAS Version, the objectDN, and the password */
rc = ber_printf(requestBer, "{ioo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize);
} else {
/* BER encode the NMAS Version and the objectDN */
rc = ber_printf(requestBer, "{io}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize);
}
if (rc < 0) {
err = LDAP_ENCODING_ERROR;
} else {
err = 0;
/* Convert the BER we just built to a berval that we'll send with the extended request. */
if ((ber_tag_t)ber_flatten(requestBer, requestBV) == LBER_ERROR) {
err = LDAP_ENCODING_ERROR;
}
}
if (requestBer) {
ber_free(requestBer, 1);
}
return err;
}
/**********************************************************************
Take the request BER value and input data items and BER encodes the
data into the BER value
**********************************************************************/
static int berEncodeLoginData(
struct berval **requestBV,
char *objectDN,
unsigned int methodIDLen,
unsigned int *methodID,
char *tag,
size_t putDataLen,
void *putData)
{
int err = 0;
BerElement *requestBer = NULL;
unsigned int i;
unsigned int elemCnt = methodIDLen / sizeof(unsigned int);
char *utf8ObjPtr=NULL;
int utf8ObjSize = 0;
char *utf8TagPtr = NULL;
int utf8TagSize = 0;
utf8ObjPtr = objectDN;
utf8ObjSize = strlen(utf8ObjPtr)+1;
utf8TagPtr = tag;
utf8TagSize = strlen(utf8TagPtr)+1;
/* Allocate a BerElement for the request parameters. */
if ((requestBer = ber_alloc()) == NULL) {
err = LDAP_ENCODING_ERROR;
return err;
}
/* BER encode the NMAS Version and the objectDN */
err = (ber_printf(requestBer, "{io", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize) < 0) ? LDAP_ENCODING_ERROR : 0;
/* BER encode the MethodID Length and value */
if (!err) {
err = (ber_printf(requestBer, "{i{", methodIDLen) < 0) ? LDAP_ENCODING_ERROR : 0;
}
for (i = 0; !err && i < elemCnt; ++i) {
err = (ber_printf(requestBer, "i", methodID[i]) < 0) ? LDAP_ENCODING_ERROR : 0;
}
if (!err) {
err = (ber_printf(requestBer, "}}", 0) < 0) ? LDAP_ENCODING_ERROR : 0;
}
if (putData) {
/* BER Encode the the tag and data */
err = (ber_printf(requestBer, "oio}", utf8TagPtr, utf8TagSize, putDataLen, putData, putDataLen) < 0) ? LDAP_ENCODING_ERROR : 0;
} else {
/* BER Encode the the tag */
err = (ber_printf(requestBer, "o}", utf8TagPtr, utf8TagSize) < 0) ? LDAP_ENCODING_ERROR : 0;
}
/* Convert the BER we just built to a berval that we'll send with the extended request. */
if (!err && (ber_tag_t)ber_flatten(requestBer, requestBV) == LBER_ERROR) {
err = LDAP_ENCODING_ERROR;
}
if (requestBer) {
ber_free(requestBer, 1);
}
return err;
}
/**********************************************************************
Takes the reply BER Value and decodes the NMAS server version and
return code and if a non null retData buffer was supplied, tries to
decode the the return data and length
**********************************************************************/
static int berDecodeLoginData(
struct berval *replyBV,
int *serverVersion,
size_t *retDataLen,
void *retData )
{
int err = 0;
BerElement *replyBer = NULL;
char *retOctStr = NULL;
size_t retOctStrLen = 0;
if ((replyBer = ber_init(replyBV)) == NULL) {
err = LDAP_OPERATIONS_ERROR;
} else if (retData) {
retOctStrLen = *retDataLen + 1;
retOctStr = (char*)SMB_MALLOC_ARRAY(char, retOctStrLen);
if (!retOctStr) {
err = LDAP_OPERATIONS_ERROR;
} else if (ber_scanf(replyBer, "{iis}", serverVersion, &err, retOctStr, &retOctStrLen) != LBER_ERROR) {
if (*retDataLen >= retOctStrLen) {
memcpy(retData, retOctStr, retOctStrLen);
} else if (!err) {
err = LDAP_NO_MEMORY;
}
*retDataLen = retOctStrLen;
} else if (!err) {
err = LDAP_DECODING_ERROR;
}
} else {
if (ber_scanf(replyBer, "{ii}", serverVersion, &err) == LBER_ERROR) {
if (!err) {
err = LDAP_DECODING_ERROR;
}
}
}
if (replyBer) {
ber_free(replyBer, 1);
}
if (retOctStr != NULL) {
memset(retOctStr, 0, retOctStrLen);
free(retOctStr);
}
return err;
}
/**********************************************************************
Retrieves data in the login configuration of the specified object
that is tagged with the specified methodID and tag.
**********************************************************************/
static int getLoginConfig(
LDAP *ld,
char *objectDN,
unsigned int methodIDLen,
unsigned int *methodID,
char *tag,
size_t *dataLen,
void *data )
{
int err = 0;
struct berval *requestBV = NULL;
char *replyOID = NULL;
struct berval *replyBV = NULL;
int serverVersion = 0;
/* Validate unicode parameters. */
if ((strlen(objectDN) == 0) || ld == NULL) {
return LDAP_NO_SUCH_ATTRIBUTE;
}
err = berEncodeLoginData(&requestBV, objectDN, methodIDLen, methodID, tag, 0, NULL);
if (err) {
;
} else if (!err && (err = ldap_extended_operation_s(ld, NMASLDAP_GET_LOGIN_CONFIG_REQUEST,
requestBV, NULL, NULL, &replyOID, &replyBV))) {
/* Call the ldap_extended_operation (synchronously) */
;
} else if (!replyOID) {
/* Make sure there is a return OID */
err = LDAP_NOT_SUPPORTED;
} else if (strcmp(replyOID, NMASLDAP_GET_LOGIN_CONFIG_RESPONSE)) {
/* Is this what we were expecting to get back. */
err = LDAP_NOT_SUPPORTED;
} else if (!replyBV) {
/* Do we have a good returned berval? */
/* No; returned berval means we experienced a rather drastic error. */
/* Return operations error. */
err = LDAP_OPERATIONS_ERROR;
} else {
err = berDecodeLoginData(replyBV, &serverVersion, dataLen, data);
if (serverVersion != NMAS_LDAP_EXT_VERSION) {
err = LDAP_OPERATIONS_ERROR;
}
}
if (replyBV) {
ber_bvfree(replyBV);
}
/* Free the return OID string if one was returned. */
if (replyOID) {
ldap_memfree(replyOID);
}
/* Free memory allocated while building the request ber and berval. */
if (requestBV) {
ber_bvfree(requestBV);
}
/* Return the appropriate error/success code. */
return err;
}
/**********************************************************************
Attempts to get the Simple Password
**********************************************************************/
static int nmasldap_get_simple_pwd(
LDAP *ld,
char *objectDN,
size_t pwdLen,
char *pwd )
{
int err = 0;
unsigned int methodID = 0;
unsigned int methodIDLen = sizeof(methodID);
char tag[] = {'P','A','S','S','W','O','R','D',' ','H','A','S','H',0};
char *pwdBuf=NULL;
size_t pwdBufLen, bufferLen;
bufferLen = pwdBufLen = pwdLen+2;
pwdBuf = (char*)SMB_MALLOC_ARRAY(char, pwdBufLen); /* digest and null */
if (pwdBuf == NULL) {
return LDAP_NO_MEMORY;
}
err = getLoginConfig(ld, objectDN, methodIDLen, &methodID, tag, &pwdBufLen, pwdBuf);
if (err == 0) {
if (pwdBufLen !=0) {
pwdBuf[pwdBufLen] = 0; /* null terminate */
switch (pwdBuf[0]) {
case 1: /* cleartext password */
break;
case 2: /* SHA1 HASH */
case 3: /* MD5_ID */
case 4: /* UNIXCrypt_ID */
case 8: /* SSHA_ID */
default: /* Unknown digest */
err = LDAP_INAPPROPRIATE_AUTH; /* only return clear text */
break;
}
if (!err) {
if (pwdLen >= pwdBufLen-1) {
memcpy(pwd, &pwdBuf[1], pwdBufLen-1); /* skip digest tag and include null */
} else {
err = LDAP_NO_MEMORY;
}
}
}
}
if (pwdBuf != NULL) {
memset(pwdBuf, 0, bufferLen);
free(pwdBuf);
}
return err;
}
/**********************************************************************
Attempts to get the Universal Password
**********************************************************************/
static int nmasldap_get_password(
LDAP *ld,
char *objectDN,
size_t *pwdSize, /* in bytes */
unsigned char *pwd )
{
int err = 0;
struct berval *requestBV = NULL;
char *replyOID = NULL;
struct berval *replyBV = NULL;
int serverVersion;
char *pwdBuf;
size_t pwdBufLen, bufferLen;
/* Validate char parameters. */
if (objectDN == NULL || (strlen(objectDN) == 0) || pwdSize == NULL || ld == NULL) {
return LDAP_NO_SUCH_ATTRIBUTE;
}
bufferLen = pwdBufLen = *pwdSize;
pwdBuf = (char*)SMB_MALLOC_ARRAY(char, pwdBufLen+2);
if (pwdBuf == NULL) {
return LDAP_NO_MEMORY;
}
err = berEncodePasswordData(&requestBV, objectDN, NULL, NULL);
if (err) {
;
} else if ((err = ldap_extended_operation_s(ld, NMASLDAP_GET_PASSWORD_REQUEST, requestBV, NULL, NULL, &replyOID, &replyBV))) {
; /* Call the ldap_extended_operation (synchronously) */
} else if (!replyOID) {
/* Make sure there is a return OID */
err = LDAP_NOT_SUPPORTED;
} else if (strcmp(replyOID, NMASLDAP_GET_PASSWORD_RESPONSE)) {
/* Is this what we were expecting to get back. */
err = LDAP_NOT_SUPPORTED;
} else if (!replyBV) {
/* Do we have a good returned berval? */
/* No; returned berval means we experienced a rather drastic error. */
/* Return operations error. */
err = LDAP_OPERATIONS_ERROR;
} else {
err = berDecodeLoginData(replyBV, &serverVersion, &pwdBufLen, pwdBuf);
if (serverVersion != NMAS_LDAP_EXT_VERSION) {
err = LDAP_OPERATIONS_ERROR;
} else if (!err && pwdBufLen != 0) {
if (*pwdSize >= pwdBufLen+1 && pwd != NULL) {
memcpy(pwd, pwdBuf, pwdBufLen);
pwd[pwdBufLen] = 0; /* add null termination */
}
*pwdSize = pwdBufLen; /* does not include null termination */
}
}
if (replyBV) {
ber_bvfree(replyBV);
}
/* Free the return OID string if one was returned. */
if (replyOID) {
ldap_memfree(replyOID);
}
/* Free memory allocated while building the request ber and berval. */
if (requestBV) {
ber_bvfree(requestBV);
}
if (pwdBuf != NULL) {
memset(pwdBuf, 0, bufferLen);
free(pwdBuf);
}
/* Return the appropriate error/success code. */
return err;
}
/**********************************************************************
Get the user's password from NDS.
*********************************************************************/
int nds_get_password(
LDAP *ld,
char *object_dn,
size_t *pwd_len,
char *pwd )
{
int rc = -1;
rc = nmasldap_get_password(ld, object_dn, pwd_len, (unsigned char *)pwd);
if (rc == LDAP_SUCCESS) {
#ifdef DEBUG_PASSWORD
DEBUG(100,("nmasldap_get_password returned %s for %s\n", pwd, object_dn));
#endif
DEBUG(5, ("NDS Universal Password retrieved for %s\n", object_dn));
} else {
DEBUG(3, ("NDS Universal Password NOT retrieved for %s\n", object_dn));
}
if (rc != LDAP_SUCCESS) {
rc = nmasldap_get_simple_pwd(ld, object_dn, *pwd_len, pwd);
if (rc == LDAP_SUCCESS) {
#ifdef DEBUG_PASSWORD
DEBUG(100,("nmasldap_get_simple_pwd returned %s for %s\n", pwd, object_dn));
#endif
DEBUG(5, ("NDS Simple Password retrieved for %s\n", object_dn));
} else {
/* We couldn't get the password */
DEBUG(3, ("NDS Simple Password NOT retrieved for %s\n", object_dn));
return LDAP_INVALID_CREDENTIALS;
}
}
/* We got the password */
return LDAP_SUCCESS;
}
| 30.834297
| 146
| 0.569706
|
spaceify
|
812d52b862ad3945413443e7fbfb225bb6fd80b5
| 4,309
|
cpp
|
C++
|
edhclient_socket.cpp
|
eDrillingSolutions/libedhclient-qt
|
be0298cb95017783bff842fc2e3a6c34668a4cda
|
[
"MIT"
] | 1
|
2020-06-29T20:49:05.000Z
|
2020-06-29T20:49:05.000Z
|
edhclient_socket.cpp
|
eDrillingSolutions/libedhclient-qt
|
be0298cb95017783bff842fc2e3a6c34668a4cda
|
[
"MIT"
] | null | null | null |
edhclient_socket.cpp
|
eDrillingSolutions/libedhclient-qt
|
be0298cb95017783bff842fc2e3a6c34668a4cda
|
[
"MIT"
] | 1
|
2018-11-07T07:38:53.000Z
|
2018-11-07T07:38:53.000Z
|
#include "edhclient_socket.h"
#include "edhclient_private.h"
#include <iostream>
#include <QFile>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QSslSocket>
#include <QtNetwork/QSslConfiguration>
using namespace eDrillingHub;
static const QString message_end_marker = QString("\r\n");
SocketClient::SocketClient(bool secure) {
if (secure) {
auto socket = new QSslSocket();
_socket.reset(socket);
_ssl_socket = true;
} else {
_socket.reset(new QTcpSocket());
_ssl_socket = false;
}
connect(_socket.get(), &QTcpSocket::readyRead, this, &SocketClient::_onSocketReadyRead);
connect(_socket.get(), &QTcpSocket::stateChanged, this, [this](QAbstractSocket::SocketState state) {
switch (state) {
case QAbstractSocket::ConnectedState:
_socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
if (_ssl_socket) {
auto sslsocket = dynamic_cast<QSslSocket*>(_socket.get());
QObject::connect(sslsocket, &QSslSocket::encrypted, [=] {
emit connected();
});
sslsocket->startClientEncryption();
} else {
emit connected();
}
break;
case QAbstractSocket::UnconnectedState:
emit disconnected();
break;
default:
break;
}
});
}
SocketClient* SocketClient::create(bool secure) {
std::unique_ptr<SocketClient> client;
client.reset(new SocketClient(secure));
if (secure) {
QFile ca(":/edhclient/CA-eDrilling.crt");
if (! ca.open(QIODevice::ReadOnly)) {
std::cerr << "eDrilling CA Certificate not found, compilation error" << std::endl;
return nullptr;
}
auto sslsocket = dynamic_cast<QSslSocket*>(client.get()->_socket.get());
sslsocket->addCaCertificates(QSslConfiguration::systemCaCertificates());
sslsocket->addCaCertificate(QSslCertificate(&ca, QSsl::Pem));
sslsocket->setProtocol(QSsl::TlsV1_2OrLater);
}
return client.release();
}
void SocketClient::open() {
if (_networkProxy) {
_socket->setProxy(*_networkProxy);
}
_socket->connectToHost(_priv->host, _priv->port, QIODevice::ReadWrite);
}
void SocketClient::close() {
_socket->close();
}
void SocketClient::setIgnoreSslErrors(bool enable) {
auto ssl_socket = dynamic_cast<QSslSocket*>(_socket.get());
if (ssl_socket == nullptr) {
return;
}
if (enable) {
QObject::connect(ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::sslErrors), &SocketClient::_onSslError);
QObject::connect(ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::sslErrors),
ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::ignoreSslErrors));
} else {
QObject::disconnect(ssl_socket, static_cast<void (QSslSocket::*)(const QList<QSslError> &errors)>(&QSslSocket::sslErrors), nullptr, nullptr);
}
}
QString SocketClient::errorString() {
return _socket->errorString();
}
void SocketClient::write(const QString &message) {
_socket->write(message.toUtf8());
_socket->write(message_end_marker.toUtf8());
}
void SocketClient::writeBinary(const QByteArray &data) {
_socket->write(data);
}
void SocketClient::_onSocketReadyRead() {
QByteArray bytes = _socket->readAll();
_readBuffer.append(bytes);
_readBufferIdx = 0;
_readBufferPos = _readBuffer.indexOf(message_end_marker);
if (_readBufferPos >= 0) {
while (_readBufferPos >= 0) {
QString reply = QString::fromUtf8(_readBuffer.mid(_readBufferIdx, _readBufferPos - _readBufferIdx));
_readBufferIdx = _readBufferPos + message_end_marker.length();
_readBufferPos = _readBuffer.indexOf(message_end_marker, _readBufferIdx);
handle(reply);
}
_readBuffer.remove(0, _readBufferIdx);
}
}
void SocketClient::_onSslError(const QList<QSslError> &errors) {
for (const auto& error : errors) {
std::cerr << "SocketClient: SSL Error: " << error.errorString().toStdString() << std::endl;
}
}
| 31.918519
| 156
| 0.644929
|
eDrillingSolutions
|
812f95259899a991724823b48ef54dc79cb85956
| 3,634
|
hpp
|
C++
|
src/modules/ROOTObjectWriter/ROOTObjectWriterModule.hpp
|
nashadroid/allpix-squared
|
ae3c9b35241b7d301866e1a602443a436bdfb35f
|
[
"MIT"
] | null | null | null |
src/modules/ROOTObjectWriter/ROOTObjectWriterModule.hpp
|
nashadroid/allpix-squared
|
ae3c9b35241b7d301866e1a602443a436bdfb35f
|
[
"MIT"
] | null | null | null |
src/modules/ROOTObjectWriter/ROOTObjectWriterModule.hpp
|
nashadroid/allpix-squared
|
ae3c9b35241b7d301866e1a602443a436bdfb35f
|
[
"MIT"
] | null | null | null |
/**
* @file
* @brief Definition of ROOT data file writer module
* @copyright Copyright (c) 2017-2019 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include <map>
#include <string>
#include <TFile.h>
#include <TTree.h>
#include "core/config/Configuration.hpp"
#include "core/geometry/GeometryManager.hpp"
#include "core/messenger/Messenger.hpp"
#include "core/module/Module.hpp"
namespace allpix {
/**
* @ingroup Modules
* @brief Module to write object data to ROOT trees in file for persistent storage
*
* Listens to all objects dispatched in the framework. Creates a tree as soon as a new type of object is encountered and
* saves the data in those objects to tree for every event. The tree name is the class name of the object. A separate
* branch is created for every combination of detector name and message name that outputs this object.
*/
class ROOTObjectWriterModule : public Module {
public:
/**
* @brief Constructor for this unique module
* @param config Configuration object for this module as retrieved from the steering file
* @param messenger Pointer to the messenger object to allow binding to messages on the bus
* @param geo_mgr Pointer to the geometry manager, containing the detectors
*/
ROOTObjectWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr);
/**
* @brief Destructor deletes the internal objects used to build the ROOT Tree
*/
~ROOTObjectWriterModule() override;
/**
* @brief Receive a single message containing objects of arbitrary type
* @param message Message dispatched in the framework
* @param name Name of the message
*/
void receive(std::shared_ptr<BaseMessage> message, std::string name);
/**
* @brief Opens the file to write the objects to
*/
void init() override;
/**
* @brief Writes the objects fetched to their specific tree, constructing trees on the fly for new objects.
*/
void run(unsigned int) override;
/**
* @brief Add the main configuration and the detector setup to the data file and write it, also write statistics
* information.
*/
void finalize() override;
private:
GeometryManager* geo_mgr_;
// Object names to include or exclude from writing
std::set<std::string> include_;
std::set<std::string> exclude_;
// Output data file to write
std::unique_ptr<TFile> output_file_;
std::string output_file_name_{};
// Last event processed
unsigned int last_event_{0};
// List of trees that are stored in data file
std::map<std::string, std::unique_ptr<TTree>> trees_;
// List of messages to keep so they can be stored in the tree
std::vector<std::shared_ptr<BaseMessage>> keep_messages_;
// List of objects of a particular type, bound to a specific detector and having a particular name
std::map<std::tuple<std::type_index, std::string, std::string>, std::vector<Object*>*> write_list_;
// Statistical information about number of objects
unsigned long write_cnt_{};
};
} // namespace allpix
| 39.075269
| 124
| 0.670061
|
nashadroid
|
8130e497664b1865aa30a860e12e720e66e86990
| 3,034
|
cc
|
C++
|
src/CBLEncryptable_CAPI.cc
|
blaugold/couchbase-lite-C
|
08d30377087bda06ed806bda4a5ff28182e0f472
|
[
"Apache-2.0"
] | 66
|
2019-05-02T12:03:19.000Z
|
2021-06-28T21:16:32.000Z
|
src/CBLEncryptable_CAPI.cc
|
blaugold/couchbase-lite-C
|
08d30377087bda06ed806bda4a5ff28182e0f472
|
[
"Apache-2.0"
] | 97
|
2019-05-28T15:46:00.000Z
|
2021-07-03T18:47:52.000Z
|
src/CBLEncryptable_CAPI.cc
|
blaugold/couchbase-lite-C
|
08d30377087bda06ed806bda4a5ff28182e0f472
|
[
"Apache-2.0"
] | 28
|
2019-05-07T21:57:36.000Z
|
2021-06-24T11:09:38.000Z
|
//
// CBLEncryptable_CAPI.cc
//
// Copyright © 2021 Couchbase. 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.
//
#include "CBLEncryptable_Internal.hh"
#ifdef COUCHBASE_ENTERPRISE
using namespace fleece;
CBL_PUBLIC const FLSlice kCBLEncryptableType = C4Document::kObjectType_Encryptable;
CBL_PUBLIC const FLSlice kCBLEncryptableValueProperty = C4Document::kValueToEncryptProperty;
CBLEncryptable* CBLEncryptable_CreateWithNull() noexcept {
return CBLEncryptable::createWithNull().detach();
}
CBLEncryptable* CBLEncryptable_CreateWithBool(bool value) noexcept {
return CBLEncryptable::createWithBool(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithInt(int64_t value) noexcept {
return CBLEncryptable::createWithInt(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithUInt(uint64_t value) noexcept {
return CBLEncryptable::createWithUInt(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithFloat(float value) noexcept {
return CBLEncryptable::createWithFloat(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithDouble(double value) noexcept {
return CBLEncryptable::createWithDouble(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithString(FLString value) noexcept {
return CBLEncryptable::createWithString(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithValue(FLValue value) noexcept {
return CBLEncryptable::createWithValue(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithArray(FLArray value) noexcept {
return CBLEncryptable::createWithArray(value).detach();
}
CBLEncryptable* CBLEncryptable_CreateWithDict(FLDict value) noexcept {
return CBLEncryptable::createWithDict(value).detach();
}
FLValue CBLEncryptable_Value(const CBLEncryptable* encryptable) noexcept {
return encryptable->value();
}
FLDict CBLEncryptable_Properties(const CBLEncryptable* encryptable) noexcept {
return encryptable->properties();
}
bool FLDict_IsEncryptableValue(FLDict _cbl_nullable dict) noexcept {
return CBLEncryptable::isEncryptableValue(dict);
}
const CBLEncryptable* FLDict_GetEncryptableValue(FLDict _cbl_nullable dict) noexcept {
return CBLEncryptable::getEncryptableValue(dict);
}
void FLSlot_SetEncryptableValue(FLSlot slot, const CBLEncryptable* encryptable) noexcept {
Dict props = encryptable->properties();
MutableDict mProps = props.asMutable();
if (!mProps)
mProps = props.mutableCopy();
FLSlot_SetValue(slot, mProps);
}
#endif
| 32.623656
| 94
| 0.785432
|
blaugold
|
813160615e18a2588084a932ce1f751fb6d508ff
| 194
|
cpp
|
C++
|
src/tabdraw/TabDraw.cpp
|
gongjianbo/EasyQPainter
|
a5b90f6c8b3427024b591a3e893162b57a928011
|
[
"MIT"
] | 106
|
2020-05-16T03:10:16.000Z
|
2022-03-26T12:15:37.000Z
|
src/tabdraw/TabDraw.cpp
|
gongjianbo/EasyQPainter
|
a5b90f6c8b3427024b591a3e893162b57a928011
|
[
"MIT"
] | null | null | null |
src/tabdraw/TabDraw.cpp
|
gongjianbo/EasyQPainter
|
a5b90f6c8b3427024b591a3e893162b57a928011
|
[
"MIT"
] | 30
|
2020-06-05T08:54:34.000Z
|
2022-03-26T12:15:27.000Z
|
#include "TabDraw.h"
#include "ui_TabDraw.h"
TabDraw::TabDraw(QWidget *parent) :
QWidget(parent),
ui(new Ui::TabDraw)
{
ui->setupUi(this);
}
TabDraw::~TabDraw()
{
delete ui;
}
| 12.933333
| 35
| 0.628866
|
gongjianbo
|
8133903abdf1bf9812ce119ff4c21f2d029daa51
| 827
|
cpp
|
C++
|
demo_1/demo_guess.cpp
|
yangy30685/cpp
|
dd0bb258ea5a6d02a8bc9947d2498e7b36b7e2c4
|
[
"MIT"
] | null | null | null |
demo_1/demo_guess.cpp
|
yangy30685/cpp
|
dd0bb258ea5a6d02a8bc9947d2498e7b36b7e2c4
|
[
"MIT"
] | null | null | null |
demo_1/demo_guess.cpp
|
yangy30685/cpp
|
dd0bb258ea5a6d02a8bc9947d2498e7b36b7e2c4
|
[
"MIT"
] | null | null | null |
#include <ctime>
#include <iostream>
#include <string>
int main(int argc, char const *argv[])
{
srand(time(NULL));
int secret_number = std::rand() % 11;
int guess = 0;
std::string str_1;
std::string quit = "q";
while(true)
{
std::cout << "guess a number :\n";
std::cin >> guess;
if(guess > secret_number) std::cout << "too big \n";
if(guess < secret_number) std::cout << "too small\n";
if(guess == secret_number)
{
std::cout << "you guessed it\n";
break;
}
// dont mix use getline() and cin
// if so, use cin.ingnore();
std::cout << "to quit press q else to continue\n";
std::cin >> str_1;
if(str_1 == quit) break;
}
system("pause");
return 0;
}
| 22.351351
| 61
| 0.503023
|
yangy30685
|
8133b05db27f2ae07ba369c3a031f7a17afcd661
| 1,302
|
cpp
|
C++
|
C++/maximum-non-negative-product-in-a-matrix.cpp
|
Akhil-Kashyap/LeetCode-Solutions
|
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
|
[
"MIT"
] | 3,269
|
2018-10-12T01:29:40.000Z
|
2022-03-31T17:58:41.000Z
|
C++/maximum-non-negative-product-in-a-matrix.cpp
|
Akhil-Kashyap/LeetCode-Solutions
|
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
|
[
"MIT"
] | 53
|
2018-12-16T22:54:20.000Z
|
2022-02-25T08:31:20.000Z
|
C++/maximum-non-negative-product-in-a-matrix.cpp
|
Akhil-Kashyap/LeetCode-Solutions
|
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
|
[
"MIT"
] | 1,236
|
2018-10-12T02:51:40.000Z
|
2022-03-30T13:30:37.000Z
|
// Time: O(m * n)
// Space: O(n)
// dp with rolling window
class Solution {
public:
int maxProductPath(vector<vector<int>>& grid) {
static const int MOD = 1e9 + 7;
vector<vector<int64_t>> max_dp(2, vector<int64_t>(size(grid[0])));
vector<vector<int64_t>> min_dp(2, vector<int64_t>(size(grid[0])));
for (int i = 0; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]); ++j) {
if (i == 0 && j == 0) {
max_dp[0][0] = min_dp[0][0] = grid[0][0];
continue;
}
auto curr_max = max(i > 0 ? max_dp[(i - 1) % 2][j] : max_dp[i % 2][j - 1],
j > 0 ? max_dp[i % 2][j - 1] : max_dp[(i - 1) % 2][j]);
auto curr_min = min(i > 0 ? min_dp[(i - 1) % 2][j] : min_dp[i % 2][j - 1],
j > 0 ? min_dp[i % 2][j - 1] : min_dp[(i - 1) % 2][j]);
if (grid[i][j] < 0) {
swap(curr_max, curr_min);
}
max_dp[i % 2][j] = curr_max * grid[i][j];
min_dp[i % 2][j] = curr_min * grid[i][j];
}
}
return max_dp[(size(grid) - 1) % 2].back() >= 0 ? max_dp[(size(grid) - 1) % 2].back() % MOD : -1;
}
};
| 42
| 105
| 0.400922
|
Akhil-Kashyap
|
8133f4f720539c8c570808ce4cf2f388d1ff00c5
| 1,002
|
cpp
|
C++
|
vm/builtin/thunk.cpp
|
sshao/rubinius
|
368df60245471f45f1294b0cd18f769377437246
|
[
"BSD-3-Clause"
] | 1
|
2015-11-08T12:37:15.000Z
|
2015-11-08T12:37:15.000Z
|
vm/builtin/thunk.cpp
|
sshao/rubinius
|
368df60245471f45f1294b0cd18f769377437246
|
[
"BSD-3-Clause"
] | null | null | null |
vm/builtin/thunk.cpp
|
sshao/rubinius
|
368df60245471f45f1294b0cd18f769377437246
|
[
"BSD-3-Clause"
] | null | null | null |
#include "arguments.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/location.hpp"
#include "builtin/system.hpp"
#include "builtin/thunk.hpp"
#include "object_utils.hpp"
namespace rubinius {
Thunk* Thunk::create(STATE, Object* self, Object* value) {
Thunk* pe = state->new_object<Thunk>(as<Class>(self));
pe->value(state, value);
pe->inliners_ = 0;
pe->prim_index_ = -1;
pe->custom_call_site_ = false;
pe->execute = thunk_executor;
return pe;
}
Object* Thunk::thunk_executor(STATE, CallFrame* call_frame, Executable* exec, Module* mod,
Arguments& args)
{
Thunk* thunk = as<Thunk>(exec);
if(args.total() != 0) {
Exception* exc =
Exception::make_argument_error(state, 0, args.total(), args.name());
exc->locations(state, Location::from_call_stack(state, call_frame));
state->raise_exception(exc);
return NULL;
}
return thunk->value();
}
}
| 27.833333
| 92
| 0.637725
|
sshao
|
8138817dd90585dec504c3e163a78a2996fb86ee
| 390
|
cpp
|
C++
|
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_40.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 965
|
2017-06-25T23:57:11.000Z
|
2022-03-31T14:17:32.000Z
|
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_40.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 3,272
|
2017-06-24T00:26:34.000Z
|
2022-03-31T22:14:07.000Z
|
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_40.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 951
|
2017-06-25T12:36:14.000Z
|
2022-03-26T22:49:06.000Z
|
// typedef CStringT<TCHAR, StrTraitATL<TCHAR, ChTraitsCRT<TCHAR>>> CAtlString;
CAtlString str;
str = _T("******Soccer is best!?!?!?!?!");
_tprintf_s(_T("Before: \"%s\"\n"), (LPCTSTR)str);
_tprintf_s(_T("After : \"%s\"\n"), (LPCTSTR)str.Trim(_T("?!*")));
// Output:
// --------------------------
// Before: ******Soccer is best!?!?!?!?!
// After: Soccer is best
| 32.5
| 81
| 0.507692
|
bobbrow
|
813b9063a8fce8e68346125554324bc22fc5e1e5
| 1,365
|
cpp
|
C++
|
yhtstfo/assets/voice_synthesizer/voice_synthesizer.plugin/source/module.cpp
|
skarab/coffee-samples
|
3f4e8e65c8fa24f2a23969d63e731fc2f0ddf7e2
|
[
"MIT"
] | null | null | null |
yhtstfo/assets/voice_synthesizer/voice_synthesizer.plugin/source/module.cpp
|
skarab/coffee-samples
|
3f4e8e65c8fa24f2a23969d63e731fc2f0ddf7e2
|
[
"MIT"
] | null | null | null |
yhtstfo/assets/voice_synthesizer/voice_synthesizer.plugin/source/module.cpp
|
skarab/coffee-samples
|
3f4e8e65c8fa24f2a23969d63e731fc2f0ddf7e2
|
[
"MIT"
] | null | null | null |
#include "module.h"
//-META-------------------------------------------------------------------------------------------//
COFFEE_BeginType(voice_synthesizer::Module);
COFFEE_Ancestor(shell::Module);
COFFEE_EndType();
namespace voice_synthesizer
{
COFFEE_ImplementModuleSingleton(Module);
//-CONSTRUCTORS-------------------------------------------------------------------------------//
Module::Module() :
shell::Module(shell::MODULE_ATTRIBUTE_Automatic)
{
COFFEE_CreateModuleSingleton(Module);
}
//--------------------------------------------------------------------------------------------//
Module::~Module()
{
COFFEE_DestroyModuleSingleton(Module);
}
//-OPERATIONS---------------------------------------------------------------------------------//
void Module::OnInitialize()
{
Register<Synthesizer>();
}
//--------------------------------------------------------------------------------------------//
void Module::OnFinalize()
{
Unregister<Synthesizer>();
}
//--------------------------------------------------------------------------------------------//
void Module::OnUpdate(const basic::Time& time_step)
{
if (Synthesizer::Get().IsAvailable())
Synthesizer::Get().OnMainThreadUpdate(time_step);
}
}
| 26.764706
| 100
| 0.372161
|
skarab
|
813bbbc08ff18b7cf8f7c1a66239d0f9b2373b6c
| 1,825
|
hpp
|
C++
|
libs/vm-modules/include/vm_modules/crypto/sha256.hpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 96
|
2018-08-23T16:49:05.000Z
|
2021-11-25T00:47:16.000Z
|
libs/vm-modules/include/vm_modules/crypto/sha256.hpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 1,011
|
2018-08-17T12:25:21.000Z
|
2021-11-18T09:30:19.000Z
|
libs/vm-modules/include/vm_modules/crypto/sha256.hpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 65
|
2018-08-20T20:05:40.000Z
|
2022-02-26T23:54:35.000Z
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI 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.
//
//------------------------------------------------------------------------------
#include "crypto/sha256.hpp"
#include "vm/object.hpp"
#include <cstdint>
namespace fetch {
namespace vm {
class Module;
}
namespace vm_modules {
class ByteArrayWrapper;
namespace math {
class UInt256Wrapper;
}
class SHA256Wrapper : public fetch::vm::Object
{
public:
using ElementType = uint8_t;
SHA256Wrapper() = delete;
~SHA256Wrapper() override = default;
static void Bind(fetch::vm::Module &module);
void UpdateUInt256(fetch::vm::Ptr<math::UInt256Wrapper> const &uint);
void UpdateString(fetch::vm::Ptr<fetch::vm::String> const &str);
void UpdateBuffer(fetch::vm::Ptr<ByteArrayWrapper> const &buffer);
void Reset();
fetch::vm::Ptr<math::UInt256Wrapper> Final();
fetch::vm::Ptr<ByteArrayWrapper> FinalAsByteArray();
SHA256Wrapper(fetch::vm::VM *vm, fetch::vm::TypeId type_id);
static fetch::vm::Ptr<SHA256Wrapper> Constructor(fetch::vm::VM *vm, fetch::vm::TypeId type_id);
private:
fetch::crypto::SHA256 hasher_;
};
} // namespace vm_modules
} // namespace fetch
| 26.449275
| 97
| 0.647671
|
chr15murray
|
81400d597fa5d493bb5bb17bf301736fa468e177
| 2,272
|
cpp
|
C++
|
QCIFSServer/QCIFSTest/cBasicFile.cpp
|
rodrigomr/VFS
|
6b68b00df8cb668106c2d0841cbcd46138298717
|
[
"Apache-2.0"
] | 38
|
2018-09-24T09:37:41.000Z
|
2022-02-21T04:16:43.000Z
|
QCIFSServer/QCIFSTest/cBasicFile.cpp
|
rodrigomr/VFS
|
6b68b00df8cb668106c2d0841cbcd46138298717
|
[
"Apache-2.0"
] | 1
|
2018-10-02T17:57:44.000Z
|
2018-10-07T06:55:44.000Z
|
QCIFSServer/QCIFSTest/cBasicFile.cpp
|
rodrigomr/VFS
|
6b68b00df8cb668106c2d0841cbcd46138298717
|
[
"Apache-2.0"
] | 6
|
2018-10-02T17:12:38.000Z
|
2021-01-27T10:01:30.000Z
|
// Copyright 2018 Grass Valley, A Belden Brand
// 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 "stdafx.h"
#include "cBasicFile.h"
using namespace vfs;
cBasicFile::cBasicFile(const String& filepath) : mFilepath(filepath), mSize(0)
{
iFile::Ptr file = iFileManager::singleton().openFile(mFilepath, fFileAccess_Read);
mSize = file->getSize();
QTRACE((L"cBasicFile::cBasicFile %s. Size %08I64x", mFilepath.c_str(), mSize));
}
cBasicFile::~cBasicFile()
{
}
WIN32_FILE_ATTRIBUTE_DATA cBasicFile::getFileAttributes()
{
WIN32_FILE_ATTRIBUTE_DATA FileAttr = { 0 };
GetFileAttributesEx(
mFilepath.c_str(), // File or directory name
GetFileExInfoStandard, // Attribute
&FileAttr); // Attribute information
return FileAttr;
}
DWORD cBasicFile::readBytes(tTransmitList &krTPM, DWORD &nBytes, const LARGE_INTEGER &nOffset, const int sessionID, ULONGLONG fid)
{
DWORD ret = ERROR_SUCCESS;
//QTRACE((L"request for file %s. Offset %08I64x, length %i", mFilepath.c_str(), nOffset.QuadPart, nBytes));
if( nOffset.QuadPart < Int64(getSize(fid)) )
{
iFile::Ptr michaelsFile = iFileManager::singleton().openFile(mFilepath, fFileAccess_Read);
if(michaelsFile.isValid())
{
cMemoryView::Ptr buf = new cMemoryView(michaelsFile->read(UInt64(nOffset.QuadPart), nBytes));
SMART_TPE smartTpe;
smartTpe.pMem = buf;
smartTpe.tpe.dwElFlags = TP_ELEMENT_MEMORY;
smartTpe.tpe.pBuffer = (PVOID)buf->getConstBytes();
smartTpe.tpe.cLength = buf->getSize();
krTPM.push_back(smartTpe);
//QTRACE((L"sending packet size = %i, offset = %i", buf->getSize(), int(nOffset.QuadPart)));
}
}
else
ret = STATUS_END_OF_FILE;
return ret;
}
| 33.910448
| 130
| 0.699384
|
rodrigomr
|
8142048cb167114964603c3c3b9dee2022825852
| 4,818
|
hpp
|
C++
|
Include/LIEF/PE/ResourcesManager.hpp
|
RaniaJarraya/fraudulent_behavior_detection
|
d1506603fd3468a6c106c73d4880623c5a9b4869
|
[
"BSD-3-Clause"
] | 54
|
2020-01-29T18:44:56.000Z
|
2022-03-14T11:24:59.000Z
|
include/LIEF/PE/ResourcesManager.hpp
|
prarthanats/LIEF
|
b26abae9a9b0dc0e82dd803b7b54a2a9dfe1034a
|
[
"Apache-2.0"
] | 13
|
2021-03-19T09:25:18.000Z
|
2022-02-10T12:15:24.000Z
|
include/LIEF/PE/ResourcesManager.hpp
|
prarthanats/LIEF
|
b26abae9a9b0dc0e82dd803b7b54a2a9dfe1034a
|
[
"Apache-2.0"
] | 8
|
2019-05-19T11:24:28.000Z
|
2022-02-16T20:19:30.000Z
|
/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 LIEF_PE_RESOURCES_MANAGER_H_
#define LIEF_PE_RESOURCES_MANAGER_H_
#include <iostream>
#include <sstream>
#include <set>
#include "LIEF/visibility.h"
#include "LIEF/Object.hpp"
#include "LIEF/BinaryStream/VectorStream.hpp"
#include "LIEF/PE/type_traits.hpp"
#include "LIEF/PE/ResourceDirectory.hpp"
#include "LIEF/PE/resources/ResourceVersion.hpp"
#include "LIEF/PE/resources/ResourceIcon.hpp"
#include "LIEF/PE/resources/ResourceDialog.hpp"
namespace LIEF {
namespace PE {
//! @brief The Resource Manager provides an enhanced API to
//! manipulate the resource tree.
class LIEF_API ResourcesManager : public Object {
public:
static RESOURCE_SUBLANGS sub_lang(RESOURCE_LANGS lang, size_t index);
static RESOURCE_LANGS lang_from_id(size_t id);
static RESOURCE_SUBLANGS sublang_from_id(size_t id);
public:
ResourcesManager(void) = delete;
ResourcesManager(ResourceNode *rsrc);
ResourcesManager(const ResourcesManager&);
ResourcesManager& operator=(const ResourcesManager&);
virtual ~ResourcesManager(void);
// Enhancemed API to explore resource tree
// =======================================
//! @brief Return @link ResourceNode node @endlink with the given LIEF::PE::RESOURCE_TYPES
ResourceNode& get_node_type(RESOURCE_TYPES type);
const ResourceNode& get_node_type(RESOURCE_TYPES type) const;
//! @brief Return list of LIEF::PE::RESOURCE_TYPES present in the resources
std::set<RESOURCE_TYPES> get_types_available(void) const;
//! @brief Return list of LIEF::PE::RESOURCE_LANGS present in the resources
std::set<RESOURCE_LANGS> get_langs_available(void) const;
//! @brief Return list of LIEF::PE::RESOURCE_SUBLANGS present in the resources
std::set<RESOURCE_SUBLANGS> get_sublangs_available(void) const;
//! @brief ``true`` if the resource has the given LIEF::PE::RESOURCE_TYPES
bool has_type(RESOURCE_TYPES type) const;
// Manifest
// ========
//! @brief ``true`` if resources contain Manifest element
bool has_manifest(void) const;
//! @brief Return the manifest as a std::string
std::string manifest(void) const;
//! @brief Update the manifest with the given string
void manifest(const std::string& manifest);
// Version
// =======
//! @brief ``true`` if resources contain LIEF::PE::ResourceVersion
bool has_version(void) const;
//! @brief Return ResourceVersion if any
ResourceVersion version(void) const;
// Icons
// =====
//! @brief ``true`` if resources contain LIEF::PE::ResourceIcon
bool has_icons(void) const;
//! @brief Return the list of the icons present in the resource
std::vector<ResourceIcon> icons(void) const;
//! @brief Add an icon to the resources
void add_icon(const ResourceIcon& icon);
//void remove_icon(const ResourceIcon& icon)
void change_icon(const ResourceIcon& original, const ResourceIcon& newone);
// Dialogs
// =======
//! @brief ``true`` if resources contain @link LIEF::PE::ResourceDialog dialogs @endlink
bool has_dialogs(void) const;
//! @brief Return the list of the dialogs present in the resource
std::vector<ResourceDialog> dialogs(void) const;
// Print
// =====
//! @brief Print the resource tree to the given depth
std::string print(uint32_t depth = 0) const;
virtual void accept(Visitor& visitor) const override;
bool operator==(const ResourcesManager& rhs) const;
bool operator!=(const ResourcesManager& rhs) const;
LIEF_API friend std::ostream& operator<<(std::ostream& os, const ResourcesManager& m);
private:
void print_tree(
const ResourceNode& node,
std::ostringstream& stream,
uint32_t current_depth,
uint32_t max_depth) const;
//! @brief Build the ResourceStringFileInfo from the RT_VERSION node
ResourceStringFileInfo get_string_file_info(const VectorStream& stream, uint16_t type, std::u16string key, size_t start, size_t struct_length) const;
//! @brief Build the ResourceVarFileInfo from the RT_VERSION node
ResourceVarFileInfo get_var_file_info(const VectorStream& stream, uint16_t type, std::u16string key, size_t start, size_t struct_length) const;
ResourceNode *resources_;
};
} // namespace PE
} // namespace LIEF
#endif
| 31.490196
| 151
| 0.733084
|
RaniaJarraya
|
8145c50ebebd02908dc2861ef9710819b05bdb05
| 658
|
cpp
|
C++
|
066_plusOne/main.cpp
|
IdLeoO/LC
|
445d8f1521d02c8481d590e5af914b6599bf8d7d
|
[
"MIT"
] | null | null | null |
066_plusOne/main.cpp
|
IdLeoO/LC
|
445d8f1521d02c8481d590e5af914b6599bf8d7d
|
[
"MIT"
] | null | null | null |
066_plusOne/main.cpp
|
IdLeoO/LC
|
445d8f1521d02c8481d590e5af914b6599bf8d7d
|
[
"MIT"
] | null | null | null |
#include "main.hpp"
#include <iostream>
using namespace std;
vector<int> Solution::plusOne(vector<int> & digits){
int idx = digits.size() - 1;
while (idx >= 0){
int carry = (digits[idx] + 1) > 9 ? 1: 0;
digits[idx] = (digits[idx] + 1 > 9) ? digits[idx] - 9 : digits[idx] + 1;
if (idx == 0 && carry == 1){
digits.insert(digits.begin(), 1);
break;
}
if (carry == 1) idx --;
else break;
}
return digits;
}
int main(int argc, char* argv[]){
vector<int> digits = {1, 2, 9};
Solution sol;
for (auto &x : sol.plusOne(digits)){
cout << x << endl;
}
}
| 24.37037
| 80
| 0.5
|
IdLeoO
|
81464a96fc88ea8aeaaf2db3ce339d43d3c39151
| 9,630
|
cpp
|
C++
|
gdal/frmts/jpeg2000/jpeg2000_vsil_io.cpp
|
riseofthetigers/GDAL
|
918b6939f6be25ac9d36edca3f71c8bf5dd5975e
|
[
"MIT"
] | null | null | null |
gdal/frmts/jpeg2000/jpeg2000_vsil_io.cpp
|
riseofthetigers/GDAL
|
918b6939f6be25ac9d36edca3f71c8bf5dd5975e
|
[
"MIT"
] | null | null | null |
gdal/frmts/jpeg2000/jpeg2000_vsil_io.cpp
|
riseofthetigers/GDAL
|
918b6939f6be25ac9d36edca3f71c8bf5dd5975e
|
[
"MIT"
] | null | null | null |
/******************************************************************************
* $Id$
*
* Project: JPEG-2000
* Purpose: Return a stream for a VSIL file
* Author: Even Rouault, even dot rouault at mines dash paris dot org
*
******************************************************************************/
/* Following code is mostly derived from jas_stream.c, which is licenced */
/* under the below terms */
/*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
* Copyright (c) 2009-2010, Even Rouault <even dot rouault at mines-paris dot org>
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") 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, 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:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "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 OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
#include "jpeg2000_vsil_io.h"
#include "cpl_vsi.h"
CPL_CVSID("$Id$");
/*
* File descriptor file object.
*/
typedef struct {
VSILFILE* fp;
} jas_stream_VSIFL_t;
/******************************************************************************\
* File stream object.
\******************************************************************************/
static int JPEG2000_VSIL_read(jas_stream_obj_t *obj, char *buf, int cnt)
{
jas_stream_VSIFL_t *fileobj = JAS_CAST(jas_stream_VSIFL_t *, obj);
return VSIFReadL(buf, 1, cnt, fileobj->fp);
}
static int JPEG2000_VSIL_write(jas_stream_obj_t *obj, char *buf, int cnt)
{
jas_stream_VSIFL_t *fileobj = JAS_CAST(jas_stream_VSIFL_t *, obj);
return VSIFWriteL(buf, 1, cnt, fileobj->fp);
}
static long JPEG2000_VSIL_seek(jas_stream_obj_t *obj, long offset, int origin)
{
jas_stream_VSIFL_t *fileobj = JAS_CAST(jas_stream_VSIFL_t *, obj);
if (offset < 0 && origin == SEEK_CUR)
{
origin = SEEK_SET;
offset += VSIFTellL(fileobj->fp);
}
else if (offset < 0 && origin == SEEK_END)
{
origin = SEEK_SET;
VSIFSeekL(fileobj->fp, 0, SEEK_END);
offset += VSIFTellL(fileobj->fp);
}
VSIFSeekL(fileobj->fp, offset, origin);
return VSIFTellL(fileobj->fp);
}
static int JPEG2000_VSIL_close(jas_stream_obj_t *obj)
{
jas_stream_VSIFL_t *fileobj = JAS_CAST(jas_stream_VSIFL_t *, obj);
VSIFCloseL(fileobj->fp);
fileobj->fp = NULL;
jas_free(fileobj);
return 0;
}
static jas_stream_ops_t JPEG2000_VSIL_stream_fileops = {
JPEG2000_VSIL_read,
JPEG2000_VSIL_write,
JPEG2000_VSIL_seek,
JPEG2000_VSIL_close
};
/******************************************************************************\
* Code for opening and closing streams.
\******************************************************************************/
static jas_stream_t *JPEG2000_VSIL_jas_stream_create()
{
jas_stream_t *stream;
if (!(stream = (jas_stream_t*) jas_malloc(sizeof(jas_stream_t)))) {
return 0;
}
stream->openmode_ = 0;
stream->bufmode_ = 0;
stream->flags_ = 0;
stream->bufbase_ = 0;
stream->bufstart_ = 0;
stream->bufsize_ = 0;
stream->ptr_ = 0;
stream->cnt_ = 0;
stream->ops_ = 0;
stream->obj_ = 0;
stream->rwcnt_ = 0;
stream->rwlimit_ = -1;
return stream;
}
static void JPEG2000_VSIL_jas_stream_destroy(jas_stream_t *stream)
{
/* If the memory for the buffer was allocated with malloc, free
this memory. */
if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) {
jas_free(stream->bufbase_);
stream->bufbase_ = 0;
}
jas_free(stream);
}
/******************************************************************************\
* Buffer initialization code.
\******************************************************************************/
static void JPEG2000_VSIL_jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
int bufsize)
{
/* If this function is being called, the buffer should not have been
initialized yet. */
assert(!stream->bufbase_);
if (bufmode != JAS_STREAM_UNBUF) {
/* The full- or line-buffered mode is being employed. */
if (!buf) {
/* The caller has not specified a buffer to employ, so allocate
one. */
if ((stream->bufbase_ = (unsigned char*)jas_malloc(JAS_STREAM_BUFSIZE +
JAS_STREAM_MAXPUTBACK))) {
stream->bufmode_ |= JAS_STREAM_FREEBUF;
stream->bufsize_ = JAS_STREAM_BUFSIZE;
} else {
/* The buffer allocation has failed. Resort to unbuffered
operation. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
} else {
/* The caller has specified a buffer to employ. */
/* The buffer must be large enough to accommodate maximum
putback. */
assert(bufsize > JAS_STREAM_MAXPUTBACK);
stream->bufbase_ = JAS_CAST(uchar *, buf);
stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
}
} else {
/* The unbuffered mode is being employed. */
/* A buffer should not have been supplied by the caller. */
assert(!buf);
/* Use a trivial one-character buffer. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
stream->ptr_ = stream->bufstart_;
stream->cnt_ = 0;
stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
}
static int JPEG2000_VSIL_jas_strtoopenmode(const char *s)
{
int openmode = 0;
while (*s != '\0') {
switch (*s) {
case 'r':
openmode |= JAS_STREAM_READ;
break;
case 'w':
openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE;
break;
case 'b':
openmode |= JAS_STREAM_BINARY;
break;
case 'a':
openmode |= JAS_STREAM_APPEND;
break;
case '+':
openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE;
break;
default:
break;
}
++s;
}
return openmode;
}
jas_stream_t *JPEG2000_VSIL_fopen(const char *filename, const char *mode)
{
jas_stream_t *stream;
jas_stream_VSIFL_t *obj;
/* Allocate a stream object. */
if (!(stream = JPEG2000_VSIL_jas_stream_create())) {
return 0;
}
/* Parse the mode string. */
stream->openmode_ = JPEG2000_VSIL_jas_strtoopenmode(mode);
/* Allocate space for the underlying file stream object. */
if (!(obj = (jas_stream_VSIFL_t*) jas_malloc(sizeof(jas_stream_VSIFL_t)))) {
JPEG2000_VSIL_jas_stream_destroy(stream);
return 0;
}
obj->fp = NULL;
stream->obj_ = (void *) obj;
/* Select the operations for a file stream object. */
stream->ops_ = &JPEG2000_VSIL_stream_fileops;
/* Open the underlying file. */
if ((obj->fp = VSIFOpenL(filename, mode)) == NULL) {
JPEG2000_VSIL_jas_stream_destroy(stream);
return 0;
}
/* By default, use full buffering for this type of stream. */
JPEG2000_VSIL_jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
return stream;
}
| 33.321799
| 91
| 0.650467
|
riseofthetigers
|
81496ed60ad2a6ff7a7ba876b89ef6eb26c70395
| 28,117
|
cpp
|
C++
|
src/agent/SpawnEnvSetupper/SpawnEnvSetupperMain.cpp
|
ROMB/passenger
|
773c544e1e60847538d43447b4e1f873e9e7eef2
|
[
"MIT"
] | null | null | null |
src/agent/SpawnEnvSetupper/SpawnEnvSetupperMain.cpp
|
ROMB/passenger
|
773c544e1e60847538d43447b4e1f873e9e7eef2
|
[
"MIT"
] | null | null | null |
src/agent/SpawnEnvSetupper/SpawnEnvSetupperMain.cpp
|
ROMB/passenger
|
773c544e1e60847538d43447b4e1f873e9e7eef2
|
[
"MIT"
] | null | null | null |
/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2012-2017 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* 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.
*/
/*
* For an introduction see SpawningKit's README.md, section "The SpawnEnvSetupper".
*/
#include <oxt/initialize.hpp>
#include <oxt/backtrace.hpp>
#include <boost/scoped_array.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <stdexcept>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <limits.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
#include <string.h>
#include <jsoncpp/json.h>
#include <adhoc_lve.h>
#include <LoggingKit/LoggingKit.h>
#include <LoggingKit/Context.h>
#include <ProcessManagement/Spawn.h>
#include <FileTools/FileManip.h>
#include <FileTools/PathManip.h>
#include <Utils.h>
#include <Utils/IOUtils.h>
#include <Utils/StrIntUtils.h>
#include <Core/SpawningKit/Exceptions.h>
using namespace std;
using namespace Passenger;
extern "C" {
extern char **environ;
}
namespace Passenger {
namespace SpawnEnvSetupper {
enum Mode {
BEFORE_MODE,
AFTER_MODE
};
struct Context {
string workDir;
Mode mode;
Json::Value args;
SpawningKit::JourneyStep step;
};
} // namespace SpawnEnvSetupper
} // namespace Passenger
using namespace Passenger::SpawnEnvSetupper;
static Json::Value
readArgsJson(const string &workDir) {
Json::Reader reader;
Json::Value result;
string contents = readAll(workDir + "/args.json");
if (reader.parse(contents, result)) {
return result;
} else {
P_CRITICAL("Cannot parse " << workDir << "/args.json: "
<< reader.getFormattedErrorMessages());
exit(1);
// Never reached
return Json::Value();
}
}
static void
initializeLogLevel(const Json::Value &args) {
if (args.isMember("log_level")) {
LoggingKit::setLevel(LoggingKit::Level(args["log_level"].asInt()));
}
}
static bool
tryWriteFile(const StaticString &path, const StaticString &value) {
try {
createFile(path.c_str(), value);
return true;
} catch (const FileSystemException &e) {
fprintf(stderr, "Warning: %s\n", e.what());
return false;
}
}
static void
recordJourneyStepBegin(const Context &context,
SpawningKit::JourneyStep step, SpawningKit::JourneyStepState state)
{
string stepString = journeyStepToStringLowerCase(step);
string stepDir = context.workDir + "/response/steps/" + stepString;
tryWriteFile(stepDir + "/state", SpawningKit::journeyStepStateToString(state));
tryWriteFile(stepDir + "/begin_time_monotonic", doubleToString(
SystemTime::getMonotonicUsecWithGranularity<SystemTime::GRAN_10MSEC>() / 1000000.0));
}
static void
recordJourneyStepEnd(const Context &context,
SpawningKit::JourneyStep step, SpawningKit::JourneyStepState state)
{
string stepString = journeyStepToStringLowerCase(step);
string stepDir = context.workDir + "/response/steps/" + stepString;
tryWriteFile(stepDir + "/state", SpawningKit::journeyStepStateToString(state));
if (!fileExists(stepDir + "/begin_time") && !fileExists(stepDir + "/begin_time_monotonic")) {
tryWriteFile(stepDir + "/begin_time_monotonic", doubleToString(
SystemTime::getMonotonicUsecWithGranularity<SystemTime::GRAN_10MSEC>() / 1000000.0));
}
tryWriteFile(stepDir + "/end_time_monotonic", doubleToString(
SystemTime::getMonotonicUsecWithGranularity<SystemTime::GRAN_10MSEC>() / 1000000.0));
}
static void
recordErrorCategory(const string &workDir, SpawningKit::ErrorCategory category) {
string path = workDir + "/response/error/category";
tryWriteFile(path, errorCategoryToString(category));
}
static void
recordAdvancedProblemDetails(const string &workDir, const string &message) {
string path = workDir + "/response/error/advanced_problem_details";
tryWriteFile(path, message);
}
static void
recordErrorSummary(const string &workDir, const string &message,
bool isAlsoAdvancedProblemDetails)
{
string path = workDir + "/response/error/summary";
tryWriteFile(path, message);
if (isAlsoAdvancedProblemDetails) {
recordAdvancedProblemDetails(workDir, message);
}
}
static void
recordAndPrintErrorSummary(const string &workDir, const string &message,
bool isAlsoAdvancedProblemDetails)
{
fprintf(stderr, "Error: %s\n", message.c_str());
recordErrorSummary(workDir, message, isAlsoAdvancedProblemDetails);
}
static void
recordProblemDescriptionHTML(const string &workDir, const string &message) {
string path = workDir + "/response/error/problem_description.html";
tryWriteFile(path, message);
}
static void
recordSolutionDescriptionHTML(const string &workDir, const string &message) {
string path = workDir + "/response/error/solution_description.html";
tryWriteFile(path, message);
}
static void
reopenStdout(int fd) {
dup2(fd, STDOUT_FILENO);
}
static void
dumpEnvvars(const string &workDir) {
FILE *f = fopen((workDir + "/envdump/envvars").c_str(), "w");
if (f == NULL) {
fprintf(stderr, "Warning: cannot open %s/envdump/envvars for writing\n",
workDir.c_str());
return;
}
const char *command[] = {
"env",
NULL
};
SubprocessInfo info;
runCommand(command, info, true, true,
boost::bind(reopenStdout, fileno(f)));
fclose(f);
}
static void
dumpUserInfo(const string &workDir) {
FILE *f = fopen((workDir + "/envdump/user_info").c_str(), "w");
if (f == NULL) {
fprintf(stderr, "Warning: cannot open %s/envdump/user_info for writing\n",
workDir.c_str());
return;
}
const char *command[] = {
"id",
NULL
};
SubprocessInfo info;
runCommand(command, info, true, true,
boost::bind(reopenStdout, fileno(f)));
fclose(f);
}
static void
dumpUlimits(const string &workDir) {
FILE *f = fopen((workDir + "/envdump/ulimits").c_str(), "w");
if (f == NULL) {
fprintf(stderr, "Warning: cannot open %s/envdump/ulimits for writing\n",
workDir.c_str());
return;
}
// On Linux, ulimit is a shell builtin and not a command.
const char *command[] = {
"/bin/sh",
"-c",
"ulimit -a",
NULL
};
SubprocessInfo info;
runCommand(command, info, true, true,
boost::bind(reopenStdout, fileno(f)));
fclose(f);
}
static void
dumpAllEnvironmentInfo(const string &workDir) {
dumpEnvvars(workDir);
dumpUserInfo(workDir);
dumpUlimits(workDir);
}
static bool
setUlimits(const Json::Value &args) {
if (!args.isMember("file_descriptor_ulimit")) {
return false;
}
rlim_t fdLimit = (rlim_t) args["file_descriptor_ulimit"].asUInt();
struct rlimit limit;
int ret;
limit.rlim_cur = fdLimit;
limit.rlim_max = fdLimit;
do {
ret = setrlimit(RLIMIT_NOFILE, &limit);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
int e = errno;
fprintf(stderr, "Error: unable to set file descriptor ulimit to %u: %s (errno=%d)",
(unsigned int) fdLimit, strerror(e), e);
}
return ret != -1;
}
static bool
canSwitchUser(const Json::Value &args) {
return args.isMember("user") && geteuid() == 0;
}
static void
lookupUserGroup(const Context &context, uid_t *uid, struct passwd **userInfo,
gid_t *gid)
{
const Json::Value &args = context.args;
errno = 0;
*userInfo = getpwnam(args["user"].asCString());
if (*userInfo == NULL) {
int e = errno;
if (looksLikePositiveNumber(args["user"].asString())) {
fprintf(stderr,
"Warning: error looking up system user database"
" entry for user '%s': %s (errno=%d)\n",
args["user"].asCString(), strerror(e), e);
*uid = (uid_t) atoi(args["user"].asString());
} else {
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Cannot lookup up system user database entry for user '"
+ args["user"].asString() + "': " + strerror(e)
+ " (errno=" + toString(e) + ")",
true);
exit(1);
}
} else {
*uid = (*userInfo)->pw_uid;
}
errno = 0;
struct group *groupInfo = getgrnam(args["group"].asCString());
if (groupInfo == NULL) {
int e = errno;
if (looksLikePositiveNumber(args["group"].asString())) {
fprintf(stderr,
"Warning: error looking up system group database entry for group '%s':"
" %s (errno=%d)\n",
args["group"].asCString(), strerror(e), e);
*gid = (gid_t) atoi(args["group"].asString());
} else {
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Cannot lookup up system group database entry for group '"
+ args["group"].asString() + "': " + strerror(e)
+ " (errno=" + toString(e) + ")",
true);
exit(1);
}
} else {
*gid = groupInfo->gr_gid;
}
}
void
chownNewWorkDirFiles(const Context &context, uid_t uid, gid_t gid) {
chown((context.workDir + "/response/steps/subprocess_before_first_exec/state").c_str(),
uid, gid);
chown((context.workDir + "/response/steps/subprocess_before_first_exec/duration").c_str(),
uid, gid);
chown((context.workDir + "/response/steps/subprocess_spawn_env_setupper_before_shell/state").c_str(),
uid, gid);
chown((context.workDir + "/response/steps/subprocess_spawn_env_setupper_before_shell/duration").c_str(),
uid, gid);
chown((context.workDir + "/envdump/envvars").c_str(),
uid, gid);
chown((context.workDir + "/envdump/user_info").c_str(),
uid, gid);
chown((context.workDir + "/envdump/ulimits").c_str(),
uid, gid);
}
static void
enterLveJail(const Context &context, const struct passwd *userInfo) {
string lveInitErr;
adhoc_lve::LibLve &liblve = adhoc_lve::LveInitSignleton::getInstance(&lveInitErr);
if (liblve.is_error()) {
if (!lveInitErr.empty()) {
lveInitErr = ": " + lveInitErr;
}
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::INTERNAL_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Failed to initialize LVE library: " + lveInitErr,
true);
exit(1);
}
if (!liblve.is_lve_available()) {
return;
}
string jailErr;
int ret = liblve.jail(userInfo, jailErr);
if (ret < 0) {
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::INTERNAL_ERROR);
recordAndPrintErrorSummary(context.workDir,
"enterLve() failed: " + jailErr,
true);
exit(1);
}
}
static void
switchGroup(const Context &context, uid_t uid, const struct passwd *userInfo, gid_t gid) {
if (userInfo != NULL) {
bool setgroupsCalled = false;
#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
#ifdef __APPLE__
int groups[1024];
int ngroups = sizeof(groups) / sizeof(int);
#else
gid_t groups[1024];
int ngroups = sizeof(groups) / sizeof(gid_t);
#endif
boost::scoped_array<gid_t> gidset;
int ret = getgrouplist(userInfo->pw_name, gid,
groups, &ngroups);
if (ret == -1) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"getgrouplist(" + string(userInfo->pw_name) + ", "
+ toString(gid) + ") failed: " + strerror(e)
+ " (errno=" + toString(e) + ")",
true);
exit(1);
}
if (ngroups <= NGROUPS_MAX) {
setgroupsCalled = true;
gidset.reset(new gid_t[ngroups]);
if (setgroups(ngroups, gidset.get()) == -1) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"setgroups(" + toString(ngroups)
+ ", ...) failed: " + strerror(e) + " (errno="
+ toString(e) + ")",
true);
exit(1);
}
}
#endif
if (!setgroupsCalled && initgroups(userInfo->pw_name, gid) == -1) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"initgroups(" + string(userInfo->pw_name)
+ ", " + toString(gid) + ") failed: " + strerror(e)
+ " (errno=" + toString(e) + ")",
true);
exit(1);
}
}
if (setgid(gid) == -1) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"setgid(" + toString(gid) + ") failed: "
+ strerror(e) + " (errno=" + toString(e) + ")",
true);
exit(1);
}
}
static void
switchUser(const Context &context, uid_t uid, const struct passwd *userInfo) {
if (setuid(uid) == -1) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"setuid(" + toString(uid) + ") failed: " + strerror(e)
+ " (errno=" + toString(e) + ")",
true);
exit(1);
}
if (userInfo != NULL) {
setenv("USER", userInfo->pw_name, 1);
setenv("LOGNAME", userInfo->pw_name, 1);
setenv("SHELL", userInfo->pw_shell, 1);
setenv("HOME", userInfo->pw_dir, 1);
} else {
unsetenv("USER");
unsetenv("LOGNAME");
unsetenv("SHELL");
unsetenv("HOME");
}
}
static string
lookupCurrentUserShell() {
struct passwd *userInfo = getpwuid(getuid());
if (userInfo == NULL) {
int e = errno;
fprintf(stderr, "Warning: cannot lookup system user database"
" entry for UID %d: %s (errno=%d)\n",
(int) getuid(), strerror(e), e);
return "/bin/sh";
} else {
return userInfo->pw_shell;
}
}
static vector<string>
inferAllParentDirectories(const string &path) {
vector<string> components, result;
split(path, '/', components);
P_ASSERT_EQ(components.front(), "");
components.erase(components.begin());
for (unsigned int i = 0; i < components.size(); i++) {
string path2;
for (unsigned int j = 0; j <= i; j++) {
path2.append("/");
path2.append(components[j]);
}
if (path2.empty()) {
path2 = "/";
}
result.push_back(path2);
}
P_ASSERT_EQ(result.back(), path);
return result;
}
static void
setCurrentWorkingDirectory(const Context &context) {
string appRoot = context.args["app_root"].asString(); // Already absolutized by HandshakePreparer
vector<string> appRootAndParentDirs = inferAllParentDirectories(appRoot);
vector<string>::const_iterator it;
int ret;
for (it = appRootAndParentDirs.begin(); it != appRootAndParentDirs.end(); it++) {
struct stat buf;
ret = stat(it->c_str(), &buf);
if (ret == -1 && errno == EACCES) {
char parent[PATH_MAX];
const char *end = strrchr(it->c_str(), '/');
memcpy(parent, it->c_str(), end - it->c_str());
parent[end - it->c_str()] = '\0';
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Directory '" + string(parent) + "' is inaccessible because of a"
" filesystem permission error.",
false);
recordProblemDescriptionHTML(context.workDir,
"<p>"
"The " PROGRAM_NAME " application server tried to start the"
" web application as user '" + escapeHTML(getProcessUsername())
+ "' and group '" + escapeHTML(getGroupName(getgid()))
+ "'. During this process, " SHORT_PROGRAM_NAME
" must be able to access its application root directory '"
+ escapeHTML(appRoot) + "'. However, the parent directory '"
+ escapeHTML(parent) + "' has wrong permissions, thereby preventing this"
" process from accessing its application root directory."
"</p>");
recordSolutionDescriptionHTML(context.workDir,
"<p class=\"sole-solution\">"
"Please fix the permissions of the directory '" + escapeHTML(appRoot)
+ "' in such a way that the directory is accessible by user '"
+ escapeHTML(getProcessUsername()) + "' and group '"
+ escapeHTML(getGroupName(getgid())) + "'."
"</p>");
exit(1);
} else if (ret == -1) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Unable to stat() directory '" + *it + "': "
+ strerror(e) + " (errno=" + toString(e) + ")",
true);
exit(1);
}
}
ret = chdir(appRoot.c_str());
if (ret != 0) {
int e = errno;
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Unable to change working directory to '" + appRoot + "': "
+ strerror(e) + " (errno=" + toString(e) + ")",
true);
if (e == EPERM || e == EACCES) {
recordProblemDescriptionHTML(context.workDir,
"<p>The " PROGRAM_NAME " application server tried to start the"
" web application as user " + escapeHTML(getProcessUsername())
+ " and group " + escapeHTML(getGroupName(getgid()))
+ ", with a working directory of "
+ escapeHTML(appRoot) + ". However, it encountered a filesystem"
" permission error while doing this.</p>");
} else {
recordProblemDescriptionHTML(context.workDir,
"<p>The " PROGRAM_NAME " application server tried to start the"
" web application as user " + escapeHTML(getProcessUsername())
+ " and group " + escapeHTML(getGroupName(getgid()))
+ ", with a working directory of "
+ escapeHTML(appRoot) + ". However, it encountered a filesystem"
" error while doing this.</p>");
}
exit(1);
}
// The application root may contain one or more symlinks
// in its path. If the application calls getcwd(), it will
// get the resolved path.
//
// It turns out that there is no such thing as a path without
// unresolved symlinks. The shell presents a working directory with
// unresolved symlinks (which it calls the "logical working directory"),
// but that is an illusion provided by the shell. The shell reports
// the logical working directory though the PWD environment variable.
//
// See also:
// https://github.com/phusion/passenger/issues/1596#issuecomment-138154045
// http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/pwd.c
// http://www.opensource.apple.com/source/shell_cmds/shell_cmds-170/pwd/pwd.c
setenv("PWD", appRoot.c_str(), 1);
}
static void
setDefaultEnvvars(const Json::Value &args) {
setenv("PYTHONUNBUFFERED", "1", 1);
setenv("NODE_PATH", args["node_libdir"].asCString(), 1);
setenv("RAILS_ENV", args["app_env"].asCString(), 1);
setenv("RACK_ENV", args["app_env"].asCString(), 1);
setenv("WSGI_ENV", args["app_env"].asCString(), 1);
setenv("NODE_ENV", args["app_env"].asCString(), 1);
setenv("PASSENGER_APP_ENV", args["app_env"].asCString(), 1);
if (args.isMember("expected_start_port")) {
setenv("PORT", toString(args["expected_start_port"].asInt()).c_str(), 1);
}
if (args["base_uri"].asString() != "/") {
setenv("RAILS_RELATIVE_URL_ROOT", args["base_uri"].asCString(), 1);
setenv("RACK_BASE_URI", args["base_uri"].asCString(), 1);
setenv("PASSENGER_BASE_URI", args["base_uri"].asCString(), 1);
} else {
unsetenv("RAILS_RELATIVE_URL_ROOT");
unsetenv("RACK_BASE_URI");
unsetenv("PASSENGER_BASE_URI");
}
}
static void
setGivenEnvVars(const Json::Value &args) {
const Json::Value &envvars = args["environment_variables"];
Json::Value::const_iterator it, end = envvars.end();
for (it = envvars.begin(); it != end; it++) {
string key = it.name();
setenv(key.c_str(), it->asCString(), 1);
}
}
static bool
shouldLoadShellEnvvars(const Json::Value &args, const string &shell) {
if (args["load_shell_envvars"].asBool()) {
string shellName = extractBaseName(shell);
bool result = shellName == "bash" || shellName == "zsh" || shellName == "ksh";
#if defined(__linux__) || defined(__APPLE__)
// On Linux, /bin/sh is usually either bash or dash, which
// supports -l.
// On macOS, it is not clear what /bin/sh is but
// it supports -l.
// This cannot be said of other platforms: for example on
// FreeBSD, /bin/sh does not support -l.
result = result || shellName == "sh";
#endif
P_DEBUG("shellName = '" << shellName << "' detected as supporting '-l': " << (result ? "true" : "false"));
return result;
} else {
return false;
}
}
static string
commandArgsToString(const vector<const char *> &commandArgs) {
vector<const char *>::const_iterator it;
string result;
for (it = commandArgs.begin(); it != commandArgs.end(); it++) {
if (*it != NULL) {
result.append(*it);
result.append(1, ' ');
}
}
return strip(result);
}
static bool
executedThroughShell(const Context &context) {
return fileExists(context.workDir + "/execute_through_os_shell");
}
static void
execNextCommand(const Context &context, const string &shell)
{
vector<const char *> commandArgs;
SpawningKit::JourneyStep nextJourneyStep;
string binShPath, binShParam;
// Note: do not try to set a process title in this function by messing with argv[0].
// https://code.google.com/p/phusion-passenger/issues/detail?id=855
if (context.mode == BEFORE_MODE) {
assert(!shell.empty());
if (shouldLoadShellEnvvars(context.args, shell)) {
nextJourneyStep = SpawningKit::SUBPROCESS_OS_SHELL;
commandArgs.push_back(shell.c_str());
if (LoggingKit::getLevel() >= LoggingKit::DEBUG3) {
commandArgs.push_back("-x");
}
commandArgs.push_back("-lc");
commandArgs.push_back("exec \"$@\"");
commandArgs.push_back("SpawnEnvSetupperShell");
// Will be used by 'spawn-env-setupper --after' to determine
// whether it should set the SUBPROCESS_OS_SHELL step to the
// PERFORMED state.
tryWriteFile(context.workDir + "/execute_through_os_shell", "");
} else {
nextJourneyStep = SpawningKit::SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL;
}
commandArgs.push_back(context.args["passenger_agent_path"].asCString());
commandArgs.push_back("spawn-env-setupper");
commandArgs.push_back(context.workDir.c_str());
commandArgs.push_back("--after");
} else {
if (context.args["starts_using_wrapper"].asBool()) {
nextJourneyStep = SpawningKit::SUBPROCESS_EXEC_WRAPPER;
} else {
nextJourneyStep = SpawningKit::SUBPROCESS_APP_LOAD_OR_EXEC;
}
if (context.args.isMember("_bin_sh_path")) {
// Used in unit tests
binShPath = context.args["_bin_sh_path"].asString();
} else {
binShPath = "/bin/sh";
}
binShParam = "exec " + context.args["start_command"].asString();
commandArgs.push_back(binShPath.c_str());
commandArgs.push_back("-c");
commandArgs.push_back(binShParam.c_str());
}
commandArgs.push_back(NULL);
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_PERFORMED);
recordJourneyStepBegin(context, nextJourneyStep,
SpawningKit::STEP_IN_PROGRESS);
execvp(commandArgs[0], (char * const *) &commandArgs[0]);
int e = errno;
recordJourneyStepEnd(context, nextJourneyStep,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir, SpawningKit::OPERATING_SYSTEM_ERROR);
recordAndPrintErrorSummary(context.workDir,
"Unable to execute command '" + commandArgsToString(commandArgs)
+ "': " + strerror(e) + " (errno=" + toString(e) + ")",
true);
exit(1);
}
int
spawnEnvSetupperMain(int argc, char *argv[]) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
if (argc != 4) {
fprintf(stderr, "Usage: PassengerAgent spawn-env-setupper <workdir> <--before|--after>\n");
exit(1);
}
oxt::initialize();
oxt::setup_syscall_interruption_support();
LoggingKit::initialize();
SystemTime::initialize();
Context context;
context.workDir = argv[2];
context.mode =
(strcmp(argv[3], "--before") == 0)
? BEFORE_MODE
: AFTER_MODE;
context.step =
(context.mode == BEFORE_MODE)
? SpawningKit::SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL
: SpawningKit::SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL;
setenv("IN_PASSENGER", "1", 1);
setenv("PASSENGER_SPAWN_WORK_DIR", context.workDir.c_str(), 1);
if (context.mode == BEFORE_MODE) {
recordJourneyStepEnd(context, SpawningKit::SUBPROCESS_BEFORE_FIRST_EXEC,
SpawningKit::STEP_PERFORMED);
}
recordJourneyStepBegin(context, context.step,
SpawningKit::STEP_IN_PROGRESS);
try {
context.args = readArgsJson(context.workDir);
bool shouldTrySwitchUser = canSwitchUser(context.args);
string shell;
initializeLogLevel(context.args);
dumpAllEnvironmentInfo(context.workDir);
if (context.mode == BEFORE_MODE) {
struct passwd *userInfo = NULL;
uid_t uid;
gid_t gid;
setDefaultEnvvars(context.args);
dumpEnvvars(context.workDir);
if (shouldTrySwitchUser) {
lookupUserGroup(context, &uid, &userInfo, &gid);
shell = userInfo->pw_shell;
} else {
shell = lookupCurrentUserShell();
}
if (setUlimits(context.args)) {
dumpUlimits(context.workDir);
}
if (shouldTrySwitchUser) {
chownNewWorkDirFiles(context, uid, gid);
enterLveJail(context, userInfo);
switchGroup(context, uid, userInfo, gid);
dumpUserInfo(context.workDir);
switchUser(context, uid, userInfo);
dumpEnvvars(context.workDir);
dumpUserInfo(context.workDir);
}
} else if (executedThroughShell(context)) {
recordJourneyStepEnd(context, SpawningKit::SUBPROCESS_OS_SHELL,
SpawningKit::STEP_PERFORMED);
} else {
recordJourneyStepEnd(context, SpawningKit::SUBPROCESS_OS_SHELL,
SpawningKit::STEP_NOT_STARTED);
}
setCurrentWorkingDirectory(context);
dumpEnvvars(context.workDir);
if (context.mode == AFTER_MODE) {
setDefaultEnvvars(context.args);
setGivenEnvVars(context.args);
dumpEnvvars(context.workDir);
}
execNextCommand(context, shell);
} catch (const oxt::tracable_exception &e) {
fprintf(stderr, "Error: %s\n%s\n",
e.what(), e.backtrace().c_str());
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::inferErrorCategoryFromAnotherException(
e, context.step));
recordErrorSummary(context.workDir, e.what(), true);
return 1;
} catch (const std::exception &e) {
fprintf(stderr, "Error: %s\n", e.what());
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordErrorCategory(context.workDir,
SpawningKit::inferErrorCategoryFromAnotherException(
e, context.step));
recordErrorSummary(context.workDir, e.what(), true);
return 1;
}
// Should never be reached
recordJourneyStepEnd(context, context.step,
SpawningKit::STEP_ERRORED);
recordAndPrintErrorSummary(context.workDir,
"*** BUG IN SpawnEnvSetupper ***: end of main() reached",
true);
return 1;
}
| 30.13612
| 108
| 0.699683
|
ROMB
|
814baaa5b9e4fd5a701f892da60b0cc9d6e41a5e
| 19,377
|
hpp
|
C++
|
include/mcl/mapto_wb19.hpp
|
alinush/mcl
|
868bccc849436b1c973d6fa9fe3c0ea3bb9ff361
|
[
"BSD-3-Clause"
] | 1
|
2020-09-10T02:48:10.000Z
|
2020-09-10T02:48:10.000Z
|
include/mcl/mapto_wb19.hpp
|
alinush/mcl
|
868bccc849436b1c973d6fa9fe3c0ea3bb9ff361
|
[
"BSD-3-Clause"
] | null | null | null |
include/mcl/mapto_wb19.hpp
|
alinush/mcl
|
868bccc849436b1c973d6fa9fe3c0ea3bb9ff361
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
/**
@file
@brief map to G2 on BLS12-381 (must be included from mcl/bn.hpp)
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
ref. https://eprint.iacr.org/2019/403 , https://github.com/algorand/bls_sigs_ref
*/
namespace mcl {
namespace local {
// y^2 = x^3 + 4(1 + i)
template<class F>
struct PointT {
typedef F Fp;
F x, y, z;
static F a_;
static F b_;
static int specialA_;
bool isZero() const
{
return z.isZero();
}
void clear()
{
x.clear();
y.clear();
z.clear();
}
bool isEqual(const PointT<F>& rhs) const
{
return ec::isEqualJacobi(*this, rhs);
}
};
template<class F> F PointT<F>::a_;
template<class F> F PointT<F>::b_;
template<class F> int PointT<F>::specialA_;
} // mcl::local
template<class Fp, class G1, class Fp2, class G2>
struct MapTo_WB19 {
typedef local::PointT<Fp> E1;
typedef local::PointT<Fp2> E2;
mpz_class sqrtConst; // (p^2 - 9) / 16
Fp2 g2A;
Fp2 g2B;
Fp2 root4[4];
Fp2 etas[4];
Fp2 xnum[4];
Fp2 xden[3];
Fp2 ynum[4];
Fp2 yden[4];
Fp g1A, g1B, g1c1, g1c2;
Fp g1xnum[12];
Fp g1xden[11];
Fp g1ynum[16];
Fp g1yden[16];
mpz_class g1cofactor;
int g1Z;
void init()
{
bool b;
g2A.a = 0;
g2A.b = 240;
g2B.a = 1012;
g2B.b = 1012;
E1::a_.clear();
E1::b_ = 4;
E1::specialA_ = ec::Zero;
E2::a_.clear();
E2::b_.a = 4;
E2::b_.b = 4;
E2::specialA_ = ec::Zero;
sqrtConst = Fp::getOp().mp;
sqrtConst *= sqrtConst;
sqrtConst -= 9;
sqrtConst /= 16;
const char *rv1Str = "0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09";
root4[0].a = 1;
root4[0].b.clear();
root4[1].a.clear();
root4[1].b = 1;
root4[2].a.setStr(&b, rv1Str);
assert(b); (void)b;
root4[2].b = root4[2].a;
root4[3].a = root4[2].a;
Fp::neg(root4[3].b, root4[3].a);
const char *ev1Str = "0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90";
const char *ev2Str = "0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5";
const char *ev3Str = "0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17";
const char *ev4Str = "0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1";
Fp& ev1 = etas[0].a;
Fp& ev2 = etas[0].b;
Fp& ev3 = etas[2].a;
Fp& ev4 = etas[2].b;
ev1.setStr(&b, ev1Str);
assert(b); (void)b;
ev2.setStr(&b, ev2Str);
assert(b); (void)b;
Fp::neg(etas[1].a, ev2);
etas[1].b = ev1;
ev3.setStr(&b, ev3Str);
assert(b); (void)b;
ev4.setStr(&b, ev4Str);
assert(b); (void)b;
Fp::neg(etas[3].a, ev4);
etas[3].b = ev3;
init_iso3();
{
const char *A = "0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d";
const char *B = "0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0";
const char *c1 = "0x680447a8e5ff9a692c6e9ed90d2eb35d91dd2e13ce144afd9cc34a83dac3d8907aaffffac54ffffee7fbfffffffeaaa";
const char *c2 = "0x3d689d1e0e762cef9f2bec6130316806b4c80eda6fc10ce77ae83eab1ea8b8b8a407c9c6db195e06f2dbeabc2baeff5";
g1A.setStr(&b, A);
assert(b); (void)b;
g1B.setStr(&b, B);
assert(b); (void)b;
g1c1.setStr(&b, c1);
assert(b); (void)b;
g1c2.setStr(&b, c2);
assert(b); (void)b;
g1Z = 11;
gmp::setStr(&b, g1cofactor, "d201000000010001", 16);
assert(b); (void)b;
}
init_iso11();
}
void initArray(Fp *dst, const char **s, size_t n) const
{
bool b;
for (size_t i = 0; i < n; i++) {
dst[i].setStr(&b, s[i]);
assert(b);
(void)b;
}
}
void init_iso3()
{
const char *tbl[] = {
"0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6",
"0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a",
"0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e",
"0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d",
"0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1",
"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63",
"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f",
"0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706",
"0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be",
"0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c",
"0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f",
"0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10",
"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb",
"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3",
"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99",
};
bool b;
xnum[0].a.setStr(&b, tbl[0]); assert(b); (void)b;
xnum[0].b = xnum[0].a;
xnum[1].a.clear();
xnum[1].b.setStr(&b, tbl[1]); assert(b); (void)b;
xnum[2].a.setStr(&b, tbl[2]); assert(b); (void)b;
xnum[2].b.setStr(&b, tbl[3]); assert(b); (void)b;
xnum[3].a.setStr(&b, tbl[4]); assert(b); (void)b;
xnum[3].b.clear();
xden[0].a.clear();
xden[0].b.setStr(&b, tbl[5]); assert(b); (void)b;
xden[1].a = 0xc;
xden[1].b.setStr(&b, tbl[6]); assert(b); (void)b;
xden[2].a = 1;
xden[2].b = 0;
ynum[0].a.setStr(&b, tbl[7]); assert(b); (void)b;
ynum[0].b = ynum[0].a;
ynum[1].a.clear();
ynum[1].b.setStr(&b, tbl[8]); assert(b); (void)b;
ynum[2].a.setStr(&b, tbl[9]); assert(b); (void)b;
ynum[2].b.setStr(&b, tbl[10]); assert(b); (void)b;
ynum[3].a.setStr(&b, tbl[11]); assert(b); (void)b;
ynum[3].b.clear();
yden[0].a.setStr(&b, tbl[12]); assert(b); (void)b;
yden[0].b = yden[0].a;
yden[1].a.clear();
yden[1].b.setStr(&b, tbl[13]); assert(b); (void)b;
yden[2].a = 0x12;
yden[2].b.setStr(&b, tbl[14]); assert(b); (void)b;
yden[3].a = 1;
yden[3].b.clear();
}
void init_iso11()
{
const char *xnumStr[] = {
"0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7",
"0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb",
"0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0",
"0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861",
"0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9",
"0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983",
"0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84",
"0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e",
"0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317",
"0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e",
"0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b",
"0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229",
};
const char *xdenStr[] = {
"0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c",
"0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff",
"0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19",
"0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8",
"0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e",
"0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5",
"0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a",
"0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e",
"0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641",
"0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a",
"0x1",
};
const char *ynumStr[] = {
"0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33",
"0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696",
"0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6",
"0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb",
"0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb",
"0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0",
"0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2",
"0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29",
"0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587",
"0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30",
"0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132",
"0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e",
"0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8",
"0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133",
"0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b",
"0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604",
};
const char *ydenStr[] = {
"0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1",
"0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d",
"0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2",
"0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416",
"0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d",
"0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac",
"0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c",
"0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9",
"0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a",
"0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55",
"0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8",
"0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092",
"0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc",
"0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7",
"0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f",
"0x1",
};
initArray(g1xnum, xnumStr, CYBOZU_NUM_OF_ARRAY(xnumStr));
initArray(g1xden, xdenStr, CYBOZU_NUM_OF_ARRAY(xdenStr));
initArray(g1ynum, ynumStr, CYBOZU_NUM_OF_ARRAY(ynumStr));
initArray(g1yden, ydenStr, CYBOZU_NUM_OF_ARRAY(ydenStr));
}
template<class F, size_t N>
void evalPoly(F& y, const F& x, const F *zpows, const F (&cof)[N]) const
{
y = cof[N - 1]; // always zpows[0] = 1
for (size_t i = 1; i < N; i++) {
y *= x;
F t;
F::mul(t, zpows[i - 1], cof[N - 1 - i]);
y += t;
}
}
// refer (xnum, xden, ynum, yden)
void iso3(G2& Q, const E2& P) const
{
Fp2 zpows[3];
Fp2::sqr(zpows[0], P.z);
Fp2::sqr(zpows[1], zpows[0]);
Fp2::mul(zpows[2], zpows[1], zpows[0]);
Fp2 mapvals[4];
evalPoly(mapvals[0], P.x, zpows, xnum);
evalPoly(mapvals[1], P.x, zpows, xden);
evalPoly(mapvals[2], P.x, zpows, ynum);
evalPoly(mapvals[3], P.x, zpows, yden);
mapvals[1] *= zpows[0];
mapvals[2] *= P.y;
mapvals[3] *= zpows[0];
mapvals[3] *= P.z;
Fp2::mul(Q.z, mapvals[1], mapvals[3]);
Fp2::mul(Q.x, mapvals[0], mapvals[3]);
Q.x *= Q.z;
Fp2 t;
Fp2::sqr(t, Q.z);
Fp2::mul(Q.y, mapvals[2], mapvals[1]);
Q.y *= t;
}
template<class X, class C, size_t N>
X evalPoly2(const X& x, const C (&c)[N]) const
{
X ret = c[N - 1];
for (size_t i = 1; i < N; i++) {
ret *= x;
ret += c[N - 1 - i];
}
return ret;
}
// refer (g1xnum, g1xden, g1ynum, g1yden)
void iso11(G1& Q, E1& P) const
{
ec::normalizeJacobi(P);
Fp xn, xd, yn, yd;
xn = evalPoly2(P.x, g1xnum);
xd = evalPoly2(P.x, g1xden);
yn = evalPoly2(P.x, g1ynum);
yd = evalPoly2(P.x, g1yden);
/*
[xn/xd:y * yn/yd:1] = [xn xd yd^2:y yn xd^3 yd^2:xd yd]
=[xn yd z:y yn xd z^2:z] where z = xd yd
*/
Fp::mul(Q.z, xd, yd);
Fp::mul(Q.x, xn, yd);
Q.x *= Q.z;
Fp::mul(Q.y, P.y, yn);
Q.y *= xd;
Fp::sqr(xd, Q.z);
Q.y *= xd;
}
/*
xi = -2-i
(a+bi)*(-2-i) = (b-2a)-(a+2b)i
*/
void mul_xi(Fp2& y, const Fp2& x) const
{
Fp t;
Fp::sub(t, x.b, x.a);
t -= x.a;
Fp::add(y.b, x.b, x.b);
y.b += x.a;
Fp::neg(y.b, y.b);
y.a = t;
}
bool isNegSign(const Fp& x) const
{
return x.isOdd();
}
bool isNegSign(const Fp2& x) const
{
bool sign0 = isNegSign(x.a);
bool zero0 = x.a.isZero();
bool sign1 = isNegSign(x.b);
return sign0 || (zero0 & sign1);
}
// https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#appendix-D.3.5
void sswuG1(Fp& xn, Fp& xd, Fp& y, const Fp& u) const
{
const Fp& A = g1A;
const Fp& B = g1B;
const Fp& c1 = g1c1;
const Fp& c2 = g1c2;
const int Z = g1Z;
Fp u2, u2Z, t, t2, t3;
Fp::sqr(u2, u);
Fp::mulUnit(u2Z, u2, Z);
Fp::sqr(t, u2Z);
Fp::add(xd, t, u2Z);
if (xd.isZero()) {
Fp::mulUnit(xd, A, Z);
xn = B;
} else {
Fp::add(xn, xd, Fp::one());
xn *= B;
xd *= A;
Fp::neg(xd, xd);
}
Fp::sqr(t, xd);
Fp::mul(t2, t, xd);
t *= A;
Fp::sqr(t3, xn);
t3 += t;
t3 *= xn;
Fp::mul(t, t2, B);
t3 += t;
Fp::sqr(y, t2);
Fp::mul(t, t3, t2);
y *= t;
Fp::pow(y, y, c1);
y *= t;
Fp::sqr(t, y);
t *= t2;
if (t != t3) {
xn *= u2Z;
y *= c2;
y *= u2;
y *= u;
}
if (isNegSign(u) != isNegSign(y)) {
Fp::neg(y, y);
}
}
void sswuG1(E1& pt, const Fp& u) const
{
Fp xn, y;
Fp& xd = pt.z;
sswuG1(xn, xd, y, u);
Fp::mul(pt.x, xn, xd);
Fp::sqr(pt.y, xd);
pt.y *= xd;
pt.y *= y;
}
// https://github.com/algorand/bls_sigs_ref
void sswuG2(E2& P, const Fp2& t) const
{
Fp2 t2, t2xi;
Fp2::sqr(t2, t);
Fp2 den, den2;
mul_xi(t2xi, t2);
den = t2xi;
Fp2::sqr(den2, den);
// (t^2 * xi)^2 + (t^2 * xi)
den += den2;
Fp2 x0_num, x0_den;
Fp2::add(x0_num, den, 1);
x0_num *= g2B;
if (den.isZero()) {
mul_xi(x0_den, g2A);
} else {
Fp2::mul(x0_den, -g2A, den);
}
Fp2 x0_den2, x0_den3, gx0_den, gx0_num;
Fp2::sqr(x0_den2, x0_den);
Fp2::mul(x0_den3, x0_den2, x0_den);
gx0_den = x0_den3;
Fp2::mul(gx0_num, g2B, gx0_den);
Fp2 tmp, tmp1, tmp2;
Fp2::mul(tmp, g2A, x0_num);
tmp *= x0_den2;
gx0_num += tmp;
Fp2::sqr(tmp, x0_num);
tmp *= x0_num;
gx0_num += tmp;
Fp2::sqr(tmp1, gx0_den); // x^2
Fp2::sqr(tmp2, tmp1); // x^4
tmp1 *= tmp2;
tmp1 *= gx0_den; // x^7
Fp2::mul(tmp2, gx0_num, tmp1);
tmp1 *= tmp2;
tmp1 *= gx0_den;
Fp2 candi;
Fp2::pow(candi, tmp1, sqrtConst);
candi *= tmp2;
bool isNegT = isNegSign(t);
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(root4); i++) {
Fp2::mul(P.y, candi, root4[i]);
Fp2::sqr(tmp, P.y);
tmp *= gx0_den;
if (tmp == gx0_num) {
if (isNegSign(P.y) != isNegT) {
Fp2::neg(P.y, P.y);
}
Fp2::mul(P.x, x0_num, x0_den);
P.y *= x0_den3;
P.z = x0_den;
return;
}
}
Fp2 x1_num, x1_den, gx1_num, gx1_den;
Fp2::mul(x1_num, t2xi, x0_num);
x1_den = x0_den;
Fp2::mul(gx1_num, den2, t2xi);
gx1_num *= gx0_num;
gx1_den = gx0_den;
candi *= t2;
candi *= t;
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(etas); i++) {
Fp2::mul(P.y, candi, etas[i]);
Fp2::sqr(tmp, P.y);
tmp *= gx1_den;
if (tmp == gx1_num) {
if (isNegSign(P.y) != isNegT) {
Fp2::neg(P.y, P.y);
}
Fp2::mul(P.x, x1_num, x1_den);
Fp2::sqr(tmp, x1_den);
P.y *= tmp;
P.y *= x1_den;
P.z = x1_den;
return;
}
}
assert(0);
}
template<class T>
void put(const T& P) const
{
const int base = 10;
printf("x=%s\n", P.x.getStr(base).c_str());
printf("y=%s\n", P.y.getStr(base).c_str());
printf("z=%s\n", P.z.getStr(base).c_str());
}
void Fp2ToG2(G2& P, const Fp2& t, const Fp2 *t2 = 0) const
{
E2 Pp;
sswuG2(Pp, t);
if (t2) {
E2 P2;
sswuG2(P2, *t2);
ec::addJacobi(Pp, Pp, P2);
}
iso3(P, Pp);
mcl::local::mulByCofactorBLS12fast(P, P);
}
void hashToFp2(Fp2 out[2], const void *msg, size_t msgSize, const void *dst, size_t dstSize) const
{
uint8_t md[256];
mcl::fp::expand_message_xmd(md, sizeof(md), msg, msgSize, dst, dstSize);
Fp *x = out[0].getFp0();
for (size_t i = 0; i < 4; i++) {
bool b;
x[i].setBigEndianMod(&b, &md[64 * i], 64);
assert(b); (void)b;
}
}
void msgToG2(G2& out, const void *msg, size_t msgSize, const void *dst, size_t dstSize) const
{
Fp2 t[2];
hashToFp2(t, msg, msgSize, dst, dstSize);
Fp2ToG2(out, t[0], &t[1]);
}
void msgToG2(G2& out, const void *msg, size_t msgSize) const
{
const char *dst = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
const size_t dstSize = strlen(dst);
msgToG2(out, msg, msgSize, dst, dstSize);
}
void FpToG1(G1& out, const Fp& u0, const Fp *u1 = 0) const
{
E1 P1;
sswuG1(P1, u0);
if (u1) {
E1 P2;
sswuG1(P2, *u1);
ec::addJacobi(P1, P1, P2);
}
iso11(out, P1);
G1::mulGeneric(out, out, g1cofactor);
}
void msgToG1(G1& out, const void *msg, size_t msgSize, const char *dst, size_t dstSize) const
{
uint8_t md[128];
mcl::fp::expand_message_xmd(md, sizeof(md), msg, msgSize, dst, dstSize);
Fp u[2];
for (size_t i = 0; i < 2; i++) {
bool b;
u[i].setBigEndianMod(&b, &md[64 * i], 64);
assert(b); (void)b;
}
FpToG1(out, u[0], &u[1]);
}
void msgToG1(G1& out, const void *msg, size_t msgSize) const
{
const char *dst = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
const size_t dstSize = strlen(dst);
msgToG1(out, msg, msgSize, dst, dstSize);
}
};
} // mcl
| 33.816754
| 123
| 0.717139
|
alinush
|
814ff6139119fbbef8713c3c54f3a546a4a860cb
| 6,700
|
cpp
|
C++
|
source/solution_zoo/common/xproto_plugins/iotvioplugin/src/vioplugin/viomessage.cpp
|
HorizonRobotics-Platform/AI-EXPRESS
|
413206d88dae1fbd465ced4d60b2a1769d15c171
|
[
"BSD-2-Clause"
] | 98
|
2020-09-11T13:52:44.000Z
|
2022-03-23T11:52:02.000Z
|
source/solution_zoo/common/xproto_plugins/iotvioplugin/src/vioplugin/viomessage.cpp
|
HorizonRobotics-Platform/ai-express
|
413206d88dae1fbd465ced4d60b2a1769d15c171
|
[
"BSD-2-Clause"
] | 8
|
2020-10-19T14:23:30.000Z
|
2022-03-16T01:00:07.000Z
|
source/solution_zoo/common/xproto_plugins/iotvioplugin/src/vioplugin/viomessage.cpp
|
HorizonRobotics-Platform/AI-EXPRESS
|
413206d88dae1fbd465ced4d60b2a1769d15c171
|
[
"BSD-2-Clause"
] | 28
|
2020-09-17T14:20:35.000Z
|
2022-01-10T16:26:00.000Z
|
/*
* @Description: implement of vioplugin
* @Author: fei.cheng@horizon.ai
* @Date: 2019-08-26 16:17:25
* @Author: songshan.gong@horizon.ai
* @Date: 2019-09-26 16:17:25
* @LastEditors: hao.tian@horizon.ai
* @LastEditTime: 2019-10-16 15:34:58
* @Copyright 2017~2019 Horizon Robotics, Inc.
*/
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "vioplugin/viomessage.h"
#include "hobotlog/hobotlog.hpp"
#include "horizon/vision_type/vision_type_util.h"
#include "xproto_msgtype/protobuf/x2.pb.h"
#include "vioplugin/vioprocess.h"
namespace horizon {
namespace vision {
namespace xproto {
namespace vioplugin {
ImageVioMessage::ImageVioMessage(
const std::shared_ptr<VioPipeLine> &vio_pipeline,
std::vector<std::shared_ptr<PymImageFrame>> &image_frame,
uint32_t img_num, bool is_valid) {
type_ = TYPE_IMAGE_MESSAGE;
num_ = img_num;
if (image_frame.size() > 0) {
time_stamp_ = image_frame[0]->time_stamp;
sequence_id_ = image_frame[0]->frame_id;
channel_ = image_frame[0]->channel_id;
image_.resize(image_frame.size());
}
is_valid_uri_ = is_valid;
vio_pipeline_ = vio_pipeline;
for (uint32_t i = 0; i < image_frame.size(); ++i) {
image_[i] = image_frame[i];
}
}
ImageVioMessage::~ImageVioMessage() { LOGI << "call ~ImageVioMessage"; }
void ImageVioMessage::FreeImage(int tmp) {
if (image_.size() > 0) {
// free image
if (num_ == 1) {
#if defined(X3_X2_VIO)
VioFeedbackContext *feedback_context =
reinterpret_cast<VioFeedbackContext *>(image_[0]->context);
if (feedback_context == nullptr) {
LOGE << "feedback_context pointer is NULL";
return;
}
if (hb_vio_free_info(HB_VIO_SRC_INFO,
&(feedback_context->src_info)) < 0) {
LOGE << "hb_vio_free_info failed";
}
int ret = hb_vio_free(&(feedback_context->pym_img_info));
if (ret != 0) {
LOGE << "hb_vio_free failed";
}
free(feedback_context);
LOGD << "free feedback context success";
#elif defined(X3_IOT_VIO)
VioFeedbackContext *feedback_context =
reinterpret_cast<VioFeedbackContext *>(image_[0]->context);
if (feedback_context == nullptr) {
LOGE << "feedback_context pointer is NULL";
return;
}
int pipe_id = vio_pipeline_->GetPipeId();
uint32_t frame_id = image_[0]->frame_id;
LOGI << "begin remove one vio slot, pipe_id: " << pipe_id
<< " frame_id: " << frame_id;
auto res = vio_pipeline_->FreeInfo(IOT_VIO_FEEDBACK_SRC_INFO,
&(feedback_context->src_info));
if (res) {
LOGE << "vio pipeline free vio feedback src info failed";
}
res = vio_pipeline_->FreeInfo(IOT_VIO_PYM_INFO,
&(feedback_context->pym_img_info));
if (res) {
LOGE << "vio pipeline free vio pym info failed";
}
free(feedback_context);
LOGD << "free feedback context success";
#endif
image_[0]->context = nullptr;
image_[0] = nullptr;
} else if (num_ == 2) {
// todo
}
image_.clear();
}
}
void ImageVioMessage::FreeImage() {
if (image_.size() > 0) {
// free image
if (num_ == 1) {
#ifdef X3_X2_VIO
img_info_t *img_info = reinterpret_cast<img_info_t *>(image_[0]->context);
hb_vio_free(img_info);
free(img_info);
#elif defined(X3_IOT_VIO)
int pipe_id = vio_pipeline_->GetPipeId();
pym_buffer_t *img_info =
reinterpret_cast<pym_buffer_t *>(image_[0]->context);
uint32_t frame_id = image_[0]->frame_id;
LOGI << "begin remove one vio slot, pipe_id: " << pipe_id
<< " frame_id: " << frame_id;
auto res = vio_pipeline_->FreeInfo(IOT_VIO_PYM_INFO, img_info);
if (res) {
LOGE << "vio pipeline free vio pym info failed";
}
free(img_info);
#endif
image_[0]->context = nullptr;
image_[0] = nullptr;
} else if (num_ == 2) {
// todo
}
image_.clear();
}
}
void ImageVioMessage::FreeMultiImage() {
#ifdef X3_IOT_VIO
if (image_.size() > 0) {
// free multi pym image
int pipe_id = vio_pipeline_->GetPipeId();
LOGI << "begin remove multi vio slot, pipe_id: " << pipe_id;
auto res = vio_pipeline_->FreeMultiPymInfo(image_);
if (res) {
LOGE << "vio pipeline free multi vio pym info failed";
}
image_.clear();
}
#endif
}
DropVioMessage::DropVioMessage(uint64_t timestamp, uint64_t seq_id) {
type_ = TYPE_DROP_MESSAGE;
time_stamp_ = timestamp;
sequence_id_ = seq_id;
}
std::string DropVioMessage::Serialize() {
std::string smart_str;
x2::SmartFrameMessage smart_frame_message;
LOGI << "Drop Serialize";
smart_frame_message.set_timestamp_(time_stamp_);
smart_frame_message.set_error_code_(1);
smart_frame_message.SerializeToString(&smart_str);
return smart_str;
}
DropImageVioMessage::DropImageVioMessage(
const std::shared_ptr<VioPipeLine> &vio_pipeline,
std::vector<std::shared_ptr<PymImageFrame>> &image_frame, uint32_t img_num,
bool is_valid) {
type_ = TYPE_DROP_IMAGE_MESSAGE;
num_ = img_num;
if (image_frame.size() > 0) {
time_stamp_ = image_frame[0]->time_stamp;
sequence_id_ = image_frame[0]->frame_id;
image_.resize(image_frame.size());
}
is_valid_uri_ = is_valid;
vio_pipeline_ = vio_pipeline;
for (uint32_t i = 0; i < image_frame.size(); ++i) {
image_[i] = image_frame[i];
}
}
DropImageVioMessage::~DropImageVioMessage() {
LOGI << "call ~DropImageVioMessage";
}
void DropImageVioMessage::FreeImage() {
if (image_.size() > 0) {
// free image
if (num_ == 1) {
LOGI << "begin remove one vio slot";
#ifdef X3_X2_VIO
img_info_t *img_info = reinterpret_cast<img_info_t *>(image_[0]->context);
hb_vio_free(img_info);
free(img_info);
#elif defined(X3_IOT_VIO)
pym_buffer_t *img_info =
reinterpret_cast<pym_buffer_t *>(image_[0]->context);
auto res = vio_pipeline_->FreeInfo(IOT_VIO_PYM_INFO, img_info);
if (res) {
LOGE << "vio pipeline free vio pym info failed";
}
free(img_info);
#endif
image_[0]->context = nullptr;
image_[0] = nullptr;
} else if (num_ == 2) {
// todo
}
image_.clear();
}
}
void DropImageVioMessage::FreeMultiImage() {
#ifdef X3_IOT_VIO
if (image_.size() > 0) {
// free multi pym image
LOGI << "begin remove multi vio slot";
auto res = vio_pipeline_->FreeMultiPymInfo(image_);
if (res) {
LOGE << "vio pipeline free multi vio pym info failed";
}
image_.clear();
}
#endif
}
} // namespace vioplugin
} // namespace xproto
} // namespace vision
} // namespace horizon
| 28.632479
| 80
| 0.647612
|
HorizonRobotics-Platform
|
81502f6041161aac63c67e4290d0acfdbf05830d
| 67
|
cpp
|
C++
|
Refureku/Library/Tests/TemplateClass.cpp
|
jsoysouvanh/Refureku
|
7548cb3b196793119737a51c1cedc136aa60d3ee
|
[
"MIT"
] | 143
|
2020-04-07T21:38:21.000Z
|
2022-03-30T01:06:33.000Z
|
Refureku/Library/Tests/TemplateClass.cpp
|
jsoysouvanh/Refureku
|
7548cb3b196793119737a51c1cedc136aa60d3ee
|
[
"MIT"
] | 7
|
2021-03-30T07:26:21.000Z
|
2022-03-28T16:31:02.000Z
|
Refureku/Library/Tests/TemplateClass.cpp
|
jsoysouvanh/Refureku
|
7548cb3b196793119737a51c1cedc136aa60d3ee
|
[
"MIT"
] | 11
|
2020-06-06T09:45:12.000Z
|
2022-01-25T17:17:55.000Z
|
#include "Include/Generated/SingleTypeTemplateClassTemplate.rfks.h"
| 67
| 67
| 0.880597
|
jsoysouvanh
|
8150b3a5a45c3cce76386fccd2d4ff48a5fe8e0a
| 1,438
|
hpp
|
C++
|
socket_utils.hpp
|
theom/tls-socket
|
05a293b5e9ad9e30826628458f9b9bb349fe1d08
|
[
"BSD-2-Clause"
] | 4
|
2018-03-24T12:02:20.000Z
|
2020-12-31T20:04:15.000Z
|
socket_utils.hpp
|
theom/tls-socket
|
05a293b5e9ad9e30826628458f9b9bb349fe1d08
|
[
"BSD-2-Clause"
] | 1
|
2019-08-04T05:34:44.000Z
|
2019-08-05T12:03:44.000Z
|
socket_utils.hpp
|
theom/tls-socket
|
05a293b5e9ad9e30826628458f9b9bb349fe1d08
|
[
"BSD-2-Clause"
] | 1
|
2018-03-24T15:01:03.000Z
|
2018-03-24T15:01:03.000Z
|
/*
* (C) 2014,2017 Jack Lloyd
* 2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* tls-socket is released under the Simplified BSD License (see license.txt)
*/
#pragma once
#if defined(_WIN32)
#include <winsock2.h>
#include <WS2tcpip.h>
typedef size_t ssize_t;
#define STDIN_FILENO _fileno(stdin)
inline void init_sockets()
{
WSAData wsa_data;
WORD wsa_version = MAKEWORD(2, 2);
if (::WSAStartup(wsa_version, &wsa_data) != 0)
{
throw Botan_CLI::CLI_Error("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
}
if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
{
::WSACleanup();
throw Botan_CLI::CLI_Error("Could not find a usable version of Winsock.dll");
}
}
inline void stop_sockets()
{
::WSACleanup();
}
inline int close(int fd)
{
return ::closesocket(fd);
}
inline int read(int s, void* buf, size_t len)
{
return ::recv(s, reinterpret_cast<char*>(buf), static_cast<int>(len), 0);
}
inline int send(int s, const uint8_t* buf, size_t len, int flags)
{
return ::send(s, reinterpret_cast<const char*>(buf), static_cast<int>(len), flags);
}
#else
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
inline void init_sockets() {}
inline void stop_sockets() {}
#endif
| 19.972222
| 96
| 0.665508
|
theom
|
8151912896bd6c6794df02af3f4db76dffb20833
| 1,472
|
hpp
|
C++
|
Source/AliveLibAE/GlukkonSwitch.hpp
|
mouzedrift/alive_reversing
|
be7dfbaed3be99b452459e974bc4e79f9503c178
|
[
"MIT"
] | 208
|
2018-06-06T13:14:03.000Z
|
2022-03-30T02:21:27.000Z
|
Source/AliveLibAE/GlukkonSwitch.hpp
|
mouzedrift/alive_reversing
|
be7dfbaed3be99b452459e974bc4e79f9503c178
|
[
"MIT"
] | 537
|
2018-06-06T16:50:45.000Z
|
2022-03-31T16:41:15.000Z
|
Source/AliveLibAE/GlukkonSwitch.hpp
|
mouzedrift/alive_reversing
|
be7dfbaed3be99b452459e974bc4e79f9503c178
|
[
"MIT"
] | 42
|
2018-06-06T00:40:08.000Z
|
2022-03-23T08:38:55.000Z
|
#pragma once
#include "BaseAnimatedWithPhysicsGameObject.hpp"
#include "Path.hpp"
#include "../AliveLibCommon/FunctionFwd.hpp"
struct Path_GlukkonSwitch final : public Path_TLV
{
enum class Scale : s16
{
eHalf_0 = 0,
eFull_1 = 1,
};
Scale field_10_scale;
s16 field_12_ok_id;
s16 field_14_fail_id;
u16 field_16_xpos;
u16 field_18_ypos;
s16 field_1A_pad;
};
ALIVE_ASSERT_SIZEOF_ALWAYS(Path_GlukkonSwitch, 0x1C);
class GlukkonSwitch final : public ::BaseAnimatedWithPhysicsGameObject
{
public:
EXPORT GlukkonSwitch* ctor_444E60(Path_GlukkonSwitch* pTlv, s32 tlvInfo);
virtual BaseGameObject* VDestructor(s32 flags) override;
virtual void VUpdate() override;
virtual void VScreenChanged() override;
private:
EXPORT void dtor_4450F0();
EXPORT GlukkonSwitch* vdtor_4450C0(s32 flags);
EXPORT void vScreenChange_4456D0();
EXPORT s16 PlayerNearMe_445180();
EXPORT void vUpdate_445200();
private:
s32 field_F4_tlvInfo;
s16 field_F8_state;
s16 field_FA_ok_id;
s16 field_FC_fail_id;
s16 field_FE;
s32 field_100_last_event_idx;
s16 field_104;
s16 field_106;
s16 field_108;
s16 field_10A;
s16 field_10C;
s16 field_10E;
s16 field_110;
s16 field_112;
s16 field_114;
s16 field_116;
PSX_Point field_118_top_left;
PSX_Point field_11C_bottom_right;
s32 field_120_timer;
};
ALIVE_ASSERT_SIZEOF(GlukkonSwitch, 0x124);
| 21.970149
| 77
| 0.722826
|
mouzedrift
|
815520972ed76917e4b879edc49e36e81193bf86
| 3,000
|
cpp
|
C++
|
libs/ledger/benchmark/transaction_verifier_bench.cpp
|
jinmannwong/ledger
|
f3b129c127e107603e08bb192eb695d23eb17dbc
|
[
"Apache-2.0"
] | null | null | null |
libs/ledger/benchmark/transaction_verifier_bench.cpp
|
jinmannwong/ledger
|
f3b129c127e107603e08bb192eb695d23eb17dbc
|
[
"Apache-2.0"
] | null | null | null |
libs/ledger/benchmark/transaction_verifier_bench.cpp
|
jinmannwong/ledger
|
f3b129c127e107603e08bb192eb695d23eb17dbc
|
[
"Apache-2.0"
] | 2
|
2019-11-13T10:55:24.000Z
|
2019-11-13T11:37:09.000Z
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI 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.
//
//------------------------------------------------------------------------------
#include "crypto/ecdsa.hpp"
#include "ledger/storage_unit/transaction_sinks.hpp"
#include "ledger/transaction_verifier.hpp"
#include "tx_generation.hpp"
#include "benchmark/benchmark.h"
#include <condition_variable>
#include <thread>
using fetch::ledger::TransactionVerifier;
using fetch::crypto::ECDSASigner;
namespace {
class DummySink : public fetch::ledger::TransactionSink
{
std::size_t const threshold_;
std::size_t count_{0};
std::mutex lock_;
std::condition_variable condition_;
public:
explicit DummySink(std::size_t threshold)
: threshold_(threshold)
{}
void OnTransaction(TransactionPtr const &) override
{
std::lock_guard<std::mutex> lock(lock_);
++count_;
if (count_ >= threshold_)
{
condition_.notify_all();
}
}
void Wait()
{
std::unique_lock<std::mutex> lock(lock_);
if (count_ >= threshold_)
{
return;
}
condition_.wait(lock);
}
};
void TransactionVerifierBench(benchmark::State &state)
{
// std::cout << "Tx Verification - threads: " << state.range(0) << " num txs: " << state.range(1)
// << std::endl;
// generate the transactions
ECDSASigner signer;
auto const txs = GenerateTransactions(static_cast<std::size_t>(state.range(1)), signer);
// wait for the
for (auto _ : state)
{
state.PauseTiming();
DummySink sink{txs.size()};
// needs to be created on the heap because of memory use
auto verifier = std::make_unique<TransactionVerifier>(sink, state.range(0), "Verifier");
// front load the verifier
for (auto const &tx : txs)
{
verifier->AddTransaction(tx);
}
verifier->Start();
state.ResumeTiming();
// wait for the
sink.Wait();
state.PauseTiming();
verifier->Stop();
}
}
void CreateRanges(benchmark::internal::Benchmark *b)
{
int const max_threads = static_cast<int>(std::thread::hardware_concurrency());
for (int i = 1; i <= max_threads; ++i)
{
b->Args({i, 1});
b->Args({i, 10});
b->Args({i, 100});
b->Args({i, 1000});
b->Args({i, 10000});
b->Args({i, 100000});
}
}
} // namespace
BENCHMARK(TransactionVerifierBench)->Apply(CreateRanges);
| 24.193548
| 100
| 0.621333
|
jinmannwong
|
8155e7d52a06d8b6d0e531bf59127373ec6dc468
| 2,883
|
hpp
|
C++
|
include/experimental/fundamental/v3/strong/mixins/modable.hpp
|
jwakely/std-make
|
f09d052983ace70cf371bb8ddf78d4f00330bccd
|
[
"BSL-1.0"
] | 105
|
2015-01-24T13:26:41.000Z
|
2022-02-18T15:36:53.000Z
|
include/experimental/fundamental/v3/strong/mixins/modable.hpp
|
jwakely/std-make
|
f09d052983ace70cf371bb8ddf78d4f00330bccd
|
[
"BSL-1.0"
] | 37
|
2015-09-04T06:57:10.000Z
|
2021-09-09T18:01:44.000Z
|
include/experimental/fundamental/v3/strong/mixins/modable.hpp
|
jwakely/std-make
|
f09d052983ace70cf371bb8ddf78d4f00330bccd
|
[
"BSL-1.0"
] | 23
|
2015-01-27T11:09:18.000Z
|
2021-10-04T02:23:30.000Z
|
// 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)
//
// Copyright (C) 2017 Vicente J. Botet Escriba
#ifndef JASEL_FUNDAMENTAL_V3_STRONG_MIXIN_MODABLE_HPP
#define JASEL_FUNDAMENTAL_V3_STRONG_MIXIN_MODABLE_HPP
#include <experimental/fundamental/v2/config.hpp>
#include <experimental/fundamental/v3/strong/mixins/is_compatible_with.hpp>
#include <experimental/type_traits.hpp>
#include <experimental/meta/v1/rebind.hpp>
namespace std
{
namespace experimental
{
inline namespace fundamental_v3
{
namespace mixin
{
template <class Final, class Check=no_check>
struct modable_assign
{
friend JASEL_MUTABLE_CONSTEXPR Final& operator%=(Final& x, Final const& y) noexcept
{
x._backdoor()._underlying() %= y.underlying();
return x;
}
};
template <class Final>
struct modable_assign<Final, check>
{
friend JASEL_MUTABLE_CONSTEXPR Final& operator%=(Final& x, Final const& y) noexcept
{
x = x % y;
return x;
}
};
// homogeneous
template <class Final, class Check=no_check>
struct modable : modable_assign<Final, Check>
{
friend constexpr Final operator%(Final const& x, Final const& y) noexcept
{
return Final(x.underlying() % y.underlying());
}
};
// heterogeneous
template <class Final, class Check=no_check, template <class, class> class Pred=is_compatible_with>
struct modable_with_if : modable_assign<Final, Check>
{
template <class Other, typename = enable_if_t<Pred<Final, Other>::value>>
friend constexpr common_type_t<Final, Other> operator%(Final const& x, Other const& y) noexcept
{
using CT = common_type_t<Final, Other>;
return CT(CT(x).underlying() % CT(y).underlying());
}
};
template <class Final, class UT=underlying_type_t<Final>>
struct modable_with
{
friend JASEL_MUTABLE_CONSTEXPR Final& operator%=(Final& x, UT const& y) noexcept
{
x._backdoor()._underlying() %= y;
return x;
}
template <class UT2
, typename = enable_if_t<is_convertible<UT2,UT>::value>
>
friend constexpr meta::rebind_t<Final, common_type_t<UT, UT2>> operator%(Final const& x, UT2 const& y) noexcept
{
using CR = common_type_t<UT, UT2>;
using CT = meta::rebind_t<Final, CR>;
return CT(CT(x).underlying() % CR(y));
}
};
}
namespace meta_mixin
{
template <class Check=mixin::no_check>
struct modable
{
template <class Final>
using type = mixin::modable<Final, Check>;
};
}
}
}
}
#endif // header
| 29.418367
| 120
| 0.624696
|
jwakely
|
81565cdc1fc074861d6e6bea8db445c3d2e785bd
| 5,991
|
cc
|
C++
|
src/core/agent/agent.cc
|
nicogno/biodynamo
|
f875994d4ea9aa07f938283719d5db83e450bfb8
|
[
"Apache-2.0"
] | null | null | null |
src/core/agent/agent.cc
|
nicogno/biodynamo
|
f875994d4ea9aa07f938283719d5db83e450bfb8
|
[
"Apache-2.0"
] | null | null | null |
src/core/agent/agent.cc
|
nicogno/biodynamo
|
f875994d4ea9aa07f938283719d5db83e450bfb8
|
[
"Apache-2.0"
] | null | null | null |
// -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & Newcastle University for the benefit of the
// BioDynaMo collaboration. 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include "core/agent/agent.h"
#include <algorithm>
#include <cassert>
#include <limits>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>
#include "core/agent/new_agent_event.h"
#include "core/behavior/behavior.h"
#include "core/environment/environment.h"
#include "core/execution_context/in_place_exec_ctxt.h"
#include "core/resource_manager.h"
#include "core/simulation.h"
#include "core/util/log.h"
#include "core/util/macros.h"
#include "core/util/root.h"
#include "core/util/type.h"
namespace bdm {
Agent::Agent() {
uid_ = Simulation::GetActive()->GetAgentUidGenerator()->GenerateUid();
}
Agent::Agent(TRootIOCtor* io_ctor) {}
Agent::Agent(const Agent& other)
: uid_(other.uid_),
box_idx_(other.box_idx_),
run_behavior_loop_idx_(other.run_behavior_loop_idx_),
propagate_staticness_neighborhood_(
other.propagate_staticness_neighborhood_),
is_static_next_ts_(other.is_static_next_ts_) {
for (auto* behavior : other.behaviors_) {
behaviors_.push_back(behavior->NewCopy());
}
}
Agent::~Agent() {
for (auto* el : behaviors_) {
delete el;
}
}
void Agent::Initialize(const NewAgentEvent& event) {
box_idx_ = event.existing_agent->GetBoxIdx();
// copy behaviors_ to me
InitializeBehaviors(event);
}
void Agent::Update(const NewAgentEvent& event) {
// Run displacement if a new agent has been created with an event.
SetPropagateStaticness();
UpdateBehaviors(event);
}
struct SetStaticnessForEachNeighbor
: public Functor<void, const Agent*, double> {
Agent* agent_;
explicit SetStaticnessForEachNeighbor(Agent* agent) : agent_(agent) {}
void operator()(const Agent* neighbor, double squared_distance) override {
double distance = agent_->GetDiameter() + neighbor->GetDiameter();
if (squared_distance < distance * distance) {
neighbor->SetStaticnessNextTimestep(false);
}
}
};
void Agent::PropagateStaticness() {
if (!Simulation::GetActive()->GetParam()->detect_static_agents) {
is_static_next_ts_ = false;
return;
}
if (!propagate_staticness_neighborhood_) {
return;
}
propagate_staticness_neighborhood_ = false;
is_static_next_ts_ = false;
auto* ctxt = Simulation::GetActive()->GetExecutionContext();
SetStaticnessForEachNeighbor for_each(this);
ctxt->ForEachNeighbor(for_each, *this);
}
void Agent::RunDiscretization() {}
void Agent::AssignNewUid() {
uid_ = Simulation::GetActive()->GetAgentUidGenerator()->GenerateUid();
}
const AgentUid& Agent::GetUid() const { return uid_; }
uint32_t Agent::GetBoxIdx() const { return box_idx_; }
void Agent::SetBoxIdx(uint32_t idx) { box_idx_ = idx; }
// ---------------------------------------------------------------------------
// Behaviors
void Agent::AddBehavior(Behavior* behavior) { behaviors_.push_back(behavior); }
void Agent::RemoveBehavior(const Behavior* behavior) {
for (unsigned int i = 0; i < behaviors_.size(); i++) {
if (behaviors_[i] == behavior) {
delete behavior;
behaviors_.erase(behaviors_.begin() + i);
// if behavior was before or at the current run_behavior_loop_idx_,
// correct it by subtracting one.
run_behavior_loop_idx_ -= i > run_behavior_loop_idx_ ? 0 : 1;
}
}
}
void Agent::RunBehaviors() {
for (run_behavior_loop_idx_ = 0; run_behavior_loop_idx_ < behaviors_.size();
++run_behavior_loop_idx_) {
auto* behavior = behaviors_[run_behavior_loop_idx_];
behavior->Run(this);
}
}
const InlineVector<Behavior*, 2>& Agent::GetAllBehaviors() const {
return behaviors_;
}
// ---------------------------------------------------------------------------
void Agent::RemoveFromSimulation() const {
Simulation::GetActive()->GetExecutionContext()->RemoveFromSimulation(uid_);
}
void Agent::InitializeBehaviors(const NewAgentEvent& event) {
const auto& existing_agent_behaviors = event.existing_agent->behaviors_;
event.new_behaviors.clear();
uint64_t cnt = 0;
for (auto* behavior : existing_agent_behaviors) {
if (behavior->WillBeCopied(event.GetUid())) {
event.new_behaviors.clear();
// collect new behaviors from other new agents
for (auto* nagent : event.new_agents) {
event.new_behaviors.push_back(nagent->behaviors_[cnt]);
}
event.existing_behavior = behavior;
auto* new_behavior = behavior->New();
new_behavior->Initialize(event);
behaviors_.push_back(new_behavior);
cnt++;
}
}
}
void Agent::UpdateBehaviors(const NewAgentEvent& event) {
// call event handler for behaviors
uint64_t cnt = 0;
for (auto* behavior : behaviors_) {
bool copied = behavior->WillBeCopied(event.GetUid());
if (!behavior->WillBeRemoved(event.GetUid())) {
event.new_behaviors.clear();
if (copied) {
for (auto* new_agent : event.new_agents) {
auto* new_behavior = new_agent->behaviors_[cnt];
event.new_behaviors.push_back(new_behavior);
}
}
behavior->Update(event);
}
cnt += copied ? 1 : 0;
}
// remove behaviors from current
for (auto it = behaviors_.begin(); it != behaviors_.end();) {
auto* behavior = *it;
if (behavior->WillBeRemoved(event.GetUid())) {
delete *it;
it = behaviors_.erase(it);
} else {
++it;
}
}
}
} // namespace bdm
| 29.512315
| 80
| 0.662494
|
nicogno
|
815ae20371c0116b8134b7129b40d82ae8af5617
| 1,501
|
cpp
|
C++
|
sliding-window-k-beauty/k_beauty.cpp
|
JBlakd/self-study
|
71cb86d43fe7f6514657958db0c0e81113bd4c43
|
[
"MIT"
] | null | null | null |
sliding-window-k-beauty/k_beauty.cpp
|
JBlakd/self-study
|
71cb86d43fe7f6514657958db0c0e81113bd4c43
|
[
"MIT"
] | null | null | null |
sliding-window-k-beauty/k_beauty.cpp
|
JBlakd/self-study
|
71cb86d43fe7f6514657958db0c0e81113bd4c43
|
[
"MIT"
] | null | null | null |
// leetcode 5299
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int divisorSubstrings(int num, int k) {
string num_str = to_string(num);
int left_idx = 0;
int right_idx = k - 1;
int ret = 0;
while (right_idx < num_str.length()) {
string sub_str = num_str.substr(left_idx, k);
int sub_int = stoi(sub_str, nullptr, 10);
// check sub_int validity
if (sub_int != 0) {
// check sub_int eligibility to score points
if (num % sub_int == 0) {
++ret;
}
}
++left_idx;
++right_idx;
}
return ret;
}
};
template <typename T>
void print_vector(vector<T> vec) {
cout << "{";
for (int i = 0; i < vec.size(); i++) {
cout << vec[i];
if (i != vec.size() - 1) {
cout << ", ";
}
}
cout << "}";
}
int main() {
Solution solution;
int num;
int k;
num = 999999999;
k = 2;
cout << solution.divisorSubstrings(num, k) << endl;
num = 1000000000;
k = 1;
cout << solution.divisorSubstrings(num, k) << endl;
num = 9;
k = 1;
cout << solution.divisorSubstrings(num, k) << endl;
num = 240;
k = 2;
cout << solution.divisorSubstrings(num, k) << endl;
num = 430043;
k = 2;
cout << solution.divisorSubstrings(num, k) << endl;
}
| 20.283784
| 60
| 0.493005
|
JBlakd
|
815e9ae379a22570ea25e9d67a9f837b57752d0f
| 12,042
|
cpp
|
C++
|
Source/COMImplementation.cpp
|
ntclark/Graphic
|
86acc119d172bb53c1666432538836b461d8a3f2
|
[
"BSD-3-Clause"
] | 12
|
2018-03-15T00:20:55.000Z
|
2021-08-11T10:02:15.000Z
|
Source/COMImplementation.cpp
|
ntclark/Graphic
|
86acc119d172bb53c1666432538836b461d8a3f2
|
[
"BSD-3-Clause"
] | null | null | null |
Source/COMImplementation.cpp
|
ntclark/Graphic
|
86acc119d172bb53c1666432538836b461d8a3f2
|
[
"BSD-3-Clause"
] | 2
|
2019-04-09T17:15:31.000Z
|
2020-12-05T19:52:59.000Z
|
// Copyright 2017 InnoVisioNate Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "Graphic.h"
#include "Graphic_resource.h"
#include "utils.h"
#include "GraphicControl_i.h"
#include "plot_i.c"
#include "axis_i.c"
#include "ViewSet_i.c"
#include "Properties_i.c"
#include "OpenGLImplementation_i.c"
#include "GraphicControl_i.c"
#include "Text_i.c"
#include "DataSet_i.c"
#include "Function_i.c"
#include "GSystem_i.c"
#include "Variable_i.h"
#include "Evaluator_i.h"
#include "Evaluator_i.c"
G *pStaticObject = NULL;
class GFactory : public IClassFactory {
public:
STDMETHOD (QueryInterface)(REFIID riid,void **ppv);
STDMETHOD_ (ULONG, AddRef)();
STDMETHOD_ (ULONG, Release)();
STDMETHOD (CreateInstance)(IUnknown *punkOuter, REFIID riid, void **ppv);
STDMETHOD (LockServer)(BOOL fLock);
GFactory(REFCLSID mg) : myGuid(mg) {};
~GFactory() {};
private:
GUID myGuid;
};
HMODULE hModule;
char szModuleName[1024];
BSTR bstrModuleName;
ITypeInfo* pITypeInfo_CLSID_G;
ITypeInfo* pITypeInfo_IG;
ITypeInfo* pITypeInfo_IGSFunctioNaterEvents;
unsigned short wsVersionMajor = 1;
unsigned short wsVersionMinor = 0;
long oleMisc = OLEMISC_ACTIVATEWHENVISIBLE | OLEMISC_SETCLIENTSITEFIRST | OLEMISC_INSIDEOUT |
OLEMISC_CANTLINKINSIDE | OLEMISC_RECOMPOSEONRESIZE | OLEMISC_ALWAYSRUN;
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppObject);
BOOL WINAPI DllMain(HANDLE module,ULONG flag,void *res) {
switch(flag) {
case DLL_PROCESS_ATTACH: {
hModule = reinterpret_cast<HMODULE>(module);
GetModuleFileName(hModule,szModuleName,1024);
bstrModuleName = SysAllocStringLen(NULL,(DWORD)strlen(szModuleName) + 1);
memset(bstrModuleName,0,(strlen(szModuleName) + 1) * sizeof(OLECHAR));
MultiByteToWideChar(CP_ACP,0,szModuleName,-1,bstrModuleName,(DWORD)strlen(szModuleName));
ITypeLib *ptLib;
LoadTypeLib(bstrModuleName,&ptLib);
HRESULT hr = ptLib -> GetTypeInfoOfGuid(CLSID_GSystemGraphic,&pITypeInfo_CLSID_G);
hr = ptLib -> GetTypeInfoOfGuid(IID_IGSGraphic,&pITypeInfo_IG);
{
char szLibrary[1026];
sprintf(szLibrary,"%s\\%ld",szModuleName,(long)FUNCTION_TYPELIB_ID);
BSTR bstrLibrary = SysAllocStringLen(NULL,256);
memset(bstrLibrary,0,strlen(szLibrary) + 1);
MultiByteToWideChar(CP_ACP,0,szLibrary,-1,bstrLibrary,(DWORD)strlen(szLibrary) + 1);
LoadTypeLib(bstrLibrary,&ptLib);
hr = ptLib -> GetTypeInfoOfGuid(DIID_IGSFunctioNaterEvents,&pITypeInfo_IGSFunctioNaterEvents);
SysFreeString(bstrLibrary);
}
}
break;
case DLL_PROCESS_DETACH:
SysFreeString(bstrModuleName);
break;
default:
break;
}
return TRUE;
}
char OBJECT_DESCRIPTION[][128] = {"InnoVisioNate Graphic Position And Size Properties",
"InnoVisioNate Graphic Style Properties",
"InnoVisioNate Graphic Background Properties",
"InnoVisioNate Graphic Text Properties",
"InnoVisioNate Graphic Lighting Properties",
"InnoVisioNate Graphic Axis Properties",
"InnoVisioNate Graphic Plot Properties",
"InnoVisioNate Graphic DataSet Properties",
"InnoVisioNate Graphic Function Properties"};
char OBJECT_NAME[][128] = {"InnoVisioNate.GraphicPropertiesPosSize",
"InnoVisioNate.GraphicPropertiesStyle",
"InnoVisioNate.GraphicPropertiesBackground",
"InnoVisioNate.GraphicPropertiesText",
"InnoVisioNate.GraphicPropertiesLighting",
"InnoVisioNate.GraphicPropertiesAxis",
"InnoVisioNate.GraphicPropertiesPlot",
"InnoVisioNate.GraphicPropertiesDataSets",
"InnoVisioNate.GraphicPropertiesFunctions"};
char OBJECT_NAME_V[][128] = {"InnoVisioNate.GraphicPropertiesPosSize.1",
"InnoVisioNate.GraphicPropertiesStyle.1",
"InnoVisioNate.GraphicPropertiesBackground.1",
"InnoVisioNate.GraphicPropertiesText.1",
"InnoVisioNate.GraphicPropertiesLighting.1",
"InnoVisioNate.GraphicPropertiesAxis.1",
"InnoVisioNate.GraphicPropertiesPlot.1",
"InnoVisioNate.GraphicPropertiesDataSets.1",
"InnoVisioNate.GraphicPropertiesFunctions.1"};
CLSID OBJECT_CLSID[] = {CLSID_GSystemGraphicPropertiesPosSize,
CLSID_GSystemGraphicPropertiesStyle,
CLSID_GSystemGraphicPropertiesBackground,
CLSID_GSystemGraphicPropertiesText,
CLSID_GSystemGraphicPropertiesLighting,
CLSID_GSystemGraphicPropertiesAxis,
CLSID_GSystemGraphicPropertiesPlot,
CLSID_GSystemGraphicPropertiesDataSets,
CLSID_GSystemGraphicPropertiesFunctions,
GUID_NULL};
static GFactory gFactory(CLSID_GSystemGraphic);
static GFactory propertyPagePosSize(OBJECT_CLSID[0]);
static GFactory propertyPageStyle(OBJECT_CLSID[1]);
static GFactory propertyPageBackground(OBJECT_CLSID[2]);
static GFactory propertyPageText(OBJECT_CLSID[3]);
static GFactory propertyPageLighting(OBJECT_CLSID[4]);
static GFactory propertyPageAxis(OBJECT_CLSID[5]);
static GFactory propertyPagePlot(OBJECT_CLSID[6]);
static GFactory propertyPageDataSets(OBJECT_CLSID[7]);
static GFactory propertyPageFunctions(OBJECT_CLSID[8]);
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppObject) {
*ppObject = NULL;
if ( rclsid == CLSID_GSystemGraphic )
return gFactory.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[0] )
return propertyPagePosSize.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[1] )
return propertyPageStyle.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[2] )
return propertyPageBackground.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[3] )
return propertyPageText.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[4] )
return propertyPageLighting.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[5] )
return propertyPageAxis.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[6] )
return propertyPagePlot.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[7] )
return propertyPageDataSets.QueryInterface(riid,ppObject);
if ( rclsid == OBJECT_CLSID[8] )
return propertyPageFunctions.QueryInterface(riid,ppObject);
return E_NOINTERFACE;
}
STDAPI DllRegisterServer() {
utilsDllRegisterTypeLib(bstrModuleName);
{
char szLibrary[1026];
sprintf(szLibrary,"%s\\%ld",szModuleName,(long)GSYSTEMS_TYPELIB_ID);
BSTR bstrLibrary = SysAllocStringLen(NULL,256);
memset(bstrLibrary,0,strlen(szLibrary) + 1);
MultiByteToWideChar(CP_ACP,0,szLibrary,-1,bstrLibrary,(DWORD)strlen(szLibrary) + 1);
utilsDllRegisterTypeLib(bstrLibrary);
utilsDllRegisterObject(CLSID_GSystems,LIBID_GSystems,hModule,szModuleName,"InnoVisioNate Graphic Common Definitions Type Library","InnoVisioNate.GraphicCommonDefinitions","InnoVisioNate.GraphicCommonDefinitions.1",
(CATID *)NULL,0,oleMisc,false,false,true);
}
for ( long objIndex = 0; 1; objIndex++ ) {
if ( GUID_NULL == OBJECT_CLSID[objIndex] )
break;
utilsDllRegisterObject(OBJECT_CLSID[objIndex],LIBID_Graphic,hModule,szModuleName,OBJECT_DESCRIPTION[objIndex],OBJECT_NAME[objIndex],OBJECT_NAME_V[objIndex],
(CATID *)NULL,0,0,false,false,false);
}
return utilsDllRegisterObject(CLSID_GSystemGraphic,LIBID_Graphic,hModule,szModuleName,"InnoVisioNate Graphic Object","InnoVisioNate.Graphic","InnoVisioNate.Graphic.1",
(CATID *)NULL,IDOCXBITMAP_GRAPHIC,oleMisc,false,false,true);//IDOCXBITMAP_GRAPHIC,oleMisc,true,true,true);
}
STDAPI DllUnregisterServer() {
for ( long objIndex = 0; 1; objIndex++ ) {
if ( GUID_NULL == OBJECT_CLSID[objIndex] )
break;
utilsDllUnregisterObject(OBJECT_CLSID[objIndex],OBJECT_NAME[objIndex],OBJECT_NAME_V[objIndex]);
}
utilsDllUnregisterObject(CLSID_GSystemGraphic,"InnoVisioNate.Graphic","InnoVisioNate.Graphic.1");
return utilsDllUnregisterTypeLib(bstrModuleName,LIBID_Graphic,wsVersionMajor,wsVersionMinor);
}
long __stdcall GFactory::QueryInterface(REFIID iid, void **ppv) {
*ppv = NULL;
if ( iid == IID_IUnknown || iid == IID_IClassFactory )
*ppv = this;
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
unsigned long __stdcall GFactory::AddRef() { return 1; }
unsigned long __stdcall GFactory::Release() { return 1; }
HRESULT STDMETHODCALLTYPE GFactory::CreateInstance(IUnknown *punkOuter, REFIID riid, void **ppv) {
*ppv = NULL;
#if 1
if ( ! pStaticObject )
pStaticObject = new G(punkOuter);
if ( CLSID_GSystemGraphic == myGuid )
return pStaticObject -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[0] == myGuid )
return pStaticObject -> PropertyPage(0) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[1] == myGuid )
return pStaticObject -> PropertyPage(1) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[2] == myGuid )
return pStaticObject -> PropertyPage(2) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[3] == myGuid )
return pStaticObject -> PropertyPage(3) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[4] == myGuid )
return pStaticObject -> PropertyPage(4) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[5] == myGuid )
return pStaticObject -> PropertyPage(5) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[6] == myGuid )
return pStaticObject -> PropertyPage(6) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[8] == myGuid )
return pStaticObject -> PropertyPage(7) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[7] == myGuid )
return pStaticObject -> PropertyPage(8) -> QueryInterface(riid,ppv);
delete pStaticObject;
pStaticObject = NULL;
#else
G *pG = new G(punkOuter);
if ( CLSID_GSystemGraphic == myGuid )
return pG -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[0] == myGuid )
return pG -> PropertyPage(0) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[1] == myGuid )
return pG -> PropertyPage(1) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[2] == myGuid )
return pG -> PropertyPage(2) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[3] == myGuid )
return pG -> PropertyPage(3) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[4] == myGuid )
return pG -> PropertyPage(4) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[5] == myGuid )
return pG -> PropertyPage(5) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[6] == myGuid )
return pG -> PropertyPage(6) -> QueryInterface(riid,ppv);
if ( OBJECT_CLSID[7] == myGuid )
return pG -> PropertyPage(7) -> QueryInterface(riid,ppv);
delete pG;
#endif
return E_NOINTERFACE;
}
long __stdcall GFactory::LockServer(int fLock) {
return S_OK;
}
| 34.904348
| 217
| 0.651138
|
ntclark
|
81612eb31bdb3db545391da8d8739e7586b5431a
| 774
|
h++
|
C++
|
include/ogonek/encoding/latin8.h++
|
libogonek/ogonek
|
46b7edbf6b7ff89892f5ba25494749b442e771b3
|
[
"CC0-1.0"
] | 25
|
2016-10-21T12:37:23.000Z
|
2021-02-22T05:46:46.000Z
|
include/ogonek/encoding/latin8.h++
|
libogonek/ogonek
|
46b7edbf6b7ff89892f5ba25494749b442e771b3
|
[
"CC0-1.0"
] | null | null | null |
include/ogonek/encoding/latin8.h++
|
libogonek/ogonek
|
46b7edbf6b7ff89892f5ba25494749b442e771b3
|
[
"CC0-1.0"
] | 4
|
2016-09-05T10:23:18.000Z
|
2020-07-09T19:37:37.000Z
|
// Ogonek
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// This file was automatically generated on 2013-11-14T13:59:12.471007Z
// Latin-8 encoding form
#ifndef OGONEK_LATIN8_HPP
#define OGONEK_LATIN8_HPP
#include <ogonek/encoding/iso8859_14.h++>
namespace ogonek {
using latin8 = iso8859_14;
} // namespace ogonek
#endif // OGONEK_LATIN8_HPP
| 29.769231
| 96
| 0.760982
|
libogonek
|
816205c61617c3e8db42dbde5b15524a5b18120a
| 2,323
|
cpp
|
C++
|
POJ/1077.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 6
|
2019-09-30T16:11:00.000Z
|
2021-11-01T11:42:33.000Z
|
POJ/1077.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 4
|
2017-11-21T08:17:42.000Z
|
2020-07-28T12:09:52.000Z
|
POJ/1077.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 4
|
2017-07-26T05:54:06.000Z
|
2020-09-30T13:35:38.000Z
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#define P 362880
using namespace std;
inline bool isNum(char c){
return c>='0'&&c<='9';
}
int prev[P],est[P],mat[3][3],que[P],qtop=1,fac[10],ktop=0,mx[4]={0,0,1,-1},my[4]={1,-1,0,0};
char move[P],mc[]="rldu",stk[P];
inline bool valid(int x,int y){
return x>=0&&x<3&&y>=0&&y<3;
}
inline int abs(int a){
return a>0?a:-a;
}
inline int estimate(){
int ret=0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
ret+=abs((mat[i][j]-1)/3-i)+abs((mat[i][j]-1)%3-j);
}
}
return ret;
}
inline int encode(){
int *num=*mat,hash=0;
for(int i=0,cnt;i<9;i++){
cnt=num[i]-1;
for(int j=0;j<i;j++){
if(num[j]<num[i]){
cnt--;
}
}
hash+=cnt*fac[8-i];
}
return hash;
}
inline void decode(int hash){
int *num=*mat;
bool exist[10]={0};
for(int i=0,rank;i<9;i++){
rank=hash/fac[8-i];
num[i]=0;
for(int j=0;j<=rank;j++){
while(exist[++num[i]]);
}
exist[num[i]]=true;
hash%=fac[8-i];
}
}
inline void push(int x){
est[x]=estimate();
que[qtop]=x;
for(int i=qtop++;i>1;i>>=1){
if(est[que[i>>1]]>est[x]){
swap(que[i],que[i>>1]);
}else{
break;
}
}
}
inline int pop(){
for(int i=--qtop,j=1;i!=j;){
swap(que[i],que[j]);
i=j;
if((i<<1)<qtop&&est[que[i<<1]]<est[que[j]]){
j=(i<<1);
}
if(((i<<1)|1)<qtop&&est[que[(i<<1)|1]]<est[que[j]]){
j=((i<<1)|1);
}
}
return que[qtop];
}
inline void blank(int &x,int &y){
for(x=0;x<3;x++){
for(y=0;y<3;y++){
if(mat[x][y]==9){
return;
}
}
}
}
int main(){
memset(prev,-1,sizeof(prev));
fac[0]=1;
for(int i=1;i<=9;i++){
fac[i]=fac[i-1]*i;
}
char c;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cin>>c;
if(isNum(c)){
mat[i][j]=c-'0';
}else{
mat[i][j]=9;
}
}
}
int hash=encode(),x,y,to;
prev[hash]=-2;
push(hash);
while(qtop>1){
hash=pop();
if(hash==0){
while(prev[hash]!=-2){
stk[ktop++]=move[hash];
hash=prev[hash];
}
while(ktop--){
putchar(stk[ktop]);
}
return 0;
}
decode(hash);
blank(x,y);
for(int i=0,tx,ty;i<4;i++){
tx=x+mx[i],ty=y+my[i];
if(valid(tx,ty)){
swap(mat[x][y],mat[tx][ty]);
to=encode();
if(prev[to]==-1){
prev[to]=hash;
move[to]=mc[i];
push(to);
}
swap(mat[x][y],mat[tx][ty]);
}
}
}
printf("unsolvable");
}
| 17.080882
| 92
| 0.510977
|
sshockwave
|
8163d5f8c2685debf06fa35207119c642b0aa02c
| 798
|
cpp
|
C++
|
Chapter 5/5.15_dowhile.cpp
|
Reavolt/Cpp-Primer-Plus
|
491876ca0808d55cb688d575ec4688b087387810
|
[
"Unlicense"
] | 3
|
2021-10-04T11:59:10.000Z
|
2022-01-05T22:26:12.000Z
|
Chapter 5/5.15_dowhile.cpp
|
Reavolt/Cpp-Primer-Plus
|
491876ca0808d55cb688d575ec4688b087387810
|
[
"Unlicense"
] | null | null | null |
Chapter 5/5.15_dowhile.cpp
|
Reavolt/Cpp-Primer-Plus
|
491876ca0808d55cb688d575ec4688b087387810
|
[
"Unlicense"
] | 3
|
2021-08-02T02:44:22.000Z
|
2022-03-26T02:01:34.000Z
|
//dowhile.срр -- цикл с проверкой на выходе
//#include "stdafx.h" --- Visual Studio --- precompiled headers
#include <iostream>
using namespace std;
//-------------------------------------------------------------------------------------------------
int main()
{
int n = 0;
cout << "Enter numbers in the range 1-10 to find ";
cout << "my favorite number\n"; // запрос на ввод любимого числа из диапазона 1-10
do
{
cin >> n; // выполнить тело
} while (n != 7); // затем проверить
cout << "Yes, 7 is my favorite. \n"; // любимое число - 7
std::cin.get();
std::cin.get();
return 0;
}
//-------------------------------------------------------------------------------------------------
/*
Enter numbers in the range 1-10 to find my favorite number
9
4
7
Yes, 7 is my favorite.
*/
| 26.6
| 99
| 0.47619
|
Reavolt
|
81650aa5878731a95b49b50d3aa3b807777eeac1
| 366
|
cpp
|
C++
|
src/fft_x86_sse2.cpp
|
mzient/genFFT
|
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
|
[
"BSD-2-Clause"
] | 3
|
2019-10-30T11:17:32.000Z
|
2019-11-04T16:38:37.000Z
|
src/fft_x86_sse2.cpp
|
mzient/genFFT
|
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
|
[
"BSD-2-Clause"
] | null | null | null |
src/fft_x86_sse2.cpp
|
mzient/genFFT
|
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
|
[
"BSD-2-Clause"
] | null | null | null |
#include <cassert>
#include <emmintrin.h>
#include <genFFT/FFTLevel.h>
#include <genFFT/generic/fft_impl_generic.h>
#include "dispatch_helper.h"
namespace genfft {
IMPORT_NAMESPACE(impl_SSE)
namespace impl_SSE2 {
#include <genFFT/x86/fft_double_impl_x86.inl>
#include <genFFT/x86/fft_dit_impl_x86.inl>
DISPATCH(double)
FORWARD(float, impl_SSE)
}
}
| 21.529412
| 49
| 0.756831
|
mzient
|
816aed1ebb3920dce591752730238c1175d0ea92
| 6,465
|
cc
|
C++
|
gazebo/physics/ode/ODEMultiRayShape.cc
|
otamachan/ros-indigo-gazebo7-deb
|
abc6b40247cdce14d9912096a0ad5135d420ce04
|
[
"ECL-2.0",
"Apache-2.0"
] | 5
|
2017-07-14T19:36:51.000Z
|
2020-04-01T06:47:59.000Z
|
gazebo/physics/ode/ODEMultiRayShape.cc
|
otamachan/ros-indigo-gazebo7-deb
|
abc6b40247cdce14d9912096a0ad5135d420ce04
|
[
"ECL-2.0",
"Apache-2.0"
] | 20
|
2017-07-20T21:04:49.000Z
|
2017-10-19T19:32:38.000Z
|
gazebo/physics/ode/ODEMultiRayShape.cc
|
otamachan/ros-indigo-gazebo7-deb
|
abc6b40247cdce14d9912096a0ad5135d420ce04
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* 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 "gazebo/common/Assert.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/physics/World.hh"
#include "gazebo/physics/ode/ODETypes.hh"
#include "gazebo/physics/ode/ODELink.hh"
#include "gazebo/physics/ode/ODECollision.hh"
#include "gazebo/physics/ode/ODEPhysics.hh"
#include "gazebo/physics/ode/ODERayShape.hh"
#include "gazebo/physics/ode/ODEMultiRayShape.hh"
using namespace gazebo;
using namespace physics;
//////////////////////////////////////////////////
ODEMultiRayShape::ODEMultiRayShape(CollisionPtr _parent)
: MultiRayShape(_parent)
{
this->SetName("ODE Multiray Shape");
// Create a space to contain the ray space
this->superSpaceId = dSimpleSpaceCreate(0);
// Create a space to contain all the rays
this->raySpaceId = dSimpleSpaceCreate(this->superSpaceId);
// Set collision bits
dGeomSetCategoryBits((dGeomID) this->raySpaceId, GZ_SENSOR_COLLIDE);
dGeomSetCollideBits((dGeomID) this->raySpaceId, ~GZ_SENSOR_COLLIDE);
// These three lines may be unessecary
ODELinkPtr pLink =
boost::static_pointer_cast<ODELink>(this->collisionParent->GetLink());
pLink->SetSpaceId(this->raySpaceId);
boost::static_pointer_cast<ODECollision>(this->collisionParent)->SetSpaceId(
this->raySpaceId);
}
//////////////////////////////////////////////////
ODEMultiRayShape::~ODEMultiRayShape()
{
dSpaceSetCleanup(this->raySpaceId, 0);
dSpaceDestroy(this->raySpaceId);
dSpaceSetCleanup(this->superSpaceId, 0);
dSpaceDestroy(this->superSpaceId);
}
//////////////////////////////////////////////////
void ODEMultiRayShape::UpdateRays()
{
ODEPhysicsPtr ode = boost::dynamic_pointer_cast<ODEPhysics>(
this->GetWorld()->GetPhysicsEngine());
if (ode == NULL)
gzthrow("Invalid physics engine. Must use ODE.");
// Do we need to lock the physics engine here? YES!
// especially when spawning models with sensors
{
boost::recursive_mutex::scoped_lock lock(*ode->GetPhysicsUpdateMutex());
// Do collision detection
dSpaceCollide2((dGeomID) (this->superSpaceId),
(dGeomID) (ode->GetSpaceId()),
this, &UpdateCallback);
}
}
//////////////////////////////////////////////////
void ODEMultiRayShape::UpdateCallback(void *_data, dGeomID _o1, dGeomID _o2)
{
dContactGeom contact;
ODEMultiRayShape *self = NULL;
self = static_cast<ODEMultiRayShape*>(_data);
// Check space
if (dGeomIsSpace(_o1) || dGeomIsSpace(_o2))
{
if (dGeomGetSpace(_o1) == self->superSpaceId ||
dGeomGetSpace(_o2) == self->superSpaceId)
dSpaceCollide2(_o1, _o2, self, &UpdateCallback);
if (dGeomGetSpace(_o1) == self->raySpaceId ||
dGeomGetSpace(_o2) == self->raySpaceId)
dSpaceCollide2(_o1, _o2, self, &UpdateCallback);
}
else
{
ODECollision *collision1 = NULL;
ODECollision *collision2 = NULL;
// Get pointers to the underlying collisions
if (dGeomGetClass(_o1) == dGeomTransformClass)
{
collision1 = static_cast<ODECollision*>(
dGeomGetData(dGeomTransformGetGeom(_o1)));
}
else
collision1 = static_cast<ODECollision*>(dGeomGetData(_o1));
if (dGeomGetClass(_o2) == dGeomTransformClass)
{
collision2 =
static_cast<ODECollision*>(dGeomGetData(dGeomTransformGetGeom(_o2)));
}
else
{
collision2 = static_cast<ODECollision*>(dGeomGetData(_o2));
}
GZ_ASSERT(collision1, "collision1 is null");
GZ_ASSERT(collision2, "collision2 is null");
ODECollision *rayCollision = NULL;
ODECollision *hitCollision = NULL;
// Figure out which one is a ray; note that this assumes
// that the ODE dRayClass is used *soley* by the RayCollision.
if (dGeomGetClass(_o1) == dRayClass)
{
rayCollision = static_cast<ODECollision*>(collision1);
hitCollision = static_cast<ODECollision*>(collision2);
dGeomRaySetParams(_o1, 0, 0);
dGeomRaySetClosestHit(_o1, 1);
}
else if (dGeomGetClass(_o2) == dRayClass)
{
GZ_ASSERT(rayCollision == NULL, "rayCollision is not null");
rayCollision = static_cast<ODECollision*>(collision2);
hitCollision = static_cast<ODECollision*>(collision1);
dGeomRaySetParams(_o2, 0, 0);
dGeomRaySetClosestHit(_o2, 1);
}
// Check for ray/collision intersections
if (rayCollision && hitCollision)
{
int n = dCollide(_o1, _o2, 1, &contact, sizeof(contact));
if (n > 0)
{
RayShapePtr shape = boost::static_pointer_cast<RayShape>(
rayCollision->GetShape());
if (contact.depth < shape->GetLength())
{
// gzerr << "ODEMultiRayShape UpdateCallback dSpaceCollide2 "
// << " depth[" << contact.depth << "]"
// << " position[" << contact.pos[0]
// << ", " << contact.pos[1]
// << ", " << contact.pos[2]
// << ", " << "]"
// << " ray[" << rayCollision->GetScopedName() << "]"
// << " pose[" << rayCollision->GetWorldPose() << "]"
// << " hit[" << hitCollision->GetScopedName() << "]"
// << " pose[" << hitCollision->GetWorldPose() << "]"
// << "\n";
shape->SetLength(contact.depth);
shape->SetRetro(hitCollision->GetLaserRetro());
}
}
}
}
}
//////////////////////////////////////////////////
void ODEMultiRayShape::AddRay(const math::Vector3 &_start,
const math::Vector3 &_end)
{
MultiRayShape::AddRay(_start, _end);
ODECollisionPtr odeCollision(new ODECollision(
this->collisionParent->GetLink()));
odeCollision->SetName("ode_ray_collision");
odeCollision->SetSpaceId(this->raySpaceId);
ODERayShapePtr ray(new ODERayShape(odeCollision));
odeCollision->SetShape(ray);
ray->SetPoints(_start, _end);
this->rays.push_back(ray);
}
| 32.164179
| 78
| 0.640217
|
otamachan
|
816b538263135a1f49f0ba597bdb487b03ba8431
| 121,998
|
cpp
|
C++
|
scripts/dp88_ar.cpp
|
TheUnstoppable/RenSharp
|
2a123c6018c18f3fc73501737d600e291ac3afa7
|
[
"Apache-2.0"
] | 1
|
2021-10-04T02:36:30.000Z
|
2021-10-04T02:36:30.000Z
|
scripts/dp88_ar.cpp
|
TheUnstoppable/RenSharp
|
2a123c6018c18f3fc73501737d600e291ac3afa7
|
[
"Apache-2.0"
] | null | null | null |
scripts/dp88_ar.cpp
|
TheUnstoppable/RenSharp
|
2a123c6018c18f3fc73501737d600e291ac3afa7
|
[
"Apache-2.0"
] | null | null | null |
/* Renegade Scripts.dll
Copyright 2017 Tiberian Technologies
This file is part of the Renegade scripts.dll
The Renegade scripts.dll is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version. See the file COPYING for more details.
In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
Only the source code to the module(s) containing the licenced code has to be released.
*/
// Include files
#include "general.h"
#include "scripts.h"
#include "engine.h"
#include "dp88_ar.h"
#include "ms.h"
#include "Definition.h"
#include "PurchaseSettingsDefClass.h"
#include "SoldierGameObj.h"
#include "VehicleGameObj.h"
#include "VehicleGameObjDef.h"
#include "MoveablePhysClass.h"
#include "SList.h"
#include "OffenseObjectClass.h"
#include "WeaponBagClass.h"
/*------------------------
Game Controller
--------------------------*/
dp88_AR_GameController::dp88_AR_GameController()
{
created = false;
team0_countryID = 0;
team1_countryID = 0;
mirageTank_disguisePresets[0] = 0;
mirageTank_disguisePresets[1] = 0;
mirageTank_disguisePresets[2] = 0;
}
// -------------------------------------------------------------------------------------------------
dp88_AR_GameController::~dp88_AR_GameController()
{}
void dp88_AR_GameController::Created( GameObject *obj )
{
dp88_Camo_Controller::Created(obj);
//Console_Output ( "Created dp88_AR_GameController\n" );
created = true;
// Check we have not disabled all soviet countries
if ( Get_Int_Parameter ( "enableCountry_Russia" ) == 0
&& Get_Int_Parameter ( "enableCountry_Cuba" ) == 0
&& Get_Int_Parameter ( "enableCountry_Iraq" ) == 0
&& Get_Int_Parameter ( "enableCountry_Libya" ) == 0 )
{
Console_Input ( "msg GAME CONTROLLER ERROR: All Soviet countries are disabled, defaulting to Russia!" );
team0_countryID = 1;
}
// Check we have not disabled all allied countries
if ( Get_Int_Parameter ( "enableCountry_America" ) == 0
&& Get_Int_Parameter ( "enableCountry_France" ) == 0
&& Get_Int_Parameter ( "enableCountry_Germany" ) == 0
&& Get_Int_Parameter ( "enableCountry_GreatBritain" ) == 0
&& Get_Int_Parameter ( "enableCountry_Korea" ) == 0 )
{
Console_Input ( "msg GAME CONTROLLER ERROR: All Allied countries are disabled, defaulting to America!" );
team1_countryID = 1;
}
// Loop around until we get a non-disabled country ID for Soviets
while ( team0_countryID == 0 )
{
team0_countryID = (short)Commands->Get_Random_Int ( 1, 5 ); // Soviet, 1 to 4
if ( team0_countryID == 1 && Get_Int_Parameter ( "enableCountry_Russia" ) == 0 )
team0_countryID = 0;
else if ( team0_countryID == 2 && Get_Int_Parameter ( "enableCountry_Cuba" ) == 0 )
team0_countryID = 0;
else if ( team0_countryID == 3 && Get_Int_Parameter ( "enableCountry_Iraq" ) == 0 )
team0_countryID = 0;
else if ( team0_countryID == 4 && Get_Int_Parameter ( "enableCountry_Libya" ) == 0 )
team0_countryID = 0;
}
// Loop around until we get a non-disabled country ID for Allies
while ( team1_countryID == 0 )
{
team1_countryID = (short)Commands->Get_Random_Int ( 1, 5 ); // Allies, 1 to 5
if ( team1_countryID == 1 && Get_Int_Parameter ( "enableCountry_America" ) == 0 )
team1_countryID = 0;
else if ( team1_countryID == 2 && Get_Int_Parameter ( "enableCountry_France" ) == 0 )
team1_countryID = 0;
else if ( team1_countryID == 3 && Get_Int_Parameter ( "enableCountry_Germany" ) == 0 )
team1_countryID = 0;
else if ( team1_countryID == 4 && Get_Int_Parameter ( "enableCountry_GreatBritain" ) == 0 )
team1_countryID = 0;
else if ( team1_countryID == 5 && Get_Int_Parameter ( "enableCountry_Korea" ) == 0 )
team1_countryID = 0;
}
// Output Soviet country name and cmsg the team what their special ability is
StringClass countriesMessage ( "The Soviets are playing as ", true );
StringClass sovietCountryMessage ( true );
StringClass alliedCountryMessage ( true );
switch ( team0_countryID )
{
case 1:
countriesMessage += "Russia";
sovietCountryMessage = "As the Russians you can use the powerful Tesla Tank to wipe out those allied scum!";
break;
case 2:
countriesMessage += "Cuba";
sovietCountryMessage = "As the Cubans you can use the insane but deadly Terrorist to bomb your enemies!";
break;
case 3:
countriesMessage += "Iraq";
sovietCountryMessage = "As the Iraqis you can use the deadly Desolator to irradiate the allied scum!";
break;
case 4:
countriesMessage += "Libya";
sovietCountryMessage = "As the Libiyans you can use the deadly Demolition Truck to destroy enemy forces!";
break;
}
// Output Allied country name and cmsg the team what their special ability is
countriesMessage += " and the Allies are playing as ";
switch ( team1_countryID )
{
case 1:
countriesMessage += "America";
alliedCountryMessage = "As the Americans you can use paradrops to surprise the Soviet forces!";
break;
case 2:
countriesMessage += "France";
alliedCountryMessage = "As the French your base is well defended by the powerful Grand Cannon";
break;
case 3:
countriesMessage += "Germany";
alliedCountryMessage = "As the Germans you can use the Tank Destroyer to easily wipe out Soviet tanks.";
break;
case 4:
countriesMessage += "Great Britain";
alliedCountryMessage = "As the British you can use snipers to pick off enemy infantry from distance";
break;
case 5:
countriesMessage += "Korea";
alliedCountryMessage = "As the Koreans you can use Black Eagles to rain death from the skies!";
break;
}
// Send public countries message and team country messages
Send_Message ( 255,255,255, countriesMessage.Peek_Buffer() );
Send_Message_Team( 0, 255,69,0, sovietCountryMessage.Peek_Buffer() );
Send_Message_Team( 1, 30,114,255, alliedCountryMessage.Peek_Buffer() );
// Get mirage tank disguise preset names
const char* mtDisguise = Get_Parameter( "MirageTank_disguisePreset_1" );
if ( strcmp ( mtDisguise, "null" ) != 0 && Is_Valid_Preset ( mtDisguise ) )
{
mirageTank_disguisePresets[0] = new char[strlen(mtDisguise)+1];
strcpy ( mirageTank_disguisePresets[0], mtDisguise );
}
mtDisguise = Get_Parameter( "MirageTank_disguisePreset_2" );
if ( strcmp ( mtDisguise, "null" ) != 0 && Is_Valid_Preset ( mtDisguise ) )
{
mirageTank_disguisePresets[1] = new char[strlen(mtDisguise)+1];
strcpy ( mirageTank_disguisePresets[1], mtDisguise );
}
mtDisguise = Get_Parameter( "MirageTank_disguisePreset_3" );
if ( strcmp ( mtDisguise, "null" ) != 0 && Is_Valid_Preset ( mtDisguise ) )
{
mirageTank_disguisePresets[2] = new char[strlen(mtDisguise)+1];
strcpy ( mirageTank_disguisePresets[2], mtDisguise );
}
}
void dp88_AR_GameController::Custom ( GameObject *obj, int type, int param, GameObject *sender )
{
}
void dp88_AR_GameController::Timer_Expired( GameObject *obj, int number )
{
}
void dp88_AR_GameController::Destroyed ( GameObject* obj )
{
// Clean up memory for Mirage Tank disguises
if ( mirageTank_disguisePresets[0] != NULL )
{
delete [] mirageTank_disguisePresets[0];
mirageTank_disguisePresets[0] = NULL;
}
if ( mirageTank_disguisePresets[1] != NULL )
{
delete [] mirageTank_disguisePresets[1];
mirageTank_disguisePresets[1] = NULL;
}
if ( mirageTank_disguisePresets[2] != NULL )
{
delete [] mirageTank_disguisePresets[2];
mirageTank_disguisePresets[2] = NULL;
}
}
/*------------------------
Default script for all vehicles in AR
--------------------------*/
void dp88_AR_Vehicle::Created(GameObject *obj)
{
//Console_Output ( "Created dp88_AR_Vehicle\n" );
pilotID = 0;
attackingTerrorDroneID = 0;
dead = false;
}
void dp88_AR_Vehicle::Killed( GameObject *obj, GameObject *killer )
{
/*dead = true;
// If we have a pilot make sure they know they are no longer a pilot
if ( pilotID != 0 )
{
Commands->Send_Custom_Event( obj,Commands->Find_Object(pilotID),CUSTOM_PILOTED_VEHICLE_ID,0,0 );
pilotID = 0;
}
// If a Terror Drone is attacking us let them know we died...
if ( attackingTerrorDroneID != 0 )
{
Commands->Send_Custom_Event( obj,Commands->Find_Object(attackingTerrorDroneID),CUSTOM_TD_TARGET_DIED,0,0 );
attackingTerrorDroneID = 0;
}*/
}
void dp88_AR_Vehicle::Custom( GameObject *obj, int type, int param, GameObject *sender )
{/*
// Look for vehicle entry
if ( type == CUSTOM_EVENT_VEHICLE_ENTERED )
{
if ( pilotID == 0 )
{
pilotID = Commands->Get_ID(sender);
// Send a custom to the driver to make their scripts work properly in
// vehicle mode, and give them our ID. They will report their veterancy level
// in return, if nessicary.
Commands->Send_Custom_Event( obj, sender, CUSTOM_PILOTED_VEHICLE_ID, Commands->Get_ID(obj), 0 );
}
}
// Look for vehicle exit
else if ( type == CUSTOM_EVENT_VEHICLE_EXITED )
{
if ( Commands->Get_ID(sender) == pilotID )
{
pilotID = 0;
// Send a custom to the driver to let them know they got out
Commands->Send_Custom_Event( obj, sender, CUSTOM_PILOTED_VEHICLE_ID, 0, 0 );
}
}
// Look for a message from the attacking terror drone telling us it died
else if ( type == CUSTOM_TD_TD_DIED )
{
attackingTerrorDroneID = 0;
}*/
}
void dp88_AR_Vehicle::Timer_Expired( GameObject *obj, int number )
{
// Terror Drone damage timer
/*if ( number == TIMER_TD_DO_DAMAGE )
{
if ( attackingTerrorDroneID != 0 && !dead )
{
Commands->Apply_Damage( obj, 40.0, "Steel", Get_Vehicle_Driver ( Commands->Find_Object( attackingTerrorDroneID ) ) );
Commands->Start_Timer( obj, this, 1.0f, TIMER_TD_DO_DAMAGE );
}
}*/
}
void dp88_AR_Vehicle::Damaged(GameObject *obj, GameObject *damager, float amount)
{
// If damage is repairing, and we are being attacked by a TD, kill the TD
/*if ( amount < 0 && attackingTerrorDroneID != 0 )
Commands->Send_Custom_Event( obj, Commands->Find_Object(attackingTerrorDroneID), CUSTOM_TD_TARGET_REPAIRED, 1, 0 );
// If the damage is from the Terror Drone gun set the attacker and start anim
// Can only be attacked by one TD at a time, and only by opposite team
const static char *TD_Comparison = "Terror Drone";
if ( strstr( Commands->Get_Preset_Name( Get_Vehicle(damager) ), TD_Comparison ) != NULL
&& ( Get_Object_Type(damager) != Get_Object_Type(obj) )
&& attackingTerrorDroneID == 0
&& !dead )
{
attackingTerrorDroneID = Commands->Get_ID( Get_Vehicle(damager) );
Commands->Send_Custom_Event( obj, Get_Vehicle(damager), CUSTOM_TD_TARGET_ID, 1, 0 );
Commands->Set_Animation( obj, Get_Parameter("TD_attack_animName"), false, 0, Get_Float_Parameter("TD_attack_firstFrame"), Get_Float_Parameter("TD_attack_lastFrame"), false );
Commands->Start_Timer( obj, this, 0.1f, TIMER_TD_DO_DAMAGE );
}*/
}
void dp88_AR_Vehicle::Animation_Complete ( GameObject *obj, const char *animation_name )
{
// Restart TD Attack Anim
/*if ( attackingTerrorDroneID != 0 )
Commands->Set_Animation( obj, Get_Parameter("TD_attack_animName"), false, 0, Get_Float_Parameter("TD_attack_firstFrame"), Get_Float_Parameter("TD_attack_lastFrame"), false );
*/
}
/*------------------------
Deployable Infantry scripts
--------------------------*/
void dp88_AR_Deployable_Infantry::Created( GameObject *obj )
{
//Console_Output ( "Created dp88_AR_Deployable_Infantry\n" );
objectID = Commands->Get_ID ( obj );
deployed = false;
undeployedWeapon = NULL;
deployedObjectId = NULL;
lastDeploy = 0;
currentVetLevel = 0;
// Check deployedObjectPreset is a valid preset name
if ( !Is_Valid_Preset(Get_Parameter ("deployedObjectPreset")) )
{
Send_Message(255,255,255,"dp88_AR_Deployable_Infantry :: Script aborting due to invalid deployedObjectPreset");
Destroy_Script();
return;
}
// Validate the weapon powerups
hasRookieWeaponPowerup = (strcmp ( Get_Parameter( "deployedWeaponPowerup" ), "null" ) != 0 && Is_Valid_Preset ( Get_Parameter( "deployedWeaponPowerup" ) )) ? true : false;
hasVeteranWeaponPowerup = (strcmp ( Get_Parameter( "deployedWeaponPowerup_veteran" ), "null" ) != 0 && Is_Valid_Preset ( Get_Parameter( "deployedWeaponPowerup_veteran" ) )) ? true : false;
hasEliteWeaponPowerup = (strcmp ( Get_Parameter( "deployedWeaponPowerup_elite" ), "null" ) != 0 && Is_Valid_Preset ( Get_Parameter( "deployedWeaponPowerup_elite" ) )) ? true : false;
// Store undeployed skin & armour types
strcpy_s ( undeployedSkinType, sizeof( undeployedSkinType ), Get_Skin ( obj ) );
strcpy_s ( undeployedArmourType, sizeof( undeployedArmourType ), Get_Shield_Type ( obj ) );
// Get cannot deploy string and sound IDs
int soundId = 0;
cannotDeployStringId = (Is_Valid_String_ID(Get_Int_Parameter("cannotDeployStringId"))) ? Get_Int_Parameter("cannotDeployStringId") : 0;
if ( cannotDeployStringId && (soundId = Get_String_Sound_ID(cannotDeployStringId)) != 0 && Is_Valid_Preset_ID(soundId) && Find_Definition(soundId)->Get_Class_ID() == 0x5000 )
cannotDeploySoundId = soundId;
// Install keyhook
if ( obj->As_SoldierGameObj() && Get_Player_ID ( obj ) >= 0 )
InstallHook( Get_Parameter("deployKeyhook"), obj );
}
void dp88_AR_Deployable_Infantry::KeyHook()
{
// Find object
GameObject* obj = Commands->Find_Object ( objectID );
if ( !obj || Get_Vehicle(obj) || obj->As_SoldierGameObj()->Is_On_Ladder() || obj->As_SoldierGameObj()->Is_In_Elevator() )
return;
if ( deployed )
{
// If deployed for less than undeployTime seconds dont allow undeploy
float undeployTime = Get_Float_Parameter("undeployTime");
if ( time(NULL) - lastDeploy < undeployTime )
{
StringClass str(true);
str.Format("You cannot undeploy yet, you must wait at least %.*f seconds after deploying to undeploy.", (((int)undeployTime)==undeployTime)?0:2, undeployTime);
Send_Message_Player(obj, DP88_RGB_WARNING_MSG, str);
return;
}
Undeploy(obj);
}
else
{
// If deployed for less than deployTime seconds dont allow deploy
float deployTime = Get_Float_Parameter("deployTime");
if ( time(NULL) - lastDeploy < deployTime )
{
StringClass str(true);
str.Format("You cannot deploy yet, you must wait at least %.*f seconds after undeploying to deploy again.",(((int)deployTime)==deployTime)?0:2, deployTime);
Send_Message_Player(obj, DP88_RGB_WARNING_MSG, str);
return;
}
// Get velocity of deployer
Vector3 velocity = Get_Velocity(obj);
// Find closest other armed object
GameObject* closest = Get_Closest_Armed_Object_To_Object(obj);
// Check if we can deploy
if ( fabs(velocity.X) > 0.001 || fabs(velocity.Y) > 0.001 || fabs(velocity.Z) > 0.001
|| (closest && Commands->Get_Distance(Commands->Get_Position(obj), Commands->Get_Position(closest)) < Get_Float_Parameter("deployedObjectSpaceRequired") ) )
{
const char *str = Get_Translated_String(cannotDeployStringId);
Send_Message_Player(obj,153,204,25,str);
delete[] str;
if ( cannotDeploySoundId )
Create_2D_Sound_Player(obj, Get_Definition_Name(cannotDeploySoundId));
}
else
{
Deploy(obj);
}
}
}
void dp88_AR_Deployable_Infantry::Killed( GameObject *obj, GameObject *killer )
{
RemoveHook();
if ( deployedObjectId != NULL )
Commands->Destroy_Object ( Commands->Find_Object ( deployedObjectId ) );
deployedObjectId = NULL;
}
void dp88_AR_Deployable_Infantry::Destroyed( GameObject *obj )
{
if ( deployedObjectId != NULL )
Commands->Destroy_Object ( Commands->Find_Object ( deployedObjectId ) );
deployedObjectId = NULL;
}
void dp88_AR_Deployable_Infantry::Custom ( GameObject *obj, int type, int param, GameObject *sender )
{
// We have been promoted, apply new weapon and/or armour types
if ( sender == obj && type == CUSTOM_VETERANCY_PROMOTED )
{
// Remember old vet level
int oldVetLevel = currentVetLevel;
// Save new level
currentVetLevel = param;
/* Save new defaults for skin and armour type, unless we are deployed and
they match the values we set for the old vet level, which implies they
didn't recieve a new armour type on promotion */
if ( !deployed || strcmp(GetArmourType(oldVetLevel),Get_Skin(obj)) != 0 )
strcpy_s ( undeployedSkinType, sizeof( undeployedSkinType ), Get_Skin ( obj ) );
if ( !deployed || strcmp(GetArmourType(oldVetLevel),Get_Shield_Type(obj)) != 0 )
strcpy_s ( undeployedArmourType, sizeof( undeployedArmourType ), Get_Shield_Type ( obj ) );
// Set new armour / shield types and weapon if deployed
if ( deployed )
{
const char* armourType = GetArmourType(currentVetLevel);
if ( armourType )
{
Commands->Set_Shield_Type(obj, armourType);
Set_Skin(obj, armourType);
}
// Grant new weapon if necessary
bool grantWeapon = ((currentVetLevel == 2 && hasEliteWeaponPowerup )||( oldVetLevel == 0 && hasVeteranWeaponPowerup)) ? true : false;
if ( grantWeapon )
{
// Do we need to remove an old deployed weapon?
if ( (oldVetLevel == 1 && hasVeteranWeaponPowerup) || hasRookieWeaponPowerup )
{
// Remove old weapon
const char* oldWeaponPowerup = GetWeaponPowerup(oldVetLevel);
Remove_Weapon ( obj, Get_Powerup_Weapon ( oldWeaponPowerup ) );
}
// Grant and select new weapon
const char* powerup = GetWeaponPowerup(currentVetLevel);
Commands->Give_PowerUp( obj, powerup, true );
Commands->Select_Weapon ( obj, Get_Powerup_Weapon ( powerup ) );
}
}
}
}
// TEMPORARY - CHECK IF GI MOVES AWAY FROM SANDBAGS
void dp88_AR_Deployable_Infantry::Timer_Expired ( GameObject* obj, int number )
{
if ( deployed && number == 154785 )
{
GameObject* deployedObject = Commands->Find_Object(deployedObjectId);
float distance = Commands->Get_Distance(Commands->Get_Position(deployedObject),Commands->Get_Position(obj));
// If more than 3m away, undeploy
if ( deployedObject != NULL && distance > 1.5f )
{
Undeploy(obj);
// Remove script to punish abusers
Send_Message_Player(obj, DP88_RGB_ERROR_MSG, StringClass::getFormattedString("Deployment abuse detected, disabling deploy script... (distance from deployment: %.2fm)", distance));
RemoveHook();
Destroy_Script();
return;
}
Commands->Start_Timer(obj,this,2.0f,154785);
}
}
// Get armour type to set for the given veterancy level
const char* dp88_AR_Deployable_Infantry::GetArmourType ( int vetLevel )
{
if ( vetLevel == 2 && strcmp ( Get_Parameter( "deployedArmourType_elite" ), "null" ) != 0 )
return Get_Parameter ( "deployedArmourType_elite" );
else if ( vetLevel >= 1 && strcmp ( Get_Parameter( "deployedArmourType_veteran" ), "null" ) != 0 )
return Get_Parameter ( "deployedArmourType_veteran" );
else if ( strcmp ( Get_Parameter( "deployedArmourType" ), "null" ) != 0 )
return Get_Parameter ( "deployedArmourType" );
return NULL;
}
// Get weapon powerup to grant for the given veterancy level
const char* dp88_AR_Deployable_Infantry::GetWeaponPowerup ( int vetLevel )
{
if ( vetLevel == 2 && hasEliteWeaponPowerup )
return Get_Parameter("deployedWeaponPowerup_elite");
else if ( vetLevel >= 1 && hasVeteranWeaponPowerup )
return Get_Parameter("deployedWeaponPowerup_veteran");
else if ( hasRookieWeaponPowerup )
return Get_Parameter("deployedWeaponPowerup");
return NULL;
}
void dp88_AR_Deployable_Infantry::Deploy(GameObject* obj)
{
if (deployed)
return;
lastDeploy = time(NULL);
deployed = true;
// Create the defensive structure
GameObject* deployedObject = Commands->Create_Object ( Get_Parameter ( "deployedObjectPreset" ), Commands->Get_Position ( obj ) );
deployedObjectId = Commands->Get_ID ( deployedObject );
// Grant deployed weapon and select it for use
const char* powerup = GetWeaponPowerup(currentVetLevel);
if ( powerup )
{
Commands->Give_PowerUp( obj, powerup, true );
Commands->Select_Weapon ( obj, Get_Powerup_Weapon ( powerup ) );
}
// Set armour & skin types
const char* armourType = GetArmourType(currentVetLevel);
if ( armourType )
{
Commands->Set_Shield_Type(obj, armourType);
Set_Skin(obj, armourType);
}
// Disable loiters and vehicle entry
if ( SoldierGameObj* sObj = obj->As_SoldierGameObj() ) // Should always be true, but safety first...
{
m_bCanDrive = sObj->Can_Drive_Vehicles(); // Save value for when we undeploy...
sObj->Set_Can_Drive_Vehicles(false);
Commands->Set_Loiters_Allowed(obj,false);
}
const char *sound = Get_Parameter("deploySound");
if (sound[0])
{
Commands->Create_Sound(sound, Commands->Get_Position(obj), obj);
}
// TEMP - Start timer to check position for script abuse
Commands->Start_Timer(obj,this,2.0f,154785);
}
void dp88_AR_Deployable_Infantry::Undeploy(GameObject* obj)
{
if (!deployed)
return;
lastDeploy = time(NULL);
deployed = false;
// Destroy the defensive structure
if (NULL != deployedObjectId)
{
Commands->Destroy_Object(Commands->Find_Object(deployedObjectId));
// Wake up any objects inside the box to prevent abusing the physics engine to
// "walk on air" by moving forward, undeploying and redeploying (and repeating)
// without waking the physics engine to check for terrain under the soldier
Vector3 pos = Commands->Get_Position(obj);
Vector3 extent(10.0f, 10.0f, 10.0f);
OBBoxClass boundingBox(pos, extent);
Wake_Up_Objects_In_OBBox(boundingBox);
}
// Remove deployed weapon
const char* powerup = GetWeaponPowerup(currentVetLevel);
if (powerup)
Remove_Weapon(obj, Get_Powerup_Weapon(powerup));
// Re-enable loiters and vehicle entry
if (SoldierGameObj* sObj = obj->As_SoldierGameObj()) // Should always be true, but safety first...
{
sObj->Set_Can_Drive_Vehicles(m_bCanDrive);
Commands->Set_Loiters_Allowed(obj,true);
}
const char *sound = Get_Parameter("undeploySound");
if (sound[0])
{
Commands->Create_Sound(sound, Commands->Get_Position(obj), obj);
}
// Reset armour & skin types
Set_Skin(obj, undeployedSkinType);
Commands->Set_Shield_Type(obj, undeployedArmourType);
}
/*------------------------
Chrono Legionnaire Scripts
--------------------------*/
void dp88_AR_CLEG::Created(GameObject *obj)
{
//Console_Output ( "Created dp88_AR_CLEG\n" );
phasing = false;
phasingBack = false;
timeRemaining = 180;
zPosDropObj = 0;
dropObjID = 0;
}
void dp88_AR_CLEG::Damaged(GameObject *obj, GameObject *damager, float amount)
{
if ( Commands->Get_ID ( damager ) == Commands->Get_ID ( obj ) && amount == 0.0 )
{
Vector3 position = Commands->Get_Position ( obj );
// If damage = 0 and damager is ourselves then phase to the top plane, or phase
// back if we are already there.
if ( !phasing )
{
position.Z = 90;
Commands->Set_Position ( obj, position );
timeRemaining = 180;
// Start the clock ticking
Commands->Start_Timer ( obj, this, 1.0f, TIMER_CLEG_PHASEDEATH );
phasing = true;
}
else if ( dropObjID == 0 )
{
position.Z -= 5.0;
// Time to phase back down again, create the object and start the timer
// to wait for it to hit the floor
phasingBack = true;
GameObject *dropper;
dropper = Commands->Create_Object( "CLEG_DropObj", position );
dropObjID = Commands->Get_ID(dropper);
zPosDropObj = 0;
Commands->Start_Timer ( obj, this, 0.2f, TIMER_CLEG_CHECKDROPOBJ );
Send_Message_Player( obj, 153, 204, 25, "Phasing in...." );
}
}
}
void dp88_AR_CLEG::Killed(GameObject *obj, GameObject *killer)
{
if ( dropObjID != 0 )
Commands->Destroy_Object( Commands->Find_Object( dropObjID ) );
}
void dp88_AR_CLEG::Timer_Expired( GameObject *obj, int number )
{
if ( number == TIMER_CLEG_CHECKDROPOBJ && dropObjID != 0 )
{
Vector3 position = Commands->Get_Position( Commands->Find_Object( dropObjID ) );
if ( (int)zPosDropObj == (int)position.Z )
{
Commands->Destroy_Object( Commands->Find_Object( dropObjID ) );
position.Z += 1;
Commands->Set_Position( obj, position );
phasing = false;
phasingBack = false;
dropObjID = 0;
zPosDropObj = 0;
}
else
{
zPosDropObj = (int)position.Z;
Commands->Start_Timer( obj, this, 0.2f, TIMER_CLEG_CHECKDROPOBJ );
}
}
else if ( number == TIMER_CLEG_PHASEDEATH )
{
if ( phasing == true )
{
Commands->Start_Timer ( obj, this, 1.0f, TIMER_CLEG_PHASEDEATH );
timeRemaining -= 1;
}
if ( timeRemaining == 0 && phasing == true && phasingBack != true )
{
char deathMSG[128];
sprintf ( deathMSG, "You have been phased out too long and have died..." );
Send_Message_Player( obj, 153, 204, 25, deathMSG );
Commands->Apply_Damage( obj, 500.0, "Death", obj );
}
else if ( phasing == true && timeRemaining % 20 == 0 || timeRemaining == 10 || timeRemaining == 5 )
{
char deathTimer[128];
sprintf ( deathTimer, "WARNING: You have %d seconds to phase back before you die...", timeRemaining );
Send_Message_Player( obj, 153, 204, 25, deathTimer );
}
}
}
void dp88_AR_CLEG_target::Created(GameObject *obj)
{
currentResistance = Get_Int_Parameter("resistance")*10;
lastResistanceCheck = 0;
effectObjectId = 0;
}
void dp88_AR_CLEG_target::Damaged(GameObject *obj, GameObject *damager, float amount)
{
const static char *Comparison = "CLEG_Weapon";
if ( damager
&& Get_Current_Weapon(damager)
&& strstr( Get_Current_Weapon(damager), Comparison ) != NULL
&& ( !Get_Vehicle(damager) ) // Check they are not in a vehicle, as current_weapon will not show this
&& ( Get_Object_Type(damager) != Get_Object_Type(obj) ) // Check they are not on the same team
&& currentResistance > 0 ) // Check if we have any CLEG resistance remaining
{
// If this is the first damage we have taken in this CLEG attack setup
// all variables
if ( lastResistanceCheck == 0 )
{
lastResistanceCheck = currentResistance;
// Start timer to see if we can be released
Commands->Start_Timer( obj, this, 1.0f, TIMER_CLEG_CHECKRELEASETARGET );
// Create instance of CLEG effect preset (if applicable)
const char* effectPreset = Get_Parameter("clegEffectPreset");
if ( Is_Valid_Preset(effectPreset) )
{
GameObject *effectObject = Commands->Create_Object ( effectPreset, Commands->Get_Position(obj) );
if ( effectObject )
effectObjectId = Commands->Get_ID ( effectObject );
}
// Disable controls for target
Commands->Control_Enable( obj, false );
}
// Reduce remaining resistance
currentResistance--;
if ( currentResistance == 0 )
{
Commands->Apply_Damage( obj, 5000.0, "Death", damager );
// Make target 'vanish'
Commands->Set_Model( obj, "null" );
}
}
}
void dp88_AR_CLEG_target::Killed(GameObject *obj, GameObject *killer)
{
/* Destroy effect object if it exists */
if ( effectObjectId != 0 )
{
GameObject *effectObject = Commands->Find_Object(effectObjectId);
if ( effectObject )
Commands->Destroy_Object(effectObject);
effectObjectId = 0;
}
}
void dp88_AR_CLEG_target::Timer_Expired( GameObject *obj, int number )
{
if ( number == TIMER_CLEG_CHECKRELEASETARGET )
{
/* If resistance since last check has not changed then CLEG has stopped attacking
us so free the unit, reset its resistance and destroy any effect object */
if ( lastResistanceCheck == currentResistance )
{
// Reset resistance
currentResistance = Get_Int_Parameter("resistance")*10;
lastResistanceCheck = 0;
// Re-enable controls
Commands->Control_Enable( obj, true );
/* Destroy effect object if it exists */
if ( effectObjectId != 0 )
{
GameObject *effectObject = Commands->Find_Object(effectObjectId);
if ( effectObject )
Commands->Destroy_Object(effectObject);
effectObjectId = 0;
}
}
/* Otherwise we are still being attacked, update the last check variable and restart
the timer... */
else if ( currentResistance > 0 )
{
// If we are still being targetted by CLEG(s) start the timer again
lastResistanceCheck = currentResistance;
Commands->Start_Timer( obj, this, 1.0f, TIMER_CLEG_CHECKRELEASETARGET );
}
}
}
/*------------------------
AR Miner Script - Base Class
This base class is used by both dp88_AR_Chrono_Miner and dp88_AR_War_Miner
and implements common functionality used by both scripts
--------------------------*/
void dp88_Ore_Miner::Created ( GameObject *obj )
{
m_aiState = MINER_AISTATE_IDLE;
m_oreMined = 0;
m_oreValue = 0;
m_bUseAI = ( Get_Int_Parameter ( "Use_AI" ) == 1 ) ? true : false;
m_resourceName = Get_Parameter("Resource_Name");
m_oreCapacity = Get_Int_Parameter("Ore_Capacity");
m_oreMiningTime = Get_Float_Parameter("Ore_Mining_Time");
m_oreDumpTime = Get_Float_Parameter("Ore_Dump_Time");
m_oreFieldId = 0;
m_oreFieldRand = 0;
// Load animation settings
m_animations[MINER_ANIM_IDLE] = Get_Parameter("Idle_Animation");
m_animations[MINER_ANIM_MINING] = Get_Parameter("Mining_Animation");
m_animations[MINER_ANIM_DUMPING] = Get_Parameter("Dump_Animation");
m_animSounds[MINER_ANIM_IDLE] = NULL;
m_animSounds[MINER_ANIM_MINING] = Get_Parameter("Mining_Sound");
m_animSounds[MINER_ANIM_DUMPING] = Get_Parameter("Dump_Sound");
for ( int i = MINER_ANIM_IDLE; i <= MINER_ANIM_DUMPING; ++i )
{
if (m_animations[i] != NULL && strlen(m_animations[i]) <= 0)
m_animations[i] = NULL;
if (m_animSounds[i] != NULL && strlen(m_animSounds[i]) <= 0)
m_animSounds[i] = NULL;
}
// Set the initial animation state
UpdateAnimation(obj, MINER_ANIM_IDLE);
/* For AI miners send a message to ourselves to start searching for an ore field - note the delay
* which is required to prevent the default harvester AI taking over */
if ( m_bUseAI )
Commands->Send_Custom_Event( obj, obj, CUSTOM_MINER_AI_SEARCH_FOR_ORE, 1, (float)Get_Int_Parameter("AI_Init_Delay") );
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::Custom ( GameObject *obj, int type, int param, GameObject *sender )
{
// Message from an ore field indicating we have entered it
if ( type == CUSTOM_MINER_ENTERED_ORE_FIELD )
{
EnteredOreField(obj, sender);
}
// Message from an ore field indicating we have left it
else if ( type == CUSTOM_MINER_EXITED_ORE_FIELD && Commands->Get_ID(sender) == m_oreFieldId )
{
ExitedOreField(obj, sender);
}
// Message to ourselves to mine another ore load
else if ( type == CUSTOM_MINER_INCREASE_ORE_LOAD && param == m_oreFieldRand )
{
GameObject* pOreField = Commands->Find_Object(m_oreFieldId);
dp88_Ore_Field* pOreFieldScript = (!pOreField) ? NULL : (dp88_Ore_Field *)(Find_Script_On_Object(pOreField,"dp88_Ore_Field"));
// Unless we are already full increase our load level and the value of our load
if ( m_oreMined < m_oreCapacity && pOreFieldScript )
{
if ( pOreFieldScript->RemoveOre(1) == 1 )
{
// Play the mining sound
if ( m_animSounds[MINER_ANIM_MINING] != NULL )
Commands->Create_Sound(m_animSounds[MINER_ANIM_MINING],Commands->Get_Position(obj),obj);
m_oreMined++;
m_oreValue += pOreFieldScript->GetOreValue();
}
}
// If we are still not full start send a delayed custom to increase it again
if ( m_oreMined < m_oreCapacity && pOreFieldScript && (pOreFieldScript->IsInfinite() || pOreFieldScript->NumOreUnits() > 0) )
Commands->Send_Custom_Event ( obj, obj, CUSTOM_MINER_INCREASE_ORE_LOAD, m_oreFieldRand, m_oreMiningTime );
// Otherwise we are full of ore... or the ore field is depleted...
else
{
UpdateAnimation(obj, MINER_ANIM_IDLE);
// If using the AI start driving to the refinery
if ( m_bUseAI )
ReturnToRefinery(obj);
// Or, if we are a player driven miner, tell the driver we are full
else if ( Get_Vehicle_Driver(obj) != NULL )
{
if ( m_oreMined < m_oreCapacity )
{
StringClass str;
str.Format("The %s field is depleted, find another %s field or dock at the Refinery to process the %s you have collected so far...",m_resourceName,m_resourceName,m_resourceName);
Send_Message_Player ( Get_Vehicle_Driver(obj), DP88_RGB_GENERAL_MSG, str);
}
else
{
StringClass str;
str.Format("Fully loaded with %s, dock at the Refinery to process the %s into credits",m_resourceName,m_resourceName);
Send_Message_Player ( Get_Vehicle_Driver(obj), DP88_RGB_GENERAL_MSG,str);
}
}
}
}
// Message from the ore dump zone notifying us that we have entered it. If
// we have ore to unload then immobilize the vehicle and begin unloading it
else if ( type == CUSTOM_MINER_ENTERED_DUMP_ZONE && m_oreMined > 0 )
{
// Inform driver we are unloading
if ( Get_Vehicle_Driver(obj) != NULL )
{
StringClass str;
str.Format("Unloading %s, please stand by...", m_resourceName);
Send_Message_Player ( Get_Vehicle_Driver(obj), DP88_RGB_GENERAL_MSG, str);
}
// Set AI state
if ( m_bUseAI )
m_aiState = MINER_AISTATE_UNLOADING_ORE;
// Send a timed event to notify us when the dump is complete and then call the docking event
Commands->Send_Custom_Event(obj, obj, CUSTOM_MINER_UNLOAD_ORE_COMPLETE, 0, m_oreDumpTime);
DockedAtRefinery(obj);
}
// Message to ourselves to indicate ore unloading is complete, grant money
// to the team and set off to collect some more ore
else if ( type == CUSTOM_MINER_UNLOAD_ORE_COMPLETE )
{
// Inform the driver that we have finished unloading
if ( Get_Vehicle_Driver(obj) != NULL )
{
StringClass message(true);
StringClass s = m_resourceName;
s[0] = (char)toupper(s[0]);
message.Format ("%s unloaded successfully, you have earned %d credits for each player and %d points for yourself",s.Peek_Buffer(), m_oreValue, m_oreValue/10 );
Send_Message_Player ( Get_Vehicle_Driver(obj), DP88_RGB_GENERAL_MSG, message );
Commands->Give_Points(Get_Vehicle_Driver(obj),(float)m_oreValue/10.0f,false);
}
// Grant money to team and reset ore load level
Commands->Give_Money ( obj, (float)m_oreValue, true );
MS_AccessHelper::Give_Bot_Credits(Get_Object_Type(obj), (float)m_oreValue);
m_oreMined = 0;
m_oreValue = 0;
// Call UndockedFromRefinery
UndockedFromRefinery(obj);
}
// AI message to search for an ore field...
else if ( type == CUSTOM_MINER_AI_SEARCH_FOR_ORE )
{
DriveToOreField(obj);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::Action_Complete ( GameObject *obj, int action_id, ActionCompleteReason complete_reason )
{
// If the completed action was RETURN_TO_REFINERY then set the AI state to
// docking and call DockAtRefinery();
if ( action_id == MINER_ACTIONID_RETURN_TO_REFINERY )
{
//Console_Output ( "dp88_Ore_Miner: Arrived at refinery... start docking\n" );
m_aiState = MINER_AISTATE_DOCK_AT_REFINERY;
DockAtRefinery(obj);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::DriveToOreField ( GameObject *obj )
{
m_aiState = MINER_AISTATE_SEARCH_FOR_ORE;
GameObject* bestField = NULL;
double bestFieldScore = 0.0;
// \todo Check number of units available in an ore field and find one with a sufficient quantity -
// ideally 1.5x our capacity to avoid it being depleted before we get there!
SList<GameObject> oreFields;
Find_All_Objects_With_Script("dp88_Ore_Field", oreFields);
for ( SLNode<GameObject>* oreFieldNode = oreFields.Head(); oreFieldNode != NULL; oreFieldNode = oreFieldNode->Next() )
{
if (GameObject* oreField = oreFieldNode->Data())
{
dp88_Ore_Field* pOreFieldScript = (dp88_Ore_Field *)(Find_Script_On_Object(oreField,"dp88_Ore_Field"));
if (!pOreFieldScript || !pOreFieldScript->IsSuitableForAI())
continue;
int availableUnits = min(m_oreCapacity, (pOreFieldScript->IsInfinite()?m_oreCapacity:(int)pOreFieldScript->NumOreUnits()));
if (0 == availableUnits)
continue;
Vector3 fieldPosition = Commands->Get_Position(oreField);
double fieldScore = (availableUnits*pOreFieldScript->GetOreValue()) / (0.5*Commands->Get_Distance(Commands->Get_Position(oreField), Commands->Get_Position(obj)));
if (fieldScore > bestFieldScore || NULL == bestField)
{
bestField = oreField;
bestFieldScore = fieldScore;
}
}
}
if (NULL == bestField)
{
//Console_Output ( "dp88_Ore_Miner: No ore fields available..." );
// No ore fields are available at the moment... send ourselves a message to have another look in 5 seconds...
Commands->Send_Custom_Event(obj, obj, CUSTOM_MINER_AI_SEARCH_FOR_ORE, 1, (float)5.0f);
return;
}
//Console_Output ( "dp88_Ore_Miner: Driving to location: %.2f, %.2f, %.2f\n", position.X, position.Y, position.Z );
/* Setup parameters and get going! */
m_aiState = MINER_AISTATE_DRIVE_TO_ORE;
ActionParamsStruct params;
params.Set_Basic(this, 100.0f, MINER_ACTIONID_DRIVE_TO_ORE);
params.Set_Movement(Commands->Get_Position(bestField), 1.0f, 1.0f);
params.MovePathfind = true;
params.ShutdownEngineOnArrival = true;
params.AttackActive = false;
Commands->Action_Goto(obj, params);
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::EnteredOreField ( GameObject *obj, GameObject* oreField )
{
// Ignore this if we are already full
if ( m_oreMined >= m_oreCapacity )
return;
// Check if this is a valid ore field
dp88_Ore_Field* pOreFieldScript = (dp88_Ore_Field *)(Find_Script_On_Object(oreField,"dp88_Ore_Field"));
if (!pOreFieldScript || (m_bUseAI && !pOreFieldScript->IsSuitableForAI()))
return;
// Check this field isn't empty (we might have just driven into it on the way to another one, or
// some thief might have stolen the resources!)
if (!pOreFieldScript->IsInfinite() && 0 == pOreFieldScript->NumOreUnits())
{
if (m_bUseAI)
DriveToOreField(obj);
return;
}
// Set AI state, notify driver or abort if neither AI controlled nor player driven...
if (m_bUseAI)
{
m_aiState = MINER_AISTATE_COLLECTING_ORE;
Commands->Action_Reset ( obj, 101.0f );
}
else if (NULL != Get_Vehicle_Driver(obj))
{
StringClass str;
str.Format("Collecting %s...",m_resourceName);
Send_Message_Player ( Get_Vehicle_Driver(obj), DP88_RGB_GENERAL_MSG, str );
}
else
return;
// Save the ore field ID and generate a random integer to identify this trip into the ore field
// to prevent glitching the timers by entering and exiting constantly
m_oreFieldId = Commands->Get_ID(oreField);
m_oreFieldRand = Commands->Get_Random_Int(2,10240);
// Send delayed message to increase ore load
Commands->Send_Custom_Event ( obj, obj, CUSTOM_MINER_INCREASE_ORE_LOAD, m_oreFieldRand, m_oreMiningTime );
UpdateAnimation(obj, MINER_ANIM_MINING);
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::ExitedOreField ( GameObject *obj, GameObject* oreField )
{
// Reset ore field parameters
m_oreFieldId = 0;
m_oreFieldRand = 0;
// Stop the mining animation
UpdateAnimation(obj, MINER_ANIM_IDLE);
// If this is an AI miner and our state is still collecting ore then we were probably shoved out
// of the ore field by some bully in a vehicle so drive back in to finish mining
if ( m_bUseAI && m_aiState == MINER_AISTATE_COLLECTING_ORE )
DriveToOreField(obj);
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::ReturnToRefinery ( GameObject *obj )
{
/* Find and drive to the refinery */
m_aiState = MINER_AISTATE_RETURN_TO_REFINERY;
GameObject *refinery = Find_Refinery(Commands->Get_Player_Type(obj));
if ( refinery != NULL )
{
GameObject* zone = Find_Closest_Object_With_Script("dp88_Ore_Dump_Zone", Commands->Get_Position(refinery));
if ( zone != NULL )
{
Vector3 position = Commands->Get_Position(zone);
//Console_Output ( "dp88_Ore_Miner: Driving to location: %.2f, %.2f, %.2f\n", position.X, position.Y, position.Z );
/* Setup parameters and get going! */
ActionParamsStruct params;
params.Set_Basic( this, 100.0f, MINER_ACTIONID_RETURN_TO_REFINERY );
params.Set_Movement ( position, 1.0f, 25.0f );
params.MovePathfind = true;
params.ShutdownEngineOnArrival = true;
params.AttackActive = false;
Commands->Action_Goto( obj, params );
}
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::DockAtRefinery ( GameObject *obj )
{
// Reset current action
Commands->Action_Reset(obj, 101.0f);
/* Find and drive to the refinery unloading area */
GameObject* zone = Find_Closest_Object_With_Script("dp88_Ore_Dump_Zone", Commands->Get_Position(obj));
if ( zone != NULL )
{
Vector3 position = Commands->Get_Position(zone);
//Console_Output ( "dp88_Ore_Miner: Docking at location: %.2f, %.2f, %.2f\n", position.X, position.Y, position.Z );
/* Setup parameters and get going! */
ActionParamsStruct params;
params.Set_Basic( this, 100.0f, MINER_ACTIONID_DOCK_AT_REFINERY );
params.Set_Movement ( position, 1.0f, 1.0f );
params.MoveBackup = true;
params.ShutdownEngineOnArrival = true;
params.MovePathfind = true;
Commands->Action_Goto(obj, params);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::DockedAtRefinery ( GameObject *obj )
{
// If we are using AI then reset the action now that we have arrived
if (m_bUseAI)
Commands->Action_Reset ( obj, 101.0f );
UpdateAnimation(obj, MINER_ANIM_DUMPING);
// Immobilize the vehicle and disable engine sounds
if ( obj->As_VehicleGameObj() )
{
obj->As_VehicleGameObj()->Set_Immovable(true);
Commands->Enable_Engine ( obj, false );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::UndockedFromRefinery ( GameObject *obj )
{
// Un-immobilize the vehicle and enable engine sounds
if ( obj->As_VehicleGameObj() )
{
obj->As_VehicleGameObj()->Set_Immovable(false);
Commands->Enable_Engine ( obj, true );
}
// If using the AI then set the AI state and start driving to the ore field
if ( m_bUseAI )
{
DriveToOreField(obj);
}
UpdateAnimation(obj, MINER_ANIM_IDLE);
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Miner::UpdateAnimation ( GameObject* pObj, MINER_ANIMID animId )
{
pObj->As_PhysicalGameObj()->Clear_Animation();
if ( animId < countof(m_animations) && m_animations[animId] != NULL )
{
bool bLooping = (animId == MINER_ANIM_MINING) ? true : false;
Commands->Set_Animation(pObj,m_animations[animId],bLooping,NULL,0,-1,false);
}
if (animId < countof(m_animSounds) && m_animSounds[animId] != NULL)
Commands->Create_Sound(m_animSounds[animId],Commands->Get_Position(pObj),pObj);
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_Ore_Miner> dp88_Ore_Miner_Registrant(
"dp88_Ore_Miner",
"Use_AI=1:int,"
"Ore_Capacity=10:int,"
"Ore_Mining_Time=2.0:float,"
"Ore_Dump_Time=8.0:float,"
"AI_Init_Delay=10:int,"
"Dump_Animation:string,"
"Dump_Sound:string,"
"Mining_Animation:String,"
"Mining_Sound:string,"
"Idle_Animation:string,"
"Resource_Name=ore:string"
);
/*------------------------
Chrono Miner Scripts (AI and non-AI)
--------------------------*/
void dp88_AR_Chrono_Miner::Created( GameObject *obj )
{
dp88_Ore_Miner::Created(obj);
objectId = Commands->Get_ID(obj);
driverId = NULL;
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Chrono_Miner::Damaged( GameObject *obj, GameObject *damager, float amount )
{
// If AI miner health drops below the emergency chronoshift health threshold and we are driving to
// the ore field or collecting ore then begin an emergency chronoshift
if ( m_bUseAI && Commands->Get_Health(obj) < (Commands->Get_Max_Health(obj)*(Get_Float_Parameter("emergencyChronoshiftHealthThreshold")/100.0f))
&& (m_aiState == MINER_AISTATE_COLLECTING_ORE && m_oreMined > 0) )
{
// Attempt to start a chronoshift - if it fails don't bother with anything else, driving away
// won't help...
Start_Chronoshift(obj);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Chrono_Miner::Custom( GameObject *obj, int type, int param, GameObject *sender )
{
// Look for vehicle entry
if ( type == CUSTOM_EVENT_VEHICLE_ENTERED && driverId == NULL )
{
driverId = Commands->Get_ID(sender);
InstallHook( Get_Parameter("chronoshiftKeyhook"), sender );
}
// Look for vehicle exit
else if ( type == CUSTOM_EVENT_VEHICLE_EXITED && Commands->Get_ID(sender) == driverId )
{
driverId = NULL;
RemoveHook();
}
// AI miner failed to chronoshift back to the refinery, if we are still more than 150m
// from the target then try again
else if ( type == CUSTOM_CHRONO_MINER_RETRY_CHRONOSHIFT && m_aiState == MINER_AISTATE_RETURN_TO_REFINERY )
{
GameObject *refinery = Find_Refinery(Commands->Get_Player_Type(obj));
if ( refinery != NULL && Commands->Get_Distance(Commands->Get_Position(refinery),Commands->Get_Position(obj)) > 150.0f )
{
// Try to chronoshift and, on failure, set timer to try again in 5 seconds
if ( !Start_Chronoshift(obj) )
Commands->Send_Custom_Event(obj,obj,CUSTOM_CHRONO_MINER_RETRY_CHRONOSHIFT,0,5.0f);
}
}
// Time to perform a chronoshift!
else if ( type == CUSTOM_CHRONO_MINER_DO_CHRONOSHIFT )
{
Do_Chronoshift(obj,param);
}
// Otherwise pass the message on to the base class
else
dp88_Ore_Miner::Custom ( obj, type, param, sender );
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Chrono_Miner::KeyHook()
{
// Find object
GameObject* obj = Commands->Find_Object ( objectId );
if ( !obj )
return;
if ( m_aiState != CMINER_AISTATE_CHRONOSHIFTING )
{
if ( !Start_Chronoshift(obj) )
Send_Message_Player ( Get_Vehicle_Driver(obj), 153, 204, 25, "Unable to chronoshift, all target zones are unavailable..." );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Chrono_Miner::ReturnToRefinery ( GameObject *obj )
{
// Attempt to chronoshift to the refinery
if ( !Start_Chronoshift(obj) )
{
// Can't chronoshift... drive there instead!
dp88_Ore_Miner::ReturnToRefinery(obj);
Send_Message_Team ( Get_Object_Type(obj), 153, 204, 25, "The AI Chronominer was unable to chronoshift, please clear the area around the refinery" );
// Send a delayed custom to retry the chronoshift in 5 seconds
Commands->Send_Custom_Event(obj,obj,CUSTOM_CHRONO_MINER_RETRY_CHRONOSHIFT,0,5.0f);
}
}
// -------------------------------------------------------------------------------------------------
bool dp88_AR_Chrono_Miner::Start_Chronoshift( GameObject *obj )
{
// If we are currently chronoshifting then bail out
if ( m_aiState == CMINER_AISTATE_CHRONOSHIFTING )
return false;
/* Find a zone to chronoshift in to */
GameObject *refinery = Find_Refinery(Commands->Get_Player_Type(obj));
if ( refinery != NULL )
{
// Check the refinery is not dead - if it is then the target script zones will
// all be gone, so we have nowhere to go...
if ( Commands->Get_Health(refinery) == 0 )
return false;
// Define the maximum distance we will shift from the refinery - this prevents us
// from going to the enemy refinery
const float maxDist = 50.0f;
Vector3 refineryPos = Commands->Get_Position(refinery);
SList<GameObject> chronoZones;
Find_All_Objects_With_Script_By_Distance ( "dp88_AR_Chrono_Miner_Chronozone", chronoZones, refineryPos );
for ( SLNode<GameObject>* x = chronoZones.Head(); x != NULL; x = x->Next() )
{
GameObject* zone = x->Data();
dp88_AR_Chrono_Miner_Chronozone *chronozone_script = NULL;
if ( !zone )
continue;
// OK, got a candidate zone, can we chronoshift here?
Vector3 zonePos = Commands->Get_Position(zone);
if (Vector3::Distance_Squared(zonePos, refineryPos) > maxDist * maxDist || !CanChronoshiftToLocation(obj, zonePos) )
continue;
// Is this zone in use for another chronoshift operation? If so then we cannot use it
chronozone_script = (dp88_AR_Chrono_Miner_Chronozone*)Find_Script_On_Object(zone, "dp88_AR_Chrono_Miner_Chronozone");
if ( !chronozone_script || (chronozone_script->chronominer_id != NULL
&& Commands->Find_Object(chronozone_script->chronominer_id)
&& Commands->Get_Health(Commands->Find_Object(chronozone_script->chronominer_id)) > 0) )
{
continue;
}
// OK, got ourselves a target zone, lock the zone to our ID and set up for chronoshift...
chronozone_script->chronominer_id = Commands->Get_ID(obj);
// NB: We use the AI state flag to determine if we are currently in the middle of
// a chronoshift for player driven miners too
m_aiState = CMINER_AISTATE_CHRONOSHIFTING;
// Immobilise the vehicle
if ( obj->As_VehicleGameObj() )
obj->As_VehicleGameObj()->Set_Immovable(true);
// Send a delayed custom to perform the chronoshift
Commands->Send_Custom_Event ( obj, obj, CUSTOM_CHRONO_MINER_DO_CHRONOSHIFT, Commands->Get_ID(zone), Get_Float_Parameter("chronoshift_time") );
/* If we have an out effect preset to spawn then spawn it at the origin */
if ( Is_Valid_Preset(Get_Parameter("chronoshift_out_effect_preset")) )
{
// Create effect object
GameObject* effectObject = Commands->Create_Object ( Get_Parameter("chronoshift_out_effect_preset"), Commands->Get_Position(obj) );
// Attach script to clean up effect
StringClass params(true);
params.Format ( "%.2f,%d", Get_Float_Parameter("chronoshift_out_effect_time"), 983142 );
Commands->Attach_Script ( effectObject, "JFW_Destroy_Self_Timer", params.Peek_Buffer() );
}
/* If we have an in effect preset to spawn then spawn it at the destination */
if ( Is_Valid_Preset(Get_Parameter("chronoshift_in_effect_preset")) )
{
// Create effect object
GameObject* effectObject = Commands->Create_Object ( Get_Parameter("chronoshift_in_effect_preset"), Commands->Get_Position ( zone ) );
// Attach script to clean up effect
StringClass params(true);
params.Format ( "%.2f,%d", Get_Float_Parameter("chronoshift_in_effect_time"), 983142 );
Commands->Attach_Script ( effectObject, "JFW_Destroy_Self_Timer", params.Peek_Buffer() );
}
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Chrono_Miner::Do_Chronoshift( GameObject *obj, int target_zone_id )
{
// Unimmobilise the vehicle
if ( obj->As_VehicleGameObj() )
obj->As_VehicleGameObj()->Set_Immovable(false);
/* Get the target chronoshift zone */
GameObject *zone = Commands->Find_Object(target_zone_id);
if ( zone != NULL )
{
// NB: We use the AI state flag to determine if we are currently in the middle
// of a chronoshift for player driven miners too
m_aiState = MINER_AISTATE_IDLE;
// Get a reference to the chronozone script and check if the chronominer_id
// matches ours. If so zero it and continue, otherwise bail out...
dp88_AR_Chrono_Miner_Chronozone *chronozone_script = (dp88_AR_Chrono_Miner_Chronozone*)Find_Script_On_Object(zone, "dp88_AR_Chrono_Miner_Chronozone");
if ( !chronozone_script || chronozone_script->chronominer_id != Commands->Get_ID(obj) )
{
// Have another go at a chronoshift...
ReturnToRefinery(obj);
return;
}
chronozone_script->chronominer_id = 0;
// Chronoshift to position of zone (resetting rotation in the process)
Vector3 zonePos = Commands->Get_Position(zone);
if ( CanChronoshiftToLocation(obj, zonePos) )
Set_Transform(obj, Matrix3D(zonePos) );
else
{
// Oh noes! Some dipstick has driven into the chronoshift zone... try again
ReturnToRefinery(obj);
return;
}
}
/* If using AI start driving to refinery now */
if ( m_bUseAI )
{
if ( m_oreMined > 0 )
{
dp88_Ore_Miner::ReturnToRefinery(obj);
}
// No ore collected... guess we must have chronoshifted away from an attack
// so lets set off towards the ore field again... what a waste of time!
else
{
DriveToOreField(obj);
}
}
}
// -------------------------------------------------------------------------------------------------
bool dp88_AR_Chrono_Miner::CanChronoshiftToLocation ( GameObject* obj, Vector3& location )
{
// Get physical game object and moveable phys class references
MoveablePhysClass* mphys = ( obj->As_PhysicalGameObj() ) ? obj->As_PhysicalGameObj()->Peek_Physical_Object()->As_MoveablePhysClass() : NULL;
// Can we move to this position without getting stuck?
if (mphys)
{
return mphys->Can_Teleport( Matrix3D(location) );
}
return false;
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_AR_Chrono_Miner> dp88_AR_Chrono_Miner_Registrant(
"dp88_AR_Chrono_Miner",
"Use_AI=1:int,"
"chronoshift_time=2.5:float,"
"chronoshift_out_effect_preset:string,"
"chronoshift_out_effect_time:float,"
"chronoshift_in_effect_preset:string,"
"chronoshift_in_effect_time:float,"
"chronoshiftKeyhook=VDeploy:string,"
"Ore_Capacity=5:int,"
"Ore_Mining_Time=1.00:float,"
"Ore_Dump_Time=4.0:float,"
"emergencyChronoshiftHealthThreshold=30.0:float,"
"AI_Init_Delay=10:int,"
"Dump_Animation:string,"
"Dump_Sound:string,"
"Mining_Animation:String,"
"Mining_Sound:string,"
"Idle_Animation:string"
);
/*------------------------
Chronoshift Zone Controller
--------------------------*/
void dp88_AR_Chrono_Miner_Chronozone::Created ( GameObject *obj )
{
// If the game controller does not exist then bail out
GameObject *gameController = Find_Object_With_Script("dp88_ar_gameController");
if ( !gameController )
{
Console_Output ( "dp88_AR_Chrono_Miner_Chronozone - Unable to find Game Controller, unable to continue. Destroying script...\n" );
Destroy_Script();
return;
}
chronominer_id = NULL;
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_AR_Chrono_Miner_Chronozone> dp88_AR_Chrono_Miner_Chronozone_Registrant(
"dp88_AR_Chrono_Miner_Chronozone",
""
);
/*------------------------
Ore Field
--------------------------*/
void dp88_Ore_Field::Created ( GameObject* pObj )
{
m_myObjId = Commands->Get_ID(pObj);
m_pZoneObserver = NULL;
m_oreValue = Get_Int_Parameter("Ore_Value");
m_oreCapacity = Get_Int_Parameter("Ore_Capacity");
m_nOreUnits = Get_Int_Parameter("Ore_Units");
if ( m_nOreUnits > m_oreCapacity )
m_nOreUnits = m_oreCapacity;
m_strAnimation = Get_Parameter("Animation_Name");
if (strlen(m_strAnimation) <= 0 || !pObj->As_PhysicalGameObj())
m_strAnimation = NULL;
else
{
m_nAnimationFullFrame = Get_Int_Parameter("Animation_Full_Frame");
m_nAnimationEmptyFrame = Get_Int_Parameter("Animation_Empty_Frame");
UpdateAnimationFrame();
}
m_zoneSizeFull = Get_Vector3_Parameter("Zone_Size");
if ( m_strAnimation )
{
m_zoneStepX = Get_Float_Parameter("Zone_Anim_Step_X");
m_zoneStepY = Get_Float_Parameter("Zone_Anim_Step_Y");
}
m_bAiIgnore = (Get_Parameter_Count() >= 10) ? Get_Bool_Parameter("AI_Ignore") : false;
if (!pObj->As_ScriptZoneGameObj())
{
// Create the miner script zone
Matrix3 rotation(true);
rotation.Rotate_Z(DEG2RAD(Commands->Get_Facing(pObj)));
// Define the bounding box and create the zone
OBBoxClass zoneBoundingBox ( Commands->Get_Position(pObj), m_zoneSizeFull, rotation );
if ( GameObject* pMinerZone = Create_Zone("Script_Zone_All",zoneBoundingBox) )
{
m_minerZoneId = Commands->Get_ID(pMinerZone);
// Attach observer to the script zone
m_pZoneObserver = new dp88_Ore_Field_Observer(this);
pMinerZone->Add_Observer(m_pZoneObserver);
return;
}
}
else
{
m_minerZoneId = Commands->Get_ID(pObj);
return;
}
m_pZoneObserver = NULL;
Console_Output ( "[%d:%s:%s] Critical Error: Unable to create the miner script zone. Destroying script...\n", Commands->Get_ID(pObj), Commands->Get_Preset_Name(pObj), this->Get_Name() );
Destroy_Script();
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Field::Detach ( GameObject* pObj )
{
ScriptImpClass::Detach(pObj);
if ( m_pZoneObserver != NULL )
{
if ( GameObject* pMinerZone = Commands->Find_Object(m_minerZoneId) )
pMinerZone->Remove_Observer(m_pZoneObserver);
delete m_pZoneObserver;
m_pZoneObserver = NULL;
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Field::Entered ( GameObject* pZoneObj, GameObject* pEnterer )
{
if ( pZoneObj == Commands->Find_Object(m_minerZoneId) )
{
GameObject* pObj = Commands->Find_Object(m_myObjId);
Commands->Send_Custom_Event( pObj, pEnterer, CUSTOM_MINER_ENTERED_ORE_FIELD, 0, 0 );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Field::Exited ( GameObject* pZoneObj, GameObject* pExiter )
{
if ( pZoneObj == Commands->Find_Object(m_minerZoneId) )
{
GameObject* pObj = Commands->Find_Object(m_myObjId);
Commands->Send_Custom_Event( pObj, pExiter, CUSTOM_MINER_EXITED_ORE_FIELD, 0, 0 );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Field::AddOre ( unsigned int nUnits )
{
if ( m_oreCapacity != 0 )
{
m_nOreUnits += min(nUnits,m_oreCapacity-m_nOreUnits);
UpdateAnimationFrame();
}
}
// -------------------------------------------------------------------------------------------------
unsigned int dp88_Ore_Field::RemoveOre ( unsigned int nUnits )
{
if ( m_oreCapacity != 0 )
{
nUnits = min(nUnits,m_nOreUnits);
m_nOreUnits -= nUnits;
UpdateAnimationFrame();
}
return nUnits;
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Field::UpdateAnimationFrame()
{
if ( GameObject* pObj = Commands->Find_Object(m_myObjId) )
UpdateAnimationFrame(pObj);
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Field::UpdateAnimationFrame( GameObject* pObj )
{
if ( m_oreCapacity != 0 && m_strAnimation != NULL )
{
int frame = m_nAnimationFullFrame - (int)ceil((m_nAnimationFullFrame-m_nAnimationEmptyFrame)*((float)m_nOreUnits/m_oreCapacity));
Commands->Set_Animation_Frame(pObj, m_strAnimation, frame);
}
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_Ore_Field> dp88_Ore_Field_Registrant(
"dp88_Ore_Field",
"Ore_Value:int,"
"Ore_Capacity:int,"
"Ore_Units:int,"
"Animation_Name:string,"
"Animation_Full_Frame:int,"
"Animation_Empty_Frame:int,"
"Zone_Size:vector3,"
"Zone_Anim_Step_X:float,"
"Zone_Anim_Step_Y:float,"
"AI_Ignore=0:int"
);
/*------------------------
Ore Extractor
--------------------------*/
void dp88_Ore_Extractor::Created ( GameObject* pObj )
{
if ( GameObject* pOreField = Find_Closest_Object_With_Script("dp88_Ore_Field", Commands->Get_Position(pObj)) )
{
m_oreFieldId = Commands->Get_ID(pOreField);
m_nOreUnits = Get_Int_Parameter("Ore_Units");
m_interval = Get_Int_Parameter("Extraction_Interval");
m_strAnimation = Get_Parameter("Extraction_Animation");
if ( strlen(m_strAnimation) <= 0 )
m_strAnimation = NULL;
Commands->Start_Timer(pObj, this, (float)m_interval, TIMER_OREMINING_EXTRACTOR );
return;
}
Console_Output ( "[%d:%s:%s] Critical Error: Unable to locate an ore field zone. Destroying script...\n", Commands->Get_ID(pObj), Commands->Get_Preset_Name(pObj), this->Get_Name() );
Destroy_Script();
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Extractor::Timer_Expired ( GameObject* pObj, int number )
{
if ( number == TIMER_OREMINING_EXTRACTOR )
{
if ( m_strAnimation )
Commands->Set_Animation ( pObj, m_strAnimation, false, NULL, 0, -1, false );
else
Animation_Complete(pObj, NULL);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_Ore_Extractor::Animation_Complete ( GameObject* pObj, const char* animationName )
{
if ( (m_strAnimation == NULL && animationName == NULL)
|| (m_strAnimation != NULL && animationName != NULL && 0 == _stricmp(m_strAnimation,animationName)) )
{
// Populate ore field with additional ore
GameObject* pOreField = Commands->Find_Object(m_oreFieldId);
if ( !pOreField )
{
Destroy_Script();
return;
}
dp88_Ore_Field* pOreFieldScript = (dp88_Ore_Field *)(Find_Script_On_Object(pOreField, "dp88_Ore_Field"));
if ( !pOreFieldScript )
{
Destroy_Script();
return;
}
pOreFieldScript->AddOre(m_nOreUnits);
// Set timer for next extraction
Commands->Start_Timer(pObj, this, (float)m_interval, TIMER_OREMINING_EXTRACTOR );
}
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_Ore_Extractor> dp88_Ore_Extractor_Registrant(
"dp88_Ore_Extractor",
"Ore_Units:int,"
"Extraction_Interval:int,"
"Extraction_Animation:string"
);
/*------------------------
Ore Deposit Zone Controller
--------------------------*/
void dp88_Ore_Dump_Zone::Entered( GameObject *obj, GameObject *enterer )
{
if ( Get_Object_Type(enterer) == Get_Int_Parameter( "Team" ) )
Commands->Send_Custom_Event( obj, enterer, CUSTOM_MINER_ENTERED_DUMP_ZONE, Get_Int_Parameter( "Team" ), 0 );
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_Ore_Dump_Zone> dp88_Ore_Dump_Zone_Registrant(
"dp88_Ore_Dump_Zone",
"Team=0:int"
);
/*------------------------
Aircraft Landing Zone Scripts
--------------------------*/
// Landing Zone
void dp88_Aircraft_LandingZone::Entered( GameObject *obj, GameObject *enterer )
{
Commands->Send_Custom_Event( obj, enterer, CUSTOM_TRANSITION_VTOL_LAND_ZONE, 1, 0 );
}
void dp88_Aircraft_LandingZone::Exited( GameObject *obj, GameObject *exiter )
{
Commands->Send_Custom_Event( obj, exiter, CUSTOM_TRANSITION_VTOL_LAND_ZONE, 0, 0 );
}
// Landing Zone - Aircraft
void dp88_Aircraft_LandingZone_Aircraft::Created ( GameObject *obj )
{
driverID = 0;
landingZoneCount = 0;
if (Get_Int_Parameter("require_landing_zone") >= 1)
{
Commands->Enable_Vehicle_Transitions(obj,false);
}
}
void dp88_Aircraft_LandingZone_Aircraft::Killed ( GameObject *obj, GameObject* killer )
{
// We can't simply kill the pilot because things go horribly wrong... instead use the script
// JFW_Timer_Destroy_Object to kill them as soon as possible.
if ( driverID != 0 && landingZoneCount == 0 && Get_Int_Parameter("require_landing_zone") >= 1 )
{
if ( GameObject* driver = Commands->Find_Object(driverID) )
Commands->Attach_Script ( driver, "JFW_Timer_Destroy_Object", "1.0,547859,5000.0,Death" );
}
}
void dp88_Aircraft_LandingZone_Aircraft::Custom ( GameObject *obj, int type, int param, GameObject *sender )
{
if ( type == CUSTOM_TRANSITION_VTOL_LAND_ZONE && param == 1 )
{
landingZoneCount++;
// Play landing animation if this is the first zone we have entered
if ( landingZoneCount == 1 )
{
if (Get_Int_Parameter("require_landing_zone") >= 1)
{
Commands->Enable_Vehicle_Transitions(obj,true);
}
Commands->Set_Animation( obj,Get_Parameter("landing_anim_name"), false, 0, Get_Float_Parameter("landing_anim_first_frame"), Get_Float_Parameter("landing_anim_last_frame"), false );
}
}
else if ( type == CUSTOM_TRANSITION_VTOL_LAND_ZONE && param == 0 )
{
landingZoneCount--;
// Play take off animation if this is the last zone we were in (landing anim in reverse...)
if ( landingZoneCount == 0 )
{
if (Get_Int_Parameter("require_landing_zone") >= 1)
{
Commands->Enable_Vehicle_Transitions(obj,false);
}
Commands->Set_Animation( obj, Get_Parameter("landing_anim_name"), false, 0, Get_Float_Parameter("landing_anim_last_frame"), Get_Float_Parameter("landing_anim_first_frame"), false );
}
}
else if ( type == CUSTOM_EVENT_VEHICLE_ENTERED && driverID == NULL )
driverID = Commands->Get_ID(sender);
else if ( type == CUSTOM_EVENT_VEHICLE_EXITED && Commands->Get_ID(sender) == driverID )
{
driverID = NULL;
// If the driver exited outside of a landing zone then kablooey!
if ( Get_Int_Parameter("require_landing_zone") >= 1 && landingZoneCount == 0 )
{
Commands->Apply_Damage(sender, 10000.0f, "Death", obj );
Commands->Apply_Damage(obj, 10000.0f, "Death", obj );
}
}
}
/*------------------------
Terror Drone Script
--------------------------*/
/*void dp88_AR_TerrorDrone::Created ( GameObject *obj )
{
//Console_Output ( "Created dp88_AR_TerrorDrone\n" );
pilotID = 0;
targetID = 0;
consoleID = 0;
// Report our creation to the game controller to pass on to the console
Commands->Send_Custom_Event ( obj, Find_Object_With_Script("dp88_AR_GameController"), CUSTOM_TD_REPORTCREATION, Commands->Get_ID( obj ), 1 );
// Remember default model
strcpy_s ( defaultModel, sizeof(defaultModel), Get_Model ( obj ) );
}
void dp88_AR_TerrorDrone::Custom( GameObject *obj, int type, int param, GameObject *sender )
{
// Look for vehicle entry
if ( type == CUSTOM_EVENT_VEHICLE_ENTERED )
{
if ( pilotID == 0 )
pilotID = Commands->Get_ID(sender);
}
// Look for vehicle exit
else if ( type == CUSTOM_EVENT_VEHICLE_EXITED )
{
if ( Commands->Get_ID(sender) == pilotID )
{
pilotID = 0;
// Report driver exit to our console
Commands->Send_Custom_Event( obj, Commands->Find_Object( consoleID ), CUSTOM_TD_DRIVEREXIT, 1, 0 );
}
}
// Look for console reporting
else if ( type == CUSTOM_TD_CONSOLEID && consoleID == 0 )
{
consoleID = Commands->Get_ID ( sender );
}
// A target reporting we have successfully latched on to them
else if ( type == CUSTOM_TD_TARGET_ID )
{
targetID = Commands->Get_ID( sender );
Commands->Set_Model ( obj, "dumbox" );
Commands->Set_Position ( obj, Commands->Get_Position ( sender ) );
Commands->Attach_To_Object_Bone ( obj, sender, "worldbox" );
Commands->Disable_All_Collisions ( obj );
}
// A target reporting they have died
else if ( type == CUSTOM_TD_TARGET_DIED )
{
targetID = 0;
Vector3 newPosition = Commands->Get_Position ( obj );
newPosition.Z += 0.5;
Commands->Set_Position ( obj, newPosition );
Commands->Enable_Collisions ( obj );
Commands->Set_Model ( obj, defaultModel );
}
// A target reporting they have been repaired (kills terror drone)
else if ( type == CUSTOM_TD_TARGET_REPAIRED )
{
Commands->Apply_Damage ( obj, 5000.00, "Death", sender );
}
}
void dp88_AR_TerrorDrone::Killed ( GameObject *obj, GameObject *killer )
{
if ( targetID )
Commands->Send_Custom_Event( obj, Commands->Find_Object( targetID ), CUSTOM_TD_TD_DIED, 1, 0 );
targetID = 0;
// Report death to our console
Commands->Send_Custom_Event( obj, Commands->Find_Object( consoleID ), CUSTOM_TD_TD_DIED, 1, 0 );
}*/
// -------------------------------------------------------------------------------------------------
// Remote Control Console Script
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::Created ( GameObject *obj )
{
//Console_Output ( "[%d:%s:%s] Created - remoteControlID %d\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name(), Get_Int_Parameter("remoteControlID") );
vehicleID = NULL;
pilotID = NULL;
m_pilotDummyID = NULL;
m_bEnabled = true;
m_nChargeTime = Get_Int_Parameter ( "chargeTime" );
m_pLoopedAnimCtrl = new LoopedAnimationController(obj);
// Start charge tick timer if necessary and set initial animation frames
if ( m_nChargeTime > 0 )
{
Commands->Start_Timer( obj, this, 1.0f, TIMER_REMOTECONTROL_CHARGETICK);
}
UpdateAnimation(obj);
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::Detach ( GameObject* obj )
{
ScriptImpClass::Detach(obj);
if (m_pLoopedAnimCtrl)
{
delete m_pLoopedAnimCtrl;
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::Poked ( GameObject *obj, GameObject *poker )
{
//Console_Output ( "[%d:%s:%s] Poked\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Check the team of the poker
int team = Get_Int_Parameter("team");
if ( team != 2 && Get_Object_Type(poker) != team )
{
//Console_Output ( "[%d:%s:%s] Console access denied\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Play access denied sound
Create_2D_Sound_Player(poker, Get_Parameter("accessDeniedSound") );
return;
}
// Check if the terminal is offline
if ( !m_bEnabled )
{
//Console_Output ( "[%d:%s:%s] Console is offline\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Play console offline sound
Create_2D_Sound_Player(poker, Get_Parameter("consoleOfflineSound") );
return;
}
// Check if the terminal is charging
if ( m_nChargeTime > 0 )
{
//Console_Output ( "[%d:%s:%s] Console still charging\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Play console charging sound
Create_2D_Sound_Player(poker, Get_Parameter("consoleChargingSound") );
return;
}
// If no vehicle currently exists then create one
if ( pilotID == NULL && vehicleID == NULL )
{
//Console_Output ( "[%d:%s:%s] BUYING\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Try to purchase the unit, will fail if we don't have enough money
int cost = Get_Int_Parameter ( "cost" );
if ( !Purchase_Item(poker, cost ) )
{
//Console_Output ( "[%d:%s:%s] NO NOOLAH\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Play insufficient funds denied sound
Create_2D_Sound_Player(poker, Get_Parameter("insufficientFundsSound") );
return;
}
// OK, we have paid for the unit, lets proceed... first glue the driver in place...
pilotID = Commands->Get_ID( poker );
Commands->Control_Enable ( poker, false );
UpdateAnimation(obj);
// ...Then create the vehicle...
//Console_Output ( "[%d:%s:%s] Creating remote control vehicle %s\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name(), Get_Parameter ( "vehiclePreset" ) );
if (!Create_Vehicle( Get_Parameter ( "vehiclePreset" ), 0.0, Commands->Find_Object( pilotID ), Get_Object_Type( Commands->Find_Object(pilotID) ) ))
{
Timer_Expired(obj, TIMER_REMOTECONTROL_TIMEOUT);
}
else
{
// And wait for confirmation... start a timer in the event that we don't ever get this...
Commands->Start_Timer ( obj, this, 5.0, TIMER_REMOTECONTROL_TIMEOUT );
}
}
// OK, a vehicle already exists, does it have a pilot? If not then take control of it
else if ( pilotID == NULL )
{
//Console_Output ( "[%d:%s:%s] ENTER EXISTING\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Enable transitions and wait until they are active to put driver in
GameObject* vehicle = Commands->Find_Object(vehicleID);
if ( vehicle )
{
// Stop the pilot from walking away in the meantime
pilotID = Commands->Get_ID( poker );
Commands->Control_Enable ( poker, false );
// Disable pokeable indicator
UpdateAnimation(obj);
Commands->Enable_Vehicle_Transitions( vehicle, true );
Commands->Start_Timer ( obj, this, 0.5, TIMER_REMOTECONTROL_DRIVERENTER );
}
else
vehicleID = NULL; // This should never actually happen... but just in case...
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::Custom( GameObject *obj, int type, int param, GameObject *sender )
{
//Console_Output ( "[%d:%s:%s] Custom %d - %d\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name(), type, param );
if ( type == CUSTOM_REMOTECONTROL_CREATED && param == Get_Int_Parameter("remoteControlID") && vehicleID == NULL && pilotID != NULL )
{
//Console_Output ( "[%d:%s:%s] Sending console ID to unit\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// Inform the remote control unit that this is it's console (we do this to prevent multiple
// consoles trying to control the same unit if two are created close together)
Commands->Send_Custom_Event ( obj, sender, CUSTOM_REMOTECONTROL_CONSOLEID, 0, 0.0 );
// Wait for the remote control unit to accept this as it's console - it will only accept the
// first response it recieves, so we may not hear back from it...
}
else if ( type == CUSTOM_REMOTECONTROL_CONSOLEACK )
{
//Console_Output ( "[%d:%s:%s] Recieved ACK from unit, establishing control\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
// The remote control unit has accepted us as it's control console
vehicleID = Commands->Get_ID(sender);
// Put our pilot in the drivers seat
Commands->Enable_Vehicle_Transitions( sender, true );
Commands->Start_Timer ( obj, this, 0.5, TIMER_REMOTECONTROL_DRIVERENTER );
}
else if ( type == CUSTOM_REMOTECONTROL_DRIVEREXIT )
{
DestroyDummy();
HandleDriverExit ( obj, Commands->Find_Object(pilotID), sender );
pilotID = NULL;
}
else if ( type == CUSTOM_REMOTECONTROL_DESTROYED )
{
//Console_Output ( "[%d:%s:%s] Remote control unit was destroyed\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
vehicleID = NULL;
// Start timer to return the pilot (if we do it immediately the game will crash...)
if (NULL != pilotID)
Commands->Start_Timer ( obj, this, 0.5, TIMER_REMOTECONTROL_DRIVEREXIT );
// Reset charge time
m_nChargeTime = Get_Int_Parameter("chargeTime");
// Start charge tick timer if necessary and set initial animation frames
if (m_bEnabled && m_nChargeTime > 0)
{
Commands->Start_Timer( obj, this, 1.0f, TIMER_REMOTECONTROL_CHARGETICK);
}
UpdateAnimation(obj);
}
else if ( type == CUSTOM_REMOTECONTROL_DISABLED )
{
SetEnabled(obj, false);
}
else if ( type == CUSTOM_REMOTECONTROL_ENABLED )
{
SetEnabled(obj, true);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::Timer_Expired ( GameObject *obj, int number )
{
if ( number == TIMER_REMOTECONTROL_TIMEOUT && vehicleID == 0 )
{
//Console_Output ( "[%d:%s:%s] Purchase timed out, refunding money and freeing pilot\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
GameObject* pilot = Commands->Find_Object(pilotID);
if ( pilot )
{
Commands->Control_Enable(pilot, true);
Commands->Give_Money(pilot, (float)(Get_Int_Parameter("cost")), 0);
}
pilotID = NULL;
UpdateAnimation(obj);
}
else if ( number == TIMER_REMOTECONTROL_DRIVERENTER )
{
//Console_Output ( "[%d:%s:%s] Transitioning driver into vehicle\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
GameObject* vehicle = Commands->Find_Object(vehicleID);
GameObject* pilot = Commands->Find_Object(pilotID);
if (pilot)
{
HandleDriverEnter(obj, pilot, vehicle);
}
else // This should never actually happen... but just in case...
{
Commands->Enable_Vehicle_Transitions(vehicle, false);
pilotID = NULL;
UpdateAnimation(obj);
}
}
// This can be called for the vehicle being destroyed OR the console becoming disabled
else if ( number == TIMER_REMOTECONTROL_DRIVEREXIT )
{
DestroyDummy();
HandleDriverExit ( obj, Commands->Find_Object(pilotID), Commands->Find_Object(vehicleID) );
pilotID = NULL;
}
// Count down tick for charge time
else if ( number == TIMER_REMOTECONTROL_CHARGETICK )
{
if ( m_bEnabled )
{
m_nChargeTime--;
if ( m_nChargeTime > 0 )
Commands->Start_Timer( obj, this, 1.0f, TIMER_REMOTECONTROL_CHARGETICK);
else
{
UpdateAnimation(obj);
}
}
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::SetEnabled(GameObject* obj, bool state)
{
if ( state == m_bEnabled )
return;
m_bEnabled = state;
// If we are no longer enabled evict the driver
if (!m_bEnabled && NULL != pilotID)
{
GameObject* pilot = Commands->Find_Object(pilotID);
if (NULL != pilot)
{
Soldier_Transition_Vehicle(pilot);
Create_2D_Sound_Player(pilot, Get_Parameter("consoleOfflineSound"));
// Force a network update
Update_Network_Object(pilot);
// Can't do this instantly or the game crashes. Yay!
Commands->Start_Timer(obj, this, 0.5, TIMER_REMOTECONTROL_DRIVEREXIT);
}
}
// Start charging for next use (if applicable)
if (m_nChargeTime > 0)
{
Commands->Start_Timer( obj, this, 1.0f, TIMER_REMOTECONTROL_CHARGETICK);
}
UpdateAnimation(obj);
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::HandleDriverEnter(GameObject* obj, GameObject* pilot, GameObject* vehicle)
{
if (NULL != pilot && NULL != vehicle)
{
// Create pilot dummy...
CreateDummy(pilot, Commands->Get_Position(pilot), Commands->Get_Facing(pilot));
Commands->Control_Enable(pilot, true);
// Make driver invisible so you don't see them flash on screen when exiting a drone
Commands->Set_Is_Rendered(pilot, false);
// Set the pilot to the uncollidable group so they can't be killed before they are teleported home
PhysicalGameObj *physPilot = pilot->As_PhysicalGameObj();
if (NULL != physPilot)
{
m_pilotCachedCollisionGroup = physPilot->Peek_Physical_Object()->Get_Collision_Group();
physPilot->Peek_Physical_Object()->Set_Collision_Group(UNCOLLIDEABLE_GROUP);
}
// Update the pilot object and then force them into the vehicle
Update_Network_Object(pilot);
Force_Vehicle_Entry(pilot, vehicle);
// Play control established sound
Create_2D_Sound_Player(pilot, Get_Parameter("connectionEstablishedSound"));
UpdateAnimation(obj);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::HandleDriverExit(GameObject* obj, GameObject* pilot, GameObject* vehicle)
{
if (pilot)
{
Commands->Set_Position ( pilot, pilotDummyPos );
// Make driver visible and collidable again
Commands->Set_Is_Rendered ( pilot, true );
PhysicalGameObj *physPilot = pilot->As_PhysicalGameObj();
if (NULL != physPilot)
{
physPilot->Peek_Physical_Object()->Set_Collision_Group(m_pilotCachedCollisionGroup);
}
Update_Network_Object(pilot);
}
// If the vehicle is still alive set it to its idle state
if ( vehicle )
{
// Set team to correct setting (so it gives points for being damaged)
Set_Object_Type ( vehicle, Get_Int_Parameter("team") );
// Disable transitions on remote vehicle
Commands->Enable_Vehicle_Transitions( vehicle, false );
}
// Start charging for next use (if applicable)
if (m_nChargeTime > 0)
{
Commands->Start_Timer( obj, this, 1.0f, TIMER_REMOTECONTROL_CHARGETICK);
}
UpdateAnimation(obj);
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::CreateDummy ( GameObject* pilot, Vector3 position, float facing )
{
GameObject* dummy = Commands->Create_Object ( "Invisible_Object_2", position );
if ( dummy )
{
m_pilotDummyID = Commands->Get_ID(dummy);
Commands->Set_Facing(dummy, facing);
pilotDummyPos = position; // Used to put the pilot back in his original location
// Clone health/armour
Set_Skin(dummy, Get_Skin(pilot) );
Commands->Set_Shield_Type(dummy, Get_Shield_Type(pilot) );
Set_Max_Health(dummy, Commands->Get_Max_Health(pilot) );
Set_Max_Shield_Strength(dummy, Commands->Get_Max_Shield_Strength(pilot) );
Commands->Set_Health(dummy, Commands->Get_Health(pilot) );
Commands->Set_Shield_Strength(dummy, Commands->Get_Shield_Strength(pilot) );
Set_Object_Type(dummy, Get_Object_Type(pilot));
// Link dummy and pilot health and armour
char pilotIdString[12];
sprintf ( pilotIdString, "%d", Commands->Get_ID(pilot) );
Attach_Script_Once ( dummy, "dp88_linkHealth", pilotIdString );
// Clone player model onto dummy and set a pose
Commands->Set_Model(dummy, Get_Model(pilot));
Commands->Set_Animation(dummy, "S_A_HUMAN.H_A_A0A0", true, NULL, 0, 0, false);
// Setup soldier collision mode on the dummy
PhysicalGameObj *physDummy = dummy->As_PhysicalGameObj();
if (NULL != physDummy)
physDummy->Peek_Physical_Object()->Set_Collision_Group(SOLDIER_COLLISION_GROUP);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::DestroyDummy()
{
if (NULL != m_pilotDummyID)
{
GameObject* dummy = Commands->Find_Object(m_pilotDummyID);
m_pilotDummyID = NULL;
// Destroy the dummy object rather than killing it - this prevents dp88_linkHealth from also
// killing the pilot
if ( dummy )
Commands->Destroy_Object(dummy);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlConsole::UpdateAnimation(GameObject* obj)
{
bool bPokable = false;
if (!m_bEnabled)
m_pLoopedAnimCtrl->PlayAnimation(Get_Parameter("animationName"), Get_Int_Parameter("animFrameDisabled1"), Get_Int_Parameter("animFrameDisabled2"));
else if (NULL != pilotID)
m_pLoopedAnimCtrl->PlayAnimation(Get_Parameter("animationName"), Get_Int_Parameter("animFrameActive1"), Get_Int_Parameter("animFrameActive2"));
else if (NULL != vehicleID)
{
m_pLoopedAnimCtrl->PlayAnimation(Get_Parameter("animationName"), Get_Int_Parameter("animFrameIdle1"), Get_Int_Parameter("animFrameIdle2"));
bPokable = true;
}
else if (m_nChargeTime > 0)
m_pLoopedAnimCtrl->PlayAnimation(Get_Parameter("animationName"), Get_Int_Parameter("animFrameCharging1"), Get_Int_Parameter("animFrameCharging2"));
else
{
m_pLoopedAnimCtrl->PlayAnimation(Get_Parameter("animationName"), Get_Int_Parameter("animFrameAvailable1"), Get_Int_Parameter("animFrameAvailable2"));
bPokable = true;
}
Commands->Enable_HUD_Pokable_Indicator(obj, bPokable);
}
// -------------------------------------------------------------------------------------------------
// Remote Control Vehicle Script
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlVehicle::Created ( GameObject *obj )
{
//Console_Output ( "[%d:%s:%s] Created - remoteControlID %d\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name(), Get_Int_Parameter("remoteControlID") );
consoleID = NULL;
pilotID = NULL;
Commands->Enable_Vehicle_Transitions(obj, false);
// Notify all consoles of our creation and disable transitions by default
Send_Custom_Event_To_Objects_With_Script(obj, "dp88_RemoteControlConsole", CUSTOM_REMOTECONTROL_CREATED, Get_Int_Parameter("remoteControlID"), 0 );
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlVehicle::Custom( GameObject *obj, int type, int param, GameObject *sender )
{
// Look for vehicle entry
if ( type == CUSTOM_EVENT_VEHICLE_ENTERED )
{
if ( pilotID == 0 )
pilotID = Commands->Get_ID(sender);
}
// Look for vehicle exit
else if ( type == CUSTOM_EVENT_VEHICLE_EXITED )
{
if ( Commands->Get_ID(sender) == pilotID )
{
pilotID = 0;
// Report driver exit to our console
if ( consoleID != NULL )
Commands->Send_Custom_Event( obj, Commands->Find_Object( consoleID ), CUSTOM_REMOTECONTROL_DRIVEREXIT, 1, 0 );
}
}
// Look for console reporting and, if we don't already have a console, send an ACK
// to accept them as our controller
else if ( type == CUSTOM_REMOTECONTROL_CONSOLEID && consoleID == 0 )
{
//Console_Output ( "[%d:%s:%s] Got console, sending ACK\n", Commands->Get_ID(obj), Commands->Get_Preset_Name(obj), this->Get_Name() );
consoleID = Commands->Get_ID ( sender );
Commands->Send_Custom_Event(obj, sender, CUSTOM_REMOTECONTROL_CONSOLEACK, 1 ,0);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_RemoteControlVehicle::Killed ( GameObject* obj, GameObject* killer )
{
if ( consoleID != NULL )
Commands->Send_Custom_Event( obj, Commands->Find_Object( consoleID ), CUSTOM_REMOTECONTROL_DESTROYED, 1, 0 );
}
/*------------------------
Demo Truck Scripts
--------------------------*/
void dp88_AR_DemoTruck::Created( GameObject *obj )
{
//Console_Output ( "Created dp88_AR_DemoTruck\n" );
pilotID = 0;
canDetonate = true;
}
void dp88_AR_DemoTruck::Custom( GameObject *obj, int type, int param, GameObject *sender )
{
// Look for vehicle entry
if ( type == CUSTOM_EVENT_VEHICLE_ENTERED )
{
if ( pilotID == 0 )
pilotID = Commands->Get_ID(sender);
}
// Look for vehicle exit
else if ( type == CUSTOM_EVENT_VEHICLE_EXITED )
{
if ( Commands->Get_ID(sender) == pilotID && canDetonate )
pilotID = 0;
}
}
void dp88_AR_DemoTruck::Killed( GameObject *obj, GameObject *killer )
{
Detonate( obj );
}
void dp88_AR_DemoTruck::Damaged ( GameObject *obj, GameObject *damager, float amount )
{
// If we damaged ourselves thats the trigger to detonate
if ( Commands->Get_ID ( damager ) == Commands->Get_ID ( Get_Vehicle_Driver ( obj ) ) && amount == 0.0 )
Detonate( obj );
}
void dp88_AR_DemoTruck::Detonate( GameObject *obj )
{
if ( canDetonate )
{
canDetonate = false;
// Create the explosion
if ( pilotID != 0 )
{
Commands->Create_Explosion ( Get_Parameter ( "explosionPreset" ),
Commands->Get_Position ( Commands->Find_Object( pilotID ) ),
Commands->Find_Object( pilotID )
);
Ranged_Scale_Damage_To_Buildings(
Get_Float_Parameter ( "buildingDamageStrength" ),
Get_Parameter ( "buildingDamageWarhead" ),
Commands->Get_Position( Commands->Find_Object( pilotID ) ),
Get_Float_Parameter ( "buildingDamageRange" ),
Commands->Find_Object( pilotID )
);
}
else
{
Commands->Create_Explosion ( Get_Parameter ( "explosionPreset" ),
Commands->Get_Position ( obj ),
obj
);
Ranged_Scale_Damage_To_Buildings(
Get_Float_Parameter ( "buildingDamageStrength" ),
Get_Parameter ( "buildingDamageWarhead" ),
Commands->Get_Position( obj ),
Get_Float_Parameter ( "buildingDamageRange" ),
obj
);
}
// Create cinematic if nessicary
if ( strcmp ( Get_Parameter( "cinematicPreset" ), "null" ) != 0 )
Commands->Create_Object ( Get_Parameter ( "cinematicPreset" ), Commands->Get_Position ( obj ) );
// Kill driver and truck - can't kill driver instantly as truck protects them
Commands->Apply_Damage ( obj, 5000.00, "Death", obj );
if ( pilotID != 0 )
Commands->Attach_Script( Commands->Find_Object( pilotID ),"RA_DriverDeath", "0" );
}
}
/*------------------------
Paradrop Scripts
--------------------------*/
void dp88_AR_paradrop_Console::Created ( GameObject *obj )
{
//Console_Output ( "Created dp88_AR_paradrop_Console\n" );
last_triggered = 0;
}
void dp88_AR_paradrop_Console::Poked ( GameObject *obj, GameObject *poker )
{
// Deny use to members of the wrong team (unless team == 2 (ie: anyone))
if ( Get_Int_Parameter("team") != 2 && Get_Object_Type(poker) != Get_Int_Parameter("team"))
{
Send_Message_Player(obj, 153, 204, 25, "Invalid Security Clearance\n");
return;
}
if ( time(NULL)-last_triggered < 180 )
{
Send_Message_Player(obj, 153, 204, 25, "This can only be used once every 3 minutes\n");
return;
}
last_triggered = (int)time(NULL);
// TEMP
Vector3 pos;
pos.X = -40.0f;
pos.Y = 110.0f;
pos.Z = 40.0f;
// Change poker into paradrop unit and teleport to position
Commands->Set_Position(poker,pos);
Change_Character(poker,"Allied_GI_Paradrop");
// Spawn 3 bots to go with me :)
for ( int i = 0; i < 3; i++ )
{
pos.X += 2;
pos.Y += 2;
Commands->Create_Object ( "Allied_GI_Paradrop", pos );
}
}
// -------------------------------------------------------------------------------------------------
// Registrar goes here...
//
void dp88_AR_Paradrop::Created( GameObject* pObj )
{
if ( !pObj->As_SoldierGameObj() )
{
Console_Output ( "[%d:%s:%s] Critical Error: This script is only compatible with soldier game objects. Destroying script...\n", Commands->Get_ID(pObj), Commands->Get_Preset_Name(pObj), this->Get_Name() );
Destroy_Script();
return;
}
//Console_Output ( "Created dp88_AR_paradrop\n" );
earth_warhead = ArmorWarheadManager::Get_Warhead_Type("Earth");
m_nParachuteModel = 0;
const char* parachute_model = Get_Parameter("Parachute_Model");
if ( strlen(parachute_model) > 0 )
{
GameObject* pParachute = Commands->Create_Object("Invisible_Object",Commands->Get_Position(pObj));
Commands->Set_Model ( pParachute, parachute_model );
Commands->Attach_To_Object_Bone(pParachute, pObj, Get_Parameter("Parachute_Bone"));
m_nParachuteModel = Commands->Get_ID(pParachute);
}
Vector3 velocity = Get_Velocity(pObj);
m_fallRate = velocity.Z;
Commands->Start_Timer(pObj, this, 1.0f, TIMER_PARADROP_CHECKFALLRATE );
if ( strlen(Get_Parameter("Animation")) > 0 )
{
m_pAnimController = new LoopedAnimationController(pObj);
m_pAnimController->PlayAnimation ( Get_Parameter("Animation"), Get_Int_Parameter("Animation_First_Frame"), Get_Int_Parameter("Animation_Last_Frame"), (Get_Int_Parameter("Animation_Looped")==1) );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Paradrop::Damaged( GameObject* pObj, GameObject* pDamager, float amount )
{
if ( Get_Damage_Warhead() == earth_warhead )
{
// Repair the falling damage. Note that, in stock Renegade and most mods, falling damage ignores
// armour, so we can't use Apply_Damage to heal the damage, it has to be done manually
float health = Commands->Get_Health(pObj);
float max = Commands->Get_Max_Health(pObj);
health += amount;
if ( health > max )
{
amount -= abs(max-health);
health = max;
}
else
amount = 0.0f;
Commands->Set_Health(pObj, health);
// Apply any left-over repairs to the armour (to support mods where armour takes falling damage)
if ( amount > 0 )
{
health = Commands->Get_Shield_Strength(pObj);
max = Commands->Get_Max_Shield_Strength(pObj);
health += amount;
if ( health > max )
health = max;
Commands->Set_Shield_Strength(pObj, health);
}
Landed(pObj);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Paradrop::Killed( GameObject* pObj, GameObject* pKilled )
{
// Despawn the parachute model
if ( m_nParachuteModel != 0 )
Commands->Destroy_Object(Commands->Find_Object(m_nParachuteModel));
m_nParachuteModel = 0;
// Prevent anything else happening, such as Timer_Expired
Destroy_Script();
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Paradrop::Timer_Expired( GameObject* pObj, int number )
{
if ( number == TIMER_PARADROP_CHECKFALLRATE )
{
Vector3 velocity = Get_Velocity(pObj);
if ( velocity.Z > m_fallRate )
Landed(pObj);
else
{
m_fallRate = velocity.Z;
Commands->Start_Timer(pObj, this, 1.0f, TIMER_PARADROP_CHECKFALLRATE );
}
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Paradrop::Detach(GameObject* obj)
{
ScriptImpClass::Detach(obj);
delete m_pAnimController;
m_pAnimController = NULL;
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Paradrop::Landed ( GameObject* pObj )
{
// Despawn the parachute model
if ( m_nParachuteModel != 0 )
Commands->Destroy_Object(Commands->Find_Object(m_nParachuteModel));
m_nParachuteModel = 0;
// Swap to new infantry preset
const char* infantry_preset = Get_Parameter("Infantry_Preset");
if ( strlen(infantry_preset) > 0 && Is_Valid_Preset(infantry_preset) )
{
float health = Commands->Get_Health(pObj);
float armour = Commands->Get_Shield_Strength(pObj);
Change_Character(pObj, infantry_preset );
Commands->Set_Health(pObj, health);
Commands->Set_Shield_Strength(pObj, armour);
}
// Prevent anything else happening, such as Timer_Expired
Destroy_Script();
}
// -------------------------------------------------------------------------------------------------
ScriptRegistrant<dp88_AR_Paradrop> dp88_AR_Paradrop_Registrant(
"dp88_AR_Paradrop",
"Infantry_Preset:string,"
"Parachute_Model:string,"
"Parachute_Bone:string,"
"Animation:string,"
"Animation_First_Frame:int,"
"Animation_Last_Frame:int,"
"Animation_Looped:int"
);
/*------------------------
Prism Tower AI
--------------------------*/
// Static variable initialisation
int dp88_AR_Prism_Tower::prismTowerCount = 0;
int dp88_AR_Prism_Tower::prismTowerIds[MAX_TOWERS] = { 0 };
dp88_AR_Prism_Tower* dp88_AR_Prism_Tower::prismTowerScripts[MAX_TOWERS] = { NULL };
// Static function - register tower
void dp88_AR_Prism_Tower::registerTower(int towerId, dp88_AR_Prism_Tower* script)
{
// Find an empty slot for this tower
for ( int i = 0; i < MAX_TOWERS; ++i )
{
if ( prismTowerIds[i] == 0 )
{
prismTowerIds[i] = towerId;
prismTowerScripts[i] = script;
// Recalculate tower map
calculateTowerMap();
break;
}
}
}
// Static function - deregister tower
void dp88_AR_Prism_Tower::deregisterTower ( int towerId )
{
// Find this tower in the list and remove it from the array
for ( int i = 0; i < MAX_TOWERS; ++i )
{
if ( prismTowerIds[i] == towerId )
{
prismTowerIds[i] = 0;
clearTowerMap(i);
prismTowerScripts[i] = NULL;
// Recalculate tower map
calculateTowerMap();
break;
}
}
}
// Static function - clear tower map for a given index
void dp88_AR_Prism_Tower::clearTowerMap ( int idx )
{
if ( idx < MAX_TOWERS )
{
prismTowerScripts[idx]->adjacentTowerCount = 0;
if ( prismTowerScripts[idx]->adjacentTowers != NULL )
{
delete [] prismTowerScripts[idx]->adjacentTowers;
prismTowerScripts[idx]->adjacentTowers = NULL;
}
}
}
// Static function - calculate tower map
void dp88_AR_Prism_Tower::calculateTowerMap()
{
// Count number of registered towers and reset their adjacent tower indexes
int numTowers = 0;
for ( int i = 0; i < MAX_TOWERS; ++i )
{
if ( prismTowerIds[i] > 0 )
{
numTowers++;
clearTowerMap(i);
}
}
// Build array of all possible connections between registered towers - maximum
// number of nodes is n(n-1)/2 (IE: Complete graph), but unless the towers are
// very close together we will probably use less than this
int maxConnections = (int)(numTowers*((numTowers-1.0f)/2.0f));
int* towerConnections = new int[maxConnections*3];
memset(towerConnections,0,sizeof(int)*maxConnections*3);
// Populate array
int connectionCount = 0;
for ( int i = 0; i < MAX_TOWERS; ++i )
{
if ( prismTowerIds[i] > 0 )
{
GameObject* t1 = Commands->Find_Object(prismTowerIds[i]);
for ( int j = i+1; j < MAX_TOWERS; ++j )
{
if ( prismTowerIds[j] > 0 )
{
GameObject* t2 = Commands->Find_Object(prismTowerIds[j]);
// If these towers can assist each other then add them to the connections list
if (CanAssistTower(t1,t2, ((dp88_AR_Prism_Tower*)prismTowerScripts[i])->primary_maxRange))
{
towerConnections[connectionCount*3] = i;
towerConnections[(connectionCount*3)+1] = j;
towerConnections[(connectionCount*3)+2] = (int)Commands->Get_Distance(Commands->Get_Position(t1),Commands->Get_Position(t2));
connectionCount++;
}
}
}
}
}
// Now sort the entries in descending order and add a fourth field to
// allow the connections to be marked as 'bad' during the reverse
// delete algorithm
int* sortedTowerConnections = new int[connectionCount*4];
memset(sortedTowerConnections,0,sizeof(int)*connectionCount*4);
// Copy connections to the new array one by one, starting with the largest
// value and ending with the smallest... yes, this is probably a horribly
// inefficient way of doing this but it only occasionally and it works...
for ( int i = 0; i < connectionCount; ++i )
{
int maxDist = 0;
int maxDistIndex = -1;
for ( int j = 0; j < connectionCount; ++j )
{
if ( towerConnections[j*3] != -1 && towerConnections[(j*3)+2] > maxDist )
{
maxDist = towerConnections[(j*3)+2];
maxDistIndex = j;
}
}
// Copy highest index and set it's first tower ID to 0 so we skip past
// it in subsequent iterations
if ( maxDistIndex != -1 )
{
sortedTowerConnections[i*4] = towerConnections[maxDistIndex*3];
sortedTowerConnections[(i*4)+1] = towerConnections[(maxDistIndex*3)+1];
sortedTowerConnections[(i*4)+2] = towerConnections[(maxDistIndex*3)+2];
sortedTowerConnections[(i*4)+3] = 0; // Not a 'bad' connection
// Remove the copied item from the sort
towerConnections[maxDistIndex*3] = -1;
}
}
// Get rid of tower connections
delete [] towerConnections;
// OK, we have a sorted list of connections, now iterate through it and
// for each connection see if there is another path between the towers it
// links. If there is then get rid of this connection
for ( int i = 0; i < connectionCount; ++i )
{
// Mark the connection as bad
sortedTowerConnections[(i*4)+3] = 1;
// Check to see if another path exists between these towers - if it
// does not then this path is required for the minimum spanning tree
// so restore it as a 'good' path
if ( !calculateTowerMapPathSearch(sortedTowerConnections,connectionCount,sortedTowerConnections[i*4],sortedTowerConnections[(i*4)+1]) )
sortedTowerConnections[(i*4)+3] = 0;
}
// OK, we now have a minimum spanning tree... update each tower with
// a list of their neighbours
for ( int i = 0; i < connectionCount; ++i )
{
// Ignore 'bad' connections
if ( sortedTowerConnections[(i*4)+3] != 1 )
{
int tower1idx = sortedTowerConnections[i*4];
int tower1id = prismTowerIds[tower1idx];
dp88_AR_Prism_Tower* tower1script = prismTowerScripts[tower1idx];
int tower2idx = sortedTowerConnections[(i*4)+1];
int tower2id = prismTowerIds[tower2idx];
dp88_AR_Prism_Tower* tower2script = prismTowerScripts[tower2idx];
// Add tower2 to tower1's adjacent towers list
int* oldAdjacentTowers = tower1script->adjacentTowers;
tower1script->adjacentTowers = new int[++tower1script->adjacentTowerCount];
// Copy existing data
for ( int j = 0; j < tower1script->adjacentTowerCount-1; ++j )
tower1script->adjacentTowers[j] = oldAdjacentTowers[j];
// Delete old array
if ( oldAdjacentTowers != NULL )
delete [] oldAdjacentTowers;
// Add new adjacent tower
tower1script->adjacentTowers[tower1script->adjacentTowerCount-1] = tower2id;
// Add tower1 to tower2's adjacent towers list
oldAdjacentTowers = tower2script->adjacentTowers;
tower2script->adjacentTowers = new int[++tower2script->adjacentTowerCount];
// Copy existing data
for ( int j = 0; j < tower2script->adjacentTowerCount-1; ++j )
tower2script->adjacentTowers[j] = oldAdjacentTowers[j];
// Delete old array
if ( oldAdjacentTowers != NULL )
delete [] oldAdjacentTowers;
// Add new adjacent tower
tower2script->adjacentTowers[tower2script->adjacentTowerCount-1] = tower1id;
}
}
// Get rid of sorted tower connections
delete [] sortedTowerConnections;
}
bool dp88_AR_Prism_Tower::calculateTowerMapPathSearch(int* sortedConnections, int numConnections, int tower1, int tower2)
{
// Try to find a path between these towers
for ( int i = 0; i < numConnections; ++i )
{
// Ignore 'bad' connections
if ( sortedConnections[(i*4)+3] != 1 )
{
// If this is a connection between the towers we are searching for then
// return success
if ( (sortedConnections[i*4] == tower1 && sortedConnections[(i*4)+1] == tower2)
|| (sortedConnections[i*4] == tower2 && sortedConnections[(i*4)+1] == tower1) )
return true;
bool bFound = false;
// Temporarily mark this connection as "bad" to prevent infinite recursion
sortedConnections[(i*4)+3] = 1;
// If either of the two towers in this connection matches the desired tower then check for a
// path between the other desired tower and the third party tower it is connected to...
if ( sortedConnections[i*4] == tower1 )
bFound = calculateTowerMapPathSearch(sortedConnections,numConnections,tower2,sortedConnections[(i*4)+1]);
else if ( sortedConnections[(i*4)+1] == tower1 )
bFound = calculateTowerMapPathSearch(sortedConnections,numConnections,tower2,sortedConnections[i*4]);
else if ( sortedConnections[i*4] == tower2 )
bFound = calculateTowerMapPathSearch(sortedConnections,numConnections,tower1,sortedConnections[(i*4)+1]);
else if ( sortedConnections[(i*4)+1] == tower2 )
bFound = calculateTowerMapPathSearch(sortedConnections,numConnections,tower1,sortedConnections[i*4]);
// Restore this connection as "good"
sortedConnections[(i*4)+3] = 0;
if ( bFound )
return true;
}
}
// Nothing found...
return false;
}
bool dp88_AR_Prism_Tower::CanAssistTower(GameObject* tower1, GameObject* tower2, int maxRange)
{
int distance = (int)Commands->Get_Distance(Commands->Get_Position(tower1),Commands->Get_Position(tower2));
if (distance > maxRange)
return false;
// In weapons range so lets do a collision test to check for obstructions
/* CastResultStruct res;
LineSegClass ray(Commands->Get_Bone_Position(tower1,"muzzlea0"),GetAssistAimPoint(tower2));
PhysRayCollisionTestClass coltest(ray, &res, BULLET_COLLISION_GROUP);
PhysicsSceneClass::Get_Instance()->Cast_Ray(coltest,false);
if (NULL != coltest.CollidedPhysObj)
{
// todo: verify the collided object == tower2
// todo: what if we hit the source tower on the way out? Do we need to figure out some math
// to offset the beam origin to slightly beyond the bounds of the origin? Or maybe
// set the turret rotation to aim at the tower2?
// use PhysClass::Inc_Ignore_Counter and PhysClass::Dec_Ignore_Counter here to make the ray casting code ignore the object you want it to ignore
}*/
return true;
}
void dp88_AR_Prism_Tower::Created( GameObject *obj )
{
loadSettings(obj, false, false);
Init(obj);
// Initialise member variables
isAssistingTower = false;
adjacentTowerCount = 0;
adjacentTowers = NULL;
// Register the tower
registerTower(Commands->Get_ID(obj),this);
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::Damaged ( GameObject *obj, GameObject *damager, float amount )
{
// If the damager is a prism tower then we have been charged, add 1 to ammo count
if ( Is_Script_Attached ( damager, "dp88_AR_Prism_Tower" ) )
{
/* Increase ammo count by 1 */
if ( Get_Current_Weapon(obj) != NULL )
Set_Current_Bullets(obj,Get_Current_Bullets(obj)+1);
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::Killed ( GameObject *obj, GameObject *killer )
{
// Notify adjacent towers to stop assisting us if they were
for ( int i = 0; i < adjacentTowerCount; i++ )
{
if (Commands->Find_Object(adjacentTowers[i]) != obj)
{
Commands->Send_Custom_Event(obj,Commands->Find_Object(adjacentTowers[i]), CUSTOM_PRISMTOWER_STOP_CHARGING,0,0.0f);
}
}
// Deregister this tower
deregisterTower(Commands->Get_ID(obj));
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::Destroyed ( GameObject *obj )
{
// Deregister this tower
deregisterTower(Commands->Get_ID(obj));
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::Custom ( GameObject *obj, int type, int param, GameObject *sender )
{
// If we recieve a stop charging message from the tower we are currently
// charging then we should stop all actions
if ( type == CUSTOM_PRISMTOWER_STOP_CHARGING && isAssistingTower && sender == m_target )
StopAssisting(obj);
// If we recieve a request charging message from another tower then we
// should check to see if their target has higher priority than our
// current target (if any) and, if so, start charging them
else if ( type == CUSTOM_PRISMTOWER_REQUEST_CHARGING )
{
// Are we idle? If so then there's no reason not to simply start charging immediatly
if ( !m_target )
StartAssisting(obj, sender, (float)param);
// Is this request from the tower we are currently charging? If so then update the last seen
// time and priority and forward the assistance request to any other adjacent towers
else if ( isAssistingTower && m_target == sender )
{
targetLastSeen = (int)time(NULL);
targetPriority = (float)param;
SendAssistanceRequests(obj);
return;
}
// Is the priority of the request greater than the priority of our current target (either
// another tower or an enemy)? If so then stop what we are doing and charge the requester
else if ( param > targetPriority )
StartAssisting(obj, sender, (float)param );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::Timer_Expired ( GameObject *obj, int number )
{
// Piggy back our assistance polling and charge refilling on the existing think timer
if ( number == TIMER_AI_THINK )
{
/* Send out assistance requests to ensure other towers don't time out on the 'last seen' check
*
* \todo
* Can this screw up the timings between charging towers and the attacking tower? Need to think
* this through sometime and possibly do some experimentation...
*/
if ( m_target )
SendAssistanceRequests(obj);
/* Refill a single unit of charge if depleted */
if ( Get_Current_Clip_Bullets(obj) == 0 )
Set_Current_Clip_Bullets(obj,1);
/* If current bullets > 1 and no enemy seen recently then additional charge is lost */
if ( Get_Current_Bullets(obj) > 1 && !m_target )
Set_Current_Bullets(obj,1);
}
// Pass the timer onto the base class to be handled
dp88_AI_ChargedTurret::Timer_Expired(obj, number);
}
// -------------------------------------------------------------------------------------------------
float dp88_AR_Prism_Tower::getPriority( GameObject *obj, GameObject *target )
{
// If the target is the tower we are currently charging then return
// the priority of that charging sequence
if ( m_target == target && isAssistingTower )
return targetPriority;
// Otherwise run the normal priority calculation
return dp88_AI_ChargedTurret::getPriority(obj, target);
}
// -------------------------------------------------------------------------------------------------
bool dp88_AR_Prism_Tower::checkTeam( GameObject *obj, GameObject *target )
{
// Return true for the tower we are charging, even though it is on the same team as us
if ( m_target == target && isAssistingTower )
return true;
// Otherwise run the normal check team function
return dp88_AI_ChargedTurret::checkTeam(obj, target);
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::attackTarget ( GameObject* obj, GameObject* target, bool primary )
{
// Call base classes attack routine
dp88_AI_ChargedTurret::attackTarget(obj, target, primary);
// Send notifications for assistance
SendAssistanceRequests(obj);
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::attackLocation ( GameObject* obj, Vector3 location, bool primary )
{
// Call base classes attack routine
dp88_AI_ChargedTurret::attackLocation(obj, location, primary);
// Send notifications for assistance
SendAssistanceRequests(obj);
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::stopAttacking ( GameObject* obj )
{
// Was the target a tower we were charging? If so this means they must have timed out on the last
// seen and are therefore probably dead...
if ( isAssistingTower )
StopAssisting(obj);
// Otherwise we were attacking a normal target, send out end assistance notifications to all
// adjacent towers and call base class
else
{
SendEndAssistanceNotifications(obj);
dp88_AI_ChargedTurret::stopAttacking(obj);
}
}
// -------------------------------------------------------------------------------------------------
/* Start charging the specified tower */
void dp88_AR_Prism_Tower::StartAssisting(GameObject* obj, GameObject* tower, float priority)
{
// Set our new target ID and priority
m_target = tower;
targetPriority = priority;
targetLastSeen = (int)time(NULL);
isAssistingTower = true;
// Work out attack position
Vector3 chargePos = GetAssistAimPoint(tower);
// Start charging the tower - this will also trigger assistance notifications to be sent out
attackLocation ( obj, chargePos, true );
}
// -------------------------------------------------------------------------------------------------
/* Stop charging the specified tower */
void dp88_AR_Prism_Tower::StopAssisting(GameObject* obj)
{
if ( isAssistingTower )
{
m_target = nullptr;
targetPriority = 0;
isAssistingTower = false;
Commands->Action_Reset(obj, 101.0f);
}
// Send end assistance notifications
SendEndAssistanceNotifications(obj);
}
// -------------------------------------------------------------------------------------------------
Vector3 dp88_AR_Prism_Tower::GetAssistAimPoint(GameObject* pTargetTower)
{
Vector3 target = Commands->Get_Position(pTargetTower);
Vector3 height = Commands->Get_Bone_Position(pTargetTower,"muzzlea0");
target.Z = height.Z;
return target;
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::SendAssistanceRequests(GameObject* obj)
{
// Send out assistance requests to all adjacent towers except the one we are charging, if any
for ( int i = 0; i < adjacentTowerCount; ++i )
{
if ( adjacentTowers[i] != m_target->Get_ID() && Commands->Find_Object(adjacentTowers[i]) != obj)
Commands->Send_Custom_Event(obj, Commands->Find_Object(adjacentTowers[i]), CUSTOM_PRISMTOWER_REQUEST_CHARGING, (int)targetPriority, 0.0f );
}
}
// -------------------------------------------------------------------------------------------------
void dp88_AR_Prism_Tower::SendEndAssistanceNotifications(GameObject* obj)
{
// Send out end assistance notifications to all adjacent towers
for ( int i = 0; i < adjacentTowerCount; ++i )
{
if (Commands->Find_Object(adjacentTowers[i]) != obj)
{
Commands->Send_Custom_Event(obj, Commands->Find_Object(adjacentTowers[i]), CUSTOM_PRISMTOWER_STOP_CHARGING, 0, 0.0f );
}
}
}
// -------------------------------------------------------------------------------------------------
/*------------------------
Health Link Script
Maintains the same health & armour between two objects, for example
the AI warminer and its gun turret
--------------------------*/
void dp88_linkHealth::Created ( GameObject* obj )
{
parentObjID = Get_Int_Parameter ( "parentObjectId" );
GameObject* parent = Commands->Find_Object(parentObjID);
if ( !parent )
{
Destroy_Script();
return;
}
// Set initial values for lastHealth / lastArmour
lastHealth = Commands->Get_Health ( parent );
lastArmour = Commands->Get_Shield_Strength ( parent );
// Set our max / current health / armour to match our parent
Set_Max_Health ( obj, Commands->Get_Max_Health(parent) );
Commands->Set_Health ( obj, lastHealth );
Set_Max_Shield_Strength ( obj, Commands->Get_Max_Shield_Strength(parent) );
Commands->Set_Shield_Strength ( obj, lastArmour );
// Start timer
Commands->Start_Timer ( obj, this, 0.25, TIMER_LINKHEALTH );
}
void dp88_linkHealth::Timer_Expired ( GameObject* obj, int number )
{
equaliseHealth( obj );
// Restart timer if still alive
if ( lastHealth + lastArmour > 0.0f )
Commands->Start_Timer ( obj, this, 0.25, TIMER_LINKHEALTH );
}
void dp88_linkHealth::Killed ( GameObject* obj, GameObject *killer )
{
// Destroy parent object if its still alive
GameObject* parent = Commands->Find_Object ( parentObjID );
if ( parent )
{
// If the parent is a soldier in a vehicle we can't simply kill them because things go horribly wrong. Instead
// eject them from a vehicle and attach JFW_Timer_Destroy_Object to kill them as soon as possible.
if ( parent->As_SoldierGameObj() && parent->As_SoldierGameObj()->Is_In_Vehicle() )
{
Soldier_Transition_Vehicle ( parent );
Commands->Attach_Script ( parent, "JFW_Timer_Destroy_Object", "1.0,547859,5000.0,Death" );
Destroy_Script(); // Prevent equaliseHealth() getting called and trying to kill the driver
}
else
Commands->Apply_Damage ( parent, 5000.00, "None", NULL );
}
}
void dp88_linkHealth::equaliseHealth ( GameObject* obj )
{
GameObject* parent = Commands->Find_Object(parentObjID);
if (!parent)
{
Commands->Apply_Damage(obj, 5000.00, "Death", obj);
return;
}
/* Work out difference in our health and armour since last check */
float difference = ((Commands->Get_Health(obj)-lastHealth)+(Commands->Get_Shield_Strength(obj)-lastArmour));
/* Apply damage to parent using 'None' warhead (this should be 1-1 ratio against all skin and
shield types. Special case scenario: if the target is a soldier in a vehicle we need to use a
special function to override the check that prevents damage to soldiers in a vehicle */
if (0.0f != difference)
{
if ( parent->As_SoldierGameObj() && parent->As_SoldierGameObj()->Is_In_Vehicle() )
{
OffenseObjectClass offense(difference*-1.0f, ArmorWarheadManager::Get_Warhead_Type("None"), NULL);
parent->As_SoldierGameObj()->Apply_Damage_IgnoreVehicleCheck ( offense, 1, -1 );
}
else
Commands->Apply_Damage ( parent, difference*-1.0f, "None", NULL );
}
/* Update our health/armour from the parents new health/armour */
Commands->Set_Health ( obj, Commands->Get_Health(parent) );
Commands->Set_Shield_Strength ( obj, Commands->Get_Shield_Strength(parent) );
/* Set lastHealth / lastArmour */
lastHealth = Commands->Get_Health(obj);
lastArmour = Commands->Get_Shield_Strength(obj);
/* Are we dead? */
if ( lastHealth <= 0.0f )
{
Commands->Set_Health ( obj, 1.0f );
Commands->Apply_Damage ( obj, 5000.00f, "Death", obj );
Commands->Set_Health ( parent, 1.0f );
Commands->Apply_Damage ( parent, 5000.00f, "Death", NULL );
}
/* Otherwise apply 0 damage to ourselves to trigger any on-damage events
that need to run, such as dp88_damageAnimation() */
Commands->Apply_Damage ( obj, 0.0, "None", obj );
}
/*------------------------
Script Registrants
--------------------------*/
// Game Controller
ScriptRegistrant<dp88_AR_GameController> dp88_AR_GameController_Registrant( "dp88_AR_GameController", "enableCountry_Russia=1:int,enableCountry_Cuba=1:int,enableCountry_Iraq=1:int,enableCountry_Libya=1:int,enableCountry_America=1:int,enableCountry_France=1:int,enableCountry_Germany=1:int,enableCountry_GreatBritain=1:int,enableCountry_Korea=1:int,MirageTank_disguisePreset_1=mt_tree:string,MirageTank_disguisePreset_2=null:string,MirageTank_disguisePreset_3=null:string,Camouflage=u:string" );
// Unit scripts
//ScriptRegistrant<dp88_AR_Vehicle> dp88_AR_Vehicle_Registrant( "dp88_AR_Vehicle", "TD_attack_animName=modelfile.animfile:string,TD_attack_firstFrame=0.0:float,TD_attack_lastFrame=30.0:float,CLEG_Resistance=10:int" );
// Deployable Infantry
ScriptRegistrant<dp88_AR_Deployable_Infantry> dp88_AR_Deployable_Infantry_Registrant("dp88_AR_Deployable_Infantry", "deployedObjectPreset=null:string,deployedObjectSpaceRequired=6:float,deployAnimation=obj.obj:string,deployTime=4:float,undeployAnimation=obj.obj:string,undeployTime=4:float,deployedWeaponPowerup=null:string,deployedWeaponPowerup_veteran=null:string,deployedWeaponPowerup_elite=null:string,cannotDeployStringId=0:int,deployKeyhook=IDeploy:string,deployedArmourType=null:string,deployedArmourType_veteran=null:string,deployedArmourType_elite=null:string,deploySound:string,undeploySound:string");
// CLEG
ScriptRegistrant<dp88_AR_CLEG> dp88_AR_CLEG_Registrant("dp88_AR_CLEG","");
// CLEG resistance script
ScriptRegistrant<dp88_AR_CLEG_target> dp88_AR_CLEG_target_Registrant( "dp88_AR_CLEG_target", "resistance=20:int,clegEffectPreset=null:string" );
// Aircraft Landing Zone
ScriptRegistrant<dp88_Aircraft_LandingZone> dp88_Aircraft_LandingZone_Registrant("dp88_Aircraft_LandingZone","");
ScriptRegistrant<dp88_Aircraft_LandingZone_Aircraft> dp88_Aircraft_LandingZone_Aircraft_Registrant("dp88_Aircraft_LandingZone_Aircraft","landing_anim_name=modelfile.animfile:string,landing_anim_first_frame=0.0:float,landing_anim_last_frame=25.0:float,require_landing_zone=1:int");
// Terror Drone
/*ScriptRegistrant<dp88_AR_TerrorDrone> dp88_AR_TerrorDrone_Registrant("dp88_AR_TerrorDrone","");*/
// Remote Control Scripts
ScriptRegistrant<dp88_RemoteControlConsole> dp88_RemoteControlConsole_Registrant("dp88_RemoteControlConsole","remoteControlID:int,vehiclePreset:string,cost:int,team:int,chargeTime=0:int,accessDeniedSound:string,consoleOfflineSound:string,consoleChargingSound:string,insufficientFundsSound:string,connectionEstablishedSound:string,animationName:string,animFrameAvailable1=0:int,animFrameAvailable2=0:int,animFrameCharging1=0:int,animFrameCharging2=0:int,animFrameActive1=0:int,animFrameActive2=0:int,animFrameIdle1=0:int,animFrameIdle2=0:int,animFrameDisabled1=0:int,animFrameDisabled2=0:int");
ScriptRegistrant<dp88_RemoteControlVehicle> dp88_RemoteControlVehicle_Registrant("dp88_RemoteControlVehicle","remoteControlID:int");
// Demo Truck
ScriptRegistrant<dp88_AR_DemoTruck> dp88_AR_DemoTruck_Registrant("dp88_AR_DemoTruck","explosionPreset=Explosion_NukeBeacon:string,cinematicPreset=null:string,buildingDamageRange=50.0:float,buildingDamageWarhead=Nuke:string,buildingDamageStrength=2200.00:float");
// Paradrop scripts
ScriptRegistrant<dp88_AR_paradrop_Console> dp88_AR_paradrop_Console_Registrant("dp88_AR_paradrop_Console","team=1:int");
// Prism Tower script
ScriptRegistrant<dp88_AR_Prism_Tower> dp88_AR_Prism_Tower_Registrant("dp88_AR_Prism_Tower","Priority_Infantry=1.0:float,Splash_Infantry=0:int,Priority_Light_Vehicle=5.0:float,Priority_Heavy_Vehicle=7.0:float,Priority_VTOL=0.0:float,Min_Attack_Range=0:int,Max_Attack_Range=150:int,Animation_Model:string,Animation_Model_Bone:string,Animation:string,Animation_Idle_Start_Frame:int,Animation_Idle_End_Frame:int,Animation_Unpowered_Start_Frame:int,Animation_Unpowered_End_Frame:int,Animation_Charge_Start_Frame:int,Animation_Charge_End_Frame:int,Charge_Sound:string,Modifier_Distance=0.25:float,Modifier_Target_Damage=0.1:float,Modifier_Target_Value=0.25:float,Requires_Power=1:int,Debug=0:int,Detects_Stealth=1:int");
// Health link script
ScriptRegistrant<dp88_linkHealth> dp88_linkHealth_Registrant("dp88_linkHealth","parentObjectId=0:int");
| 33.497529
| 714
| 0.66556
|
TheUnstoppable
|
8171467acf3d7fd994993d1066f0e36fcc5babd8
| 11,445
|
cpp
|
C++
|
examples/tutorial_developer/pose_2_extract_pose_or_heatmat_from_image.cpp
|
jimfcarroll/openpose
|
fa8d6ff8f616f90c22eaae9d6926fef84db73ea6
|
[
"DOC",
"MIT-CMU"
] | 2
|
2018-12-10T13:40:39.000Z
|
2021-06-05T02:28:50.000Z
|
examples/tutorial_developer/pose_2_extract_pose_or_heatmat_from_image.cpp
|
Mainvooid/openpose
|
e4a021228b5949150c9446e31ec9f36f0f50a21c
|
[
"DOC",
"MIT-CMU"
] | null | null | null |
examples/tutorial_developer/pose_2_extract_pose_or_heatmat_from_image.cpp
|
Mainvooid/openpose
|
e4a021228b5949150c9446e31ec9f36f0f50a21c
|
[
"DOC",
"MIT-CMU"
] | null | null | null |
// ------------------------- OpenPose Library Tutorial - Pose - Example 2 - Extract Pose or Heatmap from Image -------------------------
// This second example shows the user how to:
// 1. Load an image (`filestream` module)
// 2. Extract the pose of that image (`pose` module)
// 3. Render the pose or heatmap on a resized copy of the input image (`pose` module)
// 4. Display the rendered pose or heatmap (`gui` module)
// In addition to the previous OpenPose modules, we also need to use:
// 1. `core` module: for the Array<float> class that the `pose` module needs
// 2. `utilities` module: for the error & logging functions, i.e., op::error & op::log respectively
// 3rdparty dependencies
// GFlags: DEFINE_bool, _int32, _int64, _uint64, _double, _string
#include <gflags/gflags.h>
// Allow Google Flags in Ubuntu 14
#ifndef GFLAGS_GFLAGS_H_
namespace gflags = google;
#endif
// OpenPose dependencies
#include <openpose/core/headers.hpp>
#include <openpose/filestream/headers.hpp>
#include <openpose/gui/headers.hpp>
#include <openpose/pose/headers.hpp>
#include <openpose/utilities/headers.hpp>
// See all the available parameter options withe the `--help` flag. E.g., `build/examples/openpose/openpose.bin --help`
// Note: This command will show you flags for other unnecessary 3rdparty files. Check only the flags for the OpenPose
// executable. E.g., for `openpose.bin`, look for `Flags from examples/openpose/openpose.cpp:`.
// Debugging/Other
DEFINE_int32(logging_level, 3, "The logging level. Integer in the range [0, 255]. 0 will output any log() message, while"
" 255 will not output any. Current OpenPose library messages are in the range 0-4: 1 for"
" low priority messages and 4 for important ones.");
// Producer
DEFINE_string(image_path, "examples/media/COCO_val2014_000000000192.jpg", "Process the desired image.");
// OpenPose
DEFINE_string(model_pose, "BODY_25", "Model to be used. E.g., `COCO` (18 keypoints), `MPI` (15 keypoints, ~10% faster), "
"`MPI_4_layers` (15 keypoints, even faster but less accurate).");
DEFINE_string(model_folder, "models/", "Folder path (absolute or relative) where the models (pose, face, ...) are located.");
DEFINE_string(net_resolution, "-1x368", "Multiples of 16. If it is increased, the accuracy potentially increases. If it is"
" decreased, the speed increases. For maximum speed-accuracy balance, it should keep the"
" closest aspect ratio possible to the images or videos to be processed. Using `-1` in"
" any of the dimensions, OP will choose the optimal aspect ratio depending on the user's"
" input value. E.g., the default `-1x368` is equivalent to `656x368` in 16:9 resolutions,"
" e.g., full HD (1980x1080) and HD (1280x720) resolutions.");
DEFINE_string(output_resolution, "-1x-1", "The image resolution (display and output). Use \"-1x-1\" to force the program to use the"
" input image resolution.");
DEFINE_int32(num_gpu_start, 0, "GPU device start number.");
DEFINE_double(scale_gap, 0.3, "Scale gap between scales. No effect unless scale_number > 1. Initial scale is always 1."
" If you want to change the initial scale, you actually want to multiply the"
" `net_resolution` by your desired initial scale.");
DEFINE_int32(scale_number, 1, "Number of scales to average.");
// OpenPose Rendering
DEFINE_int32(part_to_show, 19, "Prediction channel to visualize (default: 0). 0 for all the body parts, 1-18 for each body"
" part heat map, 19 for the background heat map, 20 for all the body part heat maps"
" together, 21 for all the PAFs, 22-40 for each body part pair PAF.");
DEFINE_bool(disable_blending, false, "If enabled, it will render the results (keypoint skeletons or heatmaps) on a black"
" background, instead of being rendered into the original image. Related: `part_to_show`,"
" `alpha_pose`, and `alpha_pose`.");
DEFINE_double(render_threshold, 0.05, "Only estimated keypoints whose score confidences are higher than this threshold will be"
" rendered. Generally, a high threshold (> 0.5) will only render very clear body parts;"
" while small thresholds (~0.1) will also output guessed and occluded keypoints, but also"
" more false positives (i.e., wrong detections).");
DEFINE_double(alpha_pose, 0.6, "Blending factor (range 0-1) for the body part rendering. 1 will show it completely, 0 will"
" hide it. Only valid for GPU rendering.");
DEFINE_double(alpha_heatmap, 0.7, "Blending factor (range 0-1) between heatmap and original frame. 1 will only show the"
" heatmap, 0 will only show the frame. Only valid for GPU rendering.");
int tutorialDeveloperPose2()
{
try
{
op::log("Starting OpenPose demo...", op::Priority::High);
const auto timerBegin = std::chrono::high_resolution_clock::now();
// ------------------------- INITIALIZATION -------------------------
// Step 1 - Set logging level
// - 0 will output all the logging messages
// - 255 will output nothing
op::check(0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.",
__LINE__, __FUNCTION__, __FILE__);
op::ConfigureLog::setPriorityThreshold((op::Priority)FLAGS_logging_level);
op::log("", op::Priority::Low, __LINE__, __FUNCTION__, __FILE__);
// Step 2 - Read GFlags (user defined configuration)
// outputSize
const auto outputSize = op::flagsToPoint(FLAGS_output_resolution, "-1x-1");
// netInputSize
const auto netInputSize = op::flagsToPoint(FLAGS_net_resolution, "-1x368");
// poseModel
const auto poseModel = op::flagsToPoseModel(FLAGS_model_pose);
// Check no contradictory flags enabled
if (FLAGS_alpha_pose < 0. || FLAGS_alpha_pose > 1.)
op::error("Alpha value for blending must be in the range [0,1].", __LINE__, __FUNCTION__, __FILE__);
if (FLAGS_scale_gap <= 0. && FLAGS_scale_number > 1)
op::error("Incompatible flag configuration: scale_gap must be greater than 0 or scale_number = 1.",
__LINE__, __FUNCTION__, __FILE__);
// Step 3 - Initialize all required classes
op::ScaleAndSizeExtractor scaleAndSizeExtractor(netInputSize, outputSize, FLAGS_scale_number, FLAGS_scale_gap);
op::CvMatToOpInput cvMatToOpInput{poseModel};
op::CvMatToOpOutput cvMatToOpOutput;
auto poseExtractorPtr = std::make_shared<op::PoseExtractorCaffe>(poseModel, FLAGS_model_folder,
FLAGS_num_gpu_start);
op::PoseGpuRenderer poseGpuRenderer{poseModel, poseExtractorPtr, (float)FLAGS_render_threshold,
!FLAGS_disable_blending, (float)FLAGS_alpha_pose, (float)FLAGS_alpha_heatmap};
poseGpuRenderer.setElementToRender(FLAGS_part_to_show);
op::OpOutputToCvMat opOutputToCvMat;
op::FrameDisplayer frameDisplayer{"OpenPose Tutorial - Example 2", outputSize};
// Step 4 - Initialize resources on desired thread (in this case single thread, i.e., we init resources here)
poseExtractorPtr->initializationOnThread();
poseGpuRenderer.initializationOnThread();
// ------------------------- POSE ESTIMATION AND RENDERING -------------------------
// Step 1 - Read and load image, error if empty (possibly wrong path)
// Alternative: cv::imread(FLAGS_image_path, CV_LOAD_IMAGE_COLOR);
cv::Mat inputImage = op::loadImage(FLAGS_image_path, CV_LOAD_IMAGE_COLOR);
if(inputImage.empty())
op::error("Could not open or find the image: " + FLAGS_image_path, __LINE__, __FUNCTION__, __FILE__);
const op::Point<int> imageSize{inputImage.cols, inputImage.rows};
// Step 2 - Get desired scale sizes
std::vector<double> scaleInputToNetInputs;
std::vector<op::Point<int>> netInputSizes;
double scaleInputToOutput;
op::Point<int> outputResolution;
std::tie(scaleInputToNetInputs, netInputSizes, scaleInputToOutput, outputResolution)
= scaleAndSizeExtractor.extract(imageSize);
// Step 3 - Format input image to OpenPose input and output formats
const auto netInputArray = cvMatToOpInput.createArray(inputImage, scaleInputToNetInputs, netInputSizes);
auto outputArray = cvMatToOpOutput.createArray(inputImage, scaleInputToOutput, outputResolution);
// Step 4 - Estimate poseKeypoints
poseExtractorPtr->forwardPass(netInputArray, imageSize, scaleInputToNetInputs);
const auto poseKeypoints = poseExtractorPtr->getPoseKeypoints();
const auto scaleNetToOutput = poseExtractorPtr->getScaleNetToOutput();
// Step 5 - Render pose
poseGpuRenderer.renderPose(outputArray, poseKeypoints, scaleInputToOutput, scaleNetToOutput);
// Step 6 - OpenPose output format to cv::Mat
auto outputImage = opOutputToCvMat.formatToCvMat(outputArray);
// ------------------------- SHOWING RESULT AND CLOSING -------------------------
// Show results
frameDisplayer.displayFrame(outputImage, 0); // Alternative: cv::imshow(outputImage) + cv::waitKey(0)
// Measuring total time
const auto now = std::chrono::high_resolution_clock::now();
const auto totalTimeSec = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(now-timerBegin).count()
* 1e-9;
const auto message = "OpenPose demo successfully finished. Total time: "
+ std::to_string(totalTimeSec) + " seconds.";
op::log(message, op::Priority::High);
// Return successful message
return 0;
}
catch (const std::exception& e)
{
op::error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return -1;
}
}
int main(int argc, char *argv[])
{
// Parsing command line flags
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Running tutorialDeveloperPose2
return tutorialDeveloperPose2();
}
| 69.786585
| 148
| 0.600699
|
jimfcarroll
|
8171de8ae77a5efb98a50cdb86084fbea475b37b
| 496
|
cpp
|
C++
|
Algorithms and Data Structures/PrimeFactors.cpp
|
aldew5/Competitve-Programming
|
eb0b93a35af3bd5e806aedc44b835830af01d496
|
[
"MIT"
] | 2
|
2020-05-09T15:54:18.000Z
|
2021-01-23T22:32:53.000Z
|
Algorithms and Data Structures/PrimeFactors.cpp
|
aldew5/Competitive-Programming
|
fc93723fae739d0b06bcf2dbe3b9274584a79a66
|
[
"MIT"
] | null | null | null |
Algorithms and Data Structures/PrimeFactors.cpp
|
aldew5/Competitive-Programming
|
fc93723fae739d0b06bcf2dbe3b9274584a79a66
|
[
"MIT"
] | null | null | null |
vector<int> primeFactors(int a) {
int n = a;
vector<int> out;
while (n % 2 == 0) {
out.push_back(2);
n = n/2;
}
// n must be odd at this point. So we can skip
for (int i = 3; i <= sqrt(n); i = i + 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
out.push_back(i);
n = n/i;
}
}
// is a prime number greater than 2
if (n > 2)
out.push_back(n);
return out;
}
| 19.84
| 50
| 0.445565
|
aldew5
|
81746ac13ca6aa052759d9e2f8c4d49ddf03695d
| 2,512
|
cpp
|
C++
|
day-10-25-3.cpp
|
duasong111/c_lang_learn
|
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
|
[
"BSD-2-Clause"
] | null | null | null |
day-10-25-3.cpp
|
duasong111/c_lang_learn
|
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
|
[
"BSD-2-Clause"
] | null | null | null |
day-10-25-3.cpp
|
duasong111/c_lang_learn
|
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
|
[
"BSD-2-Clause"
] | null | null | null |
//解答疑惑篇
#include <stdio.h>
int main(void)
{
int i;
int a[5] = { 1,2,3,5,6 };
int* p;
p= &a[2]; //知道为啥可以省略地址符了
for (i = 0; i < 5; i++)
printf("&a[%d] = %p p+%d = %p\n", i, &a[i], i, p + i);
printf("%d ", *p+2); //可以用此来调控选哪个数组
return 0;
}
//其实我一直很好奇,为啥& 一会取,一会不取了呢?到底是因为什么,直到今天我才了解到,其实效果
//如果你变量取了地址 如 int *p; p=a;(标注:此时a是数组),那么你取得是a数组的地址,效果和 p=&a[0];一样的,但是你要是
//ni要是 p=&a[2];这个就是去数组三的地址,其实是不一样的,以及你能够在printf的输出中来通过*p + i;来更换你所取得第几个地址,真的很tm有趣
| 125.6
| 2,071
| 0.107882
|
duasong111
|
40bd75265756c9393de42ab3f3739e6908e1364b
| 1,880
|
cpp
|
C++
|
multicore/src/bbthread.cpp
|
jangmys/PBBPerm
|
c13ad1045d0c7a36fd8d8ace728410fee38d70a4
|
[
"MIT"
] | null | null | null |
multicore/src/bbthread.cpp
|
jangmys/PBBPerm
|
c13ad1045d0c7a36fd8d8ace728410fee38d70a4
|
[
"MIT"
] | null | null | null |
multicore/src/bbthread.cpp
|
jangmys/PBBPerm
|
c13ad1045d0c7a36fd8d8ace728410fee38d70a4
|
[
"MIT"
] | null | null | null |
#include "../../common/include/macros.h"
#include "../../common/include/pbab.h"
#include "../include/bbthread.h"
void bbthread::reset_requestQueue()
{
requestQueue.clear();
}
bool
bbthread::has_request()
{
pthread_mutex_lock_check(&mutex_workRequested);
bool ok = (requestQueue.empty()) ? false : true;
pthread_mutex_unlock(&mutex_workRequested);
return ok;
}
bool
bbthread::set_workState(const bool newstate)
{
int oldstate=got_work;
pthread_mutex_lock_check(&mutex_workState);
got_work=newstate;
pthread_mutex_unlock(&mutex_workState);
return oldstate;
}
void
bbthread::getSchedule(int *sch)
{
for (int i = 0; i < size; i++) {
sch[i]=bd->node->schedule[i];
}
}
int
bbthread::shareWork(int numerator, int denominator, bbthread *thief_thread)
{
int numShared = 0;
int l = 0;
ivm* thief = thief_thread->IVM;
while (IVM->posVect[l] == IVM->endVect[l] && l < IVM->line && l < size - 10) l++;
if (IVM->posVect[l] < IVM->endVect[l])
{
numShared++;
for (int i = 0; i < l; i++) {
thief->posVect[i] = IVM->posVect[i];
for (int j = 0; j < size; j++) thief->jobMat[i * size + j] = IVM->jobMat[i * size + j];
thief->dirVect[i] = IVM->dirVect[i];
}
for (int i = 0; i < size; i++) thief->endVect[i] = IVM->endVect[i];
for (int i = 0; i < size; i++) thief->jobMat[l * size + i] = IVM->jobMat[l * size + i];
thief->dirVect[l] = IVM->dirVect[l];
thief->posVect[l] = IVM->cuttingPosition(l, 2);
IVM->endVect[l] = thief->posVect[l] - 1;
// remaining levels : align thief left, victim right
for (int i = l + 1; i < size; i++) thief->posVect[i] = 0;
for (int i = l + 1; i < size; i++) IVM->endVect[i] = size - i - 1;
thief->line = l;
}
return numShared;
}
| 25.753425
| 99
| 0.571277
|
jangmys
|
40bf93212efa935d4ad6ca8a47338c7ea757b35d
| 4,186
|
cpp
|
C++
|
src/Audio/AudioPlayer.cpp
|
Nickswoboda/Aegis
|
60e0e770892bdcb378686508ca455f6b5d522e33
|
[
"MIT"
] | null | null | null |
src/Audio/AudioPlayer.cpp
|
Nickswoboda/Aegis
|
60e0e770892bdcb378686508ca455f6b5d522e33
|
[
"MIT"
] | null | null | null |
src/Audio/AudioPlayer.cpp
|
Nickswoboda/Aegis
|
60e0e770892bdcb378686508ca455f6b5d522e33
|
[
"MIT"
] | null | null | null |
#include "AudioPlayer.h"
#include "../Core/Assert.h"
#include <AL/al.h>
#include <AL/alc.h>
#include <stb_vorbis.h>
#include <iostream>
#include <vector>
namespace Aegis {
ALCdevice* AudioPlayer::device_ = nullptr;
ALCcontext* AudioPlayer::context_ = nullptr;
std::unordered_map<std::string, SoundID> AudioPlayer::id_map_;
std::unordered_map<SoundID, std::shared_ptr<Sound>> AudioPlayer::sound_map_;
std::unordered_set<SoundID> AudioPlayer::streaming_set_;
float AudioPlayer::master_volume_ = 1.0f;
void AudioPlayer::Init()
{
device_ = alcOpenDevice(nullptr);
AE_ASSERT(device_, "Unable to open get sound device");
context_ = alcCreateContext(device_, nullptr);
AE_ASSERT(context_, "Unable to open audio context");
AE_ASSERT(alcMakeContextCurrent(context_), "Unable set current audio context");
const ALCchar* name = nullptr;
if (alcIsExtensionPresent(device_, "ALC_ENUMERATE_ALL_EXT"))
name = alcGetString(device_, ALC_ALL_DEVICES_SPECIFIER);
if (!name || alcGetError(device_) != AL_NO_ERROR)
name = alcGetString(device_, ALC_DEVICE_SPECIFIER);
std::cout << "Audio Device Opened: " << name << "\n";
}
void AudioPlayer::Shutdown()
{
while (!sound_map_.empty()){
UnloadSound(sound_map_.begin()->first);
}
alcMakeContextCurrent(nullptr);
alcDestroyContext(context_);
alcCloseDevice(device_);
}
SoundID AudioPlayer::LoadSound(const std::string& path, bool looping, bool streaming)
{
if (id_map_.count(path)) {
return id_map_[path];
}
ALuint source_id;
alGenSources(1, &source_id);
auto sound = std::make_shared<Sound>(path, looping, streaming);
if (!streaming){
alSourceQueueBuffers(source_id, 1, &sound->buffer_ids_[0]);
alSourcei(source_id, AL_LOOPING, looping);
}
id_map_[path] = source_id;
sound_map_[source_id] = sound;
return source_id;
}
void AudioPlayer::UnloadSound(SoundID id)
{
if (!sound_map_.count(id)){
std::cout << "No sound found with id: " << id << "\n";
return;
} else {
alDeleteSources(1, &id);
sound_map_.erase(id);
}
}
void AudioPlayer::PlaySound(SoundID id, unsigned int volume)
{
AE_ASSERT(sound_map_.count(id), "Unable to play sound. Sound with id " << id << "not found\n");
volume = volume < 0 ? 0 : (volume > 100 ? 100 : volume);
auto sound = sound_map_[id];
sound->volume_ = (volume / 100.f);
alSourcef(id, AL_GAIN, (volume / 100.0f) * master_volume_);
if (sound->streaming_) {
alSourceRewind(id);
alSourcei(id, AL_BUFFER, 0);
sound->StartStream();
alSourceQueueBuffers(id, sound->num_buffers_, sound->buffer_ids_);
streaming_set_.insert(id);
}
sound->stopped_ = false;
alSourcePlay(id);
}
void AudioPlayer::StopSound(SoundID id)
{
alSourceStop(id);
streaming_set_.erase(id);
}
void AudioPlayer::Update()
{
std::vector<SoundID> stopped;
for (SoundID id : streaming_set_){
auto sound = sound_map_[id];
int state;
alGetSourcei(id, AL_SOURCE_STATE, &state);
if (state == AL_STOPPED) {
if (sound->stopped_) {
stopped.push_back(id);
continue;
}
else { //was stopped automatically. i.e dragging window
alSourcePlay(id);
}
}
int processed;
alGetSourcei(id, AL_BUFFERS_PROCESSED, &processed);
while (processed > 0) {
ALuint buffer;
alSourceUnqueueBuffers(id, 1, &buffer);
--processed;
bool updated = sound->UpdateBuffer(buffer);
if (updated) {
alSourceQueueBuffers(id, 1, &buffer);
}
}
}
for (auto id : stopped) {
streaming_set_.erase(id);
}
}
void AudioPlayer::SetMasterVolume(unsigned int volume)
{
//clamp to between 0 and 100
master_volume_ = volume < 0 ? 0 : (volume > 100 ? 1 : volume/100.0f);
for (auto it : sound_map_) {
alSourcef(it.first, AL_GAIN, it.second->volume_ * master_volume_);
}
}
void AudioPlayer::SetSoundVolume(SoundID id, unsigned int volume)
{
if (sound_map_.count(id)){
std::cout << "Unable to set volume of sound id: " << id << ". ID does not exist\n.";
return;
}
volume = volume < 0 ? 0 : (volume > 100 ? 1 : volume/100.0f);
alSourcef(id, AL_GAIN, volume * master_volume_);
sound_map_[id]->volume_ = volume;
}
}
| 24.057471
| 98
| 0.676541
|
Nickswoboda
|
40c08bc396b7e5fe3888722619f5a0f297cdb7e7
| 500
|
hpp
|
C++
|
vitamin-k/system/vikAssets.hpp
|
patchedsoul/xrgears
|
1ac9460a3fe49c9a47bc6d8262e124fd3d369758
|
[
"MIT"
] | null | null | null |
vitamin-k/system/vikAssets.hpp
|
patchedsoul/xrgears
|
1ac9460a3fe49c9a47bc6d8262e124fd3d369758
|
[
"MIT"
] | null | null | null |
vitamin-k/system/vikAssets.hpp
|
patchedsoul/xrgears
|
1ac9460a3fe49c9a47bc6d8262e124fd3d369758
|
[
"MIT"
] | null | null | null |
/*
* vitamin-k
*
* Copyright 2017-2018 Collabora Ltd.
*
* Authors: Lubosz Sarnecki <lubosz.sarnecki@collabora.com>
* SPDX-License-Identifier: MIT
*/
#pragma once
#include <string>
namespace vik {
class Assets {
public:
static const std::string get_asset_path() {
return "./assets/";
}
static const std::string get_shader_path() {
return "./shaders/";
}
static const std::string get_texture_path() {
return get_asset_path() + "textures/";
}
};
} // namespace vik
| 16.666667
| 59
| 0.66
|
patchedsoul
|
40c3c1d7457dbfe3e40689cf8b268d336fb133c7
| 1,865
|
cpp
|
C++
|
examples/f1/clkout/main.cpp
|
tufty/stm32tl
|
3f5ef1ca29695236ab9f5d964a1b4be7afc00c8f
|
[
"MIT"
] | 10
|
2017-04-16T20:54:40.000Z
|
2022-03-13T13:28:32.000Z
|
examples/f1/clkout/main.cpp
|
tufty/stm32tl
|
3f5ef1ca29695236ab9f5d964a1b4be7afc00c8f
|
[
"MIT"
] | 1
|
2018-10-04T21:06:37.000Z
|
2020-01-13T15:22:58.000Z
|
examples/f1/clkout/main.cpp
|
tufty/stm32tl
|
3f5ef1ca29695236ab9f5d964a1b4be7afc00c8f
|
[
"MIT"
] | 4
|
2019-10-30T07:35:22.000Z
|
2021-07-23T01:24:27.000Z
|
#include <clocks.h>
#include <tasks.h>
#include <gpio.h>
#define HSE_FREQ 8000000
typedef HSE_OSC_T<HSE_FREQ> HSE;
typedef PLL_T<HSE, 72000000> PLL;
typedef SYSCLK_T<PLL> SYSCLK;
typedef SYSTICK_T<SYSCLK, 1000> SYSTICK;
typedef TIMEOUT_T<SYSTICK> TIMEOUT;
#if defined(OLIMEXINO)
typedef GPIO_T<PA, 8, OUTPUT_50MHZ, ALT_PUSH_PULL, LOW> MCO;
typedef GPIO_T<PA, 3, OUTPUT_10MHZ, PUSH_PULL> D0;
typedef GPIO_T<PA, 2, OUTPUT_10MHZ, PUSH_PULL> D1;
typedef GPIO_T<PA, 0, OUTPUT_10MHZ, PUSH_PULL> D2;
typedef GPIO_T<PA, 1, OUTPUT_10MHZ, PUSH_PULL> D3;
typedef GPIO_T<PB, 5, OUTPUT_10MHZ, PUSH_PULL> D4;
typedef GPIO_T<PB, 6, OUTPUT_10MHZ, PUSH_PULL> D5;
typedef GPIO_T<PA, 9, OUTPUT_10MHZ, PUSH_PULL> D7;
typedef GPIO_T<PC, 9, INPUT, FLOATING, LOW, INTERRUPT_ENABLED, EDGE_FALLING> BUTTON;
typedef GPIO_T<PA, 5, OUTPUT_10MHZ, PUSH_PULL> LED1;
typedef GPIO_PORT_T<PA, D0, D1, D2, D3, D7, MCO, LED1> PORT_A;
typedef GPIO_PORT_T<PB, D4, D5> PORT_B;
typedef GPIO_PORT_T<PC, MCO, BUTTON> PORT_C;
#elif defined(MINIBOARD)
typedef GPIO_T<PA, 8, OUTPUT_50MHZ, ALT_PUSH_PULL, LOW> MCO;
typedef GPIO_T<PC, 13, OUTPUT_10MHZ, PUSH_PULL, LOW> LED1;
typedef GPIO_PORT_T<PA, MCO> PORT_A;
typedef GPIO_PORT_T<PB> PORT_B;
typedef GPIO_PORT_T<PC, LED1> PORT_C;
#else
typedef GPIO_T<PA, 8, OUTPUT_50MHZ, ALT_PUSH_PULL, LOW> MCO;
typedef GPIO_T<PB, 8, OUTPUT_10MHZ, PUSH_PULL, LOW> LED1;
typedef GPIO_PORT_T<PA> PORT_A;
typedef GPIO_PORT_T<PB, LED1> PORT_B;
typedef GPIO_PORT_T<PC, MCO> PORT_C;
#endif
extern "C" {
void SysTick_Handler(void) {
if (TIMEOUT::count_down()) exit_idle();
}
}
int main(void)
{
HSE::init();
PLL::init();
SYSCLK::init();
SYSTICK::init();
RCC->CFGR |= RCC_CFGR_MCO_SYSCLK;
PORT_A::init();
PORT_B::init();
PORT_C::init();
while (1) {
LED1::set_high();
SYSTICK::set_and_wait(100);
LED1::set_low();
TIMEOUT::set_and_wait(900);
}
return 0;
}
| 27.028986
| 84
| 0.737802
|
tufty
|
40c47fd93c62e1cfbbed8ad2f3ce03c5af62df49
| 209
|
hpp
|
C++
|
test/test.hpp
|
sschaetz/aura
|
3d90e4b320ff54968bed8e610f778c7b84ba19de
|
[
"BSL-1.0"
] | 34
|
2015-01-18T13:41:26.000Z
|
2021-08-17T05:23:25.000Z
|
test/test.hpp
|
sschaetz/aura
|
3d90e4b320ff54968bed8e610f778c7b84ba19de
|
[
"BSL-1.0"
] | 14
|
2015-03-11T18:17:26.000Z
|
2018-08-13T18:33:18.000Z
|
test/test.hpp
|
sschaetz/aura
|
3d90e4b320ff54968bed8e610f778c7b84ba19de
|
[
"BSL-1.0"
] | 9
|
2015-03-11T04:53:06.000Z
|
2018-11-23T15:48:01.000Z
|
#pragma once
namespace boost
{
namespace aura
{
namespace test
{
inline std::string get_test_dir() { return std::string(AURA_TEST_SOURCE_DIR); }
} // namespace test
} // namespace aura
} // namespace boost
| 13.933333
| 79
| 0.727273
|
sschaetz
|
40c523872f00f85bc08ebd44781aa7f2057b9b86
| 938
|
cpp
|
C++
|
euler077.cpp
|
suihan74/ProjectEuler
|
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
|
[
"MIT"
] | null | null | null |
euler077.cpp
|
suihan74/ProjectEuler
|
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
|
[
"MIT"
] | null | null | null |
euler077.cpp
|
suihan74/ProjectEuler
|
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
|
[
"MIT"
] | null | null | null |
/**
* Problem 77 「素数の和」
* 10は素数の和として5通りに表すことができる:
*
* 7 + 3
* 5 + 5
* 5 + 3 + 2
* 3 + 3 + 2 + 2
* 2 + 2 + 2 + 2 + 2
*
* 素数の和としての表し方が5000通り以上になる最初の数を求めよ.
*/
#include <cstdint>
#include <iostream>
#include <vector>
#include "prime.h"
using uInt = std::uint_fast64_t;
using namespace Euler::Prime;
int main(void)
{
std::vector<NumberType> table;
for (uInt bound = 100; ; bound *= 10) { // 十分な素数リストの長さが不明なのでぶん回す
auto primes = make_primes_vector<uInt>(bound, &table);
for (uInt target = 10; target < bound; target++) {
// ここからはe031, e076と同様
std::vector<uInt> memo(target + 1, 0);
memo.at(0) = 1;
for (const uInt prime : primes) {
for (uInt i = prime; i < memo.size(); i++) {
memo.at(i) += memo.at(i - prime);
}
}
if (memo.at(target) >= 5000) {
std::cout << "Euler077: " << target << std::endl;
return 0;
}
}
}
return 0;
}
| 20.391304
| 67
| 0.545842
|
suihan74
|
40c9d23eaf33e657d177171a7e331345247a3d8c
| 276
|
hpp
|
C++
|
include/chrono/MicroTimer.hpp
|
bander9289/StratifyAPI
|
9b45091aa71a4e5718047438ea4044c1fdc814a3
|
[
"MIT"
] | 2
|
2016-05-21T03:09:19.000Z
|
2016-08-27T03:40:51.000Z
|
include/chrono/MicroTimer.hpp
|
bander9289/StratifyAPI
|
9b45091aa71a4e5718047438ea4044c1fdc814a3
|
[
"MIT"
] | 75
|
2017-10-08T22:21:19.000Z
|
2020-03-30T21:13:20.000Z
|
include/chrono/MicroTimer.hpp
|
StratifyLabs/StratifyLib
|
975a5c25a84296fd0dec64fe4dc579cf7027abe6
|
[
"MIT"
] | 5
|
2018-03-27T16:44:09.000Z
|
2020-07-08T16:45:55.000Z
|
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#ifndef CHRONO_MICRO_TIMER_HPP_
#define CHRONO_MICRO_TIMER_HPP_
#include "Timer.hpp"
namespace chrono {
typedef class Timer MicroTimer;
}
#endif // CHRONO_MICRO_TIMER_HPP_
| 23
| 100
| 0.778986
|
bander9289
|
40ca5d350595bc92956bd9d8eb1b5e15ff84d51b
| 12,047
|
cpp
|
C++
|
src/servers/app/drawing/Painter/drawing_modes/PixelFormat.cpp
|
axeld/haiku
|
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
|
[
"MIT"
] | 4
|
2017-06-17T22:03:56.000Z
|
2019-01-25T10:51:55.000Z
|
src/servers/app/drawing/Painter/drawing_modes/PixelFormat.cpp
|
axeld/haiku
|
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
|
[
"MIT"
] | null | null | null |
src/servers/app/drawing/Painter/drawing_modes/PixelFormat.cpp
|
axeld/haiku
|
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
|
[
"MIT"
] | 3
|
2018-12-17T13:07:38.000Z
|
2021-09-08T13:07:31.000Z
|
/*
* Copyright 2005, Stephan Aßmus <superstippi@gmx.de>.
* Copyright 2008, Andrej Spielmann <andrej.spielmann@seh.ox.ac.uk>
* All rights reserved. Distributed under the terms of the MIT License.
*
* Copyright 2002-2004 Maxim Shemanarev (http://www.antigrain.com)
*
* A class implementing the AGG "pixel format" interface which maintains
* a PatternHandler and pointers to blending functions implementing the
* different BeOS "drawing_modes".
*
*/
#include "PixelFormat.h"
#include <stdio.h>
#include "DrawingModeAdd.h"
#include "DrawingModeAlphaCC.h"
#include "DrawingModeAlphaCO.h"
#include "DrawingModeAlphaCOSolid.h"
#include "DrawingModeAlphaPC.h"
#include "DrawingModeAlphaPCSolid.h"
#include "DrawingModeAlphaPO.h"
#include "DrawingModeAlphaPOSolid.h"
#include "DrawingModeBlend.h"
#include "DrawingModeCopy.h"
#include "DrawingModeCopySolid.h"
#include "DrawingModeCopyText.h"
#include "DrawingModeErase.h"
#include "DrawingModeInvert.h"
#include "DrawingModeMin.h"
#include "DrawingModeMax.h"
#include "DrawingModeOver.h"
#include "DrawingModeOverSolid.h"
#include "DrawingModeSelect.h"
#include "DrawingModeSubtract.h"
#include "DrawingModeAddSUBPIX.h"
#include "DrawingModeAlphaCCSUBPIX.h"
#include "DrawingModeAlphaCOSUBPIX.h"
#include "DrawingModeAlphaCOSolidSUBPIX.h"
#include "DrawingModeAlphaPCSUBPIX.h"
#include "DrawingModeAlphaPOSUBPIX.h"
#include "DrawingModeAlphaPOSolidSUBPIX.h"
#include "DrawingModeBlendSUBPIX.h"
#include "DrawingModeCopySUBPIX.h"
#include "DrawingModeCopySolidSUBPIX.h"
#include "DrawingModeCopyTextSUBPIX.h"
#include "DrawingModeEraseSUBPIX.h"
#include "DrawingModeInvertSUBPIX.h"
#include "DrawingModeMinSUBPIX.h"
#include "DrawingModeMaxSUBPIX.h"
#include "DrawingModeOverSUBPIX.h"
#include "DrawingModeOverSolidSUBPIX.h"
#include "DrawingModeSelectSUBPIX.h"
#include "DrawingModeSubtractSUBPIX.h"
#include "PatternHandler.h"
// blend_pixel_empty
void
blend_pixel_empty(int x, int y, const color_type& c, uint8 cover,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_pixel_empty()\n");
}
// blend_hline_empty
void
blend_hline_empty(int x, int y, unsigned len,
const color_type& c, uint8 cover,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_hline_empty()\n");
}
// blend_vline_empty
void
blend_vline_empty(int x, int y, unsigned len,
const color_type& c, uint8 cover,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_vline_empty()\n");
}
// blend_solid_hspan_empty
void
blend_solid_hspan_empty(int x, int y, unsigned len,
const color_type& c, const uint8* covers,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_solid_hspan_empty()\n");
}
// blend_solid_hspan_subpix_empty
void
blend_solid_hspan_empty_subpix(int x, int y, unsigned len,
const color_type& c, const uint8* covers,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_solid_hspan_empty_subpix()\n");
}
// blend_solid_vspan_empty
void
blend_solid_vspan_empty(int x, int y,
unsigned len, const color_type& c,
const uint8* covers,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_solid_vspan_empty()\n");
}
// blend_color_hspan_empty
void
blend_color_hspan_empty(int x, int y, unsigned len,
const color_type* colors,
const uint8* covers, uint8 cover,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_color_hspan_empty()\n");
}
// blend_color_vspan_empty
void
blend_color_vspan_empty(int x, int y, unsigned len,
const color_type* colors,
const uint8* covers, uint8 cover,
agg_buffer* buffer, const PatternHandler* pattern)
{
printf("blend_color_vspan_empty()\n");
}
// #pragma mark -
// constructor
PixelFormat::PixelFormat(agg::rendering_buffer& rb,
const PatternHandler* handler)
: fBuffer(&rb),
fPatternHandler(handler),
fUsesOpCopyForText(false),
fBlendPixel(blend_pixel_empty),
fBlendHLine(blend_hline_empty),
fBlendVLine(blend_vline_empty),
fBlendSolidHSpan(blend_solid_hspan_empty),
fBlendSolidHSpanSubpix(blend_solid_hspan_empty_subpix),
fBlendSolidVSpan(blend_solid_vspan_empty),
fBlendColorHSpan(blend_color_hspan_empty),
fBlendColorVSpan(blend_color_vspan_empty)
{
}
// destructor
PixelFormat::~PixelFormat()
{
}
// SetDrawingMode
void
PixelFormat::SetDrawingMode(drawing_mode mode, source_alpha alphaSrcMode,
alpha_function alphaFncMode, bool text)
{
fUsesOpCopyForText = false;
switch (mode) {
// these drawing modes discard source pixels
// which have the current low color
case B_OP_OVER:
if (fPatternHandler->IsSolid()) {
fBlendPixel = blend_pixel_over_solid;
fBlendHLine = blend_hline_over_solid;
fBlendSolidHSpan = blend_solid_hspan_over_solid;
fBlendSolidVSpan = blend_solid_vspan_over_solid;
fBlendSolidHSpanSubpix = blend_solid_hspan_over_solid_subpix;
} else {
fBlendPixel = blend_pixel_over;
fBlendHLine = blend_hline_over;
fBlendSolidHSpanSubpix = blend_solid_hspan_over_subpix;
fBlendSolidHSpan = blend_solid_hspan_over;
fBlendSolidVSpan = blend_solid_vspan_over;
}
fBlendColorHSpan = blend_color_hspan_over;
break;
case B_OP_ERASE:
fBlendPixel = blend_pixel_erase;
fBlendHLine = blend_hline_erase;
fBlendSolidHSpanSubpix = blend_solid_hspan_erase_subpix;
fBlendSolidHSpan = blend_solid_hspan_erase;
fBlendSolidVSpan = blend_solid_vspan_erase;
fBlendColorHSpan = blend_color_hspan_erase;
break;
case B_OP_INVERT:
fBlendPixel = blend_pixel_invert;
fBlendHLine = blend_hline_invert;
fBlendSolidHSpanSubpix = blend_solid_hspan_invert_subpix;
fBlendSolidHSpan = blend_solid_hspan_invert;
fBlendSolidVSpan = blend_solid_vspan_invert;
fBlendColorHSpan = blend_color_hspan_invert;
break;
case B_OP_SELECT:
fBlendPixel = blend_pixel_select;
fBlendHLine = blend_hline_select;
fBlendSolidHSpanSubpix = blend_solid_hspan_select_subpix;
fBlendSolidHSpan = blend_solid_hspan_select;
fBlendSolidVSpan = blend_solid_vspan_select;
fBlendColorHSpan = blend_color_hspan_select;
break;
// in these drawing modes, the current high
// and low color are treated equally
case B_OP_COPY:
if (text) {
fBlendPixel = blend_pixel_copy_text;
fBlendHLine = blend_hline_copy_text;
fBlendSolidHSpanSubpix = blend_solid_hspan_copy_text_subpix;
fBlendSolidHSpan = blend_solid_hspan_copy_text;
fBlendSolidVSpan = blend_solid_vspan_copy_text;
fBlendColorHSpan = blend_color_hspan_copy_text;
// set the special flag so that Painter
// knows if an update is needed even though
// "nothing changed"
fUsesOpCopyForText = true;
} else if (fPatternHandler->IsSolid()) {
fBlendPixel = blend_pixel_copy_solid;
fBlendHLine = blend_hline_copy_solid;
fBlendSolidHSpanSubpix = blend_solid_hspan_copy_solid_subpix;
fBlendSolidHSpan = blend_solid_hspan_copy_solid;
fBlendSolidVSpan = blend_solid_vspan_copy_solid;
fBlendColorHSpan = blend_color_hspan_copy_solid;
} else {
fBlendPixel = blend_pixel_copy;
fBlendHLine = blend_hline_copy;
fBlendSolidHSpanSubpix = blend_solid_hspan_copy_subpix;
fBlendSolidHSpan = blend_solid_hspan_copy;
fBlendSolidVSpan = blend_solid_vspan_copy;
fBlendColorHSpan = blend_color_hspan_copy;
}
break;
case B_OP_ADD:
fBlendPixel = blend_pixel_add;
fBlendHLine = blend_hline_add;
fBlendSolidHSpanSubpix = blend_solid_hspan_add_subpix;
fBlendSolidHSpan = blend_solid_hspan_add;
fBlendSolidVSpan = blend_solid_vspan_add;
fBlendColorHSpan = blend_color_hspan_add;
break;
case B_OP_SUBTRACT:
fBlendPixel = blend_pixel_subtract;
fBlendHLine = blend_hline_subtract;
fBlendSolidHSpanSubpix = blend_solid_hspan_subtract_subpix;
fBlendSolidHSpan = blend_solid_hspan_subtract;
fBlendSolidVSpan = blend_solid_vspan_subtract;
fBlendColorHSpan = blend_color_hspan_subtract;
break;
case B_OP_BLEND:
fBlendPixel = blend_pixel_blend;
fBlendHLine = blend_hline_blend;
fBlendSolidHSpanSubpix = blend_solid_hspan_blend_subpix;
fBlendSolidHSpan = blend_solid_hspan_blend;
fBlendSolidVSpan = blend_solid_vspan_blend;
fBlendColorHSpan = blend_color_hspan_blend;
break;
case B_OP_MIN:
fBlendPixel = blend_pixel_min;
fBlendHLine = blend_hline_min;
fBlendSolidHSpanSubpix = blend_solid_hspan_min_subpix;
fBlendSolidHSpan = blend_solid_hspan_min;
fBlendSolidVSpan = blend_solid_vspan_min;
fBlendColorHSpan = blend_color_hspan_min;
break;
case B_OP_MAX:
fBlendPixel = blend_pixel_max;
fBlendHLine = blend_hline_max;
fBlendSolidHSpanSubpix = blend_solid_hspan_max_subpix;
fBlendSolidHSpan = blend_solid_hspan_max;
fBlendSolidVSpan = blend_solid_vspan_max;
fBlendColorHSpan = blend_color_hspan_max;
break;
// this drawing mode is the only one considering
// alpha at all. In B_CONSTANT_ALPHA, the alpha
// value from the current high color is used for
// all computations. In B_PIXEL_ALPHA, the alpha
// is considered at every source pixel.
// To simplify the implementation, four separate
// DrawingMode classes are used to cover the
// four possible combinations of alpha enabled drawing.
case B_OP_ALPHA:
if (alphaSrcMode == B_CONSTANT_ALPHA) {
if (alphaFncMode == B_ALPHA_OVERLAY) {
if (fPatternHandler->IsSolid()) {
fBlendPixel = blend_pixel_alpha_co_solid;
fBlendHLine = blend_hline_alpha_co_solid;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_co_solid_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_co_solid;
fBlendSolidVSpan = blend_solid_vspan_alpha_co_solid;
} else {
fBlendPixel = blend_pixel_alpha_co;
fBlendHLine = blend_hline_alpha_co;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_co_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_co;
fBlendSolidVSpan = blend_solid_vspan_alpha_co;
}
fBlendColorHSpan = blend_color_hspan_alpha_co;
} else if (alphaFncMode == B_ALPHA_COMPOSITE) {
fBlendPixel = blend_pixel_alpha_cc;
fBlendHLine = blend_hline_alpha_cc;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_cc_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_cc;
fBlendSolidVSpan = blend_solid_vspan_alpha_cc;
fBlendColorHSpan = blend_color_hspan_alpha_cc;
}
} else if (alphaSrcMode == B_PIXEL_ALPHA){
if (alphaFncMode == B_ALPHA_OVERLAY) {
if (fPatternHandler->IsSolid()) {
fBlendPixel = blend_pixel_alpha_po_solid;
fBlendHLine = blend_hline_alpha_po_solid;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_po_solid_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_po_solid;
fBlendSolidVSpan = blend_solid_vspan_alpha_po_solid;
} else {
fBlendPixel = blend_pixel_alpha_po;
fBlendHLine = blend_hline_alpha_po;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_po_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_po;
fBlendSolidVSpan = blend_solid_vspan_alpha_po;
}
fBlendColorHSpan = blend_color_hspan_alpha_po;
} else if (alphaFncMode == B_ALPHA_COMPOSITE) {
if (fPatternHandler->IsSolid()) {
fBlendPixel = blend_pixel_alpha_pc_solid;
fBlendHLine = blend_hline_alpha_pc_solid;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_pc_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_pc_solid;
fBlendSolidVSpan = blend_solid_vspan_alpha_pc_solid;
fBlendColorHSpan = blend_color_hspan_alpha_pc_solid;
} else {
fBlendPixel = blend_pixel_alpha_pc;
fBlendHLine = blend_hline_alpha_pc;
fBlendSolidHSpanSubpix = blend_solid_hspan_alpha_pc_subpix;
fBlendSolidHSpan = blend_solid_hspan_alpha_pc;
fBlendSolidVSpan = blend_solid_vspan_alpha_pc;
fBlendColorHSpan = blend_color_hspan_alpha_pc;
}
}
}
break;
default:
fprintf(stderr, "PixelFormat::SetDrawingMode() - drawing_mode not implemented\n");
// return fDrawingModeBGRA32Copy;
break;
}
}
| 33.839888
| 82
| 0.772807
|
axeld
|
40cb69d58be34fdbcf97e9926cf39c984af64085
| 1,315
|
hpp
|
C++
|
modules/scene_manager/include/example_interfaces/action/fibonacci__result__traits.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
modules/scene_manager/include/example_interfaces/action/fibonacci__result__traits.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3
|
2019-11-14T12:20:06.000Z
|
2020-08-07T13:51:10.000Z
|
modules/scene_manager/include/example_interfaces/action/fibonacci__result__traits.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
// generated from rosidl_generator_cpp/resource/srv__traits.hpp.em
// generated code does not contain a copyright notice
#include "example_interfaces/action/fibonacci__result__struct.hpp"
#ifndef EXAMPLE_INTERFACES__ACTION__FIBONACCI__RESULT__TRAITS_HPP_
#define EXAMPLE_INTERFACES__ACTION__FIBONACCI__RESULT__TRAITS_HPP_
namespace rosidl_generator_traits
{
#ifndef __ROSIDL_GENERATOR_CPP_TRAITS
#define __ROSIDL_GENERATOR_CPP_TRAITS
template<typename T>
struct has_fixed_size : std::false_type {};
template<typename T>
struct has_bounded_size : std::false_type {};
#endif // __ROSIDL_GENERATOR_CPP_TRAITS
template<>
struct has_fixed_size<example_interfaces::action::Fibonacci_Result>
: std::integral_constant<
bool,
has_fixed_size<example_interfaces::action::Fibonacci_Result_Request>::value &&
has_fixed_size<example_interfaces::action::Fibonacci_Result_Response>::value
>
{
};
template<>
struct has_bounded_size<example_interfaces::action::Fibonacci_Result>
: std::integral_constant<
bool,
has_bounded_size<example_interfaces::action::Fibonacci_Result_Request>::value &&
has_bounded_size<example_interfaces::action::Fibonacci_Result_Response>::value
>
{
};
} // namespace rosidl_generator_traits
#endif // EXAMPLE_INTERFACES__ACTION__FIBONACCI__RESULT__TRAITS_HPP_
| 27.978723
| 84
| 0.821293
|
Omnirobotic
|
40cdce97555361cf3adf228fe2f9f15f59dfb285
| 886
|
cpp
|
C++
|
eigen_matrix_utils/src/eigen_matrix_utils/eigen_matrix_utils.cpp
|
CNR-STIIMA-IRAS/eigen_utils
|
e0697acbf39a483d61cd140ed66a1fc553009fe0
|
[
"Apache-2.0"
] | null | null | null |
eigen_matrix_utils/src/eigen_matrix_utils/eigen_matrix_utils.cpp
|
CNR-STIIMA-IRAS/eigen_utils
|
e0697acbf39a483d61cd140ed66a1fc553009fe0
|
[
"Apache-2.0"
] | 2
|
2021-02-19T12:09:12.000Z
|
2021-03-18T07:48:14.000Z
|
eigen_matrix_utils/src/eigen_matrix_utils/eigen_matrix_utils.cpp
|
CNR-STIIMA-IRAS/eigen_utils
|
e0697acbf39a483d61cd140ed66a1fc553009fe0
|
[
"Apache-2.0"
] | null | null | null |
#include <eigen_matrix_utils/overloads.h>
#include <eigen_matrix_utils/eigen_matrix_utils.h>
namespace eigen_utils
{
// double standard_deviation(const Eigen::Ref< Eigen::VectorXd >& vet)
// {
// Eigen::VectorXd mean_vet(vet.rows());
// mean_vet.setConstant(vet.mean());
// return std::sqrt((vet-mean_vet).dot(vet-mean_vet))/vet.rows();
// }
//double correlation(const Eigen::Ref< Eigen::VectorXd >& vet1, const Eigen::Ref< Eigen::VectorXd >& vet2)
//{
// Eigen::VectorXd mean_vet1(vet1.rows());
// mean_vet1.setConstant(vet1.mean());
// Eigen::VectorXd vet1_no_mean=vet1-mean_vet1;
// Eigen::VectorXd mean_vet2(vet2.rows());
// mean_vet2.setConstant(vet2.mean());
// Eigen::VectorXd vet2_no_mean=vet2-mean_vet2;
// return ( vet1_no_mean.dot(vet2_no_mean) ) / std::sqrt( ( vet1_no_mean.dot(vet1_no_mean) ) * ( vet2_no_mean.dot(vet2_no_mean) ) );
//}
}
| 27.6875
| 133
| 0.693002
|
CNR-STIIMA-IRAS
|
40ce512023bfc4aed810512ccabe43ba044c4722
| 3,977
|
cpp
|
C++
|
mp/src/game/server/fortress/tf_playerlocaldata.cpp
|
MaartenS11/Team-Fortress-Invasion
|
f36b96d27f834d94e0db2d2a9470b05b42e9b460
|
[
"Unlicense"
] | 1
|
2021-03-20T14:27:45.000Z
|
2021-03-20T14:27:45.000Z
|
mp/src/game/server/fortress/tf_playerlocaldata.cpp
|
MaartenS11/Team-Fortress-Invasion
|
f36b96d27f834d94e0db2d2a9470b05b42e9b460
|
[
"Unlicense"
] | null | null | null |
mp/src/game/server/fortress/tf_playerlocaldata.cpp
|
MaartenS11/Team-Fortress-Invasion
|
f36b96d27f834d94e0db2d2a9470b05b42e9b460
|
[
"Unlicense"
] | null | null | null |
#include "cbase.h"
#include "tf_playerlocaldata.h"
#include "tf_player.h"
#include "mathlib/mathlib.h"
#include "entitylist.h"
extern ConVar tf_fastbuild;
ConVar tf_maxbankresources( "tf_maxbankresources", "2000", 0, "Max resources a single player can have." );
#define BANK_RESOURCE_BITS 20
#define MAX_PLAYER_RESOURCES ( (1 <<BANK_RESOURCE_BITS) - 1 )
//-----------------------------------------------------------------------------
// Purpose: SendProxy that converts the UtlVector list of objects to entindexes, where it's reassembled on the client
//-----------------------------------------------------------------------------
void SendProxy_PlayerObjectList( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID )
{
CTFPlayerLocalData *pLocalData = (CTFPlayerLocalData*)pStruct;
Assert( pLocalData->m_pPlayer );
// If this fails, then SendProxyArrayLength_PlayerObjects didn't work.
Assert( iElement < pLocalData->m_pPlayer->GetObjectCount() );
CBaseObject *pObject = pLocalData->m_pPlayer->GetObject(iElement);
EHANDLE hObject;
hObject = pObject;
SendProxy_EHandleToInt( pProp, pStruct, &hObject, pOut, iElement, objectID );
}
int SendProxyArrayLength_PlayerObjects( const void *pStruct, int objectID )
{
CTFPlayerLocalData *pLocalData = (CTFPlayerLocalData*)pStruct;
Assert( pLocalData->m_pPlayer );
int iObjects = pLocalData->m_pPlayer->GetObjectCount();
Assert( iObjects < MAX_OBJECTS_PER_PLAYER );
return iObjects;
}
BEGIN_SEND_TABLE_NOBASE( CTFPlayerLocalData, DT_TFLocal )
SendPropInt( SENDINFO(m_nInTacticalView), 1, SPROP_UNSIGNED ),
SendPropInt( SENDINFO( m_bKnockedDown ), 1, SPROP_UNSIGNED ),
SendPropVector( SENDINFO( m_vecKnockDownDir ), -1, SPROP_COORD ),
SendPropInt( SENDINFO( m_bThermalVision ), 1, SPROP_UNSIGNED ),
SendPropInt( SENDINFO( m_iIDEntIndex ), 10, SPROP_UNSIGNED ),
SendPropArray( SendPropInt( SENDINFO_ARRAY(m_iResourceAmmo), 4, SPROP_UNSIGNED ), m_iResourceAmmo ),
SendPropInt( SENDINFO(m_iBankResources), BANK_RESOURCE_BITS, SPROP_UNSIGNED ),
SendPropArray2(
SendProxyArrayLength_PlayerObjects,
SendPropInt("player_object_array_element", 0, SIZEOF_IGNORE, NUM_NETWORKED_EHANDLE_BITS, SPROP_UNSIGNED, SendProxy_PlayerObjectList),
MAX_OBJECTS_PER_PLAYER,
0,
"player_object_array"
),
SendPropInt( SENDINFO( m_bAttachingSapper ), 1, SPROP_UNSIGNED ),
SendPropFloat( SENDINFO( m_flSapperAttachmentFrac ), 7, SPROP_ROUNDDOWN, 0.0f, 1.0f ),
SendPropInt( SENDINFO( m_bForceMapOverview ), 1, SPROP_UNSIGNED ),
END_SEND_TABLE()
CTFPlayerLocalData::CTFPlayerLocalData()
{
m_nInTacticalView = false;
m_pPlayer = NULL;
m_bKnockedDown = false;
m_vecKnockDownDir.Init();
m_bThermalVision = false;
m_iIDEntIndex = 0;
// Resource carrying
for ( int i = 0; i < RESOURCE_TYPES; i++ )
m_iResourceAmmo.Set( i, 0 );
if( inv_demo.GetInt() )
m_iBankResources = 5000;
else
m_iBankResources = 0;
m_aObjects.Purge();
m_bAttachingSapper = false;
m_flSapperAttachmentFrac = 0;
m_bForceMapOverview = false;
}
//-----------------------------------------------------------------------------
// Add, remove, count resources
//-----------------------------------------------------------------------------
void CTFPlayerLocalData::AddResources( int iAmount )
{
m_iBankResources += iAmount;
if ( !tf_fastbuild.GetBool() && (m_iBankResources > tf_maxbankresources.GetFloat()) )
m_iBankResources = tf_maxbankresources.GetFloat();
// Clamp for overflow...
if ( m_iBankResources > MAX_PLAYER_RESOURCES )
{
Msg("Warning: Player overflowed resource count!\n");
m_iBankResources = MAX_PLAYER_RESOURCES;
}
}
void CTFPlayerLocalData::RemoveResources( int iAmount )
{
Assert( iAmount <= m_iBankResources );
m_iBankResources = max(0, m_iBankResources - iAmount);
}
int CTFPlayerLocalData::ResourceCount( void ) const
{
return m_iBankResources;
}
void CTFPlayerLocalData::SetResources( int iAmount )
{
m_iBankResources = iAmount;
}
| 32.867769
| 140
| 0.707317
|
MaartenS11
|
40cf6f3e94ed2c9d402f999b0ed23d762437b5b5
| 3,281
|
hpp
|
C++
|
Source/utils/Coordinates.hpp
|
boxuange/GRChomboo
|
22cf6751a3be29776f35a39f433f6bb497280720
|
[
"BSD-3-Clause"
] | 2
|
2018-02-23T10:46:34.000Z
|
2019-10-01T17:28:31.000Z
|
Source/utils/Coordinates.hpp
|
boxuange/GRChomboo
|
22cf6751a3be29776f35a39f433f6bb497280720
|
[
"BSD-3-Clause"
] | null | null | null |
Source/utils/Coordinates.hpp
|
boxuange/GRChomboo
|
22cf6751a3be29776f35a39f433f6bb497280720
|
[
"BSD-3-Clause"
] | 1
|
2022-02-24T23:01:02.000Z
|
2022-02-24T23:01:02.000Z
|
/* GRChombo
* Copyright 2012 The GRChombo collaboration.
* Please refer to LICENSE in GRChombo's root directory.
*/
#ifndef COORDINATES_HPP_
#define COORDINATES_HPP_
#include "DimensionDefinitions.hpp"
#include "IntVect.H"
#include "simd.hpp"
#include <array>
template <class data_t> class Coordinates
{
public:
data_t x; // We vectorise over x so we must allow x to be a vector
double y;
double z;
std::array<double, CH_SPACEDIM> m_center;
Coordinates(IntVect integer_coords, double dx,
std::array<double, CH_SPACEDIM> center = {0})
: m_center(center)
{
compute_coord(x, integer_coords[0], dx, center[0]);
// The below code allows for 2D Cartoon reduction:
#if DEFAULT_TENSOR_DIM == CH_SPACEDIM && CH_SPACEDIM == 3
compute_coord(y, integer_coords[1], dx, center[1]);
compute_coord(z, integer_coords[2], dx, center[2]);
#elif DEFAULT_TENSOR_DIM == CH_SPACEDIM + 1 && CH_SPACEDIM == 2
y = 0;
compute_coord(z, integer_coords[1], dx, center[1]);
#else
#ifdef CH_SPACEDIM
#error compute_coord has not got your dimension combination implemented.
#endif
#endif
}
ALWAYS_INLINE static void compute_coord(double &out, int position,
double dx,
double center_distance = 0)
{
out = (position + 0.5) * dx - center_distance;
}
static typename std::enable_if_t<(simd_traits<double>::simd_len > 1), void>
compute_coord(simd<double> &out, int position, double dx,
double center_distance = 0)
{
double out_arr[simd_traits<double>::simd_len];
for (int i = 0; i < simd_traits<double>::simd_len; ++i)
{
out_arr[i] = (position + i + 0.5) * dx - center_distance;
}
out = simd<double>::load(out_arr);
}
/// This function returns the radius subject to a floor for a given
/// Coordinates object.
data_t get_radius() const
{
// Note that this is not currently dimension independent
data_t r = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
const double minimum_r = 1e-6;
return simd_max(r, minimum_r);
}
/// This static function returns the radius subject to a floor
/// for when no coordinates object exists.
static data_t get_radius(IntVect integer_coords, double dx,
std::array<double, CH_SPACEDIM> center = {0})
{
data_t xx;
double yy;
double zz;
// Note that this is not currently dimension independent
compute_coord(xx, integer_coords[0], dx, center[0]);
compute_coord(yy, integer_coords[1], dx, center[1]);
compute_coord(zz, integer_coords[2], dx, center[2]);
data_t r = sqrt(pow(xx, 2) + pow(yy, 2) + pow(zz, 2));
const double minimum_r = 1e-6;
return simd_max(r, minimum_r);
}
};
template <typename data_t>
ALWAYS_INLINE ostream &operator<<(ostream &os,
const Coordinates<data_t> &in_coords)
{
os << "(x,y,z) = (" << in_coords.x << "," << in_coords.y << ","
<< in_coords.z << ")"
<< " r = " << in_coords.get_radius();
return os;
}
#endif /* COORDINATES_HPP_ */
| 31.854369
| 79
| 0.604694
|
boxuange
|
40d3b6e1fbf2cc7cffb32460a018938c3b180399
| 1,649
|
hpp
|
C++
|
lib/_old/segment_tree_virtual.hpp
|
kuhaku-space/atcoder-lib
|
7fe1365e1be69d3eff11e122b2c7dff997a6c541
|
[
"Apache-2.0"
] | null | null | null |
lib/_old/segment_tree_virtual.hpp
|
kuhaku-space/atcoder-lib
|
7fe1365e1be69d3eff11e122b2c7dff997a6c541
|
[
"Apache-2.0"
] | 4
|
2022-01-05T14:40:40.000Z
|
2022-03-05T08:03:19.000Z
|
lib/_old/segment_tree_virtual.hpp
|
kuhaku-space/atcoder-lib
|
7fe1365e1be69d3eff11e122b2c7dff997a6c541
|
[
"Apache-2.0"
] | null | null | null |
#include "template/template.hpp"
/**
* @brief セグメント木
*
* @tparam T 要素の型
* @tparam F 関数の型
*/
template <class T>
struct segment_tree {
int N;
const T e;
vector<T> data;
segment_tree() {}
segment_tree(int _n, T _e) : e(_e) { this->init(_n, _e); }
const T &operator[](int i) const { return this->data[i + this->N]; }
T at(int k) const { return this->operator[](k); }
T get(int k) const { return this->operator[](k); }
void init(int n, const T val) {
for (this->N = 1; this->N < n; this->N <<= 1) {}
this->data.assign(this->N << 1, val);
}
template <class U>
void build(const vector<U> &v) {
for (int i = 0, n = v.size(); i < n; ++i) this->data[this->N + i] = T(v[i]);
for (int i = this->N - 1; i >= 1; --i)
this->data[i] = this->op(this->data[i * 2], this->data[i * 2 + 1]);
}
void apply(int k, T val) {
assert(0 <= k && k < this->N);
k += this->N;
this->data[k] = f(val, this->data[k]);
while ((k >>= 1) >= 1) this->data[k] = this->op(this->data[k * 2], this->data[k * 2 + 1]);
}
T all_prod() const { return this->data[1]; }
T prod(int a, int b) const {
assert(0 <= a && b <= this->N);
T l = e, r = e;
for (a += this->N, b += this->N; a < b; a >>= 1, b >>= 1) {
if (a & 1) l = this->op(l, this->data[a++]);
if (b & 1) r = this->op(this->data[--b], r);
}
return this->op(l, r);
}
protected:
virtual T op(T a, T b) const = 0;
virtual T f(T val, T x) const = 0;
};
| 29.446429
| 99
| 0.454215
|
kuhaku-space
|
40d6ff8a6ec8f722e2fdd51a0aeecb3f5a17ea1c
| 1,133
|
cpp
|
C++
|
TPPEngine/Tpp_Scene.cpp
|
ArtiomTr/Game
|
f3978d220c29a8773728c536867b8a8f8cf91493
|
[
"MIT"
] | null | null | null |
TPPEngine/Tpp_Scene.cpp
|
ArtiomTr/Game
|
f3978d220c29a8773728c536867b8a8f8cf91493
|
[
"MIT"
] | null | null | null |
TPPEngine/Tpp_Scene.cpp
|
ArtiomTr/Game
|
f3978d220c29a8773728c536867b8a8f8cf91493
|
[
"MIT"
] | null | null | null |
#include "Tpp_Scene.h"
namespace tp {
Scene::Scene(std::vector<IEntityController*> c) {
for (int i = 0; i < c.size(); i++)
controllers.push_back(c[i]);
}
int Scene::getEntityCount(std::string name) {
if (entities.find(name) != entities.end()) {
return entities[name].size();
}
return -1;
}
void Scene::addGameObject(std::vector<Entity*> ents,
GameObject* newGameObject) {
for (int i = 0; i < ents.size(); i++) {
ents[i]->gameObject = newGameObject;
if (entities.find(ents[i]->getName()) != entities.end()) {
entities[ents[i]->getName()].push_back(ents[i]);
} else {
std::vector<Entity*> newEntityVector;
newEntityVector.push_back(ents[i]);
entities.insert(
std::make_pair(ents[i]->getName(), newEntityVector));
}
newGameObject->addNewEntity(entities[ents[i]->getName()].size() -
1);
}
gameObjects.push_back(newGameObject);
}
void Scene::ECS_update() {
for (int i = 0; i < controllers.size(); i++) {
if (entities.find(controllers[i]->getName()) != entities.end())
controllers[i]->deepUpdate(entities[controllers[i]->getName()]);
}
}
}
| 26.97619
| 68
| 0.62842
|
ArtiomTr
|
40d771533e223169ff38e8bc1e59e3407db005a7
| 3,601
|
cpp
|
C++
|
tasks/functions/functions_test.cpp
|
SIP-2015/skeleton
|
6585ad70e7b5a7e9e5f416556b03bcc63f05a3ec
|
[
"Unlicense"
] | null | null | null |
tasks/functions/functions_test.cpp
|
SIP-2015/skeleton
|
6585ad70e7b5a7e9e5f416556b03bcc63f05a3ec
|
[
"Unlicense"
] | null | null | null |
tasks/functions/functions_test.cpp
|
SIP-2015/skeleton
|
6585ad70e7b5a7e9e5f416556b03bcc63f05a3ec
|
[
"Unlicense"
] | null | null | null |
/*
* functions_test.cpp
*
* Created On: June 10, 2015
* Author: Matthew Mussomele
*/
#include "gtest/gtest.h"
#include "functions.h"
namespace {
class function_test : public ::testing::Test {
protected:
function_test() { }
virtual ~function_test() { }
virtual void SetUp() { }
virtual void TearDown() { }
};
/**
* @brief gets a stringstream object containing output to stdout
* @return a stringstream object that acts as stdout (print statements will go there)
*/
std::stringstream get_cout_redirect() {
std::stringstream buffer;
std::cout.rdbuf(buffer.rdbuf());
return buffer;
}
TEST_F(function_test, test_print_joined_basic) {
std::stringstream buffer = get_cout_redirect();
print_joined(1, 23);
ASSERT_STREQ("123\n", buffer.str().c_str());
}
TEST_F(function_test, test_print_joined_neg_basic) {
std::stringstream buffer = get_cout_redirect();
print_joined(-1, 23);
ASSERT_STREQ("-123\n", buffer.str().c_str());
}
TEST_F(function_test, test_print_joined_no_middle_neg) {
std::stringstream buffer = get_cout_redirect();
print_joined(314, -413);
ASSERT_STREQ("314413\n", buffer.str().c_str());
}
TEST_F(function_test, test_print_joined_no_overflow) {
std::stringstream buffer = get_cout_redirect();
print_joined(12438234, 321948230);
ASSERT_STREQ("12438234321948230\n", buffer.str().c_str());
}
TEST_F(function_test, test_absolute_sum_basic) {
ASSERT_EQ(10, absolute_sum(5, 5));
ASSERT_EQ(10, absolute_sum(-5, -5));
}
TEST_F(function_test, test_absolute_sum_correct_abs) {
ASSERT_EQ(10, absolute_sum(-5, 15));
ASSERT_EQ(10, absolute_sum(5, -15));
ASSERT_EQ(0, absolute_sum(1500000000, -1500000000));
}
TEST_F(function_test, test_largest_product_irrelevant_order) {
ASSERT_EQ(12, largest_product(2, 3, 4));
ASSERT_EQ(12, largest_product(3, 2, 4));
ASSERT_EQ(12, largest_product(4, 3, 2));
}
TEST_F(function_test, test_largest_product_duplicates) {
ASSERT_EQ(8, largest_product(2, 2, 4));
ASSERT_EQ(12, largest_product(3, 3, 4));
ASSERT_EQ(16, largest_product(4, 4, 4));
}
TEST_F(function_test, test_largest_prime_under_valid) {
ASSERT_EQ(17, largest_prime_under(17));
ASSERT_EQ(17, largest_prime_under(18));
ASSERT_EQ(2, largest_prime_under(2));
ASSERT_EQ(3, largest_prime_under(3));
ASSERT_EQ(97, largest_prime_under(100));
ASSERT_EQ(79, largest_prime_under(81));
ASSERT_EQ(31, largest_prime_under(32));
}
TEST_F(function_test, test_largest_prime_under_noprime) {
ASSERT_EQ(1, largest_prime_under(1));
ASSERT_EQ(0, largest_prime_under(0));
ASSERT_EQ(-2000, largest_prime_under(-2000));
}
TEST_F(function_test, test_fact_or_fib_fact) {
ASSERT_EQ(6, fact_or_fib(3));
ASSERT_EQ(5040, fact_or_fib(7));
ASSERT_EQ(39916800, fact_or_fib(11));
ASSERT_EQ(1, fact_or_fib(-3));
}
TEST_F(function_test, test_fact_or_fib_fib) {
ASSERT_EQ(0, fact_or_fib(0));
ASSERT_EQ(1, fact_or_fib(2));
ASSERT_EQ(8, fact_or_fib(6));
ASSERT_EQ(46368, fact_or_fib(24));
ASSERT_EQ(832040, fact_or_fib(30));
ASSERT_EQ(102334155, fact_or_fib(40));
}
}
int main(int argc, char ** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.043103
| 89
| 0.639545
|
SIP-2015
|
40d7a6a42723bfe9db56ba286d5e7cab9f503433
| 10,983
|
cpp
|
C++
|
QuantumGateLib/Core/ListenerManager.cpp
|
kareldonk/QuantumGate
|
c6563b156c628ca0d32534680aa001d4eb820b73
|
[
"MIT"
] | 87
|
2018-09-01T05:29:22.000Z
|
2022-03-13T17:44:00.000Z
|
QuantumGateLib/Core/ListenerManager.cpp
|
kareldonk/QuantumGate
|
c6563b156c628ca0d32534680aa001d4eb820b73
|
[
"MIT"
] | 6
|
2019-01-30T14:48:17.000Z
|
2022-03-14T21:10:56.000Z
|
QuantumGateLib/Core/ListenerManager.cpp
|
kareldonk/QuantumGate
|
c6563b156c628ca0d32534680aa001d4eb820b73
|
[
"MIT"
] | 16
|
2018-11-25T23:09:47.000Z
|
2022-02-01T22:14:11.000Z
|
// This file is part of the QuantumGate project. For copyright and
// licensing information refer to the license file(s) in the project root.
#include "pch.h"
#include "ListenerManager.h"
#include "..\API\Access.h"
using namespace std::literals;
using namespace QuantumGate::Implementation::Network;
namespace QuantumGate::Implementation::Core::Listener
{
Manager::Manager(const Settings_CThS& settings, Access::Manager& accessmgr, Peer::Manager& peers) noexcept :
m_Settings(settings), m_AccessManager(accessmgr), m_PeerManager(peers)
{}
// Starts listening on the default interfaces
bool Manager::Startup() noexcept
{
if (m_Running) return true;
LogSys(L"Listenermanager starting up...");
PreStartup();
const auto& settings = m_Settings.GetCache();
const auto& listener_ports = settings.Local.ListenerPorts;
const auto nat_traversal = settings.Local.NATTraversal;
const auto cond_accept = settings.Local.UseConditionalAcceptFunction;
// Should have at least one port
if (listener_ports.empty())
{
LogErr(L"Listenermanager startup failed; no ports given");
return false;
}
const std::array<IPAddress::Family, 2> afs{ IPAddress::Family::IPv4, IPAddress::Family::IPv6 };
for (const auto& af : afs)
{
const std::optional<IPAddress> address = std::invoke([&]() -> std::optional<IPAddress>
{
switch (af)
{
case IPAddress::Family::IPv4:
return IPAddress::AnyIPv4();
break;
case IPAddress::Family::IPv6:
return IPAddress::AnyIPv6();
break;
default:
assert(false);
break;
}
return std::nullopt;
});
if (address.has_value())
{
DiscardReturnValue(AddListenerThreads(*address, listener_ports, cond_accept, nat_traversal));
}
}
if (m_ListenerThreadPool.Startup())
{
m_Running = true;
m_ListeningOnAnyAddresses = true;
LogSys(L"Listenermanager startup successful");
}
else LogErr(L"Listenermanager startup failed");
return m_Running;
}
// Starts listening on all active interfaces
bool Manager::Startup(const Vector<API::Local::Environment::EthernetInterface>& interfaces) noexcept
{
if (m_Running) return true;
LogSys(L"Listenermanager starting...");
PreStartup();
const auto& settings = m_Settings.GetCache();
const auto& listener_ports = settings.Local.ListenerPorts;
const auto nat_traversal = settings.Local.NATTraversal;
const auto cond_accept = settings.Local.UseConditionalAcceptFunction;
// Should have at least one port
if (listener_ports.empty())
{
LogErr(L"Listenermanager startup failed; no ports given");
return false;
}
// Create a listening socket for each interface that's online
for (const auto& ifs : interfaces)
{
if (ifs.Operational)
{
for (const auto& address : ifs.IPAddresses)
{
// Only for IPv4 and IPv6 addresses
if (address.GetFamily() == IPAddress::Family::IPv4 || address.GetFamily() == IPAddress::Family::IPv6)
{
DiscardReturnValue(AddListenerThreads(address, listener_ports, cond_accept, nat_traversal));
}
else assert(false);
}
}
}
if (m_ListenerThreadPool.Startup())
{
m_Running = true;
m_ListeningOnAnyAddresses = false;
LogSys(L"Listenermanager startup successful");
}
else LogErr(L"Listenermanager startup failed");
return m_Running;
}
bool Manager::AddListenerThreads(const IPAddress& address, const Vector<UInt16> ports,
const bool cond_accept, const bool nat_traversal) noexcept
{
// Separate listener for every port
for (const auto port : ports)
{
try
{
const auto endpoint = IPEndpoint(address, port);
ThreadData ltd;
ltd.UseConditionalAcceptFunction = cond_accept;
// Create and start the listenersocket
ltd.Socket = Network::Socket(endpoint.GetIPAddress().GetFamily(),
Network::Socket::Type::Stream,
Network::IP::Protocol::TCP);
if (ltd.Socket.Listen(endpoint, true, nat_traversal))
{
if (m_ListenerThreadPool.AddThread(L"QuantumGate Listener Thread " + endpoint.GetString(),
std::move(ltd), MakeCallback(this, &Manager::WorkerThreadProcessor)))
{
LogSys(L"Listening on endpoint %s", endpoint.GetString().c_str());
}
else
{
LogErr(L"Could not add listener thread for endpoint %s", endpoint.GetString().c_str());
}
}
}
catch (const std::exception& e)
{
LogErr(L"Could not add listener thread for IP %s due to exception: %s",
address.GetString().c_str(), Util::ToStringW(e.what()).c_str());
}
catch (...) {}
}
return true;
}
std::optional<Manager::ThreadPool::Thread> Manager::RemoveListenerThread(Manager::ThreadPool::Thread&& thread) noexcept
{
const IPEndpoint endpoint = thread.GetData().Socket.GetLocalEndpoint();
const auto [success, next_thread] = m_ListenerThreadPool.RemoveThread(std::move(thread));
if (success)
{
LogSys(L"Stopped listening on endpoint %s", endpoint.GetString().c_str());
}
else
{
LogErr(L"Could not remove listener thread for endpoint %s", endpoint.GetString().c_str());
}
return next_thread;
}
bool Manager::Update(const Vector<API::Local::Environment::EthernetInterface>& interfaces) noexcept
{
if (!m_Running) return false;
// No need to update in this case
if (m_ListeningOnAnyAddresses) return true;
LogSys(L"Updating Listenermanager...");
const auto& settings = m_Settings.GetCache();
const auto& listener_ports = settings.Local.ListenerPorts;
const auto nat_traversal = settings.Local.NATTraversal;
const auto cond_accept = settings.Local.UseConditionalAcceptFunction;
// Check for interfaces/IP addresses that were added for which
// there are no listeners; we add listeners for those
for (const auto& ifs : interfaces)
{
if (ifs.Operational)
{
for (const auto& address : ifs.IPAddresses)
{
// Only for IPv4 and IPv6 addresses
if (address.GetFamily() == IP::AddressFamily::IPv4 || address.GetFamily() == IP::AddressFamily::IPv6)
{
auto found = false;
auto thread = m_ListenerThreadPool.GetFirstThread();
while (thread.has_value())
{
if (thread->GetData().Socket.GetLocalIPAddress() == address)
{
found = true;
break;
}
else thread = m_ListenerThreadPool.GetNextThread(*thread);
}
if (!found)
{
DiscardReturnValue(AddListenerThreads(address, listener_ports, cond_accept, nat_traversal));
}
}
}
}
}
// Check for interfaces/IP addresses that were removed for which
// there are still listeners; we remove listeners for those
auto thread = m_ListenerThreadPool.GetFirstThread();
while (thread.has_value())
{
auto found = false;
for (const auto& ifs : interfaces)
{
if (ifs.Operational)
{
for (const auto& address : ifs.IPAddresses)
{
if (thread->GetData().Socket.GetLocalIPAddress() == address)
{
found = true;
}
}
}
}
if (!found)
{
thread = RemoveListenerThread(std::move(*thread));
}
else thread = m_ListenerThreadPool.GetNextThread(*thread);
}
return true;
}
void Manager::Shutdown() noexcept
{
if (!m_Running) return;
m_Running = false;
LogSys(L"Listenermanager shutting down...");
m_ListenerThreadPool.Shutdown();
ResetState();
LogSys(L"Listenermanager shut down");
}
void Manager::PreStartup() noexcept
{
ResetState();
}
void Manager::ResetState() noexcept
{
m_ListeningOnAnyAddresses = false;
m_ListenerThreadPool.Clear();
}
void Manager::WorkerThreadProcessor(ThreadPoolData& thpdata, ThreadData& thdata, const Concurrency::Event& shutdown_event)
{
// Check if we have a read event waiting for us
if (thdata.Socket.UpdateIOStatus(1ms))
{
if (thdata.Socket.GetIOStatus().CanRead())
{
// Probably have a connection waiting to accept
LogInfo(L"Accepting new connection on endpoint %s",
thdata.Socket.GetLocalEndpoint().GetString().c_str());
AcceptConnection(thdata.Socket, thdata.UseConditionalAcceptFunction);
}
else if (thdata.Socket.GetIOStatus().HasException())
{
LogErr(L"Exception on listener socket for endpoint %s (%s)",
thdata.Socket.GetLocalEndpoint().GetString().c_str(),
GetSysErrorString(thdata.Socket.GetIOStatus().GetErrorCode()).c_str());
}
}
else
{
LogErr(L"Could not get status of listener socket for endpoint %s",
thdata.Socket.GetLocalEndpoint().GetString().c_str());
}
}
void Manager::AcceptConnection(Network::Socket& listener_socket, const bool cond_accept) noexcept
{
auto peerths = m_PeerManager.Create(PeerConnectionType::Inbound, std::nullopt);
if (peerths != nullptr)
{
peerths->WithUniqueLock([&](Peer::Peer& peer)
{
if (cond_accept)
{
if (!listener_socket.Accept(peer.GetSocket<Network::Socket>(), true,
&Manager::AcceptConditionFunction, this))
{
// Couldn't accept for some reason
return;
}
}
else
{
if (listener_socket.Accept(peer.GetSocket<Network::Socket>(), false, nullptr, nullptr))
{
// Check if the IP address is allowed
if (!CanAcceptConnection(peer.GetPeerIPAddress()))
{
peer.Close();
LogWarn(L"Incoming connection from peer %s was rejected; IP address is not allowed by access configuration",
peer.GetPeerName().c_str());
return;
}
}
}
if (m_PeerManager.Accept(peerths))
{
LogInfo(L"Connection accepted from peer %s", peer.GetPeerName().c_str());
}
else
{
peer.Close();
LogErr(L"Could not accept connection from peer %s", peer.GetPeerName().c_str());
}
});
}
}
bool Manager::CanAcceptConnection(const IPAddress& ipaddr) const noexcept
{
// Increase connection attempts for this IP; if attempts get too high
// for a given interval the IP will get a bad reputation and this will fail
if (m_AccessManager.AddIPConnectionAttempt(ipaddr))
{
// Check if IP is allowed through filters/limits and if it has acceptible reputation
if (const auto result = m_AccessManager.GetIPConnectionAllowed(ipaddr, Access::CheckType::All); result.Succeeded())
{
return *result;
}
}
// If anything goes wrong we always deny access
return false;
}
int CALLBACK Manager::AcceptConditionFunction(LPWSABUF lpCallerId, LPWSABUF lpCallerData, LPQOS lpSQOS, LPQOS lpGQOS,
LPWSABUF lpCalleeId, LPWSABUF lpCalleeData, GROUP FAR* g,
DWORD_PTR dwCallbackData) noexcept
{
const IPEndpoint endpoint(reinterpret_cast<sockaddr_storage*>(lpCallerId->buf));
if (reinterpret_cast<Manager*>(dwCallbackData)->CanAcceptConnection(endpoint.GetIPAddress()))
{
return CF_ACCEPT;
}
LogWarn(L"Incoming connection attempt from peer %s was rejected; IP address is not allowed by access configuration",
endpoint.GetString().c_str());
return CF_REJECT;
}
}
| 27.595477
| 123
| 0.683693
|
kareldonk
|
40d87dff04118c9ec272b78385a1ce96c4dcf233
| 1,432
|
cpp
|
C++
|
LightOJ/1079 - Just another Robbery/sol.cpp
|
Tahsin716/OnlineJudge
|
a5d15f37a8c260740c148370ced7a2a9096050c1
|
[
"MIT"
] | null | null | null |
LightOJ/1079 - Just another Robbery/sol.cpp
|
Tahsin716/OnlineJudge
|
a5d15f37a8c260740c148370ced7a2a9096050c1
|
[
"MIT"
] | null | null | null |
LightOJ/1079 - Just another Robbery/sol.cpp
|
Tahsin716/OnlineJudge
|
a5d15f37a8c260740c148370ced7a2a9096050c1
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <cstring>
#include <climits>
using namespace std;
double P[101], dp[101][10001], x;
int bank[101], n;
//The prob of getting caught in one of the two banks = the prob of getting caught in the first or the prob
//of not getting caught in the first and getting caught in the second.
double rec(int index, int money)
{
if (money <= 0) return 0;
if (index < 0) return 1;
if (dp[index][money] > -1)
return dp[index][money];
double ret = 1.79769e+308; // Double Max
ret = rec(index - 1, money);
ret = min(ret, P[index] + (1.0 - P[index]) * rec(index - 1, money - bank[index]));
return dp[index][money] = ret;
}
int main()
{
int T, testCase = 0, high, low, mid;
scanf("%d", &T);
while (T--)
{
scanf("%lf %d", &x, &n);
high = 0, low = 0;
for (int i = 0; i < n; i++)
{
scanf("%d %lf", &bank[i], &P[i]);
high += bank[i];
}
memset(dp, -1, sizeof dp);
//For precision, since (high + low) / 2 will return an integer
// so there may be chances of late stages being skipped
while (high - low >= 4)
{
mid = (high + low) / 2;
if (rec(n - 1, mid) < x)
{
low = mid;
}
else
{
high = mid - 1;
}
}
//Answers are in increasing order
//So binary search to find the answer
while (high >= low)
{
if (rec(n - 1, high) < x)
break;
high--;
}
printf("Case %d: %d\n", ++testCase, high);
}
return 0;
}
| 17.463415
| 107
| 0.569832
|
Tahsin716
|
40d9d2e01422072b52d19cdabdab2f9071408f25
| 2,818
|
cpp
|
C++
|
IOI/poi.cpp
|
eddiegz/Personal-C
|
f7869826216e5c665f8f646502141f0dc680e545
|
[
"MIT"
] | 3
|
2021-05-15T08:18:09.000Z
|
2021-05-17T04:41:57.000Z
|
IOI/poi.cpp
|
eddiegz/Personal-C
|
f7869826216e5c665f8f646502141f0dc680e545
|
[
"MIT"
] | null | null | null |
IOI/poi.cpp
|
eddiegz/Personal-C
|
f7869826216e5c665f8f646502141f0dc680e545
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using str = string;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<ld>;
using vs = vector<str>;
using vc = vector<char>;
using vvi = vector<vi>;
using vvc = vector<vc>;
#define pb push_back
#define pob pop_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
#define si set<int>
#define sl set<ll>
#define sb set<bool>
#define sc set<char>
#define ff first
#define ss second
#define sf scanf
#define pf printf
#define mii map<int,int>
#define msi map<str,int>
#define mis map<int,str>
#define mci map<char,int>
#define mdd map<double,double>
#define mll map<ll,ll>
#define pii pair<int,int>
#define pis pair<int,str>
#define psi pair<str,int>
#define pss pair<str,str>
#define pci pair<char,int>
#define pcc pair<char,char>
#define endl "\n"
#define all(x) x.begin(),x.end()
#define rep( i , s , e ) for(int i = s ; i <= e ; ++i)
#define repR( i , e , s ) for(int i = e ; i >= s ; --i)
#define dtest(x,p) cout<<x<<p<<endl;
#define arprint(x) for(auto ele:x){cout<<ele<<" ";}cout<<endl;
//#define DEBUG
void inoutio(str s){
freopen((s + ".in").c_str(), "r" , stdin);
freopen((s + ".out") .c_str(), "w" , stdout);
}
void txtio(str inf,str ouf){
freopen(inf.c_str(), "r" , stdin);
freopen(ouf.c_str(), "w" , stdout);
}
const int MOD=1e9+7;
const int MAXN=1e6;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);cout.tie(nullptr);
int n,t,p;
vi rank;
cin>>n>>t>>p;
bool status[n+1][t+1];int score[t+1];
rep(i,1,n){
rep(j,1,t){
cin>>status[i][j];
}
}
rep(i,1,t){
int current=0;
rep(j,1,n){
if(!status[j][i]){current++;}
}
score[i]=current;
}
map<int,pii> recorder;
int phiscore=0;
rep(i,1,n){
int current=0;
int number=0;
rep(j,1,t){
if(status[i][j]){current+=score[j];number++;}
}
recorder[i]=mp(number,current);
if(i==p){
phiscore=current;
}
rank.pb(current);
}
int phisrank=1;
sort(all(rank));
phisrank=rank.end()-ub(all(rank),phiscore)+1;
#ifdef DEBUG
cout<<phisrank<<"ensure"<<endl;
#endif
map<int,pii> same;
int phisnumber=recorder[p].ff;
for(auto ele:recorder){
#ifdef DEBUG
cout<<ele.ff<<"id"<<endl;
cout<<ele.ss.ss<<"score"<<phiscore<<endl;
cout<<ele.ss.ff<<"number"<<phisnumber<<" "<<endl;
cout<<endl;
#endif
if(ele.ff!=p&&ele.ss.ss==phiscore&&((ele.ss.ff>phisnumber)||(ele.ss.ff==phisnumber&&ele.ff<p))){
phisrank++;
}
}
cout<<phiscore<<" "<<phisrank<<endl;
}
| 24.719298
| 104
| 0.577715
|
eddiegz
|
40dd1f7e204ce90cfc60e43aebd57158d999905b
| 3,456
|
hpp
|
C++
|
games/spiders/brood_mother.hpp
|
JackLimes/Joueur.cpp
|
d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b
|
[
"MIT"
] | null | null | null |
games/spiders/brood_mother.hpp
|
JackLimes/Joueur.cpp
|
d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b
|
[
"MIT"
] | null | null | null |
games/spiders/brood_mother.hpp
|
JackLimes/Joueur.cpp
|
d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b
|
[
"MIT"
] | null | null | null |
#ifndef GAMES_SPIDERS_BROOD_MOTHER_H
#define GAMES_SPIDERS_BROOD_MOTHER_H
// BroodMother
// The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
#include <vector>
#include <queue>
#include <deque>
#include <unordered_map>
#include <string>
#include <initializer_list>
#include "../../joueur/src/any.hpp"
#include "spider.hpp"
#include "impl/spiders_fwd.hpp"
// <<-- Creer-Merge: includes -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional #includes here
// <<-- /Creer-Merge: includes -->>
namespace cpp_client
{
namespace spiders
{
/// <summary>
/// The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses.
/// </summary>
class Brood_mother_ : public Spider_
{
public:
/// <summary>
/// How many eggs the BroodMother has to spawn Spiderlings this turn.
/// </summary>
const double& eggs;
/// <summary>
/// How much health this BroodMother has left. When it reaches 0, she dies and her owner loses.
/// </summary>
const int& health;
// <<-- Creer-Merge: member variables -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// You can add additional member variables here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: member variables -->>
/// <summary>
/// consumes a _spiderling of the same owner to regain some eggs to spawn more _spiderlings.
/// </summary>
/// <param name="spiderling"> The Spiderling to consume. It must be on the same Nest as this BroodMother. </param>
bool consume(const Spiderling& spiderling);
/// <summary>
/// spawns a new _spiderling on the same _nest as this _brood_mother, consuming an egg.
/// </summary>
/// <param name="spiderling_type"> The string name of the Spiderling class you want to Spawn. Must be 'Spitter', 'Weaver', or 'Cutter'. </param>
Spiderling spawn(const std::string& spiderling_type);
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// You can add additional methods here.
// <<-- /Creer-Merge: methods -->>
~Brood_mother_();
// ####################
// Don't edit these!
// ####################
/// \cond FALSE
Brood_mother_(std::initializer_list<std::pair<std::string, Any&&>> init);
Brood_mother_() : Brood_mother_({}){}
virtual void resize(const std::string& name, std::size_t size) override;
virtual void change_vec_values(const std::string& name, std::vector<std::pair<std::size_t, Any>>& values) override;
virtual void remove_key(const std::string& name, Any& key) override;
virtual std::unique_ptr<Any> add_key_value(const std::string& name, Any& key, Any& value) override;
virtual bool is_map(const std::string& name) override;
virtual void rebind_by_name(Any* to_change, const std::string& member, std::shared_ptr<Base_object> ref) override;
/// \endcond
// ####################
// Don't edit these!
// ####################
};
} // spiders
} // cpp_client
#endif // GAMES_SPIDERS_BROOD_MOTHER_H
| 35.265306
| 148
| 0.676505
|
JackLimes
|
40e0226b14677becafa8c73f7833aef3cbfd3045
| 48,398
|
cpp
|
C++
|
Tools/ToolsRig/TerrainConversion.cpp
|
djewsbury/XLE
|
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
|
[
"MIT"
] | 3
|
2015-12-04T09:16:53.000Z
|
2021-05-28T23:22:49.000Z
|
Tools/ToolsRig/TerrainConversion.cpp
|
djewsbury/XLE
|
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
|
[
"MIT"
] | null | null | null |
Tools/ToolsRig/TerrainConversion.cpp
|
djewsbury/XLE
|
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
|
[
"MIT"
] | 2
|
2015-03-03T05:32:39.000Z
|
2015-12-04T09:16:54.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)
#define _SCL_SECURE_NO_WARNINGS
#include "TerrainConversion.h"
#include "TerrainOp.h"
#include "TerrainShadowOp.h"
#include "../../SceneEngine/Terrain.h"
#include "../../SceneEngine/TerrainFormat.h"
#include "../../SceneEngine/TerrainConfig.h"
#include "../../SceneEngine/TerrainUberSurface.h"
#include "../../SceneEngine/TerrainScaffold.h"
#include "../../RenderCore/Format.h" // (for BitsPerPixel)
#include "../../Math/Vector.h"
#include "../../ConsoleRig/IProgress.h"
#include "../../OSServices/Log.h"
#include "../../Assets/IFileSystem.h"
#include "../../Utility/StringUtils.h"
#include "../../Utility/StringFormat.h"
#include "../../OSServices/RawFS.h"
#include "../../Utility/Streams/PathUtils.h"
#include "../../Utility/Conversion.h"
#include "../../Utility/Threading/ThreadingUtils.h"
#include <vector>
#include <regex>
#include "../../Foreign/LibTiff/tiff.h"
#include "../../Foreign/LibTiff/tiffio.h"
#include "../../Foreign/half-1.9.2/include/half.hpp"
namespace ToolsRig
{
using namespace SceneEngine;
static bool DoesFileExist(const char fn[])
{
return ::Assets::MainFileSystem::TryGetDesc(fn)._state == ::Assets::FileDesc::State::Normal;
}
//////////////////////////////////////////////////////////////////////////////////////////
static void WriteCellCoverageData(
const TerrainConfig& cfg, ITerrainFormat& ioFormat,
const ::Assets::ResChar uberSurfaceName[], unsigned layerIndex,
bool overwriteExisting,
ConsoleRig::IProgress* progress)
{
::Assets::ResChar path[MaxPath];
auto cells = BuildPrimedCells(cfg);
auto& layer = cfg.GetCoverageLayer(layerIndex);
auto step = progress ? progress->BeginStep("Write coverage cells", (unsigned)cells.size(), true) : nullptr;
TerrainUberSurfaceGeneric uberSurface(uberSurfaceName);
for (auto c=cells.cbegin(); c!=cells.cend(); ++c) {
char cellFile[MaxPath];
cfg.GetCellFilename(cellFile, dimof(cellFile), c->_cellIndex, layer._id);
if (!DoesFileExist(cellFile) || overwriteExisting) {
XlDirname(path, dimof(path), cellFile);
OSServices::CreateDirectoryRecursive(path);
TRY {
ioFormat.WriteCell(
cellFile, uberSurface,
c->_coverageUber[layerIndex].first, c->_coverageUber[layerIndex].second,
cfg.CellTreeDepth(), layer._overlap);
} CATCH(...) {
Log(Error) << "Error while writing cell coverage file to: " << cellFile << std::endl;
} CATCH_END
}
if (step) {
if (step->IsCancelled()) break;
step->Advance();
}
}
}
static unsigned FindLayer(const TerrainConfig& cfg, TerrainCoverageId coverageId)
{
for (unsigned l=0; l<cfg.GetCoverageLayerCount(); ++l)
if (cfg.GetCoverageLayer(l)._id == coverageId)
return l;
return ~0u;
}
//////////////////////////////////////////////////////////////////////////////////////////
void GenerateCellFiles(
const TerrainConfig& outputConfig,
const ::Assets::ResChar uberSurfaceDir[],
bool overwriteExisting,
const GradientFlagsSettings& gradFlagSettings,
ConsoleRig::IProgress* progress)
{
auto outputIOFormat = std::make_shared<TerrainFormat>(gradFlagSettings);
assert(outputIOFormat);
//////////////////////////////////////////////////////////////////////////////////////
// for each coverage layer, we must write all of the component parts
for (unsigned l=0; l<outputConfig.GetCoverageLayerCount(); ++l) {
const auto& layer = outputConfig.GetCoverageLayer(l);
::Assets::ResChar layerUberSurface[MaxPath];
TerrainConfig::GetUberSurfaceFilename(layerUberSurface, dimof(layerUberSurface), uberSurfaceDir, layer._id);
if (DoesFileExist(layerUberSurface)) {
// open and destroy these coverage uber shadowing surface before we open the uber heights surface
// (opening them both at the same time requires too much memory)
WriteCellCoverageData(outputConfig, *outputIOFormat, layerUberSurface, l, overwriteExisting, progress);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// load the uber height surface, and uber surface interface (but only temporarily
// while we initialise the data)
::Assets::ResChar uberSurfaceFile[MaxPath];
TerrainConfig::GetUberSurfaceFilename(uberSurfaceFile, dimof(uberSurfaceFile), uberSurfaceDir, CoverageId_Heights);
TerrainUberHeightsSurface heightsData(uberSurfaceFile);
HeightsUberSurfaceInterface uberSurfaceInterface(heightsData);
//////////////////////////////////////////////////////////////////////////////////////
auto cells = BuildPrimedCells(outputConfig);
Interlocked::Value queueLoc = 0;
auto step = progress ? progress->BeginStep("Generate Cell Files", (unsigned)cells.size(), true) : nullptr;
auto threadFunction =
[&queueLoc, &cells, &outputConfig, overwriteExisting, &outputIOFormat, &step, &uberSurfaceInterface]()
{
for (;;) {
auto i = Interlocked::Increment(&queueLoc);
if (i >= (int)cells.size()) return;
const auto& c = cells[i];
char heightMapFile[MaxPath];
outputConfig.GetCellFilename(heightMapFile, dimof(heightMapFile), c._cellIndex, CoverageId_Heights);
if (overwriteExisting || !DoesFileExist(heightMapFile)) {
char path[MaxPath];
XlDirname(path, dimof(path), heightMapFile);
OSServices::CreateDirectoryRecursive(path);
TRY {
outputIOFormat->WriteCell(
heightMapFile, *uberSurfaceInterface.GetUberSurface(),
c._heightUber.first, c._heightUber.second, outputConfig.CellTreeDepth(), outputConfig.NodeOverlap());
} CATCH(...) { // sometimes throws (eg, if the directory doesn't exist)
} CATCH_END
}
if (step) {
if (step->IsCancelled()) break;
step->Advance();
}
}
};
auto hardwareConc = std::thread::hardware_concurrency();
std::vector<std::thread> threads;
for (unsigned c=0; c<std::max(1u, hardwareConc); ++c)
threads.emplace_back(std::thread(threadFunction));
for (auto&t : threads) t.join();
}
//////////////////////////////////////////////////////////////////////////////////////////
void GenerateCellFiles(
const TerrainConfig& outputConfig,
const ::Assets::ResChar uberSurfaceDir[],
bool overwriteExisting,
SceneEngine::TerrainCoverageId coverageId,
ConsoleRig::IProgress* progress)
{
auto layerIndex = FindLayer(outputConfig, coverageId);
if (layerIndex == ~0u) return;
auto outputIOFormat = std::make_shared<TerrainFormat>();
assert(outputIOFormat);
::Assets::ResChar layerUberSurface[MaxPath];
TerrainConfig::GetUberSurfaceFilename(layerUberSurface, dimof(layerUberSurface), uberSurfaceDir, coverageId);
if (DoesFileExist(layerUberSurface)) {
// open and destroy these coverage uber shadowing surface before we open the uber heights surface
// (opening them both at the same time requires too much memory)
WriteCellCoverageData(outputConfig, *outputIOFormat, layerUberSurface, layerIndex, overwriteExisting, progress);
}
}
static void GenerateSurface(
ITerrainOp& op, TerrainCoverageId coverageId,
const TerrainConfig& cfg,
const ::Assets::ResChar uberSurfaceDir[],
bool overwriteExisting,
ConsoleRig::IProgress* progress)
{
auto layerIndex = FindLayer(cfg, coverageId);
if (layerIndex == ~0u) return;
::Assets::ResChar shadowUberFn[MaxPath];
TerrainConfig::GetUberSurfaceFilename(shadowUberFn, dimof(shadowUberFn), uberSurfaceDir, coverageId);
if (overwriteExisting || !DoesFileExist(shadowUberFn)) {
//////////////////////////////////////////////////////////////////////////////////////
// this is the shadows layer... We need to build the shadows procedurally
::Assets::ResChar uberHeightsFile[MaxPath];
TerrainConfig::GetUberSurfaceFilename(uberHeightsFile, dimof(uberHeightsFile), uberSurfaceDir, CoverageId_Heights);
TerrainUberHeightsSurface heightsData(uberHeightsFile);
HeightsUberSurfaceInterface uberSurfaceInterface(heightsData);
//////////////////////////////////////////////////////////////////////////////////////
// build the uber shadowing file, and then write out the shadowing textures for each node
// Int2 interestingMins((9-1) * 16 * 32, (19-1) * 16 * 32), interestingMaxs((9+4) * 16 * 32, (19+4) * 16 * 32);
float shadowToHeightsScale =
cfg.NodeDimensionsInElements()[0]
/ float(cfg.GetCoverageLayer(layerIndex)._nodeDimensions[0]);
UInt2 interestingMins(0, 0);
UInt2 interestingMaxs = UInt2(
unsigned((cfg._cellCount[0] * cfg.CellDimensionsInNodes()[0] * cfg.NodeDimensionsInElements()[0]) / shadowToHeightsScale),
unsigned((cfg._cellCount[1] * cfg.CellDimensionsInNodes()[1] * cfg.NodeDimensionsInElements()[1]) / shadowToHeightsScale));
//////////////////////////////////////////////////////////////////////////////////////
BuildUberSurface(
shadowUberFn, op,
*uberSurfaceInterface.GetUberSurface(), interestingMins, interestingMaxs,
cfg.ElementSpacing(), shadowToHeightsScale,
TerrainOpConfig(),
progress);
}
//////////////////////////////////////////////////////////////////////////////////////
// write cell files
auto fmt = std::make_shared<TerrainFormat>();
WriteCellCoverageData(
cfg, *fmt, shadowUberFn, layerIndex, overwriteExisting, progress);
}
void GenerateShadowsSurface(
const TerrainConfig& cfg,
const ::Assets::ResChar uberSurfaceDir[],
bool overwriteExisting,
ConsoleRig::IProgress* progress)
{
Float2 sunAxisOfMovement(XlCos(cfg.SunPathAngle()), XlSin(cfg.SunPathAngle()));
const float shadowSearchDistance = 1000.f;
AngleBasedShadowsOperator op(sunAxisOfMovement, shadowSearchDistance);
GenerateSurface(
op, CoverageId_AngleBasedShadows,
cfg, uberSurfaceDir, overwriteExisting, progress);
}
void GenerateAmbientOcclusionSurface(
const TerrainConfig& cfg,
const ::Assets::ResChar uberSurfaceDir[],
bool overwriteExisting,
ConsoleRig::IProgress* progress)
{
static auto testRadius = 24u;
static auto power = 4.f;
AOOperator op(testRadius, power);
GenerateSurface(
op, CoverageId_AmbientOcclusion,
cfg, uberSurfaceDir, overwriteExisting, progress);
}
void GenerateMissingUberSurfaceFiles(
const TerrainConfig& cfg,
const ::Assets::ResChar uberSurfaceDir[],
ConsoleRig::IProgress* progress)
{
OSServices::CreateDirectoryRecursive(uberSurfaceDir);
auto step = progress ? progress->BeginStep("Generate UberSurface Files", (unsigned)cfg.GetCoverageLayerCount(), true) : nullptr;
for (unsigned l=0; l<cfg.GetCoverageLayerCount(); ++l) {
const auto& layer = cfg.GetCoverageLayer(l);
::Assets::ResChar uberSurfaceFile[MaxPath];
TerrainConfig::GetUberSurfaceFilename(uberSurfaceFile, dimof(uberSurfaceFile), uberSurfaceDir, layer._id);
if (DoesFileExist(uberSurfaceFile)) continue;
if (layer._id == CoverageId_AngleBasedShadows || layer._id == CoverageId_AmbientOcclusion) {
continue; // (skip, we'll get this later in GenerateShadowsSurface)
} else {
HeightsUberSurfaceInterface::BuildEmptyFile(
uberSurfaceFile,
cfg._cellCount[0] * cfg.CellDimensionsInNodes()[0] * layer._nodeDimensions[0],
cfg._cellCount[1] * cfg.CellDimensionsInNodes()[1] * layer._nodeDimensions[1],
ImpliedTyping::TypeDesc{ImpliedTyping::TypeCat(layer._typeCat), uint16(layer._typeCount)});
}
if (step) {
if (step->IsCancelled()) break;
step->Advance();
}
}
GenerateShadowsSurface(cfg, uberSurfaceDir, false, progress);
GenerateAmbientOcclusionSurface(cfg, uberSurfaceDir, false, progress);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<std::string>* s_tiffWarningVector = nullptr;
static void TIFFWarningHandler(const char* module, const char* fmt, va_list args)
{
// suppress warnings
char buffer[1024];
_vsnprintf_s(buffer, dimof(buffer), _TRUNCATE, fmt, args);
Log(Warning) << "Tiff reader warning: " << buffer << std::endl;
if (s_tiffWarningVector) {
s_tiffWarningVector->push_back(buffer);
}
}
static void TIFFErrorHandler(const char* module, const char* fmt, va_list args)
{
// suppress warnings
char buffer[1024];
_vsnprintf_s(buffer, dimof(buffer), _TRUNCATE, fmt, args);
Log(Warning) << "Tiff reader error: " << buffer << std::endl;
if (s_tiffWarningVector) {
s_tiffWarningVector->push_back(buffer);
}
}
template<typename Fn>
class AutoClose
{
public:
AutoClose(Fn&& fn) : _fn(std::move(fn)) {}
~AutoClose() { _fn(); }
protected:
Fn _fn;
};
template<typename Fn>
AutoClose<Fn> MakeAutoClose(Fn&& fn) { return AutoClose<Fn>(std::move(fn)); }
static UInt2 ClampImportDims(UInt2 input, unsigned destNodeDims, unsigned destCellTreeDepth)
{
// we have to make sure the width and height are multiples of the
// dimensions of a cell (in elements). We'll pad out the edges if
// they don't match
const unsigned cellWidthInNodes = 1<<(destCellTreeDepth-1);
const unsigned clampingDim = destNodeDims * cellWidthInNodes;
if ((input[0] % clampingDim) != 0) { input[0] += clampingDim - (input[0] % clampingDim); }
if ((input[1] % clampingDim) != 0) { input[1] += clampingDim - (input[1] % clampingDim); }
return input;
}
TerrainImportOp PrepareTerrainImport(
const ::Assets::ResChar input[],
unsigned destNodeDims, unsigned destCellTreeDepth)
{
TerrainImportOp result;
result._sourceDims = UInt2(0, 0);
result._sourceFile = input;
result._sourceIsGood = false;
result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::Float;
auto ext = XlExtension(input);
if (ext && (!XlCompareStringI(ext, "hdr") || !XlCompareStringI(ext, "flt"))) {
result._sourceFormat = TerrainImportOp::SourceFormat::AbsoluteFloats;
result._sourceHeightRange = Float2(std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());
::Assets::ResChar inputFile[MaxPath];
XlCopyString(inputFile, input);
XlChopExtension(inputFile);
XlCatString(inputFile, dimof(inputFile), ".hdr");
size_t fileSize = 0;
auto block = ::Assets::MainFileSystem::TryLoadFileAsMemoryBlock(inputFile, &fileSize);
if (block.get() && fileSize) {
std::string configAsString(block.get(), &block[fileSize]);
std::regex parse("^(\\S+)\\s+(.*)");
std::vector<int> captureGroups;
captureGroups.push_back(1);
captureGroups.push_back(2);
const std::sregex_token_iterator end;
std::sregex_token_iterator iter(configAsString.begin(), configAsString.end(), parse, captureGroups);
for (;iter != end;) {
auto paramName = *iter++;
auto paramValue = *iter++;
// we ignore many parameters. But we at least need to get ncols & nrows
// These tell us the dimensions of the input data
if (!XlCompareStringI(paramName.str().c_str(), "ncols")) { result._sourceDims[0] = XlAtoI32(paramValue.str().c_str()); }
if (!XlCompareStringI(paramName.str().c_str(), "nrows")) { result._sourceDims[1] = XlAtoI32(paramValue.str().c_str()); }
}
result._sourceIsGood = true;
} else {
result._warnings.push_back("Could not open input file");
}
} else if (ext && (!XlCompareStringI(ext, "tif") || !XlCompareStringI(ext, "tiff"))) {
auto oldWarningHandler = TIFFSetWarningHandler(&TIFFWarningHandler);
auto oldErrorHandler = TIFFSetErrorHandler(&TIFFErrorHandler);
s_tiffWarningVector = &result._warnings;
auto autoClose2 = MakeAutoClose([oldWarningHandler, oldErrorHandler]()
{
TIFFSetWarningHandler(oldWarningHandler);
TIFFSetErrorHandler(oldErrorHandler);
s_tiffWarningVector = nullptr;
});
auto* tif = TIFFOpen(input, "r");
if (tif) {
auto autoClose = MakeAutoClose([tif]() { TIFFClose(tif); });
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &result._sourceDims[0]);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &result._sourceDims[1]);
uint32 bitsPerPixel = 32;
uint32 sampleFormat = SAMPLEFORMAT_IEEEFP;
TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerPixel);
TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sampleFormat);
switch (sampleFormat) {
case SAMPLEFORMAT_UINT:
result._sourceFormat = TerrainImportOp::SourceFormat::Quantized;
if (bitsPerPixel == 8) { result._sourceHeightRange = Float2(0.f, float(0xff)); result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::UInt8; }
else if (bitsPerPixel == 16) { result._sourceHeightRange = Float2(0.f, float(0xffff)); result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::UInt16; }
else if (bitsPerPixel == 32) { result._sourceHeightRange = Float2(0.f, float(0xffffffff)); result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::UInt32; }
else { result._warnings.push_back("Bad bits per pixel"); return result; }
break;
case SAMPLEFORMAT_INT:
result._sourceFormat = TerrainImportOp::SourceFormat::Quantized;
if (bitsPerPixel == 8) { result._sourceHeightRange = Float2(float( INT8_MIN), float( INT8_MAX)); result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::UInt8; }
else if (bitsPerPixel == 16) { result._sourceHeightRange = Float2(float(INT16_MIN), float(INT16_MAX)); result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::UInt16; }
else if (bitsPerPixel == 32) { result._sourceHeightRange = Float2(float(INT32_MIN), float(INT32_MAX)); result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::UInt32; }
else { result._warnings.push_back("Bad bits per pixel"); return result; }
break;
case SAMPLEFORMAT_IEEEFP:
result._sourceFormat = TerrainImportOp::SourceFormat::AbsoluteFloats;
if (bitsPerPixel != 16 && bitsPerPixel != 32)
{ result._warnings.push_back("Bad bits per pixel"); return result; }
result._importCoverageFormat = (unsigned)ImpliedTyping::TypeCat::Float; // (todo -- float16 support?)
break;
default:
result._warnings.push_back("Unsupported sample format");
return result;
}
result._sourceIsGood = true;
} else {
result._warnings.push_back("Could not open tiff file");
}
} else {
result._warnings.push_back("Unknown input file format");
}
result._importMins = UInt2(0, 0);
result._importMaxs = ClampImportDims(result._sourceDims, destNodeDims, destCellTreeDepth);
result._importHeightRange = result._sourceHeightRange;
return result;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename InputType>
static void SimpleConvert(float dest[], const InputType* input, size_t count, float offset, float scale)
{
for (unsigned c=0; c<count; ++c)
dest[c] = float(input[c]) * scale + offset;
}
template<typename InputType>
static void SimpleConvertGen(void* dest, const ImpliedTyping::TypeDesc& dstType, const InputType* input, size_t count, double offset, double scale)
{
// note -- the implied typing cast here is quite expensive! But it's
// reliable
auto dstSize = dstType.GetSize();
for (unsigned c=0; c<count; ++c) {
// good idea to use the increased precision of "doubles" here, particularly when
// loading from 32 bit integer formats
auto midway = float(double(input[c]) * scale + offset);
ImpliedTyping::Cast(
{ PtrAdd(dest, c*dstSize), PtrAdd(dest, c*dstSize+dstSize) }, dstType,
MakeOpaqueIteratorRange(midway), ImpliedTyping::TypeOf<decltype(midway)>());
}
}
static float Float16AsFloat32(unsigned short input)
{
return half_float::detail::half2float(input);
}
static void ConvertFloat16Gen(void* dest, const ImpliedTyping::TypeDesc& dstType, const uint16* input, size_t count, double offset, double scale)
{
// note -- the implied typing cast here is quite expensive! But it's
// reliable
auto dstSize = dstType.GetSize();
for (unsigned c=0; c<count; ++c) {
auto midway = float(double(Float16AsFloat32(input[c])) * scale + offset);
ImpliedTyping::Cast(
{ PtrAdd(dest, c*dstSize), PtrAdd(dest, c*dstSize+dstSize) }, dstType,
MakeOpaqueIteratorRange(midway), ImpliedTyping::TypeOf<decltype(midway)>());
}
}
void ExecuteTerrainImport(
const TerrainImportOp& op,
const ::Assets::ResChar outputDir[],
unsigned destNodeDims, unsigned destCellTreeDepth,
SceneEngine::TerrainCoverageId coverageId,
ImpliedTyping::TypeCat dstType,
ConsoleRig::IProgress* progress)
{
auto initStep = progress ? progress->BeginStep("Load source data", 1, false) : nullptr;
auto oldWarningHandler = TIFFSetWarningHandler(&TIFFWarningHandler);
auto oldErrorHandler = TIFFSetErrorHandler(&TIFFErrorHandler);
s_tiffWarningVector = nullptr;
auto autoClose2 = MakeAutoClose([oldWarningHandler, oldErrorHandler]()
{
TIFFSetWarningHandler(oldWarningHandler);
TIFFSetErrorHandler(oldErrorHandler);
s_tiffWarningVector = nullptr;
});
if (!op._sourceIsGood || ((op._importMaxs[0] <= op._importMins[0]) && (op._importMaxs[1] <= op._importMins[1]))) {
Throw(
::Exceptions::BasicLabel("Bad or missing input terrain config file (%s)", op._sourceFile.c_str()));
}
UInt2 importOffset = op._importMins;
UInt2 finalDims = ClampImportDims(op._importMaxs - op._importMins, destNodeDims, destCellTreeDepth);
OSServices::CreateDirectoryRecursive(outputDir);
auto dstSampleSize = ImpliedTyping::TypeDesc{dstType}.GetSize();
uint64 resultSize =
sizeof(TerrainUberHeader)
+ finalDims[0] * finalDims[1] * dstSampleSize
;
::Assets::ResChar outputUberFileName[MaxPath];
SceneEngine::TerrainConfig::GetUberSurfaceFilename(
outputUberFileName, dimof(outputUberFileName),
outputDir, coverageId);
auto outputUberFile = ::Assets::MainFileSystem::OpenMemoryMappedFile(outputUberFileName, resultSize, "w");
auto& hdr = *(TerrainUberHeader*)outputUberFile.GetData().begin();
hdr._magic = TerrainUberHeader::Magic;
hdr._width = finalDims[0];
hdr._height = finalDims[1];
hdr._typeCat = (unsigned)dstType;
hdr._typeArrayCount = 1;
hdr._dummy[0] = hdr._dummy[1] = hdr._dummy[2] = 0;
void* outputArray = PtrAdd(outputUberFile.GetData().begin(), sizeof(TerrainUberHeader));
auto ext = XlExtension(op._sourceFile.c_str());
if (ext && (!XlCompareStringI(ext, "hdr") || !XlCompareStringI(ext, "flt"))) {
if (dstType != ImpliedTyping::TypeCat::Float)
Throw(::Exceptions::BasicLabel("Attempting to load float format input into non-float destination (%s)", op._sourceFile.c_str()));
auto inputFileData = ::Assets::MainFileSystem::OpenMemoryMappedFile(op._sourceFile, 0, "r");
if (op._sourceFormat!=TerrainImportOp::SourceFormat::AbsoluteFloats)
Throw(::Exceptions::BasicLabel("Expecting absolute floats when loading from raw float array"));
if (initStep) {
initStep->Advance();
initStep.reset();
}
auto copyRows = std::min(finalDims[1], op._importMaxs[1]) - op._importMins[1];
const unsigned progressStep = 16;
auto copyStep = progress ? progress->BeginStep("Create uber surface data", copyRows / progressStep, true) : nullptr;
auto inputArray = (const float*)inputFileData.GetData().begin();
unsigned yoff = op._importMins[1];
unsigned y2=0;
for (; (y2+progressStep)<=copyRows; y2+=progressStep) {
for (unsigned y=0; y<progressStep; ++y) {
std::copy(
&inputArray[(y2+y+yoff) * op._sourceDims[0] + op._importMins[0]],
&inputArray[(y2+y+yoff) * op._sourceDims[0] + std::min(op._sourceDims[0], op._importMaxs[0])],
(float*)PtrAdd(outputArray, ((y2+y) * finalDims[0]) * dstSampleSize));
}
if (copyStep) {
if (copyStep->IsCancelled())
Throw(::Exceptions::BasicLabel("User cancelled"));
copyStep->Advance();
}
}
// remainder rows left over after dividing by progressStep
for (; y2<copyRows; ++y2) {
std::copy(
&inputArray[(y2+yoff) * op._sourceDims[0] + op._importMins[0]],
&inputArray[(y2+yoff) * op._sourceDims[0] + std::min(op._sourceDims[0], op._importMaxs[0])],
(float*)PtrAdd(outputArray, (y2 * finalDims[0]) * dstSampleSize));
}
} else if (ext && (!XlCompareStringI(ext, "tif") || !XlCompareStringI(ext, "tiff"))) {
// attempt to read geotiff file
auto* tif = TIFFOpen(op._sourceFile.c_str(), "r");
if (!tif)
Throw(::Exceptions::BasicLabel("Couldn't open input file (%s)", op._sourceFile.c_str()));
auto autoClose = MakeAutoClose([tif]() { TIFFClose(tif); });
auto stripCount = TIFFNumberOfStrips(tif);
auto copyStep =
progress
? progress->BeginStep("Create uber surface data", stripCount, true)
: nullptr;
uint32 rowsperstrip = 1;
TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
uint32 bitsPerPixel = 32;
uint32 sampleFormat = SAMPLEFORMAT_IEEEFP;
TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerPixel);
TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sampleFormat);
// We only support loading a few input formats.
// TIFF supports a wide variety of formats. If we get something
// unexpected, just throw;
if (sampleFormat != SAMPLEFORMAT_UINT && sampleFormat != SAMPLEFORMAT_INT && sampleFormat != SAMPLEFORMAT_IEEEFP)
Throw(::Exceptions::BasicLabel("Unexpected sample format in input file (%s). Only supporting integer or floating point inputs", op._sourceFile.c_str()));
if (bitsPerPixel != 8 && bitsPerPixel != 16 && bitsPerPixel != 32)
Throw(::Exceptions::BasicLabel("Unexpected bits per sample in input file (%s). Only supporting 8, 16 or 32 bit formats. Try floating a 32 bit float format.", op._sourceFile.c_str()));
auto stripSize = TIFFStripSize(tif);
if (!stripSize)
Throw(::Exceptions::BasicLabel("Could not get strip byte codes from tiff file (%s). Input file may be corrupted.", op._sourceFile.c_str()));
auto stripBuffer = std::make_unique<char[]>(stripSize);
XlSetMemory(stripBuffer.get(), 0, stripSize);
typedef void ConversionFn(void*, const ImpliedTyping::TypeDesc&, const void*, size_t, double, double);
ConversionFn* convFn;
switch (sampleFormat) {
case SAMPLEFORMAT_UINT:
if (bitsPerPixel == 8) convFn = (ConversionFn*)&SimpleConvertGen<uint8>;
else if (bitsPerPixel == 16) convFn = (ConversionFn*)&SimpleConvertGen<uint16>;
else if (bitsPerPixel == 32) convFn = (ConversionFn*)&SimpleConvertGen<uint32>;
else Throw(::Exceptions::BasicLabel("Unknown input format.", op._sourceFile.c_str()));
break;
case SAMPLEFORMAT_INT:
if (bitsPerPixel == 8) convFn = (ConversionFn*)&SimpleConvertGen<int8>;
else if (bitsPerPixel == 16) convFn = (ConversionFn*)&SimpleConvertGen<int16>;
else if (bitsPerPixel == 32) convFn = (ConversionFn*)&SimpleConvertGen<int32>;
else Throw(::Exceptions::BasicLabel("Unknown input format.", op._sourceFile.c_str()));
break;
case SAMPLEFORMAT_IEEEFP:
if (bitsPerPixel == 16) convFn = (ConversionFn*)&ConvertFloat16Gen;
else if (bitsPerPixel == 32) convFn = (ConversionFn*)&SimpleConvertGen<float>;
else Throw(::Exceptions::BasicLabel("8 bit floats not supported in input file (%s). Use 16 or 32 bit floats instead.", op._sourceFile.c_str()));
break;
default:
Throw(::Exceptions::BasicLabel("Unknown input format.", op._sourceFile.c_str()));
}
double valueScale = (double(op._importHeightRange[1]) - double(op._importHeightRange[0])) / (double(op._sourceHeightRange[1]) - double(op._sourceHeightRange[0]));
double valueOffset = double(op._importHeightRange[0]) - double(op._sourceHeightRange[0]) * valueScale;
for (tstrip_t strip = 0; strip < stripCount; strip++) {
auto readResult = TIFFReadEncodedStrip(tif, strip, stripBuffer.get(), stripSize);
if (readResult != stripSize) {
// Sometimes the very last strip is truncated. This occurs if the height
// is not an even multiple of the strip size
// In this case, we just blank out the remaining part
if (readResult > 0 && readResult < stripSize && (strip+1 == stripCount)) {
std::memset(PtrAdd(stripBuffer.get(), readResult), 0x0, stripSize - readResult);
} else {
Throw(::Exceptions::BasicLabel(
"Error while reading from tiff file. File may be truncated or otherwise corrupted.",
op._sourceFile.c_str()));
}
}
for (unsigned r=0; r<rowsperstrip; ++r) {
auto y = strip * rowsperstrip + r;
if (y >= op._importMins[1] && y < op._importMaxs[1]) {
(*convFn)(
PtrAdd(outputArray, ((y - op._importMins[1]) * finalDims[0]) * dstSampleSize),
ImpliedTyping::TypeDesc{dstType},
PtrAdd(stripBuffer.get(), op._importMins[0]*bitsPerPixel/8),
std::min(op._sourceDims[0], op._importMaxs[0]) - op._importMins[0],
valueOffset, valueScale);
}
}
if (copyStep) {
if (copyStep->IsCancelled())
Throw(::Exceptions::BasicLabel("User cancelled"));
copyStep->Advance();
}
}
// TIFFClose called by AutoClose
}
// fill in the extra space caused by rounding up
float blank = 0.f;
if (finalDims[0] > op._sourceDims[0]) {
for (unsigned y=0; y<(op._importMaxs[1] - op._importMins[1]); ++y) {
for (unsigned x=op._sourceDims[0]; x<finalDims[0]; ++x)
ImpliedTyping::Cast(
{ PtrAdd(outputArray, (y * finalDims[0] + x)*dstSampleSize), PtrAdd(outputArray, (y * finalDims[0] + x)*dstSampleSize+dstSampleSize) },
ImpliedTyping::TypeDesc{dstType},
MakeOpaqueIteratorRange(blank), ImpliedTyping::TypeOf<decltype(blank)>());
}
}
for (unsigned y=op._importMaxs[1] - op._importMins[1]; y < finalDims[1]; ++y) {
for (unsigned x=0; x<finalDims[0]; ++x)
ImpliedTyping::Cast(
{ PtrAdd(outputArray, (y * finalDims[0] + x)*dstSampleSize), PtrAdd(outputArray, (y * finalDims[0] + x)*dstSampleSize+dstSampleSize) },
ImpliedTyping::TypeDesc{dstType},
MakeOpaqueIteratorRange(blank), ImpliedTyping::TypeOf<decltype(blank)>());
}
}
void ExecuteTerrainExport(
const ::Assets::ResChar dstFile[],
const SceneEngine::TerrainConfig& srcCfg,
const ::Assets::ResChar srcDir[],
SceneEngine::TerrainCoverageId coverageId,
ConsoleRig::IProgress* progress)
{
// Export a uber surface file to tiff format.
::Assets::ResChar dirName[MaxPath];
XlDirname(dirName, dimof(dirName), dstFile);
OSServices::CreateDirectoryRecursive(dirName);
::Assets::ResChar srcFN[MaxPath];
srcCfg.GetUberSurfaceFilename(srcFN, dimof(srcFN), srcDir, coverageId);
if (!DoesFileExist(srcFN))
Throw(::Exceptions::BasicLabel("Could not find input file (%s)", srcFN));
TerrainUberSurfaceGeneric uberSurface(srcFN);
auto step =
progress
? progress->BeginStep("Create uber surface data", uberSurface.GetHeight(), true)
: nullptr;
auto* tif = TIFFOpen(dstFile, "w");
if (!tif)
Throw(::Exceptions::BasicLabel("Error openning output file (%s)", dstFile));
auto autoClose = MakeAutoClose([tif]() { TIFFClose(tif); });
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, uberSurface.GetWidth()); // set the width of the image
TIFFSetField(tif, TIFFTAG_IMAGELENGTH, uberSurface.GetHeight()); // set the height of the image
TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); // set the origin of the image.
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
auto fmt = uberSurface.Format();
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, fmt._arrayCount);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, fmt.GetSize() * 8 / fmt._arrayCount);
using TC = ImpliedTyping::TypeCat;
switch (fmt._type) {
case TC::Bool:
case TC::Int8:
case TC::Int16:
case TC::Int32:
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case TC::UInt8:
case TC::UInt16:
case TC::UInt32:
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case TC::Float:
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
default:
Throw(::Exceptions::BasicLabel("Unknown uber surface format, can't export"));
}
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
// I think this will only work correctly with a single sample per pixel
for (unsigned row = 0; row < uberSurface.GetHeight(); row++) {
TIFFWriteScanline(tif, uberSurface.GetData(UInt2(0, row)), row, 0);
if (step) {
if (step->IsCancelled())
break;
step->Advance();
}
}
}
void GenerateBlankUberSurface(
const ::Assets::ResChar outputDir[],
unsigned cellCountX, unsigned cellCountY,
unsigned destNodeDims, unsigned destCellTreeDepth,
ConsoleRig::IProgress* progress)
{
OSServices::CreateDirectoryRecursive(outputDir);
UInt2 finalDims(
cellCountX * destNodeDims * (1<<(destCellTreeDepth-1)),
cellCountY * destNodeDims * (1<<(destCellTreeDepth-1)));
uint64 resultSize =
sizeof(TerrainUberHeader)
+ finalDims[0] * finalDims[1] * sizeof(float)
;
::Assets::ResChar outputUberFileName[MaxPath];
SceneEngine::TerrainConfig::GetUberSurfaceFilename(
outputUberFileName, dimof(outputUberFileName),
outputDir, SceneEngine::CoverageId_Heights);
auto outputUberFile = ::Assets::MainFileSystem::OpenMemoryMappedFile(outputUberFileName, resultSize, "w");
auto& hdr = *(TerrainUberHeader*)outputUberFile.GetData().begin();
hdr._magic = TerrainUberHeader::Magic;
hdr._width = finalDims[0];
hdr._height = finalDims[1];
hdr._typeCat = (unsigned)ImpliedTyping::TypeCat::Float;
hdr._typeArrayCount = 1;
hdr._dummy[0] = hdr._dummy[1] = hdr._dummy[2] = 0;
float* outputArray = (float*)PtrAdd(outputUberFile.GetData().begin(), sizeof(TerrainUberHeader));
std::fill(
outputArray,
&outputArray[finalDims[0] * finalDims[1]],
0.f);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
static UInt2 GetUberSurfaceDimensions(const ::Assets::ResChar fn[])
{
auto file = ::Assets::MainFileSystem::OpenBasicFile(fn, "rb", OSServices::FileShareMode::Read|OSServices::FileShareMode::Write);
TerrainUberHeader hdr;
if ((file.Read(&hdr, sizeof(hdr), 1) != 1) || (hdr._magic != TerrainUberHeader::Magic))
Throw(::Exceptions::BasicLabel("Error while reading from: (%s)", fn));
return UInt2(hdr._width, hdr._height);
}
UInt2 GetCellCountFromUberSurface(
const ::Assets::ResChar inputUberSurfaceDirectory[],
UInt2 destNodeDims, unsigned destCellTreeDepth)
{
using namespace SceneEngine;
::Assets::ResChar uberSurfaceHeights[MaxPath];
TerrainConfig::GetUberSurfaceFilename(
uberSurfaceHeights, dimof(uberSurfaceHeights),
inputUberSurfaceDirectory, SceneEngine::CoverageId_Heights);
auto eleCount = GetUberSurfaceDimensions(uberSurfaceHeights);
auto cellDimsInEles = (1 << (destCellTreeDepth - 1)) * destNodeDims;
if ((eleCount[0] % cellDimsInEles[0])!=0 || (eleCount[1] % cellDimsInEles[1])!=0)
Throw(::Exceptions::BasicLabel("Uber surface size is not divisable by cell size (uber surface size:(%ix%i), cell size:(%i))",
eleCount[0], eleCount[1], cellDimsInEles[0]));
return UInt2(eleCount[0] / cellDimsInEles[0], eleCount[1] / cellDimsInEles[1]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
static void WriteNode(
float destination[], TerrainCell::Node& node,
const char sourceFileName[], const char secondaryCacheName[],
size_t stride, signed downsample)
{
// load the raw data either from the source file, or the cache file
std::unique_ptr<uint16[]> rawData;
const unsigned expectedCount = node._widthInElements*node._widthInElements;
// todo -- check for incomplete nodes (ie, with holes)
if (node._heightMapFileSize) {
auto count = node._heightMapFileSize/sizeof(uint16);
if (count == expectedCount) {
OSServices::BasicFile file(sourceFileName, "rb");
rawData = std::make_unique<uint16[]>(count);
file.Seek(node._heightMapFileOffset, SEEK_SET);
file.Read(rawData.get(), sizeof(uint16), count);
}
} else if (node._secondaryCacheSize) {
auto count = node._secondaryCacheSize/sizeof(uint16);
if (count == expectedCount) {
OSServices::BasicFile file(secondaryCacheName, "rb");
rawData = std::make_unique<uint16[]>(count);
file.Seek(node._secondaryCacheOffset, SEEK_SET);
file.Read(rawData.get(), sizeof(uint16), count);
}
}
const unsigned dimsNoOverlay = node._widthInElements - node.GetOverlapWidth();
for (unsigned y=0; y<dimsNoOverlay; ++y)
for (unsigned x=0; x<dimsNoOverlay; ++x) {
assert(((y*node._widthInElements)+x) < expectedCount);
auto inputValue = rawData ? rawData[(y*node._widthInElements)+x] : uint16(0);
float cellSpaceHeight = node._localToCell(2,2) * float(inputValue) + node._localToCell(2,3);
assert(downsample==0);
*PtrAdd(destination, y*stride + x*sizeof(float)) = cellSpaceHeight;
}
}
static void WriteBlankNode(float destination[], size_t stride, signed downsample, const UInt2 elementDims)
{
assert(downsample==0);
for (unsigned y=0; y<elementDims[1]; ++y)
for (unsigned x=0; x<elementDims[0]; ++x) {
*PtrAdd(destination, y*stride + x*sizeof(float)) = 0.f;
}
}
static bool BuildUberSurfaceFile(
const char filename[], const TerrainConfig& config,
ITerrainFormat* ioFormat,
unsigned xStart, unsigned yStart, unsigned xDims, unsigned yDims)
{
//
// Read in the existing terrain data, and generate a uber surface file
// -- this uber surface file should contain the height values for the
// entire "world", at the highest resolution
// The "uber" surface file is initialized from the source crytek terrain files,
// but becomes our new authoritative source for terrain data.
//
const unsigned cellCount = xDims * yDims;
const auto cellDimsInNodes = config.CellDimensionsInNodes();
const auto nodeDimsInElements = config.NodeDimensionsInElements();
const unsigned nodesPerCell = cellDimsInNodes[0] * cellDimsInNodes[1];
const unsigned heightsPerNode = nodeDimsInElements[0] * nodeDimsInElements[1];
size_t stride = nodeDimsInElements[0] * cellDimsInNodes[0] * xDims * sizeof(float);
uint64 resultSize =
sizeof(TerrainUberHeader)
+ cellCount * nodesPerCell * heightsPerNode * sizeof(float)
;
MemoryMappedFile mappedFile(filename, resultSize, MemoryMappedFile::Access::Write, BasicFile::ShareMode::Read);
if (!mappedFile.IsValid())
return false;
auto& hdr = *(TerrainUberHeader*)mappedFile.GetData();
hdr._magic = TerrainUberHeader::Magic;
hdr._width = nodeDimsInElements[0] * cellDimsInNodes[0] * xDims;
hdr._height = nodeDimsInElements[1] * cellDimsInNodes[1] * yDims;
hdr._dummy = 0;
void* heightArrayStart = PtrAdd(mappedFile.GetData(), sizeof(TerrainUberHeader));
TRY
{
// fill in the "uber" surface file with all of the terrain information
for (unsigned cy=0; cy<yDims; ++cy)
for (unsigned cx=0; cx<xDims; ++cx) {
char buffer[MaxPath];
config.GetCellFilename(buffer, dimof(buffer), UInt2(cx, cy),
CoverageId_Heights);
auto& cell = ioFormat->LoadHeights(buffer);
// the last "field" in the input data should be the resolution that we want
// however, if we don't have enough fields, we may have to upsample from
// the lower resolution ones
if (cell._nodeFields.size() >= 5) {
auto& field = cell._nodeFields[4];
assert(field._widthInNodes == cellDimsInNodes[0]);
assert(field._heightInNodes == cellDimsInNodes[1]);
for (auto n=field._nodeBegin; n!=field._nodeEnd; ++n) {
auto& node = *cell._nodes[n];
unsigned nx = (unsigned)std::floor(node._localToCell(0, 3) / 64.f + 0.5f);
unsigned ny = (unsigned)std::floor(node._localToCell(1, 3) / 64.f + 0.5f);
auto* nodeDataStart = (float*)PtrAdd(
heightArrayStart,
(cy * cellDimsInNodes[1] + ny) * nodeDimsInElements[1] * stride
+ (cx * cellDimsInNodes[0] + nx) * nodeDimsInElements[0] * sizeof(float));
WriteNode(
nodeDataStart, node,
cell.SourceFile().c_str(), cell.SecondaryCacheFile().c_str(),
stride, 0);
}
} else {
for (unsigned y=0; y<cellDimsInNodes[1]; ++y)
for (unsigned x=0; x<cellDimsInNodes[0]; ++x) {
auto* nodeDataStart = (float*)PtrAdd(
heightArrayStart,
(cy * cellDimsInNodes[1] + y) * nodeDimsInElements[1] * stride
+ (cx * cellDimsInNodes[0] + x) * nodeDimsInElements[0] * sizeof(float));
WriteBlankNode(nodeDataStart, stride, 0, nodeDimsInElements);
}
}
}
}
CATCH(...) { return false; }
CATCH_END
return true;
}
#endif
}
| 46.269598
| 200
| 0.57552
|
djewsbury
|
40e0276213cc148716c41399d21f730851ed2e61
| 1,450
|
cpp
|
C++
|
platform/RemotingNG/TCP/src/TransportFactory.cpp
|
gboyraz/macchina.io
|
3e26fea95e87512459693831242b297f0780cc21
|
[
"Apache-2.0"
] | 2
|
2020-11-23T23:37:00.000Z
|
2020-12-22T04:02:41.000Z
|
platform/RemotingNG/TCP/src/TransportFactory.cpp
|
bas524/cmake.macchina.io
|
22a21d78f8075fd145b788b41a23603591e91c9f
|
[
"Apache-2.0"
] | null | null | null |
platform/RemotingNG/TCP/src/TransportFactory.cpp
|
bas524/cmake.macchina.io
|
22a21d78f8075fd145b788b41a23603591e91c9f
|
[
"Apache-2.0"
] | 1
|
2020-11-23T23:37:09.000Z
|
2020-11-23T23:37:09.000Z
|
//
// TransportFactory.cpp
//
// Library: RemotingNG/TCP
// Package: TCP
// Module: TransportFactory
//
// Copyright (c) 2006-2012, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/RemotingNG/TCP/TransportFactory.h"
#include "Poco/RemotingNG/TCP/Transport.h"
#include "Poco/RemotingNG/TCP/ConnectionManager.h"
#include "Poco/RemotingNG/TransportFactoryManager.h"
namespace Poco {
namespace RemotingNG {
namespace TCP {
TransportFactory::TransportFactory():
_connectionManager(ConnectionManager::defaultManager())
{
}
TransportFactory::TransportFactory(ConnectionManager& connectionManager):
_connectionManager(connectionManager)
{
}
TransportFactory::~TransportFactory()
{
}
Poco::RemotingNG::Transport* TransportFactory::createTransport()
{
return new Transport(_connectionManager);
}
void TransportFactory::registerFactory()
{
Poco::RemotingNG::TransportFactoryManager::instance().registerFactory(Transport::PROTOCOL, new TransportFactory);
}
void TransportFactory::registerFactory(ConnectionManager& connectionManager)
{
Poco::RemotingNG::TransportFactoryManager::instance().registerFactory(Transport::PROTOCOL, new TransportFactory(connectionManager));
}
void TransportFactory::unregisterFactory()
{
Poco::RemotingNG::TransportFactoryManager::instance().unregisterFactory(Transport::PROTOCOL);
}
} } } // namespace Poco::RemotingNG::TCP
| 21.323529
| 133
| 0.786897
|
gboyraz
|
40e0fa0e50680761a1036ba9af473e4a56f28c51
| 462
|
cpp
|
C++
|
Testing/testVigenereCipher.cpp
|
MPAGS-CPP-2019/mpags-day-5-kwalkingshaw
|
25d7838114ef251e3561ba6e83ae859ba655d94d
|
[
"MIT"
] | null | null | null |
Testing/testVigenereCipher.cpp
|
MPAGS-CPP-2019/mpags-day-5-kwalkingshaw
|
25d7838114ef251e3561ba6e83ae859ba655d94d
|
[
"MIT"
] | null | null | null |
Testing/testVigenereCipher.cpp
|
MPAGS-CPP-2019/mpags-day-5-kwalkingshaw
|
25d7838114ef251e3561ba6e83ae859ba655d94d
|
[
"MIT"
] | null | null | null |
//! Unit Tests for MPAGSCipher VigenereCipher Class
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "VigenereCipher.hpp"
TEST_CASE("Vigenere Cipher encryption", "[vigenere]") {
VigenereCipher cc{"KEY"};
REQUIRE( cc.applyCipher("HELLOWORLD", CipherMode::Encrypt) == "RIJVSUYVJN");
}
TEST_CASE("Vigenere Cipher decryption", "[vigenere]") {
VigenereCipher cc{"KEY"};
REQUIRE( cc.applyCipher("RIJVSUYVJN", CipherMode::Decrypt) == "HELLOWORLD");
}
| 28.875
| 78
| 0.731602
|
MPAGS-CPP-2019
|
40e184d236f9508a0a2a5bc94d4ea22fd213efa9
| 5,186
|
cpp
|
C++
|
tdutils/td/utils/Gzip.cpp
|
sintyaaaaa/td
|
0e930c15d3cd65dc5cc3fa6e8492684038129510
|
[
"BSL-1.0"
] | 1
|
2019-10-12T18:08:04.000Z
|
2019-10-12T18:08:04.000Z
|
tdutils/td/utils/Gzip.cpp
|
sintyaaaaa/td
|
0e930c15d3cd65dc5cc3fa6e8492684038129510
|
[
"BSL-1.0"
] | null | null | null |
tdutils/td/utils/Gzip.cpp
|
sintyaaaaa/td
|
0e930c15d3cd65dc5cc3fa6e8492684038129510
|
[
"BSL-1.0"
] | 1
|
2020-08-14T12:43:30.000Z
|
2020-08-14T12:43:30.000Z
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2019
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/utils/Gzip.h"
char disable_linker_warning_about_empty_file_gzip_cpp TD_UNUSED;
#if TD_HAVE_ZLIB
#include "td/utils/logging.h"
#include <cstring>
#include <limits>
#include <utility>
#include <zlib.h>
namespace td {
class Gzip::Impl {
public:
z_stream stream_;
// z_stream is not copyable nor movable
Impl() = default;
Impl(const Impl &other) = delete;
Impl &operator=(const Impl &other) = delete;
Impl(Impl &&other) = delete;
Impl &operator=(Impl &&other) = delete;
~Impl() = default;
};
Status Gzip::init_encode() {
CHECK(mode_ == Empty);
init_common();
mode_ = Encode;
int ret = deflateInit2(&impl_->stream_, 6, Z_DEFLATED, 15, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
if (ret != Z_OK) {
return Status::Error(PSLICE() << "zlib deflate init failed: " << ret);
}
return Status::OK();
}
Status Gzip::init_decode() {
CHECK(mode_ == Empty);
init_common();
mode_ = Decode;
int ret = inflateInit2(&impl_->stream_, MAX_WBITS + 32);
if (ret != Z_OK) {
return Status::Error(PSLICE() << "zlib inflate init failed: " << ret);
}
return Status::OK();
}
void Gzip::set_input(Slice input) {
CHECK(input_size_ == 0);
CHECK(!close_input_flag_);
CHECK(input.size() <= std::numeric_limits<uInt>::max());
CHECK(impl_->stream_.avail_in == 0);
input_size_ = input.size();
impl_->stream_.avail_in = static_cast<uInt>(input.size());
impl_->stream_.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(input.data()));
}
void Gzip::set_output(MutableSlice output) {
CHECK(output_size_ == 0);
CHECK(output.size() <= std::numeric_limits<uInt>::max());
CHECK(impl_->stream_.avail_out == 0);
output_size_ = output.size();
impl_->stream_.avail_out = static_cast<uInt>(output.size());
impl_->stream_.next_out = reinterpret_cast<Bytef *>(output.data());
}
Result<Gzip::State> Gzip::run() {
while (true) {
int ret;
if (mode_ == Decode) {
ret = inflate(&impl_->stream_, Z_NO_FLUSH);
} else {
ret = deflate(&impl_->stream_, close_input_flag_ ? Z_FINISH : Z_NO_FLUSH);
}
if (ret == Z_OK) {
return Running;
}
if (ret == Z_STREAM_END) {
// TODO(now): fail if input is not empty;
clear();
return Done;
}
clear();
return Status::Error(PSLICE() << "zlib error " << ret);
}
}
size_t Gzip::left_input() const {
return impl_->stream_.avail_in;
}
size_t Gzip::left_output() const {
return impl_->stream_.avail_out;
}
void Gzip::init_common() {
std::memset(&impl_->stream_, 0, sizeof(impl_->stream_));
impl_->stream_.zalloc = Z_NULL;
impl_->stream_.zfree = Z_NULL;
impl_->stream_.opaque = Z_NULL;
impl_->stream_.avail_in = 0;
impl_->stream_.next_in = nullptr;
impl_->stream_.avail_out = 0;
impl_->stream_.next_out = nullptr;
input_size_ = 0;
output_size_ = 0;
close_input_flag_ = false;
}
void Gzip::clear() {
if (mode_ == Decode) {
inflateEnd(&impl_->stream_);
} else if (mode_ == Encode) {
deflateEnd(&impl_->stream_);
}
mode_ = Empty;
}
Gzip::Gzip() : impl_(make_unique<Impl>()) {
}
Gzip::Gzip(Gzip &&other) : Gzip() {
swap(other);
}
Gzip &Gzip::operator=(Gzip &&other) {
CHECK(this != &other);
clear();
swap(other);
return *this;
}
void Gzip::swap(Gzip &other) {
using std::swap;
swap(impl_, other.impl_);
swap(input_size_, other.input_size_);
swap(output_size_, other.output_size_);
swap(close_input_flag_, other.close_input_flag_);
swap(mode_, other.mode_);
}
Gzip::~Gzip() {
clear();
}
BufferSlice gzdecode(Slice s) {
Gzip gzip;
gzip.init_decode().ensure();
ChainBufferWriter message;
gzip.set_input(s);
gzip.close_input();
double k = 2;
gzip.set_output(message.prepare_append(static_cast<size_t>(static_cast<double>(s.size()) * k)));
while (true) {
auto r_state = gzip.run();
if (r_state.is_error()) {
return BufferSlice();
}
auto state = r_state.ok();
if (state == Gzip::Done) {
message.confirm_append(gzip.flush_output());
break;
}
if (gzip.need_input()) {
return BufferSlice();
}
if (gzip.need_output()) {
message.confirm_append(gzip.flush_output());
k *= 1.5;
gzip.set_output(message.prepare_append(static_cast<size_t>(static_cast<double>(gzip.left_input()) * k)));
}
}
return message.extract_reader().move_as_buffer_slice();
}
BufferSlice gzencode(Slice s, double k) {
Gzip gzip;
gzip.init_encode().ensure();
gzip.set_input(s);
gzip.close_input();
size_t max_size = static_cast<size_t>(static_cast<double>(s.size()) * k);
BufferWriter message{max_size};
gzip.set_output(message.prepare_append());
auto r_state = gzip.run();
if (r_state.is_error()) {
return BufferSlice();
}
auto state = r_state.ok();
if (state != Gzip::Done) {
return BufferSlice();
}
message.confirm_append(gzip.flush_output());
return message.as_buffer_slice();
}
} // namespace td
#endif
| 24.813397
| 111
| 0.658889
|
sintyaaaaa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.