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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
efa1c3d012db6b8ff25ed550db2088ff438ff81a | 33,110 | cpp | C++ | shared/src/wdg/ds_slider_painter_bevelled.cpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | shared/src/wdg/ds_slider_painter_bevelled.cpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | shared/src/wdg/ds_slider_painter_bevelled.cpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | /// QasTools: Desktop toolset for the Linux sound system ALSA.
/// \copyright See COPYING file.
#include "ds_slider_painter_bevelled.hpp"
#include "dpe/image_set.hpp"
#include "dpe/image_set_meta.hpp"
#include "dpe/paint_job.hpp"
#include "wdg/color_methods.hpp"
#include "wdg/ds_slider_meta_bg.hpp"
#include "wdg/ds_widget_style_db.hpp"
#include "wdg/ds_widget_types.hpp"
#include "wdg/uint_mapper.hpp"
#include <QImage>
#include <QLinearGradient>
#include <QPainter>
#include <QPainterPath>
#include <QRadialGradient>
#include <QScopedPointer>
#include <cmath>
#include <iostream>
namespace Wdg
{
namespace Painter
{
struct DS_Slider_Painter_Bevelled::PData
{
inline QSize &
size ()
{
return meta->size;
}
inline int
width ()
{
return meta->size.width ();
}
inline int
height ()
{
return meta->size.height ();
}
::dpe::Image_Set_Meta * meta;
QPalette pal;
QPainter qpnt;
int ew; // Edge width
int bw; // Border width x,y
int bevel;
int tick_width[ 3 ];
int tick_min_dist;
QRectF rectf;
bool has_focus;
bool has_weak_focus;
bool mouse_over;
bool is_down;
::dpe::Image * img;
::Wdg::DS_Slider_Meta_Bg * meta_bg;
};
DS_Slider_Painter_Bevelled::DS_Slider_Painter_Bevelled ()
: ::Wdg::Painter::DS_Widget_Painter ( ::Wdg::DS_SLIDER )
{
}
int
DS_Slider_Painter_Bevelled::paint_image ( ::dpe::Paint_Job * pjob_n )
{
int res ( 0 );
// Init paint data
PData pd;
pd.meta = pjob_n->meta;
pd.img = &pjob_n->img_set->image ( pjob_n->img_idx );
res = create_image_data ( pd.img, pd.meta );
if ( res == 0 ) {
// Init general painting setup
if ( wdg_style_db () != 0 ) {
pd.pal = wdg_style_db ()->palettes[ pd.meta->style_id ];
pd.pal.setCurrentColorGroup (
wdg_style_db ()->color_group ( pd.meta->style_sub_id ) );
}
pd.bw = pd.meta->size.width () / 24;
if ( pd.bw < 2 ) {
pd.bw = 2;
}
pd.ew = ( pd.bw / 4 );
if ( pd.ew < 1 ) {
pd.ew = 1;
}
pd.bevel = pd.bw;
pd.rectf = QRectF ( 0.0, 0.0, pd.width (), pd.height () );
// Init painter
pd.qpnt.begin ( &pd.img->qimage () );
pd.qpnt.setRenderHints ( QPainter::Antialiasing |
QPainter::SmoothPixmapTransform );
// Paint type
switch ( pd.meta->type_id ) {
case 0:
res = paint_bg ( pjob_n, pd );
break;
case 1:
res = paint_marker ( pjob_n, pd );
break;
case 2:
res = paint_frame ( pjob_n, pd );
break;
case 3:
res = paint_handle ( pjob_n, pd );
break;
}
}
return res;
}
// Background painting
int
DS_Slider_Painter_Bevelled::paint_bg ( ::dpe::Paint_Job * pjob_n, PData & pd )
{
//::std::cout << "DS_Slider_Painter_Bevelled::paint_bg " << "\n";
pd.meta_bg = dynamic_cast<::Wdg::DS_Slider_Meta_Bg * > ( pjob_n->meta );
if ( pd.meta_bg == 0 ) {
return -1;
}
// Calculate tick sizes
{
int in_width ( pd.meta->size.width () - 2 * pd.bw );
pd.tick_width[ 0 ] = in_width * 1 / 2;
pd.tick_width[ 1 ] = in_width * 1 / 4;
pd.tick_width[ 2 ] = in_width * 1 / 16;
pd.tick_width[ 0 ] = ::std::max ( pd.tick_width[ 0 ], 6 );
pd.tick_width[ 1 ] = ::std::max ( pd.tick_width[ 1 ], 4 );
pd.tick_width[ 2 ] = ::std::max ( pd.tick_width[ 2 ], 2 );
if ( ( pd.meta->size.width () % 2 ) == 0 ) {
for ( int ii = 0; ii < 3; ++ii ) {
if ( ( pd.tick_width[ ii ] % 2 ) != 0 ) {
++( pd.tick_width[ ii ] );
}
}
} else {
for ( int ii = 0; ii < 3; ++ii ) {
if ( ( pd.tick_width[ ii ] % 2 ) == 0 ) {
++( pd.tick_width[ ii ] );
}
}
}
pd.tick_min_dist = 8;
}
// State flags
{
pd.is_down = ( pjob_n->img_idx == 1 );
}
// Painting
{
paint_bg_area ( pd );
paint_bg_frame ( pd );
paint_bg_area_deco ( pd );
paint_bg_ticks ( pd );
}
return 0;
}
void
DS_Slider_Painter_Bevelled::paint_bg_area ( PData & pd )
{
QColor col_li ( pd.pal.color ( QPalette::Button ) );
QColor col_mid ( pd.pal.color ( QPalette::Button ) );
QColor col_dk ( pd.pal.color ( QPalette::Mid ) );
col_li.setAlpha ( 55 );
col_dk.setAlpha ( 190 );
const double inner_width ( pd.width () - 2 * pd.bw );
const double x_start = pd.bw;
const double x_end = pd.width () - pd.bw;
const double x_mid = x_start + inner_width / 3.0;
QPainterPath area_path;
papp_bevel_area ( area_path, pd.rectf, pd.bevel, pd.bw / 2.0 );
// Base color
{
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_mid );
}
pd.qpnt.drawPath ( area_path );
// Fake 3D gradient
{
QLinearGradient lgrad ( QPointF ( x_start, 0.0 ), QPointF ( x_end, 0.0 ) );
lgrad.setColorAt ( 0.0, col_li );
lgrad.setColorAt ( x_mid / ( x_end - x_start ), col_mid );
lgrad.setColorAt ( 1.0, col_dk );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( lgrad );
}
pd.qpnt.drawPath ( area_path );
// Sound color overlay
{
QColor c0 ( pd.pal.color ( QPalette::Window ) );
QColor c1 ( c0 );
c0.setAlpha ( 30 );
c1.setAlpha ( 0 );
QLinearGradient lgrad ( QPointF ( x_start, 0.0 ),
QPointF ( x_start + inner_width / 7.0, 0.0 ) );
lgrad.setColorAt ( 0.0, c0 );
lgrad.setColorAt ( 1.0, c1 );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( lgrad );
}
pd.qpnt.drawPath ( area_path );
}
void
DS_Slider_Painter_Bevelled::paint_bg_frame ( PData & pd )
{
QColor fcol;
{
QColor col_btn ( pd.pal.color ( QPalette::Button ) );
QColor col_mid ( pd.pal.color ( QPalette::Mid ) );
if ( col_mid == col_btn ) {
col_mid = pd.pal.color ( QPalette::WindowText );
fcol = col_mix ( col_btn, col_mid, 1, 1 );
} else {
fcol = col_mix ( col_btn, col_mid, 1, 2 );
}
// fcol = col_mid;
}
paint_bevel_raised_frame ( pd, pd.rectf, pd.bevel, pd.bw, pd.ew, fcol );
}
void
DS_Slider_Painter_Bevelled::paint_bg_area_deco ( PData & pd )
{
QPainterPath ppath;
const int range_max_idx ( pd.meta_bg->ticks_range_max_idx );
int y_min;
int y_bottom;
int y_top;
bool has_minimum ( pd.meta_bg->bg_show_image );
bool has_zero_split ( false );
y_bottom = pd.height () - 1;
y_bottom -= pd.meta_bg->ticks_range_start;
y_top = y_bottom - range_max_idx;
y_min = y_bottom;
if ( has_minimum ) {
Wdg::UInt_Mapper_Auto mapper ( range_max_idx, pd.meta_bg->ticks_max_idx );
y_min -= mapper.v2_to_v1 ( pd.meta_bg->bg_tick_min_idx );
}
has_zero_split = ( ( y_min > y_top ) && ( y_min < y_bottom ) );
const double w_tick ( ( pd.tick_width[ 0 ] + pd.tick_width[ 1 ] ) / 2.0 );
const double w_out ( w_tick * 2.0 / 3.0 );
const double w_neck ( 1 );
double x_out_l ( ( pd.width () - w_tick ) / 2.0 );
double x_neck_l ( x_out_l );
double x_out_r;
double x_neck_r;
x_neck_l = std::floor ( x_neck_l );
x_neck_r = x_neck_l + w_neck;
x_out_l = std::floor ( x_out_l );
x_out_r = x_out_l + w_out;
if ( has_minimum ) {
if ( has_zero_split ) {
double x_out_rt ( x_out_r );
double x_out_rb ( x_out_r );
const int dt ( y_min - y_top );
const int db ( y_bottom - y_min );
if ( dt > db ) {
int ww = ( db * w_out ) / dt;
x_out_rb = x_out_l + ww;
} else {
int ww = ( dt * w_out ) / db;
x_out_rt = x_out_l + ww;
}
ppath.moveTo ( x_out_l, y_top + 0.5 );
ppath.lineTo ( x_out_rt, y_top + 0.5 );
ppath.lineTo ( x_neck_r, y_min + 0.5 );
ppath.lineTo ( x_out_rb, y_bottom + 0.5 );
ppath.lineTo ( x_out_l, y_bottom + 0.5 );
ppath.lineTo ( x_neck_l, y_min + 0.5 );
ppath.closeSubpath ();
} else {
double x_rt;
double x_rb;
if ( y_min < y_bottom ) {
x_rt = x_neck_r;
x_rb = x_out_r;
} else {
x_rt = x_out_r;
x_rb = x_neck_r;
}
ppath.moveTo ( x_neck_l, y_top + 0.5 );
ppath.lineTo ( x_rt, y_top + 0.5 );
ppath.lineTo ( x_rb, y_bottom + 0.5 );
ppath.lineTo ( x_out_l, y_bottom + 0.5 );
ppath.closeSubpath ();
}
} else {
x_out_r = x_out_l + w_out / 2.0;
ppath.moveTo ( x_out_l, y_top + 0.5 );
ppath.lineTo ( x_out_r, y_top + 0.5 );
ppath.lineTo ( x_out_r, y_bottom + 0.5 );
ppath.lineTo ( x_out_l, y_bottom + 0.5 );
ppath.closeSubpath ();
}
{
QColor col_fill ( pd.pal.color ( QPalette::Window ) );
QColor col_pen ( pd.pal.color ( QPalette::WindowText ) );
if ( pd.is_down ) {
col_fill.setAlpha ( 40 );
col_pen.setAlpha ( 40 );
} else {
col_fill.setAlpha ( 16 );
col_pen.setAlpha ( 18 );
}
{
QPen pen;
pen.setColor ( col_pen );
pen.setWidth ( 1.0 );
pd.qpnt.setPen ( pen );
}
pd.qpnt.setBrush ( col_fill );
}
pd.qpnt.drawPath ( ppath );
}
void
DS_Slider_Painter_Bevelled::paint_bg_ticks ( PData & pd )
{
const int range_max_idx ( pd.meta_bg->ticks_range_max_idx );
unsigned int ticks_max_idx;
int idx_delta ( 1 );
int y_off;
y_off = pd.height () - 1;
y_off -= pd.meta_bg->ticks_range_start;
const int y_bottom = y_off;
const int y_top = y_off - range_max_idx;
// Setup main tick position mapper
ticks_max_idx = pd.meta_bg->ticks_max_idx;
if ( ticks_max_idx > 0 ) {
if ( ( range_max_idx / ticks_max_idx ) < 2 ) {
ticks_max_idx = range_max_idx / pd.tick_min_dist;
}
}
::Wdg::UInt_Mapper_Up mapper ( ticks_max_idx, range_max_idx );
if ( ticks_max_idx > 0 ) {
const int tmd ( mapper.min_dist () );
while ( ( idx_delta * tmd ) < pd.tick_min_dist ) {
++idx_delta;
}
}
// Paint
{
QColor tick_col ( pd.pal.color ( QPalette::WindowText ) );
tick_col = col_mix ( tick_col, pd.pal.color ( QPalette::Button ), 3, 1 );
const int idx_start = idx_delta;
for ( unsigned int ii = idx_start; ii < ticks_max_idx; ii += idx_delta ) {
int yy = y_bottom - mapper.map ( ii );
if ( ( yy - y_top ) < pd.tick_min_dist ) {
break;
}
paint_bg_tick ( pd, yy, pd.tick_width[ 1 ], tick_col );
}
}
{
QColor tick_col ( pd.pal.color ( QPalette::WindowText ) );
tick_col = col_mix ( tick_col, pd.pal.color ( QPalette::Button ), 4, 1 );
// Bottom and top ticks
if ( ticks_max_idx > 0 ) {
paint_bg_tick ( pd, y_top, pd.tick_width[ 0 ], tick_col );
}
paint_bg_tick ( pd, y_bottom, pd.tick_width[ 0 ], tick_col );
}
}
void
DS_Slider_Painter_Bevelled::paint_bg_tick ( PData & pd,
double tick_pos_n,
double tick_width_n,
const QColor & col_n )
{
const double tick_start ( ( pd.width () - tick_width_n ) / 2.0 );
QColor col ( col_n );
// Glow below solid line
{
col.setAlpha ( 32 );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col );
const unsigned int num_pts ( 9 );
double xl ( tick_start - 0.5 );
double xr ( tick_start + tick_width_n + 0.5 );
const QPointF points[ num_pts ] = {QPointF ( xl, tick_pos_n - 1 ),
QPointF ( xr, tick_pos_n - 1 ),
QPointF ( xr + 1, tick_pos_n ),
QPointF ( xr + 1, tick_pos_n + 1 ),
QPointF ( xr, tick_pos_n + 2 ),
QPointF ( xl, tick_pos_n + 2 ),
QPointF ( xl - 1, tick_pos_n + 1 ),
QPointF ( xl - 1, tick_pos_n ),
QPointF ( xl, tick_pos_n - 1 )};
pd.qpnt.drawPolygon ( points, num_pts );
}
// Solid line
{
col.setAlpha ( 200 );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col );
pd.qpnt.drawRect ( tick_start, tick_pos_n, tick_width_n, 1.0 );
}
}
// Marker painting
int
DS_Slider_Painter_Bevelled::paint_marker ( ::dpe::Paint_Job * pjob_n,
PData & pd )
{
int res ( 0 );
//::std::cout << "DS_Slider_Painter_Bevelled::paint_marker\n";
switch ( pjob_n->img_idx ) {
case 0:
paint_marker_current ( pd );
break;
case 1:
paint_marker_hint ( pd );
break;
default:
res = -1;
break;
}
return res;
}
void
DS_Slider_Painter_Bevelled::paint_marker_current ( PData & pd )
{
int bevel ( pd.width () / 3 );
bevel = qMax ( bevel, 2 );
{ // Background
const unsigned int num_pts ( 9 );
const double x0 ( 0.0 );
const double x1 ( bevel );
const double x2 ( pd.width () - bevel );
const double x3 ( pd.width () );
const double y0 ( 0.0 );
const double y1 ( bevel );
const double y2 ( pd.height () - bevel );
const double y3 ( pd.height () );
const QPointF points[ num_pts ] = {QPointF ( x0, y1 ),
QPointF ( x1, y0 ),
QPointF ( x2, y0 ),
QPointF ( x3, y1 ),
QPointF ( x3, y2 ),
QPointF ( x2, y3 ),
QPointF ( x1, y3 ),
QPointF ( x0, y2 ),
QPointF ( x0, y1 )};
{
QColor col ( pd.pal.color ( QPalette::WindowText ) );
col.setAlpha ( 64 );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col );
}
pd.qpnt.drawPolygon ( points, num_pts );
}
{ // Foreground
const unsigned int num_pts ( 9 );
double delta ( pd.width () / 6.0 );
if ( delta < 1.0 ) {
delta = 1.0;
}
double delta_sq ( delta * ( ::std::sqrt ( 2.0 ) - 1.0 ) );
const double x0 ( delta );
const double x1 ( bevel + delta_sq );
const double x2 ( pd.width () - x1 );
const double x3 ( pd.width () - x0 );
const double y0 ( delta );
const double y1 ( bevel + delta_sq );
const double y2 ( pd.height () - y1 );
const double y3 ( pd.height () - y0 );
const QPointF points[ num_pts ] = {QPointF ( x0, y1 ),
QPointF ( x1, y0 ),
QPointF ( x2, y0 ),
QPointF ( x3, y1 ),
QPointF ( x3, y2 ),
QPointF ( x2, y3 ),
QPointF ( x1, y3 ),
QPointF ( x0, y2 ),
QPointF ( x0, y1 )};
{
const QColor & col ( pd.pal.color ( QPalette::WindowText ) );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col );
}
pd.qpnt.drawPolygon ( points, num_pts );
}
}
void
DS_Slider_Painter_Bevelled::paint_marker_hint ( PData & pd )
{
int bevel ( pd.width () / 3 );
bevel = qMax ( bevel, 2 );
{
const unsigned int num_pts ( 9 );
const double x0 ( 0.0 );
const double x1 ( bevel );
const double x2 ( pd.width () - bevel );
const double x3 ( pd.width () );
const double y0 ( 0.0 );
const double y1 ( bevel );
const double y2 ( pd.height () - bevel );
const double y3 ( pd.height () );
const QPointF points[ num_pts ] = {
QPointF ( x0, y1 ),
QPointF ( x1, y0 ),
QPointF ( x2, y0 ),
QPointF ( x3, y1 ),
QPointF ( x3, y2 ),
QPointF ( x2, y3 ),
QPointF ( x1, y3 ),
QPointF ( x0, y2 ),
QPointF ( x0, y1 ),
};
{
QColor col ( pd.pal.color ( QPalette::WindowText ) );
col.setAlpha ( 100 );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col );
}
pd.qpnt.drawPolygon ( points, num_pts );
}
}
// Frame painting
int
DS_Slider_Painter_Bevelled::paint_frame ( ::dpe::Paint_Job * pjob_n,
PData & pd )
{
//::std::cout << "DS_Slider_Painter_Bevelled::paint_frame " << pjob_n->img_idx
//<< "\n";
// Calculate state flags
{
pd.has_focus = ( pjob_n->img_idx == 0 );
pd.has_weak_focus = ( pjob_n->img_idx == 1 );
}
// Paint
paint_frame_deco ( pd );
return 0;
}
void
DS_Slider_Painter_Bevelled::paint_frame_deco ( PData & pd )
{
const QColor col_norm ( pd.pal.color ( QPalette::Button ) );
const QColor col_text ( pd.pal.color ( QPalette::ButtonText ) );
const QColor col_text2 ( pd.pal.color ( QPalette::WindowText ) );
const QColor col_high ( pd.pal.color ( QPalette::Highlight ) );
{
QColor col;
if ( pd.has_weak_focus ) {
col = col_high;
} else {
col = ::Wdg::col_mix ( col_text, col_text2, 2, 1 );
col = ::Wdg::col_mix ( col, col_norm, 3, 1 );
}
int frw ( qMax ( 1, pd.bw - 2 * pd.ew ) );
double shrink ( pd.ew );
if ( frw < 2 ) {
if ( !pd.has_weak_focus ) {
if ( pd.bw > 2 ) {
frw = qMin ( 2, pd.bw );
} else {
// shrink = false;
}
}
}
// Fill
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col );
pd.qpnt.drawPath ( path_bevel_frame ( pd.rectf, pd.bevel, frw, shrink ) );
}
}
// Handle painting
int
DS_Slider_Painter_Bevelled::paint_handle ( ::dpe::Paint_Job * pjob_n,
PData & pd )
{
pd.bw = pd.width () / 24;
pd.bw = qMax ( 2, pd.bw );
pd.ew = qMax ( 1, ( pd.bw / 4 ) );
{
pd.has_focus = ( ( pjob_n->img_idx == 1 ) || ( pjob_n->img_idx == 3 ) );
pd.mouse_over = ( pjob_n->img_idx >= 2 );
pd.is_down = ( pjob_n->img_idx == 4 );
}
// Painting
{
paint_handle_area ( pd );
paint_handle_frame ( pd );
paint_handle_items ( pd );
}
return 0;
}
void
DS_Slider_Painter_Bevelled::paint_handle_area ( PData & pd )
{
const int iw ( pd.width () - 2 * pd.bw );
const int ih ( pd.height () - 2 * pd.bw );
QPainterPath area_path;
papp_bevel_area ( area_path, pd.rectf, pd.bevel, pd.bw / 2.0 );
// Background
{
const double grw ( iw / 3.0 );
const double grwn ( grw / double ( iw ) );
QColor col_base ( pd.pal.color ( QPalette::Window ) );
if ( pd.pal.currentColorGroup () == QPalette::Disabled ) {
QColor col_btn ( pd.pal.color ( QPalette::Button ) );
col_base = col_mix ( col_base, col_btn, 2, 1 );
}
QColor col_edge ( col_base );
QColor col_center ( col_base );
col_edge.setAlpha ( 170 );
col_center.setAlpha ( 145 );
QLinearGradient lgrad ( QPointF ( pd.bw, 0.0 ),
QPointF ( pd.width () - pd.bw, 0.0 ) );
lgrad.setColorAt ( 0.0, col_edge );
lgrad.setColorAt ( grwn, col_center );
lgrad.setColorAt ( 1.0 - grwn, col_center );
lgrad.setColorAt ( 1.0, col_edge );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( lgrad );
}
pd.qpnt.drawPath ( area_path );
// Highlight
{
QColor col_edge ( pd.pal.color ( QPalette::Light ) );
QColor col_trans ( pd.pal.color ( QPalette::Light ) );
col_edge.setAlpha ( 128 );
col_trans.setAlpha ( 30 );
const double hl_dy ( ih / 8.0 );
const double y_top ( pd.bw );
const double y_bottom ( pd.height () - pd.bw );
QLinearGradient lgrad;
if ( pd.is_down ) {
lgrad.setStart ( 0.0, y_bottom - hl_dy );
lgrad.setFinalStop ( 0.0, y_top );
} else {
lgrad.setStart ( 0.0, y_top + hl_dy );
lgrad.setFinalStop ( 0.0, y_bottom );
if ( pd.mouse_over ) {
col_edge.setAlpha ( 150 );
}
}
// Adjust gradient pattern
lgrad.setColorAt ( 0.0, col_edge );
lgrad.setColorAt ( 1.0, col_trans );
lgrad.setSpread ( QGradient::ReflectSpread );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( lgrad );
}
pd.qpnt.drawPath ( area_path );
}
void
DS_Slider_Painter_Bevelled::paint_handle_frame ( PData & pd )
{
QColor col;
{
// const QColor col_btn ( pd.pal.color ( QPalette::Button ) );
const QColor col_bg ( pd.pal.color ( QPalette::Window ) );
const QColor col_fg ( pd.pal.color ( QPalette::WindowText ) );
col = ::Wdg::col_mix ( col_bg, col_fg, 1, 1 );
}
paint_bevel_raised_frame ( pd, pd.rectf, pd.bevel, pd.bw, pd.ew, col );
}
void
DS_Slider_Painter_Bevelled::paint_handle_items ( PData & pd )
{
// Colors
QColor col_bg ( pd.pal.color ( QPalette::Window ) );
QColor col_light ( pd.pal.color ( QPalette::Light ) );
col_light = ::Wdg::col_mix ( col_light, col_bg, 3, 2 );
QColor col_dark ( pd.pal.color ( QPalette::WindowText ) );
col_dark = ::Wdg::col_mix ( col_dark, col_bg, 5, 1 );
// Transforms
const QTransform trans_hmirror (
-1.0, 0.0, 0.0, 0.0, 1.0, 0.0, pd.width (), 0.0, 1.0 );
// Variables
const double center_v ( pd.height () / 2.0 );
const double height_sub ( pd.bevel + pd.bw * ( sqrt ( 2.0 ) - 1.0 ) );
const double line_width_long ( 1.3333 ); // Width of the bright border
const double line_width_small ( 1.25 ); // Width of the bright border
const double line_width_fine ( 1.0 ); // Width of the bright border
double tri_height_base;
double tri_width;
{
const double in_w ( pd.width () - 2 * pd.bw );
const double in_h ( pd.height () - 2 * pd.bw );
const double tri_len_h ( in_w / 6.0f );
const double tri_len_v ( in_h / 6.0f );
const double tri_len ( qMin ( tri_len_v, tri_len_h ) );
tri_height_base = tri_len;
tri_width = tri_len;
tri_width += 1;
}
if ( pd.is_down ) {
const double down_scale ( 3.0 / 4.0 );
tri_width *= down_scale;
}
// Round
tri_width = ::std::floor ( tri_width + 0.5 );
// Install clipping region
{
QPainterPath area_path;
papp_bevel_area ( area_path, pd.rectf, pd.bevel, pd.bw );
pd.qpnt.setClipPath ( area_path );
}
{ // Paint long piece
QPainterPath ppath;
{
const double bb_w_loc ( line_width_long / 2.0 );
const double xoff ( pd.bw );
double pp_w ( tri_width - bb_w_loc );
double pp_h ( pd.height () / 2.0 - height_sub - bb_w_loc );
const QPointF ptop ( xoff, center_v - pp_h );
const QPointF pbot ( xoff, center_v + pp_h );
const QPointF pmid_top ( xoff + pp_w, center_v - 0.5 );
const QPointF pmid_bot ( xoff + pp_w, center_v + 0.5 );
const double sl_dk_x1 ( pp_w / 2.25 );
const double sl_dk_y1 ( pp_w / 2.5 );
const double sl_dk_y2 ( pp_h / 4.0 );
// Create path
ppath.moveTo ( 0.0, ptop.y () );
ppath.lineTo ( ptop.x (), ptop.y () );
ppath.cubicTo ( QPointF ( ptop.x () + sl_dk_x1, ptop.y () + sl_dk_y1 ),
QPointF ( pmid_top.x (), pmid_top.y () - sl_dk_y2 ),
QPointF ( pmid_top.x (), pmid_top.y () ) );
ppath.lineTo ( pmid_bot.x (), pmid_bot.y () );
ppath.cubicTo ( QPointF ( pmid_bot.x (), pmid_bot.y () + sl_dk_y2 ),
QPointF ( pbot.x () + sl_dk_x1, pbot.y () - sl_dk_y1 ),
QPointF ( pbot.x (), pbot.y () ) );
ppath.lineTo ( 0.0, pbot.y () );
ppath.closeSubpath ();
}
{
QPen pen;
pen.setWidthF ( line_width_long );
pen.setColor ( col_light );
pd.qpnt.setPen ( pen );
}
pd.qpnt.setBrush ( col_dark );
pd.qpnt.drawPath ( ppath );
ppath = trans_hmirror.map ( ppath );
pd.qpnt.drawPath ( ppath );
}
{ // Paint small triangle
QPainterPath ppath;
{
double tri_height ( tri_height_base );
tri_height = std::floor ( tri_height ) + 0.5;
const double xoff ( pd.bw );
const double pp_w ( tri_width );
const double pp_h ( tri_height );
// Create path
ppath.moveTo ( 0, center_v - pp_h );
ppath.lineTo ( xoff, center_v - pp_h );
ppath.lineTo ( xoff, center_v - pp_h );
ppath.lineTo ( xoff + pp_w, center_v );
ppath.lineTo ( xoff, center_v + pp_h );
ppath.lineTo ( 0, center_v + pp_h );
ppath.closeSubpath ();
}
{
QPen pen;
pen.setWidthF ( line_width_small );
pen.setColor ( col_light );
pd.qpnt.setPen ( pen );
}
pd.qpnt.setBrush ( col_dark );
pd.qpnt.drawPath ( ppath );
ppath = trans_hmirror.map ( ppath );
pd.qpnt.drawPath ( ppath );
}
{ // Center line
const double xoff ( pd.bw + tri_width );
// Bright background
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_light );
pd.qpnt.drawRect ( xoff,
center_v - 0.5 - line_width_fine,
pd.width () - 2 * xoff,
1.0 + line_width_fine * 2 );
// Dark foreground
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_dark );
pd.qpnt.drawRect ( pd.bw, center_v - 0.5f, pd.width () - 2 * pd.bw, 1.0 );
}
// Remove clipping region
pd.qpnt.setClipping ( false );
}
void
DS_Slider_Painter_Bevelled::papp_bevel_area ( QPainterPath & ppath_n,
const QRectF & area_n,
double bevel_n,
double indent_n )
{
const double angle_tan ( ::std::tan ( 22.5 / 180.0 * M_PI ) );
double ds ( indent_n );
double db ( bevel_n + angle_tan * indent_n );
double xl[ 2 ] = {area_n.left (), area_n.left () + area_n.width ()};
double yl[ 2 ] = {area_n.top (), area_n.top () + area_n.height ()};
ppath_n.moveTo ( xl[ 0 ] + ds, yl[ 0 ] + db ),
ppath_n.lineTo ( xl[ 0 ] + db, yl[ 0 ] + ds ),
ppath_n.lineTo ( xl[ 1 ] - db, yl[ 0 ] + ds ),
ppath_n.lineTo ( xl[ 1 ] - ds, yl[ 0 ] + db ),
ppath_n.lineTo ( xl[ 1 ] - ds, yl[ 1 ] - db ),
ppath_n.lineTo ( xl[ 1 ] - db, yl[ 1 ] - ds ),
ppath_n.lineTo ( xl[ 0 ] + db, yl[ 1 ] - ds ),
ppath_n.lineTo ( xl[ 0 ] + ds, yl[ 1 ] - db ), ppath_n.closeSubpath ();
}
void
DS_Slider_Painter_Bevelled::paint_bevel_raised_frame ( PData & pd,
const QRectF & area_n,
double bevel_n,
double frame_width_n,
double edge_width_n,
const QColor & col_n )
{
QColor col_light ( pd.pal.color ( QPalette::Light ) );
QColor col_shadow ( pd.pal.color ( QPalette::Shadow ) );
QColor col_mid ( col_n );
QColor col_br ( ::Wdg::col_mix ( col_n, col_light, 5, 4 ) );
QColor col_dk ( ::Wdg::col_mix ( col_n, col_shadow, 5, 4 ) );
const double shrink_out ( 0.0 );
const double shrink_in ( frame_width_n - edge_width_n );
// Bright area
{
QPainterPath pp;
papp_bevel_frame_edge ( pp, area_n, 3, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_corner (
pp, area_n, 0, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_edge ( pp, area_n, 0, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_edge ( pp, area_n, 1, bevel_n, edge_width_n, shrink_in );
papp_bevel_frame_corner ( pp, area_n, 2, bevel_n, edge_width_n, shrink_in );
papp_bevel_frame_edge ( pp, area_n, 2, bevel_n, edge_width_n, shrink_in );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_br );
pd.qpnt.drawPath ( pp );
}
// Mid area
{
QPainterPath pp;
papp_bevel_frame_corner (
pp, area_n, 1, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_corner ( pp, area_n, 1, bevel_n, edge_width_n, shrink_in );
papp_bevel_frame_corner (
pp, area_n, 3, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_corner ( pp, area_n, 3, bevel_n, edge_width_n, shrink_in );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_mid );
pd.qpnt.drawPath ( pp );
}
// Dark area
{
QPainterPath pp;
papp_bevel_frame_edge ( pp, area_n, 3, bevel_n, edge_width_n, shrink_in );
papp_bevel_frame_corner ( pp, area_n, 0, bevel_n, edge_width_n, shrink_in );
papp_bevel_frame_edge ( pp, area_n, 0, bevel_n, edge_width_n, shrink_in );
papp_bevel_frame_edge ( pp, area_n, 1, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_corner (
pp, area_n, 2, bevel_n, edge_width_n, shrink_out );
papp_bevel_frame_edge ( pp, area_n, 2, bevel_n, edge_width_n, shrink_out );
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_dk );
pd.qpnt.drawPath ( pp );
}
// Frame center line area
const double mid_width ( frame_width_n - 2.0 * edge_width_n );
if ( mid_width > 0.0 ) {
pd.qpnt.setPen ( Qt::NoPen );
pd.qpnt.setBrush ( col_mid );
pd.qpnt.drawPath (
path_bevel_frame ( area_n, bevel_n, mid_width, edge_width_n ) );
}
}
QPainterPath
DS_Slider_Painter_Bevelled::path_bevel_frame ( const QRectF & area_n,
double bevel_n,
double frame_width_n,
double indent_n )
{
QPainterPath ppath;
papp_bevel_area ( ppath, area_n, bevel_n, indent_n );
papp_bevel_area ( ppath, area_n, bevel_n, indent_n + frame_width_n );
return ppath;
}
void
DS_Slider_Painter_Bevelled::papp_bevel_frame_corner ( QPainterPath & ppath_n,
const QRectF & area_n,
unsigned int edge_n,
double bevel_n,
double width_n,
double indent_n )
{
double xx[ 4 ];
double yy[ 4 ];
{
const double angle_tan ( ::std::tan ( 22.5 / 180.0 * M_PI ) );
double ds1 ( indent_n );
double db1 ( bevel_n + angle_tan * ds1 );
double ds2 ( indent_n + width_n );
double db2 ( bevel_n + angle_tan * ds2 );
xx[ 0 ] = ds1;
xx[ 1 ] = db1;
xx[ 2 ] = db2;
xx[ 3 ] = ds2;
yy[ 0 ] = db1;
yy[ 1 ] = ds1;
yy[ 2 ] = ds2;
yy[ 3 ] = db2;
}
{
double x_off ( area_n.left () );
double y_off ( area_n.top () );
double x_scale ( 1.0 );
double y_scale ( 1.0 );
if ( edge_n == 0 ) {
// pass
} else if ( edge_n == 1 ) {
x_off += area_n.width ();
x_scale = -1;
} else if ( edge_n == 2 ) {
x_off += area_n.width ();
y_off += area_n.height ();
x_scale = -1;
y_scale = -1;
} else {
y_off += area_n.height ();
y_scale = -1;
}
for ( unsigned int ii = 0; ii < 4; ++ii ) {
xx[ ii ] *= x_scale;
}
for ( unsigned int ii = 0; ii < 4; ++ii ) {
yy[ ii ] *= y_scale;
}
for ( unsigned int ii = 0; ii < 4; ++ii ) {
xx[ ii ] += x_off;
}
for ( unsigned int ii = 0; ii < 4; ++ii ) {
yy[ ii ] += y_off;
}
}
ppath_n.moveTo ( xx[ 0 ], yy[ 0 ] );
ppath_n.lineTo ( xx[ 1 ], yy[ 1 ] );
ppath_n.lineTo ( xx[ 2 ], yy[ 2 ] );
ppath_n.lineTo ( xx[ 3 ], yy[ 3 ] );
ppath_n.closeSubpath ();
}
void
DS_Slider_Painter_Bevelled::papp_bevel_frame_edge ( QPainterPath & ppath_n,
const QRectF & area_n,
unsigned int edge_n,
double bevel_n,
double width_n,
double indent_n )
{
double xx[ 4 ];
double yy[ 4 ];
{
const double angle_tan ( ::std::tan ( 22.5 / 180.0 * M_PI ) );
double ds1 ( indent_n );
double db1 ( bevel_n + angle_tan * ds1 );
double ds2 ( indent_n + width_n );
double db2 ( bevel_n + angle_tan * ds2 );
if ( ( edge_n % 2 ) == 0 ) { // top / bottom
xx[ 0 ] = area_n.left () + db1;
xx[ 1 ] = area_n.left () + area_n.width () - db1;
xx[ 2 ] = area_n.left () + area_n.width () - db2;
xx[ 3 ] = area_n.left () + db2;
yy[ 0 ] = ds1;
yy[ 1 ] = ds1;
yy[ 2 ] = ds2;
yy[ 3 ] = ds2;
} else { // left / right
xx[ 0 ] = ds1;
xx[ 1 ] = ds1;
xx[ 2 ] = ds2;
xx[ 3 ] = ds2;
yy[ 0 ] = area_n.top () + area_n.height () - db1;
yy[ 1 ] = area_n.top () + db1;
yy[ 2 ] = area_n.top () + db2;
yy[ 3 ] = area_n.top () + area_n.height () - db2;
}
}
// Flip sides
if ( edge_n == 1 ) { // flip left to right
for ( unsigned int ii = 0; ii < 4; ++ii ) {
xx[ ii ] *= -1;
}
const double x_off ( area_n.left () + area_n.width () );
for ( unsigned int ii = 0; ii < 4; ++ii ) {
xx[ ii ] += x_off;
}
} else if ( edge_n == 2 ) { // flip top to bottom
for ( unsigned int ii = 0; ii < 4; ++ii ) {
yy[ ii ] *= -1;
}
const double y_off ( area_n.top () + area_n.height () );
for ( unsigned int ii = 0; ii < 4; ++ii ) {
yy[ ii ] += y_off;
}
}
ppath_n.moveTo ( xx[ 0 ], yy[ 0 ] );
ppath_n.lineTo ( xx[ 1 ], yy[ 1 ] );
ppath_n.lineTo ( xx[ 2 ], yy[ 2 ] );
ppath_n.lineTo ( xx[ 3 ], yy[ 3 ] );
ppath_n.closeSubpath ();
}
} // namespace Painter
} // namespace Wdg
| 27.753562 | 80 | 0.539807 | amazingidiot |
efa2b3b8f5cff514aa7914aef5da94f8f26c10e4 | 887 | cpp | C++ | 17A.cpp | felikjunvianto/kfile-codeforces-submissions | 1b53da27a294a12063b0912e12ad32efe24af678 | [
"MIT"
] | null | null | null | 17A.cpp | felikjunvianto/kfile-codeforces-submissions | 1b53da27a294a12063b0912e12ad32efe24af678 | [
"MIT"
] | null | null | null | 17A.cpp | felikjunvianto/kfile-codeforces-submissions | 1b53da27a294a12063b0912e12ad32efe24af678 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
bool prime[2000];
vector<int> bil;
int N,K,x,y,z;
int main()
{
memset(prime,true,sizeof(prime));
for(x=2;x*x<=2000;x++) if(prime[x])
{
z=2;
while(x*z<=2000)
{
prime[x*z]=false;
z++;
}
}
for(x=2;x<=2000;x++) if(prime[x]) bil.pb(x);
scanf("%d %d",&N,&K);
for(x=1;bil[x]+bil[x-1]+1<=N;x++) if(prime[bil[x]+bil[x-1]+1]) K--;
printf("%s\n",K>0?"NO":"YES");
return 0;
}
| 17.392157 | 69 | 0.598647 | felikjunvianto |
efa35a29214e795495f41465f977d9c2a4a96f50 | 753 | cpp | C++ | tests/AllegroFlare/ProfilerTest.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 25 | 2015-03-30T02:02:43.000Z | 2019-03-04T22:29:12.000Z | tests/AllegroFlare/ProfilerTest.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 122 | 2015-04-01T08:15:26.000Z | 2019-10-16T20:31:22.000Z | tests/AllegroFlare/ProfilerTest.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 4 | 2016-09-02T12:14:09.000Z | 2018-11-23T20:38:49.000Z |
#include <gtest/gtest.h>
#include <AllegroFlare/Profiler.hpp>
// for usleep on Windows
#include <unistd.h>
TEST(AllegroFlare_ProfilerTest, can_be_created_without_blowing_up)
{
AllegroFlare::Profiler profiler;
}
TEST(AllegroFlare_ProfilerTest, DISABLED__emit__will_add_an_event_time_to_that_event_bucket)
// TODO this test crashes on Windows
{
std::string EVENT_IDENTIFIER = "my_custom_event";
AllegroFlare::Profiler profiler;
for (unsigned i=0; i<10; i++)
{
profiler.emit(EVENT_IDENTIFIER);
usleep(10000);
}
ASSERT_EQ(1, profiler.get_event_buckets().size());
ASSERT_EQ(10, profiler.get_event_samples(EVENT_IDENTIFIER, 10).size());
ASSERT_EQ(6, profiler.get_event_samples(EVENT_IDENTIFIER, 6).size());
}
| 24.290323 | 92 | 0.747676 | MarkOates |
efa68845f579d193ab3e5f439ffdc6bb52b04b56 | 5,161 | cpp | C++ | src/workers/src/postgres_workers_repository.cpp | maxerMU/db-course | 3927f1cf0ccb2a937d571626dcc42d725a89d3f6 | [
"Apache-2.0"
] | null | null | null | src/workers/src/postgres_workers_repository.cpp | maxerMU/db-course | 3927f1cf0ccb2a937d571626dcc42d725a89d3f6 | [
"Apache-2.0"
] | null | null | null | src/workers/src/postgres_workers_repository.cpp | maxerMU/db-course | 3927f1cf0ccb2a937d571626dcc42d725a89d3f6 | [
"Apache-2.0"
] | null | null | null | #include "postgres_workers_repository.h"
#include <time.h>
#include "base_sections.h"
#include "database_exceptions.h"
#include "iostream"
PostgresWorkersRepository::PostgresWorkersRepository(
const std::shared_ptr<BaseConfig>& conf,
const std::string& connection_section) {
read_config(conf, connection_section);
connect();
add_prepare_statements();
}
void PostgresWorkersRepository::read_config(
const std::shared_ptr<BaseConfig>& conf,
const std::string& connection_section) {
name_ = conf->get_string_field({connection_section, DbNameSection});
user_ = conf->get_string_field({connection_section, DbUserSection});
user_password_ =
conf->get_string_field({connection_section, DbUserPasswordSection});
host_ = conf->get_string_field({connection_section, DbHostSection});
port_ = conf->get_uint_field({connection_section, DbPortSection});
}
void PostgresWorkersRepository::connect() {
std::string connection_string = "dbname = " + name_ + " user = " + user_ +
" password = " + user_password_ +
" hostaddr = " + host_ +
" port = " + std::to_string(port_);
try {
connection_ = std::shared_ptr<pqxx::connection>(
new pqxx::connection(connection_string.c_str()));
if (!connection_->is_open()) {
throw DatabaseConnectException("can't connect to " + name_);
} else
std::cout << "Connected to db " << name_ << std::endl;
} catch (std::exception& ex) {
throw DatabaseConnectException("can't connect to " + name_ + " " +
ex.what());
}
}
void PostgresWorkersRepository::add_prepare_statements() {
connection_->prepare(requests_names[CREATE],
"SELECT FN_ADD_WORKER($1, $2, $3, $4, $5, $6)");
connection_->prepare(requests_names[READ_COUNT], "SELECT FN_WORKERS_COUNT()");
connection_->prepare(requests_names[READ_PASSWORD],
"SELECT * FROM FN_GET_PASSWORD($1)");
connection_->prepare(requests_names[READ_BASE_INF],
"SELECT * FROM FN_GET_WORKER_BY_ID($1)");
connection_->prepare(
requests_names[UPDATE],
"SELECT * FROM FN_UPDATE_WORKER($1, $2, $3, $4, $5, $6)");
connection_->prepare(requests_names[UPDATE_PRIVILEGE],
"CALL PR_UPDATE_WORKER_PRIVILEGE($1, $2)");
}
int PostgresWorkersRepository::create(const WorkerPost& worker) {
pqxx::work w(*connection_);
std::string birthdate = std::to_string(worker.birthdate().tm_year + 1900) +
"-" + std::to_string(worker.birthdate().tm_mon + 1) +
"-" + std::to_string(worker.birthdate().tm_mday);
pqxx::result res = w.exec_prepared(
requests_names[CREATE], worker.name(), worker.surname(), birthdate,
(int)worker.getPrivilege(), worker.username(), worker.password());
w.commit();
return res[0][0].as<size_t>();
}
size_t PostgresWorkersRepository::workers_count() {
pqxx::work w(*connection_);
pqxx::result res = w.exec_prepared(requests_names[READ_COUNT]);
w.commit();
return res[0][0].as<size_t>();
}
WorkerBaseInf PostgresWorkersRepository::read(size_t worker_id) {
pqxx::work w(*connection_);
pqxx::result res = w.exec_prepared(requests_names[READ_BASE_INF], worker_id);
w.commit();
if (res.size() == 0)
throw DatabaseNotFoundException("can't find user");
WorkerBaseInf worker;
worker.setName(res[0][0].as<std::string>());
worker.setSurname(res[0][1].as<std::string>());
auto birthdate_str = res[0][2].as<std::string>();
tm birthdate;
if (!strptime(birthdate_str.c_str(), "%Y-%m-%d", &birthdate))
throw DatabaseIncorrectAnswerException("can't parse datetime");
worker.setBirthdate(birthdate);
worker.setPrivilege(static_cast<PrivilegeLevel>(res[0][3].as<int>()));
return worker;
}
int PostgresWorkersRepository::update(const WorkerUpdate& worker) {
pqxx::work w(*connection_);
std::string birthdate = std::to_string(worker.birthdate().tm_year + 1900) +
"-" + std::to_string(worker.birthdate().tm_mon + 1) +
"-" + std::to_string(worker.birthdate().tm_mday);
pqxx::result res = w.exec_prepared(
requests_names[UPDATE], worker.getWorker_id(), worker.name(),
worker.surname(), birthdate, worker.username(), worker.password());
w.commit();
return res[0][0].as<size_t>();
}
bool PostgresWorkersRepository::get_password(std::string& password,
size_t& worker_id,
const std::string& username) {
pqxx::work w(*connection_);
pqxx::result res = w.exec_prepared(requests_names[READ_PASSWORD], username);
w.commit();
if (!res[0][0].as<bool>())
return false;
worker_id = res[0][1].as<size_t>();
password = res[0][2].as<std::string>();
return true;
}
void PostgresWorkersRepository::update_privilege(
size_t worker_id,
const PrivilegeLevel& privilege) {
pqxx::work w(*connection_);
w.exec_prepared(requests_names[UPDATE_PRIVILEGE], worker_id, (int)privilege);
w.commit();
}
| 36.090909 | 80 | 0.649293 | maxerMU |
efaaeb5c1d98d01e80e9d8f73e66cad874694928 | 722 | hpp | C++ | core/src/modules/include/IFreezingPoint.hpp | athelaf/nextsimdg | 557e45db6af2cc07d00b3228c2d46f87567fe755 | [
"Apache-2.0"
] | null | null | null | core/src/modules/include/IFreezingPoint.hpp | athelaf/nextsimdg | 557e45db6af2cc07d00b3228c2d46f87567fe755 | [
"Apache-2.0"
] | null | null | null | core/src/modules/include/IFreezingPoint.hpp | athelaf/nextsimdg | 557e45db6af2cc07d00b3228c2d46f87567fe755 | [
"Apache-2.0"
] | null | null | null | /*!
* @file IFreezingPoint.hpp
*
* @date Nov 9, 2021
* @author Tim Spain <timothy.spain@nersc.no>
*/
#ifndef SRC_INCLUDE_IFREEZINGPOINT_HPP_
#define SRC_INCLUDE_IFREEZINGPOINT_HPP_
namespace Nextsim {
//! The interface class for calculation of the freezing point of seawater.
class IFreezingPoint {
public:
virtual ~IFreezingPoint() = default;
/*!
* @brief A virtual function that calculates the freezing point of
* seawater.
*
* @details Freezing point in ˚C of water with the given salinity at
* standard pressure.
*
* @param sss Sea surface salinity [PSU]
*/
virtual double operator()(double sss) const = 0;
};
}
#endif /* SRC_INCLUDE_IFREEZINGPOINT_HPP_ */
| 23.290323 | 74 | 0.689751 | athelaf |
efb0162355995140ed09d23da8d405bfd8ef2e39 | 2,449 | cpp | C++ | src/shaders/basic_shaders.cpp | Wei-Parker-Guo/RayTracer | 3312c5fc73d7d175818f94dcca66b87a0222aad4 | [
"MIT"
] | 1 | 2021-06-19T07:53:22.000Z | 2021-06-19T07:53:22.000Z | src/shaders/basic_shaders.cpp | Wei-Parker-Guo/RayTracer | 3312c5fc73d7d175818f94dcca66b87a0222aad4 | [
"MIT"
] | null | null | null | src/shaders/basic_shaders.cpp | Wei-Parker-Guo/RayTracer | 3312c5fc73d7d175818f94dcca66b87a0222aad4 | [
"MIT"
] | null | null | null | #include "basic_shaders.h"
/* generate lambertian shade with another light source
* equation: c = cr(ca + clmax(0, n.l))
*/
void gen_lambert_shade(const vec3 ca, const vec3 cr, const vec3 cl, const vec3 n, const vec3 l, vec3 c){
//reflectance
float r = std::max(0.0f, vec3_mul_inner(n,l));
vec3_scale(c, cl, r);
vec3_add(c, c, ca);
//apply reflect fraction
vec3_fraction(c, cr, c);
}
/* generate phong shade based on a precalculated lambertian shade
equation: c = clambert + clcpmax(e.r)^p */
void gen_phong_shade(const vec3 cl, const vec3 cp, const vec3 l, const vec3 e, const vec3 n, const int p, vec3 clambert){
//calculate r
vec3 r;
vec3_scale( r, n, 2.0f*vec3_mul_inner(l,n) );
vec3_sub(r, r, l);
vec3_norm(r,r);
//calculate shade
vec3 cphong;
vec3_scale(cphong, cp, fast_pow(std::max(0.0f,vec3_mul_inner(e,r)),p));
vec3_fraction(cphong, cl, cphong);
vec3_add(clambert, clambert, cphong);
vec3_cull(clambert);
}
/* generate anisotropic phong shade by dividing the normal into uv directions
and calculating specular based on the Ward Anisotropic Distribution Model (a BRDF), finally adding the lambertian base shade.
Notice this can't use our fast_pow since the exponential is float.
The formula is referenced from this url:
https://en.wikibooks.org/wiki/GLSL_Programming/Unity/Brushed_Metal */
void gen_WARD_anisotropic_phong_shade(const vec3 cl, const vec3 cp, const vec3 l, const vec3 e, const vec3 n, const float pu, const float pv, const float y, vec3 clambert){
//calculate h
vec3 h;
vec3_add(h, e, l);
vec3_norm(h,h);
//calculate u and v unit vector
vec3 v;
vec3 y_v = {0.0f, y, 0.0f};
vec3_scale(v, n, vec3_mul_inner(n,y_v));
vec3_sub(v, y_v, v);
vec3_norm(v,v);
vec3 u;
vec3_mul_cross(u, v, n);
vec3_norm(u,u);
//calculate kspecular
vec3 kspec;
vec3_scale(kspec, cp, sqrt( std::max(0.0f, vec3_mul_inner(n,l) / vec3_mul_inner(n,l)*vec3_mul_inner(n,e)) )); //first term of the multiplication
vec3_scale(kspec, kspec, 1.0f / (4.0f*PI*pu*pv) ); //second term
vec3_scale(kspec, kspec, exp( -2.0f * (sqr(vec3_mul_inner(h,u)/pu) + sqr(vec3_mul_inner(h,v)/pv)) / (1.0f+vec3_mul_inner(h,n)) ) ); //thrid term
vec3_fraction(kspec, kspec, cl); //control one more time by light color
//add specular to lambertian shade
vec3_add(clambert, clambert, kspec);
vec3_cull(clambert);
}
| 38.265625 | 172 | 0.684361 | Wei-Parker-Guo |
efb24ca4a71a7cc0a1f7a0bd5c90f459bb8b2996 | 3,164 | hpp | C++ | include/memory/hadesmem/detail/winapi.hpp | phlip9/hadesmem | 59e13a92c05918b8c842141fd5cac1ed390cd79e | [
"MIT"
] | 19 | 2017-10-19T23:13:11.000Z | 2022-03-29T11:37:26.000Z | include/memory/hadesmem/detail/winapi.hpp | Bia10/hadesmem | b91bce37611d0e939a55d9490c49780f9f0f3bff | [
"MIT"
] | null | null | null | include/memory/hadesmem/detail/winapi.hpp | Bia10/hadesmem | b91bce37611d0e939a55d9490c49780f9f0f3bff | [
"MIT"
] | 10 | 2018-04-04T07:55:16.000Z | 2021-11-23T20:22:43.000Z | // Copyright (C) 2010-2015 Joshua Boyce
// See the file COPYING for copying permission.
#pragma once
#include <windows.h>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/smart_handle.hpp>
#include <hadesmem/error.hpp>
namespace hadesmem
{
namespace detail
{
inline SYSTEM_INFO GetSystemInfo()
{
SYSTEM_INFO sys_info{};
::GetSystemInfo(&sys_info);
return sys_info;
}
inline bool IsWoW64Process(HANDLE handle)
{
BOOL is_wow64 = FALSE;
if (!::IsWow64Process(handle, &is_wow64))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"IsWoW64Process failed."}
<< ErrorCodeWinLast{last_error});
}
return is_wow64 != FALSE;
}
inline detail::SmartHandle OpenProcess(DWORD id, DWORD access)
{
HANDLE const handle = ::OpenProcess(access, FALSE, id);
if (!handle)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"OpenProcess failed."}
<< ErrorCodeWinLast{last_error});
}
return detail::SmartHandle(handle);
}
inline detail::SmartHandle OpenProcessAllAccess(DWORD id)
{
return OpenProcess(id, PROCESS_ALL_ACCESS);
}
inline detail::SmartHandle OpenThread(DWORD id, DWORD access)
{
HANDLE const handle = ::OpenThread(access, FALSE, id);
if (!handle)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"OpenThread failed."}
<< ErrorCodeWinLast{last_error});
}
return detail::SmartHandle(handle);
}
inline detail::SmartHandle OpenThreadAllAccess(DWORD id)
{
return OpenThread(id, THREAD_ALL_ACCESS);
}
inline detail::SmartHandle DuplicateHandle(HANDLE handle)
{
HADESMEM_DETAIL_ASSERT(handle != nullptr);
HANDLE new_handle = nullptr;
if (!::DuplicateHandle(::GetCurrentProcess(),
handle,
::GetCurrentProcess(),
&new_handle,
0,
FALSE,
DUPLICATE_SAME_ACCESS))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"DuplicateHandle failed."}
<< ErrorCodeWinLast{last_error});
}
return detail::SmartHandle(new_handle);
}
inline std::wstring QueryFullProcessImageName(HANDLE handle)
{
HADESMEM_DETAIL_ASSERT(handle != nullptr);
std::vector<wchar_t> path(HADESMEM_DETAIL_MAX_PATH_UNICODE);
DWORD path_len = static_cast<DWORD>(path.size());
if (!::QueryFullProcessImageNameW(handle, 0, path.data(), &path_len))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
Error{} << ErrorString{"QueryFullProcessImageName failed."}
<< ErrorCodeWinLast{last_error});
}
return path.data();
}
}
}
| 27.754386 | 81 | 0.611252 | phlip9 |
efba47f84fc744499023300ed0881c6224ce2206 | 365 | hxx | C++ | include/usagi/environment_special_support.hxx | usagi/usagi | 2d57d21eeb92eadfdf4154a3e470aebfc3e388e5 | [
"MIT"
] | 2 | 2016-11-20T04:59:17.000Z | 2017-02-13T01:44:37.000Z | include/usagi/environment_special_support.hxx | usagi/usagi | 2d57d21eeb92eadfdf4154a3e470aebfc3e388e5 | [
"MIT"
] | 3 | 2015-09-28T12:00:02.000Z | 2015-09-28T12:03:21.000Z | include/usagi/environment_special_support.hxx | usagi/usagi | 2d57d21eeb92eadfdf4154a3e470aebfc3e388e5 | [
"MIT"
] | 3 | 2017-07-02T06:09:47.000Z | 2018-07-09T01:00:57.000Z | /// @file
/// @brief 処理系依存の特別な対応
/// @attention 必要に応じて最も優先的にこのヘッダーファイルをインクルードして用いる
#pragma once
#include "environment_special_support/winsock.hxx"
#include "environment_special_support/windows.hxx"
#include "environment_special_support/ciso646.hxx"
#include "environment_special_support/use_math_defines.hxx"
#include "environment_special_support/emscripten.hxx"
| 30.416667 | 59 | 0.835616 | usagi |
efbc7aaac6633655864e11f11088b8a45cff837f | 787 | cpp | C++ | engine/src/concurrency/semaphore.cpp | ValtoForks/Terminus-Engine | 0c7381af84736ec7b029977843590453cde64b1d | [
"MIT"
] | 44 | 2017-01-25T05:57:21.000Z | 2021-09-21T13:36:49.000Z | engine/src/concurrency/semaphore.cpp | ValtoForks/Terminus-Engine | 0c7381af84736ec7b029977843590453cde64b1d | [
"MIT"
] | 1 | 2017-04-05T01:50:18.000Z | 2017-04-05T01:50:18.000Z | engine/src/concurrency/semaphore.cpp | ValtoForks/Terminus-Engine | 0c7381af84736ec7b029977843590453cde64b1d | [
"MIT"
] | 3 | 2017-09-28T08:11:00.000Z | 2019-03-27T03:38:47.000Z | #include <concurrency/semaphore.hpp>
TE_BEGIN_TERMINUS_NAMESPACE
#if defined(_WIN32)
Semaphore::Semaphore()
{
m_semaphore = CreateSemaphore(NULL, 0, 256000, NULL);
}
Semaphore::~Semaphore()
{
CloseHandle(m_semaphore);
}
void Semaphore::signal()
{
ReleaseSemaphore(m_semaphore, 1, NULL);
}
void Semaphore::wait()
{
WaitForSingleObject(m_semaphore, INFINITE);
}
#else
Semaphore::Semaphore()
{
assert(pthread_mutex_init(&m_lock, NULL) == 0);
assert(pthread_cond_init(&m_cond, NULL) == 0);
}
Semaphore::~Semaphore()
{
pthread_cond_destroy(&m_cond);
pthread_mutex_destroy(&m_lock);
}
void Semaphore::signal()
{
pthread_cond_signal(&m_cond);
}
void Semaphore::wait()
{
pthread_cond_wait(&m_cond, &m_lock);
}
#endif
TE_END_TERMINUS_NAMESPACE | 14.849057 | 57 | 0.710292 | ValtoForks |
efbe30af83bbe916246b4c5d45f11e020efe8ef4 | 2,393 | cpp | C++ | Engine/Source/Runtime/Core/FileSystem/FileUtils.cpp | 1992please/NullEngine | 8f5f124e9718b8d6627992bb309cf0f0d106d07a | [
"Apache-2.0"
] | null | null | null | Engine/Source/Runtime/Core/FileSystem/FileUtils.cpp | 1992please/NullEngine | 8f5f124e9718b8d6627992bb309cf0f0d106d07a | [
"Apache-2.0"
] | null | null | null | Engine/Source/Runtime/Core/FileSystem/FileUtils.cpp | 1992please/NullEngine | 8f5f124e9718b8d6627992bb309cf0f0d106d07a | [
"Apache-2.0"
] | null | null | null | #include "NullPCH.h"
#include "FileUtils.h"
#include "Core/Application/Application.h"
#include "Core/Application/ApplicationWindow.h"
bool FFileUtils::OpenFileDialog(const FString& Starting, const char* InFilter, FString& OutFilePath)
{
char OutFileName[256] = { 0 };
OPENFILENAMEA OFN;
FMemory::Memzero(&OFN, sizeof(OFN));
OFN.lStructSize = sizeof(OPENFILENAME);
OFN.hwndOwner = (HWND)FApplication::GetApplication()->GetWindow()->GetOSWindow();
//OFN.hInstance;
OFN.lpstrFilter = InFilter;
//OFN.lpstrCustomFilter;
//OFN.nMaxCustFilter;
OFN.nFilterIndex = 1;
OFN.lpstrFile = OutFileName;
OFN.nMaxFile = sizeof(OutFileName);
OFN.lpstrFileTitle;
//OFN.nMaxFileTitle;
OFN.lpstrInitialDir = Starting.GetCharArray().GetData();
//OFN.lpstrTitle;
OFN.Flags = OFN_DONTADDTORECENT | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
//OFN.nFileOffset;
//OFN.nFileExtension;
//OFN.lpstrDefExt;
//OFN.lCustData;
//OFN.lpfnHook;
//OFN.lpTemplateName;
//OFN.lpEditInfo;
//OFN.lpstrPrompt;
//OFN.pvReserved;
//OFN.dwReserved;
//OFN.FlagsEx;
if (GetOpenFileNameA(&OFN) != 0)
{
OutFilePath = OFN.lpstrFile;
return true;
}
return false;
}
bool FFileUtils::SaveFileDialog(const FString& Starting, const char* InFilter, FString& OutFilePath)
{
char OutFileName[256] = { 0 };
OPENFILENAMEA OFN;
FMemory::Memzero(&OFN, sizeof(OFN));
OFN.lStructSize = sizeof(OPENFILENAME);
OFN.hwndOwner = (HWND)FApplication::GetApplication()->GetWindow()->GetOSWindow();
//OFN.hInstance;
OFN.lpstrFilter = InFilter;
//OFN.lpstrCustomFilter;
//OFN.nMaxCustFilter;
OFN.nFilterIndex = 1;
OFN.lpstrFile = OutFileName;
OFN.nMaxFile = sizeof(OutFileName);
OFN.lpstrFileTitle;
//OFN.nMaxFileTitle;
OFN.lpstrInitialDir = Starting.GetCharArray().GetData();
//OFN.lpstrTitle;
OFN.Flags = OFN_DONTADDTORECENT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
//OFN.nFileOffset;
//OFN.nFileExtension;
OFN.lpstrDefExt = FCString::StrChar(InFilter, '\0') + 1;
//OFN.lCustData;
//OFN.lpfnHook;
//OFN.lpTemplateName;
//OFN.lpEditInfo;
//OFN.lpstrPrompt;
//OFN.pvReserved;
//OFN.dwReserved;
//OFN.FlagsEx;
if (GetSaveFileNameA(&OFN) != 0)
{
OutFilePath = OFN.lpstrFile;
return true;
}
return false;
}
FString FFileUtils::GetCurrentDirectory()
{
char currentDir[256] = { 0 };
GetCurrentDirectoryA(sizeof(currentDir), currentDir);
return currentDir;
}
| 26.588889 | 100 | 0.735896 | 1992please |
efbe3381f36230772b5ed4d20dca744b281ce35b | 857 | hpp | C++ | Merlin/Merlin/Core/layer_stack.hpp | kshatos/MerlinEngine | a7eb9b39b6cb8a02bef0f739db25268a7a06e215 | [
"MIT"
] | null | null | null | Merlin/Merlin/Core/layer_stack.hpp | kshatos/MerlinEngine | a7eb9b39b6cb8a02bef0f739db25268a7a06e215 | [
"MIT"
] | null | null | null | Merlin/Merlin/Core/layer_stack.hpp | kshatos/MerlinEngine | a7eb9b39b6cb8a02bef0f739db25268a7a06e215 | [
"MIT"
] | null | null | null | #ifndef LAYER_STACK_HPP
#define LAYER_STACK_HPP
#include <vector>
#include <deque>
#include"Merlin/Core/layer.hpp"
namespace Merlin
{
class LayerStack
{
std::deque<std::shared_ptr<Layer>> m_layers;
public:
void PushFront(std::shared_ptr<Layer> layer);
void PushBack(std::shared_ptr<Layer> layer);
void PopFront();
void PopBack();
void PopLayer(std::shared_ptr<Layer> layer);
inline std::deque<std::shared_ptr<Layer>>::iterator begin() { return m_layers.begin(); }
inline std::deque<std::shared_ptr<Layer>>::iterator end() { return m_layers.end(); }
inline std::deque<std::shared_ptr<Layer>>::const_iterator begin() const { return m_layers.begin(); }
inline std::deque<std::shared_ptr<Layer>>::const_iterator end() const { return m_layers.end(); }
};
}
#endif | 32.961538 | 108 | 0.660443 | kshatos |
efc4437cbd04243327b3fe9b9f313d0a0b1178d3 | 8,694 | hpp | C++ | SDK/ARKSurvivalEvolved_WeapCrossbow_Zipline_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_WeapCrossbow_Zipline_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_WeapCrossbow_Zipline_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_WeapCrossbow_Zipline_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass WeapCrossbow_Zipline.WeapCrossbow_Zipline_C
// 0x0118 (0x0F70 - 0x0E58)
class AWeapCrossbow_Zipline_C : public AWeapCrossbow_C
{
public:
class USceneComponent* PreviewCableAttach; // 0x0E58(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* PreviewTargetPoint; // 0x0E60(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* ProjectileMesh1P; // 0x0E68(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class AProjZiplineAnchor_C* PendingAnchor; // 0x0E70(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float MaxAnchorDistance; // 0x0E78(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x0E7C(0x0004) MISSED OFFSET
class UPrimalCableComponent* PreviewCable; // 0x0E80(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int Steps; // 0x0E88(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float StepTime; // 0x0E8C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float TracesPerCentimeter; // 0x0E90(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData01[0x4]; // 0x0E94(0x0004) MISSED OFFSET
class UParticleSystemComponent* PreviewEmitter; // 0x0E98(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UParticleSystem* PreviewEmitterParticle; // 0x0EA0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector PreviewHitLocation; // 0x0EA8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PreviewInterpSpeed; // 0x0EB4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* PreviewMeshComp; // 0x0EB8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator NewVar; // 0x0EC0(0x000C) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float MinAnchorDistance; // 0x0ECC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool PreviewHitValid; // 0x0ED0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData02[0x7]; // 0x0ED1(0x0007) MISSED OFFSET
class UMaterialInstanceDynamic* PreviewCableMID; // 0x0ED8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool UsePreviewColorChange; // 0x0EE0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData03[0x7]; // 0x0EE1(0x0007) MISSED OFFSET
class UMaterialInstanceDynamic* PreviewMeshMID; // 0x0EE8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool Temp_bool_IsClosed_Variable; // 0x0EF0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_IsClosed_Variable2; // 0x0EF1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_Has_Been_Initd_Variable; // 0x0EF2(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_Has_Been_Initd_Variable2; // 0x0EF3(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_Whether_the_gate_is_currently_open_or_close_Variable;// 0x0EF4(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_Has_Been_Initd_Variable3; // 0x0EF5(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData04[0x2]; // 0x0EF6(0x0002) MISSED OFFSET
class APlayerController* CallFunc_GetOwnerController_ReturnValue; // 0x0EF8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController; // 0x0F00(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast_CastSuccess; // 0x0F08(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsLocallyOwned_ReturnValue; // 0x0F09(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_IsClosed_Variable3; // 0x0F0A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData05[0x5]; // 0x0F0B(0x0005) MISSED OFFSET
struct UObject_FTransform CallFunc_AddComponent_RelativeTransform_AddComponentDefaultTransform;// 0x0F10(0x0030) (Transient, DuplicateTransient, IsPlainOldData)
struct UObject_FTransform CallFunc_AddComponent_RelativeTransform2_AddComponentDefaultTransform;// 0x0F40(0x0030) (Transient, DuplicateTransient, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass WeapCrossbow_Zipline.WeapCrossbow_Zipline_C");
return ptr;
}
void STATIC_ZiplineObstructionTrace(const struct FVector& Start, bool* Hit);
void BPHandleMeleeAttack();
void IsValidHitLocationForAttachment(struct FHitResult* Hit, bool* IsValidHit);
bool BPWeaponCanFire();
void Get_ZipProjectile_Default_Object(class AProjZiplineAnchor_C** AsProjArrow_Zipline_Bolt_C);
void Update_Preview_Cable();
void ReceiveTick(float* DeltaSeconds);
void ReceiveDestroyed();
void UserConstructionScript();
void ReloadNow();
void ResetReload();
void NoPlacementNoti();
void BPFiredWeapon();
void ExecuteUbergraph_WeapCrossbow_Zipline(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 95.538462 | 236 | 0.560271 | 2bite |
efc54fffed30f34b1306377ae37acada8fc33496 | 1,638 | hpp | C++ | Source/Console/ConsoleDefinition.hpp | gunstarpl/Game-Engine-12-2013 | bfc53f5c998311c17e97c1b4d65792d615c51d36 | [
"MIT",
"Unlicense"
] | 6 | 2017-12-31T17:28:40.000Z | 2021-12-04T06:11:34.000Z | Source/Console/ConsoleDefinition.hpp | gunstarpl/Game-Engine-12-2013 | bfc53f5c998311c17e97c1b4d65792d615c51d36 | [
"MIT",
"Unlicense"
] | null | null | null | Source/Console/ConsoleDefinition.hpp | gunstarpl/Game-Engine-12-2013 | bfc53f5c998311c17e97c1b4d65792d615c51d36 | [
"MIT",
"Unlicense"
] | null | null | null | #pragma once
#include "Precompiled.hpp"
//
// Console Definition
// Base class used by console variable/command classes.
//
class ConsoleDefinition : public NonCopyable
{
protected:
ConsoleDefinition(std::string name, std::string description);
public:
virtual ~ConsoleDefinition();
// Called when a definition has been executed in the console.
virtual void Execute(std::string arguments) = 0;
// Accessor methods.
std::string GetName() const
{
return m_name;
}
std::string GetDescription() const
{
return m_description;
}
bool HasExecuted() const
{
return m_executed;
}
bool HasChanged() const
{
return m_changed;
}
protected:
// Sets intermediate states.
void Executed();
void Changed();
// Resets intermediate states.
void ResetIntermediateState();
private:
std::string m_name;
std::string m_description;
bool m_executed;
bool m_changed;
public:
// Use this string as a name to mark definition as internal.
static const char* Internal;
// Call at the very beginning of main() to finalize
// static instances of this class, so static and normal
// instanced can be distinguished.
static void FinalizeStatic();
private:
// Allow console system to register static definitions.
friend class ConsoleSystem;
// List of static definitions that were created
// before the console system has been initialized.
ConsoleDefinition* m_staticNext;
static ConsoleDefinition* m_staticHead;
static bool m_staticDone;
};
| 21.552632 | 65 | 0.666667 | gunstarpl |
efcd134f4ff70b0892b244d57fab43f0fd97c732 | 882 | cpp | C++ | src/engine/keen/vorticon/ai/CDoor.cpp | rikimbo/Commander-Genius | 0b56993f4c36be8369cfd48f15aa2b9ee74a734d | [
"X11"
] | 137 | 2015-01-01T21:04:51.000Z | 2022-03-30T01:41:10.000Z | src/engine/keen/vorticon/ai/CDoor.cpp | rikimbo/Commander-Genius | 0b56993f4c36be8369cfd48f15aa2b9ee74a734d | [
"X11"
] | 154 | 2015-01-01T16:34:39.000Z | 2022-01-28T14:14:45.000Z | src/engine/keen/vorticon/ai/CDoor.cpp | rikimbo/Commander-Genius | 0b56993f4c36be8369cfd48f15aa2b9ee74a734d | [
"X11"
] | 35 | 2015-03-24T02:20:54.000Z | 2021-05-13T11:44:22.000Z | #include "CDoor.h"
#include "graphics/GsGraphics.h"
CDoor::CDoor(CMap *pmap, Uint32 x, Uint32 y, Uint32 doorspriteID):
CVorticonSpriteObject(pmap, x, y, OBJ_DOOR, 0)
{
mSpriteIdx=doorspriteID;
GsSprite &Doorsprite = gGraphics.getSprite(mSprVar,mSpriteIdx);
timer = 0;
Doorsprite.setHeight(32);
inhibitfall = true;
x = getXPosition()>>CSF;
y = getYPosition()>>CSF;
mpMap->redrawAt(x, y);
mpMap->redrawAt(x, y+1);
}
void CDoor::process()
{
GsSprite &Doorsprite = gGraphics.getSprite(mSprVar,mSpriteIdx);
if (timer > DOOR_OPEN_SPEED)
{
// TODO: Create a flag for mods in which the door can be opened in another direction
//if (DoorOpenDir==DOWN)
moveDown(1<<STC);
Doorsprite.setHeight(Doorsprite.getHeight()-1);
timer = 0;
if (Doorsprite.getHeight() == 0)
{
exists = false;
return;
}
}
else timer++;
}
| 23.210526 | 87 | 0.660998 | rikimbo |
efce684ab6546a13268fe406728c7f1d9dac2484 | 2,471 | cpp | C++ | sc-memory/unit_tests/sc-memory/units/test_python.cpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | sc-memory/unit_tests/sc-memory/units/test_python.cpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | sc-memory/unit_tests/sc-memory/units/test_python.cpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | 1 | 2021-12-03T13:20:18.000Z | 2021-12-03T13:20:18.000Z | /*
* This source file is part of an OSTIS project. For the latest info, see http://ostis.net
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#include <thread>
#include "test_defines.hpp"
#include "catch2/catch.hpp"
#include "sc-test-framework/sc_test_unit.hpp"
#include "sc-memory/python/sc_python_interp.hpp"
#include "sc-memory/python/sc_python_service.hpp"
TEST_CASE("Python_interp", "[test python]")
{
test::ScTestUnit::InitMemory("sc-memory.ini", "");
SECTION("common")
{
SUBTEST_START("common")
{
try
{
py::ScPythonInterpreter::AddModulesPath(SC_TEST_KPM_PYTHON_PATH);
py::DummyService testService("sc_tests/test_main.py");
testService.Run();
while (testService.IsRun())
std::this_thread::sleep_for(std::chrono::milliseconds(10));
testService.Stop();
} catch (...)
{
SC_LOG_ERROR("Test \"common\" failed")
}
}
SUBTEST_END()
}
test::ScTestUnit::ShutdownMemory(false);
}
TEST_CASE("Python_clean", "[test python]")
{
test::ScTestUnit::InitMemory("sc-memory.ini", "");
try
{
py::ScPythonInterpreter::AddModulesPath(SC_TEST_KPM_PYTHON_PATH);
volatile bool passed = true;
std::vector<std::unique_ptr<std::thread>> threads;
size_t const numTests = 50;
threads.resize(numTests);
for (size_t i = 0; i < numTests; ++i)
{
threads[i].reset(
new std::thread([&passed]()
{
py::DummyService testService("sc_tests/test_dummy.py");
try
{
testService.Run();
}
catch (utils::ScException const & ex)
{
SC_LOG_ERROR(ex.Message());
passed = false;
}
catch (...)
{
SC_LOG_ERROR("Unknown error");
passed = false;
}
}));
}
for (auto const & t : threads)
t->join();
REQUIRE(passed);
} catch (...)
{
SC_LOG_ERROR("Test \"Python_clean\" failed")
}
test::ScTestUnit::ShutdownMemory(false);
}
| 26.858696 | 89 | 0.511938 | kroschenko |
efd23bca15c3960369a78a0940a30f1313a5aac6 | 1,009 | cpp | C++ | jsUnits/jsVelocityResponseSpectrum.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsVelocityResponseSpectrum.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsVelocityResponseSpectrum.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 DNV AS
//
// 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 <jsUnits/jsVelocityResponseSpectrum.h>
#include <jsUnits/jsUnitClass.h>
#include <Units/VelocityResponseSpectrum.h>
#include "jsKinematicViscosity.h"
using namespace DNVS::MoFa::Units;
Runtime::DynamicPhenomenon jsVelocityResponseSpectrum::GetPhenomenon()
{
return VelocityResponseSpectrumPhenomenon();
}
void jsVelocityResponseSpectrum::init(jsTypeLibrary& typeLibrary)
{
jsUnitClass<jsVelocityResponseSpectrum,DNVS::MoFa::Units::VelocityResponseSpectrum> cls(typeLibrary);
if(cls.reinit()) return;
cls.ImplicitConstructorConversion(&jsUnitClass<jsVelocityResponseSpectrum,DNVS::MoFa::Units::VelocityResponseSpectrum>::ConstructEquivalentQuantity<jsKinematicViscosity>);
cls.ImplicitConstructorConversion([](const jsVelocityResponseSpectrum& val) {return KinematicViscosity(val); });
}
| 37.37037 | 174 | 0.800793 | dnv-opensource |
efd6998e3ce22d79dddd9d58a4a7fdf8e7051153 | 5,842 | cpp | C++ | MfgToolLib/HidDevice.cpp | Koltak/mfgtools | 02d9e639ceeda38be0184f3b697a126c5d3f03e7 | [
"BSD-3-Clause"
] | null | null | null | MfgToolLib/HidDevice.cpp | Koltak/mfgtools | 02d9e639ceeda38be0184f3b697a126c5d3f03e7 | [
"BSD-3-Clause"
] | null | null | null | MfgToolLib/HidDevice.cpp | Koltak/mfgtools | 02d9e639ceeda38be0184f3b697a126c5d3f03e7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2009-2014, 2016 Freescale Semiconductor, Inc.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of the Freescale Semiconductor nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "stdafx.h"
#include "HidDevice.h"
//#include "logmgr.h"
//#include <Assert.h>
HidDevice::HidDevice(DeviceClass * deviceClass, DEVINST devInst, CString path, INSTANCE_HANDLE handle)
: Device(deviceClass, devInst, path, handle)
, _status(CSW_CMD_PASSED)
, _pReadReport(NULL)
, _pWriteReport(NULL)
, _chipFamily(ChipUnknown)
, _habType(HabUnknown)
{
memset(&_Capabilities, 0, sizeof(_Capabilities));
INT32 err = AllocateIoBuffers();
if (err != ERROR_SUCCESS)
{
TRACE(_T("HidDevice::InitHidDevie() AllocateIoBuffers fail!\r\n"));
}
}
HidDevice::~HidDevice(void)
{
FreeIoBuffers();
}
void HidDevice::FreeIoBuffers()
{
if(_pReadReport)
{
free(_pReadReport);
_pReadReport = NULL;
}
if(_pWriteReport)
{
free(_pWriteReport);
_pWriteReport = NULL;
}
}
typedef UINT (CALLBACK* LPFNDLLFUNC1)(HANDLE, PVOID);
typedef UINT (CALLBACK* LPFNDLLFUNC2)(PVOID);
// Modiifes _Capabilities member variable
// Modiifes _pReadReport member variable
// Modiifes _pWriteReport member variable
INT32 HidDevice::AllocateIoBuffers()
{
INT32 error = ERROR_SUCCESS;
return ERROR_SUCCESS;
}
void CALLBACK HidDevice::IoCompletion(DWORD dwErrorCode, // completion code
DWORD dwNumberOfBytesTransfered, // number of bytes transferred
LPOVERLAPPED lpOverlapped) // pointer to structure with I/O information
{
HidDevice* pDevice = dynamic_cast<HidDevice*>((HidDevice*)lpOverlapped->hEvent);
switch (dwErrorCode)
{
case 0:
break;
default:
TRACE(_T(" HidDevice::IoCompletion() 0x%x - Undefined Error(%x).\r\n"), pDevice, dwErrorCode);
break;
}
}
UINT32 HidDevice::SendCommand(StApi& api, UINT8* additionalInfo)
{
return ERROR_SUCCESS;
}
bool HidDevice::ProcessWriteCommand(const HANDLE hDevice, const StApi& api, NotifyStruct& nsInfo)
{
return true;
}
bool HidDevice::ProcessReadStatus(const HANDLE hDevice, const StApi& api, NotifyStruct& nsInfo)
{
return true;
}
// Changes data in pApi parameter, therefore must use 'StAp&*' instead of 'const StApi&'
bool HidDevice::ProcessReadData(const HANDLE hDevice, StApi* pApi, NotifyStruct& nsInfo)
{
return true;
}
bool HidDevice::ProcessWriteData(const HANDLE hDevice, const StApi& api, NotifyStruct& nsInfo)
{
return true;
}
INT32 HidDevice::ProcessTimeOut(const INT32 timeout)
{
return ERROR_SUCCESS;
}
CString HidDevice::GetSendCommandErrorStr()
{
CString msg;
switch ( _status )
{
case CSW_CMD_PASSED:
msg.Format(_T("HID Status: PASSED(0x%02X)\r\n"), _status);
break;
case CSW_CMD_FAILED:
msg.Format(_T("HID Status: FAILED(0x%02X)\r\n"), _status);
break;
case CSW_CMD_PHASE_ERROR:
msg.Format(_T("HID Status: PHASE_ERROR(0x%02X)\r\n"), _status);
break;
default:
msg.Format(_T("HID Status: UNKNOWN(0x%02X)\r\n"), _status);
}
return msg;
}
UINT32 HidDevice::ResetChip()
{
api::HidDeviceReset api;
return SendCommand(api);
}
HidDevice::ChipFamily_t HidDevice::GetChipFamily()
{
if ( _chipFamily == Unknown )
{
CString devPath = UsbDevice()->_path.get();
devPath.MakeUpper();
if ( devPath.Find(_T("VID_066F&PID_3780")) != -1 )
{
_chipFamily = MX23;
}
else if ( devPath.Find(_T("VID_15A2&PID_004F")) != -1 )
{
_chipFamily = MX28;
}
}
return _chipFamily;
}
//-------------------------------------------------------------------------------------
// Function to get HAB_TYPE value
//
// @return
// HabEnabled: if is prodction
// HabDisabled: if is development/disable
//-------------------------------------------------------------------------------------
HidDevice::HAB_t HidDevice::GetHABType(ChipFamily_t chipType)
{
HAB_t habType = HabUnknown;
return habType;
}
DWORD HidDevice::GetHabType()
{
_chipFamily = GetChipFamily();
if(_chipFamily == MX28)
{
if(_habType == HabUnknown)
_habType = GetHABType(_chipFamily);
}
return _habType;
}
| 27.952153 | 116 | 0.657994 | Koltak |
efe1ffe86c38e44a2b6a41ac546f963c1b6da326 | 456 | cpp | C++ | Selection Sort.cpp | Gayane05/Algorithms-Design_Patterns | 9cba4b1b2018ae27a24f52b1e09ef037b9742f48 | [
"MIT"
] | null | null | null | Selection Sort.cpp | Gayane05/Algorithms-Design_Patterns | 9cba4b1b2018ae27a24f52b1e09ef037b9742f48 | [
"MIT"
] | null | null | null | Selection Sort.cpp | Gayane05/Algorithms-Design_Patterns | 9cba4b1b2018ae27a24f52b1e09ef037b9742f48 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
void SelectionSort(std::vector<T>& vec)
{
for (int i = 1; i < vec.size() - 1; ++i)
{
int min = i;
for (int j = i + 1; j < vec.size(); ++j)
{
if (vec[j] < vec[min])
{
min = j;
}
std::swap(vec[j], vec[min]);
}
}
}
int main()
{
std::vector<char> nums { 'c', 't', 'f', 'g', 'j' };
SelectionSort(nums);
return 0;
}
| 14.709677 | 53 | 0.482456 | Gayane05 |
efe47232b045b326e4802e9f1ae56254de9769e4 | 804 | cpp | C++ | 851-loud-and-rich/851-loud-and-rich.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | 2 | 2022-01-02T19:15:00.000Z | 2022-01-05T21:12:24.000Z | 851-loud-and-rich/851-loud-and-rich.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | null | null | null | 851-loud-and-rich/851-loud-and-rich.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | 1 | 2022-03-11T17:11:07.000Z | 2022-03-11T17:11:07.000Z | class Solution {
public:
vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
int n = quiet.size();
vector<vector<int>> graph(n);
for(auto i : richer)
graph[i[1]].push_back(i[0]);
vector<bool> visited(n, false);
vector<int> ans(n);
for(int i = 0; i < n; i++)
if(!visited[i])
dfs(i, visited, ans, quiet, graph);
return ans;
}
int dfs(int i, vector<bool> &visited, vector<int> &ans, vector<int> &quiet, vector<vector<int>> &graph)
{
if(visited[i])
return ans[i];
int tmp = i;
for(auto j : graph[i])
{
int tmp2 = dfs(j, visited, ans, quiet, graph);
if(quiet[tmp] > quiet[tmp2])
tmp = tmp2;
}
visited[i] = true;
return ans[i] = tmp;
}
}; | 22.971429 | 103 | 0.529851 | Ananyaas |
efe5cac533b77730bea13363d24a1c4e9ff18347 | 2,851 | cpp | C++ | libraries/picosystem.cpp | Gadgetoid/picosystem | 52890ea5c8e15a605889c7f5103e1ee97202d61c | [
"MIT"
] | null | null | null | libraries/picosystem.cpp | Gadgetoid/picosystem | 52890ea5c8e15a605889c7f5103e1ee97202d61c | [
"MIT"
] | null | null | null | libraries/picosystem.cpp | Gadgetoid/picosystem | 52890ea5c8e15a605889c7f5103e1ee97202d61c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <cstdlib>
#include <math.h>
#include "picosystem.hpp"
namespace picosystem {
color_t _pen;
int32_t _tx = 0, _ty = 0;
int32_t _camx = 0, _camy = 0;
uint32_t _io = 0, _lio = 0;
blend_func_t _bf = BLEND;
#ifdef PIXEL_DOUBLE
color_t _fb[120 * 120];
buffer_t SCREEN{.w = 120, .h = 120, .data = _fb};
int32_t _cx = 0, _cy = 0, _cw = 120, _ch = 120;
#else
color_t _fb[240 * 240];
buffer_t SCREEN{.w = 240, .h = 240, .data = _fb};
int32_t _cx = 0, _cy = 0, _cw = 240, _ch = 240;
#endif
buffer_t &_dt = SCREEN;
#ifdef NO_SPRITESHEET
buffer_t *_ss = nullptr;
#else
buffer_t SPRITESHEET{.w = 128, .h = 128, .data = _default_sprite_sheet};
buffer_t *_ss = &SPRITESHEET;
#endif
#ifdef NO_FONT
uint8_t *_font = nullptr;
#else
uint8_t *_font = &_default_font[0][0];
#endif
}
using namespace picosystem;
// main entry point - the users' code will be automatically
// called when they implement the init(), update(), and render()
// functions in their project
int main() {
_init_hardware();
// setup lut for fast sin/cos functions
for(uint32_t i = 0; i < 256; i++) {
_fsin_lut[i] = sin((_PI * 2.0f) * (float(i) / 256.0f));
}
#ifndef NO_STARTUP_LOGO
// fade in logo by ramping up backlight
pen(0, 0, 0); clear();
pen(15, 15, 15); _logo();
for(int i = 0; i < 75; i++) {
backlight(i);
_wait_vsync();
_flip();
}
sleep(300); // ...and breathe out...
// fade out logo in 16 colour steps
for(int i = 15; i >= 0; i--) {
pen(0, 0, 0); clear();
pen(i, i, i); _logo();
_wait_vsync();
_flip();
sleep(20);
}
#else
backlight(75);
#endif
sleep(300);
pen(0, 0, 0); clear();
// call users init() function so they can perform any needed
// setup for world state etc
init();
uint32_t update_rate_ms = 10;
uint32_t pending_update_ms = 0;
uint32_t last_ms = time();
uint32_t tick = 0;
_io = _gpio_get();
while(true) {
uint32_t ms = time();
// work out how many milliseconds of updates we're waiting
// to process and then call the users update() function as
// many times as needed to catch up
pending_update_ms += (ms - last_ms);
while(pending_update_ms >= update_rate_ms) {
_lio = _io;
_io = _gpio_get();
update(tick++);
pending_update_ms -= update_rate_ms;
}
// if current flipping the framebuffer in the background
// then wait until that is complete before allow the user
// to render
while(_is_flipping()) {}
// call user render function to draw world
draw();
// wait for the screen to vsync before triggering flip
// to ensure no tearing
_wait_vsync();
// flip the framebuffer to the screen
_flip();
last_ms = ms;
}
} | 21.598485 | 76 | 0.603297 | Gadgetoid |
efe9558965689a612351a7590523cf9f7e51ca72 | 2,420 | hpp | C++ | src/Kommunikationsstelle.hpp | Raspi64/imgui_setup | 3d2a53211d26805c4851e3e28a9b2d6f02df1db8 | [
"MIT"
] | 1 | 2021-05-04T07:30:41.000Z | 2021-05-04T07:30:41.000Z | src/Kommunikationsstelle.hpp | Raspi64/raspi64 | 3d2a53211d26805c4851e3e28a9b2d6f02df1db8 | [
"MIT"
] | 3 | 2020-11-21T17:49:13.000Z | 2020-12-18T14:21:17.000Z | src/Kommunikationsstelle.hpp | Raspi64/raspi64 | 3d2a53211d26805c4851e3e28a9b2d6f02df1db8 | [
"MIT"
] | 3 | 2020-10-27T14:13:28.000Z | 2020-12-18T14:16:07.000Z | //
// Created by simon on 12/1/20.
//
#ifndef IMGUI_SETUP_KOMMUNIKATIONSSTELLE_HPP
#define IMGUI_SETUP_KOMMUNIKATIONSSTELLE_HPP
#include <string>
#include <Gui.hpp>
#include <Plugin.hpp>
class Kommunikationsstelle {
public:
static void init(Gui *, LANG);
enum Status {
NOT_STARTED, // No program has been executed so far
LOADING, // The user-program is currently loading/parsing
LOAD_ERROR, // The user-program could not be loaded
RUNNING, // The user-program is currently running
RUN_ERROR, // There was an error when running the user-program
KILLED, // The program was stopped in mid-execution
COMPLETED_OK, // Program has exited successfully
};
static void set_language(LANG lang);
static bool start_script(const std::string &script);
static void kill_current_task();
static void save(const std::string &name, const std::string &text);
static std::string load(const std::string &name);
static bool handle_command(std::string command);
static void on_key_press(SDL_Keysym keysym);
static void on_key_release(SDL_Keysym keysym);
static Entry *get_common_help_root();
static Entry *get_language_help_root();
static std::vector<Entry *> search_entries(const std::string &searchword);
static void gui_draw_rect(TGraphicRect rect);
static void gui_draw_circle(TGraphicCircle circle);
static void gui_draw_line(TGraphicLine line);
static void gui_draw_text(TGraphicText text);
static void gui_draw_pixel(TGraphicPixel pixel);
static void gui_clear();
static void gui_print(const std::string &message);
static void on_error(int line, const std::string &message);
static std::string get_input_line();
static Kommunikationsstelle::Status status;
private:
static std::string base_path;
static Gui *gui;
static Plugin *interpreter;
static pthread_t exec_thread;
static bool waiting_for_input;
static std::string input;
static bool input_ready;
static void *exec_script(void *params_void);
static Plugin *get_interpreter(LANG language);
static Entry help_root_entry;
static void sort_subtrees(std::vector<Entry> *entries);
static std::string get_key_name(const SDL_Keysym &keysym);
static void delete_file(const std::string &basicString);
};
#endif //IMGUI_SETUP_KOMMUNIKATIONSSTELLE_HPP
| 25.208333 | 78 | 0.721074 | Raspi64 |
efef5493997fd4276533446b75110b7c76c62411 | 1,487 | cpp | C++ | Graph/networkdelaytime.cpp | thisisnitish/cp-dsa | 6a00f1d60712115f70c346cee238ad1730e6c39e | [
"MIT"
] | 4 | 2020-12-29T09:27:10.000Z | 2022-02-12T14:20:23.000Z | Graph/networkdelaytime.cpp | thisisnitish/cp-dsa | 6a00f1d60712115f70c346cee238ad1730e6c39e | [
"MIT"
] | 1 | 2021-11-27T06:15:28.000Z | 2021-11-27T06:15:28.000Z | Graph/networkdelaytime.cpp | thisisnitish/cp-dsa | 6a00f1d60712115f70c346cee238ad1730e6c39e | [
"MIT"
] | 1 | 2021-11-17T21:42:57.000Z | 2021-11-17T21:42:57.000Z | /*
Leetcode Question 743. Network Delay Time
https://leetcode.com/problems/network-delay-time/
*/
class Solution
{
public:
/*the basic idea is that indirectly the question itself is asking single
source shortest path, so we can apply dijsktra's algorithm.
Time: O(ElogV)*/
int networkDelayTime(vector<vector<int> > ×, int n, int k)
{
vector<vector<pair<int, int> > > adj(n + 1);
for (auto edge : times)
{
adj[edge[0]].push_back(make_pair(edge[1], edge[2]));
}
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
vector<int> distance(n + 1, INT_MAX);
distance[k] = 0;
pq.push(make_pair(0, k));
while (!pq.empty())
{
int u = pq.top().second;
pq.pop();
for (auto neighbour : adj[u])
{
int v = neighbour.first;
int weight = neighbour.second;
if (distance[v] > distance[u] + weight)
{
distance[v] = distance[u] + weight;
pq.push(make_pair(distance[v], v));
}
}
}
//since we want the maximum from the distance
int result = 0;
for (int i = 1; i <= n; i++)
{
if (distance[i] == INT_MAX)
return -1;
result = max(result, distance[i]);
}
return result;
}
}; | 26.553571 | 94 | 0.494956 | thisisnitish |
eff5d5ffbf67b5ff6da2cfa3e4b6b7e9e7aa478d | 933 | cpp | C++ | aws-cpp-sdk-eks/source/model/DeleteAddonRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-eks/source/model/DeleteAddonRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-eks/source/model/DeleteAddonRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/eks/model/DeleteAddonRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::EKS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
DeleteAddonRequest::DeleteAddonRequest() :
m_clusterNameHasBeenSet(false),
m_addonNameHasBeenSet(false),
m_preserve(false),
m_preserveHasBeenSet(false)
{
}
Aws::String DeleteAddonRequest::SerializePayload() const
{
return {};
}
void DeleteAddonRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_preserveHasBeenSet)
{
ss << m_preserve;
uri.AddQueryStringParameter("preserve", ss.str());
ss.str("");
}
}
| 20.733333 | 69 | 0.714898 | perfectrecall |
eff649fba127a39df62f8e4763b5d469c27ab2cf | 5,898 | cc | C++ | tensorflow_serving/servables/feature/feature_transformer.cc | ydp/serving | a3102b03a3435a645e64d28de67b45e9162a8a8c | [
"Apache-2.0"
] | 6 | 2018-03-20T19:58:10.000Z | 2020-11-23T09:29:04.000Z | tensorflow_serving/servables/feature/feature_transformer.cc | ydp/serving | a3102b03a3435a645e64d28de67b45e9162a8a8c | [
"Apache-2.0"
] | null | null | null | tensorflow_serving/servables/feature/feature_transformer.cc | ydp/serving | a3102b03a3435a645e64d28de67b45e9162a8a8c | [
"Apache-2.0"
] | null | null | null | #include "tensorflow_serving/servables/feature/feature_transformer.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/types.h"
#include "rapidjson/error/en.h"
#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb.h"
namespace tensorflow {
namespace serving {
FeatureTransformer::~FeatureTransformer() {}
Status FeatureTransformer::LoadTfExampleConf(string path) {
const string file = io::JoinPath(path, "features.conf");
std::unique_ptr<RandomAccessFile> f;
TF_RETURN_IF_ERROR(Env::Default()->NewRandomAccessFile(file, &f));
const size_t kBufferSizeBytes = 262144;
io::InputBuffer in(f.get(), kBufferSizeBytes);
string line;
while (in.ReadLine(&line).ok()) {
if (line.size() > 2 &&
line[0] == '#' &&
line[1] != '#') {
std::vector<string> cols = str_util::Split(line, '\t');
if (cols.size() != 4) {
return errors::InvalidArgument("features.conf not have 4 cols.");
}
const string& name = cols[0].substr(1);
const string& opType = cols[1];
const string& oper = cols[2];
const string& args = cols[3];
rapidjson::MemoryStream ms(args.data(), args.size());
rapidjson::EncodedInputStream<rapidjson::UTF8<>, rapidjson::MemoryStream>
jsonstream(ms);
rapidjson::Document doc;
if (doc.ParseStream<rapidjson::kParseNanAndInfFlag>(jsonstream)
.HasParseError()) {
return errors::InvalidArgument(
"JSON Parse error: ", rapidjson::GetParseError_En(doc.GetParseError()),
" at offset: ", doc.GetErrorOffset());
}
if (!doc.IsObject()) {
return errors::InvalidArgument("expected json to an object.");
}
FeatureNode node;
node.name = name;
node.opType = opType;
if (oper == "tffeaturecolumn") {
ParseFeatureColumn(doc, node);
} else if (oper == "pickcats") {
ParsePickcats(doc, node);
}
feature_nodes_.emplace_back(node);
}
}
return Status::OK();
}
Status FeatureTransformer::ParseFeatureColumn(const rapidjson::Document& doc,
FeatureNode& node) {
rapidjson::Value::ConstMemberIterator itor;
itor = doc.FindMember("type");
if (itor != doc.MemberEnd()) {
node.dataType = itor->value.GetString();
}
itor = doc.FindMember("defaultin");
if (itor != doc.MemberEnd()) {
const string& v = itor->value.GetString();
if (node.dataType == "float") {
node.defaultVal.fval = atof(v.c_str());
} else if (node.dataType == "int") {
node.defaultVal.ival = atoi(v.c_str());
} else if (node.dataType == "string") {
node.defaultVal.sval = v;
} else {
return errors::InvalidArgument("unsupported data type.");
}
}
return Status::OK();
}
Status FeatureTransformer::ParsePickcats(const rapidjson::Document& doc,
FeatureNode& node) {
rapidjson::Value::ConstMemberIterator itor;
itor = doc.FindMember("rowdelimiter");
if (itor != doc.MemberEnd()) {
node.rowdelimiter = itor->value.GetString();
}
itor = doc.FindMember("coldelimiter");
if (itor != doc.MemberEnd()) {
node.coldelimiter = itor->value.GetString();
}
itor = doc.FindMember("valuetype");
if (itor != doc.MemberEnd()) {
node.valuetype = itor->value.GetString();
}
itor = doc.FindMember("defaultin");
if (itor != doc.MemberEnd()) {
node.defaultVal.sval = itor->value.GetString();
}
return Status::OK();
}
Status FeatureTransformer::Transform(const rapidjson::Document& doc,
Tensor& example_tensor) {
rapidjson::Value::ConstMemberIterator it = doc.FindMember("input");
if (it == doc.MemberEnd()) {
return errors::InvalidArgument("did not find input field.");
}
if (!it->value.IsArray()) {
return errors::InvalidArgument("input field is not an array.");
}
rapidjson::Value::ConstMemberIterator itor;
for (rapidjson::SizeType i = 0; i < it->value.Size(); ++i) {
const rapidjson::Value& sample = it->value[i];
Example example;
string str_example;
auto features = example.mutable_features();
for (auto& feature_def : feature_nodes_) {
auto& fea = (*features->mutable_feature())[feature_def.name];
itor = sample.FindMember(feature_def.name.c_str());
if (itor != sample.MemberEnd()) {
const string& v = itor->value.GetString();
if (feature_def.opType == "tffeaturecolumn") {
if (feature_def.dataType == "int") {
fea.mutable_int64_list()->add_value(atoi(v.c_str()));
} else if (feature_def.dataType == "float") {
fea.mutable_float_list()->add_value(atof(v.c_str()));
} else if (feature_def.dataType == "string") {
fea.mutable_bytes_list()->add_value(v);
}
} else if (feature_def.opType == "pickcats") {
// TODO
}
} else {
if (feature_def.dataType == "int") {
fea.mutable_int64_list()->add_value(feature_def.defaultVal.ival);
} else if (feature_def.dataType == "float") {
fea.mutable_float_list()->add_value(feature_def.defaultVal.fval);
} else if (feature_def.dataType == "string") {
fea.mutable_bytes_list()->add_value(feature_def.defaultVal.sval);
}
}
} // for feature_nodes_
// LOG(INFO) << example.DebugString().c_str();
example.SerializeToString(&str_example);
example_tensor.flat<string>()(i) = str_example;
example.Clear();
str_example.clear();
} // for it->value
return Status::OK();
}
} // namespace serving
} // namespace tensorflow
| 35.963415 | 81 | 0.626823 | ydp |
eff977b4191397ec7902a88c7b8c346e4efb6f7d | 2,567 | cpp | C++ | TC647 - 1000.cpp | therainmak3r/dirty-laundry | 39e295e9390b62830bef53282cdcb63716efac45 | [
"MIT"
] | 20 | 2015-12-22T14:14:59.000Z | 2019-10-25T12:14:23.000Z | TC647 - 1000.cpp | therainmak3r/dirty-laundry | 39e295e9390b62830bef53282cdcb63716efac45 | [
"MIT"
] | null | null | null | TC647 - 1000.cpp | therainmak3r/dirty-laundry | 39e295e9390b62830bef53282cdcb63716efac45 | [
"MIT"
] | 2 | 2016-06-27T13:34:08.000Z | 2018-10-02T20:36:54.000Z | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class BuildingTowers
{
public:
long long between(int xi, long long a, int xj, long long b, long long k)
{
if (a > b)
return between(xj,b,xi,a,k);
int available = abs(xj - xi) - 1;
while (a < b)
{
available--;
a += k;
if (available <= 0)
return max(a,b);
}
bool flipper = 1;
while (available > 0)
{
if (flipper)
{
b +=k;
flipper = 0;
}
else
{
a += k;
flipper = 1;
}
available--;
}
return max(a,b);
}
long long maxHeight (int N, int K, vector<int> x, vector<int> t)
{
if (x.size() == 0)
return ((long long)(N-1))*(long long)K;
vector<pair<int,int> > join;
for (int i = 0; i < x.size(); i++)
join.push_back(make_pair(x[i],t[i]));
sort(join.begin(), join.end());
for (int i = 0; i < x.size(); i++)
{
x[i] = join[i].first;
t[i] = join[i].second;
// cout << "i is " << i << " and x[i] is " << x[i] << " and t[i] is " << t[i] << endl;
}
long long ans = between(1,0,x[0],t[0],K);
// cout << "max height with first building is " << ans << endl;
t[0] = min((long long)t[0],(long long)(x[0]-1)*(long long)K);
for (int i = 0; i < x.size() - 1; i++)
{
t[i+1] = min((long long)t[i+1],t[i]+ (long long)(x[i+1]-x[i])*(long long)K);
long long temp = between(x[i],t[i],x[i+1],t[i+1],K);
// cout << " i is " << i << " and max height is " << temp << endl;
ans = max(ans, temp);
}
long long temp = (long long)t[x.size()-1] + (long long)(N-x[x.size()-1])*(long long)K;
// cout << "height with last building is " << temp << endl;
ans = max(ans, temp);
return ans;
}
};
int main()
{
vector<int> x;
x.push_back(2);
/* x.push_back(7);
x.push_back(13);
x.push_back(15);
x.push_back(18);
*/ vector<int> t;
t.push_back(3);
/* t.push_back(22);
t.push_back(1);
t.push_back(55);
t.push_back(42);
*/ BuildingTowers obj;
long long ans = obj.maxHeight(5,4,x,t);
cout << "Final ans is " << ans << endl;
return 0;
}
| 28.522222 | 98 | 0.423062 | therainmak3r |
560a79738fc9fd930f5108100445c7a498b78e80 | 1,622 | cpp | C++ | brainfuck/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | brainfuck/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | brainfuck/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include <limits>
#include "brainfuck.h"
TEST_CASE("Consume") {
REQUIRE(std::is_same_v<Consume<Tape<0, 0, 'a'>>, decltype(std::pair<Char<0>, Tape<0, 'a'>>{})>);
REQUIRE(std::is_same_v<Consume<Tape<0, 'a'>>, decltype(std::pair<Char<'a'>, Tape<0>>{})>);
REQUIRE(std::is_same_v<Consume<Tape<0>>, Error>);
}
TEST_CASE("Produce") {
REQUIRE(std::is_same_v<Produce<'a', Tape<0>>, Tape<0, 'a'>>);
REQUIRE(std::is_same_v<Produce<'a', Tape<0, 'b'>>, Tape<0, 'b', 'a'>>);
}
TEST_CASE("IncrementPos") {
REQUIRE(std::is_same_v<IncrementPos<Tape<0, '0', '0'>>, Tape<1, '0', '0'>>);
REQUIRE(std::is_same_v<IncrementPos<Tape<1, '0', '0'>>, Error>);
REQUIRE(std::is_same_v<IncrementPos<Tape<0, '0'>>, Error>);
REQUIRE(std::is_same_v<IncrementPos<Tape<0>>, Error>);
}
TEST_CASE("DecrementPos") {
REQUIRE(std::is_same_v<DecrementPos<Tape<1, '0', '0'>>, Tape<0, '0', '0'>>);
REQUIRE(std::is_same_v<DecrementPos<Tape<0, 'a', 'b'>>, Error>);
REQUIRE(std::is_same_v<DecrementPos<Tape<0>>, Error>);
}
TEST_CASE("IncrementCell") {
REQUIRE(std::is_same_v<IncrementCell<Tape<1, '0', '0'>>, Tape<1, '0', '1'>>);
REQUIRE(std::is_same_v<IncrementCell<Tape<0, 'a', '0'>>, Tape<0, 'b', '0'>>);
REQUIRE(std::is_same_v<IncrementCell<Tape<0, std::numeric_limits<char>::max()>>, Error>);
}
TEST_CASE("DecrementCell") {
REQUIRE(std::is_same_v<DecrementCell<Tape<1, '0', '9'>>, Tape<1, '0', '8'>>);
REQUIRE(std::is_same_v<DecrementCell<Tape<0, '\1'>>, Tape<0, '\0'>>);
REQUIRE(std::is_same_v<DecrementCell<Tape<0, std::numeric_limits<char>::min()>>, Error>);
}
| 40.55 | 100 | 0.620838 | DenisOstashov |
560df63a041345e0e002b3745ecce37c9cfe24d7 | 3,503 | cpp | C++ | FreeRTOS/cpp11_gcc/thread.cpp | klepsydra-technologies/FreeRTOS_cpp11 | 0676bd7d9667d999c9ba8e377f51771f197359aa | [
"MIT"
] | 66 | 2019-07-23T10:25:36.000Z | 2022-03-24T12:45:03.000Z | FreeRTOS/cpp11_gcc/thread.cpp | klepsydra-technologies/FreeRTOS_cpp11 | 0676bd7d9667d999c9ba8e377f51771f197359aa | [
"MIT"
] | 10 | 2019-10-14T21:25:54.000Z | 2021-03-28T17:39:18.000Z | FreeRTOS/cpp11_gcc/thread.cpp | klepsydra-technologies/FreeRTOS_cpp11 | 0676bd7d9667d999c9ba8e377f51771f197359aa | [
"MIT"
] | 17 | 2019-06-13T03:24:07.000Z | 2022-01-18T00:28:34.000Z | /// Copyright 2021 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#include <thread>
#include <system_error>
#include <cerrno>
#include "FreeRTOS.h"
#include "gthr_key_type.h"
namespace free_rtos_std
{
extern Key *s_key;
} // namespace free_rtos_std
namespace std
{
static void __execute_native_thread_routine(void *__p)
{
__gthread_t local{*static_cast<__gthread_t *>(__p)}; //copy
{ // we own the arg now; it must be deleted after run() returns
thread::_State_ptr __t{static_cast<thread::_State *>(local.arg())};
local.notify_started(); // copy has been made; tell we are running
__t->_M_run();
}
if (free_rtos_std::s_key)
free_rtos_std::s_key->CallDestructor(__gthread_t::self().native_task_handle());
local.notify_joined(); // finished; release joined threads
}
thread::_State::~_State() = default;
void thread::_M_start_thread(_State_ptr state, void (*)())
{
const int err = __gthread_create(
&_M_id._M_thread, __execute_native_thread_routine, state.get());
if (err)
__throw_system_error(err);
state.release();
}
void thread::join()
{
id invalid;
if (_M_id._M_thread != invalid._M_thread)
__gthread_join(_M_id._M_thread, nullptr);
else
__throw_system_error(EINVAL);
// destroy the handle explicitly - next call to join/detach will throw
_M_id = std::move(invalid);
}
void thread::detach()
{
id invalid;
if (_M_id._M_thread != invalid._M_thread)
__gthread_detach(_M_id._M_thread);
else
__throw_system_error(EINVAL);
// destroy the handle explicitly - next call to join/detach will throw
_M_id = std::move(invalid);
}
// Returns the number of concurrent threads supported by the implementation.
// The value should be considered only a hint.
//
// Return value
// Number of concurrent threads supported. If the value is not well defined
// or not computable, returns 0.
unsigned int thread::hardware_concurrency() noexcept
{
return 0; // not computable
}
void this_thread::__sleep_for(chrono::seconds sec, chrono::nanoseconds nsec)
{
long ms = nsec.count() / 1'000'000;
if (sec.count() == 0 && ms == 0 && nsec.count() > 0)
ms = 1; // round up to 1 ms => if sleep time != 0, sleep at least 1ms
vTaskDelay(pdMS_TO_TICKS(chrono::milliseconds(sec).count() + ms));
}
} // namespace std
| 31.845455 | 85 | 0.697688 | klepsydra-technologies |
560f33837d3c3bcaf97b6dc85c652c32a9b3aa39 | 13,402 | cc | C++ | src/libxtp/jobcalculators/iexcitoncl.cc | choudarykvsp/xtp | 9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a | [
"Apache-2.0"
] | 1 | 2018-03-05T17:36:53.000Z | 2018-03-05T17:36:53.000Z | src/libxtp/jobcalculators/iexcitoncl.cc | choudarykvsp/xtp | 9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a | [
"Apache-2.0"
] | null | null | null | src/libxtp/jobcalculators/iexcitoncl.cc | choudarykvsp/xtp | 9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 "iexcitoncl.h"
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <votca/tools/constants.h>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <votca/tools/propertyiomanipulator.h>
#include <votca/ctp/logger.h>
#include <votca/ctp/xinteractor.h>
using namespace boost::filesystem;
using namespace votca::tools;
namespace ub = boost::numeric::ublas;
namespace votca { namespace xtp {
// +++++++++++++++++++++++++++++ //
// IEXCITON MEMBER FUNCTIONS //
// +++++++++++++++++++++++++++++ //
void IEXCITON::Initialize(tools::Property* options ) {
cout << endl
<< "... ... Initialized with " << _nThreads << " threads. "
<< flush;
_maverick = (_nThreads == 1) ? true : false;
_induce= false;
_statenumber=1;
_epsilon=1;
_cutoff=-1;
string key = "options."+Identify();
if ( options->exists(key+".job_file")) {
_jobfile = options->get(key+".job_file").as<string>();
}
else {
throw std::runtime_error("Job-file not set. Abort.");
}
key = "options." + Identify();
if ( options->exists(key+".mapping")) {
_xml_file = options->get(key+".mapping").as<string>();
}
else {
throw std::runtime_error("Mapping-file not set. Abort.");
}
if ( options->exists(key+".emp_file")) {
_emp_file = options->get(key+".emp_file").as<string>();
}
else {
throw std::runtime_error("Emp-file not set. Abort.");
}
if ( options->exists(key+".statenumber")) {
_statenumber=options->get(key+".statenumber").as<int>();
}
else {
cout << endl << "Statenumber not specified, assume singlet s1 " << flush;
_statenumber=1;
}
if ( options->exists(key+".epsilon")) {
_epsilon=options->get(key+".epsilon").as<double>();
}
else{
_epsilon=1;
}
if ( options->exists(key+".cutoff")) {
_cutoff=options->get(key+".cutoff").as<double>();
}
else{
_cutoff=-1;
}
if ( options->exists(key+".induce")) {
_induce = options->get(key+".induce").as<bool>();
}
cout << "done"<< endl;
}
void IEXCITON::PreProcess(ctp::Topology *top) {
// INITIALIZE MPS-MAPPER (=> POLAR TOP PREP)
cout << endl << "... ... Initialize MPS-mapper: " << flush;
_mps_mapper.GenerateMap(_xml_file, _emp_file, top);
}
void IEXCITON::CustomizeLogger(ctp::QMThread *thread) {
// CONFIGURE LOGGER
ctp::Logger* log = thread->getLogger();
log->setReportLevel(ctp::logDEBUG);
log->setMultithreading(_maverick);
log->setPreface(ctp::logINFO, (boost::format("\nT%1$02d INF ...") % thread->getId()).str());
log->setPreface(ctp::logERROR, (boost::format("\nT%1$02d ERR ...") % thread->getId()).str());
log->setPreface(ctp::logWARNING, (boost::format("\nT%1$02d WAR ...") % thread->getId()).str());
log->setPreface(ctp::logDEBUG, (boost::format("\nT%1$02d DBG ...") % thread->getId()).str());
}
ctp::Job::JobResult IEXCITON::EvalJob(ctp::Topology *top, ctp::Job *job, ctp::QMThread *opThread) {
// report back to the progress observer
ctp::Job::JobResult jres = ctp::Job::JobResult();
// get the logger from the thread
ctp::Logger* pLog = opThread->getLogger();
// get the information about the job executed by the thread
int _job_ID = job->getId();
Property _job_input = job->getInput();
list<Property*> segment_list = _job_input.Select( "segment" );
int ID_A = segment_list.front()->getAttribute<int>( "id" );
string type_A = segment_list.front()->getAttribute<string>( "type" );
string mps_fileA = segment_list.front()->getAttribute<string>( "mps_file" );
int ID_B = segment_list.back()->getAttribute<int>( "id" );
string type_B = segment_list.back()->getAttribute<string>( "type" );
string mps_fileB = segment_list.back()->getAttribute<string>( "mps_file" );
ctp::Segment *seg_A = top->getSegment( ID_A );
assert( seg_A->getName() == type_A );
ctp::Segment *seg_B = top->getSegment( ID_B );
assert( seg_B->getName() == type_B );
CTP_LOG(ctp::logINFO,*pLog) << ctp::TimeStamp() << " Evaluating pair "
<< _job_ID << " [" << ID_A << ":" << ID_B << "]" << flush;
vector<ctp::APolarSite*> seg_A_raw=ctp::APS_FROM_MPS(mps_fileA,0,opThread);
vector<ctp::APolarSite*> seg_B_raw=ctp::APS_FROM_MPS(mps_fileB,0,opThread);
ctp::PolarSeg* seg_A_polar=_mps_mapper.MapPolSitesToSeg(seg_A_raw,seg_A);
ctp::PolarSeg* seg_B_polar=_mps_mapper.MapPolSitesToSeg(seg_B_raw,seg_B);
double JAB=EvaluatePair(top,seg_A_polar,seg_B_polar, pLog);
std::vector< ctp::APolarSite* >::iterator it;
for (it = seg_A_raw.begin() ; it !=seg_A_raw.end(); ++it){
delete *it;
}
seg_A_raw.clear();
for (it = seg_B_raw.begin() ; it !=seg_B_raw.end(); ++it){
delete *it;
}
seg_B_raw.clear();
delete seg_A_polar;
delete seg_B_polar;
Property _job_summary;
Property *_job_output = &_job_summary.add("output","");
Property *_pair_summary = &_job_output->add("pair","");
string nameA = seg_A->getName();
string nameB = seg_B->getName();
_pair_summary->setAttribute("idA", ID_A);
_pair_summary->setAttribute("idB", ID_B);
_pair_summary->setAttribute("typeA", nameA);
_pair_summary->setAttribute("typeB", nameB);
Property *_coupling_summary = &_pair_summary->add("Coupling","");
_coupling_summary->setAttribute("jABstatic", JAB);
jres.setOutput( _job_summary );
jres.setStatus(ctp::Job::COMPLETE);
return jres;
}
double IEXCITON::EvaluatePair(ctp::Topology *top,ctp::PolarSeg* Seg1,ctp::PolarSeg* Seg2, ctp::Logger* pLog ){
ctp::XInteractor actor;
actor.ResetEnergy();
Seg1->CalcPos();
Seg2->CalcPos();
vec s=top->PbShortestConnect(Seg1->getPos(),Seg2->getPos())+Seg1->getPos()-Seg2->getPos();
//CTP_LOG(logINFO, *pLog) << "Evaluate pair for debugging " << Seg1->getId() << ":" <<Seg2->getId() << " Distance "<< abs(s) << flush;
ctp::PolarSeg::iterator pit1;
ctp::PolarSeg::iterator pit2;
double E=0.0;
for (pit1=Seg1->begin();pit1<Seg1->end();++pit1){
for (pit2=Seg2->begin();pit2<Seg2->end();++pit2){
actor.BiasIndu(*(*pit1), *(*pit2),s);
(*pit1)->Depolarize();
(*pit2)->Depolarize();
E += actor.E_f(*(*pit1), *(*pit2));
}
}
if(_cutoff>=0){
if(abs(s)>_cutoff){
E=E/_epsilon;
}
}
return E*conv::int2eV;
}
void IEXCITON::WriteJobFile(ctp::Topology *top) {
cout << endl << "... ... Writing job file " << flush;
std::ofstream ofs;
ofs.open(_jobfile.c_str(), std::ofstream::out);
if (!ofs.is_open()) throw runtime_error("\nERROR: bad file handle: " + _jobfile);
ctp::QMNBList::iterator pit;
ctp::QMNBList &nblist = top->NBList();
int jobCount = 0;
if (nblist.size() == 0) {
cout << endl << "... ... No pairs in neighbor list, skip." << flush;
return;
}
ofs << "<jobs>" << endl;
string tag = "";
for (pit = nblist.begin(); pit != nblist.end(); ++pit) {
if ((*pit)->getType()==3){
int id1 = (*pit)->Seg1()->getId();
string name1 = (*pit)->Seg1()->getName();
int id2 = (*pit)->Seg2()->getId();
string name2 = (*pit)->Seg2()->getName();
int id = ++jobCount;
string mps_file1=(boost::format("MP_FILES/%s_n2s%d.mps") % name1 % _statenumber).str();
string mps_file2=(boost::format("MP_FILES/%s_n2s%d.mps") % name1 % _statenumber).str();
Property Input;
Property *pInput = &Input.add("input","");
Property *pSegment = &pInput->add("segment" , boost::lexical_cast<string>(id1) );
pSegment->setAttribute<string>("type", name1 );
pSegment->setAttribute<int>("id", id1 );
pSegment->setAttribute<string>("mps_file",mps_file1);
pSegment = &pInput->add("segment" , boost::lexical_cast<string>(id2) );
pSegment->setAttribute<string>("type", name2 );
pSegment->setAttribute<int>("id", id2 );
pSegment->setAttribute<string>("mps_file",mps_file2);
ctp::Job job(id, tag, Input, ctp::Job::AVAILABLE );
job.ToStream(ofs,"xml");
}
}
// CLOSE STREAM
ofs << "</jobs>" << endl;
ofs.close();
cout << endl << "... ... In total " << jobCount << " jobs" << flush;
}
void IEXCITON::ReadJobFile(ctp::Topology *top) {
Property xml;
vector<Property*> records;
// gets the neighborlist from the topology
ctp::QMNBList &nblist = top->NBList();
int _number_of_pairs = nblist.size();
int _current_pairs=0;
// output using logger
ctp::Logger _log;
_log.setReportLevel(ctp::logINFO);
// load the QC results in a vector indexed by the pair ID
load_property_from_xml(xml, _jobfile);
list<Property*> jobProps = xml.Select("jobs.job");
records.resize( _number_of_pairs + 1 );
//to skip pairs which are not in the jobfile
for (unsigned i=0;i<records.size();i++){
records[i]=NULL;
}
// loop over all jobs = pair records in the job file
for (list<Property*> ::iterator it = jobProps.begin(); it != jobProps.end(); ++it) {
// if job produced an output, then continue with analysis
if ( (*it)->exists("output") && (*it)->exists("output.pair") ) {
_current_pairs++;
// get the output records
Property& poutput = (*it)->get("output.pair");
// id's of two segments of a pair
int idA = poutput.getAttribute<int>("idA");
int idB = poutput.getAttribute<int>("idB");
// segments which correspond to these ids
ctp::Segment *segA = top->getSegment(idA);
ctp::Segment *segB = top->getSegment(idB);
// pair that corresponds to the two segments
ctp::QMPair *qmp = nblist.FindPair(segA,segB);
if (qmp == NULL) { // there is no pair in the neighbor list with this name
CTP_LOG_SAVE(ctp::logINFO, _log) << "No pair " << idA << ":" << idB << " found in the neighbor list. Ignoring" << flush;
} else {
//CTP_LOG(logINFO, _log) << "Store in record: " << idA << ":" << idB << flush;
records[qmp->getId()] = & ((*it)->get("output.pair"));
}
} else {
Property thebadone = (*it)->get("id");
throw runtime_error("\nERROR: Job file incomplete.\n Job with id "+thebadone.as<string>()+" is not finished. Check your job file for FAIL, AVAILABLE, or ASSIGNED. Exiting\n");
}
} // finished loading from the file
// loop over all pairs in the neighbor list
CTP_LOG_SAVE(ctp::logINFO, _log) << "Neighborlist size " << top->NBList().size() << flush;
for (ctp::QMNBList::iterator ipair = top->NBList().begin(); ipair != top->NBList().end(); ++ipair) {
ctp::QMPair *pair = *ipair;
if (records[ pair->getId() ]==NULL) continue; //skip pairs which are not in the jobfile
//Segment* segmentA = pair->Seg1();
//Segment* segmentB = pair->Seg2();
double Jeff2 = 0.0;
double jAB=0.0;
//cout << "\nProcessing pair " << segmentA->getId() << ":" << segmentB->getId() << flush;
if ( pair->getType() == ctp::QMPair::Excitoncl){
Property* pair_property = records[ pair->getId() ];
list<Property*> pCoupling = pair_property->Select("Coupling");
for (list<Property*> ::iterator itCoupling = pCoupling.begin(); itCoupling != pCoupling.end(); ++itCoupling) {
jAB = (*itCoupling)->getAttribute<double>("jABstatic");
}
Jeff2 = jAB*jAB;
pair->setJeff2(Jeff2, 2);
pair->setIsPathCarrier(true, 2);
}
}
CTP_LOG_SAVE(ctp::logINFO, _log) << "Pairs [total:updated] " << _number_of_pairs << ":" << _current_pairs << flush;
cout << _log;
}
}};
| 32.687805 | 187 | 0.565065 | choudarykvsp |
5610b425a0cc434a6c9d241aecaf7bc4bae58eca | 1,198 | cpp | C++ | 5Graph_accesses_using_BGL.cpp | mohsenuss91/BGL_workshop | 03d2bea291d4c6d67e7ddcd562694a0b7ecc5130 | [
"MIT"
] | 1 | 2015-02-12T18:40:32.000Z | 2015-02-12T18:40:32.000Z | 5Graph_accesses_using_BGL.cpp | mohsenuss91/IBM_BGL | 03d2bea291d4c6d67e7ddcd562694a0b7ecc5130 | [
"MIT"
] | null | null | null | 5Graph_accesses_using_BGL.cpp | mohsenuss91/IBM_BGL | 03d2bea291d4c6d67e7ddcd562694a0b7ecc5130 | [
"MIT"
] | null | null | null | #include <iostream>
#include <boost/graph/adjacency_list.hpp>
using namespace boost;
using namespace std;
typedef property<edge_weight_t, int> EdgeWeightProperty;
typedef property<edge_weight_t, int> EdgeWeightProperty;
typedef boost::adjacency_list < listS, vecS, undirectedS, no_property, EdgeWeightProperty> mygraph;
int main()
{
mygraph g;
add_edge (0, 1, 8, g);
add_edge (0, 3, 18, g);
add_edge (1, 2, 20, g);
add_edge (2, 3, 2, g);
add_edge (3, 1, 1, g);
add_edge (1, 3, 7, g);
cout << "Number of edges: " << num_edges(g) << "\n";
cout << "Number of vertices: " << num_vertices(g) << "\n";
mygraph::vertex_iterator vertexIt, vertexEnd;
tie(vertexIt, vertexEnd) = vertices(g);
for (; vertexIt != vertexEnd; ++vertexIt)
{
std::cout << "in-degree for " << *vertexIt << ": "<< in_degree(*vertexIt, g) << "\n";
std::cout << "out-degree for " << *vertexIt << ": "<< out_degree(*vertexIt, g) << "\n";
}
mygraph::edge_iterator edgeIt, edgeEnd;
tie(edgeIt, edgeEnd) = edges(g);
for (; edgeIt!= edgeEnd; ++edgeIt)
{
std::cout << "edge " << source(*edgeIt, g) << "-->"<< target(*edgeIt, g) << "\n";
}
}
| 36.30303 | 99 | 0.600167 | mohsenuss91 |
561102d0305d5e59c254b50186f862a1506e482d | 25,650 | cpp | C++ | pikoc/src/PikoSummary.cpp | piko-dev/piko-public | 8d7ab461de155992ca75e839f406670279fb6bad | [
"BSD-3-Clause"
] | 15 | 2015-05-19T08:23:26.000Z | 2021-11-26T02:59:36.000Z | pikoc/src/PikoSummary.cpp | piko-dev/piko-public | 8d7ab461de155992ca75e839f406670279fb6bad | [
"BSD-3-Clause"
] | null | null | null | pikoc/src/PikoSummary.cpp | piko-dev/piko-public | 8d7ab461de155992ca75e839f406670279fb6bad | [
"BSD-3-Clause"
] | 4 | 2015-10-06T15:14:43.000Z | 2020-02-20T13:17:11.000Z | #include "PikoSummary.hpp"
#include <algorithm>
#include <sstream>
using namespace std;
bool compBranchesFurthest(vector<stageSummary*> a, vector<stageSummary*> b) {
return (a[0]->distFromDrain > b[0]->distFromDrain);
}
bool compBranchesClosest(vector<stageSummary*> a, vector<stageSummary*> b) {
return (a[0]->distFromDrain < b[0]->distFromDrain);
}
bool isInCycleRecur(stageSummary *target, stageSummary *path, vector<stageSummary*> visited) {
// if a stage looped around to itself
if(target == path)
return true;
else {
// if we haven't been to this stage already
if(std::find(visited.begin(), visited.end(), path) == visited.end()) {
visited.push_back(path);
bool ret = false;
for(unsigned i=0; i<path->prevStages.size(); i++) {
ret |= isInCycleRecur(target, path->prevStages[i], visited);
}
return ret;
}
else
return false;
}
}
bool isInCycle(stageSummary *target, stageSummary *path) {
vector<stageSummary*> visited;
return isInCycleRecur(target, path, visited);
}
bool branchReady(vector<stageSummary*> branch, vector<stageSummary*> doneStages, int whichSchedule) {
vector<stageSummary*> ds = doneStages;
for(unsigned i=0; i<branch.size(); i++) {
if(branch[i]->prevStages.size() == 0) {
ds.push_back(branch[i]);
}
else {
// check endStage dependencies
if(branch[i]->schedules[whichSchedule].endStagePtr!=NULL &&
std::find(ds.begin(), ds.end(), branch[i]->schedules[whichSchedule].endStagePtr) ==
ds.end()) return false;
// check previous stage dependencies
for(unsigned j=0; j<branch[i]->prevStages.size(); j++) {
stageSummary *curPrevStage = branch[i]->prevStages[j];
// if a previous stage is not the current stage (for self-cyclic stages) and
// the previous stage is not done yet
if(/*curPrevStage != branch[i] && */std::find(ds.begin(), ds.end(), curPrevStage) == ds.end() &&
!isInCycle(branch[i], curPrevStage))
return false;
else
ds.push_back(branch[i]);
}
}
}
return true;
}
// generate kernel plan
void PipeSummary::generateKernelPlan(ostream& outfile){
// step 1: discover drain nodes
//printf("-----------\n");
printf("%s (%s)\n",this->name.c_str(),this->filename.c_str());
for(unsigned printi=0; printi<(this->name.length() + this->filename.length() + 3); printi++)
printf("="); printf("\n");
printf("* Drain stages: ");
for(unsigned i=0; i<stages.size(); i++){
if(stages[i].nextStages.size() == 0){
printf("[%s] ",stages[i].name.c_str());
drainStages.push_back(&stages[i]);
stages[i].distFromDrain=0;
updateDrainDistance(&stages[i]);
}
}
printf("\n");
//printf("Drain distances:\n");
//for(unsigned i=0; i<stages.size(); i++){
// printf("\t[%d] %s\n",stages[i].distFromDrain, stages[i].name.c_str());
//}
// step 2. sort by drain distances
//sort(stages.begin(), stages.end(), stageSummary::higherDrainDist);
// step 3. discover preschedule candidates
for(unsigned i=0; i<stages.size(); i++){
if(stages[i].schedules[0].schedPolicy == schedDirectMap ||
stages[i].schedules[0].schedPolicy == schedSerialize){
stages[i].schedules[0].isPreScheduleCandidate = true;
}
}
// divide pipeline into branches
vector< vector<stageSummary*> > branches;
{
vector<stageSummary*> inBranch;
// create branches and add first stage to each
// new branch created if the stage:
// 1) my only parent is myself
// 2) has no previous stage OR
// 3) has multiple previous stages OR
// 4) is the child of a stage with mulitple next stages
for(unsigned i=0; i<stages.size(); i++) {
bool isInBranch = std::find(inBranch.begin(), inBranch.end(), &stages[i]) != inBranch.end();
// If my only parent is myself, make new branch
if(!isInBranch && stages[i].prevStages.size() == 1 && stages[i].prevStages[0] == &stages[i]) {
vector<stageSummary*> tmp;
tmp.push_back(&stages[i]);
inBranch.push_back(&stages[i]);
branches.push_back(tmp);
}
// Does 2 and 3
else if(!isInBranch && (stages[i].prevStages.size() == 0 || stages[i].prevStages.size() > 1) ) {
vector<stageSummary*> tmp;
tmp.push_back(&stages[i]);
inBranch.push_back(&stages[i]);
branches.push_back(tmp);
}
// Does 4
if(stages[i].nextStages.size() > 1) {
if(stages[i].nextStages.size() == 2 &&
(stages[i].nextStages[0] == &stages[i] || stages[i].nextStages[1] == &stages[i]) ) {
}
else {
for(unsigned j=0; j<stages[i].nextStages.size(); j++) {
stageSummary *candidate = stages[i].nextStages[j];
if(std::find(inBranch.begin(), inBranch.end(), candidate) == inBranch.end()) {
vector<stageSummary*> tmp;
tmp.push_back(candidate);
inBranch.push_back(candidate);
branches.push_back(tmp);
}
}
}
}
}
// find other stages in each branch
for(unsigned i=0; i<branches.size(); i++) {
int stgNum = 0;
bool done = false;
while(!done) {
if(branches[i][stgNum]->nextStages.size() == 0)
done = true;
else {
stageSummary *candidate = branches[i][stgNum]->nextStages[0];
if(candidate == branches[i][stgNum] && branches[i][stgNum]->nextStages.size() > 1)
candidate = branches[i][stgNum]->nextStages[1];
// if stage not already in a branch
if(std::find(inBranch.begin(), inBranch.end(), candidate) == inBranch.end()) {
// if stage has a Custom dependency, push to new branch
if(candidate->schedules[0].waitPolicy == waitCustom) {
vector<stageSummary*> tmp;
tmp.push_back(candidate);
inBranch.push_back(candidate);
branches.push_back(tmp);
done = true;
}
// else if stage has EndStage dependency
else if(candidate->schedules[0].waitPolicy == waitEndStage) {
// if the EndStagePtr is not in the current branch
if(std::find(branches[i].begin(), branches[i].end(), candidate->schedules[0].endStagePtr) == branches[i].end()) {
// push to new branch
vector<stageSummary*> tmp;
tmp.push_back(candidate);
inBranch.push_back(candidate);
branches.push_back(tmp);
done = true;
}
else {
// add to current branch
branches[i].push_back(candidate);
inBranch.push_back(candidate);
stgNum += 1;
}
}
else {
branches[i].push_back(candidate);
inBranch.push_back(candidate);
stgNum += 1;
}
}
else
done = true;
}
}
}
/*
for(unsigned i=0; i<branches.size(); i++) {
for(unsigned j=0; j<branches[i].size(); j++) {
printf("Branch %d Stage %d - %s\n",i,j,branches[i][j]->name.c_str());
}
}
*/
// sort branches by distFromDrain - furthest comes first or closest comes first
sort(branches.begin(), branches.end(), compBranchesFurthest); // furthest from drain are scheduled first
//sort(branches.begin(), branches.end(), compBranchesClosest); // closest drain are scheduled first
}
// schedule branches in this order:
// furthest from drain stages come first
// if dependent on another branch, skip to next branch and come back afterwards
int curKernelID = 0;
int curBranchNum = 0;
int curBucketLoopLevel = 0;
int lastBucketLoopLevel = 0;
int curBucketLoopID = -1;
vector<stageSummary*> doneStages;
while(branches.size() > 0) {
if(curBranchNum == branches.size())
break;
vector<stageSummary*> curBranch = branches[curBranchNum];
//printf("attempting %d\n", curBranchNum);
if( branchReady(curBranch, doneStages, 0) ) {
//printf("scheduling %d\n", curBranchNum);
// schedule branch
vector<stageSummary*> almostDoneStages;
vec2i lastBinsize = curBranch[0]->binsize;
for(unsigned i=0; i<curBranch.size(); i++) {
stagesInOrder.push_back(curBranch[i]);
assignBinSummary& ass = curBranch[i]->assignBin;
scheduleSummary& sch = curBranch[i]->schedules[0];
processSummary& pro = curBranch[i]->process;
int nextKernelID = curKernelID+1;
int lastBucketLoopLevel = curBucketLoopLevel;
int lastBucketLoopID = curBucketLoopID;
if(preferDepthFirst && sch.schedPolicy != schedAll) {
if(i>0) {
if(curBranch[i-1]->process.bucketLoopLevel == 0 || sch.waitPolicy == waitEndStage)
curBucketLoopLevel = 0;
else {
//bool sameBinSize = (curBranch[i]->binsize == (curBranch[i-1]->binsize));
//bool secondLarger = (curBranch[i]->binsize[0] > (curBranch[i-1]->binsize[0])
// || curBranch[i]->binsize[1] > (curBranch[i-1]->binsize[1]));
//bool secondLarger = (curBranch[i]->binsize[0] > lastBinsize[0]
// || curBranch[i]->binsize[1] > lastBinsize[1]);
int lastBinX = (lastBinsize[0] == 0) ? INT_MAX : lastBinsize[0];
int lastBinY = (lastBinsize[1] == 0) ? INT_MAX : lastBinsize[1];
int curBinX = (curBranch[i]->binsize[0] == 0) ? INT_MAX : curBranch[i]->binsize[0];
int curBinY = (curBranch[i]->binsize[1] == 0) ? INT_MAX : curBranch[i]->binsize[1];
bool secondLarger = (curBinX > lastBinX || curBinY > lastBinY);
if(secondLarger) curBucketLoopLevel = 0;
else {
curBucketLoopLevel = lastBucketLoopLevel;
curBucketLoopID = lastBucketLoopID;
}
}
}
else {
curBucketLoopLevel = 0;
}
}
else {
if(sch.schedPolicy != schedAll) curBucketLoopLevel = 0;
else if(sch.waitPolicy == waitEndStage) {
curBucketLoopLevel = 1;
curBucketLoopID = lastBucketLoopID+1;
lastBinsize = curBranch[i]->binsize;
}
else {
if(i>0){
//&& !(sch.binsize==(curBranch[i-1]->schedules[0].binsize)))
if(curBranch[i-1]->process.bucketLoopLevel == 0) {
curBucketLoopLevel = 1;
curBucketLoopID = lastBucketLoopID+1;
}
else {
//bool secondLarger = (curBranch[i]->binsize[0] > lastBinsize[0]
// || curBranch[i]->binsize[1] > lastBinsize[1]);
bool sameBinSize = (curBranch[i]->binsize == lastBinsize);
int lastBinX = (lastBinsize[0] == 0) ? INT_MAX : lastBinsize[0];
int lastBinY = (lastBinsize[1] == 0) ? INT_MAX : lastBinsize[1];
int curBinX = (curBranch[i]->binsize[0] == 0) ? INT_MAX : curBranch[i]->binsize[0];
int curBinY = (curBranch[i]->binsize[1] == 0) ? INT_MAX : curBranch[i]->binsize[1];
bool secondLarger = (curBinX > lastBinX || curBinY > lastBinY);
if(sameBinSize) {
curBucketLoopLevel = lastBucketLoopLevel;
curBucketLoopID = lastBucketLoopID;
}
else if(secondLarger) {
curBucketLoopLevel = 1;
curBucketLoopID = lastBucketLoopID+1;
}
else {
curBucketLoopLevel = lastBucketLoopLevel+1;
curBucketLoopID = lastBucketLoopID+1;
}
}
}
else{
curBucketLoopLevel = 1;
curBucketLoopID = lastBucketLoopID+1;
}
lastBinsize = curBranch[i]->binsize;
}
}
ass.kernelID = curKernelID;
ass.bucketLoopLevel = curBucketLoopLevel;
ass.bucketLoopID = (curBucketLoopLevel == 0) ? -1 : curBucketLoopID;
if(i==0 && ass.policy != assignEmpty)
curKernelID = nextKernelID;
if(i>0 && !canFuse(*curBranch[i-1],*curBranch[i],0,doneStages)) {
curKernelID = nextKernelID;
for(unsigned j=0; j<almostDoneStages.size(); j++)
doneStages.push_back(almostDoneStages[j]);
almostDoneStages.clear();
//doneStages.push_back(curBranch[i-1]);
}
almostDoneStages.push_back(curBranch[i]);
// if last iteration, add all almostDoneStages to doneStages
if(i == curBranch.size()-1) {
for(unsigned j=0; j<almostDoneStages.size(); j++)
doneStages.push_back(almostDoneStages[j]);
almostDoneStages.clear();
}
sch.kernelID = curKernelID;
sch.bucketLoopLevel = curBucketLoopLevel;
sch.bucketLoopID = (curBucketLoopLevel == 0) ? -1 : curBucketLoopID;
// TODO: Think about what PreScheduleCandiate means, and whether schedAll should be a preschedule candidate
if(sch.isPreScheduleCandidate) sch.kernelID = ass.kernelID;
else if((sch.schedPolicy != schedLoadBalance
&& sch.schedPolicy != schedAll) || !sch.trivial) curKernelID += 1;
pro.kernelID = curKernelID;
pro.bucketLoopLevel = curBucketLoopLevel;
pro.bucketLoopID = (curBucketLoopLevel == 0) ? -1 : curBucketLoopID;
for(unsigned k=0; k<curBranch[i]->nextStages.size(); k++) {
stageSummary *tmp = curBranch[i]->nextStages[k];
if(std::find(doneStages.begin(), doneStages.end(), tmp) != doneStages.end() ||
std::find(almostDoneStages.begin(), almostDoneStages.end(), tmp)
!= almostDoneStages.end())
{
tmp->loopStart = true;
curBranch[i]->loopEnd = true;
printf("\nRepeat kernels %d through %d as necessary\n\n",tmp->assignBin.kernelID,curKernelID);
}
}
// special case for self-cyclic cycles
if(curBranch[i]->nextStages.size() == 2 &&
(curBranch[i]->nextStages[0] == curBranch[i]
|| curBranch[i]->nextStages[1] == curBranch[i]) ) {
curKernelID += 1;
}
}
// remove branch from list
branches.erase(branches.begin() + curBranchNum);
curBranchNum = 0;
curKernelID += 1;
}
else
curBranchNum += 1;
}
assertPrint(branches.size() == 0, "Assert failed: There are unscheduled branches remaining.\n");
// // {{{ old planner
// vector<stageSummary*> doneStages;
//
// int curKernelID = 0;
// for(unsigned i=0; i<stages.size(); i++){
//
// assignBinSummary& ass = stages[i].assignBin;
// scheduleSummary& sch = stages[i].schedules[0];
// processSummary& pro = stages[i].process;
//
// int nextKernelID = curKernelID+1;
//
// ass.kernelID = curKernelID;
//
// if(i>0 && !canFuse(stages[i-1],stages[i],0,doneStages)){
// curKernelID = nextKernelID;
//
// doneStages.push_back(&stages[i-1]);
// }
//
// sch.kernelID = curKernelID;
//
// // TODO: Think about what PreScheduleCandiate means, and whether schedAll should be a preschedule candidate
// if(sch.isPreScheduleCandidate) sch.kernelID = ass.kernelID;
// else if(sch.schedPolicy != schedLoadBalance
// && sch.schedPolicy != schedAll) curKernelID += 1;
//
// pro.kernelID = curKernelID;
//
// }
// // }}}
printf("* Number of Kernels: %d\n", curKernelID);
printf("|Level ID|\n");
curKernelID = -1;
curBucketLoopLevel = -1;
curBucketLoopID = -1;
for(unsigned i=0; i<stagesInOrder.size(); i++){
const stageSummary& stg = *stagesInOrder[i];
const assignBinSummary& ass = stg.assignBin;
const scheduleSummary& sch = stg.schedules[0];
const processSummary& pro = stg.process;
if(ass.policy != assignEmpty){
curBucketLoopID = ass.bucketLoopID;
curBucketLoopLevel = ass.bucketLoopLevel;
if(ass.kernelID != curKernelID) {
printf("|%d %d| * Kernel %d:\n",curBucketLoopLevel,curBucketLoopID,ass.kernelID);
}
curKernelID = ass.kernelID;
//printf("|%d-%d| - [%d] %s.AssignBin\n",curBucketLoopLevel,curBucketLoopID,stg.distFromDrain, stg.name.c_str());
printf(" - [%d] %s.AssignBin\n",stg.distFromDrain, stg.name.c_str());
}
curBucketLoopID = sch.bucketLoopID;
curBucketLoopLevel = sch.bucketLoopLevel;
if(sch.kernelID != curKernelID) {
printf("|%d %d| * Kernel %d:\n",curBucketLoopLevel,curBucketLoopID,sch.kernelID);
}
curKernelID = sch.kernelID;
//printf("|%d-%d| - %s.Schedule%s",curBucketLoopLevel,curBucketLoopID, stg.name.c_str(),
printf(" - %s.Schedule%s", stg.name.c_str(),
sch.isPreScheduleCandidate? "\t<--- 1 core per block\n":
sch.schedPolicy==schedLoadBalance? "\t<--- 1 bin per block\n":"\n"); // \t<--- trivialized to cuda scheduler
if(pro.policy != procEmpty){
curBucketLoopID = sch.bucketLoopID;
curBucketLoopLevel = pro.bucketLoopLevel;
if(pro.kernelID != curKernelID) {
printf("|%d %d| * Kernel %d:\n",curBucketLoopLevel,curBucketLoopID,pro.kernelID);
}
curKernelID = pro.kernelID;
//printf("|%d-%d| - %s.Process\n",curBucketLoopLevel,curBucketLoopID, stg.name.c_str());
printf(" - %s.Process\n", stg.name.c_str());
}
}
printf("\n");
// commenting out kernel order code because it doesn't work yet
/*
printf("\tKernel order:\n");
vector< pair<int,string> > *kernOrder = new vector< pair<int,string> >();
stages[0].findKernelOrder(-1, 0, kernOrder);
int curBatch = 0;
printf("\tBatch %d\n", curBatch);
for(unsigned int i=0; i<kernOrder->size(); ++i) {
if((*kernOrder)[i].first == curBatch)
printf("\t%s", (*kernOrder)[i].second.c_str());
else {
curBatch = (*kernOrder)[i].first;
printf("\tBatch %d\n", curBatch);
printf("\t%s", (*kernOrder)[i].second.c_str());
}
}
*/
}
void stageSummary::findKernelOrder(int kernelID, int batch, vector< pair<int,string> > *order) {
stringstream ss;
ss.str("");
ss.clear();
int curKernelID = kernelID;
int curBatch = batch;
assignBinSummary& ass = assignBin;
scheduleSummary& sch = schedules[0];
processSummary& pro = process;
if(ass.kernelID != curKernelID) {
if(ass.policy != assignEmpty) {
curKernelID = ass.kernelID;
ss << "\tKernel " << curKernelID << endl;
}
}
if(sch.kernelID != curKernelID) {
curKernelID = sch.kernelID;
ss << "\tKernel " << curKernelID << endl;
}
if(pro.kernelID != curKernelID) {
if(pro.policy != procEmpty) {
curKernelID = pro.kernelID;
ss << "\tKernel " << curKernelID << endl;
}
}
//printf("!!! HERE 1 !!!\n");
pair<int,string> ret(curBatch, ss.str());
//printf("SIZE: %d\n", ret.second.length());
//printf("!!! HERE 2 !!!\n");
if(ret.second != "") {
//printf("!!! HERE 3 !!!\n");
order->push_back(ret);
//printf("!!! HERE 4 !!!\n");
ss.str("");
ss.clear();
//printf("!!! HERE 5 !!!\n");
}
if(nextStages.size() > 1) curBatch += 1;
for(unsigned int i=0; i<nextStages.size(); ++i) {
//printf("iter = %d\n",i);
//printf("!!! HERE 1 !!!\n");
if(isCurOrPrevStage(nextStages[i])) {
//printf("!!! HERE 2 !!!\n");
ss << "repeat kernel " << nextStages[i]->assignBin.kernelID << " to kernel " << curKernelID << " sequence\n";
ret.first = (curBatch == batch) ? curBatch+1 : curBatch;
ret.second = ss.str();
order->push_back(ret);
ss.str("");
ss.clear();
}
else {
//printf("!!! HERE 3 !!!\n");
if(nextStages[i]->prevStages.size() > 1)
nextStages[i]->findKernelOrder(curKernelID, curBatch+1, order);
else if(nextStages[i]->schedules[0].waitPolicy == waitEndStage)
nextStages[i]->findKernelOrder(curKernelID, curBatch+1, order);
else
nextStages[i]->findKernelOrder(curKernelID, curBatch, order);
}
}
}
bool stageSummary::isCurOrPrevStage(stageSummary *stg) {
//printf("stg = %s\n", stg->name.c_str());
//printf("this = %s\n", this->name.c_str());
//printf("!!! HERE 1 !!!\n");
if(stg == this) return true;
//printf("!!! HERE 2 !!!\n");
for(unsigned int i=0; i<prevStages.size(); ++i) {
//printf("this = %s\n", this->name.c_str());
//printf("prev = %s\n", this->prevStages[i]->name.c_str());
//printf("!!! HERE 3 !!!\n");
if(prevStages[i]->isCurOrPrevStage(stg)) return true;
}
//printf("!!! HERE 4 !!!\n");
return false;
}
// update distances from drain stage (recursively)
void PipeSummary::updateDrainDistance(stageSummary* stage){
if(stage != NULL){
for(unsigned i=0; i<stage->prevStages.size(); i++){
stageSummary* ps = stage->prevStages[i];
int oldDist = ps->distFromDrain;
ps->distFromDrain = min(stage->distFromDrain+1, oldDist);
int newDist = ps->distFromDrain;
if(oldDist != newDist)
updateDrainDistance(ps);
}
}
}
// update all links
void PipeSummary::processLinks(){
for(unsigned i=0; i<stages.size(); i++){
// update nextStages
for(unsigned j=0; j<stages[i].nextStageNames.size(); j++){
stageSummary* nextStage = findStageByName(stages[i].nextStageNames[j]);
if(nextStage!=NULL){
stages[i].nextStages.push_back(nextStage);
nextStage->prevStages.push_back(&stages[i]);
}
}
// update endStagePtr if waitPolicy is set to endStage
if(stages[i].schedules[0].waitPolicy == waitEndStage){
stages[i].schedules[0].endStagePtr = findStageByName(stages[i].schedules[0].endStageName);
}
}
}
// given stage name, fetch pointer
stageSummary* PipeSummary::findStageByName(const string& stageName){
for(unsigned i=0; i<stages.size(); i++){
if(stageName == stages[i].name) return &stages[i];
}
printf("Cannot find Stage named \"%s\"\n",stageName.c_str());
return NULL;
}
// given stage type, fetch pointer and return vector
vector<stageSummary*> PipeSummary::findStageByType(const string& stageType){
vector<stageSummary*> ret;
for(unsigned i=0; i<stages.size(); i++){
if(stageType == stages[i].type) ret.push_back(&stages[i]);
}
if(ret.size() > 0) return ret;
else {
printf("Cannot find Stage type \"%s\"\n",stageType.c_str());
exit(3);
return ret;
}
}
// display pipe summary
void PipeSummary::displaySummary(){
printf("Pipe %s\n",name.c_str());
for(unsigned i=0; i<stages.size(); i++){
stageSummary& curStage = stages[i];
printf("\tStage %s\n",curStage.name.c_str());
printf("\t\tType: %s\n", curStage.type.c_str());
printf("\t\tBinsize: %d x %d\n", curStage.binsize.x(), curStage.binsize.y());
printf("\t\tNextStages: ");
for(unsigned j=0; j<curStage.nextStageNames.size(); j++)
printf("%s ",curStage.nextStageNames[j].c_str());
printf("\n");
printf("\t\tCode: %s\n",curStage.codeFile.c_str());
printf("\t\tAssignBin\n");
printf("\t\t\tCode: %s\n",curStage.assignBin.codeFile.c_str());
printf("\t\t\tPolicy: %s\n",toString(curStage.assignBin.policy).c_str());
printf("\t\t\ttrivial: %s\n", (curStage.assignBin.trivial) ? "true" : "false");
//printf("\t\t\tCode: %s\n",curStage.assignBin.codeFile.c_str());
for(unsigned j=0; j<curStage.schedules.size(); j++){
printf("\t\tSchedule\n");
printf("\t\t\tCode: %s\n",curStage.schedules[j].codeFile.c_str());
printf("\t\t\tArch: %s\n", toString(curStage.schedules[j].arch).c_str());
printf("\t\t\tschedPolicy: %s\n", toString(curStage.schedules[j].schedPolicy).c_str());
printf("\t\t\ttileSplitSize: %d\n", curStage.schedules[j].tileSplitSize);
printf("\t\t\twaitPolicy: %s\n", toString(curStage.schedules[j].waitPolicy).c_str());
printf("\t\t\twaitBatchSize: %d\n", curStage.schedules[j].waitBatchSize);
printf("\t\t\ttrivial: %s\n", (curStage.schedules[j].trivial) ? "true" : "false");
//printf("\t\t\tCode: %s\n",curStage.schedules[j].codeFile.c_str());
}
printf("\t\tProcess\n");
printf("\t\t\tCode: %s\n",curStage.process.codeFile.c_str());
printf("\t\t\tMaxOutPrims: %d\n",curStage.process.maxOutPrims);
printf("\t\t\ttrivial: %s\n", (curStage.process.trivial) ? "true" : "false");
//printf("\t\t\tCode: %s\n",curStage.process.codeFile.c_str());
}
printf("---\n");
}
bool PipeSummary::canFuse(stageSummary& s1, stageSummary& s2, int whichSchedule,
vector<stageSummary*>& doneStages){
// Cannot fuse two stages if they are the same type
if(s1.type == s2.type)
return false;
scheduleSummary& sch1 = s1.schedules[whichSchedule];
scheduleSummary& sch2 = s2.schedules[whichSchedule];
// make sure architectures match (for your sanity)
if(sch1.arch != sch2.arch) return false;
// we will not fuse with a stage that has multiple input paths
if(s2.prevStages.size() > 1) return false;
if(s1.nextStages.size() > 1) return false;
// max_fan_out_per_\process ... removing for now
//if(s1.process.maxOutPrims > 64 && sch2.waitPolicy!=waitNone) return false;
// if dependencies are not resolved, we cannot fuse
if(sch2.endStagePtr!=NULL && std::find(doneStages.begin(), doneStages.end(), sch2.endStagePtr) ==
doneStages.end()) return false;
// the following flag will check s1 and s2 run in the same core
bool sameCore = false;
sameCore = sameCore;
// fusing DirectMap scheduler
sameCore = sameCore || ((sch2.schedPolicy == sch1.schedPolicy) &&
(s2.assignBin.policy == assignInBin) &&
(sch1.schedPolicy == schedDirectMap));
// fusing Serialize Scheduler
sameCore = sameCore || ((sch2.schedPolicy == sch1.schedPolicy) &&
(sch1.schedPolicy == schedSerialize));
// fusing LoadBalance Scheduler
sameCore = sameCore || ((sch2.schedPolicy == sch1.schedPolicy) &&
(s2.assignBin.policy == assignInBin) &&
(sch1.schedPolicy == schedLoadBalance));
bool preferLoadBalance = false;
preferLoadBalance = preferLoadBalance || (sch2.schedPolicy==schedLoadBalance);
if( 0//(sch2.waitPolicy == waitNone && s2.process.maxOutPrims<=8 && s2.assignBin.policy != assignCustom)
|| ((s2.binsize == s1.binsize) && sameCore && sch1.tileSplitSize == sch2.tileSplitSize)
|| 0
)
{
return true;
}
// fusing schedAll
else if(sch1.schedPolicy == schedAll &&
sch2.schedPolicy == schedAll &&
s2.assignBin.policy == assignInBin &&
s1.binsize == s2.binsize &&
sch2.waitPolicy == waitNone &&
sch1.tileSplitSize == sch2.tileSplitSize)
{
return true;
}
else
{
return false;
}
}
| 33.928571 | 121 | 0.625497 | piko-dev |
561158798e45c93c237c70d997d7e7d12b1867b0 | 804 | cpp | C++ | demos/tutorial/interval.cpp | tbellotti/samurai | b10fa2115d69eb184609103579ba433ff09891df | [
"BSD-3-Clause"
] | 13 | 2021-01-07T19:23:42.000Z | 2022-01-26T13:07:41.000Z | demos/tutorial/interval.cpp | gouarin/samurai | 7ae877997e8b9bdb85b84acaabb3c0483ff78689 | [
"BSD-3-Clause"
] | 1 | 2021-07-04T17:30:47.000Z | 2021-07-04T17:30:47.000Z | demos/tutorial/interval.cpp | gouarin/samurai | 7ae877997e8b9bdb85b84acaabb3c0483ff78689 | [
"BSD-3-Clause"
] | 2 | 2021-01-07T15:54:49.000Z | 2021-02-24T13:11:42.000Z | // Copyright 2021 SAMURAI TEAM. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <iostream>
#include <samurai/cell_array.hpp>
#include <samurai/cell_list.hpp>
int main()
{
constexpr std::size_t dim = 2;
samurai::CellList<dim> cl;
cl[0][{}].add_interval({0, 2});
cl[0][{}].add_interval({5, 6});
cl[1][{}].add_interval({4, 7});
cl[1][{}].add_interval({8, 10});
cl[2][{}].add_interval({15, 17});
samurai::CellArray<dim> ca{cl};
std::cout << ca << std::endl;
constexpr std::size_t start_level = 3;
samurai::Box<double, dim> box({-1, -1}, {1, 1});
samurai::CellArray<dim> ca_box;
ca_box[start_level] = {start_level, box};
std::cout << ca_box << std::endl;
} | 23.647059 | 53 | 0.614428 | tbellotti |
561c1abb21a95704ddd42ede79cbef5a8d6bb6c3 | 8,368 | cpp | C++ | examples/depthnet/depthnet.cpp | jwkim386/Jetson_Inference | 5aaba1c362b6cfca8475a41c15336dbfe03252fa | [
"MIT"
] | 5,788 | 2016-08-22T09:09:46.000Z | 2022-03-31T17:05:54.000Z | examples/depthnet/depthnet.cpp | jwkim386/Jetson_Inference | 5aaba1c362b6cfca8475a41c15336dbfe03252fa | [
"MIT"
] | 1,339 | 2016-08-15T08:51:10.000Z | 2022-03-31T18:44:20.000Z | examples/depthnet/depthnet.cpp | jwkim386/Jetson_Inference | 5aaba1c362b6cfca8475a41c15336dbfe03252fa | [
"MIT"
] | 2,730 | 2016-08-23T11:04:26.000Z | 2022-03-30T14:06:08.000Z | /*
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "videoSource.h"
#include "videoOutput.h"
#include "cudaOverlay.h"
#include "cudaMappedMemory.h"
#include "depthNet.h"
#include <signal.h>
bool signal_recieved = false;
void sig_handler(int signo)
{
if( signo == SIGINT )
{
printf("received SIGINT\n");
signal_recieved = true;
}
}
int usage()
{
printf("usage: depthnet [--help] [--network NETWORK]\n");
printf(" [--colormap COLORMAP] [--filter-mode MODE]\n");
printf(" [--visualize VISUAL] [--depth-size SIZE]\n");
printf(" input_URI [output_URI]\n\n");
printf("Mono depth estimation on a video/image stream using depthNet DNN.\n\n");
printf("See below for additional arguments that may not be shown above.\n\n");
printf("optional arguments:\n");
printf(" --help show this help message and exit\n");
printf(" --network=NETWORK pre-trained model to load (see below for options)\n");
printf(" --visualize=VISUAL controls what is displayed (e.g. --visualize=input,depth)\n");
printf(" valid combinations are: 'input', 'depth' (comma-separated)\n");
printf(" --depth-size=SIZE scales the size of the depth map visualization, as a\n");
printf(" percentage of the input size (default is 1.0)\n");
printf(" --filter-mode=MODE filtering mode used during visualization,\n");
printf(" options are: 'point' or 'linear' (default: 'linear')\n");
printf(" --colormap=COLORMAP depth colormap (default is 'viridis-inverted')\n");
printf(" options are: 'inferno', 'inferno-inverted',\n");
printf(" 'magma', 'magma-inverted',\n");
printf(" 'parula', 'parula-inverted',\n");
printf(" 'plasma', 'plasma-inverted',\n");
printf(" 'turbo', 'turbo-inverted',\n");
printf(" 'viridis', 'viridis-inverted'\n\n");
printf("positional arguments:\n");
printf(" input_URI resource URI of input stream (see videoSource below)\n");
printf(" output_URI resource URI of output stream (see videoOutput below)\n\n");
printf("%s", depthNet::Usage());
printf("%s", videoSource::Usage());
printf("%s", videoOutput::Usage());
printf("%s", Log::Usage());
return 0;
}
//
// depth map buffers
//
typedef uchar3 pixelType; // this can be uchar3, uchar4, float3, float4
pixelType* imgDepth = NULL; // colorized depth map image
pixelType* imgComposite = NULL; // original image with depth map next to it
int2 inputSize;
int2 depthSize;
int2 compositeSize;
// allocate depth map & output buffers
bool allocBuffers( int width, int height, uint32_t flags, float depthScale )
{
// check if the buffers were already allocated for this size
if( imgDepth != NULL && width == inputSize.x && height == inputSize.y )
return true;
// free previous buffers if they exit
CUDA_FREE_HOST(imgDepth);
CUDA_FREE_HOST(imgComposite);
// allocate depth map
inputSize = make_int2(width, height);
depthSize = make_int2(width * depthScale, height * depthScale);
if( !cudaAllocMapped(&imgDepth, depthSize) )
{
LogError("depthnet: failed to allocate CUDA memory for depth map (%ix%i)\n", depthSize.x, depthSize.y);
return false;
}
// allocate composite image
compositeSize = make_int2(0,0);
if( flags & depthNet::VISUALIZE_DEPTH )
{
compositeSize.x += depthSize.x;
compositeSize.y = depthSize.y;
}
if( flags & depthNet::VISUALIZE_INPUT )
{
compositeSize.x += inputSize.x;
compositeSize.y = inputSize.y;
}
if( !cudaAllocMapped(&imgComposite, compositeSize) )
{
LogError("depthnet: failed to allocate CUDA memory for composite image (%ix%i)\n", compositeSize.x, compositeSize.y);
return false;
}
return true;
}
int main( int argc, char** argv )
{
/*
* parse command line
*/
commandLine cmdLine(argc, argv);
if( cmdLine.GetFlag("help") )
return usage();
/*
* attach signal handler
*/
if( signal(SIGINT, sig_handler) == SIG_ERR )
LogError("can't catch SIGINT\n");
/*
* create input stream
*/
videoSource* input = videoSource::Create(cmdLine, ARG_POSITION(0));
if( !input )
{
LogError("depthnet: failed to create input stream\n");
return 0;
}
/*
* create output stream
*/
videoOutput* output = videoOutput::Create(cmdLine, ARG_POSITION(1));
if( !output )
LogError("depthnet: failed to create output stream\n");
/*
* create mono-depth network
*/
depthNet* net = depthNet::Create(cmdLine);
if( !net )
{
LogError("depthnet: failed to initialize depthNet\n");
return 0;
}
// parse the desired colormap
const cudaColormapType colormap = cudaColormapFromStr(cmdLine.GetString("colormap", "viridis-inverted"));
// parse the desired filter mode
const cudaFilterMode filterMode = cudaFilterModeFromStr(cmdLine.GetString("filter-mode"));
// parse the visualization flags
const uint32_t visualizationFlags = depthNet::VisualizationFlagsFromStr(cmdLine.GetString("visualize"));
// get the depth map size scaling factor
const float depthScale = cmdLine.GetFloat("depth-size", 1.0);
/*
* processing loop
*/
while( !signal_recieved )
{
// capture next image image
pixelType* imgInput = NULL;
if( !input->Capture(&imgInput, 1000) )
{
// check for EOS
if( !input->IsStreaming() )
break;
LogError("depthnet: failed to capture next frame\n");
continue;
}
// allocate buffers for this size frame
if( !allocBuffers(input->GetWidth(), input->GetHeight(), visualizationFlags, depthScale) )
{
LogError("depthnet: failed to allocate output buffers\n");
continue;
}
// infer the depth and visualize the depth map
if( !net->Process(imgInput, inputSize.x, inputSize.y,
imgDepth, depthSize.x, depthSize.y,
colormap, filterMode) )
{
LogError("depthnet-camera: failed to process depth map\n");
continue;
}
// overlay the images into composite output image
if( visualizationFlags & depthNet::VISUALIZE_INPUT )
CUDA(cudaOverlay(imgInput, inputSize, imgComposite, compositeSize, 0, 0));
if( visualizationFlags & depthNet::VISUALIZE_DEPTH )
CUDA(cudaOverlay(imgDepth, depthSize, imgComposite, compositeSize, (visualizationFlags & depthNet::VISUALIZE_INPUT) ? inputSize.x : 0, 0));
// render outputs
if( output != NULL )
{
output->Render(imgComposite, compositeSize.x, compositeSize.y);
// update the status bar
char str[256];
sprintf(str, "TensorRT %i.%i.%i | %s | Network %.0f FPS", NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, NV_TENSORRT_PATCH, net->GetNetworkName(), net->GetNetworkFPS());
output->SetStatus(str);
// check if the user quit
if( !output->IsStreaming() )
signal_recieved = true;
}
// wait for the GPU to finish
CUDA(cudaDeviceSynchronize());
// print out timing info
net->PrintProfilerTimes();
}
/*
* destroy resources
*/
LogVerbose("depthnet: shutting down...\n");
SAFE_DELETE(input);
SAFE_DELETE(output);
SAFE_DELETE(net);
CUDA_FREE_HOST(imgDepth);
CUDA_FREE_HOST(imgComposite);
LogVerbose("depthnet: shutdown complete.\n");
return 0;
}
| 29.568905 | 163 | 0.672204 | jwkim386 |
562082d638a08a7b526766b534c24e7f8c3bd751 | 2,736 | cpp | C++ | philibs/img/imgfactory.cpp | prwhite/philibs | 3cb65bd0dae105026839a3e88d9cebafb72c2616 | [
"Zlib"
] | 5 | 2015-05-12T14:48:03.000Z | 2021-07-14T13:18:16.000Z | philibs/img/imgfactory.cpp | prwhite/philibs | 3cb65bd0dae105026839a3e88d9cebafb72c2616 | [
"Zlib"
] | null | null | null | philibs/img/imgfactory.cpp | prwhite/philibs | 3cb65bd0dae105026839a3e88d9cebafb72c2616 | [
"Zlib"
] | 1 | 2021-04-18T07:32:43.000Z | 2021-04-18T07:32:43.000Z | /////////////////////////////////////////////////////////////////////
//
// class: factory
//
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
#include "imgfactory.h"
#include "pnisearchpath.h"
#include "imgdds.h"
#include "imgtarga.h"
#include "imgcoreimage.h"
#include "imgpvr.h"
#include "pnidbg.h"
#include <string>
#include <algorithm>
/////////////////////////////////////////////////////////////////////
namespace {
std::string toLower ( std::string const& src )
{
std::string ret = src;
std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
return ret;
}
}
namespace img {
factory::factory ()
{
addLoader("dds", [] ( std::string const& fname ) { return dds::loadHelper ( fname ); } );
// addLoader("tga", [] ( std::string const& fname ) { return targa::loadHelper ( fname ); } );
#if defined __IPHONE_7_0 || defined __MAC_10_9
auto coreImageFunc = [] ( std::string const& fname ) { return coreImage::loadHelper(fname); };
addLoader("jpg", coreImageFunc);
addLoader("jpeg", coreImageFunc);
addLoader("png", coreImageFunc);
addLoader("tif", coreImageFunc);
addLoader("tiff", coreImageFunc);
addLoader("gif", coreImageFunc);
auto pvrImageFunc = [] ( std::string const& fname ) { return pvr::loadHelper(fname); };
addLoader("pvr",pvrImageFunc);
addLoader("pvrtc",pvrImageFunc);
#endif
}
factory& factory::getInstance ()
{
static factory* pFactory = 0;
if ( ! pFactory )
pFactory = new factory;
return *pFactory;
}
factory::LoadFuture factory::loadAsync ( std::string const& fname )
{
return mThreadPool.enqueue( [=]() { return this->loadSync( fname ); } );
}
base* factory::loadSync ( std::string const& cfname )
{
std::string fname;
if ( mSearchPath.resolve(cfname, fname))
{
std::string extension = toLower ( pni::pstd::searchPath::ext(fname) );
auto found = mLoadFunctions.find ( extension );
if ( found != mLoadFunctions.end () )
{
base* pImg = found->second ( fname );
if ( pImg )
pImg->setName(fname);
return pImg;
}
else
PNIDBGSTR("could not find loader for " << cfname);
}
else
PNIDBGSTR("could not resolve file for " << cfname);
return nullptr;
}
void factory::cancel ( LoadFuture const& loadFuture )
{
}
void factory::addLoader ( std::string const& extension, LoadFunction func )
{
mLoadFunctions[ toLower ( extension ) ] = func;
}
void factory::remLoader ( std::string const& extension )
{
auto found = mLoadFunctions.find ( toLower ( extension ) );
if ( found != mLoadFunctions.end () )
mLoadFunctions.erase ( found );
}
} // end namespace img
| 23.586207 | 96 | 0.580775 | prwhite |
56296f30b6ea852d654ad58454ab112417e7e3f9 | 11,736 | hpp | C++ | include/uzlmath_headers/fn_dwt.hpp | dmlux/UZLMathLib | 7055c798dca6e6dc1ce0233b9ca539994feb4ade | [
"BSD-3-Clause"
] | null | null | null | include/uzlmath_headers/fn_dwt.hpp | dmlux/UZLMathLib | 7055c798dca6e6dc1ce0233b9ca539994feb4ade | [
"BSD-3-Clause"
] | null | null | null | include/uzlmath_headers/fn_dwt.hpp | dmlux/UZLMathLib | 7055c798dca6e6dc1ce0233b9ca539994feb4ade | [
"BSD-3-Clause"
] | null | null | null | //
// fn_dwt.hpp
// UZLMathLib
//
// Created by Denis-Michael Lux on 03.05.15.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
//
#ifndef UZLMathLib_fn_dwt_hpp
#define UZLMathLib_fn_dwt_hpp
UZLMATH_NAMESPACE(DWT)
/*- For more information/implementation details see fn_dwt.cpp file! -*/
/*!
* @brief Computes the **quadrature weights** as a vector that is used for the DWT
* which is necessary for a bandwidth \f$B\f$ transform.
* @details The weights vector is a vector that contains the needed weights for the
* data vector. The elements can be expressed by
* \f{eqnarray*}{
* w_B(j) = \frac{2}{B}\sin\left(\frac{\pi(2j+1)}{4B}\right)
* \sum\limits_{k = 0}^{B-1}\frac{1}{2k + 1}
* \sin\left((2j+1)(2k+1)\frac{\pi}{4B}\right)
* \f}
* where \f$B\f$ is the bandlimit that is given and \f$0\leq j\leq 2B-1\f$.
* The dimension of this matrix is \f$2B\times 2B\f$
*
* @param[in] bandwidth The given bandwidth
* @return A vector containing the quadrature weights that can be used to compute the DWT
* \f{eqnarray*}{
* \begingroup
* \renewcommand*{\arraystretch}{1.5}
* W = \left(\begin{array}{c}
* w_B(0)\\
* w_B(1)\\
* \vdots\\
* w_B(2B-1)
* \end{array}\right)
* \endgroup
* \f}
*
* @since 0.0.1
*
* @author Denis-Michael Lux <denis.lux@icloud.com>
* @date 03.05.15
*/
template< typename T >
inline
void_number_type< T > quadrature_weights(vector< T >& vec)
{
if (vec.size & 1)
{
uzlmath_warning("%s", "uneven vector length in DWT::quadrature_weights. ");
return;
}
int i, k, bandwidth = vec.size / 2;
for (i = 0; i < bandwidth; ++i)
{
T wi = 2.0 / bandwidth * sin(constants< T >::pi * (2.0 * i + 1.0)/(4.0 * bandwidth));
T sum = 0;
for (k = 0; k < bandwidth; ++k)
{
sum += 1.0 / (2.0 * k + 1.0) * sin((2.0 * i + 1.0) * (2.0 * k + 1.0) * constants< T >::pi / (4.0 * bandwidth));
}
wi *= sum;
vec[i] = wi;
vec[2 * bandwidth - 1 - i] = wi;
}
}
/*!
* @brief The Wigner d-matrix where the weights are calculated onto the matrix values.
* @details Calculates \f$d\cdot w\f$ where \f$d\f$ is matrix containing wigner
* d-Function values on each entry and \f$w\f$ is diagonal matrix containing
* the quadrature weights on the diagonal.
*
* @param[in] bandwidth The given bandwidth.
* @param[in] M The order \f$M\f$ of \f$d^J_{MM'}\f$.
* @param[in] Mp The order \f$M'\f$ of \f$d^J_{MM'}\f$.
* @param[in] weights A vector containing the quadrature weights.
* @return A matix containing weighted values of Wigner d-function.
*
* @sa wigner::wiger_d_matrix
* @sa wigner::weight_matrix
*
* @since 0.0.1
*
* @author Denis-Michael Lux <denis.lux@icloud.com>
* @date 03.05.15
*/
template< typename T >
inline
void_number_type< T > weighted_wigner_d_matrix(matrix< T >& wig, const int& bandwidth, const int& M, const int& Mp, const vector< T >& weights)
{
// Definition of used indices and the matrix that will be returned
int i, j, minJ = std::max(abs(M), abs(Mp));
if ( wig.rows != bandwidth - minJ || wig.cols != 2 * bandwidth )
{
uzlmath_warning("%s", "dimension mismatch between input matrix and function arguments in DWT::weighted_wigner_d_matrix.");
return;
}
// Compute root coefficient for the base case
T normFactor = sqrt((2.0 * minJ + 1.0)/2.0);
for (i = 0 ; i < minJ - std::min(abs(M), abs(Mp)) ; ++i)
{
normFactor *= sqrt((2.0 * minJ - i) / (i + 1.0));
}
// Sin sign for the recurrence base case
T sinSign = (minJ == abs(M) && M >= 0 && (minJ - Mp) & 1 ? 1 : -1);
sinSign = (minJ != abs(M) && Mp < 0 && (minJ - Mp) & 1 ? sinSign : -1);
// Powers
T cosPower, sinPower;
if (minJ == abs(M) && M >= 0)
{
cosPower = minJ + Mp;
sinPower = minJ - Mp;
}
else if (minJ == abs(M))
{
cosPower = minJ - Mp;
sinPower = minJ + Mp;
}
else if (Mp >= 0)
{
cosPower = minJ + M;
sinPower = minJ - M;
}
else
{
cosPower = minJ - M;
sinPower = minJ + M;
}
// Base cases and filling matrix with values
T cosBeta[2 * bandwidth];
for (i = 0 ; i < 2 * bandwidth; ++i)
{
// Getting sin and cos values for the power operator
T sinHalfBeta = sin(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth));
T cosHalfBeta = cos(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth));
// Store cosine values for reuse in recurrence loop
cosBeta[i] = cos(((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth));
// Computing base wigners. filling the first row in matrix with those values
wig(0, i) = normFactor * sinSign * pow(sinHalfBeta, sinPower) * pow(cosHalfBeta, cosPower) * weights[i];
}
// Filling wigner matrix with values. Starting with second row and
// iterate to last row with index B - 1
for(i = 0 ; i < bandwidth - minJ - 1; ++i)
{
// Recurrence coefficients
T c1 = 0;
// Index for wigner function
T idx = minJ + i;
// Terms in recurrence
T norm = sqrt((2.0 * idx + 3.0) / (2.0 * idx + 1.0));
T nom = (idx + 1.0) * (2. * idx + 1.0);
T den = 1.0 / sqrt(((idx + 1) * (idx + 1) - M*M) * ((idx + 1) * (idx + 1) - Mp*Mp));
// Fractions
T f1 = norm * nom * den;
T f2 = 0;
// Correcting undefined values from division by zero
if (minJ + i != 0)
{
T t1 = sqrt((2.0 * idx + 3.0)/(2.0 * idx - 1.0) ) * (idx + 1.0)/idx ;
T t2 = sqrt((idx*idx - M*M) * (idx*idx - Mp*Mp));
c1 = -t1 * t2 * den;
f2 = -M*Mp / (idx * (idx + 1.));
}
// Filling matrix with next recurrence step value
for (j = 0; j < 2*bandwidth; ++j)
{
wig(i + 1, j) = c1 * (i == 0 ? 0 : wig(i - 1, j)) + wig(i, j) * f1 * (f2 + cosBeta[j]);
}
}
}
/*!
* @brief Generates the Wigner d-matrix which is a matrix that
* contains the results of the \f$L^2\f$-normalized Wigner
* d-function on each entry.
* @details The dimension of this matrix is \f$(B-J+1)\times 2B\f$ where
* \f$B\f$ denotes a given bandwidth.
*
* @param[in] bandwidth The given bandwidth
* @param[in] M The order \f$M\f$ for the \f$L^2\f$-normalized Wigner d-function
* @param[in] Mp The order \f$M'\f$ for the \f$L^2\f$-normalized Wigner d-function
* @return The resulting matrix looks as follows
* \f{eqnarray*}{
* \begingroup
* \renewcommand*{\arraystretch}{1.5}
* D = \left(\begin{array}{c c c c}
* \tilde{d}^J_{M,M'}(\beta_0) & \tilde{d}^J_{M,M'}(\beta_1)
* & \cdots & \tilde{d}^J_{M,M'}(\beta_{2B-1})\\
* \tilde{d}^{J+1}_{M,M'}(\beta_0) & \tilde{d}^{J+1}_{M,M'}(\beta_1)
* & \cdots & \tilde{d}^{J+1}_{M,M'}(\beta_{2B-1})\\
* \vdots & \vdots & \ddots & \vdots\\
* \tilde{d}^{B-1}_{M,M'}(\beta_0) & \tilde{d}^{B-1}_{M,M'}(\beta_1)
* & \cdots & \tilde{d}^{B-1}_{M,M'}(\beta_{2B-1})
* \end{array}\right)
* \endgroup
* \f}
* with \f$\beta_k = \frac{\pi(2k + 1)}{4B}\f$
*
* @since 0.0.1
*
* @author Denis-Michael Lux <denis.lux@icloud.com>
* @date 03.05.15
*
* @see wigner::wigner_d
* @see wigner::wigner_d_l2normalized
*/
template< typename T >
inline
void_number_type< T > wigner_d_matrix(matrix< T >& wig, const int& bandwidth, const int& M, const int& Mp)
{
// Definition of used indices and the matrix that will be returned
int i, j, minJ = std::max(abs(M), abs(Mp));
if ( wig.rows != bandwidth - minJ || wig.cols != 2 * bandwidth )
{
uzlmath_warning("%s", "dimension mismatch between input matrix and function arguments in DWT::weighted_wigner_d_matrix.");
return;
}
// Compute root coefficient for the base case
T normFactor = sqrt((2.0 * minJ + 1.0)/2.0);
for (i = 0 ; i < minJ - std::min(abs(M), abs(Mp)) ; ++i)
{
normFactor *= sqrt((2.0 * minJ - i) / (i + 1.0));
}
// Sin sign for the recurrence base case
T sinSign = (minJ == abs(M) && M >= 0 && (minJ - Mp) & 1 ? 1 : -1 );
sinSign = (minJ != abs(M) && Mp < 0 && (minJ - Mp) & 1 ? sinSign : -1);
// Powers
T cosPower, sinPower;
if (minJ == abs(M) && M >= 0)
{
cosPower = minJ + Mp;
sinPower = minJ - Mp;
}
else if (minJ == abs(M))
{
cosPower = minJ - Mp;
sinPower = minJ + Mp;
}
else if (Mp >= 0)
{
cosPower = minJ + M;
sinPower = minJ - M;
}
else
{
cosPower = minJ - M;
sinPower = minJ + M;
}
// Base cases and filling matrix with values
T cosBeta[2 * bandwidth];
for (i = 0 ; i < 2 * bandwidth; ++i)
{
// Getting sin and cos values for the power operator
T sinHalfBeta = sin(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth));
T cosHalfBeta = cos(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth));
// Store cosine values for reuse in recurrence loop
cosBeta[i] = cos(((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth));
// Computing base wigners
wig(0, i) = normFactor * sinSign * pow(sinHalfBeta, sinPower) * pow(cosHalfBeta, cosPower);
}
// Filling wigner matrix with values. Starting with second row and
// iterate to last row with index B - 1
for(i = 0 ; i < bandwidth - minJ - 1; ++i)
{
// Recurrence coefficients
T c1 = 0;
// Index for wigner function
T idx = minJ + i;
// Terms in recurrence
T norm = sqrt((2.0 * idx + 3.0) / (2.0 * idx + 1.0));
T nom = (idx + 1.0) * (2.0 * idx + 1.0);
T den = 1.0 / sqrt(((idx + 1) * (idx + 1) - M*M) * ((idx + 1) * (idx + 1) - Mp*Mp));
// Fractions
T f1 = norm * nom * den;
T f2 = 0;
// Correcting undefined values from division by zero
if (minJ + i != 0)
{
T t1 = sqrt((2.0 * idx + 3.0)/(2.0 * idx - 1.0) ) * (idx + 1.0)/idx ;
T t2 = sqrt((idx*idx - M*M) * (idx*idx - Mp*Mp));
c1 = -t1 * t2 * den;
f2 = -M*Mp / (idx * (idx + 1.0));
}
// Filling matrix with next recurrence step value
for (j = 0; j < 2 * bandwidth; ++j)
{
wig(i + 1, j) = c1 * (i == 0 ? 0 : wig(i - 1, j)) + wig(i, j) * f1 * (f2 + cosBeta[j]);
}
}
}
UZLMATH_NAMESPACE_END
#endif /* fn_dwt.hpp */
| 35.349398 | 143 | 0.488156 | dmlux |
562e5c423a39646e8abd87e6da118261201b90e5 | 1,311 | cpp | C++ | CodeSignal/Arcade/Intro/58-messageFromBinaryCode.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 6 | 2018-11-26T02:38:07.000Z | 2021-07-28T00:16:41.000Z | CodeSignal/Arcade/Intro/58-messageFromBinaryCode.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 1 | 2021-05-30T09:25:53.000Z | 2021-06-05T08:33:56.000Z | CodeSignal/Arcade/Intro/58-messageFromBinaryCode.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 4 | 2020-04-16T07:15:01.000Z | 2020-12-04T06:26:07.000Z | /*You are taking part in an Escape Room challenge designed specifically for programmers. In your efforts to find a clue, you've found a binary code written on the wall behind a vase, and realized that it must be an encrypted message. After some thought, your first guess is that each consecutive 8 bits of the code stand for the character with the corresponding extended ASCII code.
Assuming that your hunch is correct, decode the message.
Example
For code = "010010000110010101101100011011000110111100100001", the output should be
messageFromBinaryCode(code) = "Hello!".
The first 8 characters of the code are 01001000, which is 72 in the binary numeral system. 72 stands for H in the ASCII-table, so the first letter is H.
Other letters can be obtained in the same manner.
Input/Output
[execution time limit] 0.5 seconds (cpp)
[input] string code
A string, the encrypted message consisting of characters '0' and '1'.
Guaranteed constraints:
0 < code.length < 800.
[output] string
The decrypted message.
*/
std::string messageFromBinaryCode(std::string code) {
std::string result;
for (std::size_t i = 0; i<code.size(); i+=8) {
char c = static_cast<char>(std::stoi(code.substr(i, 8), nullptr, 2));
result.push_back(c);
}
return result;
}
| 35.432432 | 382 | 0.727689 | ravirathee |
562eed95c503484ba4ceb04bff339f3592889390 | 18,094 | cc | C++ | third_party/5pt-6pt-Li-Hartley/polydet.cc | youruncleda/relative_pose | cb613f210a812e03754fbfc9c2e93d1f6fe4a265 | [
"BSD-3-Clause"
] | 21 | 2020-07-08T17:58:17.000Z | 2022-02-28T03:58:37.000Z | matlab/basic_geometry/polydet.cc | leehsiu/SFRM | 2d22a92ea737f0a03b949c7a7801bd56232b5717 | [
"MIT"
] | null | null | null | matlab/basic_geometry/polydet.cc | leehsiu/SFRM | 2d22a92ea737f0a03b949c7a7801bd56232b5717 | [
"MIT"
] | 5 | 2020-07-24T01:26:28.000Z | 2020-10-13T13:32:48.000Z | // Copyright Richard Hartley, 2010
static const char *copyright = "Copyright Richard Hartley, 2010";
//--------------------------------------------------------------------------
// LICENSE INFORMATION
//
// 1. For academic/research users:
//
// This program is free for academic/research purpose: you can redistribute
// it and/or modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Under this academic/research condition, this program is distributed in
// the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.
//
// 2. For commercial OEMs, ISVs and VARs:
//
// For OEMs, ISVs, and VARs who distribute/modify/use this software
// (binaries or source code) with their products, and do not license and
// distribute their source code under the GPL, please contact NICTA
// (www.nicta.com.au), and NICTA will provide a flexible OEM Commercial
// License.
//
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "hidden6.h"
// #define RH_DEBUG
// For generating synthetic polynomials
const int ColumnDegree[] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
const int NRepetitions = 10000;
int stuffit () { return 1; }
static double urandom()
{
// Returns a real random between -1 and 1
const int MAXRAND = 65000;
return 4.0*((rand()%MAXRAND)/((double) MAXRAND) - 0.5);
// return rand() % 20 - 10.0;
}
void eval_poly (PolyMatrix &Q, PolyDegree °, double x)
{
// Evaluates the polynomial at a given value, overwriting it
for (int i=0; i<Nrows; i++)
for (int j=0; j<Ncols; j++)
{
// Evaluate the poly
for (int k=deg[i][j]-1; k>=0; k--)
Q[i][j][k] += x*Q[i][j][k+1];
// Set degree to zero
deg[i][j] = 0;
}
}
void cross_prod (
double a11[], int deg11,
double a12[], int deg12,
double a21[], int deg21,
double a22[], int deg22,
double a00[], double toep[], int deg00,
double res[], int &dres,
BMatrix B, int ¤t_size
)
{
// Does a single 2x2 cross multiplication
// Do the multiplcation in temporary storage
double temp[2*Maxdegree + 1];
// Work out the actual degree
int deg1 = deg11 + deg22;
int deg2 = deg12 + deg21;
int deg = (deg1 > deg2) ? deg1 : deg2;
// Clear out the temporary
memset (temp, 0, sizeof(temp));
// Now, start multiplying
for (int i=0; i<=deg11; i++)
for (int j=0; j<=deg22; j++)
temp[i+j] += a11[i]*a22[j];
for (int i=0; i<=deg12; i++)
for (int j=0; j<=deg21; j++)
temp[i+j] -= a12[i]*a21[j];
// Clear out the result -- not really necessary
memset (res, 0, (Maxdegree+1)*sizeof(double));
//-----------------------------------------------------
// This is the most tricky part of the code, to divide
// one polynomial into the other. By theory, the division
// should be exact, but it is not, because of roundoff error.
// we need to find a way to do this efficiently and accurately.
//-----------------------------------------------------
#define USE_TOEPLITZ
#ifdef USE_TOEPLITZ
// Now, divide by a00 - there should be no remainder
int sres;
polyquotient (temp, deg+1, a00, toep, deg00+1, res, sres, B, current_size);
dres = sres-1;
#else
// Now, divide by a00 - there should be no remainder
double *pres = &(res[deg-deg00]);
for (int d=deg; d>=deg00; d--)
{
// Work out the divisor
int td = d - deg00; // Degree of current term
double val = temp[d] / a00[deg00];
*(pres--) = val;
// Do the subtraction involved in the division
for (int j=0; j<deg00; j++)
temp[j+td] -= val * a00[j];
}
#endif
#ifdef RH_DEBUG
// Print the remainder
printf ("Remainder\n");
for (int i=0; i<deg00; i++)
printf ("\t%.5e\n", temp[i]);
#endif
// Set the degree of the term
dres = deg - deg00;
}
void det_preprocess_6pt (
PolyMatrix &Q,
PolyDegree degree,
int n_zero_roots // Number of roots known to be zero
)
{
// We do row-echelon form decomposition on the matrix to eliminate the
// trivial known roots.
// What is assumed here is the following.
// - the first row of the matrix consists of constants
// - the nullity of the matrix of constant terms is n_zero_roots,
// so when it is put in row-echelon form, the last n_zero_roots are zero.
// Initialize the list of and columns. We will do complete pivoting
const int nrows = Nrows - 1;
const int ncols = Nrows;
int rows[Nrows], cols[Nrows];
for (int i=0; i<nrows; i++) rows[i] = i+1; // Miss the first row
for (int i=0; i<ncols; i++) cols[i] = i;
// Eliminate one row at a time
for (int nr=nrows-1, nc=ncols-1; nr>=n_zero_roots; nr--,nc--)
{
// We must take the first row first to pivot around
double bestval = 0.0;
int bestrow = 0, bestcol = 0;
// Find the highest value to pivot around
for (int i=0; i<=nr; i++)
for (int j=0; j<=nc; j++)
{
double val=Q[rows[i]][cols[j]][0];
if (fabs(val) > bestval)
{
bestval = fabs(val);
bestrow = i; // Actually rows[i]
bestcol = j;
}
}
// #define RH_DEBUG
#ifdef RH_DEBUG
#undef RH_DEBUG
// Print out the best value
printf ("Pivot %d = %e at position %d %d\n",nr,
bestval, rows[bestrow], cols[bestcol]);
#endif
// Now, select this row as a pivot. Also keep track of rows pivoted
int prow = rows[bestrow];
rows[bestrow] = rows[nr]; // Replace pivot row by last row
rows[nr] = prow;
int pcol = cols[bestcol];
cols[bestcol] = cols[nc];
cols[nc] = pcol;
// Clear out all the values above and to the right
for (int i=0; i<nr; i++)
{
int iii = rows[i];
double fac = Q[iii][pcol][0] / Q[prow][pcol][0];
// Must do this to all the columns
for (int j=0; j<ncols; j++)
{
int jjj = cols[j];
int deg = degree[prow][jjj];
int dij = degree[iii][jjj];
if (deg>dij) degree[iii][jjj] = deg;
for (int d=0; d<=deg; d++)
{
if (d <= dij)
Q[iii][jjj][d] -= Q[prow][jjj][d] * fac;
else
Q[iii][jjj][d] = -Q[prow][jjj][d] * fac;
}
}
}
}
// Decrease the degree of the remaining rows
for (int i=0; i<n_zero_roots; i++)
{
int ii = rows[i];
for (int jj=0; jj<ncols; jj++)
{
// Decrease the degree of this element by one
for (int d=1; d<=degree[ii][jj]; d++)
Q[ii][jj][d-1] = Q[ii][jj][d];
degree[ii][jj] -= 1;
}
}
// #define RH_DEBUG
#ifdef RH_DEBUG
#undef RH_DEBUG
printf ("Degrees\n");
for (int i=0; i<Nrows; i++)
{
for (int j=0; j<Nrows; j++)
printf ("%1d ", degree[i][j]);
printf ("\n");
}
printf("\n");
printf ("Equation matrix\n");
for (int i=0; i<nrows; i++)
{
for (int j=0; j<ncols; j++)
printf ("%7.4f ", Q[rows[i]][cols[j]][0]);
printf ("\n");
}
printf ("\n");
#endif
}
double quick_compute_determinant (double A[Nrows][Nrows], int dim)
{
// Do row reduction on A to find the determinant (up to sign)
// Initialize the list of rows
int rows[Nrows];
for (int i=0; i<dim; i++) rows[i] = i;
// To accumulate the determinant
double sign = 1.0;
// Sweep out one row at a time
for (int p = dim-1; p>=0; p--)
{
// Find the highest value to pivot around, in column p
double bestval = 0.0;
int bestrow = 0;
for (int i=0; i<=p; i++)
{
double val=A[rows[i]][p];
if (fabs(val) > bestval)
{
bestval = fabs(val);
bestrow = i; // Actually rows[i]
}
}
// Return early if the determinant is zero
if (bestval == 0.0) return 0.0;
// Now, select this row as a pivot. Swap this row with row p
if (bestrow != p)
{
int prow = rows[bestrow];
rows[bestrow] = rows[p]; // Replace pivot row by last row
rows[p] = prow;
sign = -sign; // Keep track of sign
}
// Clear out all the values above and to the right
for (int i=0; i<p; i++)
{
int ii = rows[i];
double fac = A[ii][p] / A[rows[p]][p];
// Must do this to all the columns
for (int j=0; j<dim; j++)
A[ii][j] -= A[rows[p]][j] * fac;
}
}
// Now compute the determinant
double det = sign;
for (int i=0; i<dim; i++)
det *= A[rows[i]][i];
return det;
}
void do_scale (
PolyMatrix &Q,
PolyDegree degree,
double &scale_factor, // Value that x is multiplied by
bool degree_by_row, // Estimate degree from row degrees
int dim // Actual dimension of the matrix
)
{
// Scale the variable so that coefficients of low and high order are equal
// There is an assumption made here that the high order term of the
// determinant can be computed from the high-order values of each term,
// which is not in general true, but is so in the cases that we consider.
// First step is to compute these values
double low_order, high_order;
int total_degree;
// Find the coefficient of minimum degree term
double A[Nrows][Nrows];
for (int i=0; i<dim; i++)
for (int j=0; j<dim; j++)
A[i][j] = Q[i][j][0];
low_order = quick_compute_determinant (A, dim);
// printf ("Low order = %.7e\n", low_order);
// Find the coefficient of maximum degree term
total_degree = 0;
for (int i=0; i<dim; i++)
{
// Find what the degree of this row is
int rowdegree = -1;
if (degree_by_row)
{
for (int j=0; j<dim; j++)
if (degree[i][j] > rowdegree) rowdegree = degree[i][j];
for (int j=0; j<dim; j++)
if (degree[i][j] < rowdegree) A[i][j] = 0.0;
else A[i][j] = Q[i][j][rowdegree];
}
else
{
for (int j=0; j<dim; j++)
if (degree[j][i] > rowdegree) rowdegree = degree[j][i];
for (int j=0; j<dim; j++)
if (degree[j][i] < rowdegree) A[j][i] = 0.0;
else A[j][i] = Q[j][i][rowdegree];
}
// Accumulate the row degree
total_degree += rowdegree;
}
high_order = quick_compute_determinant (A, dim);
// printf ("High order = %.7e\n", high_order);
// Now, work out what the scale factor should be, and scale
scale_factor = pow(fabs(low_order/high_order), 1.0 / total_degree);
// printf ("Scale factor = %e\n", scale_factor);
for (int i=0; i<dim; i++)
for (int j=0; j<dim; j++)
{
double fac = scale_factor;
for (int d=1; d<=degree[i][j]; d++)
{
Q[i][j][d] *= fac;
fac *= scale_factor;
}
}
}
void find_polynomial_determinant (
PolyMatrix &Q,
PolyDegree deg,
int rows[Nrows], // This keeps the order of rows pivoted on.
int dim // Actual dimension of the matrix
)
{
// Compute the polynomial determinant - we work backwards from
// the end of the matrix. Do not bother with pivoting
// Polynomial to start with
double aa = 1.0;
double *a00 = &aa;
int deg00 = 0;
// Initialize the list of rows
for (int i=0; i<dim; i++)
rows[i] = dim-1-i;
// The row to pivot around. At end of the loop, this will be
// the row containing the result.
int piv;
for (int p = dim-1; p>=1; p--)
{
// We want to find the element with the biggest high order term to
// pivot around
#define DO_PARTIAL_PIVOT
#ifdef DO_PARTIAL_PIVOT
double bestval = 0.0;
int bestrow = 0;
for (int i=0; i<=p; i++)
{
double val=Q[rows[i]][p][deg[rows[i]][p]];
if (fabs(val) > bestval)
{
bestval = fabs(val);
bestrow = i; // Actually rows[i]
}
}
// Now, select this row as a pivot. Also keep track of rows pivoted
piv = rows[bestrow];
rows[bestrow] = rows[p]; // Replace pivot row by last row
rows[p] = piv;
#else
piv = rows[p];
#endif
// #define RH_DEBUG
#ifdef RH_DEBUG
#undef RH_DEBUG
// Print out the pivot
printf ("Pivot %d = \n", p);
for (int i=0; i<=deg[piv][p]; i++)
printf ("\t%16.5e\n", Q[piv][p][i]);
#endif
// Set up a matrix for Toeplitz
BMatrix B;
int current_size = 0;
// Also the Toeplitz vector
double toep[Maxdegree+1];
for (int i=0; i<=deg00; i++)
{
toep[i] = 0.0;
for (int j=0; j+i<=deg00; j++)
toep[i] += a00[j] * a00[j+i];
}
// Clear out all the values above and to the right
for (int i=0; i<p; i++)
{
int iii = rows[i];
for (int j=0; j<p; j++)
cross_prod (
Q[piv][p], deg[piv][p],
Q[piv][j], deg[piv][j],
Q[iii][p], deg[iii][p],
Q[iii][j], deg[iii][j],
a00, toep, deg00,
Q[iii][j], deg[iii][j], // Replace original value
B, current_size
);
}
// Now, update to the next
a00 = &(Q[piv][p][0]);
deg00 = deg[piv][p];
}
// Now, the polynomial in the position Q(0,0) is the solution
}
//=========================================================================
// The rest of this code is for stand-alone testing
//=========================================================================
#ifndef BUILD_MEX
#ifdef POLYDET_HAS_MAIN
void copy_poly (
PolyMatrix pin, PolyDegree din, PolyMatrix pout, PolyDegree dout)
{
memcpy (pout, pin, sizeof(PolyMatrix));
memcpy (dout, din, sizeof(PolyDegree));
}
int accuracy_test_main (int argc, char *argv[])
{
// Try this out
// To hold the matrix and its degrees
PolyMatrix p;
PolyDegree degrees;
int pivotrows[Nrows];
//--------------------------------------------------------
// Generate some data
for (int i=0; i<Nrows; i++)
for (int j=0; j<Ncols; j++)
degrees[i][j] = ColumnDegree[j];
// Now, fill out the polynomials
for (int i=0; i<Nrows; i++)
for (int j=0; j<Ncols; j++)
{
for (int k=0; k<=ColumnDegree[j]; k++)
p[i][j][k] = urandom();
for (int k=ColumnDegree[j]+1; k<=Maxdegree; k++)
p[i][j][k] = 0.0;
}
//--------------------------------------------------------
// Back up the matrix
PolyMatrix pbak;
PolyDegree degbak;
copy_poly (p, degrees, pbak, degbak);
//---------------------
// Find determinant, then evaluate
//---------------------
// Now, compute the determinant
copy_poly (pbak, degbak, p, degrees);
// Preprocess
double scale_factor = 1.0;
det_preprocess_6pt (p, degrees, 3);
do_scale (p, degrees, scale_factor, true);
// Find the determinant
find_polynomial_determinant (p, degrees, pivotrows);
// Print out the solution
const double print_solution = 0;
if (print_solution)
{
printf ("Solution is\n");
for (int i=0; i<=degrees[pivotrows[0]][0]; i++)
printf ("\t%16.5e\n", p[pivotrows[0]][0][i]);
}
// Now, evaluate and print out
double x = 1.0;
eval_poly (p, degrees, x);
double val1 = p[pivotrows[0]][0][0];
//---------------------
// Now, evaluate first
//---------------------
copy_poly (pbak, degbak, p, degrees);
// Now, evaluate and print out
eval_poly (p, degrees, x);
find_polynomial_determinant (p, degrees, pivotrows);
double val2 = p[pivotrows[0]][0][0];
double diff = fabs((fabs(val1) - fabs(val2))) / fabs(val1);
printf ("%18.9e\t%18.9e\t%10.3e\n", val1, val2, diff);
return 0;
}
int timing_test_main (int argc, char *argv[])
{
// Try this out
// To hold the matrix and its degrees
PolyMatrix p;
PolyDegree degrees;
int pivotrows[Nrows];
//--------------------------------------------------------
// Generate some data
for (int i=0; i<Nrows; i++)
for (int j=0; j<Ncols; j++)
degrees[i][j] = ColumnDegree[j];
// Now, fill out the polynomials
for (int i=0; i<Nrows; i++)
for (int j=0; j<Ncols; j++)
{
for (int k=0; k<=ColumnDegree[j]; k++)
p[i][j][k] = urandom();
for (int k=ColumnDegree[j]+1; k<=Maxdegree; k++)
p[i][j][k] = 0.0;
}
//--------------------------------------------------------
// Back up the matrix
PolyMatrix pbak;
PolyDegree degbak;
copy_poly (p, degrees, pbak, degbak);
// Now, compute the determinant
for (int rep=0; rep<NRepetitions; rep++)
{
copy_poly (pbak, degbak, p, degrees);
find_polynomial_determinant (p, degrees, pivotrows);
}
return 0;
}
//===========================================================================
int main (int argc, char *argv[])
{
// Now, compute the determinant
// for (int rep=0; rep<NRepetitions; rep++)
// accuracy_test_main (argc, argv);
timing_test_main (argc, argv);
return 0;
}
#endif
#endif // BUILD_MEX
| 27.751534 | 80 | 0.525036 | youruncleda |
563227327b4aa00b9493a105a2cd7965dee1c65a | 5,115 | cpp | C++ | example/clientlike/main.cpp | clodfront/jingke | ac6da9e73d7c69c7575267d2da52cdf6357e6dc9 | [
"Apache-2.0"
] | 6 | 2019-11-18T01:37:52.000Z | 2021-07-31T14:19:10.000Z | example/clientlike/main.cpp | clodfront/jingke | ac6da9e73d7c69c7575267d2da52cdf6357e6dc9 | [
"Apache-2.0"
] | null | null | null | example/clientlike/main.cpp | clodfront/jingke | ac6da9e73d7c69c7575267d2da52cdf6357e6dc9 | [
"Apache-2.0"
] | 1 | 2019-11-18T01:27:44.000Z | 2019-11-18T01:27:44.000Z | // Project: jingke
// File: main.cpp
// Created: 11/2019
// Author: Goof
//
// Copyright 2019-2020 Goof
//
// 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 <stddef.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "server.h"
#include "log_writer.h"
#include "test_protoc.h"
#include "test_cs.pb.h"
using namespace std;
using namespace jingke;
class CSProtocolParser : public CProtocolParser
{
public:
virtual size_t GetPackSize(const void* data_, size_t length_)
{
static SPackHead head;
if(!data_ || !length_)
return INVALID_PACK_SIZE;
constexpr size_t needsize = offsetof(SPackHead, len) + sizeof(head.len);
if(length_ < needsize)
return UNDETERMINED_PACK_SIZE;
uint32_t pack_len = ntohl(*((uint32_t*)((char*)data_ + offsetof(SPackHead, len))));
return pack_len;
}
virtual uint64_t GetAsyncKey(const void* data_, size_t length_)
{
return 0;
}
};
CSProtocolParser g_parser;
class CClinetLike : public IServer
{
public:
virtual CProtocolParser* GetClientParser(uint16_t listener_id_)
{
//no cfg listener_id
return NULL;
}
virtual CProtocolParser* GetServiceParser(uint16_t service_id_)
{
//no peer service cfg
if(1 == service_id_)
return &g_parser;
return NULL;
}
virtual void OnRecvClient(const void* data_, size_t data_len_, uint32_t session_id_, uint16_t listener_id_)
{
}
virtual void OnRecvService(const void* data_, size_t data_len_, uint16_t service_id_)
{
if(!data_ || data_len_ < sizeof(SPackHead))
return;
if(service_id_ != 1)
return;
SPackHead pack_head;
if(!ExampleMessageCoder::decode_head(data_, data_len_, pack_head))
return;
switch (pack_head.cmd)
{
case CSP::cs_cmd_fight_rsp:
{
CSP::CsFightRsp rsp;
if(!ExampleMessageCoder::decode_body(data_, data_len_, rsp))
return;
if(rsp.errcode())
{
LOG_ERROR("fight failed ec:%d", rsp.errcode());
}
else
{
LOG_INFO("fight done winner:%u", rsp.winnerid());
}
}
break;
case CSP::cs_cmd_query_rank_top3_rsp:
{
CSP::CsRankTop3Rsp rsp;
if(!ExampleMessageCoder::decode_body(data_, data_len_, rsp))
return;
if(rsp.errcode())
{
LOG_ERROR("query top3 failed ec:%d", rsp.errcode());
}
else
{
LOG_INFO("top3 info : valid num:%u", rsp.validnum());
for(int i=0; i<rsp.ids_size(); ++i)
{
LOG_INFO("top3 %dth:%u", i+1, rsp.ids(i));
}
}
}
break;
default:
LOG_ERROR("recv unknow cmd:%u failed. service_id=%u", pack_head.cmd, service_id_);
}
}
protected:
virtual int OnInit()
{
srand(time(0));
uint32_t id = SetMonoTimer(std::bind(&CClinetLike::ReqFight, this, std::placeholders::_1 ,std::placeholders::_2)
,3000 ,2000);
if(!id)
{
LOG_ERROR("SetMonoTimer failed");
return -1;
}
id = SetMonoTimer(std::bind(&CClinetLike::GetTop3, this, std::placeholders::_1 ,std::placeholders::_2)
,10000 ,60000);
if(!id)
{
LOG_ERROR("SetMonoTimer failed");
return -1;
}
LOG_INFO("CClinetLike::OnInit OK");
return 0;
}
virtual void OnFini() { LOG_INFO("CClinetLike::OnFini finish"); }
private:
void ReqFight(mstime_t mono_time_, uint16_t step_)
{
static char req_pack_buff[1024];
CSP::CsFightReq req;
uint32_t fighterid_a = 0;
uint32_t fighterid_b = 0;
fighterid_a = rand()%100 + 1;
do
{
fighterid_b = rand()%100 + 1;
} while (fighterid_b == fighterid_a);
req.set_fighterid_a(fighterid_a);
req.set_fighterid_b(fighterid_b);
SPackHead req_head;
req_head.cmd = CSP::cs_cmd_fight_req;
req_head.asyncid = 0;
size_t encode_size = 0;
if(!ExampleMessageCoder::encode(req_pack_buff, sizeof(req_pack_buff), req_head, &req, &encode_size))
return;
int ret = SendToService(1, req_pack_buff, encode_size);
if(ret != 0)
{
LOG_ERROR("SendToService failed, ret:%d", ret);
}
}
void GetTop3(mstime_t mono_time_, uint16_t step_)
{
static char req_pack_buff[1024];
CSP::CsRankTop3Req req;
req.set_order(0);
SPackHead req_head;
req_head.cmd = CSP::cs_cmd_query_rank_top3_req;
req_head.asyncid = 0;
size_t encode_size = 0;
if(!ExampleMessageCoder::encode(req_pack_buff, sizeof(req_pack_buff), req_head, &req, &encode_size))
return;
int ret = SendToService(1, req_pack_buff, encode_size);
if(ret != 0)
{
LOG_ERROR("SendToService failed, ret:%d", ret);
}
}
};
int main(int argc, char** argv)
{
if(argc < 2)
{
cout << "argc < 2" << endl;
return -1;
}
CClinetLike svr;
int ret = svr.Init(argv[1]);
if(ret != 0)
{
cout << "svr.Init fail. ret:" << ret << endl;
return -2;
}
svr.Run();
return 0;
}
| 23.571429 | 114 | 0.681134 | clodfront |
56331442fa99035ab7439b67bc60cb66a33b96c1 | 19,731 | cpp | C++ | src/scripting/backend/dynarrays.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | 2 | 2018-01-18T21:30:20.000Z | 2018-01-19T02:24:46.000Z | src/scripting/backend/dynarrays.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | src/scripting/backend/dynarrays.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | /*
** dynarray.cpp
**
** internal data types for dynamic arrays
**
**---------------------------------------------------------------------------
** Copyright 2016-2017 Christoph Oelckers
** 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.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
** 4. When not used as part of ZDoom or a ZDoom derivative, this code will be
** covered by 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 SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "tarray.h"
#include "dobject.h"
#include "vm.h"
#include "types.h"
// We need one specific type for each of the 7 integral VM types and instantiate the needed functions for each of them.
// Dynamic arrays cannot hold structs because for every type there'd need to be an internal implementation which is impossible.
typedef TArray<uint8_t> FDynArray_I8;
typedef TArray<uint16_t> FDynArray_I16;
typedef TArray<uint32_t> FDynArray_I32;
typedef TArray<float> FDynArray_F32;
typedef TArray<double> FDynArray_F64;
typedef TArray<void*> FDynArray_Ptr;
typedef TArray<DObject*> FDynArray_Obj;
typedef TArray<FString> FDynArray_String;
//-----------------------------------------------------
//
// Int8 array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_I8, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_POINTER(other, FDynArray_I8);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_POINTER(other, FDynArray_I8);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(val);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(val);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(index);
PARAM_INT(val);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_I8, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// Int16 array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_I16, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_POINTER(other, FDynArray_I16);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_POINTER(other, FDynArray_I16);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(val);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(val);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(index);
PARAM_INT(val);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_I16, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// Int32 array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_I32, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_POINTER(other, FDynArray_I32);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_POINTER(other, FDynArray_I32);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(val);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(val);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(index);
PARAM_INT(val);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_I32, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// Float32 array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_F32, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_POINTER(other, FDynArray_F32);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_POINTER(other, FDynArray_F32);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_FLOAT(val);
ACTION_RETURN_INT(self->Find((float)val));
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_FLOAT(val);
ACTION_RETURN_INT(self->Push((float)val));
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_INT(index);
PARAM_FLOAT(val);
self->Insert(index, (float)val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_F32, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// Float64 array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_F64, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_POINTER(other, FDynArray_F64);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_POINTER(other, FDynArray_F64);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_FLOAT(val);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_FLOAT(val);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_INT(index);
PARAM_FLOAT(val);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_F64, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// Pointer array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_POINTER(other, FDynArray_Ptr);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_POINTER(other, FDynArray_Ptr);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_POINTER(val, void);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_POINTER(val, void);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_INT(index);
PARAM_POINTER(val, void);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// Object array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_POINTER(other, FDynArray_Obj);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_POINTER(other, FDynArray_Obj);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_OBJECT(val, DObject);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_OBJECT(val, DObject);
GC::WriteBarrier(val);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_INT(index);
PARAM_OBJECT(val, DObject);
GC::WriteBarrier(val);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_Obj, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj);
self->Clear();
return 0;
}
//-----------------------------------------------------
//
// String array
//
//-----------------------------------------------------
DEFINE_ACTION_FUNCTION(FDynArray_String, Copy)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_POINTER(other, FDynArray_String);
*self = *other;
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Move)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_POINTER(other, FDynArray_String);
*self = std::move(*other);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Find)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_STRING(val);
ACTION_RETURN_INT(self->Find(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Push)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_STRING(val);
ACTION_RETURN_INT(self->Push(val));
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Pop)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
ACTION_RETURN_BOOL(self->Pop());
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Delete)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_INT(index);
PARAM_INT_DEF(count);
self->Delete(index, count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Insert)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_INT(index);
PARAM_STRING(val);
self->Insert(index, val);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, ShrinkToFit)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
self->ShrinkToFit();
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Grow)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_INT(count);
self->Grow(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Resize)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_INT(count);
self->Resize(count);
return 0;
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Reserve)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
PARAM_INT(count);
ACTION_RETURN_INT(self->Reserve(count));
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Max)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
ACTION_RETURN_INT(self->Max());
}
DEFINE_ACTION_FUNCTION(FDynArray_String, Clear)
{
PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String);
self->Clear();
return 0;
}
DEFINE_FIELD_NAMED_X(DynArray_I8, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_I16, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_I32, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_F32, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_F64, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_Ptr, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_Obj, FArray, Count, Size)
DEFINE_FIELD_NAMED_X(DynArray_String, FArray, Count, Size)
| 22.095185 | 127 | 0.746034 | raa-eruanna |
56340e785d1e0dcecb183c96fc3029c33d72f47b | 753 | cpp | C++ | engine/poker-lib/test-game-generator.cpp | torives/poker-updater-demo | 0a7be9e53ab3bd973296ced0561bbbd1a9dd1493 | [
"Apache-2.0"
] | 12 | 2021-06-30T17:04:00.000Z | 2022-03-11T18:34:51.000Z | engine/poker-lib/test-game-generator.cpp | torives/poker-updater-demo | 0a7be9e53ab3bd973296ced0561bbbd1a9dd1493 | [
"Apache-2.0"
] | 9 | 2021-06-29T06:45:44.000Z | 2022-02-11T23:26:13.000Z | engine/poker-lib/test-game-generator.cpp | torives/poker-updater-demo | 0a7be9e53ab3bd973296ced0561bbbd1a9dd1493 | [
"Apache-2.0"
] | 1 | 2022-01-07T12:03:19.000Z | 2022-01-07T12:03:19.000Z | #include <iostream>
#include <sstream>
#include <memory.h>
#include <inttypes.h>
#include "test-util.h"
#include "poker-lib.h"
#include "game-generator.h"
#define TEST_SUITE_NAME "Test game generator"
using namespace poker;
void the_happy_path() {
std::cout << "---- " TEST_SUITE_NAME << " - the_happy_path" << std::endl;
game_generator gen;
assert_eql(SUCCESS, gen.generate());
assert_neq(0, gen.raw_player_info.size());
assert_neq(0, gen.raw_turn_metadata.size());
assert_neq(0, gen.raw_verification_info.size());
assert_neq(0, gen.raw_turn_data.size());
}
int main(int argc, char** argv) {
init_poker_lib();
the_happy_path();
std::cout << "---- SUCCESS - " TEST_SUITE_NAME << std::endl;
return 0;
}
| 25.1 | 78 | 0.671979 | torives |
5638143f1b535d49bc43a8a008499f6dafbb1a29 | 6,861 | cpp | C++ | PolyEngine/CzolgInvaders/Src/InvadersGame.cpp | MuniuDev/PolyEngine | 9389537e4f551fa5dd621ebd3704e55b04c98792 | [
"MIT"
] | 1 | 2017-04-30T13:55:54.000Z | 2017-04-30T13:55:54.000Z | PolyEngine/CzolgInvaders/Src/InvadersGame.cpp | MuniuDev/PolyEngine | 9389537e4f551fa5dd621ebd3704e55b04c98792 | [
"MIT"
] | null | null | null | PolyEngine/CzolgInvaders/Src/InvadersGame.cpp | MuniuDev/PolyEngine | 9389537e4f551fa5dd621ebd3704e55b04c98792 | [
"MIT"
] | 3 | 2017-11-22T16:37:26.000Z | 2019-04-24T17:47:58.000Z | #include "InvadersGame.hpp"
#include <DeferredTaskSystem.hpp>
#include <CameraComponent.hpp>
#include <TransformComponent.hpp>
#include <MeshRenderingComponent.hpp>
#include <FreeFloatMovementComponent.hpp>
#include <ScreenSpaceTextComponent.hpp>
#include <Core.hpp>
#include <DeferredTaskSystem.hpp>
#include <ViewportWorldComponent.hpp>
#include <ResourceManager.hpp>
#include <SoundEmitterComponent.hpp>
#include <SoundSystem.hpp>
#include "GameManagerSystem.hpp"
#include "MovementComponent.hpp"
#include "MovementSystem.hpp"
#include "CollisionComponent.hpp"
#include "CollisionSystem.hpp"
#include "TankComponent.hpp"
using namespace Poly;
DEFINE_GAME(InvadersGame)
void InvadersGame::Init()
{
Engine->RegisterComponent<PlayerControllerComponent>((int)eGameComponents::PLAYERCONTROLLER);
Engine->RegisterComponent<BulletComponent>((int)eGameComponents::BULLET);
Engine->RegisterComponent<GameManagerComponent>((int)eGameComponents::GAMEMANAGER);
Engine->RegisterComponent<EnemyMovementComponent>((int)eGameComponents::ENEMYMOVEMENT);
Engine->RegisterComponent<Invaders::MovementSystem::MovementComponent>((int)eGameComponents::MOVEMENT);
Engine->RegisterComponent<Invaders::CollisionSystem::CollisionComponent>((int)eGameComponents::COLLISION);
Engine->RegisterComponent<Invaders::TankComponent>((int)eGameComponents::TANK);
Camera = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), Camera);
DeferredTaskSystem::AddComponentImmediate<Poly::CameraComponent>(Engine->GetWorld(), Camera, 60_deg, 1.0f, 1000.f);
DeferredTaskSystem::AddComponentImmediate<Poly::FreeFloatMovementComponent>(Engine->GetWorld(), Camera, 10.0f, 0.003f);
float y_pos = (float)Engine->GetRenderingDevice()->GetScreenSize().Height;
auto textDispaly = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<Poly::ScreenSpaceTextComponent>(Engine->GetWorld(), textDispaly, Vector{ 0.0f, y_pos ,0.0f }, "Fonts/Raleway/Raleway-Heavy.ttf", 32, "Kill count: 0");
GameManager = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<GameManagerComponent>(Engine->GetWorld(), GameManager, textDispaly);
GameManagerComponent* gameManagerComponent = Engine->GetWorld()->GetComponent<GameManagerComponent>(GameManager);
// Set some camera position
Poly::TransformComponent* cameraTrans = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(Camera);
cameraTrans->SetLocalTranslation(Vector(0.0f, 20.0f, 60.0f));
cameraTrans->SetLocalRotation(Quaternion({ 1, 0, 0 }, -30_deg));
for (int i = -10; i < 0; ++i)
{
for (int j = -2; j < 1; ++j)
{
auto ent = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), ent);
DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), ent, "model-tank/turret.fbx");
Poly::TransformComponent* entTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(ent);
auto base = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), base);
DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), base, "model-tank/base.fbx");
DeferredTaskSystem::AddComponentImmediate<Invaders::MovementSystem::MovementComponent>(Engine->GetWorld(), base, Vector(5, 0, 0), Vector(0, 0, 0), Quaternion(Vector(0, 0, 0), 0_deg), Quaternion(Vector(0, 0, 0), 0_deg));
DeferredTaskSystem::AddComponentImmediate<Invaders::CollisionSystem::CollisionComponent>(Engine->GetWorld(), base, Vector(0, 0, 0), Vector(5.0f, 5.0f, 5.0f));
DeferredTaskSystem::AddComponentImmediate<Invaders::TankComponent>(Engine->GetWorld(), base, ent, 12.0_deg, (i * j)%5 );
Poly::TransformComponent* baseTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(base);
entTransform->SetParent(baseTransform);
baseTransform->SetLocalTranslation(Vector(i * 12.f, 0.f, j * 8.f));
baseTransform->SetLocalRotation(Quaternion(Vector::UNIT_Y, -90.0_deg));
entTransform->SetLocalRotation(Quaternion(Vector::UNIT_Y, -60.0_deg));
}
}
auto player = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), player);
DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), player, "Models/tank2/bradle.3ds");
DeferredTaskSystem::AddComponentImmediate<PlayerControllerComponent>(Engine->GetWorld(), player, 10.0f);
DeferredTaskSystem::AddComponentImmediate<Poly::SoundEmitterComponent>(Engine->GetWorld(), player, "COJ2_Battle_Hard_Attack.ogg");
Poly::TransformComponent* entTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(player);
entTransform->SetLocalTranslation(Vector(0, 0, 50));
entTransform->SetLocalScale(10);
entTransform->SetLocalRotation(Quaternion(Vector::UNIT_Y, -90_deg) * Quaternion(Vector::UNIT_X, -90_deg));
Engine->GetWorld()->GetWorldComponent<ViewportWorldComponent>()->SetCamera(0, Engine->GetWorld()->GetComponent<Poly::CameraComponent>(Camera));
Engine->RegisterGameUpdatePhase(Invaders::MovementSystem::MovementUpdatePhase);
Engine->RegisterGameUpdatePhase(Invaders::CollisionSystem::CollisionUpdatePhase);
Engine->RegisterGameUpdatePhase(GameMainSystem::GameUpdate);
Engine->RegisterGameUpdatePhase(ControlSystem::ControlSystemPhase);
Engine->RegisterGameUpdatePhase(GameManagerSystem::GameManagerSystemPhase);
for(int x = -1; x <= 1; ++x)
for (int z = -1; z <= 1; ++z)
{
const float SCALE = 4.0f;
const float SIZE = 40.0f;
auto ground = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld());
DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), ground);
DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), ground, "Models/ground/ground.fbx");
Poly::TransformComponent* groundTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(ground);
groundTransform->SetLocalTranslation(Vector(x * SCALE * SIZE, 0, z * SCALE * SIZE));
groundTransform->SetLocalScale(SCALE);
}
// Precache bullet mesh
BulletMesh = Poly::ResourceManager<MeshResource>::Load("Models/bullet/lowpolybullet.obj");
};
void InvadersGame::Deinit()
{
DeferredTaskSystem::DestroyEntityImmediate(Engine->GetWorld(), Camera);
for(auto ent : GameEntities)
DeferredTaskSystem::DestroyEntityImmediate(Engine->GetWorld(), ent);
Poly::ResourceManager<MeshResource>::Release(BulletMesh);
};
void GameMainSystem::GameUpdate(Poly::World* /*world*/)
{
}
| 54.452381 | 222 | 0.78181 | MuniuDev |
56397e3bac7cb82ef1f1643229888efe6f106eb5 | 2,161 | cpp | C++ | src/Main.cpp | muhopensores/dmc3-inputs-thing | 2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719 | [
"MIT"
] | 5 | 2021-06-09T23:53:28.000Z | 2022-02-21T06:09:41.000Z | src/Main.cpp | muhopensores/dmc3-inputs-thing | 2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719 | [
"MIT"
] | 9 | 2021-06-09T23:52:43.000Z | 2021-09-17T14:05:47.000Z | src/Main.cpp | muhopensores/dmc3-inputs-thing | 2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719 | [
"MIT"
] | null | null | null | #include <thread>
#include <chrono>
#include <windows.h>
#include "ModFramework.hpp"
static HMODULE g_dinput;
static HMODULE g_styleswitcher;
#if 1
extern "C" {
// DirectInput8Create wrapper for dinput8.dll
__declspec(dllexport) HRESULT WINAPI direct_input8_create(HINSTANCE hinst, DWORD dw_version, const IID& riidltf, LPVOID* ppv_out, LPUNKNOWN punk_outer) {
// This needs to be done because when we include dinput.h in DInputHook,
// It is a redefinition, so we assign an export by not using the original name
#pragma comment(linker, "/EXPORT:DirectInput8Create=_direct_input8_create@20")
return ((decltype(direct_input8_create)*)GetProcAddress(g_dinput, "DirectInput8Create"))(hinst, dw_version, riidltf, ppv_out, punk_outer);
}
}
#endif
void failed() {
MessageBox(0, "DMC3 ModFramework: Unable to load the original version.dll. Please report this to the developer.", "ModFramework", 0);
ExitProcess(0);
}
void startup_thread() {
#ifndef NDEBUG
AllocConsole();
HANDLE handleOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD consoleMode;
GetConsoleMode( handleOut , &consoleMode);
consoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
consoleMode |= DISABLE_NEWLINE_AUTO_RETURN;
SetConsoleMode( handleOut , consoleMode );
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
#endif
#if 1
wchar_t buffer[MAX_PATH]{ 0 };
if (GetSystemDirectoryW(buffer, MAX_PATH) != 0) {
// Load the original dinput8.dll
if ((g_dinput = LoadLibraryW((std::wstring{ buffer } + L"\\dinput8.dll").c_str())) == NULL) {
failed();
}
g_framework = std::make_unique<ModFramework>();
}
else {
failed();
}
#else
g_framework = std::make_unique<ModFramework>();
#endif
}
BOOL APIENTRY DllMain(HMODULE handle, DWORD reason, LPVOID reserved) {
if (reason == DLL_PROCESS_ATTACH) {
LoadLibrary("StyleSwitcher.dll");
#ifndef NDEBUG
MessageBox(NULL, "Debug attach opportunity", "DMC3", MB_ICONINFORMATION);
#endif
CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)startup_thread, nullptr, 0, nullptr);
}
if (reason == DLL_PROCESS_DETACH) {
FreeLibrary(g_styleswitcher);
}
return TRUE;
} | 30.871429 | 154 | 0.73577 | muhopensores |
5639c61e5f2394e34ff497af6f77389582a24b91 | 7,331 | hpp | C++ | include/r2p/Topic.hpp | r2p/Middleware | 6438bdef16671482ecc1330679fa56439f916c61 | [
"BSD-2-Clause"
] | 1 | 2020-11-26T04:21:41.000Z | 2020-11-26T04:21:41.000Z | include/r2p/Topic.hpp | r2p/Middleware | 6438bdef16671482ecc1330679fa56439f916c61 | [
"BSD-2-Clause"
] | null | null | null | include/r2p/Topic.hpp | r2p/Middleware | 6438bdef16671482ecc1330679fa56439f916c61 | [
"BSD-2-Clause"
] | 1 | 2020-11-26T04:21:47.000Z | 2020-11-26T04:21:47.000Z | #pragma once
#include <r2p/common.hpp>
#include <r2p/NamingTraits.hpp>
#include <r2p/impl/MemoryPool_.hpp>
#include <r2p/StaticList.hpp>
#include <r2p/Time.hpp>
namespace r2p {
#if !defined(R2P_DEFAULT_FORWARDING) || defined(__DOXYGEN__)
#define R2P_DEFAULT_FORWARDING_RULE R2P_USE_BRIDGE_MODE
#endif
class Message;
class LocalPublisher;
class LocalSubscriber;
class RemotePublisher;
class RemoteSubscriber;
class Topic : private Uncopyable {
friend class Middleware;
private:
const char *const namep;
Time publish_timeout;
MemoryPool_ msg_pool;
size_t num_local_publishers;
size_t num_remote_publishers;
StaticList<LocalSubscriber> local_subscribers;
StaticList<RemoteSubscriber> remote_subscribers;
size_t max_queue_length;
#if R2P_USE_BRIDGE_MODE
bool forwarding;
#endif
StaticList<Topic>::Link by_middleware;
public:
const char *get_name() const;
const Time &get_publish_timeout() const;
size_t get_type_size() const;
size_t get_payload_size() const;
size_t get_max_queue_length() const;
bool is_forwarding() const;
bool has_local_publishers() const;
bool has_remote_publishers() const;
bool has_publishers() const;
bool has_local_subscribers() const;
bool has_remote_subscribers() const;
bool has_subscribers() const;
bool is_awaiting_advertisements() const;
bool is_awaiting_subscriptions() const;
const Time compute_deadline_unsafe(const Time ×tamp) const;
const Time compute_deadline_unsafe() const;
Message *alloc_unsafe();
template<typename MessageType> bool alloc_unsafe(MessageType *&msgp);
bool release_unsafe(Message &msg);
void free_unsafe(Message &msg);
bool notify_locals_unsafe(Message &msg, const Time ×tamp);
bool notify_remotes_unsafe(Message &msg, const Time ×tamp);
bool forward_copy_unsafe(const Message &msg, const Time ×tamp);
const Time compute_deadline(const Time ×tamp) const;
const Time compute_deadline() const;
Message *alloc();
template<typename MessageType> bool alloc(MessageType *&msgp);
bool release(Message &msg);
void free(Message &msg);
bool notify_locals(Message &msg, const Time ×tamp);
bool notify_remotes(Message &msg, const Time ×tamp);
bool forward_copy(const Message &msg, const Time ×tamp);
void extend_pool(Message array[], size_t arraylen);
void advertise(LocalPublisher &pub, const Time &publish_timeout);
void advertise(RemotePublisher &pub, const Time &publish_timeout);
void subscribe(LocalSubscriber &sub, size_t queue_length);
void subscribe(RemoteSubscriber &sub, size_t queue_length);
private:
void patch_pubsub_msg(Message &msg, Transport &transport) const;
public:
Topic(const char *namep, size_t type_size,
bool forwarding = R2P_DEFAULT_FORWARDING_RULE);
public:
static bool has_name(const Topic &topic, const char *namep);
};
class MessageGuard : private Uncopyable {
private:
Message &msg;
Topic &topic;
public:
MessageGuard(Message &msg, Topic &topic);
~MessageGuard();
};
class MessageGuardUnsafe : private Uncopyable {
private:
Message &msg;
Topic &topic;
public:
MessageGuardUnsafe(Message &msg, Topic &topic);
~MessageGuardUnsafe();
};
} // namespace r2p
#include <r2p/Message.hpp>
#include <r2p/LocalPublisher.hpp>
#include <r2p/LocalSubscriber.hpp>
#include <r2p/RemotePublisher.hpp>
#include <r2p/RemoteSubscriber.hpp>
namespace r2p {
inline
const char *Topic::get_name() const {
return namep;
}
inline
const Time &Topic::get_publish_timeout() const {
return publish_timeout;
}
inline
size_t Topic::get_type_size() const {
return msg_pool.get_item_size();
}
inline
size_t Topic::get_payload_size() const {
return Message::get_payload_size(msg_pool.get_item_size());
}
inline
size_t Topic::get_max_queue_length() const {
return max_queue_length;
}
inline
bool Topic::is_forwarding() const {
#if R2P_USE_BRIDGE_MODE
return forwarding;
#else
return R2P_DEFAULT_FORWARDING_RULE;
#endif
}
inline
bool Topic::has_local_publishers() const {
return num_local_publishers > 0;
}
inline
bool Topic::has_remote_publishers() const {
return num_remote_publishers > 0;
}
inline
bool Topic::has_publishers() const {
return num_local_publishers > 0 || num_remote_publishers > 0;
}
inline
bool Topic::has_local_subscribers() const {
return !local_subscribers.is_empty_unsafe();
}
inline
bool Topic::has_remote_subscribers() const {
return !remote_subscribers.is_empty_unsafe();
}
inline
bool Topic::has_subscribers() const {
return !local_subscribers.is_empty_unsafe() ||
!remote_subscribers.is_empty_unsafe();
}
inline
bool Topic::is_awaiting_advertisements() const {
return !has_local_publishers() && !has_remote_publishers() &&
has_local_subscribers();
}
inline
bool Topic::is_awaiting_subscriptions() const {
return !has_local_subscribers() && !has_remote_subscribers() &&
has_local_publishers();
}
inline
const Time Topic::compute_deadline_unsafe(const Time ×tamp) const {
return timestamp + publish_timeout;
}
inline
const Time Topic::compute_deadline_unsafe() const {
return compute_deadline_unsafe(Time::now());
}
inline
Message *Topic::alloc_unsafe() {
register Message *msgp = reinterpret_cast<Message *>(msg_pool.alloc_unsafe());
if (msgp != NULL) {
msgp->reset_unsafe();
return msgp;
}
return NULL;
}
template<typename MessageType> inline
bool Topic::alloc_unsafe(MessageType *&msgp) {
static_cast_check<MessageType, Message>();
return (msgp = reinterpret_cast<MessageType *>(alloc_unsafe())) != NULL;
}
inline
bool Topic::release_unsafe(Message &msg) {
if (!msg.release_unsafe()) {
free_unsafe(msg);
return true;
}
return false;
}
inline
void Topic::free_unsafe(Message &msg) {
msg_pool.free_unsafe(reinterpret_cast<void *>(&msg));
}
inline
const Time Topic::compute_deadline(const Time ×tamp) const {
SysLock::acquire();
const Time &deadline = compute_deadline_unsafe(timestamp);
SysLock::release();
return deadline;
}
inline
const Time Topic::compute_deadline() const {
return compute_deadline(Time::now());
}
template<typename MessageType> inline
bool Topic::alloc(MessageType *&msgp) {
static_cast_check<MessageType, Message>();
return (msgp = reinterpret_cast<MessageType *>(alloc())) != NULL;
}
inline
bool Topic::release(Message &msg) {
SysLock::acquire();
bool freed = release_unsafe(msg);
SysLock::release();
return freed;
}
inline
void Topic::free(Message &msg) {
msg_pool.free(reinterpret_cast<void *>(&msg));
}
inline
void Topic::extend_pool(Message array[], size_t arraylen) {
msg_pool.extend(array, arraylen);
}
inline
bool Topic::has_name(const Topic &topic, const char *namep) {
return namep != NULL && 0 == strncmp(topic.get_name(), namep,
NamingTraits<Topic>::MAX_LENGTH);
}
inline
MessageGuard::MessageGuard(Message &msg, Topic &topic)
:
msg(msg),
topic(topic)
{
msg.acquire();
}
inline
MessageGuard::~MessageGuard() {
topic.release(msg);
}
inline
MessageGuardUnsafe::MessageGuardUnsafe(Message &msg, Topic &topic)
:
msg(msg),
topic(topic)
{
msg.acquire_unsafe();
}
inline
MessageGuardUnsafe::~MessageGuardUnsafe() {
topic.release_unsafe(msg);
}
} // namespace r2p
| 19.343008 | 80 | 0.740554 | r2p |
563b9ce01f55c133a5e2a6ec6e24aa31d8bb83ce | 6,932 | cpp | C++ | Source/DirectConnectionLibLink.cpp | NewBlueFX/DirectConnect | 49482c8555695eee77eff0317d2d5689cea33ba7 | [
"MIT"
] | null | null | null | Source/DirectConnectionLibLink.cpp | NewBlueFX/DirectConnect | 49482c8555695eee77eff0317d2d5689cea33ba7 | [
"MIT"
] | null | null | null | Source/DirectConnectionLibLink.cpp | NewBlueFX/DirectConnect | 49482c8555695eee77eff0317d2d5689cea33ba7 | [
"MIT"
] | null | null | null | // DirectConnectionLibLink.cpp
/*
MIT License
Copyright (c) 2016,2018 NewBlue, Inc. <https://github.com/NewBlueFX>
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 "DirectConnectionLibLink.h"
#include "DirectConnectionInstanceCreator.h"
#include "DirectConnectionIPCClient.h"
#include "DirectConnectionGeneric.h"
#include <string>
#include <sstream>
#include <algorithm>
#include <locale>
#include <codecvt>
#ifdef _WIN32
# include <shellapi.h>
# define LIBLINKBASE_NEW_BLUE_REG_PATH_PREFIX L"Software\\NewBlue\\"
# ifdef _WIN64
# define LIBLINKBASE_INSTALL_PATH_KEY_NAME L"Install Path 64"
# else
# define LIBLINKBASE_INSTALL_PATH_KEY_NAME L"Install Path"
# endif
#elif __APPLE__
// While nothing
#else
# error Unsupported platform
#endif
namespace DCTL
{
namespace
{
bool CheckServerConnection(Port port)
{
// The most reliable way to check connection, it is to create the client for given port and call any function.
bool bConnected = false;
DirectConnectionIPCClient* pRpcClient = new DirectConnectionIPCClient(port, false, &bConnected);
if (bConnected)
{
// Send any metadata, we do not need if server will process it.
// We need to know if server is alive.
bConnected = (pRpcClient->SendGlobalMetadataFrame(-1, "") != DCERR_ServerShutdown);
}
pRpcClient->Release();
return bConnected;
}
}
DirectConnectionLibLink::DirectConnectionLibLink(const wchar_t* pwszHostName, const wchar_t* pwszSkuName,
bool bLaunchAppOnDemand, bool bEnableMultipleAppInstances)
: m_hostName(pwszHostName)
, m_wideSkuName(pwszSkuName)
, m_skuName(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> >().to_bytes(pwszSkuName))
, m_bLaunchAppOnDemand(bLaunchAppOnDemand)
, m_bEnableMultipleAppInstances(bEnableMultipleAppInstances)
{
// PID used for generating unique shared_memory name
const long long llPID = m_bEnableMultipleAppInstances ? DCTL::Utility::GetCurrentProcessId() : -1;
m_sHostPID = DCTL::Utility::ProcessIdToString(llPID);
}
DirectConnectionLibLink::~DirectConnectionLibLink()
{
}
void DirectConnectionLibLink::Clear()
{
std::lock_guard<std::recursive_mutex> lock(m_instanceCreatorsLock);
m_instanceCreators.clear();
}
std::list<PortAndChannels> DirectConnectionLibLink::GetAvailableSources()
{
// We will check and will launch only one time Standalone per this application.
static bool standaloneLaunched = false;
if (!standaloneLaunched)
{
static std::recursive_mutex globalCritSec;
std::lock_guard<std::recursive_mutex> lock(globalCritSec);
if (!standaloneLaunched)
{
if (m_bLaunchAppOnDemand)
{
if (!StandaloneApplication::IsLaunched(m_skuName.c_str(), m_sHostPID.data()))
{
StandaloneApplication::LaunchStandaloneApplication(m_skuName.c_str(), m_sHostPID.data());
}
standaloneLaunched = true;
}
}
}
auto portAndChannels = ServerPortAndChannels::GetAvailableSources(m_skuName.c_str(), m_sHostPID.data());
for (auto it = portAndChannels.begin(); it != portAndChannels.end();)
{
// Try to connect to each port to be sure that such port is alive.
// For example, two Standalone-s will be launched and one is crashed,
// the info for crashed app will be presented in portAndChannels.
if (CheckServerConnection(it->first))
{
// Working port
++it;
}
else
{
// Unworking port
it = portAndChannels.erase(it);
}
}
return portAndChannels;
}
IDirectConnection* DirectConnectionLibLink::CreateInstance(Port port, Channel channel)
{
std::lock_guard<std::recursive_mutex> lock(m_instanceCreatorsLock);
for (auto it = m_instanceCreators.begin(); it != m_instanceCreators.end();)
{
// Just in case, check that process is running.
// If it is not so, remove such DirectConnectionInstanceCreator.
if (!(*it)->IsProcessRunning())
{
// Remove this instance
it = m_instanceCreators.erase(it);
}
else
{
++it;
}
}
auto it = std::find_if(m_instanceCreators.begin(), m_instanceCreators.end(),
[&port](const InstanceCreatorPtr& ptr) { return ptr->GetStandaloneClientPort() == port; });
DirectConnectionInstanceCreator* instanceCreator = nullptr;
if (it == m_instanceCreators.end())
{
bool bInitialized = false;
// DirectConnectionInstanceCreator was not created for this port, create now.
auto creator = std::make_shared<DirectConnectionInstanceCreator>(port, &bInitialized);
NBAssert(bInitialized); // if result is false, seems DirectConnection output was destroyed between calls -
// GetAvailableSources() and CreateInstance(). It is normal,
// but need to check this case anyway, to be sure.
if (bInitialized)
{
m_instanceCreators.push_back(creator);
instanceCreator = creator.get();
}
}
else
{
instanceCreator = (*it).get();
}
IDirectConnection* pInstance = nullptr;
if (instanceCreator)
{
DirectConnectionInstance* pDCInstance = instanceCreator->CreateInstance(channel);
NBAssert(pDCInstance); // Client is down?
if (pDCInstance)
{
pDCInstance->QueryInterface(IID_DirectConnection, reinterpret_cast<void**>(&pInstance));
NBAssert(pInstance); // dev, self-check
pDCInstance->Release();
}
}
return pInstance;
}
DCResult DirectConnectionLibLink::CloseNTXProcesses()
{
std::lock_guard<std::recursive_mutex> lock(m_instanceCreatorsLock);
DCResult res = DCResult::DCERR_Failed;
const char* pszData = "<newblue_ext command=\"exitApp\" />";
for (auto it = m_instanceCreators.begin(); it != m_instanceCreators.end(); ++it)
{
// Just in case, check that process is running.
// If it is, we end the ntx process
if ((*it)->IsProcessRunning())
{
// Kill ntx process
res = (*it)->SendGlobalMetadataFrame(-1, pszData);
}
}
return res;
}
} // end namespace DCTL
| 29.12605 | 112 | 0.723168 | NewBlueFX |
56414bebcab6e456a5fc0e6049e856756ce9648d | 1,566 | hpp | C++ | src/Engine/Physics/Obb.hpp | DaftMat/Draft-Engine | 395b22c454a4c198824b158dbe8778babb4e11c6 | [
"MIT"
] | null | null | null | src/Engine/Physics/Obb.hpp | DaftMat/Draft-Engine | 395b22c454a4c198824b158dbe8778babb4e11c6 | [
"MIT"
] | null | null | null | src/Engine/Physics/Obb.hpp | DaftMat/Draft-Engine | 395b22c454a4c198824b158dbe8778babb4e11c6 | [
"MIT"
] | null | null | null | //
// Created by mathis on 28/02/2020.
//
#ifndef DAFT_ENGINE_OBB_HPP
#define DAFT_ENGINE_OBB_HPP
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <opengl_stuff.h>
#include <Utils/types.hpp>
#include <src/Utils/adapters.hpp>
/**
* Oriented Bounding Box.
* A Bounding Box that rotate with the affiliated object
*/
class Obb
{
public:
/** type of axis for obb planes */
enum AxisType { X = 0, Y, Z };
/** Default constructor.
* creates an untransformed obb.
*/
Obb() : m_aabb(), m_transform{Utils::Transform::Identity()} {}
/** Constructor.
*
* @param aabb - AABB of the affiliated object.
* @param transform - transformation of the object.
*/
Obb( const Utils::Aabb& aabb, const Utils::Transform& transform ) :
m_aabb{aabb},
m_transform{transform} {}
/** untransformed aabb min getter.
*
* @return aabb min.
*/
glm::vec3 min() const { return toGlm( m_aabb.min() ); }
/** untransformed aabb max getter.
*
* @return aabb max.
*/
glm::vec3 max() const { return toGlm( m_aabb.max() ); }
/** obb's position getter.
*
* @return position of OBB.
*/
glm::vec3 position() const;
/** util function for the axis of obb's planes.
*
* @param i - index of the axis (0, 1, 2)
* @return
*/
glm::vec3 axis( int i ) const;
glm::vec3 axis( AxisType i ) const { return axis( int( i ) ); }
private:
Utils::Aabb m_aabb;
Utils::Transform m_transform;
};
#endif // DAFT_ENGINE_OBB_HPP
| 22.056338 | 71 | 0.599617 | DaftMat |
56417ce9c512e29badff2616b97c9e0dfcc42a62 | 41,912 | hh | C++ | schemelib/scheme/objective/hash/XformHash.hh | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 25 | 2019-07-23T01:03:48.000Z | 2022-03-31T04:16:08.000Z | schemelib/scheme/objective/hash/XformHash.hh | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 13 | 2018-01-30T17:45:57.000Z | 2022-03-28T11:02:44.000Z | schemelib/scheme/objective/hash/XformHash.hh | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 14 | 2018-02-08T01:42:28.000Z | 2022-03-31T12:56:17.000Z | #ifndef INCLUDED_objective_hash_XformHash_HH
#define INCLUDED_objective_hash_XformHash_HH
#include "scheme/util/SimpleArray.hh"
#include "scheme/util/dilated_int.hh"
#include "scheme/nest/pmap/TetracontoctachoronMap.hh"
#include "scheme/numeric/util.hh"
#include "scheme/numeric/bcc_lattice.hh"
#include <boost/utility/binary.hpp>
namespace scheme { namespace objective { namespace hash {
template<class Float>
void get_transform_rotation(
Eigen::Transform<Float,3,Eigen::AffineCompact> const & x,
Eigen::Matrix<Float,3,3> & rotation
){
for(int i = 0; i < 9; ++i) rotation.data()[i] = x.data()[i];
}
template< class _Xform >
struct XformHash_Quat_BCC7_Zorder {
typedef uint64_t Key;
typedef _Xform Xform;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::BCC< 7, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<7,Float> F7;
typedef scheme::util::SimpleArray<7,uint64_t> I7;
static Key const ORI_MASK = ~ BOOST_BINARY( 11111111 11111111 11111000 01110000 11100001 11000011 10000111 00001110 );
static Key const ORI_MASK_NO0 = ~ BOOST_BINARY( 11111111 11111111 11111000 01110000 11100001 11000011 10000111 00001111 );
static Key const CART_MASK_NO0 = BOOST_BINARY( 11111111 11111111 11111000 01110000 11100001 11000011 10000111 00001110 );
Grid grid_;
int ori_nside_;
bool operator==( XformHash_Quat_BCC7_Zorder<Xform> const & o) const { return grid_ == o.grid_; }
bool operator!=( XformHash_Quat_BCC7_Zorder<Xform> const & o) const { return grid_ != o.grid_; }
static std::string name(){ return "XformHash_Quat_BCC7_Zorder"; }
Float cart_spacing() const { return grid_.width_[0]; }
XformHash_Quat_BCC7_Zorder() {}
XformHash_Quat_BCC7_Zorder( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) {
init( cart_resl, cart_resl, cart_bound );
}
XformHash_Quat_BCC7_Zorder( Float cart_resl, int ori_nside, Float cart_bound=512.0 ){
init_nside( ori_nside, cart_resl, cart_bound );
}
void init( Float cart_resl, Float ang_resl, Float cart_bound ) {
// bcc orientation grid covering radii
static float const covrad[61] = {
84.09702,54.20621,43.98427,31.58683,27.58101,22.72314,20.42103,17.58167,16.12208,14.44320,13.40178,12.15213,11.49567,
10.53203,10.11448, 9.32353, 8.89083, 8.38516, 7.95147, 7.54148, 7.23572, 6.85615, 6.63594, 6.35606, 6.13243, 5.90677,
5.72515, 5.45705, 5.28864, 5.06335, 4.97668, 4.78774, 4.68602, 4.51794, 4.46654, 4.28316, 4.20425, 4.08935, 3.93284,
3.84954, 3.74505, 3.70789, 3.58776, 3.51407, 3.45023, 3.41919, 3.28658, 3.24700, 3.16814, 3.08456, 3.02271, 2.96266,
2.91052, 2.86858, 2.85592, 2.78403, 2.71234, 2.69544, 2.63151, 2.57503, 2.59064 };
uint64_t ori_nside = 1;
while( covrad[ori_nside-1]*1.35 > ang_resl && ori_nside < 61 ) ++ori_nside; // TODO: fix this number!
init_nside( (int)ori_nside, cart_resl, cart_bound );
ori_nside_ = ori_nside;
}
void init_nside( int ori_nside, Float cart_resl, Float cart_bound ){
cart_resl /= sqrt(3)/2.0;
if( 2.0*cart_bound/cart_resl > 8192.0 ) throw std::out_of_range("too many cart cells, > 8192");
if( ori_nside > 62 ) throw std::out_of_range("too many ori cells");
// cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) );
// ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) );
I7 nside;
nside[0] = nside[1] = nside[2] = 2 * (int)(cart_bound/cart_resl)+1;
if( ori_nside % 2 == 0 )
nside[0] = nside[1] = nside[2] = nside[0]+1; // allows repr of 0,0,0... sometimes
nside[3] = nside[4] = nside[5] = nside[6] = ori_nside+1;
F7 lb,ub;
lb[0] = lb[1] = lb[2] = -cart_bound;
ub[0] = ub[1] = ub[2] = cart_bound;
lb[3] = lb[4] = lb[5] = lb[6] = -1.0-2.0/ori_nside;
ub[3] = ub[4] = ub[5] = ub[6] = 1.0;
grid_.init( nside, lb, ub );
// std::cout << "NSIDE " << nside << std::endl;
}
Key get_key( Xform const & x ) const {
Eigen::Matrix<Float,3,3> rotation;
get_transform_rotation( x, rotation );
Eigen::Quaternion<Float> q( rotation );
q = numeric::to_half_cell(q);
F7 f7;
f7[0] = x.translation()[0];
f7[1] = x.translation()[1];
f7[2] = x.translation()[2];
f7[3] = q.w();
f7[4] = q.x();
f7[5] = q.y();
f7[6] = q.z();
// std::cout << f7 << std::endl;
bool odd;
I7 i7 = grid_.get_indices( f7, odd );
// std::cout << std::endl << (i7[0]>>6) << " " << (i7[1]>>6) << " " << (i7[2]>>6) << " " << i7[3] << " " << i7[4] << " "
// << i7[5] << " " << i7[6] << " " << std::endl;
// std::cout << std::endl << i7 << std::endl;
Key key = odd;
key = key | (i7[0]>>6)<<57;
key = key | (i7[1]>>6)<<50;
key = key | (i7[2]>>6)<<43;
key = key | util::dilate<7>( i7[0] & 63 ) << 1;
key = key | util::dilate<7>( i7[1] & 63 ) << 2;
key = key | util::dilate<7>( i7[2] & 63 ) << 3;
key = key | util::dilate<7>( i7[3] ) << 4;
key = key | util::dilate<7>( i7[4] ) << 5;
key = key | util::dilate<7>( i7[5] ) << 6;
key = key | util::dilate<7>( i7[6] ) << 7;
return key;
}
I7 get_indices(Key key, bool & odd) const {
odd = key & (Key)1;
I7 i7;
i7[0] = (util::undilate<7>( key>>1 ) & 63) | ((key>>57)&127)<<6;
i7[1] = (util::undilate<7>( key>>2 ) & 63) | ((key>>50)&127)<<6;
i7[2] = (util::undilate<7>( key>>3 ) & 63) | ((key>>43)&127)<<6;
i7[3] = util::undilate<7>( key>>4 ) & 63;
i7[4] = util::undilate<7>( key>>5 ) & 63;
i7[5] = util::undilate<7>( key>>6 ) & 63;
i7[6] = util::undilate<7>( key>>7 ) & 63;
return i7;
}
Xform get_center(Key key) const {
bool odd;
I7 i7 = get_indices(key,odd);
// std::cout << i7 << std::endl << std::endl;
F7 f7 = grid_.get_center(i7,odd);
// std::cout << f7 << std::endl;
Eigen::Quaternion<Float> q( f7[3], f7[4], f7[5], f7[6] );
q.normalize();
// q = numeric::to_half_cell(q); // should be un-necessary
Xform center( q.matrix() );
center.translation()[0] = f7[0];
center.translation()[1] = f7[1];
center.translation()[2] = f7[2];
return center;
}
Key cart_shift_key(Key key, int dx, int dy, int dz, Key d_o=0) const {
Key o = key%2;
Key x = (util::undilate<7>( key>>1 ) & 63) | ((key>>57)&127)<<6;
Key y = (util::undilate<7>( key>>2 ) & 63) | ((key>>50)&127)<<6;
Key z = (util::undilate<7>( key>>3 ) & 63) | ((key>>43)&127)<<6;
x += dx; y += dy; z += dz;
o ^= d_o;
key &= ORI_MASK; // zero cart parts of key
key &= ~(Key)1; // zero even/odd
key |= o;
key |= (x>>6)<<57 | util::dilate<7>( x & 63 ) << 1;
key |= (y>>6)<<50 | util::dilate<7>( y & 63 ) << 2;
key |= (z>>6)<<43 | util::dilate<7>( z & 63 ) << 3;
return key;
}
Key approx_size() const { return grid_.size(); }
Key approx_nori() const {
static int const nori[63] = {
0, 53, 53, 181, 321, 665, 874, 1642, 1997, 2424, 3337, 4504, 5269, 6592, 8230, 10193,
11420, 14068, 16117, 19001, 21362, 25401, 29191, 33227, 37210, 41454, 45779, 51303, 57248, 62639, 69417, 76572,
83178, 92177, 99551,108790,117666,127850,138032,149535,159922,171989,183625,196557,209596,226672,239034,253897,
271773,288344,306917,324284,342088,364686,381262,405730,427540,450284,472265,498028,521872,547463};
return nori[ grid_.nside_[3]-2 ]; // -1 for 0-index, -1 for ori_side+1
}
Float cart_width() const { return grid_.width_[0]; }
Float ang_width() const { return grid_.width_[3]; }
Key asym_key(Key key, Key & isym) const {
// get o,w,x,y,z for orig key
Key o = key & (Key)1;
Key w = util::undilate<7>( key>>4 ) & 63;
Key x = util::undilate<7>( key>>5 ) & 63;
Key y = util::undilate<7>( key>>6 ) & 63;
Key z = util::undilate<7>( key>>7 ) & 63;
// std::cout << grid_.nside_[3]-o <<" " << o << " " << w << "\t" << x << "\t" << y << "\t" << z << std::endl;
// move to primaary
assert(o==0||o==1);
Key nside1 = grid_.nside_[3] - o;
isym = /*(w>nside1/2)<<3 |*/ (x<=nside1/2&&nside1!=2*x)<<2 | (y<=nside1/2&&nside1!=2*y)<<1 | (z<=nside1/2&&nside1!=2*z)<<0;
assert( w >= nside1/2 );
// w = w > nside1/2 ? w : nside1-w;
// std::cout << "FX " << (x <= nside1/2) << " " << (2*x==nside1) << std::endl;
// std::cout << "FY " << (y <= nside1/2) << " " << (2*y==nside1) << std::endl;
// std::cout << "FZ " << (z <= nside1/2) << " " << (2*z==nside1) << std::endl;
x = x > nside1/2 ? x : nside1-x;
y = y > nside1/2 ? y : nside1-y;
z = z > nside1/2 ? z : nside1-z;
// make new key
Key k = key & ~ORI_MASK;
k = k | o;
k = k | util::dilate<7>( w ) << 4;
k = k | util::dilate<7>( x ) << 5;
k = k | util::dilate<7>( y ) << 6;
k = k | util::dilate<7>( z ) << 7;
return k;
}
Key sym_key(Key key, Key isym) const {
// get o,w,x,y,z for orig key
Key o = key & (Key)1;
Key w = util::undilate<7>( key>>4 ) & 63;
Key x = util::undilate<7>( key>>5 ) & 63;
Key y = util::undilate<7>( key>>6 ) & 63;
Key z = util::undilate<7>( key>>7 ) & 63;
// std::cout << grid_.nside_[3]-o <<" " << o << " " << w << "\t" << x << "\t" << y << "\t" << z << std::endl;
// move to isym
Key nside1 = grid_.nside_[3] - o;
assert( w >= nside1/2 );
// w = (isym>>3)&1 ? w : nside1-w;
x = (isym>>2)&1 ? nside1-x : x;
y = (isym>>1)&1 ? nside1-y : y;
z = (isym>>0)&1 ? nside1-z : z;
// make new key
Key k = key & ~ORI_MASK;
k = k | o;
k = k | util::dilate<7>( w ) << 4;
k = k | util::dilate<7>( x ) << 5;
k = k | util::dilate<7>( y ) << 6;
k = k | util::dilate<7>( z ) << 7;
return k;
}
Key num_key_symmetries() const { return 16; }
void print_key(Key key) const {
bool odd;
I7 i7 = get_indices(key,odd);
std::cout << i7 << " " << odd << std::endl;
}
F7 lever_coord( Key key, Float lever_dist, F7 const & ref ) const {
bool odd;
I7 i7 = get_indices(key,odd);
F7 f7 = grid_.get_center(i7,odd);
Eigen::Quaternion<Float> q( f7[3], f7[4], f7[5], f7[6] );
q.normalize();
Eigen::Quaternion<Float> qref( ref[3], ref[4], ref[5], ref[6] );
bool const neg = q.dot( qref ) < 0.0;
f7[3] = ( neg? -q.w() : q.w() ) * lever_dist * 2.0;
f7[4] = ( neg? -q.x() : q.x() ) * lever_dist * 2.0;
f7[5] = ( neg? -q.y() : q.y() ) * lever_dist * 2.0;
f7[6] = ( neg? -q.z() : q.z() ) * lever_dist * 2.0;
return f7;
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// EVERYTHING BELOW THIS POINT MAY BE INCOMPLETE IN SOME WAY
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template< class _Xform >
struct XformHash_Quat_BCC7 {
typedef uint64_t Key;
typedef _Xform Xform;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::BCC< 7, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<7,Float> F7;
typedef scheme::util::SimpleArray<7,uint64_t> I7;
Float grid_size_;
Float grid_spacing_;
OriMap ori_map_;
Grid grid_;
int ori_nside_;
static std::string name(){ return "XformHash_Quat_BCC7"; }
XformHash_Quat_BCC7( Float cart_resl, Float ang_resl, Float cart_bound=512.0 )
{
cart_resl /= sqrt(3)/2.0; // TODO: fix this number!
// bcc orientation grid covering radii
static float const covrad[99] = {
84.09702,54.20621,43.98427,31.58683,27.58101,22.72314,20.42103,17.58167,16.12208,14.44320,13.40178,12.15213,11.49567,
10.53203,10.11448, 9.32353, 8.89083, 8.38516, 7.95147, 7.54148, 7.23572, 6.85615, 6.63594, 6.35606, 6.13243, 5.90677,
5.72515, 5.45705, 5.28864, 5.06335, 4.97668, 4.78774, 4.68602, 4.51794, 4.46654, 4.28316, 4.20425, 4.08935, 3.93284,
3.84954, 3.74505, 3.70789, 3.58776, 3.51407, 3.45023, 3.41919, 3.28658, 3.24700, 3.16814, 3.08456, 3.02271, 2.96266,
2.91052, 2.86858, 2.85592, 2.78403, 2.71234, 2.69544, 2.63151, 2.57503, 2.59064, 2.55367, 2.48010, 2.41046, 2.40289,
2.36125, 2.33856, 2.29815, 2.26979, 2.21838, 2.19458, 2.17881, 2.12842, 2.14030, 2.06959, 2.05272, 2.04950, 2.00790,
1.96385, 1.96788, 1.91474, 1.90942, 1.90965, 1.85602, 1.83792, 1.81660, 1.80228, 1.77532, 1.76455, 1.72948, 1.72179,
1.68324, 1.67009, 1.67239, 1.64719, 1.63832, 1.60963, 1.60093, 1.58911};
uint64_t ori_nside = 1;
while( covrad[ori_nside-1]*1.35 > ang_resl && ori_nside < 100 ) ++ori_nside;
ori_nside_ = ori_nside;
if( 2.0*cart_bound/cart_resl > 8192.0 ) throw std::out_of_range("too many cart cells, > 8192");
// cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) );
// ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) );
I7 nside;
nside[0] = nside[1] = nside[2] = 2.0*cart_bound/cart_resl;
nside[3] = nside[4] = nside[5] = nside[6] = ori_nside+2;
F7 ub;
ub[0] = ub[1] = ub[2] = cart_bound;
ub[3] = ub[4] = ub[5] = ub[6] = 1.0+2.0/ori_nside;
grid_.init( nside, -ub, ub );
}
Key get_key( Xform const & x ) const {
Eigen::Matrix<Float,3,3> rotation;
get_transform_rotation( x, rotation );
Eigen::Quaternion<Float> q( rotation );
q = numeric::to_half_cell(q);
F7 f7;
f7[0] = x.translation()[0];
f7[1] = x.translation()[1];
f7[2] = x.translation()[2];
f7[3] = q.w();
f7[4] = q.x();
f7[5] = q.y();
f7[6] = q.z();
// std::cout << f7 << std::endl;
Key key = grid_[f7];
return key;
}
Xform get_center(Key key) const {
F7 f7 = grid_[key];
// std::cout << f7 << std::endl;
Eigen::Quaternion<Float> q( f7[3], f7[4], f7[5], f7[6] );
q.normalize();
Xform center( q.matrix() );
center.translation()[0] = f7[0];
center.translation()[1] = f7[1];
center.translation()[2] = f7[2];
return center;
}
Key approx_size() const { return grid_.size(); }
Key approx_nori() const {
static int const nori[63] = {
0, 53, 53, 181, 321, 665, 874, 1642, 1997, 2424, 3337, 4504, 5269, 6592, 8230, 10193,
11420, 14068, 16117, 19001, 21362, 25401, 29191, 33227, 37210, 41454, 45779, 51303, 57248, 62639, 69417, 76572,
83178, 92177, 99551,108790,117666,127850,138032,149535,159922,171989,183625,196557,209596,226672,239034,253897,
271773,288344,306917,324284,342088,364686,381262,405730,427540,450284,472265,498028,521872,547463};
return nori[ grid_.nside_[3]-2 ]; // -1 for 0-index, -1 for ori_side+1
}
Float ang_width() const { return grid_.with_[3]; }
};
template< class Xform >
struct XformHash_bt24_BCC3_Zorder {
typedef uint64_t Key;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::BCC< 3, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<3,Float> F3;
typedef scheme::util::SimpleArray<3,uint64_t> I3;
Float grid_size_;
Float grid_spacing_;
OriMap ori_map_;
Grid cart_grid_, ori_grid_;
int ori_nside_;
static std::string name(){ return "XformHash_bt24_BCC3_Zorder"; }
XformHash_bt24_BCC3_Zorder( Float cart_resl, Float ang_resl, Float cart_bound=512.0 )
{
// bcc orientation grid covering radii
static float const covrad[64] = {
49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932,
4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235,
2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216,
1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436,
1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480,
0.86141, 0.84846, 0.83677, 0.82164 };
uint64_t ori_nside = 1;
while( covrad[ori_nside-1]*1.01 > ang_resl && ori_nside < 62 ) ++ori_nside;
ori_nside_ = ori_nside;
init( cart_resl, ori_nside, cart_bound );
}
XformHash_bt24_BCC3_Zorder( Float cart_resl, int ori_nside, Float cart_bound ){
init(cart_resl,ori_nside,cart_bound);
}
void init( Float cart_resl, int ori_nside, Float cart_bound ){
cart_resl /= 0.56; // TODO: fix this number!
// std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl;
if( 2*(int)(cart_bound/cart_resl) > 8192 ){
throw std::out_of_range("can have at most 8192 cart cells!");
}
cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) );
ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) );
// std::cout << "cart_bcc " << cart_grid_ << std::endl;
// std::cout << " ori_bcc " << ori_grid_ << std::endl;
// std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl;
}
// Key structure
// 5 bits bt24 cell index
// 7 bits high order cart X bits
// 7 bits high order cart Y bits
// 7 bits high order cart Z bits
// 36 bits 6*6 zorder cart/ori
// 2 bits cart/ori even/odd
Key get_key( Xform const & x ) const {
Eigen::Matrix3d rotation;
get_transform_rotation( x, rotation );
uint64_t cell_index;
F3 params;
ori_map_.value_to_params( rotation, 0, params, cell_index );
assert( cell_index < 24 );
assert( 0.0 <= params[0] && params[0] <= 1.0 );
assert( 0.0 <= params[1] && params[1] <= 1.0 );
assert( 0.0 <= params[2] && params[2] <= 1.0 );
bool ori_odd, cart_odd;
I3 ori_indices, cart_indices;
ori_indices = ori_grid_.get_indices( params, ori_odd );
F3 trans(x.translation());
cart_indices = cart_grid_.get_indices( trans, cart_odd );
// std::cout << "get_index " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl;
Key key;
key = cell_index << 59;
key = key | (cart_indices[0]>>6) << 52;
key = key | (cart_indices[1]>>6) << 45;
key = key | (cart_indices[2]>>6) << 38;
// 6*6 zorder
key = key>>2;
key = key | ( util::dilate<6>( ori_indices[0] ) << 0 );
key = key | ( util::dilate<6>( ori_indices[1] ) << 1 );
key = key | ( util::dilate<6>( ori_indices[2] ) << 2 );
key = key | ( util::dilate<6>( (cart_indices[0] & 63) ) << 3 );
key = key | ( util::dilate<6>( (cart_indices[1] & 63) ) << 4 );
key = key | ( util::dilate<6>( (cart_indices[2] & 63) ) << 5 );
key = key<<2;
// lowest two bits, even/odd
key = key | ori_odd | cart_odd<<1;
return key;
}
Xform get_center(Key key) const {
I3 cart_indices, ori_indices;
uint64_t cell_index = key >> 59;
cart_indices[0] = (((key>>52)&127) << 6) | (util::undilate<6>( (key>>5) ) & 63);
cart_indices[1] = (((key>>45)&127) << 6) | (util::undilate<6>( (key>>6) ) & 63);
cart_indices[2] = (((key>>38)&127) << 6) | (util::undilate<6>( (key>>7) ) & 63);
ori_indices[0] = util::undilate<6>( (key>>2)&(((uint64_t)1<<36)-1) ) & 63;
ori_indices[1] = util::undilate<6>( (key>>3)&(((uint64_t)1<<36)-1) ) & 63;
ori_indices[2] = util::undilate<6>( (key>>4)&(((uint64_t)1<<36)-1) ) & 63;
bool ori_odd = key & (Key)1;
bool cart_odd = key & (Key)2;
F3 trans = cart_grid_.get_center(cart_indices,cart_odd);
F3 params = ori_grid_.get_center(ori_indices,ori_odd);
Eigen::Matrix3d m;
ori_map_.params_to_value( params, cell_index, 0, m );
// std::cout << "get_center " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl;
Xform center( m );
center.translation()[0] = trans[0];
center.translation()[1] = trans[1];
center.translation()[2] = trans[2];
return center;
}
Key approx_size() const { return (ori_grid_.sizes_[0]-1)*(ori_grid_.sizes_[1]-1)*(ori_grid_.sizes_[2]-1)*2 * cart_grid_.size() * 24; }
Key approx_nori() const { throw std::logic_error("not implemented"); }
};
template< class Xform >
struct XformHash_bt24_BCC3 {
typedef uint64_t Key;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::BCC< 3, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<3,Float> F3;
typedef scheme::util::SimpleArray<3,uint64_t> I3;
Float grid_size_;
Float grid_spacing_;
OriMap ori_map_;
Grid cart_grid_, ori_grid_;
int ori_nside_;
static std::string name(){ return "XformHash_bt24_BCC3"; }
XformHash_bt24_BCC3( Float cart_resl, Float ang_resl, Float cart_bound=512.0 )
{
cart_resl /= 0.56; // TODO: fix this number!
// bcc orientation grid covering radii
static float const covrad[64] = { 49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932,
4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235,
2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216,
1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436,
1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480,
0.86141, 0.84846, 0.83677, 0.82164 };
uint64_t ori_nside = 1;
while( covrad[ori_nside-1]*1.01 > ang_resl && ori_nside < 62 ) ++ori_nside;
// std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl;
ori_nside_ = ori_nside;
if( 2*(int)(cart_bound/cart_resl) > 8192 ){
throw std::out_of_range("can have at most 8192 cart cells!");
}
cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) );
ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) );
// std::cout << "cart_bcc " << cart_grid_ << std::endl;
// std::cout << " ori_bcc " << ori_grid_ << std::endl;
// std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl;
}
Key get_key( Xform const & x ) const {
Eigen::Matrix3d rotation;
get_transform_rotation( x, rotation );
uint64_t cell_index;
F3 params;
ori_map_.value_to_params( rotation, 0, params, cell_index );
assert( cell_index < 24 );
assert( 0.0 <= params[0] && params[0] <= 1.0 );
assert( 0.0 <= params[1] && params[1] <= 1.0 );
assert( 0.0 <= params[2] && params[2] <= 1.0 );
F3 trans(x.translation());
Key ori_index, cart_index;
ori_index = ori_grid_[ params ];
cart_index = cart_grid_[ trans ];
// std::cout << cart_index << " " << ori_isndex << " " << cell_index << std::endl;
Key key;
key = cell_index << 59;
key = key | cart_index << 18;
key = key | ori_index;
return key;
}
Xform get_center(Key key) const {
I3 cart_indices, ori_indices;
Key cell_index = key >> 59;
Key cart_index = (key<<5)>>23;
Key ori_index = key & (((Key)1<<18)-1);
// std::cout << cart_index << " " << ori_index << " " << cell_index << std::endl;
F3 trans = cart_grid_[cart_index];
F3 params = ori_grid_[ori_index];
Eigen::Matrix3d m;
ori_map_.params_to_value( params, cell_index, 0, m );
Xform center( m );
center.translation()[0] = trans[0];
center.translation()[1] = trans[1];
center.translation()[2] = trans[2];
return center;
}
Key approx_size() const { return (ori_grid_.sizes_[0]-1)*(ori_grid_.sizes_[1]-1)*(ori_grid_.sizes_[2]-1)*2 * cart_grid_.size() * 24; }
Key approx_nori() const { throw std::logic_error("not implemented"); }
};
// TODO: make _Zorder version of XformHash_bt24_BCC6
template< class Xform >
struct XformHash_bt24_BCC6 {
typedef uint64_t Key;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::BCC< 6, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<3,Float> F3;
typedef scheme::util::SimpleArray<3,uint64_t> I3;
typedef scheme::util::SimpleArray<6,Float> F6;
typedef scheme::util::SimpleArray<6,uint64_t> I6;
Float grid_size_;
Float grid_spacing_;
OriMap ori_map_;
Grid grid_;
int ori_nside_;
static std::string name(){ return "XformHash_bt24_BCC6"; }
XformHash_bt24_BCC6(){}
XformHash_bt24_BCC6( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ){
init( cart_resl, ang_resl, cart_bound );
}
void init( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ){
// bcc orientation grid covering radii
static float const covrad[64] = {
49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932,
4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235,
2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216,
1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436,
1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480,
0.86141, 0.84846, 0.83677, 0.82164 };
uint64_t ori_nside = 1;
while( covrad[ori_nside-1]*1.45 > ang_resl && ori_nside < 62 ) ++ori_nside; // TODO: HACK multiplier!
ori_nside_ = ori_nside;
// std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
// std::cout << "ori_nside: " << ori_nside << std::endl;
// std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
init( cart_resl, (int)ori_nside, cart_bound );
}
XformHash_bt24_BCC6( Float cart_resl, int ori_nside, Float cart_bound ){
// std::cout << "ori_nside c'tor" << std::endl;
init( cart_resl, ori_nside, cart_bound );
}
void init( Float cart_resl, int ori_nside, Float cart_bound ){
cart_resl /= sqrt(3.0)/2.0; // TODO: HACK multiplier!
// std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl;
if( 2*(int)(cart_bound/cart_resl) > 8192 ){
throw std::out_of_range("can have at most 8192 cart cells!");
}
I6 nside;
nside[0] = nside[1] = nside[2] = 2.0*cart_bound/cart_resl;
nside[3] = nside[4] = nside[5] = ori_nside+1;
// std::cout << "SIDES: " << nside[0] << " " << nside[3] << std::endl;
F6 lb,ub;
lb[0] = lb[1] = lb[2] = -cart_bound;
ub[0] = ub[1] = ub[2] = cart_bound;
lb[3] = lb[4] = lb[5] = -1.0/ori_nside;
ub[3] = ub[4] = ub[5] = 1.0;
grid_.init( nside, lb, ub );
}
scheme::util::SimpleArray<7,Float> get_f7( Xform const & x ) const {
Eigen::Matrix<Float,3,3> rotation;
get_transform_rotation( x, rotation );
F3 params;
uint64_t cell_index;
// ori_map_.value_to_params( rotation, 0, params, cell_index );
{ // from TetracontoctachoronMap.hh
Eigen::Quaternion<Float> q(rotation);
numeric::get_cell_48cell_half( q.coeffs(), cell_index );
q = nest::pmap::hbt24_cellcen<Float>( cell_index ).inverse() * q;
q = numeric::to_half_cell(q);
params[0] = q.x()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
params[1] = q.y()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
params[2] = q.z()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
// assert( -0.0001 <= params[0] && params[0] <= 1.0001 );
// assert( -0.0001 <= params[1] && params[1] <= 1.0001 );
// assert( -0.0001 <= params[2] && params[2] <= 1.0001 );
}
assert( cell_index < 24 );
params[0] = fmax(0.0,params[0]);
params[1] = fmax(0.0,params[1]);
params[2] = fmax(0.0,params[2]);
params[0] = fmin(1.0,params[0]);
params[1] = fmin(1.0,params[1]);
params[2] = fmin(1.0,params[2]);
scheme::util::SimpleArray<7,Float> params6;
params6[0] = x.translation()[0];
params6[1] = x.translation()[1];
params6[2] = x.translation()[2];
params6[3] = params[0];
params6[4] = params[1];
params6[5] = params[2];
params6[6] = cell_index;
return params6;
}
Key get_key( Xform const & x ) const {
Eigen::Matrix<Float,3,3> rotation;
get_transform_rotation( x, rotation );
uint64_t cell_index;
F3 params;
// ori_map_.value_to_params( rotation, 0, params, cell_index );
{ // from TetracontoctachoronMap.hh
Eigen::Quaternion<Float> q(rotation);
numeric::get_cell_48cell_half( q.coeffs(), cell_index );
q = nest::pmap::hbt24_cellcen<Float>( cell_index ).inverse() * q;
q = numeric::to_half_cell(q);
params[0] = q.x()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
params[1] = q.y()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
params[2] = q.z()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
// assert( -0.0001 <= params[0] && params[0] <= 1.0001 );
// assert( -0.0001 <= params[1] && params[1] <= 1.0001 );
// assert( -0.0001 <= params[2] && params[2] <= 1.0001 );
}
assert( cell_index < 24 );
params[0] = fmax(0.0,params[0]);
params[1] = fmax(0.0,params[1]);
params[2] = fmax(0.0,params[2]);
params[0] = fmin(1.0,params[0]);
params[1] = fmin(1.0,params[1]);
params[2] = fmin(1.0,params[2]);
F6 params6;
params6[0] = x.translation()[0];
params6[1] = x.translation()[1];
params6[2] = x.translation()[2];
params6[3] = params[0];
params6[4] = params[1];
params6[5] = params[2];
return cell_index<<59 | grid_[params6];
}
std::vector<Key> get_key_and_nbrs( Xform const & x ) const {
Eigen::Matrix<Float,3,3> rotation;
get_transform_rotation( x, rotation );
uint64_t cell_index;
F3 params;
// ori_map_.value_to_params( rotation, 0, params, cell_index );
{ // from TetracontoctachoronMap.hh
Eigen::Quaternion<Float> q(rotation);
numeric::get_cell_48cell_half( q.coeffs(), cell_index );
q = nest::pmap::hbt24_cellcen<Float>( cell_index ).inverse() * q;
q = numeric::to_half_cell(q);
params[0] = q.x()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
params[1] = q.y()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
params[2] = q.z()/q.w()/nest::pmap::cell_width<Float>() + 0.5;
// assert( -0.0001 <= params[0] && params[0] <= 1.0001 );
// assert( -0.0001 <= params[1] && params[1] <= 1.0001 );
// assert( -0.0001 <= params[2] && params[2] <= 1.0001 );
}
assert( cell_index < 24 );
params[0] = fmax(0.0,params[0]);
params[1] = fmax(0.0,params[1]);
params[2] = fmax(0.0,params[2]);
params[0] = fmin(1.0,params[0]);
params[1] = fmin(1.0,params[1]);
params[2] = fmin(1.0,params[2]);
F6 params6;
params6[0] = x.translation()[0];
params6[1] = x.translation()[1];
params6[2] = x.translation()[2];
params6[3] = params[0];
params6[4] = params[1];
params6[5] = params[2];
uint64_t index = grid_[params6];
std::vector<Key> to_ret { index };
grid_.neighbors( index, std::back_inserter(to_ret), true );
for ( int i = 0; i < to_ret.size(); i++ ) {
to_ret[i] = cell_index<<59 | to_ret[i];
}
return to_ret;
}
Xform get_center(Key key) const {
Key cell_index = key >> 59;
F6 params6 = grid_[ key & (((Key)1<<59)-(Key)1) ];
F3 params;
params[0] = params6[3];
params[1] = params6[4];
params[2] = params6[5];
Eigen::Matrix<Float,3,3> m;
// ori_map_.params_to_value( params, cell_index, 0, m );
{
Float const & w(nest::pmap::cell_width<Float>());
// assert( params[0] >= -0.0001 && params[0] <= 1.0001 );
// assert( params[1] >= -0.0001 && params[1] <= 1.0001 );
// assert( params[2] >= -0.0001 && params[2] <= 1.0001 );
params[0] = fmax(0.0,params[0]);
params[1] = fmax(0.0,params[1]);
params[2] = fmax(0.0,params[2]);
params[0] = fmin(1.0,params[0]);
params[1] = fmin(1.0,params[1]);
params[2] = fmin(1.0,params[2]);
// std::cout << cell_index << " " << p << " " << p << std::endl;
// static int count = 0; if( ++count > 30 ) std::exit(-1);
params = w*(params-0.5); // now |params| < sqrt(2)-1
// Eigen::Quaternion<Float> q( sqrt(1.0-p.squaredNorm()), p[0], p[1], p[2] );
// assert( fabs(q.squaredNorm()-1.0) < 0.000001 );
Eigen::Quaternion<Float> q( 1.0, params[0], params[1], params[2] );
q.normalize();
q = nest::pmap::hbt24_cellcen<Float>( cell_index ) * q;
m = q.matrix();
}
Xform center( m );
center.translation()[0] = params6[0];
center.translation()[1] = params6[1];
center.translation()[2] = params6[2];
return center;
}
Key approx_size() const { return grid_.size() * 24; }
Key approx_nori() const {
static int const nori[18] = {
192, 648, 1521, 2855, 4990, 7917, 11682, 16693, 23011, 30471, 39504, 50464, 62849, 77169, 93903,112604,133352,157103
};
return nori[ grid_.nside_[3]-2 ]; // -1 for 0-index, -1 for ori_side+1
}
};
template< class Xform >
struct XformHash_bt24_Cubic_Zorder {
typedef uint64_t Key;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::Cubic< 3, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<3,Float> F3;
typedef scheme::util::SimpleArray<3,uint64_t> I3;
Float grid_size_;
Float grid_spacing_;
OriMap ori_map_;
Grid cart_grid_, ori_grid_;
int ori_nside_;
static std::string name(){ return "XformHash_bt24_Cubic_Zorder"; }
XformHash_bt24_Cubic_Zorder( Float cart_resl, Float ang_resl, Float cart_bound=512.0 )
{
cart_resl /= 0.867; // TODO: fix this number!
// bcc orientation grid covering radii
static float const covrad[64] = { 62.71876,39.26276,26.61019,20.06358,16.20437,13.45733,11.58808,10.10294, 9.00817, 8.12656, 7.37295,
6.74856, 6.23527, 5.77090, 5.38323, 5.07305, 4.76208, 4.50967, 4.25113, 4.04065, 3.88241, 3.68300,
3.53376, 3.36904, 3.22018, 3.13437, 2.99565, 2.89568, 2.78295, 2.70731, 2.61762, 2.52821, 2.45660,
2.37996, 2.31057, 2.25207, 2.18726, 2.13725, 2.08080, 2.02489, 1.97903, 1.92123, 1.88348, 1.83759,
1.79917, 1.76493, 1.72408, 1.68516, 1.64581, 1.62274, 1.57909, 1.55846, 1.52323, 1.50846, 1.47719,
1.44242, 1.42865, 1.39023, 1.37749, 1.34783, 1.32588, 1.31959, 1.29872, 1.26796 };
uint64_t ori_nside = 1;
while( covrad[ori_nside-1]*1.01 > ang_resl && ori_nside < 62 ) ++ori_nside;
// std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl;
ori_nside_ = ori_nside;
if( 2*(int)(cart_bound/cart_resl) > 8192 ){
throw std::out_of_range("can have at most 8192 cart cells!");
}
cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) );
ori_grid_.init( I3(ori_nside), F3(0.0), F3(1.0) );
// std::cout << "cart_bcc " << cart_grid_ << std::endl;
// std::cout << " ori_bcc " << ori_grid_ << std::endl;
// std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl;
}
Key get_key( Xform const & x ) const {
Eigen::Matrix3d rotation;
get_transform_rotation( x, rotation );
uint64_t cell_index;
F3 params;
ori_map_.value_to_params( rotation, 0, params, cell_index );
assert( cell_index < 24 );
assert( 0.0 <= params[0] && params[0] <= 1.0 );
assert( 0.0 <= params[1] && params[1] <= 1.0 );
assert( 0.0 <= params[2] && params[2] <= 1.0 );
I3 ori_indices, cart_indices;
ori_indices = ori_grid_.get_indices( params );
F3 trans(x.translation());
cart_indices = cart_grid_.get_indices( trans );
// std::cout << "get_index " << cell_index << " " << cart_indices << " " << ori_indices << std::endl;
Key key;
key = cell_index << 59;
key = key | (cart_indices[0]>>6) << 52;
key = key | (cart_indices[1]>>6) << 45;
key = key | (cart_indices[2]>>6) << 38;
// 6*6 zorder
key = key >> 2;
key = key | ( util::dilate<6>( ori_indices[0] ) << 0 );
key = key | ( util::dilate<6>( ori_indices[1] ) << 1 );
key = key | ( util::dilate<6>( ori_indices[2] ) << 2 );
key = key | ( util::dilate<6>( (cart_indices[0] & 63) ) << 3 );
key = key | ( util::dilate<6>( (cart_indices[1] & 63) ) << 4 );
key = key | ( util::dilate<6>( (cart_indices[2] & 63) ) << 5 );
key = key << 2;
return key;
}
Xform get_center(Key key) const {
I3 cart_indices, ori_indices;
uint64_t cell_index = key >> 59;
cart_indices[0] = (((key>>52)&127) << 6) | (util::undilate<6>( (key>>5) ) & 63);
cart_indices[1] = (((key>>45)&127) << 6) | (util::undilate<6>( (key>>6) ) & 63);
cart_indices[2] = (((key>>38)&127) << 6) | (util::undilate<6>( (key>>7) ) & 63);
ori_indices[0] = util::undilate<6>( (key>>2)&(((Key)1<<36)-1) ) & 63;
ori_indices[1] = util::undilate<6>( (key>>3)&(((Key)1<<36)-1) ) & 63;
ori_indices[2] = util::undilate<6>( (key>>4)&(((Key)1<<36)-1) ) & 63;
F3 trans = cart_grid_.get_center(cart_indices);
F3 params = ori_grid_.get_center(ori_indices);
// std::cout << "get_center " << cell_index << " " << cart_indices << " " << ori_indices << std::endl;
Eigen::Matrix3d m;
ori_map_.params_to_value( params, cell_index, 0, m );
Xform center( m );
center.translation()[0] = trans[0];
center.translation()[1] = trans[1];
center.translation()[2] = trans[2];
return center;
}
Key approx_size() const { return (ori_grid_.sizes_[0])*(ori_grid_.sizes_[1])*(ori_grid_.sizes_[2]) * cart_grid_.size() * 24; }
Key approx_nori() const { throw std::logic_error("not implemented"); }
};
template< class Xform >
struct XformHash_Quatgrid_Cubic {
typedef uint64_t Key;
typedef typename Xform::Scalar Float;
typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap;
typedef scheme::numeric::Cubic< 3, Float, uint64_t > Grid;
typedef scheme::util::SimpleArray<3,Float> F3;
typedef scheme::util::SimpleArray<3,uint64_t> I3;
Float grid_size_;
Float grid_spacing_;
OriMap ori_map_;
Grid cart_grid_, ori_grid_;
static std::string name(){ return "XformHash_Quatgrid_Cubic"; }
XformHash_Quatgrid_Cubic( Float cart_resl, Float ang_resl, Float cart_bound=512.0 )
{
cart_resl /= 0.56; // TODO: fix this number!
// bcc orientation grid covering radii
static float const covrad[64] = { 49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932,
4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235,
2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216,
1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436,
1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480,
0.86141, 0.84846, 0.83677, 0.82164 };
uint64_t ori_nside = 1;
while( covrad[ori_nside-1] > ang_resl && ori_nside < 62 ) ++ori_nside;
// std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl;
if( 2*(int)(cart_bound/cart_resl) > 8192 ){
throw std::out_of_range("can have at most 8192 cart cells!");
}
cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) );
ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) );
// std::cout << "cart_bcc " << cart_grid_ << std::endl;
// std::cout << " ori_bcc " << ori_grid_ << std::endl;
// std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl;
}
Key get_key( Xform const & x ) const {
Eigen::Matrix3d rotation;
get_transform_rotation( x, rotation );
uint64_t cell_index;
F3 params;
ori_map_.value_to_params( rotation, 0, params, cell_index );
assert( cell_index < 24 );
assert( 0.0 <= params[0] && params[0] <= 1.0 );
assert( 0.0 <= params[1] && params[1] <= 1.0 );
assert( 0.0 <= params[2] && params[2] <= 1.0 );
bool ori_odd, cart_odd;
I3 ori_indices, cart_indices;
ori_indices = ori_grid_.get_indices( params, ori_odd );
F3 trans(x.translation());
cart_indices = cart_grid_.get_indices( trans, cart_odd );
// std::cout << "get_index " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl;
Key key;
key = cell_index << 59;
key = key | (cart_indices[0]>>6) << 52;
key = key | (cart_indices[1]>>6) << 45;
key = key | (cart_indices[2]>>6) << 38;
// 6*6 zorder
key = key>>2;
key = key | ( util::dilate<6>( ori_indices[0] ) << 0 );
key = key | ( util::dilate<6>( ori_indices[1] ) << 1 );
key = key | ( util::dilate<6>( ori_indices[2] ) << 2 );
key = key | ( util::dilate<6>( (cart_indices[0] & 63) ) << 3 );
key = key | ( util::dilate<6>( (cart_indices[1] & 63) ) << 4 );
key = key | ( util::dilate<6>( (cart_indices[2] & 63) ) << 5 );
key = key<<2;
// lowest two bits, even/odd
key = key | ori_odd | cart_odd<<1;
return key;
}
Xform get_center(Key key) const {
I3 cart_indices, ori_indices;
uint64_t cell_index = key >> 59;
cart_indices[0] = (((key>>52)&127) << 6) | (util::undilate<6>( (key>>5) ) & 63);
cart_indices[1] = (((key>>45)&127) << 6) | (util::undilate<6>( (key>>6) ) & 63);
cart_indices[2] = (((key>>38)&127) << 6) | (util::undilate<6>( (key>>7) ) & 63);
ori_indices[0] = util::undilate<6>( (key>>2)&(((Key)1<<36)-1) ) & 63;
ori_indices[1] = util::undilate<6>( (key>>3)&(((Key)1<<36)-1) ) & 63;
ori_indices[2] = util::undilate<6>( (key>>4)&(((Key)1<<36)-1) ) & 63;
bool ori_odd = key & (Key)1;
bool cart_odd = key & (Key)2;
F3 trans = cart_grid_.get_center(cart_indices,cart_odd);
F3 params = ori_grid_.get_center(ori_indices,ori_odd);
Eigen::Matrix3d m;
ori_map_.params_to_value( params, cell_index, 0, m );
// std::cout << "get_center " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl;
Xform center( m );
center.translation()[0] = trans[0];
center.translation()[1] = trans[1];
center.translation()[2] = trans[2];
return center;
}
Key approx_size() const { return ori_grid_.size() * cart_grid_.size() * 24; }
Key approx_nori() const { throw std::logic_error("not implemented"); }
};
}}}
#endif
| 37.45487 | 144 | 0.605292 | YaoYinYing |
5645417f6bc160fb11a7e02a0bfee4454aa1d402 | 19,920 | cc | C++ | src/rocksdb2/table/plain_table_reader.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 5 | 2019-01-23T04:36:03.000Z | 2020-02-04T07:10:39.000Z | src/rocksdb2/table/plain_table_reader.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | null | null | null | src/rocksdb2/table/plain_table_reader.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 2 | 2019-05-14T07:26:59.000Z | 2020-06-15T07:25:01.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2011 LevelDB作者。版权所有。
//此源代码的使用受可以
//在许可证文件中找到。有关参与者的名称,请参阅作者文件。
#ifndef ROCKSDB_LITE
#include "table/plain_table_reader.h"
#include <string>
#include <vector>
#include "db/dbformat.h"
#include "rocksdb/cache.h"
#include "rocksdb/comparator.h"
#include "rocksdb/env.h"
#include "rocksdb/filter_policy.h"
#include "rocksdb/options.h"
#include "rocksdb/statistics.h"
#include "table/block.h"
#include "table/bloom_block.h"
#include "table/filter_block.h"
#include "table/format.h"
#include "table/internal_iterator.h"
#include "table/meta_blocks.h"
#include "table/two_level_iterator.h"
#include "table/plain_table_factory.h"
#include "table/plain_table_key_coding.h"
#include "table/get_context.h"
#include "monitoring/histogram.h"
#include "monitoring/perf_context_imp.h"
#include "util/arena.h"
#include "util/coding.h"
#include "util/dynamic_bloom.h"
#include "util/hash.h"
#include "util/murmurhash.h"
#include "util/stop_watch.h"
#include "util/string_util.h"
namespace rocksdb {
namespace {
//从char数组安全地获取uint32_t元素,其中,从
//‘base`,每4个字节被视为一个固定的32位整数。
inline uint32_t GetFixed32Element(const char* base, size_t offset) {
return DecodeFixed32(base + offset * sizeof(uint32_t));
}
} //命名空间
//迭代索引表的迭代器
class PlainTableIterator : public InternalIterator {
public:
explicit PlainTableIterator(PlainTableReader* table, bool use_prefix_seek);
~PlainTableIterator();
bool Valid() const override;
void SeekToFirst() override;
void SeekToLast() override;
void Seek(const Slice& target) override;
void SeekForPrev(const Slice& target) override;
void Next() override;
void Prev() override;
Slice key() const override;
Slice value() const override;
Status status() const override;
private:
PlainTableReader* table_;
PlainTableKeyDecoder decoder_;
bool use_prefix_seek_;
uint32_t offset_;
uint32_t next_offset_;
Slice key_;
Slice value_;
Status status_;
//不允许复制
PlainTableIterator(const PlainTableIterator&) = delete;
void operator=(const Iterator&) = delete;
};
extern const uint64_t kPlainTableMagicNumber;
PlainTableReader::PlainTableReader(const ImmutableCFOptions& ioptions,
unique_ptr<RandomAccessFileReader>&& file,
const EnvOptions& storage_options,
const InternalKeyComparator& icomparator,
EncodingType encoding_type,
uint64_t file_size,
const TableProperties* table_properties)
: internal_comparator_(icomparator),
encoding_type_(encoding_type),
full_scan_mode_(false),
user_key_len_(static_cast<uint32_t>(table_properties->fixed_key_len)),
prefix_extractor_(ioptions.prefix_extractor),
enable_bloom_(false),
bloom_(6, nullptr),
file_info_(std::move(file), storage_options,
static_cast<uint32_t>(table_properties->data_size)),
ioptions_(ioptions),
file_size_(file_size),
table_properties_(nullptr) {}
PlainTableReader::~PlainTableReader() {
}
Status PlainTableReader::Open(const ImmutableCFOptions& ioptions,
const EnvOptions& env_options,
const InternalKeyComparator& internal_comparator,
unique_ptr<RandomAccessFileReader>&& file,
uint64_t file_size,
unique_ptr<TableReader>* table_reader,
const int bloom_bits_per_key,
double hash_table_ratio, size_t index_sparseness,
size_t huge_page_tlb_size, bool full_scan_mode) {
if (file_size > PlainTableIndex::kMaxFileSize) {
return Status::NotSupported("File is too large for PlainTableReader!");
}
TableProperties* props = nullptr;
auto s = ReadTableProperties(file.get(), file_size, kPlainTableMagicNumber,
ioptions, &props);
if (!s.ok()) {
return s;
}
assert(hash_table_ratio >= 0.0);
auto& user_props = props->user_collected_properties;
auto prefix_extractor_in_file = props->prefix_extractor_name;
if (!full_scan_mode &&
/*efix_提取器_in_file.empty()/*旧版sst文件*/
&prefix提取程序在文件中!=“null pTr”){
如果(!)ioptions.prefix_提取器)
返回状态::invalidArgument(
“打开生成的普通表时缺少前缀提取程序”
“使用前缀提取程序”);
else if(前缀_extractor_in_file.compare(
ioptions.prefix_extractor->name())!= 0){
返回状态::invalidArgument(
“给定的前缀提取程序与用于生成的前缀提取程序不匹配”
“明码表”;
}
}
编码类型编码类型=kplain;
自动编码\类型\属性=
用户属性查找(plainTablePropertyNames::kencodingType);
如果(编码\类型\属性!=user_props.end())
encoding_type=static_cast<encoding type>
decodeFixed32(encoding_type_prop->second.c_str());
}
std::unique_ptr<plaintablereader>new_reader(new plaintablereader(
ioptions,std::move(file),env_选项,internal_comparator,
编码类型、文件大小、属性);
s=new_reader->mmapdationFeeded();
如果(!)S.O.()){
返回S;
}
如果(!)全扫描模式)
s=new_reader->populateindex(props,bloom_bits_per_key,hash_table_ratio,
索引稀疏度,巨大的页面大小);
如果(!)S.O.()){
返回S;
}
}否则{
//指示它是完全扫描模式的标志,以便没有任何索引
/可以使用。
新的读卡器->全扫描模式uu=true;
}
*表读卡器=标准::移动(新读卡器);
返回S;
}
void plainTableReader::SetupForCompaction()
}
InternalIterator*PlainTableReader::NewIterator(const readoptions&options,
竞技场*竞技场,
bool skip_filters)_
bool use_prefix_seek=!istotalOrderMode()&&!选项。总订单搜索;
如果(竞技场==nullptr)
返回新的PlainTableIterator(这将使用前缀\u seek);
}否则{
auto mem=arena->allocateAligned(sizeof(plainTableIterator));
返回new(mem)plainTableIterator(这个,使用前缀\u seek);
}
}
状态PlainTableReader::PopulateIndexRecordList(
plainTableIndexBuilder*索引生成器,vector<uint32_t>*前缀_hashes)
切片前一个键前缀切片;
std::字符串prev_key_prefix_buf;
uint32_t pos=数据\开始\偏移量\;
bool isou firstou record=true;
切片键\前缀\切片;
PlainTableKeyDecoder解码器(&file_info_uuu,encoding_type_u,user_key_len_uuuu,&file_info_uu,encoding_type_u,user_key_u len_uuu,&file
ioptions前缀提取程序);
同时(pos<file_info_u.data_end_offset)
uint32_t key_offset=pos;
ParsedinInternalkey键;
切片值_slice;
bool seecable=false;
状态S=下一个(&decoder,&pos,&key,nullptr,&value_slice,&seecable);
如果(!)S.O.()){
返回S;
}
key_prefix_slice=getPrefix(key);
如果(启用ou bloom_
Bloom_u.AddHash(GetSliceHash(key.user_key));
}否则{
如果(是“第一个记录”上一个键_前缀_切片!=key_prefix_slice)
如果(!)是第一个记录吗?
前缀_hashes->push_back(getsliehash(prev_key_prefix_slice));
}
如果(文件信息为“命令”模式)
prev_key_prefix_slice=key_prefix_slice;
}否则{
prev_key_prefix_buf=key_prefix_slice.toString();
prev_key_prefix_slice=prev_key_prefix_buf;
}
}
}
index_builder->addkeyprefix(getprefix(key),key_offset);
如果(!)可查找&&是第一条记录)
返回状态::损坏(“前缀的键不可查找”);
}
第一条记录为假;
}
前缀_hashes->push_back(getslicehash(key_prefix_slice));
auto s=index_.initfromrawdata(index_builder->finish());
返回S;
}
void plainTableReader::allocateAndFillBloom(int bloom_bits_per_key,
int num_前缀,
大小\u t超大\u页\u tlb \u大小,
vector<uint32_t>*前缀_hashes)
如果(!)istotalOrderMode())
uint32_t bloom_total_bits=num_prefixes*bloom_bits_per_key;
如果(bloom_total_bits>0)
启用“Bloom”=true;
布卢姆·塞托阿尔比斯(&arena_uuu,布卢姆o total_u bits,ioptions uu.bloom u地区,
巨大的页面大小,ioptions,信息日志;
FillBloom(前缀_hashes);
}
}
}
void plainTableReader::fillBloom(vector<uint32_t>>*prefix_hashes)
断言(bloom_uu.isInitialized());
for(自动前缀_hash:*前缀_hashes)
bloom_u.addhash(前缀_hash);
}
}
status plainTableReader::mmapdationFeeded()
如果(文件信息为“命令”模式)
//获取mmap内存。
返回文件“信息文件”->“读取”(0,文件“大小”,文件“信息文件”,“数据,空指针”);
}
返回状态::OK();
}
状态PlainTableReader::PopulateIndex(TableProperties*Props,
Int Bloom_Bits_per_键,
双哈希表比率,
尺寸指数稀疏度,
尺寸特大页面TLB尺寸
断言(道具)!= null pTr);
表“属性”重置(props);
块内容索引块内容;
status s=readmetablock(file_info_.file.get(),nullptr/*预取缓冲区*/,
file_size_, kPlainTableMagicNumber, ioptions_,
PlainTableIndexBuilder::kPlainTableIndexBlock,
&index_block_contents);
bool index_in_file = s.ok();
BlockContents bloom_block_contents;
bool bloom_in_file = false;
//如果索引块在文件中,我们只需要读取bloom块。
if (index_in_file) {
/*readmetablock(file_info_.file.get(),nullptr/*预取缓冲区*/,
文件大小,kPlainTableMagicNumber,ioptions,
BloomBlockBuilder::KbloomBlock,&BloomBlock_内容);
bloom_in_file=s.ok()&&bloom_block_contents.data.size()>0;
}
切片*花块;
如果(bloom_in_file)
//如果bloom块的contents.allocation不是空的(这种情况下
//对于非mmap模式),它保存bloom块的分配内存。
//它需要保持活动才能使'bloom_block'保持有效。
bloom_block_alloc_u=std::move(bloom_block_contents.allocation);
bloom_block=&bloom_block_contents.data;
}否则{
bloom_block=nullptr;
}
切片*索引块;
if(index_in_file)
//如果index_block_contents.allocation不为空(即
//对于非mmap模式),它保存索引块的分配内存。
//需要保持活动状态才能使'index_block'保持有效。
index_block_alloc_u=std::move(index_block_contents.allocation);
index_block=&index_block_contents.data;
}否则{
索引块=nullptr;
}
if((ioptions前缀提取程序=nullptr)&&
(哈希表比率!= 0){
//对于基于哈希的查找,需要ioptons.prefix_提取器。
返回状态::不支持(
“PlainTable需要前缀提取程序启用前缀哈希模式。”);
}
//首先,读取整个文件,每个kindexintervalforameprefixkeys行
//对于前缀(从第一个开始),生成(hash,
//offset)并将其附加到indexrecordlist,这是一个创建的数据结构
//存储它们。
如果(!)_文件中的索引_
//在此处为总订单模式分配Bloom筛选器。
if(istotalOrderMode())
uint32_t num_bloom_位=
static_cast<uint32_t>(table_properties_u->num_entries)*
布卢姆每把钥匙都有一点;
如果(num_bloom_位>0)
启用“Bloom”=true;
布卢姆·塞托阿尔比斯(&arena_uuu,num_o Bloom_Bits,IOptions_u.Bloom_地区,
巨大的页面大小,ioptions,信息日志;
}
}
否则,如果(bloom_在_文件中)
启用“Bloom”=true;
auto num_blocks_property=props->user_collected_properties.find(
普通表属性名称::knumbloomblocks);
uint32_t num_块=0;
如果(num_块_属性!=props->user_collected_properties.end())
切片温度切片(num_blocks_property->second);
如果(!)getvarint32(&temp_slice,&num_blocks))
NUMIX块=0;
}
}
//取消常量限定符,因为不会更改bloom_u
布卢姆·塞特拉瓦达(
const_cast<unsigned char*>()
reinterpret_cast<const unsigned char*>(bloom_block->data()),
static_cast<uint32_t>(bloom_block->size())*8,num_blocks);
}否则{
//文件中有索引,但文件中没有bloom。在这种情况下禁用Bloom过滤器。
启用“Bloom”=false;
Bloom_Bits_per_键=0;
}
plaintableindexbuilder index_builder(&arena_uuu,ioptions_u,index_稀疏度,
hash_table_比率,巨大的_page_tlb_大小);
std::vector<uint32_t>前缀_hashes;
如果(!)_文件中的索引_
s=popultiendexrecordlist(&index_builder,&prefix_hashes);
如果(!)S.O.()){
返回S;
}
}否则{
s=index_.initfromrawdata(*index_block);
如果(!)S.O.()){
返回S;
}
}
如果(!)_文件中的索引_
//计算的Bloom筛选器大小并为分配内存
//根据前缀数进行bloom过滤,然后填充。
allocateAndFillBloom(bloom_bits_per_key,index_.getNumPrefixes(),
巨大的_page_tlb_大小,&prefix_hashes);
}
//填充两个表属性。
如果(!)_文件中的索引_
props->user_collected_properties[“plain_table_hash_table_size”]=
ToString(index_.getIndexSize()*PlainTableIndex::KoffsetLen);
props->user_collected_properties[“plain_table_sub_index_size”]=
toString(index_.getSubIndexSize());
}否则{
props->user_collected_properties[“plain_table_hash_table_size”]=
ToStand(0);
props->user_collected_properties[“plain_table_sub_index_size”]=
ToStand(0);
}
返回状态::OK();
}
状态PlainTableReader::GetOffset(PlainTableKeyDecoder*解码器,
常量切片和目标,常量切片和前缀,
uint32_t prefix_hash,bool&prefix_matched,
uint32_t*偏移)常量
前缀匹配=假;
uint32_t前缀_index_offset;
auto res=index_.getoffset(前缀_hash,&prefix_index_offset);
if(res==plainTableIndex::knoprefixForBucket)
*offset=文件\信息\数据\结束\偏移;
返回状态::OK();
else if(res==plaintableindex::kdirecttofile)
*offset=前缀_index_offset;
返回状态::OK();
}
//指向子索引,需要进行二进制搜索
uint32_t上限;
常量字符*基指针=
index_u.getSubindexBaseptrandUpperbound(前缀_index_offset,&upper_bound);
uint32_t低=0;
uint32_t high=上限;
ParsedinInternalkey Mid_键;
parsedinteralkey parsed_目标;
如果(!)parseInternalKey(target,&parsed_target))
返回状态::损坏(slice());
}
//键在[低,高]之间。在两者之间进行二进制搜索。
同时(高-低>1)
uint32_t mid=(高+低)/2;
uint32_t file_offset=getFixed32元素(base_ptr,mid);
UIT32 32 TMP;
状态S=decoder->nextkenovalue(文件偏移、&mid-key、nullptr和tmp);
如果(!)S.O.()){
返回S;
}
int cmp_result=internal_comparator_u.compare(mid_key,parsed_target);
if(cmp_result<0)
低=中;
}否则{
如果(cmp_result==0)
//碰巧发现精确的键或目标小于
//基极偏移后的第一个键。
前缀匹配=真;
*offset=文件偏移量;
返回状态::OK();
}否则{
高=中;
}
}
}
//低位或低位的两个键+1可以相同
//前缀作为目标。我们得排除其中一个以免走
//到错误的前缀。
ParsedinInternalkey低_键;
UIT32 32 TMP;
uint32_t low_key_offset=getFixed32element(base_ptr,low);
状态S=解码器->NextKeyNovalue(低\u键偏移量,&low \u键,空指针,&tmp);
如果(!)S.O.()){
返回S;
}
if(getPrefix(low_key)==前缀)
前缀匹配=真;
*偏移量=低\键\偏移量;
否则,如果(低+1<上限)
//可能有下一个前缀,返回它
前缀匹配=假;
*offset=getFixed32element(基极指针,低+1);
}否则{
//目标大于此bucket中最后一个前缀的键
//但前缀不同。密钥不存在。
*offset=文件\信息\数据\结束\偏移;
}
返回状态::OK();
}
bool plainTableReader::matchBloom(uint32_t hash)const_
如果(!)启用“Bloom”
回归真实;
}
如果(布卢姆可能含有烟灰(哈希))
性能计数器添加(bloom-sst-hit-count,1);
回归真实;
}否则{
性能计数器添加(Bloom_sst_Miss_Count,1);
返回错误;
}
}
状态:PlainTableReader::Next(PlainTableKeyDecoder*解码器,uint32_t*偏移量,
parsedinteralkey*已分析的_键,
slice*内部\键,slice*值,
bool*seecable)const_
if(*offset==file_info_u.data_end_offset)
*offset=文件\信息\数据\结束\偏移;
返回状态::OK();
}
如果(*offset>file_info_u.data_end_offset)
返回状态::损坏(“偏移量超出文件大小”);
}
uint32字节读取;
状态S=解码器->下一个键(*偏移量,已解析的键,内部键,值,
&bytes_read,可查找);
如果(!)S.O.()){
返回S;
}
*offset=*offset+bytes_read;
返回状态::OK();
}
void plainTableReader::准备(const slice&target)
如果(启用ou bloom_
uint32_t prefix_hash=getsliehash(getprefix(target));
布卢姆预取(前缀_hash);
}
}
status plaintablereader::get(const readoptions&ro,const slice&target,
getContext*获取_context,bool skip_filters)
//首先检查Bloom过滤器。
切片前缀\切片;
uint32_t前缀_hash;
if(istotalOrderMode())
如果(全扫描模式)
StutsUs=
status::invalidArgument(“get()在完全扫描模式下不允许使用”);
}
//匹配Bloom筛选器检查的整个用户密钥。
如果(!)matchbloom(getsliehash(getuserkey(target)))
返回状态::OK();
}
//在total order模式下,只有一个bucket 0,我们总是使用空的
/ /前缀。
前缀_slice=slice();
前缀_hash=0;
}否则{
prefix_slice=getprefix(目标);
前缀_hash=getslicehash(前缀_slice);
如果(!)matchbloom(前缀_hash))
返回状态::OK();
}
}
uint32_t偏移;
bool前缀匹配;
PlainTableKeyDecoder解码器(&file_info_uuu,encoding_type_u,user_key_len_uuuu,&file_info_uu,encoding_type_u,user_key_u len_uuu,&file
ioptions前缀提取程序);
状态s=getoffset(&decoder,target,prefix_slice,prefix_hash,
前缀“匹配与偏移”);
如果(!)S.O.()){
返回S;
}
ParsedinInternalkey找到了\u键;
parsedinteralkey parsed_目标;
如果(!)parseInternalKey(target,&parsed_target))
返回状态::损坏(slice());
}
切片找到值;
while(offset<file_info_u.data_end_offset)
s=下一个(&decoder,&offset,&found_key,nullptr,&found_value);
如果(!)S.O.()){
返回S;
}
如果(!)前缀匹配({)
//如果尚未找到第一个键,则需要验证其前缀
/检查。
如果(getprefix(found_key)!=前缀_slice)
返回状态::OK();
}
前缀_match=true;
}
//todo(ljin):因为我们知道这里的关键比较结果,
//我们能启用快速路径吗?
if(内部_comparator_u.compare(found_key,parsed_target)>=0)
如果(!)get_context->savevalue(found_key,found_value))
断裂;
}
}
}
返回状态::OK();
}
uint64_t plainTableReader::approceoffsetof(const slice&key)
返回0;
}
PlainTableIterator::PlainTableIterator(PlainTableReader*表,
bool使用前缀查找)
:表u(表),
解码器uux(&table)->文件u信息u,表->编码u类型uu,
table_u->user_key_len_u,table_->prefix_extractor_u,
使用_前缀_seek_u(使用_前缀_seek)
下一个偏移量
}
PlainTableIterator::~PlainTableIterator()
}
bool plainTableIterator::valid()常量
返回偏移量表->文件信息数据结束偏移量和
offset_>=table_->data_start_offset_;
}
void PlainTableIterator::seektofFirst()
下一个_offset_u=table_u->data_start_offset_u;
if(next_offset_>=table_->file_info_u.data_end_offset)
下一个偏移量
}否则{
(下);
}
}
void PlainTableIterator::seektolast()
断言(假);
status_u=status::not supported(“seektolast()在plaintable中不受支持”);
}
void plainTableIterator::seek(const slice&target)
如果(使用前缀搜索)=!表_->istotalOrderMode())
//在此处执行此检查而不是newIterator(),以允许创建
//total_order_seek=true的迭代器,即使我们无法seek()。
//它。压缩时需要这样做:它使用
//totalou orderou seek=true,但通常不会对其执行seek(),
//仅SeekToFirst()。
StutsUs=
状态::无效参数(
“未为PlainTable实现总订单寻道。”);
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
返回;
}
//如果用户没有设置前缀查找选项,并且我们无法执行
//total seek()。断言失败。
if(table_->istotalOrderMode())
if(表_->full_scan_mode_123;
StutsUs=
status::invalidArgument(“seek()在完全扫描模式下不允许使用”);
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
返回;
else if(table_->getIndexSize()>1)
断言(假);
状态=状态::不支持(
“PlainTable不能发出非前缀查找,除非按总顺序”
“模式”;
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
返回;
}
}
slice prefix_slice=table_uu->getprefix(目标);
uint32_t prefix_hash=0;
//在TOTAL ORDER模式下,Bloom过滤器被忽略。
如果(!)表_->istotalOrderMode())
前缀_hash=getslicehash(前缀_slice);
如果(!)表_->matchbloom(前缀_hash))
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
返回;
}
}
bool前缀匹配;
状态_u=table_u->getoffset(&decoder_uux,target,prefix_slice,prefix_hash,
前缀“匹配”,下一个“偏移”;
如果(!)StasuS.O.()){
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
返回;
}
if(下一个_o偏移量_<table_u->file_信息_u.data_结束_偏移量)
for(next();status_.ok()&&valid();next())
如果(!)前缀匹配({)
//需要验证第一个键的前缀
如果(table_->getPrefix(key())!=前缀_slice)
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
断裂;
}
前缀_match=true;
}
if(table_->internal_comparator_.compare(key(),target)>=0)
断裂;
}
}
}否则{
offset_=table_u->file_info_u.data_end_offset;
}
}
void PlainTableIterator::seekForRev(const slice&target)
断言(假);
StutsUs=
状态::NotSupported(“SeekForRev()在PlainTable中不受支持”);
}
void PlainTableIterator::Next()
offset_u=下一个_offset_uu;
if(offset<table_u->file_info_u.data_end_offset)
切片TMP_切片;
parsedinteralkey parsed_键;
StutsUs=
表->next(&decoder_uu,&next_offset_uu,&parsed_key,&key_uu,&value_u);
如果(!)StasuS.O.()){
offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset;
}
}
}
void PlainTableIterator::prev()
断言(假);
}
Slice PlainTableIterator::key()常量
断言(valid());
返回键;
}
Slice PlainTableIterator::Value()常量
断言(valid());
返回值;
}
status plainTableIterator::status()常量
返回状态;
}
//命名空间rocksdb
endif//rocksdb_lite
| 26.314399 | 129 | 0.642771 | yinchengtsinghua |
5646e0f01432b486fe168c43c2d60c41ed629dc8 | 178 | cpp | C++ | 4.11.cpp | tompotter0/- | 9e1ff2b035eb8769637762d3007e09bbd3fb7250 | [
"MIT"
] | null | null | null | 4.11.cpp | tompotter0/- | 9e1ff2b035eb8769637762d3007e09bbd3fb7250 | [
"MIT"
] | null | null | null | 4.11.cpp | tompotter0/- | 9e1ff2b035eb8769637762d3007e09bbd3fb7250 | [
"MIT"
] | null | null | null | #include<iostream>
int f(int x){
if (x == 1)return 1;
return x*x + f(x - 1);
}
int main(){
int a;
std::cin >> a;
std::cout << f(a) << std::endl;
return 0;
}
| 12.714286 | 33 | 0.483146 | tompotter0 |
564791367909c9a668d1623fb4a078e6d96d4f3f | 64,079 | cxx | C++ | osprey/common/targ_info/generate/si_gen.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/targ_info/generate/si_gen.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/targ_info/generate/si_gen.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2010 Advanced Micro Devices, Inc. All Rights Reserved.
*/
/*
* Copyright (C) 2007 PathScale, LLC. All Rights Reserved.
*/
/*
* Copyright 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
// si_gen
/////////////////////////////////////
//
// Description:
//
// Digest the description of a particular hardware implementation's
// scheduling information and generate a c file that describes the
// features. The interface is extensively described in si_gen.h.
//
/////////////////////////////////////
// $Revision: 1.6 $
// $Date: 04/12/21 14:57:26-08:00 $
// $Author: bos@eng-25.internal.keyresearch.com $
// $Source: /home/bos/bk/kpro64-pending/common/targ_info/generate/SCCS/s.si_gen.cxx $
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "topcode.h"
#include "targ_isa_properties.h"
#include "targ_isa_subset.h"
#include "targ_isa_operands.h"
#include "gen_util.h"
#include "si_gen.h"
// Parameters:
const int bits_per_long = 32;
const int bits_per_long_long = 64;
const bool use_long_longs = true; // For now always
const int max_operands = ISA_OPERAND_max_operands;
const int max_results = ISA_OPERAND_max_results;
const int max_machine_slots = 16;
static int current_machine_slot;
static ISA_SUBSET machine_isa[max_machine_slots];
static std::string machine_name[max_machine_slots];
static const char * const interface[] = {
"/* ====================================================================",
" * ====================================================================",
" *",
" * Description:",
" *",
" * Raw processor-specific scheduling information.",
" *",
" * Clients should access this information through the public interface",
" * defined in \"ti_si.h\". See that interface for more detailed",
" * documentation.",
" *",
" * The following variables are exported:",
" *",
" * const SI_RRW SI_RRW_initializer",
" * Initial value (no resources reserved) for resource reservation",
" * entry.",
" *",
" * const SI_RRW SI_RRW_overuse_mask",
" * Mask used to determine if a resource reservation entry has an",
" * overuse.",
" *",
" * const INT SI_resource_count",
" * Count of elements in SI_resources array.",
" *",
" * const SI_RESOURCE* const SI_resources[n]",
" * Fixed-size array of SI_RESOURCE records.",
" *",
" * const SI SI_all[m]",
" * Fixed-size array of all SI records.",
" *",
" * const SI_MACHINE si_machines[p]",
" * Fixed-size array of SI_MACHINE records.",
" *",
" * int si_current_machine",
" * Global index into the si_machines array, defined here for",
" * convenience.",
" *",
" * ====================================================================",
" * ====================================================================",
" */",
NULL
};
/////////////////////////////////////
int Mod( int i, int j )
/////////////////////////////////////
// Mathematically correct integer modulus function. Unlike C's
// builtin remainder function, this correctly handles the case where
// one of the two arguments is negative.
/////////////////////////////////////
{
int rem;
if ( j == 0 )
return i;
rem = i % j;
if ( rem == 0 )
return 0;
if ( (i < 0) != (j < 0) )
return j + rem;
else
return rem;
}
/////////////////////////////////////
static void Maybe_Print_Comma(FILE* fd, bool& is_first)
/////////////////////////////////////
// Print a "," to <fd> if <is_first> is false. Update <is_first> to false.
// Great for printing C initializers.
/////////////////////////////////////
{
if ( is_first )
is_first = false;
else
fprintf(fd,",");
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class GNAME {
/////////////////////////////////////
// A generated name for a variable in the generated file. This supports a
// unified method for naming and getting the names of the objects we generate.
/////////////////////////////////////
public:
GNAME();
// Generate a unique name. Don't care about prefix.
GNAME(const char* prefix);
// Generate a unique name. Force a particular prefix.
GNAME(const GNAME& other);
// Generate a name that is a copy of <other>. The name will not be unique.
// Really only useful when <other> is about to be destructed, but we still
// need to refer to it.
const char* Gname() const;
// Return the name. This is the name under which the object is defined.
const char* Addr_Of_Gname() const;
// Return a pointer to the named object.
void Stub_Out();
// We've decided not to define the object after all but we may still want a
// pointer to it. After this call, Addr_Of_Gname will return 0.
static GNAME Stub_Gname();
// Return pre-built stub name.
private:
char gname[16]; // Where to keep the name. (This could be more
// hi-tech, but why?
bool stubbed; // Stubbed-out?
static int count; // For generating the unique names.
};
int GNAME::count = 0;
GNAME::GNAME() : stubbed(false) {
sprintf(gname,"&gname%d",count++);
}
GNAME::GNAME(const char* prefix) : stubbed(false) {
assert(strlen(prefix) <= 8);
sprintf(gname,"&%s%d",prefix,count++);
}
GNAME::GNAME(const GNAME& other) : stubbed(other.stubbed) {
sprintf(gname,"%s",other.gname);
}
const char* GNAME::Gname() const {
if (stubbed)
return "0";
else
return gname + 1;
}
const char* GNAME::Addr_Of_Gname() const {
if (stubbed)
return "0";
else
return gname;
}
void GNAME::Stub_Out() {
stubbed = true;
}
GNAME GNAME::Stub_Gname() {
static GNAME stub_gname;
stub_gname.Stub_Out();
return stub_gname;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class RES_WORD {
/////////////////////////////////////
// A machine word in the resource reservation table. We use an encoding of
// resources that allows very effecient checking for resources with more than
// a single instance. Shifted arithmetic is used to check for resource
// availability and to reserve resources. Each resource has a reserved field
// in the RES_WORD. The field for a given resource r is log2(count(r)) + 1
// bits wide. This field is wide enough to hold the count of members of r and
// one extra bit to the left of the count. This bit is called the "overuse
// bit". The field is initialized to be 2**field_width - (count + 1). This
// means that we can add count elements to the field without effecting the
// overuse bit, but adding more elements to the field will set the overuse
// bit. So we can can check for resource availability of all the resources
// reqpresented in a word with an an add (of the counts required) and a mask
// of the overuse bits. If the result is non-zero, there is a resource
// overuse (conflict).
//
// In theory this could be any natural sized integer supported on the host
// architecture, but for now we will always use long longs so we don't have to
// worry about generating/checking more than one word/cycle. This could be
// extended, but it would mean moving the actual resource checking to the
// generated side of the compile time interface (since it would need to know
// the format of the resource reservation table which could change...
public:
static void Find_Word_Allocate_Field(int width, int count,
int &word, int &bit);
// Allocate the first available resource field with <widtn> bits to hold
// <count> resources. A new resource word is allocated if required. On
// return, <word> and <bit> hold the word index and bit index of the
// allocated word.
static void Output_All(FILE* fd);
// Write resource word descriptions to output.
private:
int bit_inx; // Index of first next free bit
const int word_inx; // My index in table
long long initializer; // Value when no resources used
long long overuse_mask; // Bits to check
// for overuse after adding new
// resources
static std::list<RES_WORD*> res_words;
// List of all res_words in order.
static int count;
// Count of all resource words.
static bool has_long_long_word;
// Will we need to use long longs for resource words?
RES_WORD()
: bit_inx(0),
word_inx(count++),
initializer(0),
overuse_mask(0)
{
res_words.push_back(this);
}
bool Allocate_Field(int width, int count, int &word, int &bit);
};
std::list<RES_WORD*> RES_WORD::res_words;
int RES_WORD::count = 0;
bool RES_WORD::has_long_long_word = false;
/////////////////////////////////////
bool RES_WORD::Allocate_Field(int width, int count, int &word, int &bit)
/////////////////////////////////////
// Allocate a field <width> bits wide to hold <count> elements. Return true
// to indicate success with <word> set to my word_inx and <bit> set to the
// the bit index of the start of the field.
/////////////////////////////////////
{
int new_inx = bit_inx + width;
if ( (use_long_longs && new_inx >= bits_per_long_long)
|| (!use_long_longs && new_inx >= bits_per_long)
) {
return false;
}
if ( new_inx >= bits_per_long )
has_long_long_word = true;
word = word_inx;
bit = bit_inx;
initializer |= ((1ll << (width - 1)) - (count + 1)) << bit_inx;
overuse_mask |= (1ll << (width - 1)) << bit_inx;
bit_inx += width;
return true;
}
void RES_WORD::Find_Word_Allocate_Field(int width, int count,
int &word, int &bit)
{
std::list<RES_WORD*>::iterator rwi;
for ( rwi = res_words.begin(); rwi != res_words.end(); ++rwi ) {
if ( (*rwi)->Allocate_Field(width,count,word,bit) )
return;
}
RES_WORD* new_res_word = new RES_WORD();
if ( ! new_res_word->Allocate_Field(width,count,word,bit) ) {
fprintf(stderr,"### Cannot allocate field for %d resources\n",count);
exit(EXIT_FAILURE);
}
}
void RES_WORD::Output_All(FILE* fd)
{
if ( count == 0 )
fprintf(stderr,"ERROR: no resource words allocated.\n");
else if ( count > 1 ) {
fprintf(stderr,"ERROR: cannot handle %d > 1 long long worth of "
"resource info.\n",
count);
}
else {
// Important special case. We don't need a vector of resource words at all
// and can just use a scalar.
fprintf(fd,"const SI_RRW SI_RRW_initializer = 0x%" LL_FORMAT "x;\n",
res_words.front()->initializer);
fprintf(fd,"const SI_RRW SI_RRW_overuse_mask = 0x%" LL_FORMAT "x;\n",
res_words.front()->overuse_mask);
}
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class RES {
/////////////////////////////////////
// A machine level resource.
/////////////////////////////////////
public:
static RES* Create(const char *name, int count);
// <name> is used for documentation and debugging. <count> is the number of
// elements in the class.
static RES* Get(int id);
// Find and return the resource with the given <id>.
const char* Name() const { return name; }
// Return debugging name.
const char* Addr_Of_Gname() { return gname.Addr_Of_Gname(); }
// Return name of pointer to this resource object (in generated code).
unsigned int Count() const { return count; }
// How may members?
int Word() const { return word; }
// Index of word in resource reservation table. (We have sort of allowed
// there to be more than one, but this is probably not fully working.)
int Id() const { return id; }
// Unique ID of resource. Index into table of pointers to resources in the
// generated file.
unsigned int Shift_Count() const { return shift_count; }
// Bit index of the field in the resource reservation word.
static void Output_All( FILE* fd );
// Write out all the resource info to <fd>.
static int Total() { return total; }
// Total number of different RESs.
private:
const int count; // Available per cycle
const char* name; // For documentation and debugging
const int id; // Unique numerical identifier
GNAME gname; // Generated symbolic name
int word; // Which word in the table?
int field_width; // How wide the field?
int shift_count; // How much to shift (starting pos of the low
// order bit
static int total; // Total number of different RESs (not the the
// total of their counts, 1 for each RES)
static std::map<int,RES*> resources;
// Map of all resources, ordered by their Id's
RES(const char *name, int count);
void Calculate_Field_Width();
void Calculate_Field_Pos();
static void Calculate_Fields();
// Calculate fields for all resources. This can only be done at the very
// end becaue we may not know for sure that there are no multiple resources
// until then.
void Output( FILE* fd );
};
int RES::total = 0;
std::map<int,RES*> RES::resources;
RES::RES(const char *name, int count)
// constructor maintains list of all resources.
: count(count), name(name), id(total++), gname("resource")
{
resources[id] = this;
}
RES* RES::Create(const char *name, int count)
{
int i;
for ( i = 0; i < total; ++i )
if (resources[i]->count == count && strcmp(resources[i]->name, name) == 0)
return resources[i];
return new RES(name,count);
}
RES* RES::Get(int i)
{
assert(total > 0 && i >= 0 && i < total);
return resources[i];
}
void RES::Output_All( FILE* fd )
{
int i;
Calculate_Fields();
for ( i = 0; i < total; ++i )
resources[i]->Output(fd);
fprintf(fd,"const int SI_resource_count = %d;\n",total);
fprintf(fd,"const SI_RESOURCE * const SI_resources[%d] = {",total);
bool is_first = true;
for ( i = 0; i < total; ++i ) {
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"\n %s",resources[i]->gname.Addr_Of_Gname());
}
fprintf(fd,"\n};\n");
}
/////////////////////////////////////
void RES::Calculate_Field_Width()
/////////////////////////////////////
// Calculate the number of bits for my field and set <field_width>
// accordingly.
/////////////////////////////////////
{
int i;
assert(count > 0);
for ( i = 31 ; i >= 0 ; --i ) {
if ((( (int) 1) << i) & count) {
field_width = i + 2;
break;
}
}
}
void RES::Calculate_Field_Pos()
{
Calculate_Field_Width();
RES_WORD::Find_Word_Allocate_Field(field_width,count,word,shift_count);
}
/////////////////////////////////////
void RES::Calculate_Fields()
/////////////////////////////////////
// See interface description.
// Description
/////////////////////////////////////
{
for ( int i = 0; i < total; ++i )
resources[i]->Calculate_Field_Pos();
}
/////////////////////////////////////
void RES::Output( FILE* fd )
/////////////////////////////////////
// Allocate my field in the resource reservation table.
/////////////////////////////////////
{
fprintf(fd,"static const SI_RESOURCE %s = {\"%s\",%d,%d,%d,%d};\n",
gname.Gname(),
name,
id,
count,
word,
shift_count);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class RES_REQ {
/////////////////////////////////////
// A resource requirement. Represents all the resources needed to perform an
// instruction.
/////////////////////////////////////
public:
RES_REQ();
RES_REQ(const RES_REQ& rhs);
// Copy constructor.
bool Add_Resource(const RES* res, int cycle);
// Require an additional resource <res> at the given <cycle> relative to
// my start. Return indication of success. If adding the resource would
// create an overuse, don't add it and return false.
void Output(FILE* fd);
// Output my definition and initialization.
const char* Addr_Of_Gname() const;
// Return name of pointer to me (in generated code).
const char* Gname() const;
// Return my name (in generated code).
// The RES_REQ must be Output first.
bool Compute_Maybe_Output_II_RES_REQ(int ii, FILE* fd,
GNAME*& res_req_gname,
GNAME*& resource_id_set_gname);
// When software pipelining, we want to check all the resources for a given
// cycle of the schedule at once. Because the resource requirement may be
// longer than the II into which we are trying to schedule it, we statically
// combine the resource requirements for each II shorter than the number of
// cycles in the request. This function does the combining and returns a
// bool to indicate whether the resource requirement can be scheduled in the
// given <ii>. If it can, the combined a definition and initialization of
// resource requirement is output to <fd> under the GNAME <res_req_gname>.
// A cycle indexed set of resource id's used is also output under the GNAME
// <resource_id_set_gname>.
int Max_Res_Cycle() const { return max_res_cycle; }
// Return the cycle (relative to my start) of the latest resource I
// require. (Used to know how many II relative resource requirements need
// to be computed/output.)
void Compute_Output_Resource_Count_Vec(FILE* fd);
// Count up all the resources of each kind that I require (in all my cycles)
// and output a definition and initialization.
const char* Res_Count_Vec_Gname() const;
// Return name of pointer to start of my resource count vector.
int Res_Count_Vec_Size() const { return res_count_vec_size; }
// Return length of my resource count vector.
const char* Res_Id_Set_Gname() const;
// Return name of pointer to start of vector of resource id sets, one per
// cycle.
friend bool operator < (const RES_REQ& lhs, const RES_REQ& rhs);
// Comparison operator for std::map.
private:
/////////////////////////////////////
class CYCLE_RES {
/////////////////////////////////////
// A cycle and resource (id) combined into a single object. Used as a key
// into a map so we can find out how may of the given resources are required
// in the given cycle.
/////////////////////////////////////
public:
CYCLE_RES(int cycle, const RES* res) : cycle(cycle), res_id(res->Id()) {}
// Construct the <cycle,res> combination.
CYCLE_RES(const CYCLE_RES& rhs) : cycle(rhs.cycle), res_id(rhs.res_id) {}
// Copy constructor for use by STL map.
int Cycle() const { return cycle; }
// Return cycle component.
RES* Res() const { return RES::Get(res_id); }
// Return resource component.
friend bool operator < (const CYCLE_RES& a, const CYCLE_RES& b)
// Ordering for map.
{
return (a.cycle < b.cycle)
|| (a.cycle == b.cycle && a.res_id < b.res_id);
}
private:
const short cycle;
const short res_id;
};
typedef std::map<CYCLE_RES,int> CYCLE_RES_COUNT_MAP;
// For keeping track of the number of resources of a given type in a given
// cycle. <cycle,res> => count
int max_res_cycle;
// Latest cycle with a resource requirement
CYCLE_RES_COUNT_MAP cycle_res_count;
// <cycle,res> -> count required
GNAME res_count_vec_gname;
// Symbolic name of my resource count vector.
int res_count_vec_size;
// How big it is.
bool Compute_II_RES_REQ(int ii, RES_REQ& ii_res_req);
static std::map<RES_REQ,GNAME> res_req_name_map;
// Map of already-printed RES_REQ instances to names.
typedef std::vector<unsigned long long> RES_ID_SET;
struct res_id_set_cmp {
bool operator () (const RES_ID_SET* lhs, const RES_ID_SET* rhs) const {
if (lhs == 0 && rhs != 0)
return true;
else if (rhs == 0)
return false;
return *lhs < *rhs; // std::lexicographical_compare
}
};
typedef std::map<RES_ID_SET*,GNAME,res_id_set_cmp> RES_ID_SET_NAME_MAP;
// Map of RES_ID_SET pointers to names.
static std::vector<RES_ID_SET*> all_res_id_sets;
// List of all allocated resource id sets.
static RES_ID_SET_NAME_MAP res_id_set_name_map;
// Map of weak RES_ID_SET references to names.
RES_ID_SET* res_used_set_ptr;
// Weak reference to res_used_set for this RES_REQ.
typedef std::map<int,int> RES_COUNT_VEC;
// Actually a map of resource ids to counts.
struct res_count_vec_cmp {
bool operator () (const RES_COUNT_VEC* lhs, const RES_COUNT_VEC* rhs) const {
if (lhs == 0 && rhs != 0)
return true;
else if (rhs == 0)
return false;
return *lhs < *rhs; // std::map lexicographical_compare
}
};
typedef std::map<RES_COUNT_VEC*,GNAME,res_count_vec_cmp> RES_COUNT_NAME_MAP;
static std::vector<RES_COUNT_VEC*> all_res_count_vecs;
// List of all allocated resource count vectors.
static RES_COUNT_NAME_MAP res_count_name_map;
// Map of RES_COUNT_VEC weak references to names.
RES_COUNT_VEC* res_count_vec_ptr;
// Weak reference to res_count_vec for this RES_REQ.
};
std::map<RES_REQ,GNAME> RES_REQ::res_req_name_map;
std::vector<RES_REQ::RES_ID_SET*> RES_REQ::all_res_id_sets;
RES_REQ::RES_ID_SET_NAME_MAP RES_REQ::res_id_set_name_map;
std::vector<RES_REQ::RES_COUNT_VEC*> RES_REQ::all_res_count_vecs;
RES_REQ::RES_COUNT_NAME_MAP RES_REQ::res_count_name_map;
RES_REQ::RES_REQ()
: max_res_cycle(-1)
{}
RES_REQ::RES_REQ(const RES_REQ& rhs)
: max_res_cycle(rhs.max_res_cycle),
cycle_res_count(rhs.cycle_res_count),
res_count_vec_gname(rhs.res_count_vec_gname),
res_count_vec_size(rhs.res_count_vec_size)
{}
bool RES_REQ::Add_Resource(const RES* res, int cycle)
{
assert(cycle >= 0);
if ( cycle > max_res_cycle ) max_res_cycle = cycle;
CYCLE_RES cr = CYCLE_RES(cycle,res);
int count = cycle_res_count[cr];
if ( count >= res->Count() )
return false;
cycle_res_count[cr] = ++count;
return true;
}
const char* RES_REQ::Addr_Of_Gname() const
{
return res_req_name_map[*this].Addr_Of_Gname();
}
const char* RES_REQ::Gname() const
{
return res_req_name_map[*this].Gname();
}
const char* RES_REQ::Res_Count_Vec_Gname() const
{
if ( res_count_vec_size == 0 )
return "0";
return res_count_name_map[res_count_vec_ptr].Gname();
}
const char* RES_REQ::Res_Id_Set_Gname() const
{
if ( max_res_cycle < 0 )
return "0";
return res_id_set_name_map[res_used_set_ptr].Gname();
}
/////////////////////////////////////
bool RES_REQ::Compute_II_RES_REQ(int ii, RES_REQ& ii_res_req)
/////////////////////////////////////
// Compute my <ii> relative resourse requirement info <ii_res_req> and return
// a bool to indicate whether it is possible to issue me in a loop with <ii>
// cycles.
/////////////////////////////////////
{
CYCLE_RES_COUNT_MAP::iterator mi;
for (mi = cycle_res_count.begin(); mi != cycle_res_count.end(); ++mi) {
int cycle = (*mi).first.Cycle();
RES* res = (*mi).first.Res();
int count = (*mi).second;
for (int i = 0; i < count; ++i) {
if ( ! ii_res_req.Add_Resource(res,Mod(cycle,ii)) )
return false;
}
}
return true;
}
bool RES_REQ::Compute_Maybe_Output_II_RES_REQ(int ii, FILE* fd,
GNAME*& res_req_gname,
GNAME*& res_id_set_gname_ref)
{
RES_REQ ii_res_req;
if ( ! Compute_II_RES_REQ(ii,ii_res_req) )
return false;
ii_res_req.Output(fd);
res_req_gname = new GNAME(res_req_name_map[ii_res_req]);
if ( max_res_cycle < 0 )
res_id_set_gname_ref = new GNAME(GNAME::Stub_Gname());
else
res_id_set_gname_ref = new GNAME(res_id_set_name_map[res_used_set_ptr]);
return true;
}
void RES_REQ::Compute_Output_Resource_Count_Vec(FILE* fd)
{
CYCLE_RES_COUNT_MAP::iterator mi;
std::map<int,int,std::less<int> > res_inx_count; // res_id => count
// Sum up the number of each required
for (mi = cycle_res_count.begin(); mi != cycle_res_count.end(); ++mi) {
RES* res = (*mi).first.Res();
int count = (*mi).second;
res_inx_count[res->Id()] += count;
}
res_count_vec_size = res_inx_count.size();
if ( res_count_vec_size == 0 )
return;
// Avoid printing duplicate RES_REQ definitions.
RES_COUNT_NAME_MAP::iterator rcmi = res_count_name_map.find(&res_inx_count);
if ( rcmi == res_count_name_map.end() ) {
// Allocate and save a copy of the local res_inx_count variable.
RES_COUNT_VEC* res_inx_copy = new RES_COUNT_VEC(res_inx_count);
all_res_count_vecs.push_back(res_inx_copy);
res_count_vec_ptr = res_inx_copy;
// Generate a name and add it to the map.
GNAME gname;
res_count_name_map[res_inx_copy] = gname;
fprintf(fd,"static const SI_RESOURCE_TOTAL %s[] = {", gname.Gname());
bool is_first = true;
RES_COUNT_VEC::iterator mj;
for (mj = res_inx_count.begin(); mj != res_inx_count.end(); ++mj) {
RES* res = RES::Get((*mj).first); // You'd think STL would allow
int count = (*mj).second; // something less ugly! But no.
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"\n {%s,%d} /* %s */",
RES::Get(res->Id())->Addr_Of_Gname(),count,res->Name());
}
fprintf(fd,"\n};\n");
}
else
res_count_vec_ptr = rcmi->first;
}
void RES_REQ::Output(FILE* fd)
{
int i;
CYCLE_RES_COUNT_MAP::iterator mi;
RES_ID_SET res_vec((size_t) max_res_cycle + 1,0);
RES_ID_SET res_used_set((size_t) max_res_cycle + 1,0);
for (mi = cycle_res_count.begin(); mi != cycle_res_count.end(); ++mi) {
int cycle = (*mi).first.Cycle(); // You'd think this could be abstracted,
RES* res = (*mi).first.Res(); // but I couldn't even explain the
long long count = (*mi).second; // the concept to Alex S.
res_vec[cycle] += count << res->Shift_Count();
res_used_set[cycle] |= 1ll << res->Id();
}
// Avoid printing duplicate RES_REQ definitions.
std::map<RES_REQ,GNAME>::iterator rrmi = res_req_name_map.find(*this);
if ( rrmi == res_req_name_map.end() ) {
// Generate a name and add it to the map.
GNAME gname("res_req");
res_req_name_map[*this] = gname;
fprintf(fd,"static const SI_RRW %s[%d] = {\n %d",
gname.Gname(),
max_res_cycle + 2,
max_res_cycle + 1);
for ( i = 0; i <= max_res_cycle; ++i )
fprintf(fd,",\n 0x%" LL_FORMAT "x",res_vec[i]);
fprintf(fd,"\n};\n");
}
if ( max_res_cycle < 0 )
return;
// Avoid printing duplicate resource id sets.
RES_ID_SET_NAME_MAP::iterator rsmi = res_id_set_name_map.find(&res_used_set);
if ( rsmi == res_id_set_name_map.end() ) {
// Allocate and save a copy of the local res_used_set variable.
RES_ID_SET* res_set_copy = new RES_ID_SET(res_used_set);
all_res_id_sets.push_back(res_set_copy);
res_used_set_ptr = res_set_copy;
// Generate a name and add it to the map.
GNAME gname;
res_id_set_name_map[res_set_copy] = gname;
fprintf(fd,"static const SI_RESOURCE_ID_SET %s[%d] = {", gname.Gname(),
max_res_cycle + 1);
bool is_first = true;
for ( i = 0; i <= max_res_cycle; ++i ) {
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"\n 0x%" LL_FORMAT "x",res_used_set[i]);
}
fprintf(fd,"\n};\n");
}
else
res_used_set_ptr = rsmi->first;
}
bool operator < (const RES_REQ& lhs, const RES_REQ& rhs)
{
// Check for differing max_res_cycle values.
if (lhs.max_res_cycle != rhs.max_res_cycle)
return lhs.max_res_cycle < rhs.max_res_cycle;
// Compute the res_vec vector as in RES_REQ::Output.
std::vector<unsigned long long> res_vec_lhs((size_t) lhs.max_res_cycle + 1,0);
RES_REQ::CYCLE_RES_COUNT_MAP::const_iterator mi;
for (mi = lhs.cycle_res_count.begin(); mi != lhs.cycle_res_count.end(); ++mi)
{
int cycle = (*mi).first.Cycle();
RES* res = (*mi).first.Res();
long long count = (*mi).second;
res_vec_lhs[cycle] += count << res->Shift_Count();
}
std::vector<unsigned long long> res_vec_rhs((size_t) rhs.max_res_cycle + 1,0);
for (mi = rhs.cycle_res_count.begin(); mi != rhs.cycle_res_count.end(); ++mi)
{
int cycle = (*mi).first.Cycle();
RES* res = (*mi).first.Res();
long long count = (*mi).second;
res_vec_rhs[cycle] += count << res->Shift_Count();
}
// Compare values in res_vec vectors.
int i;
for ( i = 0; i <= lhs.max_res_cycle; ++i )
if (res_vec_lhs[i] != res_vec_rhs[i])
return res_vec_lhs[i] < res_vec_rhs[i];
// The two RES_REQ instances will be identical in output.
return false;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class ISLOT {
/////////////////////////////////////
// An issue slot. This is for modeling the horrible beast skewed pipe and we
// hope that it will be useful enough to support experimentation with related
// ideas.
/////////////////////////////////////
public:
ISLOT(const char* name, int skew, int avail_count);
// <name> is for documentation and debugging. <skew> gives a latency skew
// instructions issued in me.
const char* Addr_Of_Gname() { return gname.Addr_Of_Gname(); }
// Return pointer to my name in generated.
static void Output_Data(FILE* fd, int machine_slot);
// Output all the issue slots and a vector of pointers to them all.
static void Output_Members(FILE* fd, int machine_slot);
// Output the count of issue slots and a pointer to the vector.
private:
const char* name; // User supplied for documentation & debugging
const int skew; // Latency skew
const int avail_count; // How many instructions can happen in it
GNAME gname; // Symbolic name in generated
static std::list<ISLOT*> islots[max_machine_slots];
// All the created islot lists.
static int count[max_machine_slots];
// How many issue slots in each list?
};
std::list<ISLOT*> ISLOT::islots[max_machine_slots];
int ISLOT::count[max_machine_slots] = { 0 };
ISLOT::ISLOT(const char* name, int skew, int avail_count)
: name(name),
skew(skew),
avail_count(avail_count)
{
islots[current_machine_slot].push_back(this);
++count[current_machine_slot];
}
void ISLOT::Output_Data(FILE* fd, int machine_slot)
{
std::list<ISLOT*>::iterator isi;
for ( isi = islots[machine_slot].begin();
isi != islots[machine_slot].end();
++isi
) {
ISLOT* islot = *isi;
fprintf(fd,"static const SI_ISSUE_SLOT %s = { \"%s\",%d,%d};\n",
islot->gname.Gname(),
islot->name,
islot->skew,
islot->avail_count);
}
if ( count[machine_slot] == 0 )
fprintf(fd, "\n"
"static const SI_ISSUE_SLOT * const SI_issue_slots_%d[1] = {0};\n",
machine_slot);
else {
fprintf(fd,"\nstatic const SI_ISSUE_SLOT * const SI_issue_slots_%d[%d] = {",
machine_slot, count[machine_slot]);
bool is_first = true;
for ( isi = islots[machine_slot].begin();
isi != islots[machine_slot].end();
++isi
) {
ISLOT* islot = *isi;
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"\n %s",islot->Addr_Of_Gname());
}
fprintf(fd,"\n};\n");
}
}
void ISLOT::Output_Members(FILE* fd, int machine_slot)
{
fprintf(fd," %-20d /* SI_issue_slot_count */,\n",count[machine_slot]);
fprintf(fd," SI_issue_slots_%-5d /* si_issue_slots */,\n",machine_slot);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class LATENCY_INFO {
/////////////////////////////////////
// Describes latency information for an instruction group's operands or
// results.
/////////////////////////////////////
public:
LATENCY_INFO(int max_elements);
// <max_elements> is the maximum number either of operands or results.
LATENCY_INFO(const LATENCY_INFO& rhs);
// Copy constructor
void Set_Any_Time(int time);
// Any (all) of the operands or results have <time> as access or available
// time.
void Set_Time(int index, int time);
// <index>'th operand or result has <time> as access or available time.
void Output(FILE* fd);
// Output latency vector to <fd>.
const char* Gname() const;
// Return name of pointer to me in generated file.
// The latency vector must be output first.
friend bool operator < (const LATENCY_INFO& a, const LATENCY_INFO& b);
// Comparison operator for std::map.
private:
const int max_elements; // Maximum number of operands or results
bool any_time_defined; // Overriding time defined
int any_time; // And here it is
std::vector<bool> times_defined; // Times for each operands defined?
std::vector<int> times; // And here they are
static std::map<LATENCY_INFO,GNAME> output_latencies;
};
std::map<LATENCY_INFO,GNAME> LATENCY_INFO::output_latencies;
LATENCY_INFO::LATENCY_INFO(int max_elements)
: max_elements(max_elements),
any_time_defined(false),
times_defined(max_elements,false),
times(max_elements)
{}
LATENCY_INFO::LATENCY_INFO(const LATENCY_INFO& rhs)
: max_elements(rhs.max_elements),
any_time_defined(rhs.any_time_defined),
any_time(rhs.any_time),
times_defined(rhs.times_defined),
times(rhs.times)
{}
void LATENCY_INFO::Set_Any_Time(int time)
{
if ( any_time_defined ) {
fprintf(stderr,"### Warning any_time redefined for latency. "
"Was %d. Is %d\n",
any_time,
time);
}
any_time_defined = true;
any_time = time;
}
void LATENCY_INFO::Set_Time(int index, int time)
{
if ( any_time_defined ) {
fprintf(stderr,"### WARNING: latency setting specific time after any time. "
"Any %d. Specific %d\n",
any_time,
time);
}
assert(index < max_elements);
if ( times_defined[index] ) {
fprintf(stderr,"### WARNING: Resetting latency time. "
"Was %d. Now is %d\n",
time,
times[index]);
}
times_defined[index] = true;
times[index] = time;
}
void LATENCY_INFO::Output(FILE* fd)
{
// Avoid output of duplicate latencies.
std::map<LATENCY_INFO,GNAME>::iterator lmi = output_latencies.find(*this);
if ( lmi != output_latencies.end() )
return;
// Generate a name and add it to the map.
GNAME gname("latency");
output_latencies[*this] = gname;
fprintf(fd,"static const mUINT8 %s[%lu] = {",gname.Gname(),times.size());
bool is_first = true;
std::vector<int>::iterator i;
for ( i = times.begin(); i < times.end(); ++i ) {
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"%d",any_time_defined ? any_time : *i);
}
fprintf(fd,"};\n");
}
const char* LATENCY_INFO::Gname() const
{
return output_latencies[*this].Gname();
}
bool operator < (const LATENCY_INFO& a, const LATENCY_INFO& b)
{
if ( a.times.size() != b.times.size() )
return a.times.size() < b.times.size();
for (int i = 0; i < a.times.size(); ++i) {
int t_a = a.any_time_defined ? a.any_time : a.times[i];
int t_b = b.any_time_defined ? b.any_time : b.times[i];
if ( t_a != t_b )
return t_a < t_b;
}
// The two latencies will be identical in output.
return false;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class INSTRUCTION_GROUP {
/////////////////////////////////////
// Represents one of the instruction groups, a common piece of scheduling
// information for a set of instructions.
/////////////////////////////////////
public:
// These functions correspond exactly with the defined C client interface.
INSTRUCTION_GROUP(const char* name);
void Set_Any_Operand_Access_Time(int time);
void Set_Operand_Access_Time(int operand_index, int time);
void Set_Any_Result_Available_Time(int time);
void Set_Result_Available_Time(int result_index, int time);
void Set_Load_Access_Time( int time );
void Set_Last_Issue_Cycle( int time );
void Set_Store_Available_Time( int time );
void Add_Resource_Requirement(const RES* res, int cycle);
void Add_Alternative_Resource_Requirement(const RES* res, int cycle);
void Add_Valid_ISLOT(ISLOT* islot);
void Set_Write_Write_Interlock();
static void Output_All(FILE* fd);
// Write them all out
static void Output_Data(FILE* fd, int machine_slot);
// Write out per-machine list of pointers.
static void Output_Members(FILE* fd, int machine_slot);
// Write out count and pointer to data.
unsigned int Id();
// Unique id (available only after call to Output_All).
static unsigned int Count();
// Number of unique SI records (available only after call to Output_All).
private:
int id; // Index in vector of same
const char* name; // User supplied name for documentation
RES_REQ res_requirement; // Required to issue
RES_REQ alternative_res_requirement; // Alternative resource if
// res_requirement cannot be satisified
std::list<ISLOT*> valid_islots; // If there are any issue slots at all
GNAME islot_vec_gname; // Variable name of above in generated
LATENCY_INFO operand_latency_info; // When operands latch
LATENCY_INFO result_latency_info; // When results available
int load_access_time; // When loads access memory
int last_issue_cycle; // Last issue cycle in simulated insts
int store_available_time; // When stores make value available in
// memory
bool write_write_interlock; // For simulator
GNAME ii_res_req_gname;
// Generated name of vector of resource requirements for each II less than
// the total number of cycles in res_requirement (one based).
GNAME ii_res_id_set_gname;
// Generate name of vector of resource id sets for each II less than
// the total number of cycles in res_requirement (one based).
unsigned long long bad_iis[2];
// Tells whether it is possible to schedule at all at a given II. This
// could be a more flexible data structure. As it is, it is limited to 128
// bad IIs, but I think this will be enough.
static std::list<INSTRUCTION_GROUP*> instruction_groups;
// All the defined instruction groups (may have duplicates).
static std::list<INSTRUCTION_GROUP*>
by_machine_instruction_groups[max_machine_slots];
// List of instruction groups for each machine.
static int by_machine_count[max_machine_slots];
// Count of instruction groups for each machine.
int II_Info_Size() const { return res_requirement.Max_Res_Cycle(); }
// Latest cycle in which I need a resource
void Output_II_Info(FILE* fd);
void Output_Latency_Info(FILE* fd);
void Output_Issue_Slot_Info(FILE* fd);
void Output_Members(FILE* fd);
void Output(FILE* fd) const;
struct instruction_group_cmp {
bool operator () (const INSTRUCTION_GROUP* lhs,
const INSTRUCTION_GROUP* rhs) const
{
if (lhs == NULL && rhs != NULL)
return true;
else if (rhs == NULL)
return false;
// Compare fields as in Output member function.
#ifdef Is_True_On
// name
if (lhs->name == NULL && rhs->name != NULL)
return true;
else if (rhs->name == NULL)
return false;
if (strcmp(lhs->name, rhs->name) != 0)
return strcmp(lhs->name, rhs->name) < 0;
#endif
// operand_latency_info
if (strcmp(lhs->operand_latency_info.Gname(),
rhs->operand_latency_info.Gname()) != 0)
return strcmp(lhs->operand_latency_info.Gname(),
rhs->operand_latency_info.Gname()) < 0;
// result_latency_info
if (strcmp(lhs->result_latency_info.Gname(),
rhs->result_latency_info.Gname()) != 0)
return strcmp(lhs->result_latency_info.Gname(),
rhs->result_latency_info.Gname()) < 0;
// load_access_time
if (lhs->load_access_time != rhs->load_access_time)
return lhs->load_access_time < rhs->load_access_time;
// last_issue_cycle
if (lhs->last_issue_cycle != rhs->last_issue_cycle)
return lhs->last_issue_cycle < rhs->last_issue_cycle;
// store_available_time
if (lhs->store_available_time != rhs->store_available_time)
return lhs->store_available_time < rhs->store_available_time;
// res_requirement
if (strcmp(lhs->res_requirement.Gname(),
rhs->res_requirement.Gname()) != 0)
return strcmp(lhs->res_requirement.Gname(),
rhs->res_requirement.Gname()) < 0;
// alternative_res_requirement
if (strcmp(lhs->alternative_res_requirement.Gname(),
rhs->alternative_res_requirement.Gname()) != 0)
return strcmp(lhs->alternative_res_requirement.Gname(),
rhs->alternative_res_requirement.Gname()) < 0;
// Res_Id_Set_Gname, II_Info_Size: redundant (res_requirement)
// ii_res_req_gname
if (strcmp(lhs->ii_res_req_gname.Gname(),
rhs->ii_res_req_gname.Gname()) != 0)
return strcmp(lhs->ii_res_req_gname.Gname(),
rhs->ii_res_req_gname.Gname()) < 0;
// ii_res_id_set_gname
if (strcmp(lhs->ii_res_id_set_gname.Gname(),
rhs->ii_res_id_set_gname.Gname()) != 0)
return strcmp(lhs->ii_res_id_set_gname.Gname(),
rhs->ii_res_id_set_gname.Gname()) < 0;
// bad_iis
int i;
for (i = 0; i < sizeof(lhs->bad_iis) / sizeof(lhs->bad_iis[0]); ++i)
if (lhs->bad_iis[i] != rhs->bad_iis[i])
return lhs->bad_iis[i] < rhs->bad_iis[i];
// valid_islots
if (lhs->valid_islots.size() != rhs->valid_islots.size())
return lhs->valid_islots.size() < rhs->valid_islots.size();
// islot_vec_gname
if (strcmp(lhs->islot_vec_gname.Gname(),
rhs->islot_vec_gname.Gname()) != 0)
return strcmp(lhs->islot_vec_gname.Gname(),
rhs->islot_vec_gname.Gname()) < 0;
// Res_Count_Vec_Size, Res_Count_Vec_Gname: redundant (res_requirment)
// write_write_interlock
if (lhs->write_write_interlock != rhs->write_write_interlock)
return lhs->write_write_interlock < rhs->write_write_interlock;
return false;
}
};
typedef std::set<INSTRUCTION_GROUP*,instruction_group_cmp>
INSTRUCTION_GROUP_SET;
static INSTRUCTION_GROUP_SET instruction_group_set;
// Set of all unique instruction group objects.
};
std::list<INSTRUCTION_GROUP*> INSTRUCTION_GROUP::instruction_groups;
std::list<INSTRUCTION_GROUP*>
INSTRUCTION_GROUP::by_machine_instruction_groups[max_machine_slots];
INSTRUCTION_GROUP::INSTRUCTION_GROUP_SET
INSTRUCTION_GROUP::instruction_group_set;
INSTRUCTION_GROUP::INSTRUCTION_GROUP(const char* name)
: name(name),
operand_latency_info(max_operands),
result_latency_info(max_results),
load_access_time(0),
last_issue_cycle(0),
store_available_time(0),
write_write_interlock(false),
ii_res_req_gname("ii_rr")
{
bad_iis[0] = 0;
bad_iis[1] = 0;
instruction_groups.push_back(this);
by_machine_instruction_groups[current_machine_slot].push_back(this);
}
void INSTRUCTION_GROUP::Set_Any_Operand_Access_Time(int time)
{
operand_latency_info.Set_Any_Time(time);
}
void INSTRUCTION_GROUP::Set_Operand_Access_Time(int operand_index, int time)
{
operand_latency_info.Set_Time(operand_index,time);
}
void INSTRUCTION_GROUP::Set_Any_Result_Available_Time(int time)
{
result_latency_info.Set_Any_Time(time);
}
void INSTRUCTION_GROUP::Set_Result_Available_Time(int result_index, int time)
{
result_latency_info.Set_Time(result_index,time);
}
void INSTRUCTION_GROUP::Set_Load_Access_Time( int time )
{
load_access_time = time;
}
void INSTRUCTION_GROUP::Set_Last_Issue_Cycle( int time )
{
last_issue_cycle = time;
}
void INSTRUCTION_GROUP::Set_Store_Available_Time( int time )
{
store_available_time = time;
}
void INSTRUCTION_GROUP::Add_Resource_Requirement(const RES* res, int cycle)
{
if (! res_requirement.Add_Resource(res,cycle)) {
fprintf(stderr,"### ERROR: Impossible resource request for "
"instruction group %s.\n",
name);
fprintf(stderr,"### %s at cycle %d.\n",res->Name(),cycle);
}
}
void INSTRUCTION_GROUP::Add_Alternative_Resource_Requirement(const RES* res, int cycle)
{
if (! alternative_res_requirement.Add_Resource(res,cycle)) {
fprintf(stderr,"### ERROR: Impossible resource request for "
"instruction group %s.\n",
name);
fprintf(stderr,"### %s at cycle %d.\n",res->Name(),cycle);
}
}
void INSTRUCTION_GROUP::Add_Valid_ISLOT(ISLOT* islot)
{
valid_islots.push_back(islot);
}
void INSTRUCTION_GROUP::Set_Write_Write_Interlock()
{
write_write_interlock = true;
}
void INSTRUCTION_GROUP::Output_II_Info(FILE* fd)
{
int i;
bool is_first;
const int ii_vec_size = II_Info_Size();
const int max_num_bad_iis = sizeof(bad_iis) * 8;
// We need ii relative information for ii's in the range
// 1..cycle_with_final_res_requirement. An ii of 0 makes no sense and an II
// enough cycles that the request doesn't need to wrap are the outside bounds.
if ( ii_vec_size <= 0 ) {
ii_res_req_gname.Stub_Out();
ii_res_id_set_gname.Stub_Out();
return;
}
std::vector<GNAME*> ii_res_req_gname_vector(ii_vec_size);
std::vector<GNAME*> ii_resources_used_gname_vector(ii_vec_size);
std::vector<bool> ii_can_do_vector(ii_vec_size);
int greatest_bad_ii = 0;
for ( i = 0; i < res_requirement.Max_Res_Cycle(); ++i ) {
if ( res_requirement.Compute_Maybe_Output_II_RES_REQ(
i+1,fd,
ii_res_req_gname_vector[i],
ii_resources_used_gname_vector[i])
) {
ii_can_do_vector[i] = true;
}
else {
ii_can_do_vector[i] = false;
greatest_bad_ii = i;
if ( i > max_num_bad_iis ) {
fprintf(stderr,"### Error: bad II %d > %d. "
"Need a more flexible representation.\n",
i, max_num_bad_iis);
}
}
}
unsigned int j;
for ( j = 0; j < sizeof(bad_iis) / sizeof(bad_iis[0]); ++j ) {
bad_iis[j] = 0ULL;
}
for ( i = 0; i <= greatest_bad_ii; ++i ) {
if ( ! ii_can_do_vector[i] ) {
bad_iis[i / bits_per_long_long] |= (1ULL << (i % bits_per_long_long));
}
}
// Print vector of pointers to the II relative resource requirements
fprintf(fd,"static const SI_RR %s[] = {",
ii_res_req_gname.Gname());
is_first = true;
for ( i = 0; i < ii_vec_size; ++i ) {
Maybe_Print_Comma(fd,is_first);
if ( ii_can_do_vector[i] )
fprintf(fd,"\n %s",ii_res_req_gname_vector[i]->Gname());
else
fprintf(fd,"\n 0");
}
fprintf(fd,"\n};\n");
// Print vector of pointers to the II relative resoruce id sets
fprintf(fd,"static const SI_RESOURCE_ID_SET * const %s[] = {",
ii_res_id_set_gname.Gname());
is_first = true;
for ( i = 0; i < ii_vec_size; ++i ) {
Maybe_Print_Comma(fd,is_first);
if ( ii_can_do_vector[i] ) {
fprintf(fd,"\n %s",
ii_resources_used_gname_vector[i]->Gname());
}
else
fprintf(fd,"\n 0");
}
fprintf(fd,"\n};\n");
}
void INSTRUCTION_GROUP::Output_Latency_Info(FILE* fd)
{
operand_latency_info.Output(fd);
result_latency_info.Output(fd);
}
void INSTRUCTION_GROUP::Output_Issue_Slot_Info(FILE* fd)
{
if ( valid_islots.size() == 0 ) {
/* Comment out the warning until the beast skewed support is implemented;
* it's currently a post 7.2 affair.
*
* if ( ISLOT::Count() > 0 )
* fprintf(stderr,"### Issue slots defined but none defined for %s\n",name);
*/
islot_vec_gname.Stub_Out();
return;
}
fprintf(fd,"static SI_ISSUE_SLOT * const %s[] = {",islot_vec_gname.Gname());
bool is_first = true;
std::list<ISLOT*>::iterator i;
for (i = valid_islots.begin(); i != valid_islots.end(); ++i) {
ISLOT* islot = *i;
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"\n %s",islot->Addr_Of_Gname());
}
fprintf(fd,"\n};\n");
}
void INSTRUCTION_GROUP::Output_Members(FILE* fd)
{
unsigned int i;
res_requirement.Output(fd);
res_requirement.Compute_Output_Resource_Count_Vec(fd);
alternative_res_requirement.Output(fd);
alternative_res_requirement.Compute_Output_Resource_Count_Vec(fd);
Output_II_Info(fd);
Output_Latency_Info(fd);
Output_Issue_Slot_Info(fd);
// Keep track of duplicate instruction group data.
INSTRUCTION_GROUP_SET::iterator mi = instruction_group_set.find(this);
if (mi == instruction_group_set.end()) {
instruction_group_set.insert(this);
}
}
void INSTRUCTION_GROUP::Output(FILE* fd) const
{
unsigned int i;
assert(id != 0);
fprintf(fd," { /* SI id %u */\n",id);
#ifdef Is_True_On
fprintf(fd," \"%s\",\n",name);
#endif
fprintf(fd," %-15s, /* operand latency */\n",
operand_latency_info.Gname());
fprintf(fd," %-15s, /* result latency */\n",
result_latency_info.Gname());
fprintf(fd," %-15d, /* load access time */\n",
load_access_time);
fprintf(fd," %-15d, /* last issue cycle */\n",
last_issue_cycle);
fprintf(fd," %-15d, /* store available time */\n",
store_available_time);
fprintf(fd," %-15s, /* resource requirement */\n",
res_requirement.Gname());
fprintf(fd," %-15s, /* alternative resource requirement */\n",
alternative_res_requirement.Gname());
fprintf(fd," %-15s, /* res id used set vec */\n",
res_requirement.Res_Id_Set_Gname());
fprintf(fd," %-15d, /* II info size */\n",
II_Info_Size() >= 0 ? II_Info_Size() : 0);
fprintf(fd," %-15s, /* II resource requirement vec */\n",
ii_res_req_gname.Gname());
fprintf(fd," %-15s, /* II res id used set vec */\n",
ii_res_id_set_gname.Gname());
fprintf(fd," {{");
for ( i = 0; i < sizeof(bad_iis) / sizeof(bad_iis[0]); ++i ) {
fprintf(fd, "0x%" LL_FORMAT "x", bad_iis[i]);
if ( i < sizeof(bad_iis) / sizeof(bad_iis[0]) - 1 ) fprintf(fd, ",");
}
fprintf(fd, "}} , /* bad IIs */\n");
fprintf(fd," %-15d, /* valid issue slots vec size */\n",
(unsigned int) valid_islots.size());
fprintf(fd," %-15s, /* valid issue slots vec */\n",
islot_vec_gname.Gname());
fprintf(fd," %-15d, /* resource count vec size */\n",
res_requirement.Res_Count_Vec_Size());
fprintf(fd," %-15s, /* resource count vec */\n",
res_requirement.Res_Count_Vec_Gname());
fprintf(fd," %-15s /* write-write interlock */\n",
write_write_interlock ? "1" : "0");
fprintf(fd," }");
}
void INSTRUCTION_GROUP::Output_All(FILE* fd)
{
std::list<INSTRUCTION_GROUP*>::iterator iig;
INSTRUCTION_GROUP_SET::iterator mi;
unsigned int i;
for (iig = instruction_groups.begin();
iig != instruction_groups.end();
++iig
) {
(*iig)->Output_Members(fd);
}
i = 1;
fprintf(fd,"\nconst SI SI_all[%lu] = {\n", instruction_group_set.size());
for (mi = instruction_group_set.begin();
mi != instruction_group_set.end();
++mi
) {
if (i > 1)
fprintf(fd,",\n");
(*mi)->id = i;
(*mi)->Output(fd);
i++;
}
fprintf(fd,"\n};\n");
}
void INSTRUCTION_GROUP::Output_Data(FILE* fd, int machine_slot)
{
std::list<INSTRUCTION_GROUP*>::iterator iig;
fprintf(fd,"\nstatic const int SI_ID_si_%d[%lu] = {",machine_slot,
by_machine_instruction_groups[machine_slot].size());
bool is_first = true;
for (iig = by_machine_instruction_groups[machine_slot].begin();
iig != by_machine_instruction_groups[machine_slot].end();
++iig
) {
Maybe_Print_Comma(fd,is_first);
fprintf(fd,"\n %u",(*iig)->Id());
}
fprintf(fd,"\n};\n");
fprintf(fd,"\n"); // One extra new line to separate from what follows.
}
void INSTRUCTION_GROUP::Output_Members(FILE* fd, int machine_slot)
{
fprintf(fd," %-20lu /* SI_ID_count */,\n",
by_machine_instruction_groups[machine_slot].size());
fprintf(fd," SI_ID_si_%-11d /* SI_ID_si */,\n",machine_slot);
}
unsigned int INSTRUCTION_GROUP::Id()
{
// Use the id from the representative instruction group object.
INSTRUCTION_GROUP_SET::iterator mi = instruction_group_set.find(this);
assert(mi != instruction_group_set.end());
return (*mi)->id;
}
unsigned int INSTRUCTION_GROUP::Count()
{
return instruction_group_set.size();
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
class TOP_SCHED_INFO_MAP {
/////////////////////////////////////
// Keeps track of which TOPs need are in which INSTRUCTION_GROUPs (and thus
// map to which TOP_SCHED_INFOs.
/////////////////////////////////////
public:
static void Add_Entry( TOP top, INSTRUCTION_GROUP* ig );
// Add entry to the map. <top> uses <ig>'s scheduling information.
static void Output_Data( FILE* fd , int machine_slot );
// Write out the map.
static void Output_Members( FILE* fd, int machine_slot );
// Write out a pointer to the map.
static void Create_Dummies( void );
// Create scheduling info for the "dummy" instructions.
private:
static std::vector<INSTRUCTION_GROUP*> top_sched_info_ptr_map[max_machine_slots];
// Map to instruction group instances.
static std::vector<bool> top_sched_info_defined[max_machine_slots];
// Which elements defined
static INSTRUCTION_GROUP* machine_dummies[max_machine_slots];
// Pointer to dummy instruction used to fill unused slots
};
std::vector<INSTRUCTION_GROUP*>
TOP_SCHED_INFO_MAP::top_sched_info_ptr_map[max_machine_slots];
std::vector<bool>
TOP_SCHED_INFO_MAP::top_sched_info_defined[max_machine_slots];
INSTRUCTION_GROUP* TOP_SCHED_INFO_MAP::machine_dummies[max_machine_slots];
void TOP_SCHED_INFO_MAP::Create_Dummies( void )
{
INSTRUCTION_GROUP *dummies = NULL;
top_sched_info_ptr_map[current_machine_slot].resize(TOP_count,NULL);
top_sched_info_defined[current_machine_slot].resize(TOP_count,false);
for ( int i = 0; i < TOP_count; ++i ) {
if ( TOP_is_dummy((TOP)i) ) {
if ( !dummies ) {
dummies = new INSTRUCTION_GROUP("Dummy instructions");
dummies->Set_Any_Operand_Access_Time(0);
dummies->Set_Any_Result_Available_Time(0);
}
top_sched_info_ptr_map[current_machine_slot][i] = dummies;
}
}
machine_dummies[current_machine_slot] = dummies;
}
void TOP_SCHED_INFO_MAP::Add_Entry( TOP top, INSTRUCTION_GROUP* ig )
{
if ( top_sched_info_defined[current_machine_slot][(int) top] ) {
fprintf(stderr,"### Warning: scheduling information for %s redefined.\n",
TOP_Name(top));
}
top_sched_info_ptr_map[current_machine_slot][(int) top] = ig;
top_sched_info_defined[current_machine_slot][(int) top] = true;
}
void TOP_SCHED_INFO_MAP::Output_Data( FILE* fd, int machine_slot )
{
int i;
fprintf(fd,"static const int SI_top_si_%d[%d] = {",machine_slot,TOP_count);
bool err = false;
bool is_first = true;
for ( i = 0; i < TOP_count; ++i ) {
bool isa_member = ISA_SUBSET_Member(machine_isa[machine_slot], (TOP)i);
bool is_dummy = TOP_is_dummy((TOP)i);
if ( top_sched_info_defined[machine_slot][i] ) {
if ( ! isa_member ) {
fprintf(stderr,
"### Warning: scheduling info for non-%s ISA opcode %s (%s)\n",
ISA_SUBSET_Name(machine_isa[machine_slot]),
TOP_Name((TOP)i),
machine_name[machine_slot].c_str());
} else if ( is_dummy ) {
fprintf(stderr,
"### Warning: scheduling info for dummy opcode %s (%s)\n",
TOP_Name((TOP)i),
machine_name[machine_slot].c_str());
}
} else {
if ( isa_member && ! is_dummy ) {
fprintf(stderr,
"### Error: no scheduling info for opcode %s for machine %s\n",
TOP_Name((TOP)i),
machine_name[machine_slot].c_str());
err = true;
}
}
// If we have seen a fatal error, skip printing the entry to avoid a crash.
if ( ! err ) {
Maybe_Print_Comma(fd,is_first);
if ( ! isa_member )
fprintf(fd,"\n %-4u /* %s (dummy, not in ISA subset %s) */",
machine_dummies[machine_slot]->Id(),TOP_Name((TOP)i),
ISA_SUBSET_Name(machine_isa[machine_slot]));
else
fprintf(fd,"\n %-4u /* %s */",
top_sched_info_ptr_map[machine_slot][i]->Id(),TOP_Name((TOP)i));
}
}
fprintf(fd,"\n};\n");
if (err) exit(EXIT_FAILURE);
}
void TOP_SCHED_INFO_MAP::Output_Members( FILE* fd, int machine_slot )
{
fprintf(fd," SI_top_si_%-10d /* SI_top_si */\n",machine_slot);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// The client interface functions
static INSTRUCTION_GROUP* current_instruction_group;
void Targ_SI( void )
{
current_machine_slot = 0;
}
void Machine( const char* name, ISA_SUBSET isa )
{
machine_name[current_machine_slot] = name;
machine_isa[current_machine_slot] = isa;
TOP_SCHED_INFO_MAP::Create_Dummies();
}
RESOURCE RESOURCE_Create(const char* name, int count)
{
return RES::Create(name,count);
}
ISSUE_SLOT ISSUE_SLOT_Create(const char* name, int skew, int count)
{
return new ISLOT(name,skew,count);
}
void Instruction_Group(const char* name,...)
{
va_list ap;
TOP opcode;
current_instruction_group = new INSTRUCTION_GROUP(name);
va_start(ap,name);
while ( (opcode = static_cast<TOP>(va_arg(ap,int))) != TOP_UNDEFINED )
TOP_SCHED_INFO_MAP::Add_Entry(opcode,current_instruction_group);
va_end(ap);
}
void Any_Operand_Access_Time( int time )
{
current_instruction_group->Set_Any_Operand_Access_Time(time);
}
void Operand_Access_Time( int operand_index, int time )
{
current_instruction_group->Set_Operand_Access_Time(operand_index,time);
}
void Any_Result_Available_Time( int time )
{
current_instruction_group->Set_Any_Result_Available_Time(time);
}
void Result_Available_Time( int result_index, int time )
{
current_instruction_group->Set_Result_Available_Time(result_index,time);
}
void Load_Access_Time( int time )
{
current_instruction_group->Set_Load_Access_Time(time);
}
void Last_Issue_Cycle( int time )
{
current_instruction_group->Set_Last_Issue_Cycle(time);
}
void Store_Available_Time( int time )
{
current_instruction_group->Set_Store_Available_Time(time);
}
void Resource_Requirement( RESOURCE resource, int time )
{
current_instruction_group->Add_Resource_Requirement(resource,time);
}
void Alternative_Resource_Requirement( RESOURCE resource, int time )
{
current_instruction_group->Add_Alternative_Resource_Requirement(resource,time);
}
void Valid_Issue_Slot( ISSUE_SLOT slot )
{
current_instruction_group->Add_Valid_ISLOT(slot);
}
void Write_Write_Interlock( void )
{
current_instruction_group->Set_Write_Write_Interlock();
}
void Machine_Done( void )
{
current_machine_slot++;
if (current_machine_slot == max_machine_slots) {
fprintf(stderr,"### Error: max_machine_slots is %d\n",max_machine_slots);
exit(EXIT_FAILURE);
}
}
void Targ_SI_Done( const char* basename )
{
std::string h_filename(basename);
std::string c_filename(basename);
h_filename.append(".h");
c_filename.append(".c");
FILE* hfile = fopen(h_filename.c_str(),"w");
FILE* cfile = fopen(c_filename.c_str(),"w");
if ( hfile == NULL ) {
fprintf(stderr,"### Error: couldn't write %s\n",h_filename.c_str());
return;
}
if ( cfile == NULL ) {
fprintf(stderr,"### Error: couldn't write %s\n",c_filename.c_str());
return;
}
Emit_Header(hfile, basename, interface);
fprintf(hfile,"#include \"ti_si_types.h\"\n");
fprintf(cfile,"#include \"%s\"\n", h_filename.c_str());
bool is_first = true;
int i;
// output global data
RES::Output_All(cfile);
RES_WORD::Output_All(cfile);
INSTRUCTION_GROUP::Output_All(cfile);
// output per-machine data
for (i = 0; i < current_machine_slot; ++i) {
ISLOT::Output_Data(cfile, i);
INSTRUCTION_GROUP::Output_Data(cfile, i);
TOP_SCHED_INFO_MAP::Output_Data(cfile, i);
}
fprintf(hfile,"\nextern const SI_RRW SI_RRW_initializer;\n");
fprintf(hfile,"extern const SI_RRW SI_RRW_overuse_mask;\n");
fprintf(hfile,"\nextern const INT SI_resource_count;\n");
fprintf(hfile,"extern const SI_RESOURCE* const SI_resources[%d];\n",
RES::Total());
fprintf(hfile,"\nextern const SI SI_all[%u];\n",INSTRUCTION_GROUP::Count());
fprintf(hfile,"\nextern const SI_MACHINE si_machines[%d];\n",
current_machine_slot);
fprintf(cfile,"\nconst SI_MACHINE si_machines[%d] = {",current_machine_slot);
// output SI_MACHINE members
for (i = 0; i < current_machine_slot; ++i) {
std::string quoted_name("\"");
quoted_name.append(machine_name[i]);
quoted_name.append("\"");
Maybe_Print_Comma(cfile, is_first);
fprintf(cfile,"\n {\n");
fprintf(cfile," %-20s /* name */,\n", quoted_name.c_str());
ISLOT::Output_Members(cfile, i);
INSTRUCTION_GROUP::Output_Members(cfile, i);
TOP_SCHED_INFO_MAP::Output_Members(cfile, i);
fprintf(cfile," }");
}
fprintf(cfile,"\n};\n");
fprintf(hfile,"\nextern int si_current_machine;\n");
fprintf(cfile,"\nint si_current_machine; /* index into si_machines */\n");
Emit_Footer(hfile);
fclose(hfile);
fclose(cfile);
}
| 30.881446 | 87 | 0.624932 | sharugupta |
871cda5ce2cc19e20b167f28215c3f7c9c6b4a99 | 1,528 | cpp | C++ | Past Papers/2020 Assignment 01/THUSHARA/Train/Sol-2-Train - Thushara.cpp | GIHAA/Cpp-programming | 0b094868652fd83f8dc4eb02c5abe3c3501bcdf1 | [
"MIT"
] | 19 | 2021-04-28T13:32:15.000Z | 2022-03-08T11:52:59.000Z | Past Papers/2020 Assignment 01/THUSHARA/Train/Sol-2-Train - Thushara.cpp | GIHAA/Cpp-programming | 0b094868652fd83f8dc4eb02c5abe3c3501bcdf1 | [
"MIT"
] | 5 | 2021-03-03T08:06:15.000Z | 2021-12-26T18:14:45.000Z | Past Papers/2020 Assignment 01/THUSHARA/Train/Sol-2-Train - Thushara.cpp | GIHAA/Cpp-programming | 0b094868652fd83f8dc4eb02c5abe3c3501bcdf1 | [
"MIT"
] | 27 | 2021-01-18T22:35:01.000Z | 2022-02-22T19:52:19.000Z | // Using Char Arrays
#include<iostream>
#include<cstring>
using namespace std;
// You can put this code segment in Train.h file -----
class Train {
private:
int trainID;
int capacity;
char startTime[15];
char destination[10];
public:
void setTrainDetails(int tID, int c, char sT[10], char d[15]);
void displayTrainDetails();
void setStartTime();
};
// ----------------------------------------------------
int main() {
Train t1, t2, t3;
t1.setTrainDetails(1, 200, (char *)"6:00AM", (char *)"Kandy");
t2.setTrainDetails(2, 150, (char *)"7:30AM", (char *)"Galle");
t3.setTrainDetails(3, 300, (char *)"4:00AM", (char *)"Jaffna");
t1.setStartTime();
t2.setStartTime();
t3.setStartTime();
t1.displayTrainDetails();
t2.displayTrainDetails();
t3.displayTrainDetails();
return 0;
}
// You can put this code segment in Train.cpp file -----
void Train::setTrainDetails(int tID, int c, char sT[10], char d[15]) {
trainID = tID;
capacity = c;
strcpy(startTime, sT);
strcpy(destination, d);
}
void Train::displayTrainDetails() {
cout << endl << "TrainID = " << trainID << endl;
cout << "Capacity = " << capacity << endl;
cout << "StartTime = " << startTime << endl;
cout << "Destination = " << destination << endl;
}
void Train::setStartTime() {
cout << "Input new start time of train " << trainID << ": ";
cin >> startTime;
}
// ---------------------------------------------------- | 25.466667 | 70 | 0.554319 | GIHAA |
871eb51ace4e94c3b6a2fa16d62c3e0e2464b1b0 | 2,105 | cc | C++ | src/network/connection_manager.cc | fon/flexran-rtc | 27a955a0494597c6fd175f6b4d31b9eaac2b8dfd | [
"MIT"
] | 1 | 2019-11-05T16:22:11.000Z | 2019-11-05T16:22:11.000Z | src/network/connection_manager.cc | fon/flexran-rtc | 27a955a0494597c6fd175f6b4d31b9eaac2b8dfd | [
"MIT"
] | null | null | null | src/network/connection_manager.cc | fon/flexran-rtc | 27a955a0494597c6fd175f6b4d31b9eaac2b8dfd | [
"MIT"
] | 3 | 2019-05-02T05:14:36.000Z | 2021-06-15T12:40:52.000Z | /* The MIT License (MIT)
Copyright (c) 2016 Xenofon Foukas
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 "connection_manager.h"
flexran::network::connection_manager::connection_manager(boost::asio::io_service& io_service,
const boost::asio::ip::tcp::endpoint& endpoint,
async_xface& xface)
: acceptor_(io_service, endpoint), socket_(io_service), next_id_(0), xface_(xface) {
do_accept();
}
void flexran::network::connection_manager::send_msg_to_agent(std::shared_ptr<tagged_message> msg) {
sessions_[msg->getTag()]->deliver(msg);
}
void flexran::network::connection_manager::do_accept() {
acceptor_.async_accept(socket_,
[this](boost::system::error_code ec) {
if (!ec) {
sessions_[next_id_] = std::make_shared<agent_session>(std::move(socket_), *this, xface_, next_id_);
sessions_[next_id_]->start();
xface_.initialize_connection(next_id_);
next_id_++;
}
do_accept();
});
}
void flexran::network::connection_manager::close_connection(int session_id) {
sessions_.erase(session_id);
}
| 36.929825 | 100 | 0.737292 | fon |
87227fe73c6eefada6b3f33ace19caa52b1edbdb | 3,478 | cpp | C++ | scripts/urdf_scenes.cpp | psh117/motion_bench_maker | 11ec8378a50595b27151da878517ada6642f10b5 | [
"BSD-3-Clause"
] | 19 | 2021-12-13T14:48:29.000Z | 2022-03-11T03:24:17.000Z | scripts/urdf_scenes.cpp | psh117/motion_bench_maker | 11ec8378a50595b27151da878517ada6642f10b5 | [
"BSD-3-Clause"
] | 1 | 2022-02-15T20:05:04.000Z | 2022-02-15T20:05:04.000Z | scripts/urdf_scenes.cpp | psh117/motion_bench_maker | 11ec8378a50595b27151da878517ada6642f10b5 | [
"BSD-3-Clause"
] | 1 | 2021-12-29T10:54:49.000Z | 2021-12-29T10:54:49.000Z | /*Constantinos Chamzas */
#include <motion_bench_maker/parser.h>
// Robowflex library
#include <robowflex_library/util.h>
#include <robowflex_library/yaml.h>
#include <robowflex_library/io/visualization.h>
#include <robowflex_library/io.h>
#include <robowflex_library/scene.h>
#include <robowflex_library/trajectory.h>
#include <robowflex_library/detail/fetch.h>
#include <robowflex_library/builder.h>
// Robowflex ompl
#include <robowflex_ompl/ompl_interface.h>
static const std::string GROUP = "arm_with_torso";
using namespace robowflex;
int main(int argc, char **argv)
{
ROS ros(argc, argv, "urdf_scenes");
ros::NodeHandle node("~");
// Create scene
auto scene_robot = std::make_shared<Robot>("robot");
// scene_robot->initialize("package://fetch_description/robots/fetch.urdf");
scene_robot->initialize("package://motion_bench_maker/configs/scenes/kitchen/kitchen.urdf");
scene_robot->getScratchState()->setToRandomPositions();
scene_robot->dumpToScene(IO::resolvePackage("package://motion_bench_maker/"
"configs/scenes/kitchen/"
"kitchen_urdf.yaml"));
auto robot = std::make_shared<robowflex::FetchRobot>();
robot->initialize();
auto scene = std::make_shared<robowflex::Scene>(robot);
// Create RVIZ helper.
auto rviz = std::make_shared<IO::RVIZHelper>(robot);
// Create the default planner for the Fetch.
auto planner = std::make_shared<OMPL::FetchOMPLPipelinePlanner>(robot, "default");
planner->initialize();
// Create a motion planning request with a pose goal.
auto request = std::make_shared<MotionRequestBuilder>(planner, GROUP);
robot->setGroupState(GROUP, {0.05, 1.32, 1.40, -0.2, 1.72, 0.0, 1.66, 0.0}); // Stow
request->setStartConfiguration(robot->getScratchState());
robot->setGroupState(GROUP, {0.15, 0, 0, 0, 0, 0, 0, 0});
request->setGoalConfiguration(robot->getScratchState());
request->setConfig("RRTConnect");
int attempts = 0;
while (1)
{
scene_robot->getScratchState()->setToRandomPositions();
scene_robot->dumpToScene(IO::resolvePackage("package://motion_bench_maker/"
"configs/scenes/kitchen/"
"kitchen_urdf.yaml"));
ROS_INFO("Visualizing scene %d ....", attempts);
attempts += 1;
scene->fromYAMLFile(IO::resolvePackage("package://motion_bench_maker/"
"configs/scenes/kitchen/"
"kitchen_urdf.yaml"));
rviz->updateScene(scene);
rviz->updateScene(scene);
// Visualize start state.
rviz->visualizeState(request->getStartConfiguration());
parser::waitForUser("Displaying initial state!");
// Visualize goal state.
rviz->visualizeState(request->getGoalConfiguration());
parser::waitForUser("Displaying goal state!");
auto res = planner->plan(scene, request->getRequestConst());
auto trajectory = std::make_shared<Trajectory>(*res.trajectory_);
if (res.error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS)
{
// Visualize the trajectory.
rviz->updateTrajectory(trajectory->getTrajectory());
parser::waitForUser("Displaying The trajectory!");
}
}
}
| 37.804348 | 96 | 0.63226 | psh117 |
873ff515bbef697598acb4f7c9defed11472eb93 | 273 | cpp | C++ | Some_cpp_sols/A1467.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | Some_cpp_sols/A1467.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | Some_cpp_sols/A1467.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int t,n,counter;cin>>t;while(t--){cin>>n;counter=0;for(int i=0;i<n;i++){if(i == 2 || i == 0){cout<<9;}if(i == 1){cout<<8;}if(i > 2){cout<<counter;counter = counter == 9 ? 0: counter + 1;}}cout<<"\n";}
return 0;
} | 45.5 | 204 | 0.567766 | Darknez07 |
8740058b7482430fa785a8635f2de62be14297d1 | 360 | cc | C++ | example/main.cc | baotiao/picdb | ca3d92f721796abb0620fdc7045465dd54ac6037 | [
"MIT"
] | 1 | 2016-09-13T09:18:06.000Z | 2016-09-13T09:18:06.000Z | example/main.cc | baotiao/picdb | ca3d92f721796abb0620fdc7045465dd54ac6037 | [
"MIT"
] | null | null | null | example/main.cc | baotiao/picdb | ca3d92f721796abb0620fdc7045465dd54ac6037 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <unistd.h>
#include <linux/falloc.h>
#include <fcntl.h>
#include "xdebug.h"
#include "include/db.h"
#include "output/include/options.h"
int main()
{
bitcask::Options op;
bitcask::DB *db;
db = NULL;
bitcask::DB::Open(op, "./db", &db);
// bitcask::WriteOptions wop;
// db->Put(wop, "zz", "czzzz");
return 0;
}
| 13.846154 | 37 | 0.613889 | baotiao |
87403295a119177bfdc6a356c9e15263d14c8b57 | 919 | cpp | C++ | image.ContourDetector/src/contour_detector.cpp | LALMAN2000/bnosa | d37e869c724736133b0ac1513a366817bb2dc5c1 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | 243 | 2017-02-28T08:52:35.000Z | 2022-03-10T16:54:48.000Z | image.ContourDetector/src/contour_detector.cpp | LALMAN2000/bnosa | d37e869c724736133b0ac1513a366817bb2dc5c1 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | 25 | 2017-07-07T20:39:47.000Z | 2022-03-15T11:38:14.000Z | image.ContourDetector/src/contour_detector.cpp | LALMAN2000/bnosa | d37e869c724736133b0ac1513a366817bb2dc5c1 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | 59 | 2017-04-05T15:39:19.000Z | 2021-11-08T13:49:08.000Z | #include <Rcpp.h>
using namespace Rcpp;
extern "C" {
#include "smooth_contours.h"
}
// [[Rcpp::export]]
List detect_contours(NumericVector image, int X, int Y, double Q = 2.0)
{
double * x; /* x[n] y[n] coordinates of result contour point n */
double * y;
int * curve_limits; /* limits of the curves in the x[] and y[] */
int N,M; /* result: N contour points, forming M curves */
//double Q = 2.0; /* default Q=2 */
//double W = 1.3; /* PDF line width 1.3 */
smooth_contours(&x, &y, &N, &curve_limits, &M, image.begin(), X, Y, Q);
NumericVector contour_x(N);
for(int i = 0; i < N; i++) contour_x[i] = x[i];
NumericVector contour_y(N);
for(int i = 0; i < N; i++) contour_y[i] = y[i];
NumericVector curvelimits(M);
for(int i = 0; i < M; i++) curvelimits[i] = curve_limits[i];
List z = List::create(contour_x, contour_y, curvelimits, M, N);
return z;
}
| 27.848485 | 76 | 0.594124 | LALMAN2000 |
874325ee04d2502492e247783c225fcbc6a4403e | 3,369 | hpp | C++ | gears/meta/core.hpp | Rapptz/Gears | ce65bf135057939c19710286f772a874504efeb4 | [
"MIT"
] | 16 | 2015-01-18T13:40:22.000Z | 2021-11-08T11:52:35.000Z | gears/meta/core.hpp | Rapptz/Gears | ce65bf135057939c19710286f772a874504efeb4 | [
"MIT"
] | 3 | 2015-01-17T01:23:26.000Z | 2015-03-30T22:30:01.000Z | gears/meta/core.hpp | Rapptz/Gears | ce65bf135057939c19710286f772a874504efeb4 | [
"MIT"
] | 3 | 2017-10-21T05:42:58.000Z | 2021-06-07T18:04:40.000Z | // The MIT License (MIT)
// Copyright (c) 2012-2014 Danny Y., Rapptz
// 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.
#ifndef GEARS_META_CORE_HPP
#define GEARS_META_CORE_HPP
#include <type_traits>
// macros for C++14 detection
#ifndef GEARS_META_HAS_CPP14
#define GEARS_META_CLANG defined(__clang__) && ((__clang_major__ > 3) || (__clang_major__ == 3) && (__clang_minor__ >= 4))
#define GEARS_META_HAS_CPP14 GEARS_META_CLANG
#endif
namespace gears {
namespace meta {
/**
* @ingroup meta
* @brief Template alias for getting the type
*/
template<typename T>
using eval = typename T::type;
/**
* @ingroup meta
* @brief Template alias for `std::integral_constant`.
*/
template<typename T, T t>
using constant = std::integral_constant<T, t>;
/**
* @ingroup meta
* @brief Template alias for integer `std::integral_constant`.
*/
template<int i>
using integer = constant<int, i>;
/**
* @ingroup meta
* @brief Tag used to check if a type is deduced.
*/
struct deduced {};
/**
* @ingroup meta
* @brief Metafunction used to check if a type is the same as deduced.
*/
template<typename T>
using is_deduced = std::is_same<T, deduced>;
/**
* @ingroup meta
* @brief Identity meta function
* @details The identity meta function. Typically
* used for lazy evaluation or forced template parameter
* evaluation.
*
*/
template<typename T>
struct identity {
using type = T;
};
/**
* @ingroup meta
* @brief Void meta function.
* @details Void meta function. Used to swallow
* arguments and evaluate to void.
*
*/
template<typename...>
struct void_ {
using type = void;
};
/**
* @ingroup meta
* @brief Template alias for void meta function.
*/
template<typename... T>
using void_t = eval<void_<T...>>;
/**
* @ingroup meta
* @brief Template alias for `std::integral_constant<bool, B>`.
*/
template<bool B>
using boolean = constant<bool, B>;
/**
* @ingroup meta
* @brief Removes all cv and ref qualifiers from a type.
*/
template<typename T>
struct unqualified {
using type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
};
/**
* @ingroup meta
* @brief Template alias for `std::aligned_storage` with proper alignment.
*/
template<typename T>
using storage_for = eval<std::aligned_storage<sizeof(T), std::alignment_of<T>::value>>;
} // meta
} // gears
#endif // GEARS_META_CORE_HPP
| 26.320313 | 122 | 0.721282 | Rapptz |
8747ea64e5078cadc82e49c525d94acc7a012438 | 12,264 | hpp | C++ | include/VROSC/GarbageManager.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/GarbageManager.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/GarbageManager.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: Error
struct Error;
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: GarbageManager
class GarbageManager;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::GarbageManager);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::GarbageManager*, "VROSC", "GarbageManager");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x19
#pragma pack(push, 1)
// Autogenerated type: VROSC.GarbageManager
// [TokenAttribute] Offset: FFFFFFFF
class GarbageManager : public ::UnityEngine::MonoBehaviour {
public:
// Nested type: ::VROSC::GarbageManager::$DisableCollectionForSessionHandling$d__7
struct $DisableCollectionForSessionHandling$d__7;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.Boolean _automaticCollectionEnabled
// Size: 0x1
// Offset: 0x18
bool automaticCollectionEnabled;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private System.Boolean _automaticCollectionEnabled
bool& dyn__automaticCollectionEnabled();
// protected System.Void Awake()
// Offset: 0x88FABC
void Awake();
// protected System.Void OnDestroy()
// Offset: 0x890008
void OnDestroy();
// protected System.Void Start()
// Offset: 0x890554
void Start();
// private System.Void EnableAutomaticCollection(System.Boolean enable)
// Offset: 0x890620
void EnableAutomaticCollection(bool enable);
// public System.Void Collect()
// Offset: 0x890584
void Collect();
// private System.Void EnableCollectionForSessionHandling()
// Offset: 0x890668
void EnableCollectionForSessionHandling();
// private System.Void DisableCollectionForSessionHandling()
// Offset: 0x89069C
void DisableCollectionForSessionHandling();
// private System.Void RecorderSaveSucceeded()
// Offset: 0x890760
void RecorderSaveSucceeded();
// private System.Void RecorderSaveFailed(VROSC.Error error)
// Offset: 0x890764
void RecorderSaveFailed(::VROSC::Error error);
// private System.Void SaveSucceeded(System.String sessionId)
// Offset: 0x890768
void SaveSucceeded(::StringW sessionId);
// private System.Void SaveFailed(System.String sessionId, VROSC.Error error)
// Offset: 0x89076C
void SaveFailed(::StringW sessionId, ::VROSC::Error error);
// private System.Void LoadSucceeded(System.String sessionId, System.Boolean isDefaultSession)
// Offset: 0x890770
void LoadSucceeded(::StringW sessionId, bool isDefaultSession);
// private System.Void LoadFailed(System.String sessionId, System.Boolean isDefaultSession, VROSC.Error error)
// Offset: 0x890774
void LoadFailed(::StringW sessionId, bool isDefaultSession, ::VROSC::Error error);
// public System.Void .ctor()
// Offset: 0x890778
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static GarbageManager* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::GarbageManager::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<GarbageManager*, creationType>()));
}
}; // VROSC.GarbageManager
#pragma pack(pop)
static check_size<sizeof(GarbageManager), 24 + sizeof(bool)> __VROSC_GarbageManagerSizeCheck;
static_assert(sizeof(GarbageManager) == 0x19);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::GarbageManager::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::EnableAutomaticCollection
// Il2CppName: EnableAutomaticCollection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(bool)>(&VROSC::GarbageManager::EnableAutomaticCollection)> {
static const MethodInfo* get() {
static auto* enable = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "EnableAutomaticCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{enable});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::Collect
// Il2CppName: Collect
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::Collect)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "Collect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::EnableCollectionForSessionHandling
// Il2CppName: EnableCollectionForSessionHandling
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::EnableCollectionForSessionHandling)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "EnableCollectionForSessionHandling", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::DisableCollectionForSessionHandling
// Il2CppName: DisableCollectionForSessionHandling
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::DisableCollectionForSessionHandling)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "DisableCollectionForSessionHandling", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::RecorderSaveSucceeded
// Il2CppName: RecorderSaveSucceeded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::RecorderSaveSucceeded)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "RecorderSaveSucceeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::RecorderSaveFailed
// Il2CppName: RecorderSaveFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::VROSC::Error)>(&VROSC::GarbageManager::RecorderSaveFailed)> {
static const MethodInfo* get() {
static auto* error = &::il2cpp_utils::GetClassFromName("VROSC", "Error")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "RecorderSaveFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{error});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::SaveSucceeded
// Il2CppName: SaveSucceeded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW)>(&VROSC::GarbageManager::SaveSucceeded)> {
static const MethodInfo* get() {
static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "SaveSucceeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::SaveFailed
// Il2CppName: SaveFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW, ::VROSC::Error)>(&VROSC::GarbageManager::SaveFailed)> {
static const MethodInfo* get() {
static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* error = &::il2cpp_utils::GetClassFromName("VROSC", "Error")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "SaveFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, error});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::LoadSucceeded
// Il2CppName: LoadSucceeded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW, bool)>(&VROSC::GarbageManager::LoadSucceeded)> {
static const MethodInfo* get() {
static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* isDefaultSession = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "LoadSucceeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, isDefaultSession});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::LoadFailed
// Il2CppName: LoadFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW, bool, ::VROSC::Error)>(&VROSC::GarbageManager::LoadFailed)> {
static const MethodInfo* get() {
static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* isDefaultSession = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* error = &::il2cpp_utils::GetClassFromName("VROSC", "Error")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "LoadFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, isDefaultSession, error});
}
};
// Writing MetadataGetter for method: VROSC::GarbageManager::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 51.746835 | 184 | 0.740868 | RedBrumbler |
874995fe98ffeae177797375b13cf239a4796968 | 3,339 | cpp | C++ | src/agent/Shared/Fundamentals/Utils.cpp | m5o/passenger | 9640816af708867d0994bd2eddb80ac24399f855 | [
"MIT"
] | 2,728 | 2015-01-01T10:06:45.000Z | 2022-03-30T18:12:58.000Z | src/agent/Shared/Fundamentals/Utils.cpp | philson-philip/passenger | 144a6f39722987921c7fce0be9d64befb125a88b | [
"MIT"
] | 1,192 | 2015-01-01T06:03:19.000Z | 2022-03-31T09:14:36.000Z | src/agent/Shared/Fundamentals/Utils.cpp | philson-philip/passenger | 144a6f39722987921c7fce0be9d64befb125a88b | [
"MIT"
] | 334 | 2015-01-08T20:47:03.000Z | 2022-02-18T07:07:01.000Z | /*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-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.
*/
#include <Shared/Fundamentals/Utils.h>
#include <oxt/backtrace.hpp>
#include <cstdlib>
#include <cstring>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
namespace Passenger {
namespace Agent {
namespace Fundamentals {
using namespace std;
const char *
getEnvString(const char *name, const char *defaultValue) {
const char *value = getenv(name);
if (value != NULL && *value != '\0') {
return value;
} else {
return defaultValue;
}
}
bool
getEnvBool(const char *name, bool defaultValue) {
const char *value = getEnvString(name);
if (value != NULL) {
return strcmp(value, "yes") == 0
|| strcmp(value, "y") == 0
|| strcmp(value, "1") == 0
|| strcmp(value, "on") == 0
|| strcmp(value, "true") == 0;
} else {
return defaultValue;
}
}
void
ignoreSigpipe() {
struct sigaction action;
action.sa_handler = SIG_IGN;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGPIPE, &action, NULL);
}
/**
* Linux-only way to change OOM killer configuration for
* current process. Requires root privileges, which we
* should have.
*
* Returns 0 on success, or an errno code on error.
*
* This function is async signal-safe.
*/
int
tryRestoreOomScore(const StaticString &scoreString, bool &isLegacy) {
TRACE_POINT();
if (scoreString.empty()) {
return 0;
}
int fd, ret, e;
size_t written = 0;
StaticString score;
if (scoreString.at(0) == 'l') {
isLegacy = true;
score = scoreString.substr(1);
fd = open("/proc/self/oom_adj", O_WRONLY | O_TRUNC, 0600);
} else {
isLegacy = false;
score = scoreString;
fd = open("/proc/self/oom_score_adj", O_WRONLY | O_TRUNC, 0600);
}
if (fd == -1) {
return errno;
}
do {
ret = write(fd, score.data() + written, score.size() - written);
if (ret != -1) {
written += ret;
}
} while (ret == -1 && errno != EAGAIN && written < score.size());
e = errno;
close(fd);
if (ret == -1) {
return e;
} else {
return 0;
}
}
} // namespace Fundamentals
} // namespace Agent
} // namespace Passenger
| 26.085938 | 81 | 0.685235 | m5o |
874af4cb08261e47f30739b862bc3d57b47678b2 | 533 | cpp | C++ | 0039-Recover Rotated Sorted Array/0039-Recover Rotated Sorted Array.cpp | nmdis1999/LintCode-1 | 316fa395c9a6de9bfac1d9c9cf58acb5ffb384a6 | [
"MIT"
] | 77 | 2017-12-30T13:33:37.000Z | 2022-01-16T23:47:08.000Z | 0001-0100/0039-Recover Rotated Sorted Array/0039-Recover Rotated Sorted Array.cpp | jxhangithub/LintCode-1 | a8aecc65c47a944e9debad1971a7bc6b8776e48b | [
"MIT"
] | 1 | 2018-05-14T14:15:40.000Z | 2018-05-14T14:15:40.000Z | 0001-0100/0039-Recover Rotated Sorted Array/0039-Recover Rotated Sorted Array.cpp | jxhangithub/LintCode-1 | a8aecc65c47a944e9debad1971a7bc6b8776e48b | [
"MIT"
] | 39 | 2017-12-07T14:36:25.000Z | 2022-03-10T23:05:37.000Z | class Solution {
public:
void recoverRotatedSortedArray(vector<int> &nums) {
// write your code here
if (nums.size() == 0)
{
return;
}
for (int i = 0; i < nums.size() - 1; ++i)
{
if (nums[i] > nums[i + 1])
{
reverse(nums.begin(), nums.begin() + i + 1);
reverse(nums.begin() + i + 1, nums.end());
reverse(nums.begin(), nums.end());
return;
}
}
}
};
| 24.227273 | 60 | 0.390244 | nmdis1999 |
87509160f6dcfb7d192723537785b4342edce344 | 781 | cpp | C++ | src/Core/Grammar/LoopBreaker.cpp | johnzeng/SimpleCompletor | e54b57242b7e624fea2d240bc50733ab6be72f6d | [
"MIT"
] | 1 | 2016-06-10T05:30:32.000Z | 2016-06-10T05:30:32.000Z | src/Core/Grammar/LoopBreaker.cpp | johnzeng/SimpleCompletor | e54b57242b7e624fea2d240bc50733ab6be72f6d | [
"MIT"
] | 1 | 2016-07-19T02:36:39.000Z | 2016-08-12T02:11:51.000Z | src/Core/Grammar/LoopBreaker.cpp | johnzeng/CppParser | e54b57242b7e624fea2d240bc50733ab6be72f6d | [
"MIT"
] | null | null | null | #include "LoopBreaker.h"
#include "StringUtil.h"
LoopBreaker::LoopBreaker(){}
LoopBreaker::~LoopBreaker(){}
bool LoopBreaker::insert(const string& file, int line, int index)
{
if (false == check(file, line, index))
{
return false;
}
mLoopMark[getKey(file, line, index)] = 1;
return true;
}
bool LoopBreaker::check(const string& file, int line, int index)
{
auto it = mLoopMark.find(getKey(file,line, index)) ;
if (mLoopMark.end() == it)
{
return true;
}
return it->second == 0;
}
void LoopBreaker::remomve(const string& file, int line, int index)
{
mLoopMark[getKey(file, line, index)] = 0;
}
string LoopBreaker::getKey(const string& file, int line, int index)
{
return file + ":" + StringUtil::tostr(line) + ":" + StringUtil::tostr(index);
}
| 21.108108 | 79 | 0.664533 | johnzeng |
87546f6abfb80b325f8a6b2457886b86016c83a8 | 918 | cpp | C++ | aws-cpp-sdk-wellarchitected/source/model/UpgradeLensReviewRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-wellarchitected/source/model/UpgradeLensReviewRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-wellarchitected/source/model/UpgradeLensReviewRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/wellarchitected/model/UpgradeLensReviewRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::WellArchitected::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
UpgradeLensReviewRequest::UpgradeLensReviewRequest() :
m_workloadIdHasBeenSet(false),
m_lensAliasHasBeenSet(false),
m_milestoneNameHasBeenSet(false),
m_clientRequestTokenHasBeenSet(false)
{
}
Aws::String UpgradeLensReviewRequest::SerializePayload() const
{
JsonValue payload;
if(m_milestoneNameHasBeenSet)
{
payload.WithString("MilestoneName", m_milestoneName);
}
if(m_clientRequestTokenHasBeenSet)
{
payload.WithString("ClientRequestToken", m_clientRequestToken);
}
return payload.View().WriteReadable();
}
| 20.4 | 69 | 0.761438 | perfectrecall |
8759450edf0914156ea45d95387556e618c96a60 | 5,320 | hpp | C++ | src/musicpp/Enums.hpp | Cannedfood/musicpp | e2ba4337f7a434533ad15a2b4ce3c2d2a767c4ee | [
"Zlib"
] | null | null | null | src/musicpp/Enums.hpp | Cannedfood/musicpp | e2ba4337f7a434533ad15a2b4ce3c2d2a767c4ee | [
"Zlib"
] | null | null | null | src/musicpp/Enums.hpp | Cannedfood/musicpp | e2ba4337f7a434533ad15a2b4ce3c2d2a767c4ee | [
"Zlib"
] | null | null | null | // Copyright 2018 Benno Straub, Licensed under the MIT License, a copy can be found at the bottom of this file.
#pragma once
#include <string_view>
#include <array>
#include <stdexcept>
namespace music {
enum Accidental : int8_t {
FLAT = -1,
NATURAL = 0,
SHARP = 1,
};
enum Chroma : int8_t {
C = 0,
Cs = 1,
D = 2, Db = Cs,
Ds = 3,
E = 4, Eb = Ds,
F = 5, Fb = E,
Fs = 6, Gb = Fs,
G = 7,
Gs = 8, Ab = Gs,
A = 9,
As = 10, Bb = As,
B = 11,
};
namespace detail {
constexpr inline int negativeModulo(int a, int b) {
int result = a % b;
if(result < 0) result += b;
return result;
}
}
constexpr inline Chroma operator+ (Chroma v, int interval) noexcept { return Chroma(detail::negativeModulo(int(v) + interval, 12)); }
constexpr inline Chroma operator- (Chroma v, int interval) noexcept { return Chroma(detail::negativeModulo(int(v) - interval, 12)); }
constexpr inline Chroma operator+=(Chroma& v, int interval) noexcept { return v = v + interval; }
constexpr inline Chroma operator-=(Chroma& v, int interval) noexcept { return v = v - interval; }
constexpr inline
bool not_sharp_or_flat(Chroma note) {
switch(note){
case A: case B: case C: case D: case E: case F: case G:
return true;
default:
return false;
}
}
enum Interval : int {
prime = 0,
min2nd = 1,
maj2nd = 2,
min3rd = 3, m = 3,
maj3rd = 4, M = 4,
perf4th = 5,
aug4th = 6,
dim5th = 6,
perf5th = 7,
aug5th = 8,
min6th = 8,
maj6th = 9,
min7th = 10,
maj7th = 11,
octave = 12,
min9th = 13,
maj9th = 14,
min10th = 15,
maj10th = 16,
perf11th = 17,
aug11th = 18,
dim12th = 18,
pref12th = 19,
};
constexpr inline Interval operator- (Chroma a, Chroma b) noexcept { return Interval(detail::negativeModulo(int(a) - int(b), 12)); }
constexpr inline
std::string_view to_string(Chroma value, Accidental hint = NATURAL) noexcept {
if(hint == NATURAL) hint = SHARP;
switch(value) {
case C: return "C";
case Cs: return hint==SHARP?"C#":"Db";
case D: return "D";
case Ds: return hint==SHARP?"D#":"Eb";
case E: return "E";
case F: return "F";
case Fs: return hint==SHARP?"F#":"Gb";
case G: return "G";
case Gs: return hint==SHARP?"G#":"Ab";
case A: return "A";
case As: return hint==SHARP?"A#":"Bb";
case B: return "B";
}
}
constexpr inline
Chroma from_string(std::string_view s, Accidental alter = NATURAL) {
if(s == "C") return Chroma::C + alter;
if(s == "C#") return Chroma::Cs + alter;
if(s == "Cb") return Chroma::B + alter;
if(s == "D") return Chroma::D + alter;
if(s == "D#") return Chroma::Db + alter;
if(s == "Db") return Chroma::Ds + alter;
if(s == "E") return Chroma::E + alter;
if(s == "E#") return Chroma::F + alter;
if(s == "Eb") return Chroma::Eb + alter;
if(s == "F") return Chroma::F + alter;
if(s == "F#") return Chroma::Fs + alter;
if(s == "Fb") return Chroma::Fb + alter;
if(s == "G") return Chroma::G + alter;
if(s == "G#") return Chroma::Gs + alter;
if(s == "Gb") return Chroma::Gb + alter;
if(s == "A") return Chroma::A + alter;
if(s == "A#") return Chroma::As + alter;
if(s == "Ab") return Chroma::Ab + alter;
if(s == "B") return Chroma::B + alter;
if(s == "B#") return Chroma::C + alter;
if(s == "Bb") return Chroma::Bb + alter;
throw std::runtime_error("Failed parsing Chroma");
}
constexpr inline
std::string_view to_string(Interval ivl, Accidental hint = NATURAL) noexcept {
if(hint == NATURAL) hint = SHARP;
switch(ivl) {
case prime: return "1st";
case min2nd: return "m2nd";
case maj2nd: return "2nd";
case min3rd: return "m3rd";
case maj3rd: return "3rd";
case perf4th: return "4th";
case aug4th: return "aug. 4th";
case perf5th: return "5th";
case aug5th: return "aug. 5th";
case maj6th: return "6th";
case min7th: return "m7th";
case maj7th: return "7th";
case octave: return "octave";
case min9th: return "m9th";
case maj9th: return "9th";
case min10th: return "m10th";
case maj10th: return "10th";
case perf11th: return "11th";
case aug11th: return "aug. 11th";
default: return "?";
}
}
} // namespace music
// The MIT License (MIT)
// Copyright (c) 2018 Benno Straub
// 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.
| 29.72067 | 134 | 0.641729 | Cannedfood |
87598f7bc09dea23ca6541153d611f55b7056819 | 1,209 | hpp | C++ | Questless/Questless/src/entities/beings/world_view.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | 2 | 2020-07-14T12:50:06.000Z | 2020-11-04T02:25:09.000Z | Questless/Questless/src/entities/beings/world_view.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | null | null | null | Questless/Questless/src/entities/beings/world_view.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | null | null | null | //! @file
//! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>.
#pragma once
#include "entities/perception.hpp"
#include "world/coordinates.hpp"
#include "world/section.hpp"
#include <array>
#include <optional>
#include <variant>
#include <vector>
namespace ql {
struct being;
//! Represents everything an agent can perceive about its being's environment.
struct world_view {
struct tile_view {
id id;
perception perception;
// Position is included here (redundantly) for efficiency because it's required in various places.
view::point position;
};
struct entity_view {
id id;
perception perception;
// Position is included here (redundantly) for efficiency because it's required in various places.
view::point position;
};
std::vector<tile_view> tile_views;
std::vector<entity_view> entity_views;
location center;
pace visual_range;
//! Constructs the world view of the being with id @p viewer_id.
world_view(ql::reg& reg, id viewer_id);
world_view(world_view const&) = default;
world_view(world_view&&) = default;
auto operator=(world_view const&) -> world_view& = default;
auto operator=(world_view &&) -> world_view& = default;
};
}
| 23.705882 | 101 | 0.71464 | jonathansharman |
87643dc47b33eb0417bee94f127e4e45c81716ff | 417 | hpp | C++ | library/ATF/_force_result_other_zocl.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/_force_result_other_zocl.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/_force_result_other_zocl.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_CHRID.hpp>
START_ATF_NAMESPACE
struct _force_result_other_zocl
{
char byRetCode;
char byForceIndex;
char byForceLv;
_CHRID idPerformer;
_CHRID idDster;
char byAttackSerial;
};
END_ATF_NAMESPACE
| 21.947368 | 108 | 0.688249 | lemkova |
8766ad7e467125ea0d05c0ec58631a7ebe879e6c | 10,339 | hpp | C++ | timer/timer.hpp | Spilleren/mega2560-hal | 6531602e77cc94bb225e9df829e2f6d356ad00cf | [
"MIT"
] | null | null | null | timer/timer.hpp | Spilleren/mega2560-hal | 6531602e77cc94bb225e9df829e2f6d356ad00cf | [
"MIT"
] | null | null | null | timer/timer.hpp | Spilleren/mega2560-hal | 6531602e77cc94bb225e9df829e2f6d356ad00cf | [
"MIT"
] | null | null | null | #pragma once
#include "interface_timer.hpp"
#include "timer_configs.hpp"
#include <stdint.h>
namespace MEGA2560
{
namespace Timer
{
template <typename config>
class Device : public InterfaceTimer
{
public:
static Device &instance()
{
static Device instance;
return instance;
}
/*
Timer created as a singleton object
*/
Device(const Device &) = delete;
Device(Device &&) = delete;
Device &operator=(const Device &) = delete;
Device &operator=(Device &&) = delete;
/*
Initiate timer with default values
- fast pwm
- input_capture 40000
- prescaler 8
- compare value 1500
- non-inverting compare mode
*/
void init()
{
set_waveform_generation_mode(fast_pwm_input_top);
set_input_capture(40000);
set_prescaler(8);
set_compare(1500);
set_compare_output_mode(non_inverting);
}
/*
Set compare output for all channels
*/
void set_compare_output_mode(compare_output_mode mode)
{
set_compare_output_mode(mode, output_channel::A);
set_compare_output_mode(mode, output_channel::B);
set_compare_output_mode(mode, output_channel::C);
}
/*
Set compare output for specific channel
*/
void set_compare_output_mode(compare_output_mode mode, output_channel channel)
{
if (channel == A)
{
switch (mode)
{
case normal_compare:
*config::TCCRA |= (0 << COM1A1) | (0 << COM1A0);
break;
case toggle:
*config::TCCRA |= (0 << COM1A1) | (1 << COM1A0);
break;
case non_inverting:
*config::TCCRA |= (1 << COM1A1) | (0 << COM1A0);
break;
case inverting:
*config::TCCRA |= (1 << COM1A1) | (1 << COM1A0);
break;
default:
*config::TCCRA |= (0 << COM1A1) | (0 << COM1A0);
break;
}
}
if (channel == B)
{
switch (mode)
{
case normal_compare:
*config::TCCRA |= (0 << COM1B1) | (0 << COM1B0);
break;
case toggle:
*config::TCCRA |= (0 << COM1B1) | (1 << COM1B0);
break;
case non_inverting:
*config::TCCRA |= (1 << COM1B1) | (0 << COM1B0);
break;
case inverting:
*config::TCCRA |= (1 << COM1B1) | (1 << COM1B0);
break;
default:
*config::TCCRA |= (0 << COM1B1) | (0 << COM1B0);
break;
}
}
if (channel == C)
{
switch (mode)
{
case normal_compare:
*config::TCCRA |= (0 << COM1C1) | (0 << COM1C0);
break;
case toggle:
*config::TCCRA |= (0 << COM1C1) | (1 << COM1C0);
break;
case non_inverting:
*config::TCCRA |= (1 << COM1C1) | (0 << COM1C0);
break;
case inverting:
*config::TCCRA |= (1 << COM1C1) | (1 << COM1C0);
break;
default:
*config::TCCRA |= (0 << COM1C1) | (0 << COM1C0);
break;
}
}
}
/*
Set waveform generation mode
*/
void set_waveform_generation_mode(waveform_mode mode)
{
switch (mode)
{
case normal_waveform:
*config::TCCRA |= (0 << WGM11) | (0 << WGM10);
*config::TCCRB |= (0 << WGM13) | (0 << WGM12);
break;
case pwm_phase_correct_8bit:
*config::TCCRA |= (0 << WGM11) | (1 << WGM10);
*config::TCCRB |= (0 << WGM13) | (0 << WGM12);
break;
case pwm_phase_correct_9bit:
*config::TCCRA |= (1 << WGM11) | (0 << WGM10);
*config::TCCRB |= (0 << WGM13) | (0 << WGM12);
break;
case pwm_phase_correct_10bit:
*config::TCCRA |= (1 << WGM11) | (1 << WGM10);
*config::TCCRB |= (0 << WGM13) | (0 << WGM12);
break;
case ctc_compare_top:
*config::TCCRA |= (0 << WGM11) | (0 << WGM10);
*config::TCCRB |= (0 << WGM13) | (1 << WGM12);
break;
case fast_pwm_8bit:
*config::TCCRA |= (0 << WGM11) | (1 << WGM10);
*config::TCCRB |= (0 << WGM13) | (1 << WGM12);
break;
case fast_pwm_9bit:
*config::TCCRA |= (1 << WGM11) | (0 << WGM10);
*config::TCCRB |= (0 << WGM13) | (1 << WGM12);
break;
case fast_pwm_10bit:
*config::TCCRA |= (1 << WGM11) | (1 << WGM10);
*config::TCCRB |= (0 << WGM13) | (1 << WGM12);
break;
case pwm_phase_freq_correct_input_top:
*config::TCCRA |= (0 << WGM11) | (0 << WGM10);
*config::TCCRB |= (1 << WGM13) | (0 << WGM12);
break;
case pwm_phase_freq_correct_compare_top:
*config::TCCRA |= (0 << WGM11) | (1 << WGM10);
*config::TCCRB |= (1 << WGM13) | (0 << WGM12);
break;
case pwm_phase_correct_input_top:
*config::TCCRA |= (0 << WGM11) | (1 << WGM10);
*config::TCCRB |= (1 << WGM13) | (0 << WGM12);
break;
case pwm_phase_correct_compare_top:
*config::TCCRA |= (1 << WGM11) | (1 << WGM10);
*config::TCCRB |= (1 << WGM13) | (0 << WGM12);
break;
case ctc_input_top:
*config::TCCRA |= (0 << WGM11) | (0 << WGM10);
*config::TCCRB |= (1 << WGM13) | (1 << WGM12);
break;
case fast_pwm_input_top:
*config::TCCRA |= (1 << WGM11) | (0 << WGM10);
*config::TCCRB |= (1 << WGM13) | (1 << WGM12);
break;
case fast_pwm_compare_top:
*config::TCCRA |= (1 << WGM11) | (1 << WGM10);
*config::TCCRB |= (1 << WGM13) | (1 << WGM12);
break;
default:
break;
}
}
/*
Set prescaler to prefered value
Input options are 0, 1, 8, 64, 256 and 1024
*/
void set_prescaler(uint16_t prescaler)
{
switch (prescaler)
{
case 0:
*config::TCCRB |= (0 << CS12) | (0 << CS11) | (0 << CS10);
break;
case 1:
*config::TCCRB |= (0 << CS12) | (0 << CS11) | (1 << CS10);
break;
case 8:
*config::TCCRB |= (0 << CS12) | (1 << CS11) | (0 << CS10);
break;
case 64:
*config::TCCRB |= (0 << CS12) | (1 << CS11) | (1 << CS10);
break;
case 256:
*config::TCCRB |= (1 << CS12) | (0 << CS11) | (0 << CS10);
break;
case 1024:
*config::TCCRB |= (1 << CS12) | (0 << CS11) | (1 << CS10);
break;
default:
*config::TCCRB |= (0 << CS12) | (0 << CS11) | (0 << CS10);
break;
}
}
/*
Set compare value for specfic channel
*/
void set_compare(uint16_t value, output_channel output)
{
switch (output)
{
case A:
*config::OCRA = value;
break;
case B:
*config::OCRB = value;
break;
case C:
*config::OCRC = value;
break;
default:
break;
}
}
/*
Set compare value for all channels
*/
void set_compare(uint16_t value)
{
set_compare(value, output_channel::A);
set_compare(value, output_channel::B);
set_compare(value, output_channel::C);
}
void set_input_capture(uint16_t value)
{
*config::ICR |= value;
}
/*
Enable interrupt type
Input options are
- input_capture
- output_compare_c
- output_compare_b
- output_compare_a
- timer_overflow
*/
void interrupt_type_enable(interrupt_type value)
{
// sei();
switch (value)
{
case input_capture:
*config::TIMSK |= (1 << ICIE1);
break;
case output_compare_c:
*config::TIMSK |= (1 << OCIE1C);
break;
case output_compare_b:
*config::TIMSK |= (1 << OCIE1B);
break;
case output_compare_a:
*config::TIMSK |= (1 << OCIE1A);
break;
case timer_overflow:
*config::TIMSK |= (1 << TOIE1);
break;
default:
break;
}
}
/*
Disable interrupt type
Input options are
- input_capture
- output_compare_c
- output_compare_b
- output_compare_a
- timer_overflow
*/
void interrupt_type_disable(interrupt_type type)
{
switch (type)
{
case input_capture:
*config::TIMSK |= (0 << ICIE1);
break;
case output_compare_c:
*config::TIMSK |= (0 << OCIE1C);
break;
case output_compare_b:
*config::TIMSK |= (0 << OCIE1B);
break;
case output_compare_a:
*config::TIMSK |= (0 << OCIE1A);
break;
case timer_overflow:
*config::TIMSK |= (0 << TOIE1);
break;
default:
break;
}
}
/* Timer enable pwm channel A, B or C*/
void enable_pwm_pin(output_channel output)
{
switch (output)
{
case A:
*config::DDR |= config::CHANNEL_A;
break;
case B:
*config::DDR |= config::CHANNEL_B;
break;
case C:
*config::DDR |= config::CHANNEL_C;
break;
default:
break;
}
}
private:
Device() {} // no one else can create one
~Device() {} // prevent accidental deletion
};
} // namespace Time
}// namespace MEGA2560 | 29.042135 | 85 | 0.448303 | Spilleren |
876a03d24d6cbaca07ec59f4252627356f92f8fb | 2,857 | cpp | C++ | suffix_array_long.cpp | agaitanis/strings | 13688cc3e9007d0dadaf92feca198272e135fe60 | [
"MIT"
] | 2 | 2018-10-30T08:13:30.000Z | 2019-03-05T22:49:40.000Z | suffix_array_long.cpp | agaitanis/strings | 13688cc3e9007d0dadaf92feca198272e135fe60 | [
"MIT"
] | null | null | null | suffix_array_long.cpp | agaitanis/strings | 13688cc3e9007d0dadaf92feca198272e135fe60 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <cassert>
using namespace std;
#define ALPHABET_SIZE 5
static void print_vec(const char *s, const vector<int> &vec)
{
cout << s << ": ";
for (size_t i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
}
static int letter_to_index(char c)
{
switch (c) {
case '$':
return 0;
case 'A':
return 1;
case 'C':
return 2;
case 'G':
return 3;
case 'T':
return 4;
default:
assert(0);
return 0;
}
}
static vector<int> SortCharacters(const string &s)
{
int n = s.size();
vector<int> order(n);
vector<int> cnt(ALPHABET_SIZE, 0);
for (int i = 0; i < n; i++) {
int c_i = letter_to_index(s[i]);
cnt[c_i]++;
}
for (size_t j = 1; j < cnt.size(); j++) {
cnt[j] += cnt[j-1];
}
for (int i = n - 1; i >= 0; i--) {
char c = letter_to_index(s[i]);
cnt[c]--;
order[cnt[c]] = i;
}
return order;
}
static vector<int> ComputeCharClasses(const string &s, const vector<int> &order)
{
int n = s.size();
vector<int> my_class(n);
my_class[order[0]] = 0;
for (size_t i = 1; i < n; i++) {
if (s[order[i]] != s[order[i-1]]) {
my_class[order[i]] = my_class[order[i-1]] + 1;
} else {
my_class[order[i]] = my_class[order[i-1]];
}
}
return my_class;
}
static vector<int> SortDoubled(const string &s, int L, const vector<int> &order, const vector<int> &my_class)
{
int n = s.size();
vector<int> cnt(n, 0);
vector<int> new_order(n);
for (int i = 0; i < n; i++) {
cnt[my_class[i]]++;
}
for (int j = 1; j < n; j++) {
cnt[j] += cnt[j-1];
}
for (int i = n - 1; i >= 0; i--) {
int start = (order[i] - L + n) % n;
int cl = my_class[start];
cnt[cl]--;
new_order[cnt[cl]] = start;
}
return new_order;
}
static vector<int> UpdateClasses(const vector<int> &new_order, const vector<int> &my_class, int L)
{
int n = new_order.size();
vector<int> new_class(n);
new_class[new_order[0]] = 0;
for (int i = 1; i < n; i++) {
int cur = new_order[i];
int prev = new_order[i-1];
int mid = (cur + L) % n;
int mid_prev = (prev + L) % n;
if (my_class[cur] != my_class[prev] || my_class[mid] != my_class[mid_prev]) {
new_class[cur] = new_class[prev] + 1;
} else {
new_class[cur] = new_class[prev];
}
}
return new_class;
}
static vector<int> BuildSuffixArray(const string &s)
{
vector<int> order = SortCharacters(s);
vector<int> my_class = ComputeCharClasses(s, order);
int n = s.size();
int L = 1;
while (L < n) {
order = SortDoubled(s, L, order, my_class);
my_class = UpdateClasses(order, my_class, L);
L *= 2;
}
return order;
}
int main()
{
string s;
cin >> s;
vector<int> suffix_array = BuildSuffixArray(s);
for (int i = 0; i < suffix_array.size(); ++i) {
cout << suffix_array[i] << ' ';
}
cout << endl;
return 0;
}
| 17.745342 | 109 | 0.583479 | agaitanis |
87722f657ad29345370fa872900120f6f91564da | 312 | hpp | C++ | include/internal/utils.hpp | hrlou/nhentai | 83440bd2b61c00d893941349bd7d571cc10cbec1 | [
"BSD-3-Clause"
] | 2 | 2020-10-11T15:27:12.000Z | 2020-10-14T19:28:09.000Z | include/internal/utils.hpp | hrlou/nhentai_c | 83440bd2b61c00d893941349bd7d571cc10cbec1 | [
"BSD-3-Clause"
] | null | null | null | include/internal/utils.hpp | hrlou/nhentai_c | 83440bd2b61c00d893941349bd7d571cc10cbec1 | [
"BSD-3-Clause"
] | 1 | 2021-05-29T07:51:02.000Z | 2021-05-29T07:51:02.000Z | #pragma once
#include <string>
namespace utils {
bool is_dir(const std::string& path);
bool exist_test(const std::string& name);
std::string dirname(const std::string& path);
std::string read_file(const std::string& name);
bool do_mkdir(const std::string& path);
bool mkpath(std::string path);
} | 22.285714 | 48 | 0.705128 | hrlou |
877583617168c2cda0f2f512daa22c2ed8b9bcc6 | 129 | cpp | C++ | tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:b7a689390058519b2e382a8fd260640bad650f9d9b17ef70106d4d3dd50bf16f
size 1082
| 32.25 | 75 | 0.883721 | initialz |
877923bbe74e410e909c125a899c18d641a3e150 | 8,094 | cpp | C++ | usr/ringbuffer.cpp | Itamare4/ROS_stm32f1_rosserial_USB_VCP | 5fac421fa991db1ffe6fa469b93c0fb9d4ae2b87 | [
"BSD-3-Clause"
] | 14 | 2018-12-06T04:04:16.000Z | 2022-03-01T17:45:04.000Z | usr/ringbuffer.cpp | Itamare4/ROS_stm32f1_rosserial_USB_VCP | 5fac421fa991db1ffe6fa469b93c0fb9d4ae2b87 | [
"BSD-3-Clause"
] | null | null | null | usr/ringbuffer.cpp | Itamare4/ROS_stm32f1_rosserial_USB_VCP | 5fac421fa991db1ffe6fa469b93c0fb9d4ae2b87 | [
"BSD-3-Clause"
] | 7 | 2018-10-09T12:17:01.000Z | 2021-09-14T02:43:13.000Z | /*
* File : ringbuffer.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2012, RT-Thread Development Team
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Change Logs:
* Date Author Notes
* 2012-09-30 Bernard first version.
* 2013-05-08 Grissiom reimplement
*/
#include "stm32f1xx_hal.h"
#include "ringbuffer.h"
#include <string.h>
#define ASSERT(EX) \
__inline enum ringbuffer_state ringbuffer_status(struct ringbuffer *rb)
{
if (rb->read_index == rb->write_index) {
if (rb->read_mirror == rb->write_mirror)
return RT_RINGBUFFER_EMPTY;
else
return RT_RINGBUFFER_FULL;
}
return RT_RINGBUFFER_HALFFULL;
}
/** return the size of data in rb */
uint16_t ringbuffer_data_len(struct ringbuffer *rb)
{
switch ( ringbuffer_status(rb)) {
case RT_RINGBUFFER_EMPTY:
return 0;
case RT_RINGBUFFER_FULL:
return rb->buffer_size;
case RT_RINGBUFFER_HALFFULL:
default:
if (rb->write_index > rb->read_index)
return rb->write_index - rb->read_index;
else
return rb->buffer_size - (rb->read_index - rb->write_index);
};
}
/** return the free space size of rb */
uint16_t ringbuffer_free_len(struct ringbuffer *rb)
{
return rb->buffer_size - ringbuffer_data_len(rb);
}
/**
* put a block of data into ring buffer
*/
uint32_t ringbuffer_put(struct ringbuffer *rb,
const uint8_t *ptr,
uint16_t length)
{
uint16_t size;
ASSERT(rb != NULL);
/* whether has enough space */
size = ringbuffer_empty_space(rb);
/* no space */
if (size == 0)
return 0;
/* drop some data */
if (size < length)
length = size;
if (rb->buffer_size - rb->write_index > length)
{
/* read_index - write_index = empty space */
memcpy(&rb->buffer_ptr[rb->write_index], ptr, length);
/* this should not cause overflow because there is enough space for
* length of data in current mirror */
rb->write_index += length;
return length;
}
memcpy(&rb->buffer_ptr[rb->write_index],
&ptr[0],
rb->buffer_size - rb->write_index);
memcpy(&rb->buffer_ptr[0],
&ptr[rb->buffer_size - rb->write_index],
length - (rb->buffer_size - rb->write_index));
/* we are going into the other side of the mirror */
rb->write_mirror = ~rb->write_mirror;
rb->write_index = length - (rb->buffer_size - rb->write_index);
return length;
}
/**
* put a block of data into ring buffer
*
* When the buffer is full, it will discard the old data.
*/
uint32_t ringbuffer_put_force(struct ringbuffer *rb, const uint8_t *ptr, uint16_t length)
{
enum ringbuffer_state old_state;
ASSERT(rb != NULL);
old_state = ringbuffer_status(rb);
if (length > rb->buffer_size)
length = rb->buffer_size;
if (rb->buffer_size - rb->write_index > length) {
/* read_index - write_index = empty space */
memcpy(&rb->buffer_ptr[rb->write_index], ptr, length);
/* this should not cause overflow because there is enough space for
* length of data in current mirror */
rb->write_index += length;
if (old_state == RT_RINGBUFFER_FULL)
rb->read_index = rb->write_index;
return length;
}
memcpy(&rb->buffer_ptr[rb->write_index], &ptr[0], rb->buffer_size - rb->write_index);
memcpy(&rb->buffer_ptr[0], &ptr[rb->buffer_size - rb->write_index],
length - (rb->buffer_size - rb->write_index));
/* we are going into the other side of the mirror */
rb->write_mirror = ~rb->write_mirror;
rb->write_index = length - (rb->buffer_size - rb->write_index);
if (old_state == RT_RINGBUFFER_FULL) {
rb->read_mirror = ~rb->read_mirror;
rb->read_index = rb->write_index;
}
return length;
}
/**
* get data from ring buffer
*/
uint32_t ringbuffer_get(struct ringbuffer *rb,
uint8_t *ptr,
uint16_t length)
{
uint32_t size;
ASSERT(rb != NULL);
/* whether has enough data */
size = ringbuffer_data_len(rb);
/* no data */
if (size == 0)
return 0;
/* less data */
if (size < length)
length = size;
if (rb->buffer_size - rb->read_index > length)
{
/* copy all of data */
memcpy(ptr, &rb->buffer_ptr[rb->read_index], length);
/* this should not cause overflow because there is enough space for
* length of data in current mirror */
rb->read_index += length;
return length;
}
memcpy(&ptr[0],
&rb->buffer_ptr[rb->read_index],
rb->buffer_size - rb->read_index);
memcpy(&ptr[rb->buffer_size - rb->read_index],
&rb->buffer_ptr[0],
length - (rb->buffer_size - rb->read_index));
/* we are going into the other side of the mirror */
rb->read_mirror = ~rb->read_mirror;
rb->read_index = length - (rb->buffer_size - rb->read_index);
return length;
}
/**
* put a character into ring buffer
*/
uint32_t ringbuffer_putchar(struct ringbuffer *rb, const uint8_t ch)
{
ASSERT(rb != NULL);
/* whether has enough space */
if (! ringbuffer_empty_space(rb))
return 0;
rb->buffer_ptr[rb->write_index] = ch;
/* flip mirror */
if (rb->write_index == rb->buffer_size - 1) {
rb->write_mirror = ~rb->write_mirror;
rb->write_index = 0;
} else {
rb->write_index++;
}
return 1;
}
/**
* put a character into ring buffer
*
* When the buffer is full, it will discard one old data.
*/
uint32_t ringbuffer_putchar_force(struct ringbuffer *rb, const uint8_t ch)
{
enum ringbuffer_state old_state;
ASSERT(rb != NULL);
old_state = ringbuffer_status(rb);
rb->buffer_ptr[rb->write_index] = ch;
/* flip mirror */
if (rb->write_index == rb->buffer_size-1)
{
rb->write_mirror = ~rb->write_mirror;
rb->write_index = 0;
if (old_state == RT_RINGBUFFER_FULL)
{
rb->read_mirror = ~rb->read_mirror;
rb->read_index = rb->write_index;
}
}
else
{
rb->write_index++;
if (old_state == RT_RINGBUFFER_FULL)
rb->read_index = rb->write_index;
}
return 1;
}
/**
* get a character from a ringbuffer
*/
uint32_t ringbuffer_getchar(struct ringbuffer *rb, uint8_t *ch)
{
ASSERT(rb != NULL);
/* ringbuffer is empty */
if (! ringbuffer_data_len(rb))
return 0;
/* put character */
*ch = rb->buffer_ptr[rb->read_index];
if (rb->read_index == rb->buffer_size-1)
{
rb->read_mirror = ~rb->read_mirror;
rb->read_index = 0;
}
else
{
rb->read_index++;
}
return 1;
}
void ringbuffer_flush(struct ringbuffer *rb)
{
ASSERT(rb != NULL);
/* initialize read and write index */
rb->read_mirror = rb->read_index = 0;
rb->write_mirror = rb->write_index = 0;
}
void ringbuffer_init(struct ringbuffer *rb,
uint8_t *pool,
int16_t size)
{
ASSERT(rb != NULL);
ASSERT(size > 0);
/* initialize read and write index */
rb->read_mirror = rb->read_index = 0;
rb->write_mirror = rb->write_index = 0;
/* set buffer pool and size */
rb->buffer_ptr = pool;
rb->buffer_size = size; //ALIGN_DOWN(size, ALIGN_SIZE);
}
| 25.695238 | 89 | 0.618112 | Itamare4 |
877969918d674c75ff14ee8e0bd12f2473d65237 | 1,643 | cpp | C++ | src/MemeGraphics/IndexBuffer.cpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | src/MemeGraphics/IndexBuffer.cpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | src/MemeGraphics/IndexBuffer.cpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | #include <MemeGraphics/IndexBuffer.hpp>
#include <MemeGraphics/OpenGL.hpp>
namespace ml
{
/* * * * * * * * * * * * * * * * * * * * */
IndexBuffer::IndexBuffer()
: IHandle (NULL)
, m_data (NULL)
, m_count (NULL)
, m_usage (GL::StaticDraw)
, m_type (GL::UnsignedInt)
{
}
IndexBuffer::IndexBuffer(const IndexBuffer & copy)
: IHandle (copy)
, m_data (copy.m_data)
, m_count (copy.m_count)
, m_usage (copy.m_usage)
, m_type (copy.m_type)
{
}
IndexBuffer::~IndexBuffer()
{
clean();
}
/* * * * * * * * * * * * * * * * * * * * */
IndexBuffer & IndexBuffer::clean()
{
if ((*this))
{
ML_GL.deleteBuffers(1, (*this));
}
return (*this);
}
IndexBuffer & IndexBuffer::create(GL::Usage usage, GL::Type type)
{
if (set_handle(ML_GL.genBuffers(1)))
{
m_usage = usage;
m_type = type;
}
return (*this);
}
/* * * * * * * * * * * * * * * * * * * * */
const IndexBuffer & IndexBuffer::bind() const
{
ML_GL.bindBuffer(GL::ElementArrayBuffer, (*this));
return (*this);
}
const IndexBuffer & IndexBuffer::unbind() const
{
ML_GL.bindBuffer(GL::ElementArrayBuffer, NULL);
return (*this);
}
/* * * * * * * * * * * * * * * * * * * * */
const IndexBuffer & IndexBuffer::bufferData(const List<uint32_t> & data) const
{
return bufferData(&data[0], (uint32_t)data.size());
}
const IndexBuffer & IndexBuffer::bufferData(const uint32_t * data, uint32_t count) const
{
m_data = data;
m_count = count;
ML_GL.bufferData(
GL::ElementArrayBuffer,
(m_count * sizeof(uint32_t)),
m_data,
m_usage);
return (*this);
}
/* * * * * * * * * * * * * * * * * * * * */
} | 18.670455 | 89 | 0.567864 | Gurman8r |
877db499e700e6495e5846c988e73903eaced9cd | 305 | cpp | C++ | lab4/src/countnegatives.cpp | Sinduja-S/Algorithm-Design-Lab | 9bd64ae42c574b91ca733bb108cd845c15fe3baf | [
"MIT"
] | 2 | 2020-04-17T05:26:11.000Z | 2020-05-09T12:27:07.000Z | lab4/src/countnegatives.cpp | sindu-sss/Algorithm-Design-Lab | 9bd64ae42c574b91ca733bb108cd845c15fe3baf | [
"MIT"
] | null | null | null | lab4/src/countnegatives.cpp | sindu-sss/Algorithm-Design-Lab | 9bd64ae42c574b91ca733bb108cd845c15fe3baf | [
"MIT"
] | 3 | 2020-04-02T12:50:10.000Z | 2021-03-27T05:01:22.000Z | #include <iostream>
using namespace std;
int countneg(int *a,int s,int e){
if(e==s){
if(a[e]<0)
return(1);
return(0);
}
else{
int z1,z2;
cout<<e;
cout<<s<<endl;
z1=countneg(a,s,(e+s)/2);
z2=countneg(a,(s+e)/2+1,e);
return(z1+z2);
}
} | 14.52381 | 33 | 0.472131 | Sinduja-S |
877fec58ed7c13622c1759d9146899aa20460ea9 | 427 | cpp | C++ | CodeBlocks1908/share/CodeBlocks/templates/wizard/fltk/files/main.cpp | BenjaminRenz/FirmwareTY71M | 55cff63f23c8d844341f4dbf58ce145f073567f6 | [
"MIT"
] | 9 | 2019-02-04T02:13:38.000Z | 2021-06-24T20:31:49.000Z | CodeBlocks1908/share/CodeBlocks/templates/wizard/fltk/files/main.cpp | userx14/FirmwareTY71M | 55cff63f23c8d844341f4dbf58ce145f073567f6 | [
"MIT"
] | null | null | null | CodeBlocks1908/share/CodeBlocks/templates/wizard/fltk/files/main.cpp | userx14/FirmwareTY71M | 55cff63f23c8d844341f4dbf58ce145f073567f6 | [
"MIT"
] | 1 | 2021-06-24T20:31:53.000Z | 2021-06-24T20:31:53.000Z | #include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
int main (int argc, char ** argv)
{
Fl_Window *window;
Fl_Box *box;
window = new Fl_Window (300, 180);
box = new Fl_Box (20, 40, 260, 100, "Hello World!");
box->box (FL_UP_BOX);
box->labelsize (36);
box->labelfont (FL_BOLD+FL_ITALIC);
box->labeltype (FL_SHADOW_LABEL);
window->end ();
window->show (argc, argv);
return(Fl::run());
}
| 19.409091 | 54 | 0.63466 | BenjaminRenz |
87836940c2798edb41ccb43175c5019e177b54b6 | 349 | cpp | C++ | src/KEngine/src/Common/Color.cpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 4 | 2019-04-09T13:03:11.000Z | 2021-01-27T04:58:29.000Z | src/KEngine/src/Common/Color.cpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 2 | 2017-02-06T03:48:45.000Z | 2020-08-31T01:30:10.000Z | src/KEngine/src/Common/Color.cpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 4 | 2020-06-28T08:19:53.000Z | 2020-06-28T16:30:19.000Z | #include "KEngine/Common/Color.hpp"
namespace ke
{
const Color Color::WHITE { 255, 255, 255, 255};
const Color Color::BLACK { 0, 0, 0, 255 };
const Color Color::RED { 255, 0, 0, 255 };
const Color Color::GREEN { 0, 255, 0, 255 };
const Color Color::BLUE { 0, 0, 255, 255 };
const Color Color::TRANSPARENT { 0, 0, 0, 0 };
} | 26.846154 | 51 | 0.595989 | yxbh |
878db0266024ff8c6088177de583c77696c6ef60 | 2,482 | cpp | C++ | CtCI/Chapter1/1.3.cpp | wqw547243068/DS_Algorithm | 6d4a9baeb3650a8f93308c7405c9483bac59e98b | [
"RSA-MD"
] | 2 | 2021-12-29T14:42:51.000Z | 2021-12-29T14:46:45.000Z | CtCI/Chapter1/1.3.cpp | wqw547243068/DS_Algorithm | 6d4a9baeb3650a8f93308c7405c9483bac59e98b | [
"RSA-MD"
] | null | null | null | CtCI/Chapter1/1.3.cpp | wqw547243068/DS_Algorithm | 6d4a9baeb3650a8f93308c7405c9483bac59e98b | [
"RSA-MD"
] | null | null | null | #include <iostream>
#include <cstring>
using namespace std;
string removeDuplicate1(string s)
{
int check = 0;
int len = s.length();
if(len < 2) return s;
string str = "";
for(int i=0; i<len; ++i)
{
int v = (int)(s[i]-'a');
if((check & (1<<v)) == 0)
{
str += s[i];
check |= (1<<v);
}
}
return str;
}
string removeDuplicate2(string s)
{
int len = s.length();
if(len < 2) return s;
string str = "";
for(int i=0; i<len; ++i)
{
if(s[i] != '\0')
{
str += s[i];
for(int j=i+1; j<len; ++j)
if(s[j]==s[i])
s[j] = '\0';
}
}
return str;
}
void removeDuplicate3(char s[])
{
int len = strlen(s);
if(len < 2) return;
int p = 0;
for(int i=0; i<len; ++i)
{
if(s[i] != '\0')
{
s[p++] = s[i];
for(int j=i+1; j<len; ++j)
if(s[j]==s[i])
s[j] = '\0';
}
}
s[p] = '\0';
}
void removeDuplicate4(char s[])
{
int len = strlen(s);
if(len < 2) return;
bool c[256];
memset(c, 0, sizeof(c));
int p = 0;
for(int i=0; i<len; ++i)
{
if(!c[s[i]])
{
s[p++] = s[i];
c[s[i]] = true;
}
}
s[p] = '\0';
}
void removeDuplicate5(char s[])
{
int len = strlen(s);
if(len < 2) return;
int check = 0, p = 0;
for(int i=0; i<len; ++i)
{
int v = (int)(s[i]-'a');
if((check & (1<<v))==0)
{
s[p++] = s[i];
check |= (1<<v);
}
}
s[p] = '\0';
}
int main()
{
string s1 = "abcde";
string s2 = "aaabbb";
string s3 = "";
string s4 = "abababc";
string s5 = "ccccc";
cout<<removeDuplicate1(s1)<<" "<<removeDuplicate2(s1)<<endl;
cout<<removeDuplicate1(s2)<<" "<<removeDuplicate2(s2)<<endl;
cout<<removeDuplicate1(s3)<<" "<<removeDuplicate2(s3)<<endl;
cout<<removeDuplicate1(s4)<<" "<<removeDuplicate2(s4)<<endl;
cout<<removeDuplicate1(s5)<<" "<<removeDuplicate2(s5)<<endl;
char ss1[] = "abcde";
char ss2[] = "aaabbb";
char ss3[] = "";
char ss4[] = "abababc";
char ss5[] = "ccccc";
removeDuplicate5(ss1);
removeDuplicate5(ss2);
removeDuplicate5(ss3);
removeDuplicate5(ss4);
removeDuplicate5(ss5);
cout<<ss1<<" "<<ss2<<" "<<ss3<<" "<<ss4<<" "<<ss5<<endl;
return 0;
}
| 21.033898 | 64 | 0.43755 | wqw547243068 |
878ff952ba31c6ca43afaed0936051ecd81610c8 | 2,388 | hpp | C++ | src/models/Mesh.hpp | sophia-x/RayTracing | 1092971b08ff17e8642e408e2cb0c518d6591e2b | [
"MIT"
] | 1 | 2016-05-05T10:20:45.000Z | 2016-05-05T10:20:45.000Z | src/models/Mesh.hpp | sophia-x/RayTracing | 1092971b08ff17e8642e408e2cb0c518d6591e2b | [
"MIT"
] | null | null | null | src/models/Mesh.hpp | sophia-x/RayTracing | 1092971b08ff17e8642e408e2cb0c518d6591e2b | [
"MIT"
] | null | null | null | #ifndef MESH
#define MESH
#include "Model.hpp"
#include "Triangle.hpp"
#include "../common.hpp"
class Mesh : public Model {
private:
vector<Triangle> __tris;
vector<vec3> __vertices;
vector<vec3> __model_verticles;
vector<vec2> __uvs;
public:
Mesh(const char *file_name, const Material &material):
Model(material) {
loadObj(file_name);
buildModel();
}
Mesh(const vector<vec3> &vertices, const vector<int> &tri_idx, const Material &material):
Model(material), __vertices(vertices) {
size_t size = tri_idx.size() / 3;
__tris.reserve(size);
for (size_t i = 0; i < size; i++) {
__tris.push_back(Triangle(__vertices[tri_idx[3 * i]], __vertices[tri_idx[3 * i + 1]], __vertices[tri_idx[3 * i + 2]], __hash_code, __material));
}
buildModel();
}
Mesh(const vector<vec3> &vertices, const vector<vec2> &uvs, const vector<int> &tri_idx, const Material &material):
Model(material), __vertices(vertices), __uvs(uvs) {
size_t size = tri_idx.size() / 3;
__tris.reserve(size);
for (size_t i = 0; i < size; i++) {
__tris.push_back(Triangle(__vertices[tri_idx[3 * i]], __vertices[tri_idx[3 * i + 1]], __vertices[tri_idx[3 * i + 2]], __uvs[tri_idx[3 * i]], __uvs[tri_idx[3 * i + 1]], __uvs[tri_idx[3 * i + 2]], __hash_code, __material));
}
buildModel();
}
void transform(const mat4 &transform_matrix) {
for (size_t i = 0; i < __vertices.size(); i ++) {
__vertices[i] = vec3(transform_matrix * vec4(__model_verticles[i], 1));
}
for (auto tri = __tris.begin(); tri != __tris.end(); tri++)
tri->update();
}
inline void addPrimitives(vector<Primitive *> &primitives) {
for (size_t i = 0; i < __tris.size(); i++)
primitives.push_back(&(__tris[i]));
}
private:
void loadObj(const char* file_name);
void buildModel() {
vec3 mean(0), max_p(numeric_limits<float>::min()), min_p(numeric_limits<float>::max());
for (size_t i = 0; i < __vertices.size(); i++) {
mean += __vertices[i];
max_p = max(max_p, __vertices[i]);
min_p = min(min_p, __vertices[i]);
}
mean /= float(__vertices.size());
vec3 m = max(abs(max_p - mean), abs(min_p - mean));
__model_verticles.reserve(__vertices.size());
for (size_t i = 0; i < __vertices.size(); i ++) {
vec3 p = __vertices[i] - mean;
for (int j = 0; j < 3; j ++) {
if (m[j] >= EPSILON) {
p[j] /= m[j];
}
}
__model_verticles.push_back(p);
}
}
};
#endif | 28.428571 | 224 | 0.643216 | sophia-x |
87926192a988cd4db786867eb9a8df26601c7619 | 16,021 | cc | C++ | src/model/mem_sampler.cc | delorean-sim/gem5 | 0c02c1d7efb781680eb5817730440832af3d5587 | [
"BSD-3-Clause"
] | null | null | null | src/model/mem_sampler.cc | delorean-sim/gem5 | 0c02c1d7efb781680eb5817730440832af3d5587 | [
"BSD-3-Clause"
] | null | null | null | src/model/mem_sampler.cc | delorean-sim/gem5 | 0c02c1d7efb781680eb5817730440832af3d5587 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2012-2019 Nikos Nikoleris
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nikos Nikoleris
*/
#include "model/mem_sampler.hh"
#include <fstream>
#include <functional>
#include <string>
#include "arch/utility.hh"
#include "base/compiler.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "cpu/simple_thread.hh"
#include "cpu/thread_context.hh"
#include "debug/MemSampler.hh"
#include "debug/MemSamplerDebug.hh"
#include "model/statcache.hh"
#include "params/MemSampler.hh"
#include "sim/system.hh"
MemSampler::MemSampler(const MemSamplerParams *p)
: SimObject(p),
kvmWatchpoints(p->system),
blockSize(p->blockSize),
vicinityWindowSize(p->windowSize),
targetedAccessMinReuseInst(20000),
excludeKernel(true)
{
std::random_device rd;
rng.seed(rd());
}
void
MemSampler::observeLoad(ThreadContext *tc, Addr inst_addr, Addr phys_addr,
Addr virt_addr, int size)
{
if (!TheISA::inUserMode(tc) && excludeKernel) {
return;
}
recordReuse(inst_addr, virt_addr, phys_addr, size);
if (nextLoadSample == loadCtr) {
sampleAccess(inst_addr, virt_addr, phys_addr, size);
if (sampledLoadsInBatch < batchSize) {
sampledLoadsInBatch++;
nextLoadSample++;
}
}
if (nextLoadSample <= loadCtr) {
sampledLoadsInBatch = 0;
if (samplingEnabled) {
nextLoadSample += nextSample();
} else {
nextLoadSample = (uint64_t)-1;
}
DPRINTF(MemSampler, "Next load sample %d\n", nextLoadSample);
}
}
void
MemSampler::observeStore(ThreadContext *tc, Addr inst_addr, Addr phys_addr,
Addr virt_addr, int size)
{
if (!TheISA::inUserMode(tc) && excludeKernel) {
return;
}
recordReuse(inst_addr, virt_addr, phys_addr, size);
if (nextStoreSample == storeCtr) {
sampleAccess(inst_addr, virt_addr, phys_addr, size);
if (sampledStoresInBatch < batchSize) {
sampledStoresInBatch++;
nextStoreSample++;
}
}
if (nextStoreSample <= storeCtr) {
sampledStoresInBatch = 0;
if (samplingEnabled) {
nextStoreSample += nextSample();
} else {
nextStoreSample = (uint64_t)-1;
}
DPRINTF(MemSampler, "Next store sample %d\n", nextStoreSample);
}
}
void
MemSampler::sampleAccess(Addr inst_addr, Addr virt_addr,
Addr phys_addr, Addr size)
{
AccessSample ac;
ac.instAddr = inst_addr;
ac.effAddr = virt_addr;
ac.effPhysAddr = phys_addr;
ac.size = size;
ac.mtime = memInstCtr;
ac.itime = instCtr;
ac.weight = samplingPeriod;
ac.targeted = false;
ac.random = true;
DPRINTF(MemSampler, "Sampling access: (%d/%d): access: %#llx "
"(+%d) by %#x\n", instCtr, memInstCtr, ac.effPhysAddr,
ac.size, ac.instAddr);
sampleAccess(ac);
}
void
MemSampler::sampleAccess(const AccessSample ac)
{
const Addr blk_phys_addr = roundDown(ac.effPhysAddr, blockSize);
auto ret = watchpoints.emplace(blk_phys_addr, ac);
if (!ret.second) {
// there was already a targeted watchpoint and we happened to
// randomly sample the same block
auto &wp = ret.first;
AccessSample &old_ac = wp->second;
assert(old_ac.targeted || ac.targeted);
old_ac.random = old_ac.targeted = true;
}
kvmWatchpoints.insert(blk_phys_addr);
}
void
MemSampler::recordReuse(Addr inst_addr, Addr virt_addr, Addr phys_addr,
Addr size)
{
const Addr blk_phys_addr = roundDown(phys_addr, blockSize);
auto it = watchpoints.find(blk_phys_addr);
if (it == watchpoints.end()) {
return;
}
AccessSample &ac1 = it->second;
MemoryReuse reuse;
reuse.begin = ac1;
AccessSample &ac2 = reuse.end;
ac2.instAddr = inst_addr;
ac2.effAddr = virt_addr;
ac2.effPhysAddr = phys_addr;
ac2.size = size;
ac2.mtime = memInstCtr;
ac2.itime = instCtr;
const Tick rdist = memInstCtr - ac1.mtime;
// At this point, this could be a targeted access or the reuse of
// a randomly choosen instruction or both
if (ac1.random) {
DPRINTF(MemSampler, "Recording smpl reuse - addr: %#llx "
"pc: %#llx inst count: %llu rdist %llu\n", blk_phys_addr,
inst_addr, instCtr, rdist);
numSampledReuses++;
sampledReuses.push_back(reuse);
ac1.random = false;
}
auto wp = targetedAccesses.find(blk_phys_addr);
assert(!ac1.targeted || wp != targetedAccesses.end());
if (ac1.targeted) {
TargetedAccess &acc = wp->second;
numTargetedWatchpointHits++;
if (virt_addr == acc.effAddr && phys_addr == acc.effPhysAddr &&
inst_addr == acc.instAddr && size == acc.size) {
// only if there is a match in a couple of properties we
// record this
const Tick rdist_inst = instCtr - ac1.itime;
// if this is the first time, we observed this access or
// it reuse is small than we expected, we skip it
if (ac1.mtime != -1 && rdist_inst > targetedAccessMinReuseInst) {
DPRINTF(MemSampler, "Recording tgt reuse - addr: %#llx "
"pc: %#llx inst count: %llu rdist: %llu\n",
blk_phys_addr, inst_addr, instCtr, rdist);
numTargetedReuses++;
targetedReuses.push_back(reuse);
acc.count++;
acc.itime = instCtr;
acc.dist = memInstCtr - ac1.mtime;
}
}
ac1 = ac2;
ac1.targeted = true;
} else {
// if this is not a targeted access, we don't need the
// watchpoint any more
watchpoints.erase(it);
kvmWatchpoints.remove(phys_addr);
}
}
void
MemSampler::stage()
{
assert(stagedTargetedAccesses.empty());
std::swap(targetedAccesses, stagedTargetedAccesses);
stagedTime = instCtr;
for (const auto &reuse: stagedTargetedAccesses) {
TargetedAccess acc = reuse.second;
const Addr blk_phys_addr = roundDown(acc.effPhysAddr, blockSize);
DPRINTF(MemSampler, "Staging access %#x\n", acc.effPhysAddr);
auto it = watchpoints.find(blk_phys_addr);
assert(it != watchpoints.end());
AccessSample &as = it->second;
assert(as.targeted);
as.targeted = false;
if (!as.random) {
watchpoints.erase(it);
kvmWatchpoints.remove(blk_phys_addr);
}
}
assert(targetedAccesses.empty());
for (const auto &wp: watchpoints) {
const AccessSample &as = wp.second;
assert(!as.targeted);
}
}
void
MemSampler::loadAccesses(const char *ifile)
{
assert(targetedAccesses.empty());
std::fstream input(ifile, std::ios::in | std::ios::binary);
panic_if(!input, "File not found: %s\n", ifile);
ProtoReuseProfile::Accesses pAccesses;
panic_if(!pAccesses.ParseFromIstream(&input),
"Failed to parse file: %s\n", ifile);
for (unsigned i = 0; i < pAccesses.accesses_size(); i++) {
const ProtoReuseProfile::Access &pAccess = pAccesses.accesses(i);
TargetedAccess tgt_acc;
tgt_acc.instAddr = pAccess.pc();
tgt_acc.effAddr = pAccess.addr();
tgt_acc.effPhysAddr = pAccess.physaddr();
tgt_acc.size = pAccess.size();
tgt_acc.count = 0;
tgt_acc.dist = 0;
const Addr blk_phys_addr = roundDown(tgt_acc.effPhysAddr, blockSize);
auto ret M5_VAR_USED = targetedAccesses.emplace(blk_phys_addr,
tgt_acc);
assert(ret.second);
AccessSample smpl_acc;
smpl_acc.instAddr = pAccess.pc();
smpl_acc.effAddr = pAccess.addr();
smpl_acc.effPhysAddr = pAccess.physaddr();
smpl_acc.size = pAccess.size();
smpl_acc.targeted = true;
smpl_acc.random = false;
smpl_acc.mtime = -1;
DPRINTF(MemSampler, "Loading key access: %#llx (+%d) by %#x\n",
smpl_acc.effPhysAddr, smpl_acc.size, smpl_acc.instAddr);
sampleAccess(smpl_acc);
kvmWatchpoints.enable(smpl_acc.effPhysAddr);
}
numTargetedAccesses += pAccesses.accesses_size();
google::protobuf::ShutdownProtobufLibrary();
}
Vicinity
MemSampler::populateVicinity(Tick itime)
{
Vicinity vicinity(vicinityWindowSize);
vicinity.reset();
// Traverse recorded reuse samples and populate the vicinity
// histogram and a per-instruction bounded buffer with reuse
// samples
auto rit = sampledReuses.begin();
while (rit != sampledReuses.end()) {
const MemoryReuse &reuse = *rit;
if (reuse.begin.itime < itime) {
Tick rdist = reuse.end.mtime - reuse.begin.mtime;
vicinity.addReuse(reuse.begin.mtime, reuse.end.mtime,
reuse.begin.weight);
DPRINTF(MemSampler, "Adding reuse to vicinity: %llu (w:%llu) - "
"from pc: %#llx time: %#llu, to pc: %#llx time: %#llu\n",
rdist, reuse.begin.weight, reuse.begin.instAddr,
reuse.begin.mtime, reuse.end.instAddr, reuse.end.mtime);
rit = sampledReuses.erase(rit);
} else {
rit++;
}
}
// Add pending watchpoints in the vicinity histogram as infinite
// reuses, danglings.
auto wit = watchpoints.begin();
while (wit != watchpoints.end()) {
const AccessSample as = wit->second;
if (as.itime < itime) {
assert(!as.targeted);
DPRINTF(MemSampler, "Adding dangling to vicinity: inf (w: %%llu) "
"- from pc: %#llx time: %#llu\n", as.instAddr, as.mtime);
vicinity.addDangling(as.mtime, as.weight);
wit = watchpoints.erase(wit);
kvmWatchpoints.remove(as.effPhysAddr);
} else {
wit++;
}
}
return vicinity;
}
void
MemSampler::save(const char *reuse_file, const char *accesses_file)
{
Vicinity vicinity = populateVicinity(stagedTime);
ProtoReuseProfile::ReuseProfile reuseProfile;
vicinity.save(reuseProfile);
ProtoReuseProfile::Accesses pAccesses;
bool dump_key_accesses = false;
for (const auto &reuse: stagedTargetedAccesses) {
TargetedAccess acc = reuse.second;
ProtoReuseProfile::Access *pAccess;
if (!acc.count) {
dump_key_accesses = true;
DPRINTF(MemSampler, "Key access not found (i:%llu): "
"%#llx (%#llx) by %#llx\n", acc.itime,
acc.effAddr, acc.effPhysAddr, acc.instAddr);
pAccess = pAccesses.add_accesses();
} else {
DPRINTF(MemSampler, "Saving access (i:%llu): %d "
"%#llx (%#llx) by %#llx\n", acc.itime,
acc.dist, acc.effAddr, acc.effPhysAddr, acc.instAddr);
pAccess = reuseProfile.add_accesses();
pAccess->set_dist(acc.dist);
}
pAccess->set_pc(acc.instAddr);
pAccess->set_addr(acc.effAddr);
pAccess->set_physaddr(acc.effPhysAddr);
pAccess->set_size(acc.size);
}
stagedTargetedAccesses.clear();
if (reuse_file) {
DPRINTF(MemSampler, "Dumping collected reuses until %d to: %s\n",
stagedTime, reuse_file);
using namespace std;
fstream output(reuse_file, ios::out | ios::trunc | ios::binary);
panic_if(!reuseProfile.SerializeToOstream(&output),
"Failed to write %s.", reuse_file);
}
if (accesses_file && dump_key_accesses) {
DPRINTF(MemSampler, "Dumping remaining key accesses to: %s\n",
accesses_file);
using namespace std;
fstream output(accesses_file, ios::out | ios::trunc | ios::binary);
panic_if(!pAccesses.SerializeToOstream(&output),
"Failed to write %s.", accesses_file);
}
google::protobuf::ShutdownProtobufLibrary();
}
void
MemSampler::setSamplingPeriod(long period, int size)
{
DPRINTF(MemSampler, "Changing parameters: period %lld size: %d\n",
period, size);
if (size == 0) {
samplingEnabled = false;
return;
}
samplingPeriod = period;
batchSize = size;
double lambda = 1. / samplingPeriod;
expDistr = std::exponential_distribution<double>(lambda);
if (!samplingEnabled) {
nextLoadSample = loadCtr + nextSample();
nextStoreSample = storeCtr + nextSample();
samplingEnabled = true;
DPRINTF(MemSampler, "Enabling sampling next - load: %d store: %d\n",
nextLoadSample, nextStoreSample);
}
}
void
MemSampler::regStats()
{
SimObject::regStats();
using namespace Stats;
numRandomSamples
.name(name() + ".random_samples")
.desc("Number of times a random sample was taken")
;
numTargetedAccesses
.name(name() + ".targeted_accesses")
.desc("Number of accesses that we targeted")
;
numSampledReuses
.name(name() + ".sampled_reuses")
.desc("Number of reuses we sampled")
;
numTargetedReuses
.name(name() + ".targeted_reuses")
.desc("Number of targeted reuses we obtained")
;
numTargetedWatchpointHits
.name(name() + ".targeted_watchpoint_hits")
.desc("Number of time a targeted watchpoint was triggered")
;
numMissedSamplesLoad
.name(name() + ".missed_samples_load")
.desc("Number of missed samples - load")
;
numMissedSamplesStore
.name(name() + ".missed_samples_store")
.desc("Number of missed samples - store")
;
kvmWatchpoints.regStats();
}
MemSampler*
MemSamplerParams::create()
{
return new MemSampler(this);
}
| 32.629328 | 78 | 0.628051 | delorean-sim |
87947efc4974a50c8e689fb07952009ffe8ef12f | 1,925 | cpp | C++ | foo_cover_resizer/ContextMenuUtils.cpp | marc2k3/fb2k-component | 1dcdfd489eefc3a392d2ff4d0fb5133aa6636e73 | [
"MIT"
] | 7 | 2021-10-05T02:13:08.000Z | 2022-03-29T15:17:37.000Z | foo_cover_resizer/ContextMenuUtils.cpp | marc2k3/fb2k-component | 1dcdfd489eefc3a392d2ff4d0fb5133aa6636e73 | [
"MIT"
] | 2 | 2022-03-11T04:49:10.000Z | 2022-03-17T00:13:04.000Z | foo_cover_resizer/ContextMenuUtils.cpp | marc2k3/fb2k-component | 1dcdfd489eefc3a392d2ff4d0fb5133aa6636e73 | [
"MIT"
] | null | null | null | #include "stdafx.h"
using namespace resizer;
static const std::vector<ContextItem> context_items =
{
{ &guid_context_command_convert, "Convert front covers to JPG without resizng" },
{ &guid_context_command_remove_all_except_front, "Remove all except front" },
};
class ContextMenuUtils : public contextmenu_item_simple
{
public:
GUID get_item_guid(uint32_t index) override
{
return *context_items[index].guid;
}
GUID get_parent() override
{
return guid_context_group_utils;
}
bool context_get_display(uint32_t index, metadb_handle_list_cref handles, pfc::string_base& out, uint32_t& displayflags, const GUID& caller) override
{
get_item_name(index, out);
return true;
}
bool get_item_description(uint32_t index, pfc::string_base& out) override
{
get_item_name(index, out);
return true;
}
uint32_t get_num_items() override
{
return context_items.size();
}
void context_command(uint32_t index, metadb_handle_list_cref handles, const GUID& caller) override
{
const HWND hwnd = core_api::get_main_window();
if (index == 0)
{
if (MessageBoxW(hwnd, L"This option will ignore any images that are already JPG. Continue?", string_wide_from_utf8_fast(group_utils), MB_ICONWARNING | MB_SETFOREGROUND | MB_YESNO) == IDYES)
{
auto cb = fb2k::service_new<CoverResizer>(handles, true);
threaded_process::get()->run_modeless(cb, threaded_process_flags, hwnd, "Converting front covers to JPG...");
}
}
else if (index == 1)
{
auto cb = fb2k::service_new<CoverRemover>(handles);
threaded_process::get()->run_modeless(cb, threaded_process_flags, hwnd, "Removing covers...");
}
}
void get_item_name(uint32_t index, pfc::string_base& out) override
{
out = context_items[index].name;
}
};
static contextmenu_group_popup_factory g_context_group_utils(guid_context_group_utils, contextmenu_groups::root, group_utils, 1);
FB2K_SERVICE_FACTORY(ContextMenuUtils);
| 28.308824 | 192 | 0.753766 | marc2k3 |
8797e5ee50a22e5af0a19ef86a3311b1661a95b3 | 3,173 | cpp | C++ | modules/trivia/cmd_achievements.cpp | brainboxdotcc/triviabot | d074256f38a002bfb9d352c4f80bc45f19a71384 | [
"Apache-2.0"
] | 23 | 2020-06-28T18:07:03.000Z | 2022-03-02T20:12:47.000Z | modules/trivia/cmd_achievements.cpp | brainboxdotcc/triviabot | d074256f38a002bfb9d352c4f80bc45f19a71384 | [
"Apache-2.0"
] | 4 | 2020-10-08T13:37:39.000Z | 2022-03-26T22:41:19.000Z | modules/trivia/cmd_achievements.cpp | brainboxdotcc/triviabot | d074256f38a002bfb9d352c4f80bc45f19a71384 | [
"Apache-2.0"
] | 13 | 2020-10-08T13:32:02.000Z | 2021-12-02T00:00:28.000Z | /************************************************************************************
*
* TriviaBot, The trivia bot for discord based on Fruitloopy Trivia for ChatSpike IRC
*
* Copyright 2004 Craig Edwards <support@brainbox.cc>
*
* Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019.
*
* 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 <dpp/dpp.h>
#include <fmt/format.h>
#include <sporks/modules.h>
#include <sporks/regex.h>
#include <string>
#include <cstdint>
#include <fstream>
#include <streambuf>
#include <sporks/stringops.h>
#include <sporks/statusfield.h>
#include <sporks/database.h>
#include <dpp/nlohmann/json.hpp>
#include "state.h"
#include "trivia.h"
#include "webrequest.h"
#include "commands.h"
using json = nlohmann::json;
command_achievements_t::command_achievements_t(class TriviaModule* _creator, const std::string &_base_command, bool adm, const std::string& descr, std::vector<dpp::command_option> options) : command_t(_creator, _base_command, adm, descr, options) { }
void command_achievements_t::call(const in_cmd &cmd, std::stringstream &tokens, guild_settings_t &settings, const std::string &username, bool is_moderator, dpp::channel* c, dpp::user* user)
{
dpp::snowflake user_id = 0;
tokens >> user_id;
if (!user_id) {
user_id = cmd.author_id;
}
uint32_t unlock_count = from_string<uint32_t>(db::query("SELECT COUNT(*) AS unlocked FROM achievements WHERE user_id = ?", {user_id})[0]["unlocked"], std::dec);
std::string trophies = fmt::format(_("ACHCOUNT", settings), unlock_count, creator->achievements->size() - unlock_count) + "\n";
std::vector<field_t> fields;
for (auto& showoff : *(creator->achievements)) {
db::resultset inf = db::query("SELECT *, date_format(unlocked, '%d-%b-%Y') AS unlocked_friendly FROM achievements WHERE user_id = ? AND achievement_id = ?", {user_id, showoff["id"].get<uint32_t>()});
if (inf.size()) {
fields.push_back({
"<:" + showoff["image"].get<std::string>() + ":" + showoff["emoji_unlocked"].get<std::string>() + "> - " + _(showoff["name"].get<std::string>(), settings),
_(showoff["desc"].get<std::string>(), settings) + " (*" + inf[0]["unlocked_friendly"] + "*)\n<:blank:667278047006949386>",
false
});
}
}
creator->EmbedWithFields(
cmd.interaction_token, cmd.command_id, settings,
_("TROPHYCABINET", settings), fields, cmd.channel_id,
"https://triviabot.co.uk/", "", "",
"<:blank:667278047006949386>\n" + trophies + "<:blank:667278047006949386>"
);
creator->CacheUser(cmd.author_id, cmd.user, cmd.member, cmd.channel_id);
}
| 40.679487 | 250 | 0.670974 | brainboxdotcc |
879a470fc5bf0aebafbd40975363b09fa0725bd3 | 479 | cpp | C++ | src/A/A6B84.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | src/A/A6B84.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | src/A/A6B84.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define ll long long
#define ld long double
using namespace std;
bool prime(int n){
int m=sqrt(n);
for(int i=2;i<=m;i++){
if(n%i==0) return false;
}
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
ll n,q=1;
while(cin>>n){
if(n==0) return 0;
else{
if(n<=3) ;
ll i=sqrt(n)*2+10;
while(i*(i-3)/2>n) i-=100;
if(i<0) i=1;
while(i*(i-3)/2<n) i++;
cout<<"Case "<<q<<": "<<i<<endl;
q++;
}
}
return 0;
}
| 15.451613 | 35 | 0.542797 | wlhcode |
879bb074afd41eb3c778443b83ee7f18ddd99b5b | 770 | cc | C++ | apose.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | apose.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | apose.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | #include "imgutils.hh"
#include "strutils.hh"
#include "partrait.hh"
#include "parson.hh"
#include "catalog.hh"
#include "autoposer.hh"
using namespace makemore;
using namespace std;
int main(int argc, char **argv) {
assert(argc > 0);
Catalog cat(argv[1]);
Autoposer ap("fineposer.proj");
for (auto fn : cat.fn) {
Partrait par;
par.load(fn);
Triangle mark;
mark.p = Point(192, 240);
mark.q = Point(320, 240);
mark.r = Point(256, 384);
par.set_mark(mark);
ap.autopose(&par);
ap.autopose(&par);
Pose pose = par.get_pose();
par.set_tag("angle", pose.angle);
par.set_tag("stretch", pose.stretch);
par.set_tag("skew", pose.skew);
par.save(fn);
fprintf(stderr, "%s\n", fn.c_str());
}
return 0;
}
| 19.25 | 41 | 0.619481 | jdb19937 |
879cf099e1424416d9da9c5c94647ab57d86a769 | 5,575 | cpp | C++ | runtime/tests/test_message_priority.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | 1 | 2021-09-03T10:22:04.000Z | 2021-09-03T10:22:04.000Z | runtime/tests/test_message_priority.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | runtime/tests/test_message_priority.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | #include <config.h>
#include <boost/config.hpp>
#include "am++/am++.hpp"
#include <iostream>
#include <pthread.h>
#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#define TRANSPORT_HEADER <am++/BOOST_JOIN(TRANSPORT, _transport).hpp>
#include TRANSPORT_HEADER
#include <time.h>
#include <sys/time.h>
#define DISABLE_SELF_SEND_CHECK
typedef double time_type;
// copies directly from europar_tests
inline time_type get_time()
{
return MPI_Wtime();
#if 0
timeval tp;
gettimeofday(&tp, 0);
return tp.tv_sec + tp.tv_usec / 1000000.0;
#endif
}
time_type non_priority_time = 0;
time_type priority_time = 0;
time_type time_at_start = 0;
struct message_priority_handler {
typedef amplusplus::message_type<int> tm_type;
tm_type& tm;
amplusplus::transport& trans;
message_priority_handler(tm_type& tm, amplusplus::transport& t): tm(tm), trans(t) { std::cerr << "Constructor" << std::endl; }
void operator()(int source, const int* buf, int count) const {
// std::cout << "My rank is " << trans.rank() << " Messag is from rank " << source << std::endl;
for (int i = 0; i < count; ++i) {
// std::cout << "The message content - " << buf[i] << std::endl;
if (buf[i] % 2 == 0) {
non_priority_time = get_time(); // even - non priority message
} else {
priority_time = get_time(); // odd - priority message
}
}
}
};
struct empty_deleter {
typedef void result_type;
void operator()() const {}
template <typename T> void operator()(const T&) const {}
};
#define MSG_SIZE 10000
struct msg_send_args {
amplusplus::transport& trans;
amplusplus::message_type<int>& tm;
amplusplus::message_type<int>& priority_tm;
bool coalesced;
int start;
boost::barrier& barier;
msg_send_args(amplusplus::transport& t, amplusplus::message_type<int>& mt, amplusplus::message_type<int>& priority_m, bool c, int st,
boost::barrier& cur_barier):
trans(t), tm(mt), priority_tm(priority_m), coalesced(c), start(st), barier(cur_barier) {}
};
void *send_normal_messages(void *arguments) {
struct msg_send_args *args = (struct msg_send_args *)arguments;
amplusplus::transport& trans = args->trans;
amplusplus::message_type<int> tm = args->tm;
amplusplus::message_type<int> priority_tm = args->priority_tm;
if (!(args->coalesced)) {
// wait till both threads reach here
args->barier.wait();
// message sending must be within an epoch
amplusplus::scoped_epoch epoch(trans);
{
if (trans.rank() == 0) {
// boost::shared_ptr<int> msg = boost::make_shared<int>(0);
for(int j=0; j<MSG_SIZE; ++j) {
tm.message_being_built(1);
priority_tm.message_being_built(1);
tm.send(&j, 1, 1, empty_deleter()); // even - non priority
++j;
priority_tm.send(&j, 1, 1, empty_deleter()); //odd - priority
}
}
}
} else {
// TODO
}
return NULL;
}
void run_test(amplusplus::environment& env) {
std::cout << "Inside run test" << std::endl;
amplusplus::transport trans = env.create_transport();
std::cout << "Transport size " << trans.size() << std::endl;
BOOST_ASSERT (trans.size() == 2);
// sending normal messages
amplusplus::message_type<int> tm = trans.create_message_type<int>();
tm.set_max_count(1);
tm.set_handler(message_priority_handler(tm, trans));
// sending priority messages
amplusplus::message_type<int> ptm = trans.create_message_type<int>(1);
ptm.set_max_count(1);
ptm.set_handler(message_priority_handler(ptm, trans));
bool coalesced = false;
// create the barier for 2 threads
boost::barrier bar(2);
struct msg_send_args args(trans,tm, ptm, coalesced, 0, bar);
// struct msg_send_args pargs(trans,ptm, coalesced, MSG_SIZE);
if (trans.rank() == 0) {
// set number of threads to 2
trans.set_nthreads(2);
// { amplusplus::scoped_epoch epoch(trans); }
// create threads
pthread_t normal_thread, priority_thread;
int ret = 0;
// create thread to send priority messages
ret = pthread_create(&priority_thread, NULL, send_normal_messages, (void*)&args);
if(ret) {
std::cerr << "ERROR - Error creating the normal thread. Error code - " << ret << std::endl;
return;
}
// create thread to send non priority messages
ret = pthread_create(&normal_thread, NULL, send_normal_messages, (void*)&args);
if(ret) {
std::cerr << "ERROR - Error creating the normal thread. Error code - " << ret << std::endl;
return;
}
// wait till threads finishes
pthread_join(normal_thread, NULL);
pthread_join(priority_thread, NULL);
trans.set_nthreads(1);
std::cout << "Finish sending messages ..." << std::endl;
} else {
// do nothing, but need epoch for termination detection
amplusplus::scoped_epoch epoch(trans);
// register handler for the message types
}
{ amplusplus::scoped_epoch epoch(trans); }
if (trans.rank() == 1) {
non_priority_time = non_priority_time - time_at_start;
priority_time = priority_time - time_at_start;
std::cout << "The priority time - " << priority_time << " non-priority time - " << non_priority_time << std::endl;
// for rank 1 - we should be receiving priority messages before non priority messages
std::cout << "The difference - " << non_priority_time - priority_time << " the ratio - " << non_priority_time / priority_time << std::endl;
BOOST_ASSERT(priority_time < non_priority_time * 0.99);
}
}
int main(int argc, char** argv) {
std::cout << "Main starting ..." << std::endl;
amplusplus::environment env = amplusplus::mpi_environment(argc, argv, false, 1, 10000);
time_at_start = get_time();
run_test(env);
}
| 28.589744 | 142 | 0.686816 | thejkane |
87a65939b208840ff4e2d1558aa4447830597e51 | 1,528 | cpp | C++ | codeforces/4d.mysterious-present/4d.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | 3 | 2018-01-19T14:09:23.000Z | 2018-02-01T00:40:55.000Z | codeforces/4d.mysterious-present/4d.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | null | null | null | codeforces/4d.mysterious-present/4d.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#define X first
#define Y second
using namespace std;
const int MAX_N = 5e3 + 123;
typedef pair <int, int> point;
typedef pair <point, int> tp;
vector <tp> vec;
point dp[MAX_N];
vector <int> result;
bool CMP(tp a, tp b)
{
if ((long long) a.X.X * (long long) a.X.Y == (long long) b.X.X * (long long) b.X.Y)
return a.X.X < b.X.X;
return (long long) a.X.X * (long long) a.X.Y < (long long) b.X.X * (long long) b.X.Y;
}
int main()
{
int n, x0, y0;
cin >> n >> x0 >> y0;
for(int i=0; i<n; i++)
{
point inp;
cin >> inp.X >> inp.Y;
if (inp.X > x0 && inp.Y > y0)
vec.push_back(make_pair(inp, i));
}
sort(vec.begin(), vec.end(), CMP);
for(int i=0; i<vec.size(); i++)
{
dp[vec[i].Y] = make_pair (1, -1);
for(int j=0; j<i; j++)
{
if (vec[j].X.X < vec[i].X.X && vec[j].X.Y < vec[i].X.Y)
if (dp[vec[j].Y].X + 1 > dp[vec[i].Y].X)
dp[vec[i].Y] = make_pair (dp[vec[j].Y].X + 1, vec[j].Y);
}
}
// cerr << endl << "\t Test data :" << endl;
// for(int i=0; i<vec.size(); i++)
// cerr << i << ": " << vec[i].Y << " " << vec[i].X.X << " " << vec[i].X.Y << " sz : " << dp[vec[i].Y].X << " par : " << dp[vec[i].Y].Y << endl;
int _mx = max_element(dp, dp+MAX_N) - dp;
int pos = _mx;
while(pos != -1 && dp[_mx].X)
{
result.push_back(pos + 1);
pos = dp[pos].Y;
}
reverse(result.begin(), result.end());
cout << result.size() << endl;
for(int i=0; i<result.size(); i++)
cout << result[i] << " ";
cout << endl;
return 0;
}
| 22.144928 | 150 | 0.521597 | KayvanMazaheri |
87ab3ef53b136b43f93bdec284d6f777eb097868 | 1,546 | cpp | C++ | cpp/codeforces/educational/educational_108/C.cpp | nirvanarsc/CompetitiveProgramming | 218ae447bbf7455e4953e05220418b7c32ee6b0e | [
"MIT"
] | 2 | 2021-06-02T16:11:46.000Z | 2021-12-23T20:37:02.000Z | cpp/codeforces/educational/educational_108/C.cpp | nirvanarsc/CompetitiveProgramming | 218ae447bbf7455e4953e05220418b7c32ee6b0e | [
"MIT"
] | null | null | null | cpp/codeforces/educational/educational_108/C.cpp | nirvanarsc/CompetitiveProgramming | 218ae447bbf7455e4953e05220418b7c32ee6b0e | [
"MIT"
] | 1 | 2021-05-14T14:19:14.000Z | 2021-05-14T14:19:14.000Z | #include <bits/stdc++.h>
#define fast_io \
ios::sync_with_stdio(false); \
cin.tie(nullptr);
using ll = long long;
using namespace std;
signed main() {
fast_io;
int t;
cin >> t;
for (int test = 0; test < t; test++) {
int n;
cin >> n;
int u[n];
int s[n];
vector<vector<int>> g(n);
for (int i = 0; i < n; i++) {
cin >> u[i];
u[i]--;
}
for (int i = 0; i < n; i++) {
cin >> s[i];
g[u[i]].push_back(s[i]);
}
unordered_map<int, vector<ll>> map;
unordered_map<int, vector<ll>> pre;
for (int i = 0; i < n; i++) {
if (g[i].size() > 0) {
sort(g[i].begin(), g[i].end());
reverse(g[i].begin(), g[i].end());
if (!map.count(g[i].size())) {
map[g[i].size()] = vector<ll>(g[i].size());
}
for (int j = 0; j < g[i].size(); j++) {
map[g[i].size()][j] += g[i][j];
}
}
}
int maxL = 0;
for (auto it = map.begin(); it != map.end(); ++it) {
maxL = max(maxL, it->first);
pre[it->first] = vector<ll>(it->first + 1);
for (int j = 1; j <= it->second.size(); j++) {
pre[it->first][j] = pre[it->first][j - 1] + it->second[j - 1];
}
}
ll* res = (ll*)(calloc(n, sizeof(ll)));
for (int L = 1; L <= maxL; L++) {
for (auto it = map.begin(); it != map.end(); ++it) {
res[L - 1] += pre[it->first][it->first - (it->first % L)];
}
}
for (int i = 0; i < n; i++) {
cout << res[i] << " ";
}
cout << "\n";
}
}
| 25.766667 | 70 | 0.42238 | nirvanarsc |
87b00527361099dbefaf8c7d6af3ef6c27afb5ca | 289 | cpp | C++ | src/PontoPartida.cpp | leohmcs/AVANTStation | f1f635b2f4ec9ffcb010660f4b5c91eb9d5fa190 | [
"Apache-2.0"
] | null | null | null | src/PontoPartida.cpp | leohmcs/AVANTStation | f1f635b2f4ec9ffcb010660f4b5c91eb9d5fa190 | [
"Apache-2.0"
] | null | null | null | src/PontoPartida.cpp | leohmcs/AVANTStation | f1f635b2f4ec9ffcb010660f4b5c91eb9d5fa190 | [
"Apache-2.0"
] | 1 | 2020-12-10T03:39:05.000Z | 2020-12-10T03:39:05.000Z | #include "PontoPartida.h"
PontoPartida::PontoPartida()
{
}
PontoPartida::PontoPartida(double lat, double lon)
{
setInitialPoint(Point(lat, lon, 0));
}
void PontoPartida::setApproxPoint(double lat, double lon, double h)
{
setApproxPoint(Point(lat, lon, h));
}
| 13.761905 | 68 | 0.67128 | leohmcs |
87bd38ac62a9ade0f356e5a2bd38846420462e42 | 3,524 | cpp | C++ | getnum/widget.cpp | upcMvc/-BankQueuingSystem | 6eaec760f61430cb3a49692453b444982299e45f | [
"MIT"
] | 2 | 2016-07-20T02:23:51.000Z | 2017-09-02T09:44:52.000Z | getnum/widget.cpp | upcMvc/bank-queue-system | 6eaec760f61430cb3a49692453b444982299e45f | [
"MIT"
] | null | null | null | getnum/widget.cpp | upcMvc/bank-queue-system | 6eaec760f61430cb3a49692453b444982299e45f | [
"MIT"
] | null | null | null | #include "widget.h"
#include "ui_widget.h"
#include "close.h"
#include <QLabel>
#include <QString>
#include <QByteArray>
#include <QtNetwork>
#include <QDebug>
#include <QCloseEvent>
#include <QEvent>
#include <QPalette>
#include <QBrush>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QPalette palette;
palette.setBrush(this->backgroundRole(),QBrush(QPixmap("../img/zx.jpg"))); //括号内为图片的相对目录
this->setPalette(palette);
sender=new QUdpSocket(this);
receiver=new QUdpSocket(this);
receiver->bind(45454,QUdpSocket::ShareAddress);
connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
//时间表
QTimer *timer=new QTimer(this);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(time()));
timer->start(500);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked(){
//向服务器发送信息
QByteArray datagram="a";
sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress("172.19.43.206"),45454);
}
void Widget::on_pushButton_2_clicked(){
//向服务器发送信息
QByteArray datagram="b";
sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress("172.19.43.206"),45454);
}
void Widget::time(){
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd");
ui->label_5->setText(str);
}
void Widget::processPendingDatagram(){
//等待数据
QByteArray datagram;
while(receiver->hasPendingDatagrams()){
datagram.resize(receiver->pendingDatagramSize());
//接受数据,存到datagram中
receiver->readDatagram(datagram.data(),datagram.size());
}
//将QByteArray转换成Qstring
QString string;
QString str0;
string = QString(datagram);
str0=string.section(",",0,0);
if("c"==str0){
QString str1=string.section(',',1,1);
QString str2=string.section(',',2,2);
ui->label->setText("普通客户您好,您前面有"+str1+"位普通客户,有"+str2+"位VIP用户");
ui->label_2->setText("vip客户您好,您前面有"+str2+"人在排队");
}
if("e"==str0){
QString str1=string.section(',',1,1);
QString str2=string.section(',',2,2);
QString str3=string.section(',',3,3);
ui->label->setText("普通客户您好,您前面有"+str2+"位普通客户,有"+str3+"位VIP用户");
ui->label_2->setText("vip客户您好,您前面有"+str3+"人在排队");
ui->lineEdit->setText("取号成功,您的号码是"+str1+"号");
}
if("x"==str0){
QString str1=string.section(',',1,1);
QString str2=string.section(',',2,2);
QString str3=string.section(',',3,3);
ui->label->setText("普通客户您好,您前面有"+str2+"位普通客户,有"+str3+"位VIP用户");
ui->label_2->setText("vip客户您好,您前面有"+str3+"人在排队");
ui->lineEdit_2->setText("取号成功,您的号码是"+str1+"号");
}
if("h"==str0){
QString str1=string.section(',',1,1);
QString str2=string.section(',',2,2);
QString str3=string.section(',',3,3);
if("0"==str3){
ui->textEdit->moveCursor(QTextCursor::Start);
ui->textEdit->insertPlainText("请普通用户"+str1+"号到"+str2+"号柜台办理业务\n");
}
else{
ui->textEdit->moveCursor(QTextCursor::Start);
ui->textEdit->insertPlainText("请VIP用户"+str1+"号到"+str2+"号柜台办理业务\n");
}
}
}
void Widget::closeEvent(QCloseEvent *event)
{
Close *close = new Close(this);
close->setModal(true);
close->exec();
if (close->flag == 1)
{
event->accept();
}
else
{
event->ignore();
}
}
| 26.103704 | 95 | 0.612372 | upcMvc |
87c0621d5a6a4dee4187e1f88ea212826847bdf8 | 4,094 | cpp | C++ | glfw3_app/common/mdf/surface.cpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | 9 | 2015-09-22T21:36:57.000Z | 2021-04-01T09:16:53.000Z | glfw3_app/common/mdf/surface.cpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | null | null | null | glfw3_app/common/mdf/surface.cpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | 2 | 2019-02-21T04:22:13.000Z | 2021-03-02T17:24:32.000Z | //=====================================================================//
/*! @file
@brief サーフェース・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include "mdf/surface.hpp"
namespace mdf {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 球を描画
@param[in] radius 半径
@param[in] lats 分割数
@param[in] longs 分割数
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
void draw_sphere(float radius, int lats, int longs)
{
for(int i = 0; i <= lats; ++i) {
float lat0 = vtx::get_pi<float>() * (-0.5f + static_cast<float>(i - 1) / lats);
float z0 = radius * std::sin(lat0);
float zr0 = radius * std::cos(lat0);
float lat1 = vtx::get_pi<float>() * (-0.5f + static_cast<float>(i) / lats);
float z1 = radius * std::sin(lat1);
float zr1 = radius * std::cos(lat1);
glBegin(GL_QUAD_STRIP);
for(int j = 0; j <= longs; ++j) {
float lng = 2 * vtx::get_pi<float>() * static_cast<float>(j - 1) / longs;
float x = std::cos(lng);
float y = std::sin(lng);
glNormal3f(x * zr1, y * zr1, z1);
glVertex3f(x * zr1, y * zr1, z1);
glNormal3f(x * zr0, y * zr0, z0);
glVertex3f(x * zr0, y * zr0, z0);
}
glEnd();
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief シリンダーを描画
@param[in] radius_org 半径(開始)
@param[in] radius_end 半径(終点)
@param[in] length 長さ
@param[in] lats 分割数
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
void draw_cylinder(float radius_org, float radius_len, float length, int lats)
{
int divide = 12;
float a = 0.0f;
float d = 2.0f * vtx::get_pi<float>() / static_cast<float>(divide);
glBegin(GL_TRIANGLE_STRIP);
for(int i = 0; i < divide; ++i) {
float x = std::sin(a);
float y = std::cos(a);
a += d;
glVertex3f(x * radius_org, 0.0f, y * radius_org);
glVertex3f(x * radius_len, length, y * radius_len);
}
{
a = 0.0f;
float x = std::sin(a);
float y = std::cos(a);
glVertex3f(x * radius_org, 0.0f, y * radius_org);
glVertex3f(x * radius_len, length, y * radius_len);
}
glEnd();
}
#if 0
void surface::destroy_vertex_()
{
if(vertex_id_) {
glDeleteBuffers(1, &vertex_id_);
vertex_id_ = 0;
}
}
void surface::destroy_element_()
{
if(!elements_.empty()) {
glDeleteBuffers(elements_.size(), &elements_[0]);
elements_.clear();
}
}
//-----------------------------------------------------------------//
/*!
@brief 頂点を開始
@param[in] n 頂点数を指定する場合指定
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool surface::begin_vertex(uint32_t n)
{
destroy_vertex_();
glGenBuffers(1, &vertex_id_);
if(n) {
vertexes_.reserve(n);
}
vertexes_.clear();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 頂点を追加
@param[in] n 数を指定する場合
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool surface::add_vertex(const vertex& v)
{
vertexes_.push_back(v);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 頂点を終了
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool surface::end_vertex()
{
glBindBuffer(GL_ARRAY_BUFFER, vertex_id_);
glBufferData(GL_ARRAY_BUFFER, vertexes_.size() * sizeof(vertex),
&vertexes_[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
vertexes tmp;
tmp.swap(vertexes_);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
@param[in] h ハンドル(0なら全てをレンダリング)
*/
//-----------------------------------------------------------------//
void surface::render(handle h)
{
if(h == 0) {
} else if((h - 1) < elements_.size()) {
}
}
#endif
}
| 23.94152 | 82 | 0.462384 | hirakuni45 |
87c60c367286d35a99d44dc732aecb69676271e3 | 216,697 | cpp | C++ | MMOCoreORB/src/server/zone/managers/sui/SuiManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/managers/sui/SuiManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/managers/sui/SuiManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
Copyright <SWGEmu>
See file COPYING for copying conditions. */
#include "SuiManager.h"
#include "server/zone/ZoneProcessServer.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/sui/SuiWindowType.h"
#include "server/zone/objects/player/sui/banktransferbox/SuiBankTransferBox.h"
#include "server/zone/objects/player/sui/characterbuilderbox/SuiCharacterBuilderBox.h"
#include "server/zone/objects/player/sui/transferbox/SuiTransferBox.h"
#include "server/zone/objects/creature/commands/UnconsentCommand.h"
#include "server/zone/managers/skill/SkillManager.h"
#include "server/zone/objects/player/sui/listbox/SuiListBox.h"
#include "server/zone/objects/player/sui/inputbox/SuiInputBox.h"
#include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/minigames/FishingManager.h"
#include "server/zone/objects/player/sui/keypadbox/SuiKeypadBox.h"
#include "server/zone/objects/player/sui/callbacks/LuaSuiCallback.h"
#include "server/zone/objects/tangible/terminal/characterbuilder/CharacterBuilderTerminal.h"
#include "templates/params/creature/CreatureAttribute.h"
#include "templates/params/creature/CreatureState.h"
#include "server/zone/objects/tangible/deed/eventperk/EventPerkDeed.h"
#include "server/zone/objects/tangible/eventperk/Jukebox.h"
#include "server/zone/objects/tangible/eventperk/ShuttleBeacon.h"
#include "server/zone/objects/player/sui/SuiBoxPage.h"
#include "server/zone/managers/loot/LootManager.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/managers/skill/SkillManager.h"
#include "server/zone/managers/player/PlayerManager.h"
#include "server/zone/packets/player/PlayMusicMessage.h"
#include "server/zone/managers/creature/CreatureManager.h"
#include "server/zone/objects/region/CityRegion.h"
#include "server/zone/ZoneServer.h"
#include "server/chat/ChatManager.h"
#include "server/zone/objects/tangible/components/vendor/VendorDataComponent.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "server/zone/managers/auction/AuctionManager.h"
#include "server/zone/managers/auction/AuctionsMap.h"
#include "server/zone/managers/statistics/StatisticsManager.h"
#include "server/zone/objects/mission/MissionTypes.h"
SuiManager::SuiManager() : Logger("SuiManager") {
server = nullptr;
setGlobalLogging(true);
setLogging(false);
}
void SuiManager::handleSuiEventNotification(uint32 boxID, CreatureObject* player, uint32 eventIndex, Vector<UnicodeString>* args) {
uint16 windowType = (uint16) boxID;
Locker _lock(player);
ManagedReference<PlayerObject*> ghost = player->getPlayerObject();
if (ghost == nullptr)
return;
ManagedReference<SuiBox*> suiBox = ghost->getSuiBox(boxID);
if (suiBox == nullptr)
return;
//Remove the box from the player, callback can readd it to the player if needed.
ghost->removeSuiBox(boxID);
suiBox->clearOptions(); //TODO: Eventually SuiBox needs to be cleaned up to not need this.
Reference<SuiCallback*> callback = suiBox->getCallback();
if (callback != nullptr) {
Reference<LuaSuiCallback*> luaCallback = cast<LuaSuiCallback*>(callback.get());
if (luaCallback != nullptr && suiBox->isSuiBoxPage()) {
Reference<SuiBoxPage*> boxPage = cast<SuiBoxPage*>(suiBox.get());
if (boxPage != nullptr) {
Reference<SuiPageData*> pageData = boxPage->getSuiPageData();
if (pageData != nullptr) {
try {
Reference<SuiCommand*> suiCommand = pageData->getCommand(eventIndex);
if (suiCommand != nullptr && suiCommand->getCommandType() == SuiCommand::SCT_subscribeToEvent) {
StringTokenizer callbackString(suiCommand->getNarrowParameter(2));
callbackString.setDelimeter(":");
String luaPlay = "";
String luaCall = "";
callbackString.getStringToken(luaPlay);
callbackString.getStringToken(luaCall);
callback = new LuaSuiCallback(player->getZoneServer(), luaPlay, luaCall);
}
} catch(Exception& e) {
error(e.getMessage());
}
}
}
}
callback->run(player, suiBox, eventIndex, args);
return;
}
StringBuffer msg;
msg << "Unknown message callback with SuiWindowType: " << hex << windowType << ". Falling back on old handler system.";
//info(msg, true);
switch (windowType) {
case SuiWindowType::DANCING_START:
handleStartDancing(player, suiBox, eventIndex, args);
break;
case SuiWindowType::DANCING_CHANGE:
handleStartDancing(player, suiBox, eventIndex, args);
break;
case SuiWindowType::MUSIC_START:
handleStartMusic(player, suiBox, eventIndex, args);
break;
case SuiWindowType::MUSIC_CHANGE:
handleStartMusic(player, suiBox, eventIndex, args);
break;
case SuiWindowType::BAND_START:
handleStartMusic(player, suiBox, eventIndex, args);
break;
case SuiWindowType::BAND_CHANGE:
handleStartMusic(player, suiBox, eventIndex, args);
break;
case SuiWindowType::BANK_TRANSFER:
handleBankTransfer(player, suiBox, eventIndex, args);
break;
case SuiWindowType::FISHING:
handleFishingAction(player, suiBox, eventIndex, args);
break;
case SuiWindowType::CHARACTER_BUILDER_LIST:
handleCharacterBuilderSelectItem(player, suiBox, eventIndex, args);
break;
case SuiWindowType::OBJECT_NAME:
handleSetObjectName(player, suiBox, eventIndex, args);
break;
}
}
void SuiManager::handleSetObjectName(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
if (!suiBox->isInputBox() || cancel != 0)
return;
ManagedReference<SceneObject*> object = suiBox->getUsingObject().get();
if (object == nullptr)
return;
if (args->size() < 1)
return;
UnicodeString objectName = args->get(0);
object->setCustomObjectName(objectName, true);
if (object->isSignObject()) {
StringIdChatParameter params("@player_structure:prose_sign_name_updated"); //Sign name successfully updated to '%TO'.
params.setTO(objectName);
player->sendSystemMessage(params);
}
}
void SuiManager::handleStartDancing(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
if (!suiBox->isListBox() || cancel != 0)
return;
if (args->size() < 2)
return;
int index = Integer::valueOf(args->get(0).toString());
uint32 id = suiBox->getBoxID();
bool change = (uint16)id == SuiWindowType::DANCING_CHANGE;
SuiListBox* listBox = cast<SuiListBox*>( suiBox);
if (index == -1)
return;
String dance = listBox->getMenuItemName(index);
if (!change)
player->executeObjectControllerAction(STRING_HASHCODE("startdance"), 0, dance);
else
player->executeObjectControllerAction(STRING_HASHCODE("changedance"), 0, dance);
}
void SuiManager::handleStartMusic(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
if (!suiBox->isListBox() || cancel != 0)
return;
if (args->size() < 2)
return;
int index = Integer::valueOf(args->get(0).toString());
uint32 id = suiBox->getBoxID();
SuiListBox* listBox = cast<SuiListBox*>( suiBox);
if (index == -1)
return;
String dance = listBox->getMenuItemName(index);
switch ((uint16)id) {
case SuiWindowType::MUSIC_START:
player->executeObjectControllerAction(STRING_HASHCODE("startmusic"), player->getTargetID(), dance);
break;
case SuiWindowType::MUSIC_CHANGE:
player->executeObjectControllerAction(STRING_HASHCODE("changemusic"), player->getTargetID(), dance);
break;
case SuiWindowType::BAND_CHANGE:
player->executeObjectControllerAction(STRING_HASHCODE("changebandmusic"), player->getTargetID(), dance);
break;
case SuiWindowType::BAND_START:
player->executeObjectControllerAction(STRING_HASHCODE("startband"), player->getTargetID(), dance);
break;
}
}
void SuiManager::handleBankTransfer(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
if (!suiBox->isBankTransferBox() || cancel != 0)
return;
if (args->size() < 2)
return;
int cash = Integer::valueOf(args->get(0).toString());
int bank = Integer::valueOf(args->get(1).toString());
SuiBankTransferBox* suiBank = cast<SuiBankTransferBox*>( suiBox);
ManagedReference<SceneObject*> bankObject = suiBank->getBank();
if (bankObject == nullptr)
return;
if (!player->isInRange(bankObject, 5))
return;
uint32 currentCash = player->getCashCredits();
uint32 currentBank = player->getBankCredits();
if ((currentCash + currentBank) == ((uint32) cash + (uint32) bank)) {
player->setCashCredits(cash);
player->setBankCredits(bank);
}
}
void SuiManager::handleFishingAction(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
if (cancel != 0)
return;
if (args->size() < 1)
return;
int index = Integer::valueOf(args->get(0).toString());
FishingManager* manager = server->getFishingManager();
manager->setNextAction(player, index + 1);
uint32 newBoxID = 0;
switch (index + 1) {
case FishingManager::TUGUP:
newBoxID = manager->createWindow(player, suiBox->getBoxID());
break;
case FishingManager::TUGRIGHT:
newBoxID = manager->createWindow(player, suiBox->getBoxID());
break;
case FishingManager::TUGLEFT:
newBoxID = manager->createWindow(player, suiBox->getBoxID());
break;
case FishingManager::REEL:
newBoxID = manager->createWindow(player, suiBox->getBoxID());
break;
case FishingManager::STOPFISHING:
player->sendSystemMessage("@fishing:stop_fishing"); //You reel-in your line and stop fishing...
manager->stopFishing(player, suiBox->getBoxID(), true);
return;
break;
default:
newBoxID = manager->createWindow(player, suiBox->getBoxID());
break;
}
manager->setFishBoxID(player, suiBox->getBoxID());
}
void SuiManager::handleCharacterBuilderSelectItem(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
if (!ConfigManager::instance()->getCharacterBuilderEnabled())
return;
ZoneServer* zserv = player->getZoneServer();
if (args->size() < 1)
return;
bool otherPressed = false;
int index = 0;
if(args->size() > 1) {
otherPressed = Bool::valueOf(args->get(0).toString());
index = Integer::valueOf(args->get(1).toString());
} else {
index = Integer::valueOf(args->get(0).toString());
}
if (!suiBox->isCharacterBuilderBox())
return;
ManagedReference<SuiCharacterBuilderBox*> cbSui = cast<SuiCharacterBuilderBox*>( suiBox);
CharacterBuilderMenuNode* currentNode = cbSui->getCurrentNode();
PlayerObject* ghost = player->getPlayerObject();
//If cancel was pressed then we kill the box/menu.
if (cancel != 0 || ghost == nullptr)
return;
//Back was pressed. Send the node above it.
if (otherPressed) {
CharacterBuilderMenuNode* parentNode = currentNode->getParentNode();
if(parentNode == nullptr)
return;
cbSui->setCurrentNode(parentNode);
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
return;
}
CharacterBuilderMenuNode* node = currentNode->getChildNodeAt(index);
//Node doesn't exist or the index was out of bounds. Should probably resend the menu here.
if (node == nullptr) {
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
return;
}
if (node->hasChildNodes()) {
//If it has child nodes, display them.
cbSui->setCurrentNode(node);
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
} else {
ManagedReference<SceneObject*> scob = cbSui->getUsingObject().get();
if (scob == nullptr)
return;
CharacterBuilderTerminal* bluefrog = scob.castTo<CharacterBuilderTerminal*>();
if (bluefrog == nullptr)
return;
String templatePath = node->getTemplatePath();
if (templatePath.indexOf(".iff") < 0) { // Non-item selections
if (templatePath == "unlearn_all_skills") {
SkillManager::instance()->surrenderAllSkills(player, true, false);
player->sendSystemMessage("All skills unlearned.");
} else if (templatePath == "cleanse_character") {
if (!player->isInCombat()) {
player->sendSystemMessage("You have been cleansed from the signs of previous battles.");
for (int i = 0; i < 9; ++i) {
player->setWounds(i, 0);
}
player->setShockWounds(0);
} else {
player->sendSystemMessage("Not within combat.");
return;
}
} else if (templatePath == "fill_force_bar") {
if (ghost->isJedi()) {
if (!player->isInCombat()) {
player->sendSystemMessage("You force bar has been filled.");
ghost->setForcePower(ghost->getForcePowerMax(), true);
} else {
player->sendSystemMessage("Not within combat.");
}
}
} else if (templatePath == "reset_buffs") {
if (!player->isInCombat()) {
player->sendSystemMessage("Your buffs have been reset.");
player->clearBuffs(true, false);
ghost->setFoodFilling(0);
ghost->setDrinkFilling(0);
} else {
player->sendSystemMessage("Not within combat.");
return;
}
} else if (templatePath.beginsWith("crafting_apron_")) {
//"object/tangible/wearables/apron/apron_chef_s01.iff"
//"object/tangible/wearables/ithorian/apron_chef_jacket_s01_ith.iff"
ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
if (inventory == nullptr) {
return;
}
uint32 itemCrc = ( player->getSpecies() != CreatureObject::ITHORIAN ) ? 0x5DDC4E5D : 0x6C191FBB;
ManagedReference<WearableObject*> apron = zserv->createObject(itemCrc, 2).castTo<WearableObject*>();
if (apron == nullptr) {
player->sendSystemMessage("There was an error creating the requested item. Please report this issue.");
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
error("could not create frog crafting apron");
return;
}
Locker locker(apron);
apron->createChildObjects();
if (apron->isWearableObject()) {
apron->addMagicBit(false);
UnicodeString modName = "(General)";
apron->addSkillMod(SkillModManager::WEARABLE, "general_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "general_experimentation", 25);
if(templatePath == "crafting_apron_armorsmith") {
modName = "(Armorsmith)";
apron->addSkillMod(SkillModManager::WEARABLE, "armor_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "armor_experimentation", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "armor_repair", 25);
} else if(templatePath == "crafting_apron_weaponsmith") {
modName = "(Weaponsmith)";
apron->addSkillMod(SkillModManager::WEARABLE, "weapon_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "weapon_experimentation", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "weapon_repair", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "grenade_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "grenade_experimentation", 25);
} else if(templatePath == "crafting_apron_tailor") {
modName = "(Tailor)";
apron->addSkillMod(SkillModManager::WEARABLE, "clothing_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "clothing_experimentation", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "clothing_repair", 25);
} else if(templatePath == "crafting_apron_chef") {
modName = "(Chef)";
apron->addSkillMod(SkillModManager::WEARABLE, "food_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "food_experimentation", 25);
} else if(templatePath == "crafting_apron_architect") {
modName = "(Architect)";
apron->addSkillMod(SkillModManager::WEARABLE, "structure_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "structure_experimentation", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "structure_complexity", 25);
} else if(templatePath == "crafting_apron_droid_engineer") {
modName = "(Droid Engineer)";
apron->addSkillMod(SkillModManager::WEARABLE, "droid_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "droid_experimentation", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "droid_complexity", 25);
} else if(templatePath == "crafting_apron_doctor") {
modName = "(Doctor)";
apron->addSkillMod(SkillModManager::WEARABLE, "medicine_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "medicine_experimentation", 25);
} else if(templatePath == "crafting_apron_combat_medic") {
modName = "(Combat Medic)";
apron->addSkillMod(SkillModManager::WEARABLE, "combat_medicine_assembly", 25);
apron->addSkillMod(SkillModManager::WEARABLE, "combat_medicine_experimentation", 25);
}
UnicodeString apronName = "Crafting Apron " + modName;
apron->setCustomObjectName(apronName, false);
}
if (inventory->transferObject(apron, -1, true)) {
apron->sendTo(player, true);
} else {
apron->destroyObjectFromDatabase(true);
return;
}
StringIdChatParameter stringId;
stringId.setStringId("@faction_perk:bonus_base_name"); //You received a: %TO.
stringId.setTO(apron->getObjectID());
player->sendSystemMessage(stringId);
} else if (templatePath == "enhance_character") {
bluefrog->enhanceCharacter(player);
} else if (templatePath == "credits") {
player->addCashCredits(50000, true);
player->sendSystemMessage("You have received 50.000 Credits");
} else if (templatePath == "faction_rebel") {
ghost->increaseFactionStanding("rebel", 100000);
} else if (templatePath == "faction_imperial") {
ghost->increaseFactionStanding("imperial", 100000);
} else if (templatePath == "language") {
bluefrog->giveLanguages(player);
} else if (templatePath == "apply_all_dots") {
player->addDotState(player, CreatureState::POISONED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0);
player->addDotState(player, CreatureState::BLEEDING, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0);
player->addDotState(player, CreatureState::DISEASED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0);
player->addDotState(player, CreatureState::ONFIRE, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0, 20);
} else if (templatePath == "apply_poison_dot") {
player->addDotState(player, CreatureState::POISONED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0);
} else if (templatePath == "apply_bleed_dot") {
player->addDotState(player, CreatureState::BLEEDING, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0);
} else if (templatePath == "apply_disease_dot") {
player->addDotState(player, CreatureState::DISEASED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0);
} else if (templatePath == "apply_fire_dot") {
player->addDotState(player, CreatureState::ONFIRE, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0, 20);
} else if (templatePath == "clear_dots") {
player->clearDots();
} else if (templatePath == "frs_light_side") {
if (ghost->getJediState() < 4) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("FRS Light Jedi");
box->setPromptText("FRS Light Jedi Requires (Light Jedi Rank");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (ghost->getJediState() == 4) {
PlayerManager* pman = zserv->getPlayerManager();
pman->unlockFRSForTesting(player, 1);
}
} else if (templatePath == "frs_dark_side") {
if (ghost->getJediState() < 8) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("FRS Dark Jedi");
box->setPromptText("FRS Dark Jedi Requires (Dark Jedi Rank");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (ghost->getJediState() == 8) {
PlayerManager* pman = zserv->getPlayerManager();
pman->unlockFRSForTesting(player, 2);
}
} else if (templatePath == "color_crystals" || templatePath == "krayt_pearls") {
ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
if (inventory == nullptr)
return;
LootManager* lootManager = zserv->getLootManager();
lootManager->createLoot(inventory, templatePath, 300, true);
} else if (templatePath == "max_xp") {
ghost->maximizeExperience();
player->sendSystemMessage("You have maximized all xp types.");
//Gray Jedi Unlock Checks
} else if (templatePath == "jedi_Lives") {
if (ghost->getJediState() < 2) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Gray Jedi Unlock");
box->setPromptText("Gray Jedi Requires (Force Sensative)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (ghost->getJediState() >= 2 && player->getScreenPlayState("jedi_Lives") == 0) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
player->sendSystemMessage("You Have Unlocked Gray Jedi");
int livesLeft = player->getScreenPlayState("jediLives") + 3;
player->setScreenPlayState("jediLives", livesLeft);
int jediVis1 = ghost->getVisibility();
box->setPromptTitle("Gray Jedi Progress");
StringBuffer promptText;
String playerName = player->getFirstName();
promptText << "\\#00ff00 " << playerName << " Has " << "\\#000000 " << "(" << "\\#ffffff " << player->getScreenPlayState("jediLives") << "\\#000000 " << ")" << "\\#00ff00 " << " Gray Jedi Lives" << endl;
promptText << "\\#ffffff " << playerName << "\\#00ff00 Your Visibility is at: " << jediVis1;
box->setPromptText(promptText.toString());
ghost->addSuiBox(box);
player->sendMessage(box->generateMessage());
SkillManager* skillManager = server->getSkillManager();
SkillManager::instance()->awardSkill("combat_jedi_novice", player, true, true, true);
box->setForceCloseDistance(5.f);
}
//Player Stats
} else if (templatePath == "player_stats") {
PlayerObject* ghost = player->getPlayerObject();
StringBuffer msg;
msg << "---PvP Statistics---\n"
<< "PvP Rating: " << ghost->getPvpRating() << "\n"
<< "Total PvP Kills: " << ghost->getPvpKills() << "\n"
<< "Total PvP Deaths: " << ghost->getPvpDeaths() << "\n"
<< "Total Bounty Kills: " << ghost->getBountyKills() << "\n\n"
<< "---PvE Statistics---\n"
<< "Total PvE Kills: " << ghost->getPveKills() << "\n"
<< "Total PvE Deaths: " << ghost->getPveDeaths() << "\n"
<< "Total Boss Kills: " << ghost->getworldbossKills() << "\n\n"
<< "---Mission Statistics---\n"
<< "Total Missions Completed: " << ghost->getMissionsCompleted() << "\n\n"
<< "---Misc Statistics---\n"
<< "Event Attendance: " << ghost->geteventplayerCrate();
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::NONE);
box->setPromptTitle(player->getFirstName() + "'s" + " Character Statistics");
box->setPromptText(msg.toString());
ghost->addSuiBox(box);
player->sendMessage(box->generateMessage());
//Community Online Status
} else if (templatePath == "community_status") {
ManagedReference<PlayerObject*> ghost = player->getPlayerObject();
PlayerManager* playerManager = server->getZoneServer()->getPlayerManager();
StringBuffer body;
Time timestamp;
timestamp.updateToCurrentTime();
body << "-- Flurry Server --" << endl << endl;
body << "Connections Online: " << String::valueOf(player->getZoneServer()->getConnectionCount()) << endl;
body << "Most Concurrent (since last reset): " << String::valueOf(player->getZoneServer()->getMaxPlayers()) << endl;
body << "Server Cap: " << String::valueOf(player->getZoneServer()->getServerCap()) << endl << endl << endl;
body << "Deleted Characters (since last reset): " << String::valueOf(player->getZoneServer()->getDeletedPlayers()) << endl;
body << "Total Connections (since last reset): " << String::valueOf(player->getZoneServer()->getTotalPlayers()) << endl;
body << endl;endl;
body << "Missions info (since last reset): " << endl;
body << StatisticsManager::instance()->getStatistics() << endl;
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::NONE);
box->setPromptTitle("Flurry Community Status");
box->setPromptText(body.toString());
ghost->addSuiBox(box);
player->sendMessage(box->generateMessage());
//JediQuest Remove Screen Play Tester
} else if (templatePath == "jedi_quest_remove") {
if (!player->isInCombat() && player->getBankCredits() < 999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Jedi Quest");
box->setPromptText("Jedi Quest Requires 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
player->sendSystemMessage("Thank you for your credits.");
int questLeft = player->getScreenPlayState("jediQuest") - 1;
player->setScreenPlayState("jediQuest", questLeft);
int jediVis1 = ghost->getVisibility();
box->setPromptTitle("Jedi Quest Progress");
StringBuffer promptText;
String playerName = player->getFirstName();
promptText << "\\#00ff00 " << playerName << " Has " << "\\#000000 " << "(" << "\\#ffffff " << player->getScreenPlayState("jediQuest") << "\\#000000 " << ")" << "\\#00ff00 " << " Jedi Quest Progress" << endl;
promptText << "\\#ffffff " << playerName << "\\#00ff00 Your Visibility is at: " << jediVis1;
box->setPromptText(promptText.toString());
ghost->addSuiBox(box);
player->sendMessage(box->generateMessage());
player->subtractBankCredits(1000);
box->setForceCloseDistance(5.f);
}
//BOSS TELEPORT ROOM
} else if (templatePath == "teleportroom") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Boss Instance Teleport Room");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dungeon2", -33.6957, 0.77033, 24.5291, 14200816);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//GALACTIC TRAVEL SYSTEM City Politician Skill
} else if (templatePath == "citypolitician") {
if (!player->isInCombat() && player->getBankCredits() < 999999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Master Politician");
box->setPromptText("Master Politician Requires 1,000,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 999999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
player->sendSystemMessage("Thank you for your credits.");
SkillManager::instance()->awardSkill("social_politician_master", player, true, true, true);
player->subtractBankCredits(1000000);
box->setForceCloseDistance(5.f);
}
//GALACTIC TRAVEL SYSTEM Recalculate's Jedi's Force Pool
} else if (templatePath == "recalculateforce") {
if (!player->checkCooldownRecovery("force_recalculate_cooldown")) {
StringIdChatParameter stringId;
Time* cdTime = player->getCooldownTime("force_recalculate_cooldown");
int timeLeft = floor((float)cdTime->miliDifference() / 1000) *-1;
stringId.setStringId("@innate:equil_wait"); // You are still recovering from your last Command available in %DI seconds.
stringId.setDI(timeLeft);
player->sendSystemMessage(stringId);
error("Cooldown In Effect You May Not Recalculate Force: " + player->getFirstName());
return;
}
if (!player->isInCombat()) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
String playerName = player->getFirstName();
StringBuffer zBroadcast;
zBroadcast << "\\#00E604" << playerName << " \\#63C8F9 Has Recalculated Their Force Pool.";
SkillManager* skillManager = SkillManager::instance();
skillManager->awardForceFromSkills(player);
player->sendSystemMessage("Recalculated Max force and Regen");
player->playEffect("clienteffect/mus_relay_activate.cef", "");
player->addCooldown("force_recalculate_cooldown", 86400 * 1000);// 24 hour cooldown
player->getZoneServer()->getChatManager()->broadcastGalaxy(nullptr, zBroadcast.toString());
}
//GALACTIC TRAVEL SYSTEM Recalculate's Players Skills
} else if (templatePath == "recalculateskills") {
if (!player->checkCooldownRecovery("skill_recalculate_cooldown")) {
StringIdChatParameter stringId;
Time* cdTime = player->getCooldownTime("skill_recalculate_cooldown");
int timeLeft = floor((float)cdTime->miliDifference() / 1000) *-1;
stringId.setStringId("@innate:equil_wait"); // You are still recovering from your last Command available in %DI seconds.
stringId.setDI(timeLeft);
player->sendSystemMessage(stringId);
error("Cooldown In Effect You May Not Recalculate Skills: " + player->getFirstName());
return;
}
if (!player->isInCombat()) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
String playerName = player->getFirstName();
StringBuffer zBroadcast;
zBroadcast << "\\#00E604" << playerName << " \\#63C8F9 Has Recalculated Their Skills.";
SkillManager* skillManager = SkillManager::instance();
skillManager->awardResetSkills(player);
player->sendSystemMessage("Recalculated Skills");
player->playEffect("clienteffect/mus_relay_activate.cef", "");
player->addCooldown("skill_recalculate_cooldown", 86400 * 1000);// 24 hour cooldown
player->getZoneServer()->getChatManager()->broadcastGalaxy(nullptr, zBroadcast.toString());
}
//GALACTIC TRAVEL SYSTEM
//Corellia Travel
} else if (templatePath == "corellia_bela_vistal_a_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Bela Vistal Shuttleport A");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 6644.269, 330, -5922.5225);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "corellia_bela_vistal_b_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Bela Vistal Shuttleport B");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 6930.8042, 330, -5534.8936);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "corellia_coronet_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Coronet Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -66.760902, 28, -4711.3281);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "corellia_coronet_a_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Coronet Shuttle A");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -25.671804, 28, -4409.7847);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "corellia_coronet_b_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Coronet Shuttle B");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -329.76605, 28, -4641.23);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "doaba_guerfel_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Doaba Guerfel Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 3085.4963, 280, 4993.0098);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "doaba_guerfel_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Doaba Guerfel Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 3349.8933, 308, 5598.1362);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "kor_vella_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Kor Vella Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -3775.2546, 31, 3234.2202);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "kor_vella_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Kor Vella Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -3157.2834, 31, 2876.2029);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "tyrena_a_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Tyrena Shuttle A");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -5005.354, 21, -2386.9819);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "tyrena_b_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Tyrena Shuttle B");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -5600.6367, 21, -2790.7429);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "tyrena_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Tyrena Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -5003.0649, 21, -2228.3665);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "vreni_island_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Vreni Island Shuttle");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -5551.9473, 15.890146, -6059.9673);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "argilat_swamp_badge") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("POI Argilat Swamp Badge");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 1387, 30, 3749);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "bela_vistal_fountain_badge") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("POI Bela Vistal Fountain Badge");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 6767, 30, -5617);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "rebel_hideout_badge") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("POI Rebel Hideout");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -6530, 30, 5967);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "rogue_corsec_base_badge") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("POI Rogue Corsec Base Badge");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", 5291, 30, 1494);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "tyrena_theater_badge") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("POI Tyrena Theater Badge");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -5418, 30, -6248);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Dantooine Travels
} else if (templatePath == "dantooine_agro_outpost_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dantooine Agro Outpost Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", 1569.66, 4, -6415.7598);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "dantooine_imperial_outpost_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dantooine Imperial Outpost Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", -4208.6602, 3, -2350.24);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "dantooine_mining_outpost_startport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dantooine Mining Outpost Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", -635.96887, 3, 2507.0115);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Dathomir Travels
} else if (templatePath == "dathomir_trade_outpost_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dathomir Trade Outpost Starport ");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", 618.89258, 6.039608, 3092.0142);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "dathomir_science_outpost_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dathomir Science Outpost Starport ");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", -49.021923, 18, -1584.7278);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "dathomir_village_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dathomir Village Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", 5271.4, 0, -4119.53);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Lok Travels
} else if (templatePath == "nyms_stronghold_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Nym's Stronghold Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("lok", 478.92676, 9, 5511.9565);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Hoth Travels
} else if (templatePath == "scavenger_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Scavenger Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("hoth", 0, 0, -2000);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Yavin IV Travels
} else if (templatePath == "yavin_iv_imperial_outpost_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Yavin IV Imperial Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("yavin4", 4054.1, 37, -6216.9);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "yavin_iv_labor_outpost_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Yavin IV Labor Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("yavin4", -6921.6733, 73, -5726.5161);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "yavin_iv_mining_outpost_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Yavin IV Mining Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("yavin4", -269, 35, 4893);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Tatooine Travels
} else if (templatePath == "anchorhead_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Tatooine Anchorhead Shuttle");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 47.565128, 52, -5338.9072);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "bestine_shuttle_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Bestine Shuttle");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -1098.4836, 12, -3563.5342);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "bestine_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Bestine Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -1361.1917, 12, -3600.0254);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_eisley_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Eisley Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 3416.6914, 5, -4648.1411);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_entha_shuttle_a_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Entha Shuttle A");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 1730.8828, 7, 3184.6135);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_entha_shuttle_b_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Entha Shuttle B");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 1395.447, 7, 3467.0117);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_entha_spaceport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Entha Spaceport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 1266.0996, 7, 3065.1392);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_espa_shuttleport_east_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Espa Shuttle Port East");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -2803.511, 5, 2182.9648);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_espa_shuttleport_south_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Espa Shuttle Port South");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -2897.0933, 5, 1933.4144);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_espa_shuttleport_west_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Espa Shuttle Port West");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -3112.1296, 5, 2176.9607);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_espa_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Espa Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -2833.1609, 5, 2107.3787);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_eisley_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Eisley Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 3594, 5, -4778);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Talus Travels
} else if (templatePath == "talus_dearic_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Talus Dearic Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 699.297, 6, -3041.4199);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "talus_dearic_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Talus Dearic Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 263.58401, 6, -2952.1284);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "talus_nashal_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Talus Nashal Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 4334.5786, 9.8999996, 5431.0415);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "talus_imperial_outpost_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Talus Imprial Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", -2226, 20, 2319);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "talus_nashal_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Talus Imprial Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 4455, 2, 5356);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Naboo Travels
} else if (templatePath == "deeja_peak_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dee'ja Peak ShuttlePort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 5331.9375, 327.02765, -1576.6733);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "kaadar_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Kaadara ShuttlePort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 5123.3857, -192, 6616.0264);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "kaadara_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Kaadara StarPort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 5280.2002, -192, 6688.0498);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "keren_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Keren ShuttlePort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 2021.0026, 19, 2525.679);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "keren_shuttleport_south_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Karen ShuttlePort South");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 1567.5193, 25, 2837.8777);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "keren_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Keren Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 1371.5938, 13, 2747.9043);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "moenia_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Moenia StarPort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 4731.1743, 4.1700001, -4677.5439);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "the_lake_retreat_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("The Lake Retreat ShuttlePort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -5494.4224, -150, -21.837162);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "theed_shuttleport_a_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Theed ShuttlePort A");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -5856.1055, 6, 4172.1606);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "theed_shuttleport_b_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Theed ShuttlePort B");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -5005, 6, 4072);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "theed_shuttleport_c_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Theed ShuttlePort C");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -5411.0171, 6, 4322.3315);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "theed_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Theed Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -4858.834, 5.9483199, 4164.0679);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_kessel_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City - Kessel");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 7405, -196, 6200);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "moenia_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Moenia StarPort");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 4961, 3, -4898);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Rori Travels
} else if (templatePath == "narmel_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Narmle Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", -5255.4116, 80.664185, -2161.6274);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "narmel_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Narmle Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", -5374.0718, 80, -2188.6143);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "rebel_outpost_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Rebel Outpost Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", 3691.9023, 96, -6403.4404);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "restuss_shuttleport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Restuss Shuttleport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", 5210, 78, 5794);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "restuss_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Restuss Starport");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", 5340, 80, 5734);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Endor Travels
} else if (templatePath == "smuggler_outpost_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Endor Smuggler Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("endor", -950.59241, 73, 1553.4125);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "research_outpost_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Endor Research Outpost");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("endor", 3201.6599, 24, -3499.76);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Chandrila Travels
} else if (templatePath == "nayli_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Nayli Starpot");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("chandrila", -5271, 18, 265);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "hanna_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Hanna City Starpot");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("chandrila", 253, 6, -2937);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Hutta Travels
} else if (templatePath == "bilbousa_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Bilbousa Starpot");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("hutta", -765, 80, 1703);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Geonosis Travels
} else if (templatePath == "geonosis_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Geonosis Starpot");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("geonosis", 86, 5, -11);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
// Mandalore Travels
} else if (templatePath == "keldabe_starport_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Keldabe Starport");
box->setPromptText("Travel Cost 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("mandalore", 1568, 4, -6415);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Light Jedi Enclave
} else if (templatePath == "light_enclave_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Light Jedi Enclave");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("yavin4", -5575, 87, 4901);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Dark Jedi Enclave
} else if (templatePath == "dark_enclave_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Dark Jedi Enclave");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("yavin4", 5080, 79, 306);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Rori Restuss PVP Zone
} else if (templatePath == "restuss_pvp_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Restuss PvP Zone");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", 5297, 78, 6115);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//Player City Travels
} else if (templatePath == "pc_korrivan_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Korrivan");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -1644, 0, -5277);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_intas_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Intas Minor");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -2577, -196, 6027);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_caladan_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Caladan");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 6049, 6, -1218);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_hilltop_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Hill Top");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", -2859, 77, -5211);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_sundari_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Sundari");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("endor", -3947, 10, 3794);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_shadowfalls_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Shadow Falls");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -1474, 3, -3220);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_jantatown_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Janta Town");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", 6533, 1, -4294);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_serendipity_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Serendipity");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", -7116, 0, -3726);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_riverside_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Riverside");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("kashyyyk", 3300, 0, 2244);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_maka_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Make America Krayt Again");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", 6093, 52, 4307);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_darkness_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Darkness Falls");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", 3136, 77, -5953);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_bmh_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Bad Mutta Hutta");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("hutta", 2876, 108, 3923);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_indestine_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Indestine");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("hoth", -1847, 36, 3788);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_cyberdyne_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Cyberdyne");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", -5060, 78, -5015);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_lafayette_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Lafayette");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -6955, -196, 5360);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_skynet_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Skynet");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -4791, 22, 6402);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_crimson_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Crimson Throne");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("lok", -2996, 11, 6867);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_freedom_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("New Freedom");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("mandalore", 5733, 0, 876);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_malice_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Malice");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", 3480, 5, 3300);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_annamnesis_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Annamnesis" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("yavin4", -2253, 18, 6958);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_avalon_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Avalon Prime" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", -7004, 11, -3785);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_sanctus_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Sactus" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", -4556, 83, -4669);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_unrest_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Unrest" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", -5350, 90, -3587);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_oldwest_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("The Old West" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("mandalore", -7155, 3, -787);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_nerfherder_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Nerf Herder Central" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("taanab", 5129, 49, -4794);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_virdomus_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Vir Domus" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", -179, 20, -4180);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_littlechina_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Little China" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("tatooine", -377, 0, 3777);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "frs_floor") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("FRS Selection Floor" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dungeon2", 5994, 39, 0, 14200833);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "mos_potatoes") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Mos Potatoes" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("endor", -46, 207, 4767);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_binary_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Binary" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("lok", 1245, 0, 6603);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_asgard_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Asgard" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("geonosis", -28, 7, 1937);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_sparta_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Sparta" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", -3417, 122, 2684);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_purgatory_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Purgatory" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("endor", -3593, 200, 5764);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_sincity_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Sin city" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("taanab", -2225, 58, -501);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_nofate_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("No Fate" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", 6159, 75, 1625);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_serenity_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Serenity" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("lok", 3260, 12, -3912);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_banir_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Banir" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", 3179, 1, 5309);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_setec_astronomy_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Setec Astronomy" );
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("mandalore", -2022, 1, 2603);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_limes inferior_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Limes Inferior");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dathomir", 1985, 0, -4320);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_lowca island_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Lowca Island");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("corellia", -2019 , 8, -4392);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_solace_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Solace");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", -5499, 40, -4139);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_stewjon_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Stewjon");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("rori", 4241, 79, 5983);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_valinor_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Valinor");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("taanab", 6028, 10, 3724);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_flurrys haven_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Flurrys Haven");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 1995, -197, 6198);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_lost city_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Lost City");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("geonosis", -3476, 7, 1948);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_rebs_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Rebs of Hoth");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("hoth", -2654, 12, 4883);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_portrielig_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Port Rielig");
box->setPromptText("Travel Coast 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", 1950, 10, -6910);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_somov city_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Somov'Rit");
box->setPromptText("Travel Cost 5,000 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("geonosis", 600, 9, -1512);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity != nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_crymorenoobs_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Cry More Noobs");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 6397, 9, 2809);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_sanitarium_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Sanitarium");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("naboo", 4374, 7, 1528);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_newjustice_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City New Justice");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("lok", -6671, 11, -3516);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_laconia_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Laconia");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 315, 41, 330);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_phobos_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Phobos");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("geonosis", 5388, 6, -3956);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_infinite_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Infinite");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("dantooine", -529, 3, -2933);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
} else if (templatePath == "pc_tombstone_travel") {
if (!player->isInCombat() && player->getBankCredits() < 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Player City Tombstone");
box->setPromptText("Travel Cost 5,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 4999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
ManagedReference<CityRegion*> currentCity = player->getCityRegion().get();
player->sendSystemMessage("Thank you for your travels.");
player->switchZone("talus", 3900, 71, -2279);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
if(currentCity !=nullptr && !currentCity->isClientRegion()) {
Locker clocker(currentCity, player);
currentCity->addToCityTreasury(1000);
}
}
//GRAY JEDI HOLOCRON QUEST END CHAPTER
} else if (templatePath == "switch_normal_loadout") {
if (!player->isInCombat() && player->getBankCredits() < 99) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Normal Player Loadout");
box->setPromptText("Costume Coast 100 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 99) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
player->sendSystemMessage("You are now swtiching back to your normal loadout , soft logging your character will fully cloth you again , you can also unequipt and reqequipt your items if you do not want to soft log..");
player->setAlternateAppearance("", true);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
}
} else if (templatePath == "royal_guard_appearance") {
if (!player->isInCombat() && player->getBankCredits() < 99) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Royal Guard");
box->setPromptText("Costume Coast 100 credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 99) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
player->sendSystemMessage("Thank you for purchasing a costume.");
player->setAlternateAppearance("object/mobile/shared_royal_guard.iff", true);
player->subtractBankCredits(5000);
box->setForceCloseDistance(5.f);
}
} else if (templatePath == "become_glowy") {
bluefrog->grantGlowyBadges(player);
} else if (templatePath == "unlock_jedi_initiate") {
if (!player->isInCombat() && player->getBankCredits() < 9999999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
box->setPromptTitle("Unlocking Jedi");
box->setPromptText("Unlocking Jedi Cost 10,000,000 Credits. (Bank)");
box->setOkButton(true, "@cancel");
box->setUsingObject(player);
player->getPlayerObject()->addSuiBox(box);
player->sendMessage(box->generateMessage());
}
if (!player->isInCombat() && player->getBankCredits() > 9999999) {
ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE);
player->sendSystemMessage("Thank you for purchasing a Jedi Unlock.");
bluefrog->grantGlowyBadges(player);
bluefrog->grantJediInitiate(player);
player->subtractBankCredits(10000000);
box->setForceCloseDistance(5.f);
}
} else {
if (templatePath.length() > 0) {
SkillManager::instance()->awardSkill(templatePath, player, true, true, true);
if (player->hasSkill(templatePath))
player->sendSystemMessage("You have learned a skill.");
} else {
player->sendSystemMessage("Unknown selection.");
return;
}
}
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
} else { // Items
ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
if (inventory == nullptr) {
return;
}
if (templatePath.contains("event_perk")) {
if (!ghost->hasGodMode() && ghost->getEventPerkCount() >= 5) {
player->sendSystemMessage("@event_perk:pro_too_many_perks"); // You cannot rent any more items right now.
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
return;
}
}
ManagedReference<SceneObject*> item = zserv->createObject(node->getTemplateCRC(), 1);
if (item == nullptr) {
player->sendSystemMessage("There was an error creating the requested item. Please report this issue.");
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
error("could not create frog item: " + node->getDisplayName());
return;
}
Locker locker(item);
item->createChildObjects();
if (item->isEventPerkDeed()) {
EventPerkDeed* deed = item.castTo<EventPerkDeed*>();
deed->setOwner(player);
ghost->addEventPerk(deed);
}
if (item->isEventPerkItem()) {
if (item->getServerObjectCRC() == 0x46BD798B) { // Jukebox
Jukebox* jbox = item.castTo<Jukebox*>();
if (jbox != nullptr)
jbox->setOwner(player);
} else if (item->getServerObjectCRC() == 0x255F612C) { // Shuttle Beacon
ShuttleBeacon* beacon = item.castTo<ShuttleBeacon*>();
if (beacon != nullptr)
beacon->setOwner(player);
}
ghost->addEventPerk(item);
}
if (inventory->transferObject(item, -1, true)) {
item->sendTo(player, true);
StringIdChatParameter stringId;
stringId.setStringId("@faction_perk:bonus_base_name"); //You received a: %TO.
stringId.setTO(item->getObjectID());
player->sendSystemMessage(stringId);
} else {
item->destroyObjectFromDatabase(true);
player->sendSystemMessage("Error putting item in inventory.");
return;
}
ghost->addSuiBox(cbSui);
player->sendMessage(cbSui->generateMessage());
}
player->info("[CharacterBuilder] gave player " + templatePath, true);
}
}
void SuiManager::sendKeypadSui(SceneObject* keypad, SceneObject* creatureSceneObject, const String& play, const String& callback) {
if (keypad == nullptr)
return;
if (creatureSceneObject == nullptr || !creatureSceneObject->isCreatureObject())
return;
CreatureObject* creature = cast<CreatureObject*>(creatureSceneObject);
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiKeypadBox*> keypadSui = new SuiKeypadBox(creature, 0x00);
keypadSui->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback));
keypadSui->setUsingObject(keypad);
keypadSui->setForceCloseDisabled();
creature->sendMessage(keypadSui->generateMessage());
playerObject->addSuiBox(keypadSui);
}
}
void SuiManager::sendConfirmSui(SceneObject* terminal, SceneObject* player, const String& play, const String& callback, const String& prompt, const String& button) {
if (terminal == nullptr)
return;
if (player == nullptr || !player->isCreatureObject())
return;
CreatureObject* creature = cast<CreatureObject*>(player);
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiMessageBox*> confirmSui = new SuiMessageBox(creature, 0x00);
confirmSui->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback));
confirmSui->setUsingObject(terminal);
confirmSui->setPromptText(prompt);
confirmSui->setOkButton(true, button);
confirmSui->setOtherButton(false, "");
confirmSui->setCancelButton(false, "");
confirmSui->setForceCloseDistance(32);
creature->sendMessage(confirmSui->generateMessage());
playerObject->addSuiBox(confirmSui);
}
}
void SuiManager::sendInputBox(SceneObject* terminal, SceneObject* player, const String& play, const String& callback, const String& prompt, const String& button) {
if (terminal == nullptr)
return;
if (player == nullptr || !player->isCreatureObject())
return;
CreatureObject* creature = cast<CreatureObject*>(player);
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiInputBox*> confirmSui = new SuiInputBox(creature, 0x00);
confirmSui->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback));
confirmSui->setUsingObject(terminal);
confirmSui->setPromptText(prompt);
confirmSui->setOkButton(true, button);
confirmSui->setOtherButton(false, "");
confirmSui->setCancelButton(false, "");
confirmSui->setForceCloseDistance(32);
creature->sendMessage(confirmSui->generateMessage());
playerObject->addSuiBox(confirmSui);
}
}
void SuiManager::sendMessageBox(SceneObject* usingObject, SceneObject* player, const String& title, const String& text, const String& okButton, const String& screenplay, const String& callback, unsigned int windowType ) {
if (usingObject == nullptr)
return;
if (player == nullptr || !player->isCreatureObject())
return;
CreatureObject* creature = cast<CreatureObject*>(player);
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiMessageBox*> messageBox = new SuiMessageBox(creature, windowType);
messageBox->setCallback(new LuaSuiCallback(creature->getZoneServer(), screenplay, callback));
messageBox->setPromptTitle(title);
messageBox->setPromptText(text);
messageBox->setUsingObject(usingObject);
messageBox->setOkButton(true, okButton);
messageBox->setCancelButton(true, "@cancel");
messageBox->setForceCloseDistance(32.f);
creature->sendMessage(messageBox->generateMessage());
playerObject->addSuiBox(messageBox);
}
}
void SuiManager::sendListBox(SceneObject* usingObject, SceneObject* player, const String& title, const String& text, const uint8& numOfButtons, const String& cancelButton, const String& otherButton, const String& okButton, LuaObject& options, const String& screenplay, const String& callback, const float& forceCloseDist) {
if (usingObject == nullptr)
return;
if (player == nullptr || !player->isCreatureObject())
return;
CreatureObject* creature = cast<CreatureObject*>(player);
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiListBox*> box = nullptr;
switch (numOfButtons) {
case 1:
box = new SuiListBox(creature, 0x00, SuiListBox::HANDLESINGLEBUTTON);
box->setCancelButton(false, "");
box->setOtherButton(false, "");
box->setOkButton(true, okButton);
break;
case 2:
box = new SuiListBox(creature, 0x00, SuiListBox::HANDLETWOBUTTON);
box->setCancelButton(true, cancelButton);
box->setOtherButton(false, "");
box->setOkButton(true, okButton);
break;
case 3:
box = new SuiListBox(creature, 0x00, SuiListBox::HANDLETHREEBUTTON);
box->setCancelButton(true, cancelButton);
box->setOtherButton(true, otherButton);
box->setOkButton(true, okButton);
break;
default:
return;
break;
}
if (options.isValidTable()) {
for (int i = 1; i <= options.getTableSize(); ++i) {
LuaObject table = options.getObjectAt(i);
box->addMenuItem(table.getStringAt(1), table.getLongAt(2));
table.pop();
}
options.pop();
}
box->setCallback(new LuaSuiCallback(creature->getZoneServer(), screenplay, callback));
box->setPromptTitle(title);
box->setPromptText(text);
box->setUsingObject(usingObject);
box->setForceCloseDistance(forceCloseDist);
creature->sendMessage(box->generateMessage());
playerObject->addSuiBox(box);
}
}
void SuiManager::sendTransferBox(SceneObject* usingObject, SceneObject* player, const String& title, const String& text, LuaObject& optionsAddFrom, LuaObject& optionsAddTo, const String& screenplay, const String& callback) {
if (usingObject == nullptr)
return;
if (player == nullptr || !player->isCreatureObject())
return;
CreatureObject* creature = cast<CreatureObject*>(player);
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiTransferBox*> box = nullptr;
box = new SuiTransferBox(creature, 0x00);
if(optionsAddFrom.isValidTable()){
String optionAddFromTextString = optionsAddFrom.getStringAt(1);
String optionAddFromStartingString = optionsAddFrom.getStringAt(2);
String optionAddFromRatioString = optionsAddFrom.getStringAt(3);
box->addFrom(optionAddFromTextString,
optionAddFromStartingString,
optionAddFromStartingString, optionAddFromRatioString);
optionsAddFrom.pop();
}
if(optionsAddTo.isValidTable()){
String optionAddToTextString = optionsAddTo.getStringAt(1);
String optionAddToStartingString = optionsAddTo.getStringAt(2);
String optionAddToRatioString = optionsAddTo.getStringAt(3);
box->addTo(optionAddToTextString,
optionAddToStartingString,
optionAddToStartingString, optionAddToRatioString);
optionsAddTo.pop();
}
box->setCallback(new LuaSuiCallback(creature->getZoneServer(), screenplay, callback));
box->setPromptTitle(title);
box->setPromptText(text);
box->setUsingObject(usingObject);
box->setForceCloseDistance(32.f);
creature->sendMessage(box->generateMessage());
playerObject->addSuiBox(box);
}
}
int32 SuiManager::sendSuiPage(CreatureObject* creature, SuiPageData* pageData, const String& play, const String& callback, unsigned int windowType) {
if (pageData == nullptr)
return 0;
if (creature == nullptr || !creature->isPlayerCreature())
return 0;
PlayerObject* playerObject = creature->getPlayerObject();
if (playerObject != nullptr) {
ManagedReference<SuiBoxPage*> boxPage = new SuiBoxPage(creature, pageData, windowType);
boxPage->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback));
creature->sendMessage(boxPage->generateMessage());
playerObject->addSuiBox(boxPage);
return boxPage->getBoxID();
}
return 0;
}
| 53.505432 | 323 | 0.636271 | V-Fib |
87c9666cbb690c2e1adede8d9ece41a4fd3f59de | 15,614 | cpp | C++ | src/Library/DetectorSpheres/DetectorSphere.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | 1 | 2018-12-20T19:31:02.000Z | 2018-12-20T19:31:02.000Z | src/Library/DetectorSpheres/DetectorSphere.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | src/Library/DetectorSpheres/DetectorSphere.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// DetectorSphere.cpp - Implements a detector sphere
//
// Author: Aravind Krishnaswamy
// Date of Birth: April 11, 2002
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#include "pch.h"
#include <fstream>
#include "DetectorSphere.h"
#include "../Geometry/SphereGeometry.h"
#include "../Utilities/RandomNumbers.h"
#include "../Utilities/RTime.h"
#include "../Interfaces/ILog.h"
#include <algorithm>
using namespace RISE;
using namespace RISE::Implementation;
DetectorSphere::DetectorSphere( ) :
m_pTopPatches( 0 ),
m_pBottomPatches( 0 ),
m_numThetaPatches( 0 ),
m_numPhiPatches( 0 ),
m_dRadius( 0 ),
m_discretization( eEqualPSA )
{
}
DetectorSphere::~DetectorSphere( )
{
if( m_pTopPatches ) {
GlobalLog()->PrintDelete( m_pTopPatches, __FILE__, __LINE__ );
delete [] m_pTopPatches;
m_pTopPatches = 0;
}
if( m_pBottomPatches ) {
GlobalLog()->PrintDelete( m_pBottomPatches, __FILE__, __LINE__ );
delete [] m_pBottomPatches;
m_pBottomPatches = 0;
}
}
void DetectorSphere::ComputePatchAreas( const Scalar radius )
{
// Scalar sqrRadius = radius * radius;
for( unsigned int i=0; i<m_numThetaPatches/2; i++ )
{
for( unsigned int j=0; j<m_numPhiPatches; j++ )
{
const PATCH& p = m_pTopPatches[ i * m_numPhiPatches + j ];
Scalar patch_area = GeometricUtilities::SphericalPatchArea( PI_OV_TWO-p.dThetaEnd, PI_OV_TWO-p.dThetaBegin, p.dPhiBegin, p.dPhiEnd, radius );
// approx. of theta_r
// Cos(Theta) is approximated by averaging theta
// Scalar ctr = fabs( cos( (p.dThetaEnd-p.dThetaBegin)/2.0 + p.dThetaBegin ) );
// Cos(Theta) is approximated by averaging the Cos(thetas)
Scalar ctr = (fabs( cos( p.dThetaBegin ) ) + fabs( cos( p.dThetaEnd ) )) / 2.0;
{
PATCH& p = m_pTopPatches[ i * m_numPhiPatches + j ];
p.dArea = patch_area;
p.dCosT = ctr;
p.dAreaCos = p.dArea*p.dCosT;
// p.dSolidProjectedAngle = p.dAreaCos / sqrRadius;
// Alternate method of computing the projected solid angle
p.dSolidProjectedAngle = 0.5 * (p.dPhiEnd-p.dPhiBegin) * (cos(p.dThetaBegin)*cos(p.dThetaBegin) - cos(p.dThetaEnd)*cos(p.dThetaEnd) );
}
}
}
}
void DetectorSphere::InitPatches(
const unsigned int num_theta_patches,
const unsigned int num_phi_patches,
const Scalar radius,
const PatchDiscretization discretization
)
{
if( m_pTopPatches ) {
GlobalLog()->PrintDelete( m_pTopPatches, __FILE__, __LINE__ );
delete m_pTopPatches;
m_pTopPatches = 0;
}
m_dRadius = radius;
m_discretization = discretization;
// Allocate the memory for the patches
m_pTopPatches = new PATCH[num_theta_patches*num_phi_patches/2];
GlobalLog()->PrintNew( m_pTopPatches, __FILE__, __LINE__, "top patches" );
memset( m_pTopPatches, 0, sizeof( PATCH ) * num_theta_patches*num_phi_patches/2 );
m_numThetaPatches = num_theta_patches;
m_numPhiPatches = num_phi_patches;
const Scalar delta_phi = 2.0 * PI/Scalar(num_phi_patches);
const Scalar delta_the = PI_OV_TWO/Scalar(num_theta_patches/2); // adjusted to sphere
const Scalar h = radius / Scalar(num_theta_patches/2);
//Scalar delta_costheta = 1.0 / Scalar(num_theta_patches/2);
// Setup the top hemisphere of patches
int unsigned i=0, j=0;
Scalar last_te = 0.0;
const Scalar psa_per_patch = PI / Scalar(num_theta_patches/2); // Hemisphere
const Scalar OV_Num_Theta = 1.0 / Scalar(num_theta_patches/2);
for( i=0; i<num_theta_patches/2; i++ )
{
Scalar tb=0, te=0;
if( m_discretization == eEqualAngles ) {
// This keeps the angle the same for each of the patches
tb = i*delta_the;
te = tb + delta_the;
} else if( m_discretization == eEqualAreas ) {
// This keeps the area the same for each of the patches
tb = asin( h*Scalar(i) / radius );
te = asin( h*Scalar(i+1) / radius );
// This also keeps the area the same for each of the patches, equal intervals in CosT space
// tb = acos( delta_costheta * Scalar(i+1) );
// te = acos( delta_costheta * Scalar(i) );
} else if( m_discretization == eExponentiallyIncreasingSolidAngles ) {
// Right from the paper
tb = acos( h*Scalar(i+1) / radius );
te = acos( h*Scalar(i) / radius );
} else if( m_discretization == eEqualPSA ) {
// Keeps the PSA the same, but assumes that the coses are embedded in the integration
tb = last_te;
te = acos( sqrt( fabs( OV_Num_Theta - cos(last_te)*cos(last_te) ) ) );
last_te = te;
}
for( j=0; j<num_phi_patches; j++ )
{
PATCH& patch = m_pTopPatches[ i*num_phi_patches + j ];
patch.dThetaBegin = tb;
patch.dThetaEnd = te;
patch.dPhiBegin = j*delta_phi;
patch.dPhiEnd = patch.dPhiBegin + delta_phi;
if( m_discretization == eEqualPSA ) {
patch.dArea = GeometricUtilities::SphericalPatchArea( patch.dThetaBegin, patch.dThetaEnd, patch.dPhiBegin, patch.dPhiEnd, radius );
patch.dSolidProjectedAngle = psa_per_patch / Scalar(num_phi_patches);
}
patch.dKnownValue = INV_PI;
patch.dRatio = 0;
}
}
if( m_discretization != eEqualPSA ) {
ComputePatchAreas( m_dRadius );
}
// Now setup the bottom hemisphere of patches, the bottom hemisphere can be a direct copy of
// the top, except that the theta's just need to be adjusted to add PI_OV_TWO
if( m_pBottomPatches ) {
GlobalLog()->PrintDelete( m_pBottomPatches, __FILE__, __LINE__ );
delete [] m_pBottomPatches;
m_pBottomPatches = 0;
}
// Allocate the memory for the patches
m_pBottomPatches = new PATCH[num_theta_patches*num_phi_patches/2];
GlobalLog()->PrintNew( m_pBottomPatches, __FILE__, __LINE__, "bottom patches" );
memcpy( m_pBottomPatches, m_pTopPatches, sizeof( PATCH ) * num_theta_patches*num_phi_patches/2 );
// Now go through and adjust the thetas
for( i=0; i<num_theta_patches/2; i++ ) {
for( j=0; j<num_phi_patches; j++ ) {
PATCH& patch = m_pBottomPatches[ i*num_phi_patches + j ];
patch.dThetaBegin = PI - patch.dThetaBegin;
patch.dThetaEnd = PI - patch.dThetaEnd;
}
}
}
void DetectorSphere::DumpToCSVFileForExcel( const char * szFile, const Scalar phi_begin, const Scalar phi_end, const Scalar theta_begin, const Scalar theta_end ) const
{
int i, e;
// We write our results to a CSV file so that it can be loaded in excel and nice graphs can be
// made from it...
std::ofstream f( szFile );
f << "Top hemisphere" << std::endl;
f << "Theta begin, Theta end, Phi begin, Phi end, Patch area, Cos T, Solid Proj. Angle, Ratio\n";;
for( i=0, e = numPatches()/2; i<e; i++ ) {
f << m_pTopPatches[i].dThetaBegin * RAD_TO_DEG << ", " << m_pTopPatches[i].dThetaEnd * RAD_TO_DEG << ", " << m_pTopPatches[i].dPhiBegin * RAD_TO_DEG << ", " << m_pTopPatches[i].dPhiEnd * RAD_TO_DEG << ", " << m_pTopPatches[i].dArea << ", " << m_pTopPatches[i].dCosT << ", " << m_pTopPatches[i].dSolidProjectedAngle << ", " << m_pTopPatches[i].dRatio << "\n";
}
f << std::endl << std::endl;
f << "Bottom hemisphere" << std::endl;
f << "Theta begin, Theta end, Phi begin, Phi end, Patch area, Cos T, Solid Proj. Angle, Ratio\n";;
for( i=0, e = numPatches()/2; i<e; i++ ) {
f << m_pBottomPatches[i].dThetaBegin * RAD_TO_DEG << ", " << m_pBottomPatches[i].dThetaEnd * RAD_TO_DEG << ", " << m_pBottomPatches[i].dPhiBegin * RAD_TO_DEG << ", " << m_pBottomPatches[i].dPhiEnd * RAD_TO_DEG << ", " << m_pBottomPatches[i].dArea << ", " << m_pBottomPatches[i].dCosT << ", " << m_pBottomPatches[i].dSolidProjectedAngle << ", " << m_pBottomPatches[i].dRatio << "\n";
}
}
void DetectorSphere::DumpForMatlab( const char* szFile, const Scalar phi_begin, const Scalar phi_end, const Scalar theta_begin, const Scalar theta_end ) const
{
std::ofstream f( szFile );
unsigned int i, j;
for( i=0; i<m_numThetaPatches/2; i++ ) {
for( j=0; j<m_numPhiPatches; j++ ) {
f << m_pTopPatches[i*m_numPhiPatches+j].dRatio << " ";
}
f << std::endl;
}
for( i=0; i<m_numThetaPatches/2; i++ ) {
for( j=0; j<m_numPhiPatches; j++ ) {
f << m_pBottomPatches[i*m_numPhiPatches+j].dRatio << " ";
}
f << std::endl;
}
}
DetectorSphere::PATCH* DetectorSphere::PatchFromAngles( const Scalar& theta, const Scalar phi ) const
{
// Optimization: Finding out which phi is trivial, its which theta that is tricky...
// This says its the nth phi patch on the mth theta ring
const unsigned int phi_num = int( (phi / TWO_PI) * Scalar(m_numPhiPatches));
// Find out which side first
if( theta <= PI_OV_TWO ) {
// Top patches
for( unsigned int i=0; i<m_numThetaPatches/2; i++ )
{
const unsigned int iPatchIdx = i*m_numPhiPatches+phi_num;
const PATCH& p = m_pTopPatches[iPatchIdx];
if( theta >= p.dThetaBegin && theta <= p.dThetaEnd ) {
// This is the right ring...
return &m_pTopPatches[iPatchIdx];
}
}
}
if( theta >= PI_OV_TWO ) {
// Bottom patches
for( unsigned int i=0; i<m_numThetaPatches/2; i++ )
{
const unsigned int iPatchIdx = i*m_numPhiPatches+phi_num;
const PATCH& p = m_pBottomPatches[iPatchIdx];
if( theta >= p.dThetaEnd && theta <= p.dThetaBegin ) {
// This is the right ring...
return &m_pBottomPatches[iPatchIdx];
}
}
}
return 0;
}
void DetectorSphere::PerformMeasurement(
const ISampleGeometry& pEmmitter, ///< [in] Sample geometry of the emmitter
const ISampleGeometry& pSpecimenGeom, ///< [in] Sample geometry of the specimen
const Scalar& radiant_power,
const IMaterial& pSample,
const unsigned int num_samples,
const unsigned int samples_base,
IProgressCallback* pProgressFunc,
int progress_rate
)
{
// Clear the current results
{
for( int i=0, e=numPatches()/2; i<e; i++ ) {
m_pTopPatches[i].dRatio = 0;
m_pBottomPatches[i].dRatio = 0;
}
}
srand( GetMilliseconds() );
// The detector geometry itself, which is a sphere
SphereGeometry* pDetector = new SphereGeometry( m_dRadius );
GlobalLog()->PrintNew( pDetector, __FILE__, __LINE__, "Detector sphere geometry" );
//Scalar theta_size = Scalar(m_numThetaPatches) * INV_PI;
//Scalar phi_size = 0.5 * Scalar(m_numPhiPatches) * INV_PI;
Scalar power_each_sample = radiant_power / (Scalar(num_samples) * Scalar(samples_base));
// See below, this is power distributed to every patch in the ring at the top of the detector
Scalar specialCaseDistributedEnergy = power_each_sample / Scalar(m_numPhiPatches);
unsigned int i = 0;
ISPF* pSPF = pSample.GetSPF();
if( !pSPF ) {
return;
}
for( ; i<num_samples; i++ )
{
for( unsigned int j = 0; j<samples_base; j++ )
{
Point3 pointOnEmmitter = pEmmitter.GetSamplePoint();
Point3 pointOnSpecimen = pSpecimenGeom.GetSamplePoint();
// The emmitter ray starts at where the emmitter is, and heads towards the world origin
Ray emmitter_ray( pointOnEmmitter, Vector3Ops::Normalize(Vector3Ops::mkVector3(pointOnSpecimen,pointOnEmmitter)) );
RayIntersectionGeometric ri( emmitter_ray, nullRasterizerState );
ri.ptIntersection = Point3(0,0,0);
// ri.onb.CreateFromW( Vector3( 1, 0, 0 ) );
// For each sample, fire it down to the surface, the fire the reflected ray to see
// which detector it hits
ScatteredRayContainer scattered;
pSPF->Scatter( ri, random, scattered, 0 );
ScatteredRay* pScat = scattered.RandomlySelect( random.CanonicalRandom(), false );
if( pScat )
{
// If the ray wasn't absorbed, then fire it at the detector patches
RayIntersectionGeometric ri( pScat->ray, nullRasterizerState );
Vector3Ops::NormalizeMag(ri.ray.dir);
// Ignore the front faces, just hit the back faces!
pDetector->IntersectRay( ri, false, true, false );
if( ri.bHit )
{
// Compute the deposited power on this detector
//
// To do this we just follow the instructions as laid out in
// Baranoski and Rokne's Eurographics tutorial
// "Simulation Of Light Interaction With Plants"
//
// This is the ratio between the radiant power reaching the detector
// and the incident radiant power (which is multiplied by the projected solid angle)
// Note that rather than accruing the power reaching the detector, we could simply
// count the number of rays that hit the detector and use that as the ratio (still multiplying)
// by the projected solid angle of course... either way is fine, neither is more or less
// beneficial... though I could see an application of this method to ensure materials
// maintain energy conservation.
//
// Here we just store the incident power, which is simple enough to do
Scalar phi=0, theta=0;
if( Point3Ops::AreEqual(ri.ptIntersection, Point3( 0, 0, 1 ), NEARZERO ) )
{
// Special case:
// The ray is reflected completely straight up, at precisely the point
// where all the patches of one ring meet. This was causing accuracy problems with
// certain BRDFs, so instead, the power is equally distributed to all the patches
// that particular ring
for( unsigned int k=(m_numThetaPatches-2)*m_numPhiPatches/2; k<m_numPhiPatches*m_numThetaPatches/2; k++ ) {
m_pTopPatches[ k ].dRatio += specialCaseDistributedEnergy;
}
}
else if( Point3Ops::AreEqual(ri.ptIntersection, Point3( 0, 0, -1 ), NEARZERO ) )
{
for( unsigned int k=(m_numThetaPatches-2)*m_numThetaPatches/2; k<m_numPhiPatches*m_numThetaPatches/2; k++ ) {
m_pBottomPatches[ k ].dRatio += specialCaseDistributedEnergy;
}
}
else
{
if( GeometricUtilities::GetSphericalFromPoint3( ri.ptIntersection, phi, theta ) ) {
#if 1
if( theta < PI_OV_TWO ) {
theta = PI_OV_TWO - theta;
} else {
theta = PI_OV_TWO + PI - theta;
}
if( phi < PI ) {
phi = PI + phi;
} else {
phi = phi - PI;
}
#endif
PATCH* patch = PatchFromAngles( theta, phi );
if( !patch ) {
GlobalLog()->PrintEx( eLog_Warning, "DetectorSphere::PerformMeasurement, Couldn't find patch, phi: %f, theta: %f", phi, theta );
} else {
patch->dRatio += power_each_sample*ColorMath::MaxValue(pScat->kray);
}
}
}
}
}
}
if( (i % progress_rate == 0) && pProgressFunc ) {
if( !pProgressFunc->Progress( static_cast<double>(i), static_cast<double>(num_samples) ) ) {
break; // abort
}
}
}
safe_release( pDetector );
if( pProgressFunc ) {
pProgressFunc->Progress( 1.0, 1.0 );
}
// Scalar sqrRadius = (m_dRadius*m_dRadius);
unsigned int e = m_numThetaPatches*m_numPhiPatches/2;
for( i=0; i<e; i++ )
{
//
// Now we compute the ratio,
// which is the power reaching the detector, divided by
// the total incident power times the solid projected angle
m_pTopPatches[i].dRatio /= radiant_power * m_pTopPatches[i].dSolidProjectedAngle;
m_pBottomPatches[i].dRatio /= radiant_power * m_pBottomPatches[i].dSolidProjectedAngle;
}
}
Scalar DetectorSphere::ComputeOverallRMSErrorIfPerfectlyDiffuse( ) const
{
//
// Given the known value for each of the patches, it computes the overall error for
// the entire detector
//
//
// RMS error = sqrt( 1/M sum_i sum_j e^2(i,j) where e(i,j) = abs( f(i,j) - fr(i,j) )
// where f(i,j) is the estimated value for the patch
// and fr(i,j) is the actual value for the patch
//
Scalar accruedSum=0;
for( unsigned int i=0; i<numPatches(); i++ ) {
Scalar eij = m_pTopPatches[i].dRatio - m_pTopPatches[i].dKnownValue;
accruedSum += eij*eij;
}
return sqrt(accruedSum / Scalar(numPatches()) );
}
| 33.363248 | 385 | 0.671128 | aravindkrishnaswamy |
d7b54eb5eefebc6c56e7906c584d96697fcebb3a | 736 | cpp | C++ | input/pointer2.cpp | xdevkartik/cpp_basics | a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55 | [
"MIT"
] | null | null | null | input/pointer2.cpp | xdevkartik/cpp_basics | a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55 | [
"MIT"
] | null | null | null | input/pointer2.cpp | xdevkartik/cpp_basics | a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
main()
{
string str = {};
int i = 0;
string wordfinal;
for (string word; i < 3; i++)
{
cout << "Please enter any word " << i + 1 << ": ";
//cin.ignore(); // I have to use it to clear apce of previous cout.
getline(cin, word);
//cout << word;
//cin >> word; // cin only take char as a input, means only 1 character.
// So i have to use getline() function
wordfinal = "\"" + word + "\", ";
//str.append(wordfinal);
str[i] = wordfinal;
cout << str << "\n";
}
cout << "Now printing array backward.\n";
// Printing last entered word first and so on...
cout << str[2];
return 0;
} | 28.307692 | 80 | 0.516304 | xdevkartik |
d7b789f0fddc21ac674103af32f37b76dc5f8c83 | 198 | hpp | C++ | src/waygate.hpp | ohowland/waygate | 926100c101b30827b52ba9262f3b7dfdbb6f50ad | [
"MIT"
] | null | null | null | src/waygate.hpp | ohowland/waygate | 926100c101b30827b52ba9262f3b7dfdbb6f50ad | [
"MIT"
] | null | null | null | src/waygate.hpp | ohowland/waygate | 926100c101b30827b52ba9262f3b7dfdbb6f50ad | [
"MIT"
] | null | null | null | #define WAYGATE_VERSION_MAJOR @WAYGATE_VERSION_MAJOR@
#define WAYGATE_VERSION_MINOR @WAYGATE_VERSION_MINOR@
#define PROJECT_CONFIG_DIR @PROJECT_CONFIG_DIR@
#include "bus.hpp"
#include "signals.hpp" | 33 | 53 | 0.848485 | ohowland |
d7c5469fb3b0a151a1a37df3fd5ecfbd460ac47f | 9,264 | cpp | C++ | Arduino/libraries/PMIC_SGM41512/src/SGM41512.cpp | rdpoor/tinyml_low_power | 65fe34cc1f156e5bc9687cc8cc690ea71baa56de | [
"MIT"
] | null | null | null | Arduino/libraries/PMIC_SGM41512/src/SGM41512.cpp | rdpoor/tinyml_low_power | 65fe34cc1f156e5bc9687cc8cc690ea71baa56de | [
"MIT"
] | null | null | null | Arduino/libraries/PMIC_SGM41512/src/SGM41512.cpp | rdpoor/tinyml_low_power | 65fe34cc1f156e5bc9687cc8cc690ea71baa56de | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2021 Syntiant Corp. All rights reserved.
* Contact at http://www.syntiant.com
*
* This software is available to you under a choice of one of two licenses.
* You may choose to be licensed under the terms of the GNU General Public
* License (GPL) Version 2, available from the file LICENSE in the main
* directory of this source tree, or the OpenIB.org BSD license below. Any
* code involving Linux software will require selection of the GNU General
* Public License (GPL) Version 2.
*
* OPENIB.ORG BSD LICENSE
*
* 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.
*
* 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 "SGM41512.h"
//Default PMIC (SGM41512) I2C address
#define PMIC_ADDRESS 0x6B
// Register address definitions (only the ones used here)
#define PMIC_POWERON_CONFIG_REG 0x01
#define PMIC_CHARGE_VOLTAGE_CONTROL_REG 0x04
#define PMIC_CHARGE_TIMER_CONTROL_REG 0x05
#define PMIC_MISC_CONTROL_REG 0x07
#define PMIC_SYSTEM_STATUS_REG 0x08
#define PMIC_RESET_AND_VERSION_REG 0x0B
PMICClass::PMICClass(TwoWire &wire) : _wire(&wire)
{
}
/*******************************************************************************
* Function Name : begin
* Description : Initializes the I2C for the PMIC module
* Input : NONE
* Return : 0 on Error, 1 on Success
*******************************************************************************/
bool PMICClass::begin()
{
_wire->begin();
#ifdef ARDUINO_ARCH_SAMD
pinMode(PIN_USB_HOST_ENABLE - 3, OUTPUT);
//digitalWrite(PIN_USB_HOST_ENABLE, LOW);
digitalWrite(PIN_USB_HOST_ENABLE - 3, HIGH);
#if defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500)
pinMode(PMIC_IRQ_PIN, INPUT_PULLUP);
#endif
#endif
//check PMIC version --- ignoring the last two-bit field, DEV_REV[1:0]
if ((readRegister(PMIC_RESET_AND_VERSION_REG) | 0x03) != 0x2F)
{
return 0;
}
else
{
return 1;
}
}
/*******************************************************************************
* Function Name : end
* Description : Deinitializes the I2C for the PMIC module
* Input : NONE
* Return : NONE
*******************************************************************************/
void PMICClass::end()
{
#ifdef ARDUINO_ARCH_SAMD
//pinMode(PIN_USB_HOST_ENABLE, INPUT);
pinMode(PIN_USB_HOST_ENABLE - 3, INPUT);
#if defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500)
pinMode(PMIC_IRQ_PIN, INPUT);
#endif
#endif
_wire->end();
}
/*******************************************************************************
* Function Name : enableCharge
* Description : Enables PMIC charge mode
* Input : NONE
* Return : 0 on Error, 1 on Success
*******************************************************************************/
bool PMICClass::enableCharge()
{
#ifdef ARDUINO_ARCH_SAMD
//digitalWrite(PIN_USB_HOST_ENABLE, LOW);
digitalWrite(PIN_USB_HOST_ENABLE - 3, HIGH);
#endif
int DATA = readRegister(PMIC_POWERON_CONFIG_REG);
if (DATA == -1) {
return 0;
}
byte mask = DATA & 0xCF;
// Enable PMIC battery charging mode
if (!writeRegister(PMIC_POWERON_CONFIG_REG, mask | 0x10)) {
return 0;
}
DATA = readRegister(PMIC_CHARGE_TIMER_CONTROL_REG);
if (DATA == -1) {
return 0;
}
mask = DATA & 0x7F;
// Enable charge termination feature
if (!writeRegister(PMIC_CHARGE_TIMER_CONTROL_REG, mask | 0x80)) {
return 0;
}
DATA = readRegister(PMIC_CHARGE_VOLTAGE_CONTROL_REG);
if (DATA == -1) {
return 0;
}
// Enable Top-off timer
if (!writeRegister(PMIC_CHARGE_VOLTAGE_CONTROL_REG, DATA | 0x03)) {
return 0;
}
return enableBATFET();
}
/*******************************************************************************
* Function Name : enableBoostMode
* Description : Enables PMIC boost mode, allow to generate 5V from battery
* Input : NONE
* Return : 0 on Error, 1 on Success
*******************************************************************************/
bool PMICClass::enableBoostMode()
{
int DATA = readRegister(PMIC_POWERON_CONFIG_REG);
if (DATA == -1) {
return 0;
}
byte mask = DATA & 0xCF;
// Enable PMIC boost mode
if (!writeRegister(PMIC_POWERON_CONFIG_REG, mask | 0x20)) {
return 0;
}
#ifdef ARDUINO_ARCH_SAMD
//digitalWrite(PIN_USB_HOST_ENABLE, LOW);
digitalWrite(PIN_USB_HOST_ENABLE - 3, HIGH);
#endif
// Disable charge termination feature
DATA = readRegister(PMIC_CHARGE_TIMER_CONTROL_REG);
if (DATA == -1) {
return 0;
}
mask = DATA & 0x7F; // remove "enable termination" bit
if (!writeRegister(PMIC_CHARGE_TIMER_CONTROL_REG, mask)) {
return 0;
}
// wait for enable boost mode
delay(500);
return 1;
}
/*******************************************************************************
* Function Name : enableBATFET
* Description : turn on BATFET
* Input : NONE
* Return : 0 on Error, 1 on Success
*******************************************************************************/
bool PMICClass::enableBATFET(void)
{
int DATA = readRegister(PMIC_MISC_CONTROL_REG);
if (DATA == -1) {
return 0;
}
return writeRegister(PMIC_MISC_CONTROL_REG, (DATA & 0b11011111));
}
/*******************************************************************************
* Function Name : chargeStatus
* Description : Query the PMIC and returns the Charging status
* Input : NONE
* Return : -1 on Error, Charging status on Success
*******************************************************************************/
int PMICClass::chargeStatus()
{
int DATA = readRegister(PMIC_SYSTEM_STATUS_REG);
if (DATA == -1) {
return DATA;
}
byte charge_staus = (DATA & 0x18)>>3;
return charge_staus;
}
/*******************************************************************************
* Function Name : getOperationMode
* Description : Query the PMIC and returns the mode of operation
* Input : NONE
* Return : -1 on Error, 0 on Charge mode, 1 on Boost mode
*******************************************************************************/
int PMICClass::getOperationMode()
{
int DATA = readRegister(PMIC_POWERON_CONFIG_REG);
if (DATA == -1) {
return DATA;
}
byte mode_staus = (DATA & 0x20)>>5;
return mode_staus;
}
/*******************************************************************************
* Function Name : disableWatchdog
* Description : Disable Watchdog timer
* Input : NONE
* Return : 0 on Error, 1 on Success
*******************************************************************************/
bool PMICClass::disableWatchdog(void)
{
int DATA = readRegister(PMIC_CHARGE_TIMER_CONTROL_REG);
if (DATA == -1) {
return 0;
}
return writeRegister(PMIC_CHARGE_TIMER_CONTROL_REG, (DATA & 0b11001111));
}
/*******************************************************************************
* Function Name : readRegister
* Description : read the register with the given address in the PMIC
* Input : register address
* Return : 0 on Error, 1 on Success
*******************************************************************************/
int PMICClass::readRegister(byte address)
{
_wire->beginTransmission(PMIC_ADDRESS);
_wire->write(address);
if (_wire->endTransmission(true) != 0) {
return -1;
}
if (_wire->requestFrom(PMIC_ADDRESS, 1, true) != 1) {
return -1;
}
return _wire->read();
}
/*******************************************************************************
* Function Name : writeRegister
* Description : write a value in the register with the given address in the PMIC
* Input : register address, value
* Return : 0 on Error, 1 on Success
*******************************************************************************/
int PMICClass::writeRegister(byte address, byte val)
{
_wire->beginTransmission(PMIC_ADDRESS);
_wire->write(address);
_wire->write(val);
if (_wire->endTransmission(true) != 0) {
return 0;
}
return 1;
}
PMICClass PMIC(Wire);
| 30.574257 | 85 | 0.554512 | rdpoor |
d7cac9e4a9cc3fd29c53b9ab50d1c8a9ef0aa9c5 | 658 | hpp | C++ | source/Senses/View/ResizeUITab.hpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 8 | 2015-01-23T05:41:46.000Z | 2019-11-20T05:10:27.000Z | source/Senses/View/ResizeUITab.hpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | null | null | null | source/Senses/View/ResizeUITab.hpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 4 | 2015-05-05T05:15:43.000Z | 2020-03-07T11:10:56.000Z | /*********************************************************************************************************
* UIWindow.cpp
* Note: ResizeUITab.cpp
* Date: @2015.04
* E-mail:<forcemz@outlook.com>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#ifndef PHOENXI_RESIZEUITAB_HPP
#define PHOENXI_RESIZEUITAB_HPP
class ResizeUITab{
private:
RECT m_place;
public:
ResizeUITab();
bool Create();
LRESULT Initialize();
LRESULT Resize();
LRESULT Move();
LRESULT Draw();
LRESULT Close();
LRESULT Click();
};
#endif
| 25.307692 | 107 | 0.465046 | fstudio |
d7d09a740cfbd23b9debf34ea601735536edaf16 | 805 | cpp | C++ | potato/spud/tests/test_delegate_ref.cpp | seanmiddleditch/grimm | 9f47fc5d7aa0af19a3a7c82a38b7f7c59b83fbf5 | [
"MIT"
] | 38 | 2019-05-25T17:32:26.000Z | 2022-02-27T22:25:05.000Z | potato/spud/tests/test_delegate_ref.cpp | seanmiddleditch/grimm | 9f47fc5d7aa0af19a3a7c82a38b7f7c59b83fbf5 | [
"MIT"
] | 35 | 2019-05-26T17:52:39.000Z | 2022-02-12T19:54:14.000Z | potato/spud/tests/test_delegate_ref.cpp | seanmiddleditch/grimm | 9f47fc5d7aa0af19a3a7c82a38b7f7c59b83fbf5 | [
"MIT"
] | 2 | 2019-06-09T16:06:27.000Z | 2019-08-16T14:17:20.000Z | #include "potato/spud/delegate_ref.h"
#include <catch2/catch.hpp>
TEST_CASE("potato.spud.delegate_ref", "[potato][spud]") {
using namespace up;
SECTION("lambda delegate_ref") {
int (*f)(int) = [](int i) {
return i * 2;
};
delegate_ref d = f;
CHECK(d(0) == 0);
CHECK(d(-1) == -2);
CHECK(d(10) == 20);
}
SECTION("delegate_ref reassignment") {
int i1 = 2;
auto f1 = [&i1](int i) {
return i1 += i;
};
static_assert(is_invocable_v<decltype(f1), int>);
int i2 = 2;
auto f2 = [&i2](int i) {
return i2 *= i;
};
delegate_ref<int(int)> d(f1);
d(2);
CHECK(i1 == 4);
d = f2;
d(4);
CHECK(i2 == 8);
}
}
| 20.125 | 57 | 0.448447 | seanmiddleditch |
d7d1e3215854e380e81622caaeee52b61611a464 | 3,807 | cpp | C++ | project/OFEC_sc2/instance/problem/continuous/multi_modal/metrics_mmop.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/problem/continuous/multi_modal/metrics_mmop.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/problem/continuous/multi_modal/metrics_mmop.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | #include "../../../../core/algorithm/solution.h"
#include "../../../../core/problem/continuous/continuous.h"
#include "metrics_mmop.h"
#include <algorithm>
namespace OFEC {
void MetricsMMOP::updateCandidates(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates) const {
updateOnlyByObj(sol, candidates);
}
size_t MetricsMMOP::numOptimaFound(const std::list<std::unique_ptr<SolBase>> &candidates) const {
return numOptimaOnlyByObj(candidates);
}
void MetricsMMOP::updateOnlyByObj(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates) const {
if (sol.objectiveDistance(m_optima.objective(0)) < m_objective_accuracy) {
for (auto &c : candidates) {
if (c->variableDistance(sol, m_id_pro) < m_variable_niche_radius)
return;
}
candidates.emplace_back(new Solution<>(dynamic_cast<const Solution<>&>(sol)));
}
}
void MetricsMMOP::updateByObjAndVar(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates) const {
std::vector<bool> is_opt_fnd(m_optima.numberObjectives(), false);
Real dis_obj, dis_var;
for (auto &c : candidates) {
for (size_t i = 0; i < m_optima.numberVariables(); i++) {
if (is_opt_fnd[i])
continue;
dis_obj = c->objectiveDistance(m_optima.objective(i));
dis_var = c->variableDistance(m_optima.variable(i), m_id_pro);
if (dis_obj < m_objective_accuracy && dis_var < m_variable_niche_radius)
is_opt_fnd[i] = true;
}
}
for (size_t i = 0; i < m_optima.numberObjectives(); i++) {
if (!is_opt_fnd[i]) {
dis_obj = sol.objectiveDistance(m_optima.objective(i));
dis_var = sol.variableDistance(m_optima.variable(i), m_id_pro);
if (dis_obj < m_objective_accuracy && dis_var < m_variable_niche_radius) {
candidates.emplace_back(new Solution<>(dynamic_cast<const Solution<>&>(sol)));
break;
}
}
}
}
void MetricsMMOP::updateBestFixedNumSols(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates, size_t num_sols) const {
bool flag_add = true;
for (auto iter = candidates.begin(); iter != candidates.end();) {
if (sol.variableDistance(**iter, m_id_pro) < m_variable_niche_radius) {
if (sol.dominate(**iter, m_id_pro))
iter = candidates.erase(iter);
else {
flag_add = false;
break;
}
}
else
iter++;
}
if (flag_add) {
if (candidates.size() < num_sols)
candidates.emplace_back(new Solution<>(dynamic_cast<const Solution<>&>(sol)));
else {
auto iter_worst = std::min_element(
candidates.begin(), candidates.end(),
[this](const std::unique_ptr<SolBase> &rhs1, const std::unique_ptr<SolBase> &rhs2) { return rhs1->dominate(*rhs2, this->m_id_pro); });
(*iter_worst).reset(new Solution<>(dynamic_cast<const Solution<>&>(sol)));
}
}
}
size_t MetricsMMOP::numOptimaOnlyByObj(const std::list<std::unique_ptr<SolBase>> &candidates) const {
std::list<SolBase*> opts_fnd;
for (auto &c : candidates) {
if (c->objectiveDistance(m_optima.objective(0)) < m_objective_accuracy) {
bool is_new_opt = true;
for (auto of : opts_fnd) {
if (of->variableDistance(*c, m_id_pro) < m_variable_niche_radius) {
is_new_opt = false;
break;
}
}
if (is_new_opt)
opts_fnd.push_back(c.get());
}
}
return opts_fnd.size();
}
size_t MetricsMMOP::numOptimaByObjAndVar(const std::list<std::unique_ptr<SolBase>> &candidates) const {
size_t count = 0;
Real dis_obj, dis_var;
for (size_t i = 0; i < m_optima.numberObjectives(); i++) {
for (auto &c : candidates) {
dis_obj = c->objectiveDistance(m_optima.objective(i));
dis_var = c->variableDistance(m_optima.variable(i), m_id_pro);
if (dis_obj < m_objective_accuracy && dis_var < m_variable_niche_radius) {
count++;
break;
}
}
}
return count;
}
} | 34.926606 | 139 | 0.679275 | BaiChunhui-9803 |
d7d64647ebace47c95299ab67c845921d10ded46 | 681 | cpp | C++ | Cpp_primer_5th/code_part7/prog7_1.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | Cpp_primer_5th/code_part7/prog7_1.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | Cpp_primer_5th/code_part7/prog7_1.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
struct Sales_data{
string bookNo;
double revenue = 0.0;
int usold= 0;
};
int main(){
Sales_data total;
if(cin >> total.bookNo >> total.usold >> total.revenue){
Sales_data trans;
while(cin >> trans.bookNo >> trans.usold >> trans.revenue){
if(total.bookNo == trans.bookNo){
total.usold += trans.usold;
total.revenue += trans.revenue;
}
else{
cout << total.bookNo << " " << total.usold << " " << total.revenue << endl;
total = trans;
}
}
cout << total.bookNo << " " << total.usold << " " << total.revenue << endl;
}d
else{
cerr << "No data?!" << endl;
return -1;
}
return 0;
}
| 20.636364 | 79 | 0.582966 | Links789 |
d7d8e6203585b78e5a2e850c83112151697b7868 | 495 | cpp | C++ | WaveformGenerator/waveformgenerator.cpp | VioletGiraffe/AudioGenerator | bea5118a55ffd3f246f87aea7e22880741d4e669 | [
"Apache-2.0"
] | null | null | null | WaveformGenerator/waveformgenerator.cpp | VioletGiraffe/AudioGenerator | bea5118a55ffd3f246f87aea7e22880741d4e669 | [
"Apache-2.0"
] | null | null | null | WaveformGenerator/waveformgenerator.cpp | VioletGiraffe/AudioGenerator | bea5118a55ffd3f246f87aea7e22880741d4e669 | [
"Apache-2.0"
] | null | null | null | #include "waveformgenerator.h"
WaveformGenerator::~WaveformGenerator()
{
}
float WaveformGenerator::extraParameter() const
{
return _extraParameter;
}
bool WaveformGenerator::hasExtraParameter() const
{
return false;
}
const WaveformGenerator::ExtraParameterProperties WaveformGenerator::extraParameterProperties()
{
return ExtraParameterProperties{std::string(), 0.0f, 0.0f, 0.0f};
}
void WaveformGenerator::setExtraParameter(float p)
{
_extraParameter = p;
}
| 19.038462 | 96 | 0.747475 | VioletGiraffe |
d7df21b6414e312c796e0fedab119443608b9032 | 3,084 | cpp | C++ | Nesis/Instruments/src/XMLGaugeRoundAltitude.cpp | jpoirier/x-gauges | 8261b19a9678ad27db44eb8c354f5e66bd061693 | [
"BSD-3-Clause"
] | 3 | 2015-11-08T07:17:46.000Z | 2019-04-05T17:08:05.000Z | Nesis/Instruments/src/XMLGaugeRoundAltitude.cpp | jpoirier/x-gauges | 8261b19a9678ad27db44eb8c354f5e66bd061693 | [
"BSD-3-Clause"
] | null | null | null | Nesis/Instruments/src/XMLGaugeRoundAltitude.cpp | jpoirier/x-gauges | 8261b19a9678ad27db44eb8c354f5e66bd061693 | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* *
* Copyright (C) 2007 by Kanardia d.o.o. [see www.kanardia.eu] *
* Writen by: *
* Ales Krajnc [ales.krajnc@kanardia.eu] *
* *
* Status: Open Source *
* *
* License: GPL - GNU General Public License *
* See 'COPYING.html' for more details about the license. *
* *
***************************************************************************/
#include <QDebug>
#include "Unit/Manager.h"
#include "XMLTags.h"
#include "XMLGaugeRoundAltitude.h"
namespace instrument {
// -------------------------------------------------------------------------
XMLGaugeRoundAltitude::XMLGaugeRoundAltitude(
const QDomElement& e,
QWidget *pParent
)
: XMLGaugeRound(e, pParent)
{
Q_ASSERT(m_vpScale.count() == 1);
Q_ASSERT(m_vpScale[0]->GetParameter()->GetName()==TAG_ALTITUDE);
unit::Manager* pM = unit::Manager::GetInstance();
m_vpScale[0]->EnableBoundScale(false);
m_bThreeNeedles = false;
bool bThird = (e.attribute(TAG_THIRD_NEEDLE)==TAG_YES);
if(bThird) {
int iUserKey = m_vpScale[0]->GetParameter()->GetUnitKeyUser();
if(iUserKey >= 0) {
if(pM->GetUnit(iUserKey)->GetSignature()=="feet")
m_bThreeNeedles = true;
}
}
// At this time we know if we have QNH frame.
// Set number of decimals ...
for(int i=0; i<m_vpFrame.count(); i++) {
if(m_vpFrame[i]->GetParameter()->GetName()==TAG_QNH) {
// Check units
int iUserKey = m_vpFrame[i]->GetParameter()->GetUnitKeyUser();
if(iUserKey >= 0) {
if(pM->GetUnit(iUserKey)->GetSignature()=="inHg") {
m_vpFrame[i]->SetDecimals(1);
}
}
break;
}
}
m_vpScale[0]->GetNeedle().SetType(Needle::tPointed);
m_needle3.SetType(Needle::tFatShort);
m_needle4.SetType(Needle::t10000);
}
// -------------------------------------------------------------------------
void XMLGaugeRoundAltitude::DrawForeground(QPainter& P)
{
XMLGaugeRound::DrawForeground(P);
float fU = m_vpScale[0]->GetParameter()->GetValueUser();
m_needle3.Draw(P, 90.0f - 36*fU/1000);
if(m_bThreeNeedles)
m_needle4.Draw(P, 90.0f - 36*fU/10000);
}
// -------------------------------------------------------------------------
void XMLGaugeRoundAltitude::ResizeBackground()
{
XMLGaugeRound::ResizeBackground();
const int iW = width();
const int iOff = 7*iW/100;
m_vpScale[0]->GetNeedle().SetSize(QSize(40*iW/100, 5), iOff);
m_needle3.SetSize(QSize(28*iW/100, 5*iW/100), iOff);
m_needle4.SetSize(QSize(46*iW/100, 7*iW/100), iOff);
}
// -------------------------------------------------------------------------
} // namespace
| 31.793814 | 77 | 0.467899 | jpoirier |
d7e4286d7ff4c1c5b13e9232815f4f983858b873 | 23,423 | cpp | C++ | LithiumGD/Cheats/Creator.cpp | ALEHACKsp/LithiumGD | 7f1e2c7da98e879830fbf9657c2618625c6daa5b | [
"MIT"
] | null | null | null | LithiumGD/Cheats/Creator.cpp | ALEHACKsp/LithiumGD | 7f1e2c7da98e879830fbf9657c2618625c6daa5b | [
"MIT"
] | null | null | null | LithiumGD/Cheats/Creator.cpp | ALEHACKsp/LithiumGD | 7f1e2c7da98e879830fbf9657c2618625c6daa5b | [
"MIT"
] | 1 | 2021-09-19T17:35:28.000Z | 2021-09-19T17:35:28.000Z | #include <Windows.h>
#include "Cheats.h"
#include "../Game/Game.h"
#include "../Game/Offsets.h"
void cCheats::CopyHack() {
static const char Patch1[] = { 0x90, 0x90 };
static const char Patch2[] = { 0x8B, 0xCA, 0x90 };
static const char Patch3[] = { 0xB0, 0x01, 0x90 };
static const char OriginalAddress1[] = { 0x75, 0x0E };
static const char OriginalAddress2[] = { 0x0F, 0x44, 0xCA };
static const char OriginalAddress3[] = { 0x0F, 0x95, 0xC0 };
if (Configuration.CopyHack) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address2), &Patch2, sizeof(Patch2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address3), &Patch3, sizeof(Patch3), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0);
}
}
void cCheats::NoCopyMark() {
static const char Patch1[] = { 0x2B, 0x87, 0xCC, 0x02, 0x00, 0x00 };
static const char Patch2[] = { 0xEB, 0x26 };
static const char OriginalAddress1[] = { 0x2B, 0x87, 0xD0, 0x02, 0x00, 0x00 };
static const char OriginalAddress2[] = { 0x74, 0x26 };
if (Configuration.NoCopyMark) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address2), &Patch2, sizeof(Patch2), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
}
}
void cCheats::UnlimitedObjects() {
static const char Patch[] = { 0xFF, 0xFF, 0xFF, 0x7F };
static const char OriginalAddresses[] = { 0x80, 0x38, 0x01, 0x00 };
if (Configuration.UnlimitedObjects) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address1), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address2), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address3), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address4), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address5), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address6), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address7), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address1), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address2), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address3), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address4), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address5), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address6), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address7), &OriginalAddresses, sizeof(OriginalAddresses), 0);
}
}
void cCheats::UnlimitedCustomObjects() {
static const char Patch1[] = { 0xEB };
static const char Patch2[] = { 0xEB };
static const char Patch3[] = { 0x90, 0x90 };
static const char OriginalAddress1[] = { 0x72 };
static const char OriginalAddress2[] = { 0x76 };
static const char OriginalAddress3[] = { 0x77, 0x3A };
if (Configuration.UnlimitedCustomObjects) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address2), &Patch2, sizeof(Patch2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address3), &Patch3, sizeof(Patch3), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0);
}
}
void cCheats::UnlimitedZoom() {
static const char Patch[] = { 0x90, 0x90, 0x90 };
static const char OriginalAddress1[] = { 0x0F, 0x2F, 0xC8 };
static const char OriginalAddress2[] = { 0x0F, 0x28, 0xC8 };
static const char OriginalAddress3[] = { 0x0F, 0x2F, 0xC8 };
static const char OriginalAddress4[] = { 0x0F, 0x28, 0xC8 };
if (Configuration.UnlimitedZoom) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address1), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address2), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address3), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address4), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address4), &OriginalAddress4, sizeof(OriginalAddress4), 0);
}
}
void cCheats::UnlimitedToolboxButtons() {
static const char Patch1[] = { 0x83, 0xF9, 0x01 };
static const char Patch2[] = { 0xB8, 0x01, 0x00, 0x00, 0x00 };
static const char Patch3[] = { 0x83, 0xF9, 0x7F };
static const char Patch4[] = { 0xB9, 0x7F, 0x00, 0x00, 0x00 };
static const char OriginalAddress1[] = { 0x83, 0xF9, 0x06 };
static const char OriginalAddress2[] = { 0xB8, 0x06, 0x00, 0x00, 0x00 };
static const char OriginalAddress3[] = { 0x83, 0xF9, 0x0C };
static const char OriginalAddress4[] = { 0xB9, 0x0C, 0x00, 0x00, 0x00 };
static const char OriginalAddress5[] = { 0x83, 0xF9, 0x02 };
static const char OriginalAddress6[] = { 0xB8, 0x02, 0x00, 0x00, 0x00 };
static const char OriginalAddress7[] = { 0x83, 0xF9, 0x03 };
static const char OriginalAddress8[] = { 0xB9, 0x03, 0x00, 0x00, 0x00 };
if (Configuration.UnlimitedToolboxButtons) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address2), &Patch2, sizeof(Patch2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address3), &Patch3, sizeof(Patch3), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address4), &Patch4, sizeof(Patch4), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address5), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address6), &Patch2, sizeof(Patch2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address7), &Patch3, sizeof(Patch3), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address8), &Patch4, sizeof(Patch4), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address4), &OriginalAddress4, sizeof(OriginalAddress4), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address5), &OriginalAddress5, sizeof(OriginalAddress5), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address6), &OriginalAddress6, sizeof(OriginalAddress6), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address7), &OriginalAddress7, sizeof(OriginalAddress7), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address8), &OriginalAddress8, sizeof(OriginalAddress8), 0);
}
}
void cCheats::VerifyHack() {
static const char Patch[] = { 0xEB };
static const char OriginalAddress1[] = { 0x74 };
if (Configuration.VerifyHack) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.VerifyHack.Address1), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.VerifyHack.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
}
}
void cCheats::HiddenSongs() {
static const char Patch1[] = { 0x90, 0x90 };
static const char Patch2[] = { 0x90, 0x90, 0x90 };
static const char OriginalAddress1[] = { 0x74, 0x2F };
static const char OriginalAddress2[] = { 0x0F, 0x4F, 0xC6 };
if (Configuration.HiddenSongs) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address2), &Patch2, sizeof(Patch2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address3), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address4), &Patch2, sizeof(Patch2), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address3), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address4), &OriginalAddress2, sizeof(OriginalAddress2), 0);
}
}
void cCheats::EditorLength() {
static const char Patch1[] = { 0x00, 0x60, 0xEA, 0x4B };
static const char Patch2[] = { 0x0F, 0x60, 0xEA, 0x4B };
static const char OriginalAddress1[] = { 0x00, 0x60, 0x6A, 0x48 };
static const char OriginalAddress2[] = { 0x80, 0x67, 0x6A, 0x48 };
if (Configuration.EditorLength) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address2), &Patch2, sizeof(Patch2), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
}
}
void cCheats::PlaceOver() {
static const char Patch1[] = { 0x8B, 0xC1, 0x90 };
static const char Patch2[] = { 0xE9, 0x23, 0x02, 0x00, 0x00, 0x90 };
static const char OriginalAddress1[] = { 0x0F, 0x48, 0xC1 };
static const char OriginalAddress2[] = { 0x0F, 0x8F, 0x22, 0x02, 0x00, 0x00 };
if (Configuration.PlaceOver) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address1), &Patch1, sizeof(Patch1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address2), &Patch2, sizeof(Patch2), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
}
}
void cCheats::AntiTestmode() {
static const char Patch[] = { 0xE9, 0xB7, 0x00, 0x00, 0x00, 0x90 };
static const char OriginalAddress1[] = { 0x0F, 0x84, 0xB6, 0x00, 0x00, 0x00 };
if (Configuration.AntiTestmode) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AntiTestmode.Address1), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AntiTestmode.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
}
}
void cCheats::RotationHack() {
static const char Patch[] = { 0xB8, 0x01, 0x00, 0x00, 0x00, 0x90 };
static const char OriginalAddress1[] = { 0x8B, 0x80, 0x00, 0x03, 0x00, 0x00 };
static const char OriginalAddress2[] = { 0x8B, 0x80, 0x00, 0x03, 0x00, 0x00 };
static const char OriginalAddress3[] = { 0x8B, 0x80, 0x00, 0x03, 0x00, 0x00 };
static const char OriginalAddress4[] = { 0x8B, 0x87, 0x00, 0x03, 0x00, 0x00 };
static const char OriginalAddress5[] = { 0x8B, 0x86, 0x00, 0x03, 0x00, 0x00 };
static const char OriginalAddress6[] = { 0x8B, 0x83, 0x00, 0x03, 0x00, 0x00 };
if (Configuration.RotationHack) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address1), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address2), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address3), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address4), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address5), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address6), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address4), &OriginalAddress4, sizeof(OriginalAddress4), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address5), &OriginalAddress5, sizeof(OriginalAddress5), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address6), &OriginalAddress6, sizeof(OriginalAddress6), 0);
}
}
void cCheats::FreeScroll() {
static const char Patch[] = { 0xEB };
static const char OriginalAddresses[] = { 0x77 };
if (Configuration.FreeScroll) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address1), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address2), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address3), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address4), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address1), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address2), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address3), &OriginalAddresses, sizeof(OriginalAddresses), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address4), &OriginalAddresses, sizeof(OriginalAddresses), 0);
}
}
void cCheats::NoEditorUI() {
static const char Patch[] = { 0xB3, 0x00, 0x90 };
static const char OriginalAddress1[] = { 0x0F, 0x44, 0xD9 };
if (Configuration.NoEditorUI) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoEditorUI.Address1), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoEditorUI.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
}
}
void cCheats::UnlimitedZOrder() {
static const char Patch[] = { 0x90, 0x90, 0x90 };
static const char OriginalAddress1[] = { 0x0F, 0x4C, 0xC1 };
static const char OriginalAddress2[] = { 0x0F, 0x4F, 0xC1 };
if (Configuration.UnlimitedZOrder) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address1), &Patch, sizeof(Patch), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address2), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0);
}
}
void cCheats::AbsoluteScaling() {
static const char Patch[] = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 };
static const char OriginalAddress1[] = { 0x56, 0xE8, 0xB1, 0xEA, 0xFF, 0xFF };
if (Configuration.AbsoluteScaling) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsoluteScaling.Address1), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsoluteScaling.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
}
}
void cCheats::AbsolutePosition() {
static const char Patch[] = { 0x90, 0x8B, 0xCE, 0x90, 0x90, 0x90 };
static const char OriginalAddress1[] = { 0x51, 0x8B, 0xCE, 0xFF, 0x50, 0x5C };
if (Configuration.AbsolutePosition) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsolutePosition.Address1), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsolutePosition.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
}
}
void cCheats::NoScaleSnap() {
static const char Patch[] = { 0xEB };
static const char OriginalAddress1[] = { 0x76 };
if (Configuration.NoScaleSnap) {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoScaleSnap.Address1), &Patch, sizeof(Patch), 0);
}
else {
WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoScaleSnap.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0);
}
} | 68.090116 | 180 | 0.745165 | ALEHACKsp |
d7e6e7c3da957da091e1315a75b44d07aab9edb2 | 190 | cpp | C++ | myblog/Cplusplus/004_pointer/demo3.cpp | WangBaobaoLOVE/WangBaobaoLOVE.github.io | e8e53475874193a929bbda247dd6a77da8950856 | [
"CC-BY-3.0"
] | null | null | null | myblog/Cplusplus/004_pointer/demo3.cpp | WangBaobaoLOVE/WangBaobaoLOVE.github.io | e8e53475874193a929bbda247dd6a77da8950856 | [
"CC-BY-3.0"
] | null | null | null | myblog/Cplusplus/004_pointer/demo3.cpp | WangBaobaoLOVE/WangBaobaoLOVE.github.io | e8e53475874193a929bbda247dd6a77da8950856 | [
"CC-BY-3.0"
] | null | null | null | #include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL;
cout << "ptr 的值是 " << ptr ;
if(ptr)
cout << false;
if(!ptr)
cout << true;
return 0;
} | 11.176471 | 30 | 0.505263 | WangBaobaoLOVE |
d7e97b217df8db666c383e0f903c2082b90a17bc | 1,063 | cpp | C++ | src/test/currenttime/main.cpp | xsjqqq123/treefrog-framework | da7cc2c4b277e4858ee7a6e5e7be7ce707642e00 | [
"BSD-3-Clause"
] | 1 | 2019-01-08T12:37:11.000Z | 2019-01-08T12:37:11.000Z | src/test/currenttime/main.cpp | dragondjf/treefrog-framework | b85df01fffab5a9bab94679376ec057ebc2293f5 | [
"BSD-3-Clause"
] | null | null | null | src/test/currenttime/main.cpp | dragondjf/treefrog-framework | b85df01fffab5a9bab94679376ec057ebc2293f5 | [
"BSD-3-Clause"
] | 2 | 2018-09-14T12:35:36.000Z | 2020-05-09T16:52:20.000Z | #include <QTest>
#include <QtCore>
#include <tglobal.h>
class TestDateTime : public QObject
{
Q_OBJECT
private slots:
void compare();
void benchQtCurrentDateTime();
void benchTfCurrentDateTime();
};
void TestDateTime::compare()
{
for (int i = 0; i < 3; ++i) {
QDateTime qt = QDateTime::currentDateTime();
QDateTime tf = Tf::currentDateTimeSec();
QCOMPARE(qt.date().year(), tf.date().year());
QCOMPARE(qt.date().month(), tf.date().month());
QCOMPARE(qt.date().day(), tf.date().day());
QCOMPARE(qt.time().hour(), tf.time().hour());
QCOMPARE(qt.time().minute(), tf.time().minute());
QCOMPARE(qt.time().second(), tf.time().second());
Tf::msleep(1500);
}
}
void TestDateTime::benchQtCurrentDateTime()
{
QBENCHMARK {
QDateTime dt = QDateTime::currentDateTime();
}
}
void TestDateTime::benchTfCurrentDateTime()
{
QBENCHMARK {
QDateTime dt = Tf::currentDateTimeSec();
}
}
QTEST_APPLESS_MAIN(TestDateTime)
#include "main.moc"
| 21.26 | 57 | 0.608655 | xsjqqq123 |
d7ebe3bb2f48c3bcca53fa9a86d38d65abbf85c6 | 2,011 | hpp | C++ | modules/memory/include/shard/memory/allocators/heap_allocator.hpp | ikimol/shard | 72a72dbebfd247d2b7b300136c489672960b37d8 | [
"MIT"
] | null | null | null | modules/memory/include/shard/memory/allocators/heap_allocator.hpp | ikimol/shard | 72a72dbebfd247d2b7b300136c489672960b37d8 | [
"MIT"
] | null | null | null | modules/memory/include/shard/memory/allocators/heap_allocator.hpp | ikimol/shard | 72a72dbebfd247d2b7b300136c489672960b37d8 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Miklos Molnar. All rights reserved.
#ifndef SHARD_MEMORY_HEAP_ALLOCATOR_HPP
#define SHARD_MEMORY_HEAP_ALLOCATOR_HPP
#include "shard/memory/allocator.hpp"
#include "shard/memory/utils.hpp"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
namespace shard {
namespace memory {
class heap_allocator : public allocator {
public:
heap_allocator() : allocator(0) {}
void* allocate(std::size_t size, std::size_t align) override {
assert(size != 0);
auto total_size = size + header_size;
auto ptr = std::malloc(total_size);
// check if allocation was successful
if (!ptr) {
return nullptr;
}
// clear the bytes in the allocated memory block
std::memset(ptr, '\0', total_size);
// padding includes the size of the allocation header, hence it is
// subtracted from the aligned address
auto header = reinterpret_cast<allocation_header*>(ptr);
header->size = total_size;
auto aligned_address = add(ptr, header_size);
// check that the alignments are ok (should always be the case)
assert(is_aligned(header));
assert(is_aligned(aligned_address, align));
m_used_memory += total_size;
++m_allocation_count;
return aligned_address;
}
void deallocate(void* ptr) override {
assert(ptr);
// get the header at the start of the allocated memory
auto header = reinterpret_cast<allocation_header*>(sub(ptr, header_size));
m_used_memory -= header->size;
--m_allocation_count;
// return the memory
std::free(header);
}
private:
struct allocation_header {
std::size_t size;
};
private:
static constexpr auto header_size = sizeof(allocation_header);
};
} // namespace memory
// bring symbols into parent namespace
using memory::heap_allocator;
} // namespace shard
#endif // SHARD_MEMORY_HEAP_ALLOCATOR_HPP
| 24.228916 | 82 | 0.660368 | ikimol |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.