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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3fc2a174476f2c36ae82f3a0eb8634353eaaf27 | 11,531 | cpp | C++ | arduino/libraries/Button2/src/Button2.cpp | Mchaney3/AXSResearch | 6843b833a95010014bb3113ca59dda3b5e1c3663 | [
"Unlicense"
] | null | null | null | arduino/libraries/Button2/src/Button2.cpp | Mchaney3/AXSResearch | 6843b833a95010014bb3113ca59dda3b5e1c3663 | [
"Unlicense"
] | null | null | null | arduino/libraries/Button2/src/Button2.cpp | Mchaney3/AXSResearch | 6843b833a95010014bb3113ca59dda3b5e1c3663 | [
"Unlicense"
] | null | null | null | /////////////////////////////////////////////////////////////////
/*
Button2.cpp - Arduino Library to simplify working with buttons.
Created by Lennart Hennigs.
*/
/////////////////////////////////////////////////////////////////
#include "Button2.h"
/////////////////////////////////////////////////////////////////
// initalize static counter
int Button2::_nextID = 0;
/////////////////////////////////////////////////////////////////
// default contructor
Button2::Button2() {
pin = UNDEFINED_PIN;
id = _nextID++;
}
/////////////////////////////////////////////////////////////////
// contructor
Button2::Button2(byte attachTo, byte buttonMode /* = INPUT_PULLUP */, boolean isCapacitive /* = false */, boolean activeLow /* = true */) {
begin(attachTo, buttonMode, isCapacitive, activeLow);
}
/////////////////////////////////////////////////////////////////
void Button2::begin(byte attachTo, byte buttonMode /* = INPUT_PULLUP */, boolean isCapacitive /* = false */, boolean activeLow /* = true */) {
pin = attachTo;
longclick_detected_counter = 0;
longclick_detected_retriggerable = false;
_pressedState = activeLow ? LOW : HIGH;
setDebounceTime(DEBOUNCE_MS);
setLongClickTime(LONGCLICK_MS);
setDoubleClickTime(DOUBLECLICK_MS);
if (!isCapacitive) {
if (attachTo != VIRTUAL_PIN) {
pinMode(attachTo, buttonMode);
}
} else {
is_capacitive = true;
}
// state = activeLow ? HIGH : LOW;
state = _getState();
prev_state = state ;
}
/////////////////////////////////////////////////////////////////
void Button2::setDebounceTime(unsigned int ms) {
debounce_time_ms = ms;
}
/////////////////////////////////////////////////////////////////
void Button2::setLongClickTime(unsigned int ms) {
longclick_time_ms = ms;
}
/////////////////////////////////////////////////////////////////
void Button2::setDoubleClickTime(unsigned int ms) {
doubleclick_time_ms = ms;
}
/////////////////////////////////////////////////////////////////
unsigned int Button2::getDebounceTime() const {
return debounce_time_ms;
}
/////////////////////////////////////////////////////////////////
unsigned int Button2::getLongClickTime() const {
return longclick_time_ms;
}
/////////////////////////////////////////////////////////////////
unsigned int Button2::getDoubleClickTime() const {
return doubleclick_time_ms;
}
/////////////////////////////////////////////////////////////////
byte Button2::getPin() const {
return pin;
}
/////////////////////////////////////////////////////////////////
void Button2::setButtonStateFunction(StateCallbackFunction f) {
get_state_cb = f;
}
/////////////////////////////////////////////////////////////////
bool Button2::operator == (Button2 &rhs) {
return (this == &rhs);
}
/////////////////////////////////////////////////////////////////
void Button2::setLongClickDetectedRetriggerable(bool retriggerable) {
longclick_detected_retriggerable = retriggerable;
}
/////////////////////////////////////////////////////////////////
void Button2::setChangedHandler(CallbackFunction f) {
change_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setPressedHandler(CallbackFunction f) {
pressed_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setReleasedHandler(CallbackFunction f) {
released_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setClickHandler(CallbackFunction f) {
click_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setTapHandler(CallbackFunction f) {
tap_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setLongClickHandler(CallbackFunction f) {
long_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setDoubleClickHandler(CallbackFunction f) {
double_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setTripleClickHandler(CallbackFunction f) {
triple_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button2::setLongClickDetectedHandler(CallbackFunction f) {
longclick_detected_cb = f;
}
/////////////////////////////////////////////////////////////////
unsigned int Button2::wasPressedFor() const {
return down_time_ms;
}
/////////////////////////////////////////////////////////////////
boolean Button2::isPressed() const {
return (state == _pressedState);
}
/////////////////////////////////////////////////////////////////
boolean Button2::isPressedRaw() {
return (_getState() == _pressedState);
}
/////////////////////////////////////////////////////////////////
byte Button2::getNumberOfClicks() const {
return click_count;
}
/////////////////////////////////////////////////////////////////
clickType Button2::getType() const {
return last_click_type;
}
/////////////////////////////////////////////////////////////////
int Button2::getID() const {
return id;
}
/////////////////////////////////////////////////////////////////
void Button2::setID(int newID) {
id = newID;
}
/////////////////////////////////////////////////////////////////
String Button2::clickToString(clickType type) const {
if (type == single_click) return "click";
if (type == double_click) return "double click";
if (type == long_click) return "long click";
if (type == triple_click) return "triple click";
return "empty";
}
/////////////////////////////////////////////////////////////////
bool Button2::wasPressed() const {
return was_pressed;
}
/////////////////////////////////////////////////////////////////
clickType Button2::read(bool keepState /* = false */) {
if (!keepState) {
clickType res = last_click_type;
last_click_type = empty;
was_pressed = false;
return res;
}
return last_click_type;
}
/////////////////////////////////////////////////////////////////
clickType Button2::wait(bool keepState /* = false */) {
while(!wasPressed()) {
loop();
}
return read(keepState);
}
/////////////////////////////////////////////////////////////////
void Button2::waitForClick(bool keepState /* = false */) {
do {
while(!wasPressed()) {
loop();
}
} while(read() != single_click);
}
/////////////////////////////////////////////////////////////////
void Button2::waitForDouble(bool keepState /* = false */) {
do {
while(!wasPressed()) {
loop();
}
} while(read() != double_click);
}
/////////////////////////////////////////////////////////////////
void Button2::waitForTriple(bool keepState /* = false */) {
do {
while(!wasPressed()) {
loop();
}
} while(read() != triple_click);
}
/////////////////////////////////////////////////////////////////
void Button2::waitForLong(bool keepState /* = false */) {
do {
while(!wasPressed()) {
loop();
}
} while(read() != long_click);
}
/////////////////////////////////////////////////////////////////
byte Button2::_getState() {
if (get_state_cb != NULL) return get_state_cb();
if (!is_capacitive) {
return digitalRead(pin);
} else {
#if defined(ARDUINO_ARCH_ESP32)
int capa = touchRead(pin);
return capa < CAPACITIVE_TOUCH_THRESHOLD ? LOW : HIGH;
#endif
}
return state;
}
/////////////////////////////////////////////////////////////////
void Button2::loop() {
if (pin != UNDEFINED_PIN) {
unsigned long now = millis();
prev_state = state;
state = _getState();
// is button pressed?
if (state == _pressedState) {
// is it pressed now?
if (prev_state != _pressedState) {
down_ms = now;
pressed_triggered = false;
click_ms = down_ms;
// trigger pressed event (after debounce has passed)
} else if (!pressed_triggered && (now - down_ms >= debounce_time_ms)) {
pressed_triggered = true;
click_count++;
if (change_cb != NULL) change_cb (*this);
if (pressed_cb != NULL) pressed_cb (*this);
}
// is a longpress detected callback defined?
if (longclick_detected_cb != NULL) {
// check to see that the longclick_ms period has been exceeded and call the appropriate callback
bool longclick_period_detected = now - down_ms >= (longclick_time_ms * (longclick_detected_counter + 1));
if (longclick_period_detected && !longclick_detected_reported) {
longclick_detected_reported = true;
longclick_detected = true;
if (longclick_detected_retriggerable) {
// increate the counter and reset the "reported" flag (as the counter will stop the false trigger)
longclick_detected_counter++;
longclick_detected_reported = false;
}
if (longclick_detected_cb != NULL) longclick_detected_cb(*this);
}
}
// is the button released?
} else if (state != _pressedState) {
// is it released right now?
if (prev_state == _pressedState) {
down_time_ms = now - down_ms;
// is it beyond debounce time?
if (down_time_ms >= debounce_time_ms) {
last_click_type = single_click;
// trigger release
if (change_cb != NULL) change_cb (*this);
if (released_cb != NULL) released_cb (*this);
// trigger tap
if (tap_cb != NULL) tap_cb (*this);
// was it a longclick? (preceeds single / double / triple clicks)
if (down_time_ms >= longclick_time_ms) {
longclick_detected = true;
}
}
// is the button released and the time has passed for multiple clicks?
} else if (now - click_ms > doubleclick_time_ms) {
// was there a longclick?
if (longclick_detected) {
// was it part of a combination?
if (click_count == 1) {
last_click_type = long_click;
if (long_cb != NULL) long_cb (*this);
was_pressed = true;
}
longclick_detected = false;
longclick_detected_reported = false;
longclick_detected_counter = 0;
// determine the number of single clicks
} else if (click_count > 0) {
switch (click_count) {
case 1:
last_click_type = single_click;
if (click_cb != NULL) click_cb (*this);
break;
case 2:
last_click_type = double_click;
if (double_cb != NULL) double_cb (*this);
break;
case 3:
last_click_type = triple_click;
if (triple_cb != NULL) triple_cb (*this);
break;
}
was_pressed = true;
}
// clean up
click_count = 0;
click_ms = 0;
}
}
}
}
/////////////////////////////////////////////////////////////////
void Button2::reset() {
pin = UNDEFINED_PIN;
click_count = 0;
last_click_type = empty;
down_time_ms = 0;
pressed_triggered = false;
longclick_detected = false;
longclick_detected_reported = false;
longclick_detected_counter = 0;
pressed_cb = NULL;
released_cb = NULL;
change_cb = NULL;
tap_cb = NULL;
click_cb = NULL;
long_cb = NULL;
double_cb = NULL;
triple_cb = NULL;
longclick_detected_cb = NULL;
}
/////////////////////////////////////////////////////////////////
| 27.586124 | 144 | 0.471338 | Mchaney3 |
a3fe874a4d7150056180b581459429533fed4e75 | 15,430 | cc | C++ | src/Circle.cc | DottorZini/Clothoids | 5dc563ae56044edb3efee1f3ca37501afa184328 | [
"BSD-2-Clause"
] | null | null | null | src/Circle.cc | DottorZini/Clothoids | 5dc563ae56044edb3efee1f3ca37501afa184328 | [
"BSD-2-Clause"
] | null | null | null | src/Circle.cc | DottorZini/Clothoids | 5dc563ae56044edb3efee1f3ca37501afa184328 | [
"BSD-2-Clause"
] | null | null | null | /*--------------------------------------------------------------------------*\
| |
| Copyright (C) 2017 |
| |
| , __ , __ |
| /|/ \ /|/ \ |
| | __/ _ ,_ | __/ _ ,_ |
| | \|/ / | | | | \|/ / | | | |
| |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ |
| /| /| |
| \| \| |
| |
| Enrico Bertolazzi |
| Dipartimento di Ingegneria Industriale |
| Universita` degli Studi di Trento |
| email: enrico.bertolazzi@unitn.it |
| |
\*--------------------------------------------------------------------------*/
#include "Circle.hh"
#include "CubicRootsFlocke.hh"
#include <cmath>
namespace G2lib {
using namespace std ;
/*\
| ____ _ _ _
| / ___(_)_ __ ___| | ___ / \ _ __ ___
| | | | | '__/ __| |/ _ \ / _ \ | '__/ __|
| | |___| | | | (__| | __// ___ \| | | (__
| \____|_|_| \___|_|\___/_/ \_\_| \___|
\*/
bool
CircleArc::build_G1( real_type _x0,
real_type _y0,
real_type _theta0,
real_type _x1,
real_type _y1 ) {
real_type dx = _x1 - _x0 ;
real_type dy = _y1 - _y0 ;
real_type d = hypot( dx, dy );
if ( d > 0 ) {
real_type th = atan2( dy, dx ) - _theta0 ;
x0 = _x0 ;
y0 = _y0 ;
theta0 = _theta0 ;
k = 2*sin(th)/d ;
L = d/Sinc(th);
return true ;
}
return false ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool
CircleArc::build_3P( real_type _x0,
real_type _y0,
real_type _x1,
real_type _y1,
real_type _x2,
real_type _y2 ) {
real_type dxa = _x1 - _x0 ;
real_type dya = _y1 - _y0 ;
real_type dxb = _x2 - _x1 ;
real_type dyb = _y2 - _y1 ;
real_type La = hypot(dya,dxa) ;
real_type Lb = hypot(dyb,dxb) ;
real_type cosom = (dxa*dxb + dya*dyb)/(La*Lb) ;
if ( cosom > 1 ) cosom = 1 ;
else if ( cosom < -1 ) cosom = -1 ;
real_type omega = acos(cosom) ;
real_type alpha = omega - atan2(Lb*sin(omega),La+Lb*cos(omega)) ;
real_type dxc = _x2 - _x0 ;
real_type dyc = _y2 - _y0 ;
real_type Lc = hypot(dyc,dxc) ;
real_type cosal = (dxa*dxc + dya*dyc)/(La*Lc) ;
if ( cosal > 1 ) cosal = 1 ;
else if ( cosal < -1 ) cosal = -1 ;
alpha += acos(cosal) ;
if ( dxa*dyb > dya*dxb ) alpha = -alpha ;
real_type _theta0 = atan2( dyc, dxc ) + alpha ;
return build_G1( _x0, _y0, _theta0, _x2, _y2 );
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::thetaMinMax( real_type & thMin, real_type & thMax ) const {
thMin = theta0 ;
thMax = theta0 + L * k ;
if ( thMax < thMin ) std::swap( thMin, thMax ) ;
return thMax-thMin ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::X( real_type s ) const {
real_type sk = (s*k)/2 ;
return x0+s*Sinc(sk)*cos(theta0+sk);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::Y( real_type s ) const {
real_type sk = (s*k)/2 ;
return x0+s*Sinc(sk)*sin(theta0+sk);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::X_D( real_type s ) const {
return cos(theta0+s*k);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::Y_D( real_type s ) const {
return sin(theta0+s*k);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::X_DD( real_type s ) const {
return -k*sin(theta0+s*k);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::Y_DD( real_type s ) const {
return k*cos(theta0+s*k);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::X_DDD( real_type s ) const {
return -(k*k)*cos(theta0+s*k);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::Y_DDD( real_type s ) const {
return -(k*k)*sin(theta0+s*k);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::XY( real_type s,
real_type & x,
real_type & y ) const {
real_type sk = (s*k)/2 ;
real_type tmp = s*Sinc(sk);
x = x0+tmp*cos(theta0+sk);
y = y0+tmp*sin(theta0+sk);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::XY( real_type s,
real_type t,
real_type & x,
real_type & y ) const {
real_type sk = (s*k)/2 ;
real_type tmp = s*Sinc(sk);
real_type th = theta(s);
real_type th0 = theta0+sk;
x = x0+tmp*cos(th0)-t*sin(th);
y = y0+tmp*sin(th0)+t*cos(th);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::TG( real_type s, real_type & tx, real_type & ty ) const {
real_type th = theta(s);
tx = cos(th);
ty = sin(th);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::NOR( real_type s, real_type & nx, real_type & ny ) const {
real_type th = theta(s);
nx = -sin(th);
ny = cos(th);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::NOR_D( real_type s, real_type & nx_D, real_type & ny_D ) const {
real_type th = theta(s);
nx_D = -cos(th)*k;
ny_D = -sin(th)*k;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::NOR_DD( real_type s, real_type & nx_DD, real_type & ny_DD ) const {
real_type th = theta(s);
real_type k2 = k*k ;
real_type S = sin(th);
real_type C = cos(th);
nx_DD = S*k2;
ny_DD = -C*k2;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::NOR_DDD( real_type s, real_type & nx_DDD, real_type & ny_DDD ) const {
real_type th = theta(s);
real_type S = sin(th);
real_type C = cos(th);
real_type k3 = k*k*k;
nx_DDD = C*k3 ;
ny_DDD = S*k3 ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval( real_type s,
real_type & x,
real_type & y ) const {
real_type sk = (s*k)/2 ;
real_type LS = s*Sinc(sk);
real_type arg = theta0+sk ;
x = x0+LS*cos(arg);
y = y0+LS*sin(arg);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval_D( real_type s,
real_type & x_D,
real_type & y_D ) const {
real_type arg = theta0+s*k;
x_D = cos(arg);
y_D = sin(arg);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval_DD( real_type s,
real_type & x_DD,
real_type & y_DD ) const {
real_type arg = theta0+s*k;
x_DD = -k*sin(arg);
y_DD = k*cos(arg);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval_DDD( real_type s,
real_type & x_DDD,
real_type & y_DDD ) const {
real_type arg = theta0+s*k;
real_type k2 = k*k;
x_DDD = -k2*cos(arg);
y_DDD = -k2*sin(arg);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval( real_type s,
real_type t,
real_type & x,
real_type & y ) const {
real_type sk = (s*k)/2 ;
real_type LS = s*Sinc(sk);
real_type arg = theta0+sk ;
real_type nx, ny ;
NOR( s, nx, ny );
x = x0 + LS*cos(arg) + nx * t ;
y = y0 + LS*sin(arg) + ny * t ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval_D( real_type s,
real_type t,
real_type & x_D,
real_type & y_D ) const {
real_type arg = theta0+s*k;
real_type nx_D, ny_D ;
NOR_D( s, nx_D, ny_D );
x_D = cos(arg)+t*nx_D;
y_D = sin(arg)+t*ny_D;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval_DD( real_type s,
real_type t,
real_type & x_DD,
real_type & y_DD ) const {
real_type arg = theta0+s*k;
real_type nx_DD, ny_DD ;
NOR_DD( s, nx_DD, ny_DD );
x_DD = -k*sin(arg)+t*nx_DD;
y_DD = k*cos(arg)+t*ny_DD;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::eval_DDD( real_type s,
real_type t,
real_type & x_DDD,
real_type & y_DDD ) const {
real_type arg = theta0+s*k;
real_type k2 = k*k;
real_type nx_DDD, ny_DDD ;
NOR_DDD( s, nx_DDD, ny_DDD );
x_DDD = -k2*cos(arg)+t*nx_DDD;
y_DDD = -k2*sin(arg)+t*ny_DDD;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::trim( real_type s_begin, real_type s_end ) {
real_type x, y ;
eval( s_begin, x, y ) ;
theta0 += s_begin * k ;
L = s_end - s_begin ;
x0 = x ;
y0 = y ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::rotate( real_type angle, real_type cx, real_type cy ) {
real_type dx = x0 - cx ;
real_type dy = y0 - cy ;
real_type C = cos(angle) ;
real_type S = sin(angle) ;
real_type ndx = C*dx - S*dy ;
real_type ndy = C*dy + S*dx ;
x0 = cx + ndx ;
y0 = cy + ndy ;
theta0 += angle ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::scale( real_type s ) {
k /= s ;
L *= s ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::reverse() {
theta0 = theta0 + m_pi ;
if ( theta0 > m_pi ) theta0 -= 2*m_pi ;
k = -k ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
real_type
CircleArc::closestPoint( real_type qx,
real_type qy,
real_type & X,
real_type & Y,
real_type & S ) const {
S = projectPointOnCircle( x0, y0, cos(theta0), sin(theta0), k, L, qx, qy );
if ( S < 0 || S > L ) { // minimum distance at the border
eval( L, X, Y );
// costruisco piano
real_type nx = X-x0 ;
real_type ny = Y-y0 ;
real_type dx = 2*qx-(x0+X) ;
real_type dy = 2*qy-(y0+Y) ;
if ( nx*dx + ny*dy > 0 ) {
S = L ;
} else {
S = 0 ;
X = x0 ;
Y = y0 ;
}
} else {
eval( S, X, Y );
}
return hypot(qx-X,qy-Y) ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::findST( real_type x,
real_type y,
real_type & s,
real_type & t ) const {
real_type X, Y, nx, ny ;
s = projectPointOnCircle( x0, y0, cos(theta0), sin(theta0), k, L, x, y );
eval( s, X, Y );
NOR( s, nx, ny );
t = nx*(x-X) + ny*(y-Y);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void
CircleArc::changeCurvilinearOrigin( real_type new_s0, real_type newL ) {
real_type new_x0, new_y0 ;
eval( new_s0, new_x0, new_y0 ) ;
x0 = new_x0 ;
y0 = new_y0 ;
theta0 += k*new_s0 ;
L = newL ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//! get the bounding box triangle (if angle variation less that pi/3)
bool
CircleArc::bbTriangle( real_type p0[2],
real_type p1[2],
real_type p2[2] ) const {
real_type dtheta = L * k ;
bool ok = std::abs(dtheta) <= m_pi/3 ;
if ( ok ) {
p0[0] = x0 ; p0[1] = y0 ;
eval( L, p2[0], p2[1] );
p1[0] = (p0[0]+p2[0])/2 ;
p1[1] = (p0[1]+p2[1])/2 ;
real_type nx = p0[1]-p2[1] ;
real_type ny = p2[0]-p0[0] ;
real_type tg = tan(dtheta/2)/2;
p1[0] -= nx * tg ;
p1[1] -= ny * tg ;
}
return ok ;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int_type
CircleArc::toNURBS( real_type knots[],
real_type Poly[],
bool get_size ) const {
real_type dtheta = L*k ;
int_type ns = int_type(std::floor(3*std::abs(dtheta)/m_pi)) ;
if ( ns < 1 ) ns = 1 ;
if ( get_size ) return 1+2*ns;
real_type th = dtheta/(2*ns) ;
real_type w = cos(th) ;
real_type tg = tan(th)/2;
real_type p0[2], p2[2] ;
p0[0] = x0 ; p0[1] = y0 ;
knots[0] = knots[1] = knots[2] = 0 ;
Poly[0] = p0[0] ;
Poly[1] = p0[1] ;
Poly[2] = 1 ;
real_type s = 0 ;
real_type ds = L/ns ;
int_type kk = 0 ;
for ( int_type i = 0 ; i < ns ; ++i ) {
s += ds ;
eval( s, p2[0], p2[1] );
real_type nx = p0[1]-p2[1] ;
real_type ny = p2[0]-p0[0] ;
real_type xm = (p0[0]+p2[0])/2 ;
real_type ym = (p0[1]+p2[1])/2 ;
++kk;
Poly[kk*3+0] = w*(xm - nx * tg) ;
Poly[kk*3+1] = w*(ym - ny * tg) ;
Poly[kk*3+2] = w ;
++kk;
Poly[kk*3+0] = p2[0] ;
Poly[kk*3+1] = p2[1] ;
Poly[kk*3+2] = 1 ;
knots[kk+1] = i+1 ;
knots[kk+2] = i+1 ;
p0[0] = p2[0] ;
p0[1] = p2[1] ;
}
knots[kk+3] = ns ;
return 1+2*ns;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::ostream &
operator << ( std::ostream & stream, CircleArc const & c ) {
stream << "x0 = " << c.x0
<< "\ny0 = " << c.y0
<< "\ntheta0 = " << c.theta0
<< "\nk = " << c.k
<< "\nL = " << c.L
<< "\n" ;
return stream ;
}
}
// EOF: Circle.cc
| 28.311927 | 83 | 0.358652 | DottorZini |
a3feb5ac74dcb3f04003fceb6fbfead6c66660b5 | 458 | cpp | C++ | src/file.cpp | jw-develop/bit-chess | ffb80dd65f798b60feb180f552dae90fb776c55e | [
"MIT"
] | null | null | null | src/file.cpp | jw-develop/bit-chess | ffb80dd65f798b60feb180f552dae90fb776c55e | [
"MIT"
] | null | null | null | src/file.cpp | jw-develop/bit-chess | ffb80dd65f798b60feb180f552dae90fb776c55e | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2013-2016 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
#include "file.h"
namespace pulse {
const std::array<int, File::VALUES_SIZE> File::values = {
a, b, c, d, e, f, g, h
};
bool File::isValid(int file) {
switch (file) {
case a:
case b:
case c:
case d:
case e:
case f:
case g:
case h:
return true;
default:
return false;
}
}
}
| 13.878788 | 69 | 0.611354 | jw-develop |
430130c297d0e143a7ac637e729e58e765cd04ea | 3,377 | cpp | C++ | Atcoder/AGC038/F.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | Atcoder/AGC038/F.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | Atcoder/AGC038/F.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | /*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)5e18;
const int MOD=998244353;
int _abs(int x){return x<0 ? -x : x;}
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=mul(x,y);}
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=500005;
const int M=2000005;
int S,T,tot=0;
namespace Flow{
int e=0,first[N],cur[N],nxt[M],point[M],w[M];
void add_edge(int x,int y,int z){
point[e]=y; nxt[e]=first[x];
w[e]=z; first[x]=e++;
}
void ADD(int x,int y,int z){add_edge(x,y,z); add_edge(y,x,0);}
int dep[N],vis[N];
bool bfs(){
memset(vis,0,sizeof(vis));
queue<int> q;
q.push(S); vis[S]=1; dep[S]=0;
while(!q.empty()){
int u=q.front(); q.pop();
for(int i=first[u];i!=-1;i=nxt[i])if(w[i]){
int to=point[i]; if(vis[to]) continue;
dep[to]=dep[u]+1; vis[to]=1; q.push(to);
}
}
return vis[T];
}
int dfs(int u,int flow){
if(u==T) return flow;
int ret=flow;
for(int &i=cur[u];i!=-1;i=nxt[i]){
int to=point[i];
if(!w[i]||dep[to]!=dep[u]+1) continue;
int tmp=dfs(to,min(ret,w[i]));
ret-=tmp; w[i]-=tmp; w[i^1]+=tmp;
if(!ret) break;
}
return flow-ret;
}
int Dinic(){
int ret=0;
while(bfs()){
for(int i=1;i<=tot;i++) cur[i]=first[i];
ret+=dfs(S,inf);
}
return ret;
}
void init(){
memset(first,-1,sizeof(first));
}
}
int n,p[N],q[N],idp[N],idq[N];
int vis[N];
int main()
{
n=read();
for(int i=1;i<=n;i++) p[i]=read()+1;
for(int i=1;i<=n;i++) q[i]=read()+1;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++) if(!vis[i]){
int x=i; tot++;
while(!vis[x]) vis[x]=1,idp[x]=tot,x=p[x];
}
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++) if(!vis[i]){
int x=i; tot++;
while(!vis[x]) vis[x]=1,idq[x]=tot,x=q[x];
}
//for(int i=1;i<=n;i++) out(i),out(idp[i]),outln(idq[i]);
S=++tot; T=++tot;
int ans=n; Flow::init();
for(int i=1;i<=n;i++){
if(p[i]!=q[i]){
if(p[i]==i) Flow::ADD(idq[i],T,1);
else if(q[i]==i) Flow::ADD(S,idp[i],1);
else Flow::ADD(idq[i],idp[i],1);
}
else if(p[i]!=i) Flow::ADD(idp[i],idq[i],1),Flow::ADD(idq[i],idp[i],1);
else ans--;
}
cout<<ans-Flow::Dinic()<<endl;
return 0;
} | 29.622807 | 98 | 0.491857 | jinzhengyu1212 |
4305dfad6c9432e9fcaef8022c5aa95a1c4a86e5 | 1,364 | hpp | C++ | include/eepp/version.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | include/eepp/version.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | null | null | null | include/eepp/version.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #ifndef EE_VERSION_HPP
#define EE_VERSION_HPP
#include <eepp/config.hpp>
#include <string>
#define EEPP_MAJOR_VERSION 2
#define EEPP_MINOR_VERSION 3
#define EEPP_PATCH_LEVEL 0
#define EEPP_CODENAME "Anāgāmin"
/** The compiled version of the library */
#define EEPP_VERSION( x ) \
{ \
( x )->major = EEPP_MAJOR_VERSION; \
( x )->minor = EEPP_MINOR_VERSION; \
( x )->patch = EEPP_PATCH_LEVEL; \
}
#define EEPP_VERSIONNUM( X, Y, Z ) ( (X)*1000 + (Y)*100 + ( Z ) )
#define EEPP_COMPILEDVERSION \
EEPP_VERSIONNUM( EEPP_MAJOR_VERSION, EEPP_MINOR_VERSION, EEPP_PATCH_LEVEL )
#define EEPP_VERSION_ATLEAST( X, Y, Z ) ( EEPP_COMPILEDVERSION >= EEPP_VERSIONNUM( X, Y, Z ) )
namespace EE {
class EE_API Version {
public:
Uint8 major; /**< major version */
Uint8 minor; /**< minor version */
Uint8 patch; /**< update version */
/** @return The linked version of the library */
static Version getVersion();
/** @return The linked version number of the library */
static Uint32 getVersionNum();
/** @return The library version name: "eepp version major.minor.patch" */
static std::string getVersionName();
/** @return The version codename */
static std::string getCodename();
/** @return The build time of the library */
static std::string getBuildTime();
};
} // namespace EE
#endif
| 25.259259 | 94 | 0.670821 | jayrulez |
430d5c6dc6cee51f1fce3bc6ecabafe7d6c03d14 | 10,065 | cxx | C++ | RAW/RAWDatarec/AliRawReaderChain.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | RAW/RAWDatarec/AliRawReaderChain.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | RAW/RAWDatarec/AliRawReaderChain.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
///
/// This is a class for reading raw data from a root chain.
/// There are two constructors available - one from a text file containing the
/// list of root raw-data files to be processed and one directly from
/// TFileCollection.
///
/// cvetan.cheshkov@cern.ch 29/07/2008
///
///////////////////////////////////////////////////////////////////////////////
#include <TChain.h>
#include <TFileCollection.h>
#include <TEntryList.h>
#include "TGridCollection.h"
#include <TPluginManager.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TFile.h>
#include <TKey.h>
#include <TGrid.h>
#include <TGridResult.h>
#include "AliRawReaderChain.h"
#include "AliRawVEvent.h"
#include "AliLog.h"
ClassImp(AliRawReaderChain)
TString AliRawReaderChain::fgSearchPath = "/alice/data";
AliRawReaderChain::AliRawReaderChain() :
AliRawReaderRoot(),
fChain(NULL)
{
// default constructor
}
AliRawReaderChain::AliRawReaderChain(const char* fileName) :
AliRawReaderRoot(),
fChain(NULL)
{
// create raw-reader objects which takes as an input a root chain
// either from the file list found in 'fileName' (IsCollection = true)
// or from entry list found in 'filename' (IsCollection = false)
// The entry-list syntax follows root convetion: filename.root/listname
fChain = new TChain("RAW");
TString fileNameStr = fileName;
if (fileNameStr.EndsWith(".xml")) {
TGridCollection *collection = NULL;
TPluginManager* pluginManager = gROOT->GetPluginManager();
TPluginHandler* pluginHandler = pluginManager->FindHandler("TGridCollection", "alice");
if (!pluginHandler) {
pluginManager->AddHandler("TGridCollection", "alice",
"AliXMLCollection", "ANALYSISalice", "AliXMLCollection(const char*)");
pluginHandler = pluginManager->FindHandler("TGridCollection", "alice");
}
gSystem->Load("libANALYSIS");
if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
collection = (TGridCollection*)pluginHandler->ExecPlugin(1,fileNameStr.Data());
}
else {
fIsValid = kFALSE;
return;
}
collection->Reset();
Bool_t elistsExist = kFALSE;
TEntryList *elist = new TEntryList();
while (collection->Next()) {
fChain->Add(collection->GetTURL(""));
TEntryList *list = (TEntryList *)collection->GetEntryList("");
if (list) {
list->SetTreeName("RAW");
list->SetFileName(collection->GetTURL(""));
elist->Add(list);
elistsExist = kTRUE;
}
}
if (elistsExist) {
fChain->SetEntryList(elist,"ne");
}
else {
Info("AliRawReaderChain", "no entry lists found in %s. Using all entries", fileNameStr.Data());
delete elist;
}
}
else if (fileNameStr.EndsWith(".root")) {
TDirectory* dir = gDirectory;
TFile *listFile = TFile::Open(fileNameStr.Data());
dir->cd();
if (!listFile || !listFile->IsOpen()) {
Error("AliRawReaderChain", "could not open file %s", fileNameStr.Data());
fIsValid = kFALSE;
return;
}
TEntryList *elist = NULL;
TKey *key = NULL;
TIter nextkey(listFile->GetListOfKeys());
while ((key=(TKey*)nextkey())){
if (strcmp("TEntryList", key->GetClassName())==0){
elist = (TEntryList*)key->ReadObj();
}
}
if (!elist) {
Error("AliRawReaderChain", "no TEntryList found in %s", fileNameStr.Data());
fIsValid = kFALSE;
return;
}
TEntryList *templist = NULL;
TList *elists = elist->GetLists();
TIter next(elists);
while((templist = (TEntryList*)next())){
Info("AliRawReaderChain", "%s added to the chain", templist->GetFileName());
fChain->Add(templist->GetFileName());
}
fChain->SetEntryList(elist,"ne");
}
else {
TFileCollection collection("RAW",
"Collection with raw-data files",
fileNameStr.Data());
if (!fChain->AddFileInfoList((TCollection*)(collection.GetList()))) {
Error("AliRawReaderChain","Bad file list in collection, the chain is empty");
fIsValid = kFALSE;
return;
}
}
fChain->SetBranchStatus("*",1);
fChain->SetBranchAddress("rawevent",&fEvent,&fBranch);
}
AliRawReaderChain::AliRawReaderChain(TFileCollection *collection) :
AliRawReaderRoot(),
fChain(NULL)
{
// create raw-reader objects which takes as an input a root chain
// from a root file collection
fChain = new TChain("RAW");
if (!fChain->AddFileInfoList((TCollection*)(collection->GetList()))) {
Error("AliRawReaderChain","Bad file list in collection, the chain is empty");
fIsValid = kFALSE;
return;
}
fChain->SetBranchStatus("*",1);
fChain->SetBranchAddress("rawevent",&fEvent,&fBranch);
}
AliRawReaderChain::AliRawReaderChain(TChain *chain) :
AliRawReaderRoot(),
fChain(chain)
{
// create raw-reader objects which takes as an input a root chain
// from a root file collection
if (!fChain) {
fIsValid = kFALSE;
return;
}
fChain->SetBranchStatus("*",1);
fChain->SetBranchAddress("rawevent",&fEvent,&fBranch);
}
AliRawReaderChain::AliRawReaderChain(TEntryList *elist) :
AliRawReaderRoot(),
fChain(NULL)
{
// create raw-reader objects which takes as an input a root chain
// from a root file collection
if (!elist) {
fIsValid = kFALSE;
return;
}
fChain = new TChain("RAW");
TEntryList *templist = NULL;
TList *elists = elist->GetLists();
TIter next(elists);
while((templist = (TEntryList*)next())){
fChain->Add(templist->GetFileName());
}
fChain->SetEntryList(elist,"ne");
fChain->SetBranchStatus("*",1);
fChain->SetBranchAddress("rawevent",&fEvent,&fBranch);
}
AliRawReaderChain::AliRawReaderChain(Int_t runNumber) :
AliRawReaderRoot(),
fChain(NULL)
{
// create raw-reader objects which takes as an input a root chain
// with the raw-data files for a given run
// It queries alien FC in order to do that and therefore
// it needs alien API to be enabled
if (runNumber <= 0) {
Error("AliRawReaderChain","Bad run number:%d",runNumber);
fIsValid = kFALSE;
}
if (!gGrid) TGrid::Connect("alien://");
if (!gGrid) {
fIsValid = kFALSE;
return;
}
if (fgSearchPath.IsNull()) fgSearchPath = "/alice/data";
TGridResult *res = gGrid->Query(fgSearchPath.Data(),Form("%09d/raw/*%09d*.root",runNumber,runNumber));
Int_t nFiles = res->GetEntries();
if (!nFiles) {
Error("AliRawReaderChain","No raw-data files found for run %d",runNumber);
fIsValid = kFALSE;
delete res;
return;
}
fChain = new TChain("RAW");
for (Int_t i = 0; i < nFiles; i++) {
TString filename = res->GetKey(i, "turl");
if(filename == "") continue;
fChain->Add(filename.Data());
}
delete res;
fChain->SetBranchStatus("*",1);
fChain->SetBranchAddress("rawevent",&fEvent,&fBranch);
}
AliRawReaderChain::AliRawReaderChain(const AliRawReaderChain& rawReader) :
AliRawReaderRoot(rawReader),
fChain(rawReader.fChain)
{
// copy constructor
}
AliRawReaderChain& AliRawReaderChain::operator = (const AliRawReaderChain&
rawReader)
{
// assignment operator
this->~AliRawReaderChain();
new(this) AliRawReaderChain(rawReader);
return *this;
}
AliRawReaderChain::~AliRawReaderChain()
{
// delete objects and close root file
if (fChain) {
delete fChain;
fChain = NULL;
}
}
Bool_t AliRawReaderChain::NextEvent()
{
// go to the next event in the root file
if (!fChain || !fChain->GetListOfFiles()->GetEntriesFast()) return kFALSE;
do {
delete fEvent;
fEvent = NULL;
fEventHeader = NULL;
Long64_t treeEntry = fChain->LoadTree(fEventIndex+1);
if (!fBranch)
return kFALSE;
if (fBranch->GetEntry(treeEntry) <= 0)
return kFALSE;
fEventHeader = fEvent->GetHeader();
fEventIndex++;
} while (!IsEventSelected());
fEventNumber++;
return Reset();
}
Bool_t AliRawReaderChain::RewindEvents()
{
// go back to the beginning of the root file
fEventIndex = -1;
delete fEvent;
fEvent = NULL;
fEventHeader = NULL;
fEventNumber = -1;
return Reset();
}
Bool_t AliRawReaderChain::GotoEvent(Int_t event)
{
// go to a particular event
// Uses the absolute event index inside the
// chain with raw data
if (!fChain || !fChain->GetListOfFiles()->GetEntriesFast()) return kFALSE;
delete fEvent;
fEvent = NULL;
fEventHeader = NULL;
Long64_t treeEntry = fChain->LoadTree(event);
if (!fBranch)
return kFALSE;
if (fBranch->GetEntry(treeEntry) <= 0)
return kFALSE;
fEventHeader = fEvent->GetHeader();
fEventIndex = event;
fEventNumber++;
return Reset();
}
Int_t AliRawReaderChain::GetNumberOfEvents() const
{
// Get the total number of events in the chain
// of raw-data files
if (!fChain) return -1;
return fChain->GetEntries();
}
void AliRawReaderChain::SetSearchPath(const char* path)
{
// set alien query search path
AliInfoGeneral("SetSearchPath",Form("Setting search path to \"%s\" (was \"%s\")",path,fgSearchPath.Data()));
fgSearchPath = path;
}
| 28.114525 | 110 | 0.641232 | AllaMaevskaya |
430d7e39c530e6e043f7f754b4095f7c2a87f275 | 11,953 | cpp | C++ | src/modules/osgAnimation/generated_code/UpdateBone.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 3 | 2017-04-20T09:11:47.000Z | 2021-04-29T19:24:03.000Z | src/modules/osgAnimation/generated_code/UpdateBone.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | null | null | null | src/modules/osgAnimation/generated_code/UpdateBone.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | null | null | null | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osgAnimation.h"
#include "wrap_referenced.h"
#include "UpdateBone.pypp.hpp"
namespace bp = boost::python;
struct UpdateBone_wrapper : osgAnimation::UpdateBone, bp::wrapper< osgAnimation::UpdateBone > {
UpdateBone_wrapper(::std::string const & name="" )
: osgAnimation::UpdateBone( name )
, bp::wrapper< osgAnimation::UpdateBone >(){
// constructor
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osgAnimation::UpdateBone::className( );
}
}
char const * default_className( ) const {
return osgAnimation::UpdateBone::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osgAnimation::UpdateBone::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osgAnimation::UpdateBone::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osgAnimation::UpdateBone::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osgAnimation::UpdateBone::cloneType( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osgAnimation::UpdateBone::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osgAnimation::UpdateBone::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osgAnimation::UpdateBone::libraryName( );
}
}
char const * default_libraryName( ) const {
return osgAnimation::UpdateBone::libraryName( );
}
virtual void operator()( ::osg::Node * node, ::osg::NodeVisitor * nv ) {
if( bp::override func___call__ = this->get_override( "__call__" ) )
func___call__( boost::python::ptr(node), boost::python::ptr(nv) );
else{
this->osgAnimation::UpdateBone::operator()( boost::python::ptr(node), boost::python::ptr(nv) );
}
}
void default___call__( ::osg::Node * node, ::osg::NodeVisitor * nv ) {
osgAnimation::UpdateBone::operator()( boost::python::ptr(node), boost::python::ptr(nv) );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual int link( ::osgAnimation::Animation * animation ) {
if( bp::override func_link = this->get_override( "link" ) )
return func_link( boost::python::ptr(animation) );
else{
return this->osgAnimation::AnimationUpdateCallback< osg::NodeCallback >::link( boost::python::ptr(animation) );
}
}
int default_link( ::osgAnimation::Animation * animation ) {
return osgAnimation::AnimationUpdateCallback< osg::NodeCallback >::link( boost::python::ptr(animation) );
}
virtual bool link( ::osgAnimation::Channel * channel ) {
if( bp::override func_link = this->get_override( "link" ) )
return func_link( boost::python::ptr(channel) );
else{
return this->osgAnimation::UpdateMatrixTransform::link( boost::python::ptr(channel) );
}
}
bool default_link( ::osgAnimation::Channel * channel ) {
return osgAnimation::UpdateMatrixTransform::link( boost::python::ptr(channel) );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Object::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Object::setThreadSafeRefUnref( threadSafe );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
};
void register_UpdateBone_class(){
{ //::osgAnimation::UpdateBone
typedef bp::class_< UpdateBone_wrapper, bp::bases< osgAnimation::UpdateMatrixTransform >, osg::ref_ptr< UpdateBone_wrapper >, boost::noncopyable > UpdateBone_exposer_t;
UpdateBone_exposer_t UpdateBone_exposer = UpdateBone_exposer_t( "UpdateBone", bp::init< bp::optional< std::string const & > >(( bp::arg("name")="" )) );
bp::scope UpdateBone_scope( UpdateBone_exposer );
bp::implicitly_convertible< std::string const &, osgAnimation::UpdateBone >();
{ //::osgAnimation::UpdateBone::className
typedef char const * ( ::osgAnimation::UpdateBone::*className_function_type )( ) const;
typedef char const * ( UpdateBone_wrapper::*default_className_function_type )( ) const;
UpdateBone_exposer.def(
"className"
, className_function_type(&::osgAnimation::UpdateBone::className)
, default_className_function_type(&UpdateBone_wrapper::default_className) );
}
{ //::osgAnimation::UpdateBone::clone
typedef ::osg::Object * ( ::osgAnimation::UpdateBone::*clone_function_type )( ::osg::CopyOp const & ) const;
typedef ::osg::Object * ( UpdateBone_wrapper::*default_clone_function_type )( ::osg::CopyOp const & ) const;
UpdateBone_exposer.def(
"clone"
, clone_function_type(&::osgAnimation::UpdateBone::clone)
, default_clone_function_type(&UpdateBone_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osgAnimation::UpdateBone::cloneType
typedef ::osg::Object * ( ::osgAnimation::UpdateBone::*cloneType_function_type )( ) const;
typedef ::osg::Object * ( UpdateBone_wrapper::*default_cloneType_function_type )( ) const;
UpdateBone_exposer.def(
"cloneType"
, cloneType_function_type(&::osgAnimation::UpdateBone::cloneType)
, default_cloneType_function_type(&UpdateBone_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osgAnimation::UpdateBone::isSameKindAs
typedef bool ( ::osgAnimation::UpdateBone::*isSameKindAs_function_type )( ::osg::Object const * ) const;
typedef bool ( UpdateBone_wrapper::*default_isSameKindAs_function_type )( ::osg::Object const * ) const;
UpdateBone_exposer.def(
"isSameKindAs"
, isSameKindAs_function_type(&::osgAnimation::UpdateBone::isSameKindAs)
, default_isSameKindAs_function_type(&UpdateBone_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) );
}
{ //::osgAnimation::UpdateBone::libraryName
typedef char const * ( ::osgAnimation::UpdateBone::*libraryName_function_type )( ) const;
typedef char const * ( UpdateBone_wrapper::*default_libraryName_function_type )( ) const;
UpdateBone_exposer.def(
"libraryName"
, libraryName_function_type(&::osgAnimation::UpdateBone::libraryName)
, default_libraryName_function_type(&UpdateBone_wrapper::default_libraryName) );
}
{ //::osgAnimation::UpdateBone::operator()
typedef void ( ::osgAnimation::UpdateBone::*__call___function_type )( ::osg::Node *,::osg::NodeVisitor * ) ;
typedef void ( UpdateBone_wrapper::*default___call___function_type )( ::osg::Node *,::osg::NodeVisitor * ) ;
UpdateBone_exposer.def(
"__call__"
, __call___function_type(&::osgAnimation::UpdateBone::operator())
, default___call___function_type(&UpdateBone_wrapper::default___call__)
, ( bp::arg("node"), bp::arg("nv") ) );
}
{ //::osgAnimation::AnimationUpdateCallback< osg::NodeCallback >::link
typedef osgAnimation::UpdateBone exported_class_t;
typedef int ( exported_class_t::*link_function_type )( ::osgAnimation::Animation * ) ;
typedef int ( UpdateBone_wrapper::*default_link_function_type )( ::osgAnimation::Animation * ) ;
UpdateBone_exposer.def(
"link"
, link_function_type(&::osgAnimation::AnimationUpdateCallback< osg::NodeCallback >::link)
, default_link_function_type(&UpdateBone_wrapper::default_link)
, ( bp::arg("animation") ) );
}
{ //::osgAnimation::UpdateMatrixTransform::link
typedef bool ( ::osgAnimation::UpdateMatrixTransform::*link_function_type )( ::osgAnimation::Channel * ) ;
typedef bool ( UpdateBone_wrapper::*default_link_function_type )( ::osgAnimation::Channel * ) ;
UpdateBone_exposer.def(
"link"
, link_function_type(&::osgAnimation::UpdateMatrixTransform::link)
, default_link_function_type(&UpdateBone_wrapper::default_link)
, ( bp::arg("channel") ) );
}
}
}
| 40.518644 | 176 | 0.596252 | cmbruns |
430dfce395d8d768640c6c5a8edb0a1241d638f6 | 92 | cpp | C++ | Include em C/Include.cpp | Suricat0Br/Programacao-em-C | a04b5b8e3dbbf82fcec4888d7bdf888bdc53d715 | [
"Apache-2.0"
] | null | null | null | Include em C/Include.cpp | Suricat0Br/Programacao-em-C | a04b5b8e3dbbf82fcec4888d7bdf888bdc53d715 | [
"Apache-2.0"
] | null | null | null | Include em C/Include.cpp | Suricat0Br/Programacao-em-C | a04b5b8e3dbbf82fcec4888d7bdf888bdc53d715 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include "./incluindo/main.cpp";
| 18.4 | 32 | 0.695652 | Suricat0Br |
430e73b3d7bd1f597a6e88a06e52f7ce9b50653b | 2,612 | hpp | C++ | include/libtorrent/bandwidth_queue_entry.hpp | luluandleilei/libtorrent | 8648de3706efe0d9ab2504793bd0dd8a9566a1d6 | [
"BSL-1.0",
"BSD-3-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | include/libtorrent/bandwidth_queue_entry.hpp | luluandleilei/libtorrent | 8648de3706efe0d9ab2504793bd0dd8a9566a1d6 | [
"BSL-1.0",
"BSD-3-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | include/libtorrent/bandwidth_queue_entry.hpp | luluandleilei/libtorrent | 8648de3706efe0d9ab2504793bd0dd8a9566a1d6 | [
"BSL-1.0",
"BSD-3-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
Copyright (c) 2007-2016, Arvid Norberg
All rights reserved.
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 author 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.
*/
#ifndef TORRENT_BANDWIDTH_QUEUE_ENTRY_HPP_INCLUDED
#define TORRENT_BANDWIDTH_QUEUE_ENTRY_HPP_INCLUDED
#include <memory>
#include "libtorrent/bandwidth_limit.hpp"
#include "libtorrent/bandwidth_socket.hpp"
namespace libtorrent {
struct TORRENT_EXTRA_EXPORT bw_request
{
bw_request(std::shared_ptr<bandwidth_socket> const& pe
, int blk, int prio);
std::shared_ptr<bandwidth_socket> peer;
// 1 is normal prio
int priority;
// the number of bytes assigned to this request so far
int assigned;
// once assigned reaches this, we dispatch the request function
int request_size;
// the max number of rounds for this request to survive
// this ensures that requests gets responses at very low
// rate limits, when the requested size would take a long
// time to satisfy
int ttl;
// loops over the bandwidth channels and assigns bandwidth
// from the most limiting one
int assign_bandwidth();
constexpr static int max_bandwidth_channels = 10;
// we don't actually support more than 10 channels per peer
bandwidth_channel* channel[max_bandwidth_channels];
};
}
#endif
| 35.297297 | 78 | 0.785988 | luluandleilei |
430eb6d7507eae1b9c274b976848ed8efe00d842 | 9,117 | cpp | C++ | src/audio/oni-audio-manager.cpp | sina-/granite | 95b873bc545cd4925b5cea8c632a82f2d815be6e | [
"MIT"
] | 2 | 2019-08-01T09:18:49.000Z | 2020-03-26T05:59:52.000Z | src/audio/oni-audio-manager.cpp | sina-/granite | 95b873bc545cd4925b5cea8c632a82f2d815be6e | [
"MIT"
] | null | null | null | src/audio/oni-audio-manager.cpp | sina-/granite | 95b873bc545cd4925b5cea8c632a82f2d815be6e | [
"MIT"
] | 1 | 2020-03-26T05:59:53.000Z | 2020-03-26T05:59:53.000Z | #include <oni-core/audio/oni-audio-manager.h>
#include <assert.h>
#include <fmod.hpp>
#include <oni-core/component/oni-component-geometry.h>
#include <oni-core/entities/oni-entities-manager.h>
#include <oni-core/game/oni-game-event.h>
#define ERRCHECK(_result) assert((_result) == FMOD_OK)
namespace oni {
AudioManager::AudioManager(AssetFilesIndex &assetManager) : mAssetManager(assetManager) {
mMaxAudibleDistance = 150.f;
mMaxNumberOfChannels = 1024;
FMOD::System *system;
auto result = FMOD::System_Create(&system);
ERRCHECK(result);
mSystem = std::unique_ptr<FMOD::System, FMODDeleter>(system, FMODDeleter());
u32 version;
result = mSystem->getVersion(&version);
ERRCHECK(result);
assert(version >= FMOD_VERSION);
result = mSystem->init(mMaxNumberOfChannels, FMOD_INIT_NORMAL, nullptr);
ERRCHECK(result);
result = mSystem->update();
ERRCHECK(result);
_loadChannels();
_preLoadSounds();
}
void
AudioManager::tick(const WorldP3D &playerPos) {
// TODO: Do I need this?
mPlayerPos = playerPos;
auto result = mSystem->update();
ERRCHECK(result);
}
void
AudioManager::_preLoadSounds() {
for (auto iter = mAssetManager.soundAssetsBegin(); iter != mAssetManager.soundAssetsEnd(); ++iter) {
const auto &soundAsset = iter->second;
_loadSound(soundAsset);
}
}
void
AudioManager::_loadChannels() {
FMOD::ChannelGroup *group{nullptr};
auto result = mSystem->createChannelGroup("effectsChannel", &group);
ERRCHECK(result);
auto effectsGroup = std::unique_ptr<FMOD::ChannelGroup, FMODDeleter>(group, FMODDeleter());
effectsGroup->setVolume(1.f);
mChannelGroup[ChannelGroup::GET("effect").id] = std::move(effectsGroup);
group = nullptr;
result = mSystem->createChannelGroup("musicChannel", &group);
ERRCHECK(result);
auto musicGroup = std::unique_ptr<FMOD::ChannelGroup, FMODDeleter>(group, FMODDeleter());
musicGroup->setVolume(1.f);
mChannelGroup[ChannelGroup::GET("music").id] = std::move(musicGroup);
group = nullptr;
for (auto channelGroup = ChannelGroup::begin() + 1; channelGroup != ChannelGroup::end(); ++channelGroup) {
setChannelGroupVolume(*channelGroup, 1.f);
}
}
void
AudioManager::kill(EntityID entityID) {
for (auto it = mLoopingChannels.begin(); it != mLoopingChannels.end();) {
if (it->entityID == entityID) {
auto result = it->channel->stop();
ERRCHECK(result);
it = mLoopingChannels.erase(it);
} else {
++it;
}
}
}
void
AudioManager::_loadSound(const SoundAsset &asset) {
FMOD::Sound *sound{};
auto result = mSystem->createSound(asset.path.getFullPath().data(), FMOD_DEFAULT, nullptr, &sound);
ERRCHECK(result);
assert(sound);
std::unique_ptr<FMOD::Sound, FMODDeleter> value(sound);
mSounds.emplace(asset.name.hash, std::move(value));
}
FMOD::Channel *
AudioManager::_createChannel(const Sound &sound) {
if (sound.group.id < 0 || sound.group.id > ChannelGroup::size()) {
assert(false);
return nullptr;
}
auto *group = mChannelGroup[sound.group.id].get();
auto soundToPlay = mSounds.find(sound.name.hash);
if (soundToPlay == mSounds.end()) {
assert(false);
return nullptr;
}
FMOD::Channel *channel{};
auto paused = true;
auto result = mSystem->playSound(soundToPlay->second.get(), group, paused, &channel);
ERRCHECK(result);
return channel;
}
FMOD::ChannelGroup *
AudioManager::_getChannelGroup(ChannelGroup cg) {
if (cg.id < 0 || cg.id > ChannelGroup::size()) {
assert(false);
return nullptr;
}
auto *group = mChannelGroup[cg.id].get();
assert(group);
return group;
}
void
AudioManager::playOneShot(const Sound &sound,
const SoundPitch &pitch,
const vec3 &distance) {
auto *channel = _createChannel(sound);
if (!channel) {
assert(false);
return;
}
auto result = channel->setMode(FMOD_3D);
ERRCHECK(result);
_setPitch(*channel, pitch.value);
// TODO: Does this matter?
vec3 velocity{1.f, 1.f, 0.f};
_set3DPos(*channel, distance, velocity);
_unPause(*channel);
}
static FMOD_RESULT
endOfPlayCallback(FMOD_CHANNELCONTROL *channelControl,
FMOD_CHANNELCONTROL_TYPE type,
FMOD_CHANNELCONTROL_CALLBACK_TYPE callbackType,
void *,
void *) {
if (type == FMOD_CHANNELCONTROL_TYPE::FMOD_CHANNELCONTROL_CHANNELGROUP) {
return FMOD_OK;
}
auto *channel = (FMOD::Channel *) (channelControl);
if (callbackType == FMOD_CHANNELCONTROL_CALLBACK_TYPE::FMOD_CHANNELCONTROL_CALLBACK_END) {
void *finished;
auto result = channel->getUserData(&finished);
ERRCHECK(result);
*(bool *) finished = true;
}
return FMOD_OK;
}
AudioManager::EntityChannel *
AudioManager::_getOrCreateLooping3DChannel(const Sound &sound,
EntityID entityID) {
if (!sound.name.valid()) {
assert(false);
return nullptr;
}
if (entityID == EntityManager::nullEntity()) {
assert(false);
return nullptr;
}
for (auto it = mLoopingChannels.begin(); it != mLoopingChannels.end();) {
if (it->entityID == entityID && it->name == sound.name) {
return &(*it);
} else {
++it;
}
}
EntityChannel entityChannel;
entityChannel.entityID = entityID;
entityChannel.name = sound.name;
entityChannel.channel = _createChannel(sound);
entityChannel.channel->setMode(FMOD_LOOP_NORMAL | FMOD_3D);
mLoopingChannels.push_back(entityChannel);
return &mLoopingChannels.back();
}
void
AudioManager::_setPitch(FMOD::Channel &channel,
r32 pitch) {
if (pitch > 256) {
pitch = 256;
}
auto result = channel.setPitch(pitch);
ERRCHECK(result);
}
bool
AudioManager::_isPaused(FMOD::Channel &channel) {
bool paused{false};
auto result = channel.getPaused(&paused);
ERRCHECK(result);
return paused;
}
void
AudioManager::_unPause(FMOD::Channel &channel) {
auto result = channel.setPaused(false);
ERRCHECK(result);
}
void
AudioManager::_pause(FMOD::Channel &channel) {
auto result = channel.setPaused(true);
ERRCHECK(result);
}
void
AudioManager::FMODDeleter::operator()(FMOD::Sound *s) const {
s->release();
}
void
AudioManager::FMODDeleter::operator()(FMOD::System *sys) const {
sys->close();
sys->release();
}
void
AudioManager::FMODDeleter::operator()(FMOD::ChannelGroup *channel) const {
channel->stop();
channel->release();
}
void
AudioManager::_set3DPos(FMOD::Channel &channel,
const vec3 &pos,
const vec3 &velocity) {
FMOD_VECTOR fPos;
fPos.x = pos.x;
fPos.y = pos.y;
fPos.z = pos.z;
FMOD_VECTOR fVelocity;
fVelocity.x = velocity.x;
fVelocity.y = velocity.y;
fVelocity.z = velocity.z;
auto result = channel.set3DAttributes(&fPos, &fVelocity);
ERRCHECK(result);
result = channel.set3DMinMaxDistance(20.f, mMaxAudibleDistance); // In meters
ERRCHECK(result);
}
void
AudioManager::_updateChannelVolume(ChannelGroup cg) {
auto channelVolume = mChannelVolume[cg.id];
setChannelGroupVolume(cg, channelVolume);
}
void
AudioManager::setChannelGroupVolume(ChannelGroup channelGroup,
r32 volume) {
auto effectiveVolume = volume * mMasterVolume;
auto *group = _getChannelGroup(channelGroup);
auto result = group->setVolume(effectiveVolume);
ERRCHECK(result);
mChannelVolume[channelGroup.id] = volume;
}
void
AudioManager::setMasterVolume(r32 volume) {
assert(almost_Positive(volume) || almost_Zero(volume));
assert(almost_Less(volume, 1.f));
mMasterVolume = volume;
for (auto iter = ChannelGroup::begin() + 1;
iter < ChannelGroup::end(); ++iter) {
_updateChannelVolume(*iter);
}
}
}
| 29.990132 | 114 | 0.576834 | sina- |
430f0d60423784bdaa7331746bab5791c9aeac4f | 277 | hpp | C++ | Client/client/Global.hpp | pinkmouse/SlayersWorld | 53cdde28f3464ee9ada9b655f8c4df63f0e9389e | [
"MIT"
] | 14 | 2019-03-05T10:03:59.000Z | 2021-12-21T03:00:18.000Z | Client/client/Global.hpp | pinkmouse/SlayersWorld | 53cdde28f3464ee9ada9b655f8c4df63f0e9389e | [
"MIT"
] | 1 | 2019-10-24T21:37:59.000Z | 2019-10-24T21:37:59.000Z | Client/client/Global.hpp | pinkmouse/SlayersWorld | 53cdde28f3464ee9ada9b655f8c4df63f0e9389e | [
"MIT"
] | 1 | 2020-12-06T21:07:52.000Z | 2020-12-06T21:07:52.000Z | #pragma once
#include "Entities/Player.hpp"
#include "Socket/Socket.hpp"
#include <SFML/Graphics/Font.hpp>
#include "World/ConfigHandler.hpp"
extern ConfigHandler* g_Config;
extern Player* g_Player;
extern Socket* g_Socket;
extern sf::Font* g_Font; | 25.181818 | 34 | 0.703971 | pinkmouse |
430f44e2fb83aa6d267000ba687eaa6e6177c9cb | 3,444 | hpp | C++ | cpp/src/jit/common_headers.hpp | jperez999/cudf | e63eb311089837eaa24fa871e1106ec3ce5df318 | [
"Apache-2.0"
] | null | null | null | cpp/src/jit/common_headers.hpp | jperez999/cudf | e63eb311089837eaa24fa871e1106ec3ce5df318 | [
"Apache-2.0"
] | null | null | null | cpp/src/jit/common_headers.hpp | jperez999/cudf | e63eb311089837eaa24fa871e1106ec3ce5df318 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <christian@blazingdb.com>
*
* 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 <iostream>
#include <libcudacxx/details/__config.jit>
#include <libcudacxx/libcxx/include/__config.jit>
#include <libcudacxx/libcxx/include/__undef_macros.jit>
#include <libcudacxx/libcxx/include/cfloat.jit>
#include <libcudacxx/libcxx/include/chrono.jit>
#include <libcudacxx/libcxx/include/ctime.jit>
#include <libcudacxx/libcxx/include/limits.jit>
#include <libcudacxx/libcxx/include/ratio.jit>
#include <libcudacxx/libcxx/include/type_traits.jit>
#include <libcudacxx/simt/cfloat.jit>
#include <libcudacxx/simt/chrono.jit>
#include <libcudacxx/simt/ctime.jit>
#include <libcudacxx/simt/limits.jit>
#include <libcudacxx/simt/ratio.jit>
#include <libcudacxx/simt/type_traits.jit>
#include <libcudacxx/simt/version.jit>
#include <string>
namespace cudf {
namespace jit {
const std::vector<std::string> compiler_flags
{
"-std=c++14",
// Have jitify prune unused global variables
"-remove-unused-globals",
// suppress all NVRTC warnings
"-w",
// force libcudacxx to not include system headers
"-D__CUDACC_RTC__",
// __CHAR_BIT__ is from GCC, but libcxx uses it
"-D__CHAR_BIT__=" + std::to_string(__CHAR_BIT__),
// enable temporary workarounds to compile libcudacxx with nvrtc
"-D_LIBCUDACXX_HAS_NO_CTIME", "-D_LIBCUDACXX_HAS_NO_WCHAR", "-D_LIBCUDACXX_HAS_NO_CFLOAT",
"-D_LIBCUDACXX_HAS_NO_STDINT", "-D_LIBCUDACXX_HAS_NO_CSTDDEF", "-D_LIBCUDACXX_HAS_NO_CLIMITS",
"-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS",
#if defined(__powerpc64__)
"-D__powerpc64__"
#elif defined(__x86_64__)
"-D__x86_64__"
#endif
};
const std::unordered_map<std::string, char const*> stringified_headers{
{"details/../../libcxx/include/__config", libcxx_config},
{"../libcxx/include/__undef_macros", libcxx_undef_macros},
{"simt/../../libcxx/include/cfloat", libcxx_cfloat},
{"simt/../../libcxx/include/chrono", libcxx_chrono},
{"simt/../../libcxx/include/ctime", libcxx_ctime},
{"simt/../../libcxx/include/limits", libcxx_limits},
{"simt/../../libcxx/include/ratio", libcxx_ratio},
{"simt/../../libcxx/include/type_traits", libcxx_type_traits},
{"simt/../details/__config", libcudacxx_details_config},
{"simt/cfloat", libcudacxx_simt_cfloat},
{"simt/chrono", libcudacxx_simt_chrono},
{"simt/ctime", libcudacxx_simt_ctime},
{"simt/limits", libcudacxx_simt_limits},
{"simt/ratio", libcudacxx_simt_ratio},
{"simt/type_traits", libcudacxx_simt_type_traits},
{"simt/version", libcudacxx_simt_version},
};
inline std::istream* send_stringified_header(std::iostream& stream, char const* header)
{
// skip the filename line added by stringify
stream << (std::strchr(header, '\n') + 1);
return &stream;
}
} // namespace jit
} // namespace cudf
| 37.434783 | 98 | 0.738676 | jperez999 |
430f6df5724b6b5e07ad83c5d52c126d7790d55a | 3,964 | cpp | C++ | Nistal Engine/ModuleSceneIntro.cpp | AlbertCayuela/NistalEngine | d5a082c49326dcd47557fdb856a5a86deac40616 | [
"MIT"
] | null | null | null | Nistal Engine/ModuleSceneIntro.cpp | AlbertCayuela/NistalEngine | d5a082c49326dcd47557fdb856a5a86deac40616 | [
"MIT"
] | null | null | null | Nistal Engine/ModuleSceneIntro.cpp | AlbertCayuela/NistalEngine | d5a082c49326dcd47557fdb856a5a86deac40616 | [
"MIT"
] | 1 | 2020-09-28T13:25:32.000Z | 2020-09-28T13:25:32.000Z | #include "Globals.h"
#include "Application.h"
#include "ModuleSceneIntro.h"
#include "ModuleUI.h"
#include "GOMesh.h"
#include "GOMaterial.h"
#include "GOTransform.h"
#include "GOCamera.h"
#include "GameObject.h"
#include "GOAudioSource.h"
#include "ModuleSerialization.h"
#include "SDL/include/SDL_opengl.h"
#include <gl/GL.h>
#include <gl/GLU.h>
ModuleSceneIntro::ModuleSceneIntro(Application* app, bool start_enabled) : Module(app, start_enabled)
{}
ModuleSceneIntro::~ModuleSceneIntro()
{}
bool ModuleSceneIntro::Start()
{
LOG("Loading Intro assets");
bool ret = true;
App->camera->Move(float3(-50.0f, -20.0f, -150.0f));
App->camera->LookAt(float3(0, 0, 0));
root = CreateGameObject(nullptr, "root");
camera = CreateGameObject(root, "camera");
camera->AddComponent(GOCOMPONENT_TYPE::CAMERA, "camera");
camera->transform->NewPosition(float3(0.0f, 7.2f, -22.50f));
camera->camera->SetFarPlane(200.0f);
sound_go = CreateGameObject(root, "Music and listener");
sound_go->AddComponent(GOCOMPONENT_TYPE::AUDIO_SOURCE, "AudioSource");
sound_go->AddComponent(GOCOMPONENT_TYPE::AUDIO_LISTENER, "AudioListener");
sound_go->audio_source->PlayEvent("PlaySong1");
sound_go->audio_source->is_music = true;
moving_sound_go = CreateGameObject(root, "MovingMotorcycle");
moving_sound_go->AddComponent(GOCOMPONENT_TYPE::AUDIO_SOURCE, "AudioSource");
moving_sound_go->audio_source->PlayEvent("PlayMotorcycle");
reverb_zone_go = CreateGameObject(root, "ReverbZone");
reverb_zone_go->AddComponent(GOCOMPONENT_TYPE::REVERB_ZONE, "ReverbZone");
return ret;
}
update_status ModuleSceneIntro::PreUpdate(float dt)
{
App->playing_timer.UpdateTimer();
return UPDATE_CONTINUE;
}
// Update
update_status ModuleSceneIntro::Update(float dt)
{
PlanePrimitive p(0, 1, 0, 0);
p.axis = true;
//to change size see p.innerrender() -> variable d(now its 10 it was 200 before)
p.Render();
if (!objects_created)
{
App->load_fbx->LoadFBX("Primitives/Cube.fbx", sound_go);
App->load_fbx->LoadFBX("Primitives/Cube.fbx", moving_sound_go);
objects_created = true;
}
//PRIMITIVES
if (App->ui->cube)
{
App->load_fbx->LoadFBX("Primitives/Cube.fbx");
App->ui->cube = false;
}
if (App->ui->sphere)
{
App->load_fbx->LoadFBX("Primitives/Sphere.fbx");
App->ui->sphere = false;
}
if (App->ui->cylinder)
{
App->load_fbx->LoadFBX("Primitives/Cylinder.fbx");
App->ui->cylinder = false;
}
if (App->ui->cone)
{
App->load_fbx->LoadFBX("Primitives/Cone.fbx");
App->ui->cone = false;
}
if (App->ui->torus)
{
App->load_fbx->LoadFBX("Primitives/Torus.fbx");
App->ui->torus = false;
}
ImGui::Separator();
root->Update(dt);
for (std::vector<GameObject*>::iterator i = game_objects.begin(); i != game_objects.end(); ++i)
{
if ((*i)->has_mesh)
{
(*i)->mesh->DrawMesh((*i)->material->texture_id);
}
if ((*i)->parent != nullptr)
{
if (!(*i)->parent->active)
{
(*i)->active = false;
}
}
}
if (App->ui->render_face_normals)
{
App->load_fbx->DrawNormals(selected_go->mesh->mesh_info);
}
if (App->ui->render_vertex_normals)
{
App->load_fbx->DrawVertexNormals(selected_go->mesh->mesh_info);
}
return UPDATE_CONTINUE;
}
update_status ModuleSceneIntro::PostUpdate(float dt)
{
return UPDATE_CONTINUE;
}
// Load assets
bool ModuleSceneIntro::CleanUp()
{
LOG("Unloading Intro scene");
return true;
}
GameObject* ModuleSceneIntro::CreateGameObject(GameObject* parent, const char* name)
{
GameObject* game_object = new GameObject(parent, name);
game_objects.push_back(game_object);
return game_object;
}
| 24.469136 | 101 | 0.639001 | AlbertCayuela |
431425020a741c006bde96a5257d0038906ad258 | 2,995 | cpp | C++ | node_modules/gl/angle/src/compiler/translator/OutputGLSL.cpp | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | Source/ANGLE/compiler/translator/OutputGLSL.cpp | wpbest/XPF | cb54ad82a8c6f675f2d5bc840a78f66f03de65e2 | [
"MIT"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | Source/ANGLE/compiler/translator/OutputGLSL.cpp | wpbest/XPF | cb54ad82a8c6f675f2d5bc840a78f66f03de65e2 | [
"MIT"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | //
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/translator/OutputGLSL.h"
TOutputGLSL::TOutputGLSL(TInfoSinkBase& objSink,
ShArrayIndexClampingStrategy clampingStrategy,
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable,
int shaderVersion,
ShShaderOutput output)
: TOutputGLSLBase(objSink,
clampingStrategy,
hashFunction,
nameMap,
symbolTable,
shaderVersion,
output)
{
}
bool TOutputGLSL::writeVariablePrecision(TPrecision)
{
return false;
}
void TOutputGLSL::visitSymbol(TIntermSymbol *node)
{
TInfoSinkBase& out = objSink();
const TString &symbol = node->getSymbol();
if (symbol == "gl_FragDepthEXT")
{
out << "gl_FragDepth";
}
else if (symbol == "gl_FragColor" && IsGLSL130OrNewer(getShaderOutput()))
{
out << "webgl_FragColor";
}
else if (symbol == "gl_FragData" && IsGLSL130OrNewer(getShaderOutput()))
{
out << "webgl_FragData";
}
else if (symbol == "gl_SecondaryFragColorEXT")
{
out << "angle_SecondaryFragColor";
}
else if (symbol == "gl_SecondaryFragDataEXT")
{
out << "angle_SecondaryFragData";
}
else
{
TOutputGLSLBase::visitSymbol(node);
}
}
TString TOutputGLSL::translateTextureFunction(TString &name)
{
static const char *simpleRename[] = {
"texture2DLodEXT", "texture2DLod",
"texture2DProjLodEXT", "texture2DProjLod",
"textureCubeLodEXT", "textureCubeLod",
"texture2DGradEXT", "texture2DGradARB",
"texture2DProjGradEXT", "texture2DProjGradARB",
"textureCubeGradEXT", "textureCubeGradARB",
NULL, NULL
};
static const char *legacyToCoreRename[] = {
"texture2D", "texture",
"texture2DProj", "textureProj",
"texture2DLod", "textureLod",
"texture2DProjLod", "textureProjLod",
"texture2DRect", "texture",
"textureCube", "texture",
"textureCubeLod", "textureLod",
// Extensions
"texture2DLodEXT", "textureLod",
"texture2DProjLodEXT", "textureProjLod",
"textureCubeLodEXT", "textureLod",
"texture2DGradEXT", "textureGrad",
"texture2DProjGradEXT", "textureProjGrad",
"textureCubeGradEXT", "textureGrad",
NULL, NULL
};
const char **mapping = (IsGLSL130OrNewer(getShaderOutput())) ?
legacyToCoreRename : simpleRename;
for (int i = 0; mapping[i] != NULL; i += 2)
{
if (name == mapping[i])
{
return mapping[i+1];
}
}
return name;
}
| 29.07767 | 77 | 0.583306 | aaverty |
4319eb2ebfeb91efc38c94d3afea14d48c128566 | 244 | cpp | C++ | Ch 03/3.02.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 03/3.02.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 03/3.02.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::getline;
int main()
{
string s1;
//getline(cin, s1); // 一次读入一整行
cin >> s1; // 一次读入一个单词
cout << s1 << endl;
return 0;
} | 13.555556 | 32 | 0.639344 | Felon03 |
431c524ee2242c27274b0b763622a874a9133faa | 116 | hpp | C++ | src/window_macos.hpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | src/window_macos.hpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | src/window_macos.hpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | #pragma once
extern "C" {
/// Based on https://stackoverflow.com/a/47497879
void macos_force_foreground_level();
}
| 16.571429 | 49 | 0.741379 | jlangvand |
4321d62be7725cfc1920bd58023f5b94494c46aa | 5,379 | hpp | C++ | src/Evolution/Systems/GeneralizedHarmonic/Equations.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/Evolution/Systems/GeneralizedHarmonic/Equations.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/Evolution/Systems/GeneralizedHarmonic/Equations.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Defines class template GeneralizedHarmonicEquations.
#pragma once
#include <cstddef>
#include "DataStructures/Tensor/TypeAliases.hpp"
#include "Evolution/Systems/GeneralizedHarmonic/TagsDeclarations.hpp" // IWYU pragma: keep
#include "NumericalAlgorithms/LinearOperators/PartialDerivatives.hpp"
#include "PointwiseFunctions/GeneralRelativity/TagsDeclarations.hpp" // IWYU pragma: keep
#include "Utilities/TMPL.hpp"
/// \cond
class DataVector;
namespace Tags {
template <typename>
class dt;
template <typename>
struct NormalDotFlux;
} // namespace Tags
namespace gsl {
template <class T>
class not_null;
} // namespace gsl
/// \endcond
namespace GeneralizedHarmonic {
/*!
* \brief Compute the RHS of the Generalized Harmonic formulation of
* Einstein's equations.
*
* \details For the full form of the equations see "A New Generalized Harmonic
* Evolution System" by Lindblom et. al, arxiv.org/abs/gr-qc/0512093.
*/
template <size_t Dim>
struct ComputeDuDt {
public:
using argument_tags =
tmpl::list<gr::Tags::SpacetimeMetric<Dim>, Pi<Dim>, Phi<Dim>,
Tags::deriv<gr::Tags::SpacetimeMetric<Dim>, tmpl::size_t<Dim>,
Frame::Inertial>,
Tags::deriv<Pi<Dim>, tmpl::size_t<Dim>, Frame::Inertial>,
Tags::deriv<Phi<Dim>, tmpl::size_t<Dim>, Frame::Inertial>,
ConstraintGamma0, ConstraintGamma1, ConstraintGamma2,
GaugeH<Dim>, SpacetimeDerivGaugeH<Dim>, gr::Tags::Lapse<>,
gr::Tags::Shift<Dim>, gr::Tags::InverseSpatialMetric<Dim>,
gr::Tags::InverseSpacetimeMetric<Dim>,
gr::Tags::TraceSpacetimeChristoffelFirstKind<Dim>,
gr::Tags::SpacetimeChristoffelFirstKind<Dim>,
gr::Tags::SpacetimeChristoffelSecondKind<Dim>,
gr::Tags::SpacetimeNormalVector<Dim>,
gr::Tags::SpacetimeNormalOneForm<Dim>>;
static void apply(
gsl::not_null<tnsr::aa<DataVector, Dim>*> dt_spacetime_metric,
gsl::not_null<tnsr::aa<DataVector, Dim>*> dt_pi,
gsl::not_null<tnsr::iaa<DataVector, Dim>*> dt_phi,
const tnsr::aa<DataVector, Dim>& spacetime_metric,
const tnsr::aa<DataVector, Dim>& pi,
const tnsr::iaa<DataVector, Dim>& phi,
const tnsr::iaa<DataVector, Dim>& d_spacetime_metric,
const tnsr::iaa<DataVector, Dim>& d_pi,
const tnsr::ijaa<DataVector, Dim>& d_phi,
const Scalar<DataVector>& gamma0, const Scalar<DataVector>& gamma1,
const Scalar<DataVector>& gamma2,
const tnsr::a<DataVector, Dim>& gauge_function,
const tnsr::ab<DataVector, Dim>& spacetime_deriv_gauge_function,
const Scalar<DataVector>& lapse, const tnsr::I<DataVector, Dim>& shift,
const tnsr::II<DataVector, Dim>& inverse_spatial_metric,
const tnsr::AA<DataVector, Dim>& inverse_spacetime_metric,
const tnsr::a<DataVector, Dim>& trace_christoffel,
const tnsr::abb<DataVector, Dim>& christoffel_first_kind,
const tnsr::Abb<DataVector, Dim>& christoffel_second_kind,
const tnsr::A<DataVector, Dim>& normal_spacetime_vector,
const tnsr::a<DataVector, Dim>& normal_spacetime_one_form);
};
/*!
* \brief Compute the fluxes of the Generalized Harmonic formulation of
* Einstein's equations.
*
* \details The expressions for the fluxes is obtained
* from <a href="https://arxiv.org/abs/gr-qc/0512093">
* gr-qc/0512093 </a>.
* The fluxes for each variable are obtained by taking the principal part of
* equations 35, 36, and 37, and replacing derivatives \f$ \partial_k \f$
* with the unit normal \f$ n_k \f$. This gives:
*
* \f{align*}
* F(\psi_{ab}) =& -(1 + \gamma_1) N^k n_k \psi_{ab} \\
* F(\Pi_{ab}) =& - N^k n_k \Pi_{ab} + N g^{ki}n_k \Phi_{iab} - \gamma_1
* \gamma_2
* N^k n_k \psi_{ab} \\
* F(\Phi_{iab}) =& - N^k n_k \Phi_{iab} + N n_i \Pi_{ab} - \gamma_1 \gamma_2
* N^i \Phi_{iab}
* \f}
*
* where \f$\psi_{ab}\f$ is the spacetime metric, \f$\Pi_{ab}\f$ its conjugate
* momentum, \f$ \Phi_{iab} \f$ is an auxiliary field as defined by the tag Phi,
* \f$N\f$ is the lapse, \f$ N^k \f$ is the shift, \f$ g^{ki} \f$ is the inverse
* spatial metric, and \f$ \gamma_1, \gamma_2 \f$ are constraint damping
* parameters.
*/
template <size_t Dim>
struct ComputeNormalDotFluxes {
public:
using argument_tags =
tmpl::list<gr::Tags::SpacetimeMetric<Dim>, Pi<Dim>, Phi<Dim>,
ConstraintGamma1, ConstraintGamma2, gr::Tags::Lapse<>,
gr::Tags::Shift<Dim>, gr::Tags::InverseSpatialMetric<Dim>>;
static void apply(
gsl::not_null<tnsr::aa<DataVector, Dim>*>
spacetime_metric_normal_dot_flux,
gsl::not_null<tnsr::aa<DataVector, Dim>*> pi_normal_dot_flux,
gsl::not_null<tnsr::iaa<DataVector, Dim>*> phi_normal_dot_flux,
const tnsr::aa<DataVector, Dim>& spacetime_metric,
const tnsr::aa<DataVector, Dim>& pi,
const tnsr::iaa<DataVector, Dim>& phi, const Scalar<DataVector>& gamma1,
const Scalar<DataVector>& gamma2, const Scalar<DataVector>& lapse,
const tnsr::I<DataVector, Dim>& shift,
const tnsr::II<DataVector, Dim>& inverse_spatial_metric,
const tnsr::i<DataVector, Dim>& unit_normal) noexcept;
};
} // namespace GeneralizedHarmonic
| 40.75 | 91 | 0.669641 | marissawalker |
4324317089a25b20113fc40180491616fda2cf7a | 644 | cpp | C++ | Spoonity/src/Platform/OpenGL/OpenGLUniformBuffer.cpp | Revelation2106/Spoonity | 7e1a5600ce12a741c39cfd73e5491bda5f804a41 | [
"Apache-2.0"
] | null | null | null | Spoonity/src/Platform/OpenGL/OpenGLUniformBuffer.cpp | Revelation2106/Spoonity | 7e1a5600ce12a741c39cfd73e5491bda5f804a41 | [
"Apache-2.0"
] | null | null | null | Spoonity/src/Platform/OpenGL/OpenGLUniformBuffer.cpp | Revelation2106/Spoonity | 7e1a5600ce12a741c39cfd73e5491bda5f804a41 | [
"Apache-2.0"
] | null | null | null | #include "SpoonityPCH.h"
#include "Platform//OpenGL/OpenGLUniformBuffer.h"
#include <glad/glad.h>
namespace Spoonity {
OpenGLUniformBuffer::OpenGLUniformBuffer(uint32_t size, uint32_t binding)
{
glCreateBuffers(1, &m_RendererID);
glNamedBufferData(m_RendererID, size, nullptr, GL_DYNAMIC_DRAW); // TODO: investigate usage hint
glBindBufferBase(GL_UNIFORM_BUFFER, binding, m_RendererID);
}
OpenGLUniformBuffer::~OpenGLUniformBuffer()
{
glDeleteBuffers(1, &m_RendererID);
}
void OpenGLUniformBuffer::SetData(const void* data, uint32_t size, uint32_t offset)
{
glNamedBufferSubData(m_RendererID, offset, size, data);
}
}
| 23.851852 | 98 | 0.773292 | Revelation2106 |
4325554a7c9e2d9c6a674488fae98ac6966243e6 | 929 | cpp | C++ | project_euler/023/23.cpp | jason24585/practice | 6f3f961f766d80c73e1855e4b6f4cb167625a22a | [
"MIT"
] | null | null | null | project_euler/023/23.cpp | jason24585/practice | 6f3f961f766d80c73e1855e4b6f4cb167625a22a | [
"MIT"
] | null | null | null | project_euler/023/23.cpp | jason24585/practice | 6f3f961f766d80c73e1855e4b6f4cb167625a22a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#define LIMIT 28123
/* Check if number is abundant */
bool isAbundant(int x){
int sum = 0;
for(int i = 1; i <= sqrt(x); i++){
if(x % i == 0){
sum += i;
if((x/i) != i && x/i != x){
sum += x/i;
}
}
}
return sum > x;
}
int main(){
int ans = 0;
std::vector<int> abundants;
for(int i = 0; i <= LIMIT; i++){
bool found = false;
/* Checks if number is the sum of two abundant numbers */
for(int j = 0; j < abundants.size(); j++){
if(isAbundant(i - abundants[j])){
found = true;
break;
}
}
if(!found){
ans += i;
}
if(isAbundant(i)){
abundants.push_back(i);
}
}
std::cout << ans << std::endl;
return 0;
}
| 20.195652 | 65 | 0.430571 | jason24585 |
43265c0729d6236f6b36f400e96f35da53c60d65 | 12,265 | cxx | C++ | osprey/common/targ_info/generate/isa_hazards_gen.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/targ_info/generate/isa_hazards_gen.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/targ_info/generate/isa_hazards_gen.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2003, 2004 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
*/
// isa_hazards_gen.cxx
/////////////////////////////////////
//
// Description:
//
// Generate a description of the ISA hazards.
//
/////////////////////////////////////
//
// $Revision: 1.1.1.1 $
// $Date: 2005/10/21 19:00:00 $
// $Author: marcel $
// $Source: /proj/osprey/CVS/open64/osprey1.0/common/targ_info/generate/isa_hazards_gen.cxx,v $
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <list>
#include "topcode.h"
#include "gen_util.h"
#include "targ_isa_subset.h"
#include "isa_hazards_gen.h"
#include "bstring.h"
struct isa_hazard {
const char *name; // hazard name
};
struct haz_desc {
isa_hazard *type;
int data;
int pre_ops;
int post_ops;
int subsets[ISA_SUBSET_MAX+1];
};
struct op_haz {
haz_desc *desc;
struct op_haz *next;
int index;
};
static std::list<ISA_HAZARD> hazards; // All the hazards
static op_haz *op_hazards[TOP_count+1];
static std::list<op_haz *> op_hazards_list;
static haz_desc *current_haz_desc;
static int haz_index;
static const char * const interface[] = {
"/* ====================================================================",
" * ====================================================================",
" *",
" * Description:",
" *",
" * A description of the ISA hazards. The description exports",
" * the following:",
" *",
" * typedef (enum) ISA_HAZARD",
" * An enumeration of the hazard types, and ISA_HAZARD_UNDEFINED.",
" *",
" * typedef (struct) ISA_HAZARD_INFO",
" * Describes a particular hazard. The contents are private.",
" *",
" * BOOL ISA_HAZARD_TOP_Has_Hazard(TOP topcode)",
" * Returns TRUE if the instruction specified by 'topcode'",
" * has a hazard.",
" *",
" * ISA_HAZARD_INFO *ISA_HAZARD_First(TOP topcode)",
" * Get the first hazard description for 'topcode'.",
" *",
" * ISA_HAZARD_INFO *ISA_HAZARD_Next(ISA_HAZARD_INFO *info)",
" * Gets the next hazard description when a 'topcode' has",
" * more than one hazard.",
" *",
" * ISA_HAZARD ISA_HAZARD_Type(ISA_HAZARD_INFO *info)",
" * Returns the type of the hazard.",
" *",
" * INT ISA_HAZARD_Data(ISA_HAZARD_INFO *info)",
" * Returns the hazard specific data.",
" *",
" * INT ISA_HAZARD_Pre_Ops(ISA_HAZARD_INFO *info)",
" * Returns the number of OPs that must precede the instruction",
" * with the hazard.",
" *",
" * INT ISA_HAZARD_Post_Ops(ISA_HAZARD_INFO *info)",
" * Returns the number of OPs that must follow the instruction",
" * with the hazard.",
" *",
" * void ISA_HAZARD_Initialize(void)",
" * Initializes the hazard description data for ISA_SUBSET_Value."
" * This may only be called once (if not called at all the description",
" * contains the hazards for all ISAs).",
" *",
" * ====================================================================",
" * ====================================================================",
" */",
NULL
};
/////////////////////////////////////
void ISA_Hazards_Begin( const char* /* name */ )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
}
/////////////////////////////////////
ISA_HAZARD Hazard_Create( const char *name )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
ISA_HAZARD result = new isa_hazard;
memset(result, 0, sizeof(isa_hazard));
hazards.push_back(result);
result->name = name;
return result;
}
/////////////////////////////////////
void Hazard_Group( TOP topcode, ... )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
va_list ap;
TOP opcode;
int count = 0;
current_haz_desc = new haz_desc;
memset(current_haz_desc, 0, sizeof(haz_desc));
va_start(ap,topcode);
for (opcode = topcode;
opcode != TOP_UNDEFINED;
opcode = static_cast<TOP>(va_arg(ap,int))) {
op_haz *op_hazard = new op_haz;
op_hazards_list.push_back(op_hazard);
op_hazard->desc = current_haz_desc;
op_hazard->next = op_hazards[(int)opcode];
op_hazard->index = ++haz_index;
op_hazards[(int)opcode] = op_hazard;
++count;
}
va_end(ap);
if (count == 0) {
fprintf(stderr, "### Warning: hazard group is empty\n");
}
}
/////////////////////////////////////
void Hazard_Type( ISA_HAZARD isa_hazard )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
current_haz_desc->type = isa_hazard;
}
/////////////////////////////////////
void Hazard_Data( int data )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
current_haz_desc->data = data;
}
/////////////////////////////////////
void Hazard_Post_Ops( int ops )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
current_haz_desc->post_ops = ops;
}
/////////////////////////////////////
void Hazard_Pre_Ops( int ops )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
current_haz_desc->pre_ops = ops;
}
/////////////////////////////////////
void Hazard_ISA( ISA_SUBSET isa )
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
if ((unsigned)isa > (unsigned)ISA_SUBSET_MAX) {
fprintf(stderr, "### Error: isa value (%d) out of range (%d..%d)\n",
(int)isa, ISA_SUBSET_MIN, ISA_SUBSET_MAX);
exit(EXIT_FAILURE);
}
current_haz_desc->subsets[(int)isa] = true;
}
/////////////////////////////////////
void ISA_Hazards_End(void)
/////////////////////////////////////
// See interface description.
/////////////////////////////////////
{
int top;
bool first;
std::list<ISA_HAZARD>::iterator isi;
std::list<op_haz *>::iterator ophaz_iter;
const char * const isa_hazard_info_format =
" { ISA_HAZARD_%-9s, %d, %d, %2d, 0x%02x, %d }, /* %2d */\n";
#define FNAME "targ_isa_hazards"
char filename[1000];
sprintf(filename,"%s.h",FNAME);
FILE* hfile = fopen(filename,"w");
sprintf(filename,"%s.c",FNAME);
FILE* cfile = fopen(filename,"w");
sprintf(filename,"%s.Exported",FNAME);
FILE* efile = fopen(filename,"w");
fprintf(cfile,"#include \"topcode.h\"\n");
fprintf(cfile,"#include \"targ_isa_subset.h\"\n");
fprintf(cfile,"#include \"%s.h\"\n",FNAME);
sprintf (filename, "%s", FNAME);
Emit_Header (hfile, filename, interface);
fprintf(hfile,"#include \"targ_isa_subset.h\"\n");
fprintf(hfile,"typedef enum {");
first = true;
for ( isi = hazards.begin(); isi != hazards.end(); ++isi ) {
ISA_HAZARD hazard = *isi;
fprintf(hfile,"%c\n ISA_HAZARD_%s",first ? ' ' : ',',
hazard->name);
first = false;
}
fprintf(hfile,",\n ISA_HAZARD_UNDEFINED");
fprintf(hfile,"\n} ISA_HAZARD;\n");
fprintf(hfile, "\ntypedef struct {\n"
" ISA_HAZARD type;\n"
" mUINT16 data;\n"
" mUINT16 pre_ops;\n"
" mUINT16 post_ops;\n"
" mUINT8 isa_mask;\n"
" mUINT8 next;\n"
"} ISA_HAZARD_INFO;\n");
fprintf(efile, "ISA_HAZARD_hazard_info\n");
fprintf(cfile, "\nISA_HAZARD_INFO ISA_HAZARD_hazard_info[%d] = {\n",
haz_index + 1);
fprintf(cfile, isa_hazard_info_format,
"UNDEFINED", 0, 0, 0, 0, 0, 0);
for ( ophaz_iter = op_hazards_list.begin();
ophaz_iter != op_hazards_list.end();
++ophaz_iter
) {
int mask;
ISA_SUBSET subset;
op_haz *op_hazard = *ophaz_iter;
haz_desc *haz = op_hazard->desc;
op_haz *next = op_hazard->next;
mask = 0;
for (subset = ISA_SUBSET_MIN;
subset <= ISA_SUBSET_MAX;
subset = (ISA_SUBSET)((int)subset + 1)
) {
if ( haz->subsets[(int)subset] ) mask |= 1 << (int)subset;
}
fprintf(cfile, isa_hazard_info_format,
haz->type->name,
haz->data,
haz->pre_ops,
haz->post_ops,
mask,
next ? next->index : 0,
op_hazard->index);
}
fprintf(cfile, "};\n");
fprintf(efile, "ISA_HAZARD_hazard_index\n");
fprintf(cfile, "\nmUINT8 ISA_HAZARD_hazard_index[%d] = {\n", TOP_count);
for ( top = 0; top < TOP_count; ++top ) {
op_haz *op_hazard = op_hazards[top];
fprintf(cfile, " %3d, ", op_hazard ? op_hazard->index : 0);
fprintf(cfile, "/* %-9s */\n", TOP_Name((TOP)top));
}
fprintf(cfile, "};\n");
fprintf(hfile, "\ninline BOOL ISA_HAZARD_TOP_Has_Hazard(TOP topcode)\n"
"{\n"
" extern mUINT8 ISA_HAZARD_hazard_index[%d];\n"
" return ISA_HAZARD_hazard_index[(INT)topcode] != 0;\n"
"}\n",
TOP_count);
fprintf(hfile, "\ninline ISA_HAZARD_INFO *ISA_HAZARD_First(TOP topcode)\n"
"{\n"
" extern mUINT8 ISA_HAZARD_hazard_index[%d];\n"
" extern ISA_HAZARD_INFO ISA_HAZARD_hazard_info[%d];\n"
" INT index = ISA_HAZARD_hazard_index[(INT)topcode];\n"
" return index ? ISA_HAZARD_hazard_info + index : (ISA_HAZARD_INFO *)0;\n"
"}\n",
TOP_count,
haz_index + 1);
fprintf(hfile, "\ninline ISA_HAZARD_INFO *ISA_HAZARD_Next(ISA_HAZARD_INFO *info)\n"
"{\n"
" extern ISA_HAZARD_INFO ISA_HAZARD_hazard_info[%d];\n"
" INT index = info->next;\n"
" return index ? ISA_HAZARD_hazard_info + index : (ISA_HAZARD_INFO *)0;\n"
"}\n",
haz_index + 1);
fprintf(hfile, "\ninline ISA_HAZARD ISA_HAZARD_Type(ISA_HAZARD_INFO *info)\n"
"{\n"
" return info->type;\n"
"}\n");
fprintf(hfile, "\ninline INT ISA_HAZARD_Data(ISA_HAZARD_INFO *info)\n"
"{\n"
" return info->data;\n"
"}\n");
fprintf(hfile, "\ninline INT ISA_HAZARD_Pre_Ops(ISA_HAZARD_INFO *info)\n"
"{\n"
" return info->pre_ops;\n"
"}\n");
fprintf(hfile, "\ninline INT ISA_HAZARD_Post_Ops(ISA_HAZARD_INFO *info)\n"
"{\n"
" return info->post_ops;\n"
"}\n");
fprintf(hfile, "\nextern void ISA_HAZARD_Initialize(void);\n");
fprintf(efile, "ISA_HAZARD_Initialize\n");
fprintf(cfile, "\nvoid ISA_HAZARD_Initialize(void)\n"
"{\n"
" INT top;\n"
" INT mask = 1 << (INT)ISA_SUBSET_Value;\n"
" for ( top = 0; top < TOP_count; ++top ) {\n"
" INT j, k;\n"
" INT i = ISA_HAZARD_hazard_index[top];\n"
" for (j = i; j != 0; j = k) {\n"
" for (k = ISA_HAZARD_hazard_info[j].next;\n"
" k != 0 && (ISA_HAZARD_hazard_info[k].isa_mask & mask) == 0;\n"
" k = ISA_HAZARD_hazard_info[k].next\n"
" );\n"
" ISA_HAZARD_hazard_info[j].next = k;\n"
" }\n"
" if ((ISA_HAZARD_hazard_info[i].isa_mask & mask) == 0) {\n"
" ISA_HAZARD_hazard_index[top] = ISA_HAZARD_hazard_info[i].next;\n"
" }\n"
" }\n"
"}\n");
Emit_Footer (hfile);
fclose(hfile);
fclose(efile);
fclose(cfile);
}
| 28.858824 | 96 | 0.57179 | sharugupta |
432a20539f926e33bd6e6229a137874ea1ca76bb | 9,233 | cpp | C++ | Source/Urho3D/Engine/DebugHud.cpp | sabotage3d/Urho3D | 3dfb4a4c0bfa8a7da82b934de0ce7161fec7965c | [
"BSD-2-Clause",
"Apache-2.0"
] | 1 | 2016-09-19T16:08:51.000Z | 2016-09-19T16:08:51.000Z | Source/Urho3D/Engine/DebugHud.cpp | fireword/Urho3D | 180936cebdf6bdcbb6eb74a0959f5616e208ca5d | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | Source/Urho3D/Engine/DebugHud.cpp | fireword/Urho3D | 180936cebdf6bdcbb6eb74a0959f5616e208ca5d | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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 "../Precompiled.h"
#include "../Core/CoreEvents.h"
#include "../Core/Profiler.h"
#include "../Core/EventProfiler.h"
#include "../Core/Context.h"
#include "../Engine/DebugHud.h"
#include "../Engine/Engine.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Renderer.h"
#include "../Resource/ResourceCache.h"
#include "../IO/Log.h"
#include "../UI/Font.h"
#include "../UI/Text.h"
#include "../UI/UI.h"
#include "../DebugNew.h"
namespace Urho3D
{
static const char* qualityTexts[] =
{
"Low",
"Med",
"High"
};
static const char* shadowQualityTexts[] =
{
"16bit Simple",
"24bit Simple",
"16bit PCF",
"24bit PCF",
"VSM",
"Blurred VSM"
};
DebugHud::DebugHud(Context* context) :
Object(context),
profilerMaxDepth_(M_MAX_UNSIGNED),
profilerInterval_(1000),
useRendererStats_(false),
mode_(DEBUGHUD_SHOW_NONE)
{
UI* ui = GetSubsystem<UI>();
UIElement* uiRoot = ui->GetRoot();
statsText_ = new Text(context_);
statsText_->SetAlignment(HA_LEFT, VA_TOP);
statsText_->SetPriority(100);
statsText_->SetVisible(false);
uiRoot->AddChild(statsText_);
modeText_ = new Text(context_);
modeText_->SetAlignment(HA_LEFT, VA_BOTTOM);
modeText_->SetPriority(100);
modeText_->SetVisible(false);
uiRoot->AddChild(modeText_);
profilerText_ = new Text(context_);
profilerText_->SetAlignment(HA_RIGHT, VA_TOP);
profilerText_->SetPriority(100);
profilerText_->SetVisible(false);
uiRoot->AddChild(profilerText_);
memoryText_ = new Text(context_);
memoryText_->SetAlignment(HA_LEFT, VA_BOTTOM);
memoryText_->SetPriority(100);
memoryText_->SetVisible(false);
uiRoot->AddChild(memoryText_);
eventProfilerText_ = new Text(context_);
eventProfilerText_->SetAlignment(HA_RIGHT, VA_TOP);
eventProfilerText_->SetPriority(100);
eventProfilerText_->SetVisible(false);
uiRoot->AddChild(eventProfilerText_);
SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(DebugHud, HandlePostUpdate));
}
DebugHud::~DebugHud()
{
statsText_->Remove();
modeText_->Remove();
profilerText_->Remove();
memoryText_->Remove();
eventProfilerText_->Remove();
}
void DebugHud::Update()
{
Graphics* graphics = GetSubsystem<Graphics>();
Renderer* renderer = GetSubsystem<Renderer>();
if (!renderer || !graphics)
return;
// Ensure UI-elements are not detached
if (!statsText_->GetParent())
{
UI* ui = GetSubsystem<UI>();
UIElement* uiRoot = ui->GetRoot();
uiRoot->AddChild(statsText_);
uiRoot->AddChild(modeText_);
uiRoot->AddChild(profilerText_);
}
if (statsText_->IsVisible())
{
unsigned primitives, batches;
if (!useRendererStats_)
{
primitives = graphics->GetNumPrimitives();
batches = graphics->GetNumBatches();
}
else
{
primitives = renderer->GetNumPrimitives();
batches = renderer->GetNumBatches();
}
String stats;
stats.AppendWithFormat("Triangles %u\nBatches %u\nViews %u\nLights %u\nShadowmaps %u\nOccluders %u",
primitives,
batches,
renderer->GetNumViews(),
renderer->GetNumLights(true),
renderer->GetNumShadowMaps(true),
renderer->GetNumOccluders(true));
if (!appStats_.Empty())
{
stats.Append("\n");
for (HashMap<String, String>::ConstIterator i = appStats_.Begin(); i != appStats_.End(); ++i)
stats.AppendWithFormat("\n%s %s", i->first_.CString(), i->second_.CString());
}
statsText_->SetText(stats);
}
if (modeText_->IsVisible())
{
String mode;
mode.AppendWithFormat("Tex:%s Mat:%s Spec:%s Shadows:%s Size:%i Quality:%s Occlusion:%s Instancing:%s API:%s",
qualityTexts[renderer->GetTextureQuality()],
qualityTexts[renderer->GetMaterialQuality()],
renderer->GetSpecularLighting() ? "On" : "Off",
renderer->GetDrawShadows() ? "On" : "Off",
renderer->GetShadowMapSize(),
shadowQualityTexts[renderer->GetShadowQuality()],
renderer->GetMaxOccluderTriangles() > 0 ? "On" : "Off",
renderer->GetDynamicInstancing() ? "On" : "Off",
graphics->GetApiName().CString());
modeText_->SetText(mode);
}
Profiler* profiler = GetSubsystem<Profiler>();
EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
if (profiler)
{
if (profilerTimer_.GetMSec(false) >= profilerInterval_)
{
profilerTimer_.Reset();
if (profilerText_->IsVisible())
profilerText_->SetText(profiler->PrintData(false, false, profilerMaxDepth_));
profiler->BeginInterval();
if (eventProfiler)
{
if (eventProfilerText_->IsVisible())
eventProfilerText_->SetText(eventProfiler->PrintData(false, false, profilerMaxDepth_));
eventProfiler->BeginInterval();
}
}
}
if (memoryText_->IsVisible())
memoryText_->SetText(GetSubsystem<ResourceCache>()->PrintMemoryUsage());
}
void DebugHud::SetDefaultStyle(XMLFile* style)
{
if (!style)
return;
statsText_->SetDefaultStyle(style);
statsText_->SetStyle("DebugHudText");
modeText_->SetDefaultStyle(style);
modeText_->SetStyle("DebugHudText");
profilerText_->SetDefaultStyle(style);
profilerText_->SetStyle("DebugHudText");
memoryText_->SetDefaultStyle(style);
memoryText_->SetStyle("DebugHudText");
eventProfilerText_->SetDefaultStyle(style);
eventProfilerText_->SetStyle("DebugHudText");
}
void DebugHud::SetMode(unsigned mode)
{
statsText_->SetVisible((mode & DEBUGHUD_SHOW_STATS) != 0);
modeText_->SetVisible((mode & DEBUGHUD_SHOW_MODE) != 0);
profilerText_->SetVisible((mode & DEBUGHUD_SHOW_PROFILER) != 0);
memoryText_->SetVisible((mode & DEBUGHUD_SHOW_MEMORY) != 0);
eventProfilerText_->SetVisible((mode & DEBUGHUD_SHOW_EVENTPROFILER) != 0);
memoryText_->SetPosition(0, modeText_->IsVisible() ? modeText_->GetHeight() * -2 : 0);
#ifdef URHO3D_PROFILING
// Event profiler is created on engine initialization if "EventProfiler" parameter is set
EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
if (eventProfiler)
EventProfiler::SetActive((mode & DEBUGHUD_SHOW_EVENTPROFILER) != 0);
#endif
mode_ = mode;
}
void DebugHud::SetProfilerMaxDepth(unsigned depth)
{
profilerMaxDepth_ = depth;
}
void DebugHud::SetProfilerInterval(float interval)
{
profilerInterval_ = Max((unsigned)(interval * 1000.0f), 0U);
}
void DebugHud::SetUseRendererStats(bool enable)
{
useRendererStats_ = enable;
}
void DebugHud::Toggle(unsigned mode)
{
SetMode(GetMode() ^ mode);
}
void DebugHud::ToggleAll()
{
Toggle(DEBUGHUD_SHOW_ALL);
}
XMLFile* DebugHud::GetDefaultStyle() const
{
return statsText_->GetDefaultStyle(false);
}
float DebugHud::GetProfilerInterval() const
{
return (float)profilerInterval_ / 1000.0f;
}
void DebugHud::SetAppStats(const String& label, const Variant& stats)
{
SetAppStats(label, stats.ToString());
}
void DebugHud::SetAppStats(const String& label, const String& stats)
{
bool newLabel = !appStats_.Contains(label);
appStats_[label] = stats;
if (newLabel)
appStats_.Sort();
}
bool DebugHud::ResetAppStats(const String& label)
{
return appStats_.Erase(label);
}
void DebugHud::ClearAppStats()
{
appStats_.Clear();
}
void DebugHud::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace PostUpdate;
Update();
}
}
| 29.783871 | 119 | 0.643453 | sabotage3d |
432d3cdb6cb53cabeeaa82f26861c99b128575f4 | 2,139 | cpp | C++ | tests/dll_tests/raw_api_test.cpp | tshino/softcam | be472efd889900dcd7e147b4f9fed866dd738a8c | [
"MIT"
] | 8 | 2020-11-21T18:33:52.000Z | 2022-03-29T14:42:03.000Z | tests/dll_tests/raw_api_test.cpp | tshino/softcam | be472efd889900dcd7e147b4f9fed866dd738a8c | [
"MIT"
] | 4 | 2021-01-11T08:37:08.000Z | 2021-12-19T15:02:56.000Z | tests/dll_tests/raw_api_test.cpp | tshino/softcam | be472efd889900dcd7e147b4f9fed866dd738a8c | [
"MIT"
] | 2 | 2021-01-22T04:52:19.000Z | 2022-03-29T14:42:05.000Z | #include <softcam/softcam.h>
#include <gtest/gtest.h>
namespace {
TEST(scCreateCamera, Basic) {
{
void* cam = scCreateCamera(320, 240, 60);
EXPECT_NE(cam, nullptr);
EXPECT_NO_THROW({ scDeleteCamera(cam); });
}{
void* cam = scCreateCamera(1920, 1080, 30);
EXPECT_NE(cam, nullptr);
EXPECT_NO_THROW({ scDeleteCamera(cam); });
}
}
TEST(scCreateCamera, MultipleInstancingFails) {
void* cam1 = scCreateCamera(320, 240, 60);
void* cam2 = scCreateCamera(320, 240, 60);
EXPECT_NE(cam1, nullptr);
EXPECT_EQ(cam2, nullptr);
scDeleteCamera(cam2);
scDeleteCamera(cam1);
}
TEST(scCreateCamera, FramerateIsOptional) {
void* cam = scCreateCamera(320, 240);
EXPECT_NE(cam, nullptr);
scDeleteCamera(cam);
}
TEST(scCreateCamera, ZeroMeansUnlimitedVariableFramerate) {
void* cam = scCreateCamera(320, 240, 0.0f);
EXPECT_NE(cam, nullptr);
scDeleteCamera(cam);
}
TEST(scCreateCamera, InvalidArgs) {
void* cam;
cam = scCreateCamera(0, 240, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
cam = scCreateCamera(320, 0, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
cam = scCreateCamera(0, 0, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
cam = scCreateCamera(-320, 240, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
cam = scCreateCamera(320, -240, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
cam = scCreateCamera(320, 240, -60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
}
TEST(scCreateCamera, TooLarge) {
void* cam;
cam = scCreateCamera(32000, 240, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
cam = scCreateCamera(320, 24000, 60);
EXPECT_EQ(cam, nullptr);
scDeleteCamera(cam);
}
TEST(scDeleteCamera, IgnoresNullPointer) {
scDeleteCamera(nullptr);
}
TEST(scDeleteCamera, IgnoresDoubleFree) {
void* cam = scCreateCamera(320, 240, 60);
scDeleteCamera(cam);
scDeleteCamera(cam);
}
TEST(scDeleteCamera, IgnoresInvalidPointer) {
int x = 0;
scDeleteCamera(&x);
}
} //namespace
| 22.051546 | 59 | 0.657317 | tshino |
432d4b862f254ea750cbd8e8506df12d63aafec5 | 5,509 | hh | C++ | src/modules/Common/mf_api.hh | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 31 | 2015-12-15T19:14:10.000Z | 2021-12-31T17:40:21.000Z | src/modules/Common/mf_api.hh | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 5 | 2015-12-04T08:06:47.000Z | 2020-08-09T21:49:46.000Z | src/modules/Common/mf_api.hh | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 21 | 2015-11-05T08:25:45.000Z | 2021-06-19T02:24:50.000Z |
/*
Copyright (C) 1999-2008 by Mark D. Hill and David A. Wood for the
Wisconsin Multifacet Project. Contact: gems@cs.wisc.edu
http://www.cs.wisc.edu/gems/
--------------------------------------------------------------------
This file is part of the Ruby Multiprocessor Memory System Simulator,
a component of the Multifacet GEMS (General Execution-driven
Multiprocessor Simulator) software toolset originally developed at
the University of Wisconsin-Madison.
Ruby was originally developed primarily by Milo Martin and Daniel
Sorin with contributions from Ross Dickson, Carl Mauer, and Manoj
Plakal.
Substantial further development of Multifacet GEMS at the
University of Wisconsin was performed by Alaa Alameldeen, Brad
Beckmann, Jayaram Bobba, Ross Dickson, Dan Gibson, Pacia Harper,
Derek Hower, Milo Martin, Michael Marty, Carl Mauer, Michelle Moravan,
Kevin Moore, Andrew Phelps, Manoj Plakal, Daniel Sorin, Haris Volos,
Min Xu, and Luke Yen.
--------------------------------------------------------------------
If your use of this software contributes to a published paper, we
request that you (1) cite our summary paper that appears on our
website (http://www.cs.wisc.edu/gems/) and (2) e-mail a citation
for your published paper to gems@cs.wisc.edu.
If you redistribute derivatives of this software, we request that
you notify us and either (1) ask people to register with us at our
website (http://www.cs.wisc.edu/gems/) or (2) collect registration
information and periodically send it to us.
--------------------------------------------------------------------
Multifacet GEMS 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.
Multifacet GEMS 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 the Multifacet GEMS; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA
The GNU General Public License is contained in the file LICENSE.
### END HEADER ###
*/
/*------------------------------------------------------------------------*/
/* Includes */
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/* Macro declarations */
/*------------------------------------------------------------------------*/
#ifndef _MF_MEMORY_API_H_
#define _MF_MEMORY_API_H_
#define SIM_ENHANCE
#define SIM_NET_PORTS
#define SIM_MEMORY
typedef struct CacheConfig
{
int valid;
unsigned numSets;
unsigned blockSize;
unsigned associativity;
} CacheConfigStruct;
typedef struct BiNBufferRequest_t
{
unsigned int numberOfPoints;
unsigned int* bufferSize;
unsigned int* bandwidthRequirement;
unsigned int* cacheImpact;
int nodeID;
int bufferID;
} BiNBufferRequest;
void scheduleCB(void (*)(void*), void*, uint64_t);
uint64_t GetSystemTime();
#ifdef SIM_MEMORY
#define SIM_MEMORY_READ 0
#define SIM_MEMORY_WRITE 1
#define SIM_MEMORY_SPM_READ 2
#define SIM_MEMORY_SPM_WRITE 3
#define SIM_MEMORY_BIC_READ 4
#define SIM_MEMORY_BIC_READ_COPY 5
#define SIM_MEMORY_BIC_WRITE 6
typedef struct gem5MemoryInterfaceMemRequest_t
{
// Indicates that a response to this message is being solicited. Not
// responding to this message is an error. 0 implies 'no', otherwise 'yes'
int responseNeeded;
// A unique ID marking this request
uint64_t requestID;
// Time the request was originated, measured in cycles. This is the time that
// a CPU emitted the request
uint64_t emitTime;
// Device source. This is the node ID of the source from enumerated CPUs or
// accelerators
int source;
// Machine type enum work-around
int sourceType;
// Device target
int target;
int targetType;
// Program counter
uint64_t sourcePC;
// Zero-normalized priority. priority of zero is 'normal', higher is better.
int priority;
uint64_t logicalAddr;
uint64_t physicalAddr;
uint64_t size;
int bufferID;
int bufferSize;
// Marks the access as a read/write/eviction.
int type;
int solicitingDeviceID;
} gem5MemoryInterfaceMemRequest;
typedef struct gem5MemoryInterfaceMemResponse_t
{
// Relates to an ID associated with MemRequest
uint64_t requestID;
int priority;
int source;
int sourceType;
int target;
int targetType;
uint64_t logicalAddr;
uint64_t physicalAddr;
uint64_t size;
int bufferID;
int bufferSize;
int type;
} gem5MemoryInterfaceMemResponse;
typedef struct mf_simics_memory_interface_api_x
{
void (*RegisterMemMsgReciever)(void* obj, int controller,
void (*handler)(const gem5MemoryInterfaceMemRequest* mReq, void* args),
void* args);
void (*EmitMemMsgResponse)(void* obj, int controller,
const gem5MemoryInterfaceMemResponse* mResp, unsigned int delay);
int (*GetControllerCount)(void* obj);
uint64_t (*CurrentTime)(void* obj);
} mf_simics_memory_interface_api;
#endif
#endif //_MF_MEMORY_API_H_
| 30.436464 | 79 | 0.662552 | cdsc-github |
4331ea95d827476ace493f114ed50046ae12c72b | 2,269 | cpp | C++ | test/function/scalar/bitwise_notand.cpp | TobiasLudwig/boost.simd | c04d0cc56747188ddb9a128ccb5715dd3608dbc1 | [
"BSL-1.0"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | test/function/scalar/bitwise_notand.cpp | remymuller/boost.simd | 3caefb7ee707e5f68dae94f8f31f72f34b7bb5de | [
"BSL-1.0"
] | null | null | null | test/function/scalar/bitwise_notand.cpp | remymuller/boost.simd | 3caefb7ee707e5f68dae94f8f31f72f34b7bb5de | [
"BSL-1.0"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/function/scalar/bitwise_notand.hpp>
#include <scalar_test.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/minf.hpp>
#include <boost/simd/constant/mone.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/zero.hpp>
STF_CASE_TPL (" bitwise_notand real", STF_IEEE_TYPES)
{
namespace bs = boost::simd;
using bs::bitwise_notand;
using r_t = decltype(bitwise_notand(T(), T()));
// return type conformity test
STF_EXPR_IS(bitwise_notand(T(), T()), T);
// specific values tests
#ifndef BOOST_SIMD_NO_INVALIDS
STF_EQUAL(bitwise_notand(bs::Inf<T>(), bs::Inf<T>()), bs::Zero<r_t>());
STF_EQUAL(bitwise_notand(bs::Minf<T>(), bs::Minf<T>()), bs::Zero<r_t>());
STF_EQUAL(bitwise_notand(bs::Nan<T>(), bs::Nan<T>()), bs::Zero<r_t>());
#endif
STF_EQUAL(bitwise_notand(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<r_t>());
STF_EQUAL(bitwise_notand(bs::Zero<T>(),bs::One<T>()), bs::One<r_t>());
} // end of test for floating_
STF_CASE_TPL("bitwise_notand mix", STF_IEEE_TYPES)
{
namespace bs = boost::simd;
namespace bd = boost::dispatch;
using bs::bitwise_notand;
using siT = bd::as_integer_t<T>;
using uiT = bd::as_integer_t<T, unsigned>;
// return type conformity test
STF_EXPR_IS(bitwise_notand(T(),uiT()), T);
STF_EXPR_IS(bitwise_notand(T(),siT()), T);
STF_EXPR_IS(bitwise_notand(uiT(), T()), uiT);
STF_EXPR_IS(bitwise_notand(siT(), T()), siT);
// specific values tests
STF_IEEE_EQUAL(bitwise_notand(bs::Zero<T>(),bs::Valmax<uiT>()), bs::Nan<T>());
STF_IEEE_EQUAL(bitwise_notand(bs::Zero<T>(), bs::Mone<siT>()), bs::Nan<T>());
STF_EQUAL(bitwise_notand(bs::Zero<siT>(),bs::Nan<T>()), bs::Mone<siT>());
STF_EQUAL(bitwise_notand(bs::Zero<uiT>(), bs::Nan<T>()), bs::Valmax<uiT>());
}
| 37.816667 | 100 | 0.62803 | TobiasLudwig |
4335b6a5b7a2c1d48a95aa209da16a158fe90e27 | 2,312 | cc | C++ | src/fail.cc | hamish-milne/windowjs | 4e50ac3bd5c418966f3fac91698563908f156303 | [
"MIT"
] | 1 | 2022-01-12T09:49:54.000Z | 2022-01-12T09:49:54.000Z | src/fail.cc | hamish-milne/windowjs | 4e50ac3bd5c418966f3fac91698563908f156303 | [
"MIT"
] | 1 | 2022-01-13T04:54:24.000Z | 2022-01-13T04:54:24.000Z | src/fail.cc | hamish-milne/windowjs | 4e50ac3bd5c418966f3fac91698563908f156303 | [
"MIT"
] | null | null | null | #include "fail.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <v8/src/base/debug/stack_trace.h>
#include "platform.h"
#include "version.h"
#if defined(WINDOWJS_WIN)
#include <windows.h>
#else
#include <signal.h>
#endif
static const char intro[] =
"The program has crashed.\n\nPlease file a bug report at "
"https://github.com/windowjs/windowjs/issues.\n\n";
#if defined(WINDOWJS_WIN)
static LONG OnUnhandledException(_EXCEPTION_POINTERS* ExceptionInfo) {
std::string description = intro;
#if !defined(WINDOWJS_RELEASE_BUILD)
description +=
"Use Ctrl+C to copy the stack trace below and include it "
"in the bug report.\n\n";
description += v8::base::debug::StackTrace().ToString();
#endif
description += "\n\n" + GetVersionString();
UINT flags = MB_OK | MB_ICONERROR | MB_SETFOREGROUND;
MessageBox(nullptr, description.c_str(), "Crash in Window.js", flags);
return EXCEPTION_EXECUTE_HANDLER;
}
void InitFail() {
SetUnhandledExceptionFilter(OnUnhandledException);
}
void Fail(const char* reason, ...) {
char buffer[1024];
va_list ap;
va_start(ap, reason);
vsnprintf(buffer, 1024, reason, ap);
std::string description = intro;
description +=
"Use Ctrl+C to copy the message below and include it in the "
"bug report.\n\n";
description += buffer;
description += "\n\n" + GetVersionString();
UINT flags = MB_OK | MB_ICONERROR | MB_SETFOREGROUND;
MessageBox(nullptr, description.c_str(), "Crash in Window.js", flags);
abort();
}
#else
static void HandleSegfault(int ignored) {
fprintf(stderr, "%s", intro);
#if !defined(WINDOWJS_RELEASE_BUILD)
fprintf(stderr, "Include the stack trace below in the bug report:\n\n%s\n",
v8::base::debug::StackTrace().ToString().c_str());
#endif
fprintf(stderr, "%s\n", GetVersionString().c_str());
abort();
}
void InitFail() {
signal(SIGSEGV, HandleSegfault);
}
void Fail(const char* reason, ...) {
fprintf(stderr, "%s", intro);
va_list ap;
va_start(ap, reason);
vfprintf(stderr, reason, ap);
fprintf(stderr, "\n");
fprintf(stderr, "%s\n", GetVersionString().c_str());
abort();
}
#endif // WINDOWJS_WIN
void ErrorQuit(const char* reason, ...) {
va_list ap;
va_start(ap, reason);
vfprintf(stderr, reason, ap);
exit(1);
}
| 22.230769 | 77 | 0.682958 | hamish-milne |
433b69c1f107beaf8636f80fe7774f9622696650 | 13,890 | hpp | C++ | include/utility/container/map.hpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | 2 | 2017-12-10T10:59:48.000Z | 2017-12-13T04:11:14.000Z | include/utility/container/map.hpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | null | null | null | include/utility/container/map.hpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | null | null | null |
#ifndef __UTILITY_CONTAINER_MAP__
#define __UTILITY_CONTAINER_MAP__
/**
* \file map.hpp
* \author Inochi Amaoto
*
*
*/
#include<utility/config/utility_config.hpp>
#include<utility/container/container_helper.hpp>
#include<utility/algorithm/move.hpp>
#include<utility/algorithm/swap.hpp>
#include<utility/algorithm/possible_swap.hpp>
#include<utility/container/pair.hpp>
#include<utility/container/compressed_pair.hpp>
#include<utility/container/white_black_tree.hpp>
#include<utility/trait/type/releations/is_same.hpp>
#include<utility/trait/type/miscellaneous/enable_if.hpp>
#include<utility/iterator/iterator_traits.hpp>
#include<utility/memory/addressof.hpp>
#include<utility/memory/allocator_traits.hpp>
namespace utility
{
namespace container
{
template
<
typename _Key,
typename _Value,
typename _Compare = algorithm::less<void>,
typename _Alloc = memory::allocator<container::pair<const _Key, _Value>>
>
class map
{
public:
class value_compare
{
protected:
_Compare __compare;
protected:
value_compare(const _Compare& __comp):
__compare(__comp)
{ }
public:
bool operator()(
container::pair<const _Key, _Value>& __x,
container::pair<const _Key, _Value>& __y
) const
{ return this->__compare(__get_key(__x), __get_key(__y));}
};
private:
typedef typename memory::allocator_traits<_Alloc>::template
rebind_alloc<container::pair<const _Key, _Value>>
__allocator;
typedef container::white_black_tree<
_Key, _Value, _Compare,
container::pair<const _Key, _Value>, __allocator>
__tree_type;
public:
typedef _Key key_type;
typedef _Value mapped_type;
typedef container::pair<const _Key, _Value> value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef _Compare key_compare;
typedef _Alloc allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
public:
typedef memory::allocator_traits<allocator_type>
allocator_traits_type;
public:
typedef typename allocator_traits_type::pointer pointer;
typedef typename allocator_traits_type::const_pointer const_pointer;
public:
typedef typename __tree_type::iterator iterator;
typedef typename __tree_type::const_iterator const_iterator;
typedef typename __tree_type::reverse_iterator
reverse_iterator;
typedef typename __tree_type::const_reverse_iterator
const_reverse_iterator;
private:
__tree_type __tree;
public:
map(): map(key_compare())
{ }
explicit map(
const key_compare& __comp,
const allocator_type& __alloc = allocator_type()
):__tree(__comp, __alloc)
{ }
explicit map(const allocator_type& __alloc):
__tree(__alloc)
{ }
template<typename _InputIterator,
typename
trait::type::miscellaneous::enable_if<
is_iterator<_InputIterator>::value,
bool
>::type = true
>
map(
_InputIterator __first, _InputIterator __last,
const _Compare& __comp = _Compare(),
const allocator_type __alloc = allocator_type()
): __tree(__first, __last, __comp, __alloc)
{ }
template<typename _InputIterator,
typename
trait::type::miscellaneous::enable_if<
is_iterator<_InputIterator>::value,
bool
>::type = true
>
map(
_InputIterator __first, _InputIterator __last,
const allocator_type __alloc
): __tree(__first, __last, __alloc)
{ }
map(const map& __other):
__tree(__other.__tree)
{ }
map(
const map& __other, const allocator_type __alloc
):__tree(__other.__tree, __alloc)
{ }
map(map&& __other):
__tree(algorithm::move(__other.__tree))
{ }
map(
map&& __other, const allocator_type __alloc
):__tree(algorithm::move(__other.__tree), __alloc)
{ }
map(
initializer_list<value_type> __initlist,
const _Compare __comp = _Compare(),
const allocator_type __alloc = allocator_type()
): __tree(__initlist, __comp, __alloc)
{ }
map(
initializer_list<value_type> __initlist,
const allocator_type __alloc
): __tree(__initlist, __alloc)
{ }
public:
map& operator=(const map& __other)
{
if(&__other != this)
{ this->__tree = __other.__tree;}
return *this;
}
map& operator=(map&& __other)
{
if(&__other != this)
{ this->__tree = algorithm::move(__other.__tree);}
return *this;
}
map& operator=(initializer_list<value_type> __initlist)
{
this->__tree = __initlist;
return *this;
}
public:
allocator_type get_allocator() const
{ return allocator_type{};}
public:
key_compare key_comp() const
{ return key_compare{};}
value_compare value_comp() const
{ return value_compare{key_compare{}};}
public:
iterator begin() noexcept
{ return this->__tree.begin();}
const_iterator begin() const noexcept
{ return this->__tree.begin();}
const_iterator cbegin() const noexcept
{ return this->__tree.cbegin();}
iterator end() noexcept
{ return this->__tree.end();}
const_iterator end() const noexcept
{ return this->__tree.end();}
const_iterator cend() const noexcept
{ return this->__tree.cend();}
public:
reverse_iterator rbegin() noexcept
{ return this->__tree.rbegin();}
const_reverse_iterator rbegin() const noexcept
{ return this->__tree.rbegin();}
const_reverse_iterator crbegin() const noexcept
{ return this->__tree.crbegin();}
reverse_iterator rend() noexcept
{ return this->__tree.rend();}
const_reverse_iterator rend() const noexcept
{ return this->__tree.rend();}
const_reverse_iterator crend() const noexcept
{ return this->__tree.crend();}
public:
bool empty() const noexcept
{ return this->__tree.empty();}
size_type size() const noexcept
{ return this->__tree.size();}
public:
container::pair<iterator, bool>
insert(const value_type& __val)
{ return this->__tree.insert_unique(__val);}
container::pair<iterator, bool>
insert(value_type&& __val)
{
return this->__tree.insert_unique(
algorithm::move(__val)
);
}
iterator insert(
const_iterator __hint, const value_type& __val
)
{ return this->__tree.insert_unique(__hint, __val);}
iterator insert(
const_iterator __hint, value_type&& __val
)
{
return this->__tree.insert_unique(
__hint, algorithm::move(__val)
);
}
public:
container::pair<iterator, bool>
insert_or_assign(const value_type& __val)
{
container::pair<iterator, bool> __tmp =
this->__tree.insert_unique(__val);
if(!(__tmp.second))
{ *(__tmp.first) = __val;}
return __tmp;
}
container::pair<iterator, bool>
insert_or_assign(value_type&& __val)
{
iterator __tmp = this->__tree.find(__val.first);
if(__tmp == this->end())
{
return container::pair<iterator, bool>{
this->__tree.insert_unique(algorithm::move(__val)),
true
};
}
*__tmp = algorithm::move(__val);
return container::pair<iterator, bool>{__tmp, false};
}
iterator insert_or_assign(
const_iterator __hint, const value_type& __val
)
{
iterator __tmp = this->__tree.find(__val.first);
if(__tmp == this->end())
{ return this->__tree.insert_unique(__hint, __val);}
*__tmp = __val;
return __tmp;
}
container::pair<iterator, bool>
insert_or_assign(
const_iterator __hint, value_type&& __val
)
{
iterator __tmp = this->__tree.find(__val.first);
if(__tmp == this->end())
{
return container::pair<iterator, bool>{
this->__tree.insert_unique(
__hint, algorithm::move(__val)
),true
};
}
*__tmp = algorithm::move(__val);
return container::pair<iterator, bool>{__tmp, false};
}
public:
template<typename... _Args>
container::pair<iterator, bool>
emplace(_Args&&... __args)
{
return this->__tree.emplace_unique(
algorithm::move(__args)...
);
}
template<typename... _Args>
iterator emplace_hint(
const_iterator __hint, _Args&&... __args
)
{
return this->__tree.emplace_unique(
__hint, algorithm::move(__args)...
);
}
public:
inline size_type count(const key_type& __key) const noexcept
{ return this->__tree.count(__key);}
public:
inline iterator lower_bound(const key_type& __key) noexcept
{ return this->__tree.lower_bound(__key);}
inline const_iterator lower_bound(const key_type& __key) const noexcept
{ return this->__tree.lower_bound(__key);}
inline iterator upper_bound(const key_type& __key) noexcept
{ return this->__tree.upper_bound(__key);}
inline const_iterator upper_bound(const key_type& __key) const noexcept
{ return this->__tree.upper_bound(__key);}
inline container::pair<iterator, iterator>
equal_range(const key_type& __key) noexcept
{
return container::pair<iterator, iterator>{
this->lower_bound(__key), this->upper_bound(__key)
};
}
inline container::pair<const_iterator, const_iterator>
equal_range(const key_type& __key) const noexcept
{
return container::pair<const_iterator, const_iterator>{
this->lower_bound(__key), this->upper_bound(__key)
};
}
public:
inline iterator find(const key_type& __key) noexcept
{ return this->__tree.find(__key);}
inline iterator find(const key_type& __key) const noexcept
{ return this->__tree.find(__key);}
public:
inline iterator erase(const_iterator __pos)
{ return this->__tree.erase(__pos);}
inline iterator erase(
const_iterator __first, const_iterator __last
)
{ return this->__tree.erase(__first, __last);}
inline size_type erase(const key_type& __key)
{ return this->__tree.erase(__key);}
public:
void clear()
{ this->__tree.clear();}
public:
void swap(map& __other) noexcept(
noexcept(__tree.swap(__other.__tree))
)
{ this->__tree.swap(__other.__tree);}
void possible_swap(map& __other) noexcept(
noexcept(__tree.possible_swap(__other.__tree))
)
{ this->__tree.possible_swap(__other.__tree);}
public:
bool operator==(const map& __y) const
{ return this->__tree == __y.__tree;}
bool operator<(const map& __y) const
{ return this->__tree < __y.__tree;}
};
template<
typename _Key, typename _Value,
typename _Compare, typename _Alloc
>
bool operator!=(
const map<_Key, _Value, _Compare, _Alloc>& __x,
const map<_Key, _Value, _Compare, _Alloc>& __y
)
{ return !(__x == __y);}
template<
typename _Key, typename _Value,
typename _Compare, typename _Alloc
>
bool operator>(
const map<_Key, _Value, _Compare, _Alloc>& __x,
const map<_Key, _Value, _Compare, _Alloc>& __y
)
{ return __y < __x;}
template<
typename _Key, typename _Value,
typename _Compare, typename _Alloc
>
bool operator<=(
const map<_Key, _Value, _Compare, _Alloc>& __x,
const map<_Key, _Value, _Compare, _Alloc>& __y
)
{ return !(__y < __x);}
template<
typename _Key, typename _Value,
typename _Compare, typename _Alloc
>
bool operator>=(
const map<_Key, _Value, _Compare, _Alloc>& __x,
const map<_Key, _Value, _Compare, _Alloc>& __y
)
{ return !(__x < __y);}
}
namespace algorithm
{
template<
typename _Key, typename _Value,
typename _Compare, typename _Alloc
>
void swap(
container::map<_Key, _Value, _Compare, _Alloc>& __x,
container::map<_Key, _Value, _Compare, _Alloc>& __y
) noexcept(noexcept(__x.swap(__y)))
{
__x.swap(__y);
}
template<
typename _Key, typename _Value,
typename _Compare, typename _Alloc
>
void possible_swap(
container::map<_Key, _Value, _Compare, _Alloc>& __x,
container::map<_Key, _Value, _Compare, _Alloc>& __y
) noexcept(noexcept(__x.possible_swap(__y)))
{
__x.possible_swap(__y);
}
}
}
#endif // ! __UTILITY_CONTAINER_MAP__
| 30.327511 | 79 | 0.588049 | SakuraLife |
433e66ff7a4fc235ddc6a26a7bb94e53ec1d18ac | 7,914 | cpp | C++ | audio/common/Semantic/jhcBindings.cpp | jconnell11/ALIA | f7a6c9dfd775fbd41239051aeed7775adb878b0a | [
"Apache-2.0"
] | null | null | null | audio/common/Semantic/jhcBindings.cpp | jconnell11/ALIA | f7a6c9dfd775fbd41239051aeed7775adb878b0a | [
"Apache-2.0"
] | null | null | null | audio/common/Semantic/jhcBindings.cpp | jconnell11/ALIA | f7a6c9dfd775fbd41239051aeed7775adb878b0a | [
"Apache-2.0"
] | null | null | null | // jhcBindings.cpp : list of substitutions of one node for another
//
// Written by Jonathan H. Connell, jconnell@alum.mit.edu
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright 2017-2018 IBM Corporation
// Copyright 2020-2021 Etaoin Systems
//
// 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 "Semantic/jhcBindings.h"
///////////////////////////////////////////////////////////////////////////
// Creation and Initialization //
///////////////////////////////////////////////////////////////////////////
//= Default destructor does necessary cleanup.
jhcBindings::~jhcBindings ()
{
delete [] sub;
delete [] key;
}
//= Default constructor initializes certain values.
jhcBindings::jhcBindings (const jhcBindings *ref)
{
// make arrays on heap (keeps jhcAliaDir size manageable)
key = new const jhcNetNode * [bmax];
sub = new jhcNetNode * [bmax];
// initialize contents
nb = 0;
expect = 0;
if (ref != NULL)
Copy(*ref);
}
//= Make an exact copy of some other set of bindings, including order.
// returns pointer to self for convenience
jhcBindings *jhcBindings::Copy (const jhcBindings& ref)
{
int nref = ref.nb;
for (nb = 0; nb < nref; nb++)
{
key[nb] = ref.key[nb];
sub[nb] = ref.sub[nb];
}
expect = ref.expect;
return this;
}
//= See if any substitution node has a belief of zero.
// returns 1 if something is hypothetical, 0 if none are
int jhcBindings::AnyHyp () const
{
int i;
for (i = 0; i < nb; i++)
// if (sub[i]->Belief() <= 0.0)
if (sub[i]->Hyp())
return 1;
return 0;
}
///////////////////////////////////////////////////////////////////////////
// List Functions //
///////////////////////////////////////////////////////////////////////////
//= Get the current binding value for some key.
// returns NULL if key not found
jhcNetNode *jhcBindings::LookUp (const jhcNetNode *k) const
{
int i = index(k);
return((i >= 0) ? sub[i] : NULL);
}
//= Get the index of the matching key.
// returns negative if no match found
int jhcBindings::index (const jhcNetNode *probe) const
{
int i;
if (probe != NULL)
for (i = 0; i < nb; i++)
if (probe == key[i])
return i;
return -1;
}
//= Do inverse lookup of key for this substitution (may not be unique).
const jhcNetNode *jhcBindings::FindKey (const jhcNetNode *subst) const
{
int i;
if (subst != NULL)
for (i = 0; i < nb; i++)
if (subst == sub[i]) // first key found is winner
return key[i];
return NULL;
}
//= Remember a particular key-value pair at the end of the current list.
// if NULL substitution (out) is given, key (in) remains in list but LookUp returns NULL
// generally returns number of bindings, including new, for use with TrimTo(N - 1)
// return: N = number of bindings, 0 = no more room, -1 = duplicate key, -2 = bad key
int jhcBindings::Bind (const jhcNetNode *k, jhcNetNode *subst)
{
// see if key already in list
if (k == NULL)
return -2;
if (InKeys(k))
return -1;
// try adding a new key-substitution pair
if (nb >= bmax)
return jprintf(">>> More than %d pairs in jhcBindings:Bind !\n", bmax);
key[nb] = k;
sub[nb] = subst;
nb++;
return nb;
}
//= Remove most recently added bindings to retain only N.
// more useful than simply "Pop" since can revert to prior state
// returns 1 if okay, 0 if nothing to remove, -1 bad request
int jhcBindings::TrimTo (int n)
{
if ((n < 0) || (n > nb))
return -1;
if (nb <= 0)
return 0;
nb = n;
return 1;
}
//= Remove most recent binding, but only if it has the specified key.
void jhcBindings::RemFinal (jhcNetNode *k)
{
if (nb > 0)
if (key[nb - 1] == k)
nb--;
}
///////////////////////////////////////////////////////////////////////////
// List Functions //
///////////////////////////////////////////////////////////////////////////
//= See if some particular key has a binding.
bool jhcBindings::InKeys (const jhcNetNode *probe) const
{
return(index(probe) >= 0);
}
//= See if some particular substitution is already associated with a key.
bool jhcBindings::InSubs (const jhcNetNode *probe) const
{
int i;
if (probe != NULL)
for (i = 0; i < nb; i++)
if (probe == sub[i])
return true;
return false;
}
//= Count nodes in a pattern that are not in the keys of these bindings.
int jhcBindings::KeyMiss (const jhcNodeList& f) const
{
const jhcNetNode *node = NULL;
int miss = f.Length();
while ((node = f.NextNode(node)) != NULL)
if (InKeys(node))
miss--;
return miss;
}
//= Count nodes in a pattern that are not in the substitutions of these bindings.
int jhcBindings::SubstMiss (const jhcNodeList& f) const
{
const jhcNetNode *node = NULL;
int miss = f.Length();
while ((node = f.NextNode(node)) != NULL)
if (InSubs(node))
miss--;
return miss;
}
///////////////////////////////////////////////////////////////////////////
// Bulk Functions //
///////////////////////////////////////////////////////////////////////////
//= Tells whether this list is equivalent to reference bindings.
// this means the same keys go to the same values, independent of order
// useful for non-return inhibition checking of operators
bool jhcBindings::Same (const jhcBindings& ref) const
{
const jhcNetNode *s;
int i;
// must have exactly the same number of bindings
if (nb != ref.nb)
return false;
// check all keys in local list
for (i = 0; i < nb; i++)
{
// punt if key does not exist in reference or value is different
if ((s = ref.LookUp(key[i])) == NULL)
return false;
if (s != sub[i])
return false;
}
return true;
}
//= Replace each value in list with its lookup in the reference bindings.
// self: obj-8 = obj-1 + ref: obj-1 = obj-237 --> self: obj-8 = obj-237
void jhcBindings::ReplaceSubs (const jhcBindings& alt)
{
jhcNetNode *s;
int i;
for (i = 0; i < nb; i++)
if ((s = alt.LookUp(sub[i])) != NULL)
sub[i] = s;
}
//= List bindings in format "key = subst" where subst can be NULL.
// can optionally write header "<prefix> bindings:" instead of "bindings:"
// can optionally show only first "num" bindings instead of all
// if num < 0 then shows everything except the first bindings
void jhcBindings::Print (const char *prefix, int lvl, int num) const
{
int start = ((num < 0) ? -num : 0);
int stop = ((num > 0) ? __min(num, nb) : nb);
int i, k = 0, n = 0, k2 = 0, n2 = 0;
// get print field widths
for (i = start; i < stop; i++)
{
key[i]->NodeSize(k, n);
if (sub[i] != NULL)
sub[i]->NodeSize(k2, n2);
}
// print header (even if nothing to show)
if ((prefix != NULL) && (*prefix != '\0'))
jprintf("%*s%s bindings:\n", lvl, "", prefix);
else
jprintf("%*sBindings:\n", lvl, "");
// print key-sub pairs (might be no pairs)
for (i = start; i < stop; i++)
{
jprintf("%*s %*s = ", lvl, "", (k + n + 1), key[i]->Nick());
if (sub[i] != NULL)
jprintf("%*s\n", -(k2 + n2 + 1), sub[i]->Nick());
else
jprintf("NULL\n");
}
}
| 25.203822 | 88 | 0.55345 | jconnell11 |
4344b6ffd0bc0929c676e7c0c315910ddb896471 | 105 | hpp | C++ | falcon/preprocessor/nil.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | 2 | 2018-02-02T14:19:59.000Z | 2018-05-13T02:48:24.000Z | falcon/preprocessor/nil.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | falcon/preprocessor/nil.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | #ifndef FALCON_PREPROCESSOR_NIL_HPP
#define FALCON_PREPROCESSOR_NIL_HPP
#define FALCON_PP_NIL()
#endif
| 15 | 35 | 0.857143 | jonathanpoelen |
434c01cc9e2933f000c0a3bcf21da7e487733953 | 521 | hpp | C++ | tools/material_munge/src/terrain_assemble_textures.hpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 13 | 2019-03-25T09:40:12.000Z | 2022-03-13T16:12:39.000Z | tools/material_munge/src/terrain_assemble_textures.hpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 110 | 2018-10-16T09:05:43.000Z | 2022-03-16T23:32:28.000Z | tools/material_munge/src/terrain_assemble_textures.hpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 1 | 2020-02-06T20:32:50.000Z | 2020-02-06T20:32:50.000Z | #pragma once
#include <filesystem>
#include <string>
#include <string_view>
#include <vector>
#include "terrain_materials_config.hpp"
namespace sp {
void terrain_assemble_textures(const Terrain_materials_config& config,
const std::string_view texture_suffix,
const std::vector<std::string>& materials,
const std::filesystem::path& output_dir,
const std::filesystem::path& sptex_files_dir);
}
| 27.421053 | 77 | 0.602687 | SleepKiller |
434d8114ef41d4d07d02d867b2f293201ea6b40c | 3,319 | cc | C++ | src/pastar.cc | jinnaiyuu/pbnf | d197723e7499a91e2c15042de243ccab2cb0f9d5 | [
"MIT"
] | 4 | 2019-03-19T17:31:33.000Z | 2022-01-08T12:27:33.000Z | src/pastar.cc | jinnaiyuu/pbnf | d197723e7499a91e2c15042de243ccab2cb0f9d5 | [
"MIT"
] | null | null | null | src/pastar.cc | jinnaiyuu/pbnf | d197723e7499a91e2c15042de243ccab2cb0f9d5 | [
"MIT"
] | 1 | 2019-04-26T08:17:22.000Z | 2019-04-26T08:17:22.000Z | // © 2014 the PBNF Authors under the MIT license. See AUTHORS for the list of authors.
/**
* \file pastar.cc
*
*
*
* \author Sofia Lemons
* \date 2008-11-02
*/
#include "util/thread.h"
#include "state.h"
#include "pastar.h"
class PAStarThread : public Thread {
public:
PAStarThread() {}
PAStarThread(PAStar *p) : p(p) {}
PAStarThread(PAStar *p, pthread_mutex_t* mut, CompletionCounter* cc) : p(p), mut(mut), cc(cc) {}
virtual void run(void){
vector<State *> *children = NULL;
State *s;
while(!p->is_done()){
pthread_mutex_lock(mut);
if(!p->open.empty()){
s = p->open.take();
pthread_mutex_unlock(mut);
}
else{
cc->complete();
if (cc->is_complete()){
p->set_done();
}
if (p->done==true){
pthread_mutex_unlock(mut);
if (children)
delete children;
return;
}
pthread_mutex_unlock(mut);
while(p->open.empty() && !p->is_done()){
}
pthread_mutex_lock(mut);
cc->uncomplete();
pthread_mutex_unlock(mut);
continue;
}
if (s->get_f() >= p->bound.read()) {
p->open.prune();
continue;
}
if (s->is_goal())
p->set_path(s->get_path());
children = p->expand(s, get_id());
for (unsigned int i = 0; i < children->size(); i += 1) {
State *c = children->at(i);
State *dup = p->closed.lookup(c);
if (dup){
pthread_mutex_lock(mut);
if (dup->get_g() > c->get_g()) {
dup->update(c->get_parent(), c->get_c(), c->get_g());
if (dup->is_open())
p->open.see_update(dup);
else
p->open.add(dup);
}
pthread_mutex_unlock(mut);
delete c;
}
else{
p->open.add(c);
p->closed.add(c);
}
}
}
delete children;
}
private:
PAStar *p;
pthread_mutex_t* mut;
friend class PAStar;
CompletionCounter *cc;
};
PAStar::PAStar(unsigned int n_threads) : n_threads(n_threads),
path(NULL),
bound(fp_infinity){
done = false;
}
void PAStar::set_done()
{
pthread_mutex_lock(&mutex);
done = true;
pthread_mutex_unlock(&mutex);
}
bool PAStar::is_done()
{
bool ret;
pthread_mutex_lock(&mutex);
ret = done;
pthread_mutex_unlock(&mutex);
return ret;
}
void PAStar::set_path(vector<State *> *p)
{
pthread_mutex_lock(&mutex);
if (this->path == NULL ||
this->path->at(0)->get_g() > p->at(0)->get_g()){
this->path = p;
bound.set(p->at(0)->get_g());
}
pthread_mutex_unlock(&mutex);
}
bool PAStar::has_path()
{
bool ret;
pthread_mutex_lock(&mutex);
ret = (path != NULL);
pthread_mutex_unlock(&mutex);
return ret;
}
/**
* Perform a Parallel A* search.
*/
vector<State *> *PAStar::search(Timer *t, State *init)
{
open.add(init);
pthread_mutex_init(&mutex, NULL);
CompletionCounter cc = CompletionCounter(n_threads);
pthread_mutex_t m;
pthread_mutex_init(&m, NULL);
unsigned int worker;
vector<PAStarThread *> threads;
vector<PAStarThread *>::iterator iter;
for (worker=0; worker<n_threads; worker++) {
PAStarThread *t = new PAStarThread(this, &m, &cc);
threads.push_back(t);
t->start();
}
for (iter = threads.begin(); iter != threads.end(); iter++) {
(*iter)->join();
delete *iter;
}
return path;
}
| 20.237805 | 97 | 0.580295 | jinnaiyuu |
4352ca4eb1b4c528acbf3c368387dfb587cc2603 | 2,428 | cpp | C++ | testsuite/core/thread/TestCase_Core_Thread_Tls.cpp | lailongwei/llbc | ec7e69bfa1f0afece8bb19dfa9a0a4578508a077 | [
"MIT"
] | 83 | 2015-11-10T09:52:56.000Z | 2022-01-12T11:53:01.000Z | testsuite/core/thread/TestCase_Core_Thread_Tls.cpp | lailongwei/llbc | ec7e69bfa1f0afece8bb19dfa9a0a4578508a077 | [
"MIT"
] | 30 | 2017-09-30T07:43:20.000Z | 2022-01-23T13:18:48.000Z | testsuite/core/thread/TestCase_Core_Thread_Tls.cpp | lailongwei/llbc | ec7e69bfa1f0afece8bb19dfa9a0a4578508a077 | [
"MIT"
] | 34 | 2015-11-14T12:37:44.000Z | 2021-12-16T02:38:36.000Z | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.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 "core/thread/TestCase_Core_Thread_Tls.h"
namespace
{
static LLBC_Tls<long> __g_tls;
static const long __g_threadNum = 5;
}
static int ThreadProc(void *arg)
{
long threadIndex;
::memcpy(&threadIndex, &arg, sizeof(long));
LLBC_PrintLine("thread %d startup", threadIndex);
__g_tls.SetValue(LLBC_New(long));
(*__g_tls) = threadIndex;
for(int i = 0; i < 5000000; ++i)
(*__g_tls) += 1;
LLBC_PrintLine("thread [%ld] tls value: %ld", threadIndex, *__g_tls);
return 0;
}
TestCase_Core_Thread_Tls::TestCase_Core_Thread_Tls()
{
}
TestCase_Core_Thread_Tls::~TestCase_Core_Thread_Tls()
{
}
int TestCase_Core_Thread_Tls::Run(int argc, char *argv[])
{
LLBC_PrintLine("core/thread/tls test");
// Create threads.
LLBC_NativeThreadHandle threads[__g_threadNum] = {LLBC_INVALID_NATIVE_THREAD_HANDLE};
for(long i = 0; i < __g_threadNum; ++i)
{
void *threadArg = NULL;
::memcpy(&threadArg, &i, sizeof(long));
LLBC_CreateThread(&threads[i], &ThreadProc, threadArg);
}
// Join threads.
for(long i = 0; i < __g_threadNum; ++i)
{
LLBC_JoinThread(threads[i]);
}
LLBC_PrintLine("Press any key to continue ...");
getchar();
return 0;
}
| 30.734177 | 89 | 0.7014 | lailongwei |
4354ef0f969361e3b587ee9234aaada412f35a5c | 9,499 | cpp | C++ | src/modules/packetio/drivers/dpdk/port/checksum_calculator.cpp | smprogsoft/openperf | 2eabdf86a14be2f56773e370708e27f94971c6f4 | [
"Apache-2.0"
] | 20 | 2019-12-04T01:28:52.000Z | 2022-03-17T14:09:34.000Z | src/modules/packetio/drivers/dpdk/port/checksum_calculator.cpp | smprogsoft/openperf | 2eabdf86a14be2f56773e370708e27f94971c6f4 | [
"Apache-2.0"
] | 115 | 2020-02-04T21:29:54.000Z | 2022-02-17T13:33:51.000Z | src/modules/packetio/drivers/dpdk/port/checksum_calculator.cpp | smprogsoft/openperf | 2eabdf86a14be2f56773e370708e27f94971c6f4 | [
"Apache-2.0"
] | 16 | 2019-12-03T16:41:18.000Z | 2021-11-06T04:44:11.000Z | #include <array>
#include "lib/packet/protocol/protocols.hpp"
#include "packetio/drivers/dpdk/dpdk.h"
#include "packetio/drivers/dpdk/port/checksum_calculator.hpp"
#include "packetio/drivers/dpdk/port/signature_utils.hpp"
#include "packetio/drivers/dpdk/port_info.hpp"
#include "spirent_pga/api.h"
namespace openperf::packetio::dpdk::port {
template <typename T> T get_next_header(libpacket::protocol::ipv4* ipv4)
{
static_assert(std::is_pointer_v<T>);
auto* cursor = reinterpret_cast<uint8_t*>(ipv4);
cursor += get_ipv4_header_length(*ipv4);
return (reinterpret_cast<T>(cursor));
}
template <typename T> T get_l3_header(struct rte_mbuf* m)
{
static_assert(std::is_pointer_v<T>);
return (rte_pktmbuf_mtod_offset(m, T, m->l2_len));
}
template <typename T> T get_l4_header(struct rte_mbuf* m)
{
static_assert(std::is_pointer_v<T>);
return (rte_pktmbuf_mtod_offset(m, T, m->l2_len + m->l3_len));
}
static uint16_t calculate_checksums([[maybe_unused]] uint16_t port_id,
uint16_t queue_id,
rte_mbuf* packets[],
uint16_t nb_packets,
void* user_param)
{
using namespace libpacket::protocol;
constexpr auto TX_L4_CKSUM =
RTE_MBUF_F_TX_TCP_CKSUM | RTE_MBUF_F_TX_UDP_CKSUM;
auto& scratch = reinterpret_cast<callback_checksum_calculator::scratch_t*>(
user_param)[queue_id];
auto start = 0U;
while (start < nb_packets) {
const auto end =
start + std::min(utils::chunk_size, nb_packets - start);
auto nb_ipv4_headers = 0U, nb_ipv4_tcpudp_headers = 0U,
nb_ipv6_tcpudp_headers = 0U;
/*
* Use packet metadata to categorize packets. We need to know what
* type of checksums to calculate.
*/
std::for_each(packets + start, packets + end, [&](auto* mbuf) {
if (mbuf->ol_flags & RTE_MBUF_F_TX_IPV4) {
auto* ipv4 = get_l3_header<struct ipv4*>(mbuf);
scratch.ipv4_cksums.set(nb_ipv4_headers++, {ipv4, 0});
if (mbuf->ol_flags & TX_L4_CKSUM) {
scratch.ipv4_tcpudp_cksums.set(nb_ipv4_tcpudp_headers++,
{ipv4, 0});
/*
* Note: the generator helpfully sets the pseudo-header
* value into the payload's checksum field. We need to clear
* it in order to calculate the correct checksum with our
* pga functions.
*/
switch (mbuf->ol_flags & TX_L4_CKSUM) {
case RTE_MBUF_F_TX_TCP_CKSUM: {
auto* tcp = get_l4_header<struct tcp*>(mbuf);
set_tcp_checksum(*tcp, 0);
break;
}
case RTE_MBUF_F_TX_UDP_CKSUM: {
auto* udp = get_l4_header<struct udp*>(mbuf);
set_udp_checksum(*udp, 0);
break;
}
default:
break;
}
}
} else if (mbuf->ol_flags & RTE_MBUF_F_TX_IPV6) {
auto* ipv6 = get_l3_header<struct ipv6*>(mbuf);
switch (mbuf->ol_flags & TX_L4_CKSUM) {
case RTE_MBUF_F_TX_TCP_CKSUM: {
auto* tcp = get_l4_header<struct tcp*>(mbuf);
set_tcp_checksum(*tcp, 0);
scratch.ipv6_tcpudp_cksums.set(
nb_ipv6_tcpudp_headers++,
{ipv6,
reinterpret_cast<uint8_t*>(tcp),
IPPROTO_TCP,
0});
break;
}
case RTE_MBUF_F_TX_UDP_CKSUM: {
auto* udp = get_l4_header<struct udp*>(mbuf);
set_udp_checksum(*udp, 0);
scratch.ipv6_tcpudp_cksums.set(
nb_ipv6_tcpudp_headers++,
{ipv6,
reinterpret_cast<uint8_t*>(udp),
IPPROTO_UDP,
0});
break;
}
default:
break;
}
}
});
/* Now, calculate and fill in checksum data */
if (nb_ipv4_headers) {
pga_checksum_ipv4_headers(
reinterpret_cast<uint8_t**>(scratch.ipv4_cksums.data<0>()),
nb_ipv4_headers,
scratch.ipv4_cksums.data<1>());
if (nb_ipv4_tcpudp_headers) {
pga_checksum_ipv4_tcpudp(
reinterpret_cast<uint8_t**>(
scratch.ipv4_tcpudp_cksums.data<0>()),
nb_ipv4_tcpudp_headers,
scratch.ipv4_tcpudp_cksums.data<1>());
auto start = std::begin(scratch.ipv4_tcpudp_cksums);
std::for_each(start,
std::next(start, nb_ipv4_tcpudp_headers),
[](auto&& tuple) {
auto* ipv4 = std::get<0>(tuple);
auto cksum = std::get<1>(tuple);
switch (get_ipv4_protocol(*ipv4)) {
case IPPROTO_TCP: {
auto* tcp =
get_next_header<struct tcp*>(ipv4);
set_tcp_checksum(*tcp, htons(cksum));
break;
}
case IPPROTO_UDP: {
auto* udp =
get_next_header<struct udp*>(ipv4);
set_udp_checksum(*udp, htons(cksum));
break;
}
default:
break;
}
});
}
auto start = std::begin(scratch.ipv4_cksums);
std::for_each(
start, std::next(start, nb_ipv4_headers), [](auto&& tuple) {
auto* ipv4 = std::get<0>(tuple);
auto cksum = std::get<1>(tuple);
set_ipv4_checksum(*ipv4, htons(cksum));
});
}
if (nb_ipv6_tcpudp_headers) {
pga_checksum_ipv6_tcpudp(reinterpret_cast<uint8_t**>(
scratch.ipv6_tcpudp_cksums.data<0>()),
scratch.ipv6_tcpudp_cksums.data<1>(),
nb_ipv6_tcpudp_headers,
scratch.ipv6_tcpudp_cksums.data<3>());
auto start = std::begin(scratch.ipv6_tcpudp_cksums);
std::for_each(start,
std::next(start, nb_ipv6_tcpudp_headers),
[](auto&& tuple) {
auto* payload = std::get<1>(tuple);
auto protocol = std::get<2>(tuple);
auto cksum = std::get<3>(tuple);
switch (protocol) {
case IPPROTO_TCP: {
auto* tcp =
reinterpret_cast<struct tcp*>(payload);
set_tcp_checksum(*tcp, htons(cksum));
break;
}
case IPPROTO_UDP: {
auto* udp =
reinterpret_cast<struct udp*>(payload);
set_udp_checksum(*udp, htons(cksum));
break;
}
default:
break;
}
});
}
start = end;
}
return (nb_packets);
}
std::string callback_checksum_calculator::description()
{
return ("IP checksum calculator");
}
tx_callback<callback_checksum_calculator>::tx_callback_fn
callback_checksum_calculator::callback()
{
return (calculate_checksums);
}
void* callback_checksum_calculator::callback_arg() const
{
if (scratch.size() != port_info::tx_queue_count(port_id())) {
scratch.resize(port_info::tx_queue_count(port_id()));
}
return (scratch.data());
}
static checksum_calculator::variant_type
make_checksum_calculator(uint16_t port_id)
{
constexpr auto tx_cksum_offloads =
(RTE_ETH_TX_OFFLOAD_IPV4_CKSUM | RTE_ETH_TX_OFFLOAD_TCP_CKSUM
| RTE_ETH_TX_OFFLOAD_UDP_CKSUM);
if ((port_info::tx_offloads(port_id) & tx_cksum_offloads)
!= tx_cksum_offloads) {
/* We need checksums! */
return (callback_checksum_calculator(port_id));
}
return (null_feature(port_id));
}
checksum_calculator::checksum_calculator(uint16_t port_id)
: feature(make_checksum_calculator(port_id))
{
pga_init();
}
} // namespace openperf::packetio::dpdk::port
| 38.302419 | 80 | 0.472155 | smprogsoft |
43561b53cca7812ed59f6c2f68182a6cbff30543 | 749 | cpp | C++ | src/usdTri/moduleDeps.cpp | colevfx/USDPluginExamples | ccc5b2c69fa8757a169b8095675565f9cea2c1a0 | [
"Apache-2.0"
] | 68 | 2020-11-25T22:08:55.000Z | 2022-03-25T23:09:47.000Z | src/usdTri/moduleDeps.cpp | colevfx/USDPluginExamples | ccc5b2c69fa8757a169b8095675565f9cea2c1a0 | [
"Apache-2.0"
] | 16 | 2020-11-27T04:49:18.000Z | 2021-08-31T08:05:11.000Z | src/usdTri/moduleDeps.cpp | colevfx/USDPluginExamples | ccc5b2c69fa8757a169b8095675565f9cea2c1a0 | [
"Apache-2.0"
] | 9 | 2020-12-11T00:27:22.000Z | 2021-12-01T21:21:31.000Z | //
// Copyright © 2021 Weta Digital Limited
//
// SPDX-License-Identifier: Apache-2.0
//
#include <pxr/base/tf/registryManager.h>
#include <pxr/base/tf/scriptModuleLoader.h>
#include <pxr/base/tf/token.h>
#include <pxr/pxr.h>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfScriptModuleLoader)
{
// List of direct dependencies for this library.
const std::vector<TfToken> reqs = {
TfToken("js"), TfToken("plug"), TfToken("sdf"),
TfToken("tf"), TfToken("trace"), TfToken("usd"),
TfToken("vt"), TfToken("work"), TfToken("usdGeom"),
};
TfScriptModuleLoader::GetInstance().RegisterLibrary(
TfToken("usdTri"), TfToken("usdpluginexamples.UsdTri"), reqs);
}
PXR_NAMESPACE_CLOSE_SCOPE
| 26.75 | 70 | 0.688919 | colevfx |
43599005d346f05a5d9a2bd6064adb5c1e0b8a16 | 483 | cpp | C++ | SSegment.cpp | AhoyDev/Rubens-Engine | 269354486db52ed65e1528e4e34c2349d7b29d02 | [
"MIT"
] | null | null | null | SSegment.cpp | AhoyDev/Rubens-Engine | 269354486db52ed65e1528e4e34c2349d7b29d02 | [
"MIT"
] | null | null | null | SSegment.cpp | AhoyDev/Rubens-Engine | 269354486db52ed65e1528e4e34c2349d7b29d02 | [
"MIT"
] | null | null | null | #include "SSegment.h"
#include "SLine.h"
#include "SRay.h"
#include "SPlane.h"
#include "STriangle.h"
#include "SCircle.h"
#include "SPolygon.h"
#include "SFrustum.h"
#include "SSphere.h"
#include "SCapsule.h"
#include "SPolyhedron.h"
SSegment::SSegment() : SPrimitive(SEGMENT)
{
vec end = float3(0.f, 1.f, 0.f);
shape = new LineSegment(GetPos(), end);
}
SSegment::SSegment(vec begin, vec end) : SPrimitive(((begin + end) / 2), SEGMENT)
{
shape = new LineSegment(begin, end);
} | 21 | 81 | 0.6853 | AhoyDev |
435a3aec902fbb91a546f8e4947ea81427b2e7b4 | 4,539 | cpp | C++ | modules/ti.UI/ui_module.cpp | mital/titanium | 5e02a4406686d627f6828fd5cc18dc1a75d0714f | [
"Apache-2.0"
] | 4 | 2016-01-02T17:14:06.000Z | 2016-05-09T08:57:33.000Z | modules/ti.UI/ui_module.cpp | mital/titanium | 5e02a4406686d627f6828fd5cc18dc1a75d0714f | [
"Apache-2.0"
] | null | null | null | modules/ti.UI/ui_module.cpp | mital/titanium | 5e02a4406686d627f6828fd5cc18dc1a75d0714f | [
"Apache-2.0"
] | null | null | null | /**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "ui_module.h"
#include <Poco/URI.h>
namespace ti
{
KROLL_MODULE(UIModule, STRING(MODULE_NAME), STRING(MODULE_VERSION))
SharedKObject UIModule::global = SharedKObject(NULL);
SharedPtr<MenuItem> UIModule::app_menu = SharedPtr<MenuItem>(NULL);
SharedPtr<MenuItem> UIModule::app_context_menu = SharedPtr<MenuItem>(NULL);
SharedString UIModule::icon_path = SharedString(NULL);
std::vector<SharedPtr<TrayItem> > UIModule::tray_items;
UIModule* UIModule::instance_;
void UIModule::Initialize()
{
// We are keeping this object in a static variable, which means
// that we should only ever have one copy of the UI module.
SharedKObject global = this->host->GetGlobalObject();
UIModule::global = global;
UIModule::instance_ = this;
}
void UIModule::Start()
{
SharedKMethod api = this->host->GetGlobalObject()->GetNS("API.fire")->ToMethod();
api->Call("ti.UI.start", Value::Undefined);
#ifdef OS_WIN32
this->uiBinding = new Win32UIBinding(this, host);
#elif OS_OSX
this->uiBinding = new OSXUIBinding(host);
#elif OS_LINUX
this->uiBinding = new GtkUIBinding(host);
#endif
AppConfig *config = AppConfig::Instance();
if (config == NULL)
{
std::string msg = "Error loading tiapp.xml. Your application "
"is not properly configured or packaged.";
this->uiBinding->ErrorDialog(msg);
throw ValueException::FromString(msg.c_str());
return;
}
WindowConfig *main_window_config = config->GetMainWindow();
if (main_window_config == NULL)
{
std::string msg ="Error loading tiapp.xml. Your application "
"window is not properly configured or packaged.";
this->uiBinding->ErrorDialog(msg);
throw ValueException::FromString(msg.c_str());
return;
}
this->uiBinding->CreateMainWindow(main_window_config);
}
void UIModule::Exiting(int exitcode)
{
// send a stop notification - we need to do this before
// stop is called given that the API module is registered (and unregistered)
// before our module and it will then be too late
SharedKMethod api = this->host->GetGlobalObject()->GetNS("API.fire")->ToMethod();
api->Call("ti.UI.stop", Value::Undefined);
}
void UIModule::Stop()
{
// Remove app tray icons
UIModule::ClearTrayItems();
// Only one copy of the UI module loaded hopefully,
// otherwise we need to count instances and free
// this variable when the last instance disappears
UIModule::global = SharedKObject(NULL);
}
bool UIModule::IsResourceLocalFile(std::string string)
{
Poco::URI uri(string.c_str());
std::string scheme = uri.getScheme();
return (scheme == "app" || scheme == "ti" || scheme == "file");
}
SharedString UIModule::GetResourcePath(const char *URL)
{
if (URL == NULL || !strcmp(URL, ""))
return new std::string("");
Poco::URI uri(URL);
std::string scheme = uri.getScheme();
if (scheme == "app" || scheme == "ti")
{
SharedValue new_url = global->CallNS(
"App.appURLToPath",
Value::NewString(URL));
if (new_url->IsString())
return new std::string(new_url->ToString());
}
return new std::string(URL);
}
void UIModule::SetMenu(SharedPtr<MenuItem> menu)
{
UIModule::app_menu = menu;
}
SharedPtr<MenuItem> UIModule::GetMenu()
{
return UIModule::app_menu;
}
void UIModule::SetContextMenu(SharedPtr<MenuItem> menu)
{
UIModule::app_context_menu = menu;
}
SharedPtr<MenuItem> UIModule::GetContextMenu()
{
return UIModule::app_context_menu;
}
void UIModule::SetIcon(SharedString icon_path)
{
UIModule::icon_path = icon_path;
}
SharedString UIModule::GetIcon()
{
return UIModule::icon_path;
}
void UIModule::AddTrayItem(SharedPtr<TrayItem> item)
{
// One tray item at a time
UIModule::ClearTrayItems();
UIModule::tray_items.push_back(item);
}
void UIModule::ClearTrayItems()
{
std::vector<SharedPtr<TrayItem> >::iterator i = UIModule::tray_items.begin();
while (i != UIModule::tray_items.end())
{
(*i++)->Remove();
}
UIModule::tray_items.clear();
}
void UIModule::UnregisterTrayItem(TrayItem* item)
{
std::vector<SharedPtr<TrayItem> >::iterator i = UIModule::tray_items.begin();
while (i != UIModule::tray_items.end())
{
SharedPtr<TrayItem> c = *i;
if (c.get() == item)
{
i = UIModule::tray_items.erase(i);
}
else
{
i++;
}
}
}
}
| 25.5 | 83 | 0.686935 | mital |
435b3adb433dccfcef4ff5749979089819024a2b | 1,153 | cpp | C++ | benchmarks/reduce_rand.cpp | wrathematics/spar | 11d75700fdffea904237357070b690ed945ab460 | [
"BSL-1.0"
] | 1 | 2019-11-07T04:29:59.000Z | 2019-11-07T04:29:59.000Z | benchmarks/reduce_rand.cpp | wrathematics/spvec | 11d75700fdffea904237357070b690ed945ab460 | [
"BSL-1.0"
] | null | null | null | benchmarks/reduce_rand.cpp | wrathematics/spvec | 11d75700fdffea904237357070b690ed945ab460 | [
"BSL-1.0"
] | null | null | null | #include "args.hpp"
#include "common.hpp"
#include "printing.hpp"
#include "timer.hpp"
#define BENCHMARK "reduce_rand"
int main(int argc, char **argv)
{
opts_t<INDEX> opts;
timer t;
// setup
spar::mpi::init();
int rank = spar::mpi::get_rank();
int size = spar::mpi::get_size();
spar::mpi::err::check_size(MPI_COMM_WORLD);
int check = process_flags(rank, argc, argv, &opts);
if (check == EARLY_EXIT || check == BAD_FLAG)
{
spar::mpi::finalize();
return check;
}
int root = opts.allreduce ? spar::mpi::REDUCE_TO_ALL : 0;
INDEX n = opts.n;
print_header(rank, &opts);
print_setup<INDEX, SCALAR>(rank, size, BENCHMARK, &opts);
// generation
t.start();
auto x = spar::gen::rand<INDEX, SCALAR>(opts.seed, opts.prop_dense, n, n, !opts.approx);
t.stop();
print_time(rank, x, t);
spar::mpi::barrier();
// reduce
MAT y;
t.start(true);
if (opts.densevec)
y = spar::reduce::dense<MAT, INDEX, SCALAR>(root, x);
else
y = spar::reduce::gather<MAT, INDEX, SCALAR>(root, x);
t.stop();
print_time(rank, y, t);
print_final(rank);
spar::mpi::finalize();
return 0;
}
| 20.589286 | 90 | 0.618387 | wrathematics |
435c141a630919fa012d07e7ae0ac7b816e493b7 | 1,660 | cpp | C++ | Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp | Jatin-Shihora/LeetCode-Solutions | 8e6fc84971ec96ec1263ba5ba2a8ae09e6404398 | [
"MIT"
] | 1 | 2022-01-02T10:29:32.000Z | 2022-01-02T10:29:32.000Z | Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp | Jatin-Shihora/LeetCode-Solutions | 8e6fc84971ec96ec1263ba5ba2a8ae09e6404398 | [
"MIT"
] | null | null | null | Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp | Jatin-Shihora/LeetCode-Solutions | 8e6fc84971ec96ec1263ba5ba2a8ae09e6404398 | [
"MIT"
] | 1 | 2022-03-04T12:44:14.000Z | 2022-03-04T12:44:14.000Z | // { Driver Code Starts
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
struct Node
{
int cnt{0};
Node * children[26] = {0};
};
void insert(Node * root, string& word)
{
for(auto ch:word)
{
int c = ch-'a';
if(!root->children[c])
{
root->children[c] = new Node;
}
root->cnt++;
root = root->children[c];
}
}
string get_prefix(Node * root, string& word)
{
string pref;
for(auto ch: word)
{
int c = ch-'a';
if(root->cnt==1)
break;
pref += ch;
root = root->children[c];
}
return pref;
}
vector<string> findPrefixes(string arr[], int n)
{
//code here
Node * trie = new Node;
for(int i=0; i<n; i++)
insert(trie, arr[i]);
vector<string> res;
for(int i=0;i<n; i++)
res.push_back(get_prefix(trie, arr[i]));
return res;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
string arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
Solution ob;
vector<string> ans = ob.findPrefixes(arr, n);
for (int i = 0; i < ans.size(); i++)
cout << ans[i] <<" ";
cout << "\n";
}
return 0;
}
// } Driver Code Ends | 18.863636 | 53 | 0.41747 | Jatin-Shihora |
435c2c2b2dec5dd0c3f10b370e49dd0216795b2e | 2,922 | hpp | C++ | source/modules/distribution/distribution.hpp | JonathanLehner/korali | 90f97d8e2fed2311f988f39cfe014f23ba7dd6cf | [
"MIT"
] | 43 | 2018-07-26T07:20:42.000Z | 2022-03-02T10:23:12.000Z | source/modules/distribution/distribution.hpp | JonathanLehner/korali | 90f97d8e2fed2311f988f39cfe014f23ba7dd6cf | [
"MIT"
] | 212 | 2018-09-21T10:44:07.000Z | 2022-03-22T14:33:05.000Z | source/modules/distribution/distribution.hpp | JonathanLehner/korali | 90f97d8e2fed2311f988f39cfe014f23ba7dd6cf | [
"MIT"
] | 16 | 2018-07-25T15:00:36.000Z | 2022-03-22T14:19:46.000Z | /** \namespace korali
* @brief Namespace declaration for modules of type: korali.
*/
/** \file
* @brief Header file for module: Distribution.
*/
/** \dir distribution
* @brief Contains code, documentation, and scripts for module: Distribution.
*/
#pragma once
#include "modules/module.hpp"
#include <gsl/gsl_rng.h>
#include <map>
namespace korali
{
;
/**
* @brief Class declaration for module: Distribution.
*/
class Distribution : public Module
{
public:
/**
* @brief Defines the name of the distribution.
*/
std::string _name;
/**
* @brief Defines the random seed of the distribution.
*/
size_t _randomSeed;
/**
* @brief Stores the current state of the distribution in hexadecimal notation.
*/
gsl_rng* _range;
/**
* @brief Obtains the entire current state and configuration of the module.
* @param js JSON object onto which to save the serialized state of the module.
*/
void getConfiguration(knlohmann::json& js) override;
/**
* @brief Sets the entire state and configuration of the module, given a JSON object.
* @param js JSON object from which to deserialize the state of the module.
*/
void setConfiguration(knlohmann::json& js) override;
/**
* @brief Applies the module's default configuration upon its creation.
* @param js JSON object containing user configuration. The defaults will not override any currently defined settings.
*/
void applyModuleDefaults(knlohmann::json& js) override;
/**
* @brief Applies the module's default variable configuration to each variable in the Experiment upon creation.
*/
void applyVariableDefaults() override;
/**
* @brief Map to store the link between parameter names and their pointers.
*/
std::map<std::string, double *> _conditionalsMap;
/**
* @brief Auxiliar variable to hold pre-calculated data to avoid re-processing information.
*/
double _aux;
/**
* @brief Indicates whether or not this distribution contains conditional variables.
*/
bool _hasConditionalVariables;
/**
* @brief Creates and sets the RNG range (state and seed) of the random distribution
* @param rangeString The range to load, in string of hexadecimal values form
* @return Pointer to the new range.
*/
gsl_rng *setRange(const std::string rangeString);
/**
* @brief Gets a hexadecimal string from a given range's state and seed
* @param range Range to read from
* @return Hexadecimal string produced.
*/
std::string getRange(gsl_rng *range) const;
/**
* @brief Updates the parameters of the distribution based on conditional variables.
*/
virtual void updateDistribution(){};
/**
* @brief Gets the pointer to a distribution property.
* @param property The name of the property to update
* @return Pointer to the property
*/
virtual double *getPropertyPointer(const std::string &property) { return NULL; };
};
} //korali
;
| 27.055556 | 119 | 0.706023 | JonathanLehner |
435fa40be18cfa69e944b0d540539b43e4ad1cb2 | 1,419 | hpp | C++ | ArIRadial/LoadFunction1D.hpp | kcdodd/masters | e96fc2feaa6edffb99f90278e14a8fcdd138db75 | [
"MIT"
] | null | null | null | ArIRadial/LoadFunction1D.hpp | kcdodd/masters | e96fc2feaa6edffb99f90278e14a8fcdd138db75 | [
"MIT"
] | null | null | null | ArIRadial/LoadFunction1D.hpp | kcdodd/masters | e96fc2feaa6edffb99f90278e14a8fcdd138db75 | [
"MIT"
] | null | null | null | #ifndef LOADFUNCTION1D_HPP_INCLUDED
#define LOADFUNCTION1D_HPP_INCLUDED
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
template<class T>
class LoadFunction1D
{
private:
string mFilename;
public:
LoadFunction1D(const string& filename)
:
mFilename(filename)
{
}
void load(
dynarry<T>& function)
{
ifstream inputfile(mFilename.c_str());
if (inputfile.is_open())
{
unsigned int input_num = 0;
inputfile >> input_num;
if (input_numr != numr)
{
cerr << "Input error: numr not correct in input file." << endl;
}
double tmp;
// r
for(unsigned int nr = 0; nr < numr; ++nr)
{
inputfile >> tmp;
//cerr << tmp << endl;
}
// Te
for(unsigned int nr = 0; nr < numr; ++nr)
{
inputfile >> tmp;
}
// ne
for(unsigned int nr = 0; nr < numr; ++nr)
{
inputfile >> tmp;
}
for(unsigned int nr = 0; nr < numr; ++nr)
{
inputfile >> Li[nr];
//cerr << Li[nr] << endl;
}
inputfile.close();
}
}
};
#endif // LOADATOMICDATA_HPP_INCLUDED
| 17.096386 | 79 | 0.450317 | kcdodd |
cb1a2916c50048fd35455208875c438c6832a197 | 505 | hpp | C++ | my_vulkan/helpers/io.hpp | pixelwise/my_vulkan | f1c139ed8f95380186905d77cb8e81008f48bc95 | [
"CC0-1.0"
] | null | null | null | my_vulkan/helpers/io.hpp | pixelwise/my_vulkan | f1c139ed8f95380186905d77cb8e81008f48bc95 | [
"CC0-1.0"
] | 3 | 2019-02-25T10:13:57.000Z | 2020-11-11T14:46:14.000Z | my_vulkan/helpers/io.hpp | pixelwise/my_vulkan | f1c139ed8f95380186905d77cb8e81008f48bc95 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include <vulkan/vulkan.h>
template<typename ostream_t>
ostream_t& operator<<(ostream_t& os, VkOffset2D offset)
{
os << "(" << offset.x << "," << offset.y << ")";
return os;
}
template<typename ostream_t>
ostream_t& operator<<(ostream_t& os, VkExtent2D extent)
{
os << extent.width << "x" << extent.height;
return os;
}
template<typename ostream_t>
ostream_t& operator<<(ostream_t& os, VkRect2D rect)
{
os << "@" << rect.offset << " " << rect.extent;
return os;
}
| 20.2 | 55 | 0.635644 | pixelwise |
cb1de260065da984a654d17b4642774391cb27d8 | 7,267 | hpp | C++ | standard/17/variant/variant.hpp | jrdbb/cpp | 99a7f8ac8e280324aaa72f611558b7ccd74adfaa | [
"MIT"
] | null | null | null | standard/17/variant/variant.hpp | jrdbb/cpp | 99a7f8ac8e280324aaa72f611558b7ccd74adfaa | [
"MIT"
] | 9 | 2021-06-01T02:43:51.000Z | 2021-09-12T05:26:35.000Z | standard/17/variant/variant.hpp | jrdbb/cpp | 99a7f8ac8e280324aaa72f611558b7ccd74adfaa | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
namespace {
template <typename T, typename... Ts>
struct variant_traits {
public:
template <typename Tx>
static constexpr bool contains = (std::is_same_v<Tx, T> ||
(std::is_same_v<Tx, Ts> || ...));
inline static void destroy(std::size_t id, void* data) {
if (id == typeid(T).hash_code())
reinterpret_cast<T*>(data)->~T();
else if constexpr (sizeof...(Ts) == 0)
throw std::runtime_error("Unexpected");
else
variant_traits<Ts...>::destroy(id, data);
}
inline static void move(std::size_t old_t, void* old_v, void* new_v) {
if (old_t == typeid(T).hash_code())
new (new_v) T(std::move(*reinterpret_cast<T*>(old_v)));
else if constexpr (sizeof...(Ts) == 0)
throw std::runtime_error("Unexpected");
else
variant_traits<Ts...>::move(old_t, old_v, new_v);
}
inline static void copy(std::size_t old_t, const void* old_v, void* new_v) {
if (old_t == typeid(T).hash_code())
new (new_v) T(*reinterpret_cast<const T*>(old_v));
else if constexpr (sizeof...(Ts) == 0)
throw std::runtime_error("Unexpected");
else
variant_traits<Ts...>::copy(old_t, old_v, new_v);
}
inline static std::size_t index(std::size_t id, std::size_t i = 0) {
if (id == typeid(T).hash_code())
return i;
else if constexpr (sizeof...(Ts) == 0)
throw std::runtime_error("Unexpected");
else
return variant_traits<Ts...>::index(id, i + 1);
}
};
template <std::size_t I, typename T, typename... Ts>
struct variant_index {
using type = std::enable_if_t<sizeof...(Ts) >= I,
typename variant_index<I - 1, Ts...>::type>;
};
template <typename T, typename... Ts>
struct variant_index<0, T, Ts...> {
using type = T;
};
} // namespace
namespace cpp::std17 {
template <typename T_0, typename... Ts>
class variant {
public:
template <typename Require =
std::enable_if_t<std::is_default_constructible_v<T_0>>>
variant() {
mTypeID = typeid(T_0).hash_code();
new (&mData) T_0();
};
variant(const variant& rhs) { *this = rhs; };
variant(variant&& rhs) { *this = std::move(rhs); };
variant& operator=(const variant& rhs) {
try_destory();
mTypeID = rhs.mTypeID;
if (mTypeID != 0) {
_traits::copy(mTypeID, &rhs.mData, &mData);
}
return *this;
};
variant& operator=(variant&& rhs) {
try_destory();
mTypeID = rhs.mTypeID;
if (mTypeID != 0) {
_traits::move(mTypeID, &rhs.mData, &mData);
rhs.mTypeID = 0;
}
return *this;
};
~variant() { try_destory(); };
using _traits = variant_traits<T_0, Ts...>;
template <typename T,
typename = std::enable_if_t<_traits::template contains<T>>>
explicit variant(T&& t) {
mTypeID = typeid(T).hash_code();
new (&mData) T(std::forward<T>(t));
}
// observers
constexpr std::size_t index() const {
if (valueless_by_exception()) {
return -1;
}
return _traits::index(mTypeID);
}
constexpr bool valueless_by_exception() const { return mTypeID == 0; }
// assignment
template <typename T,
typename = std::enable_if_t<_traits::template contains<T>>>
variant& operator=(const T& t) {
if (mTypeID != typeid(T).hash_code()) {
try_destory();
}
*(T*)(&mData) = t;
return *this;
}
template <std::size_t I, class... Types>
friend constexpr typename variant_index<I, Types...>::type& std::get(
variant<Types...>& v);
template <std::size_t I, class... Types>
friend constexpr typename variant_index<I, Types...>::type&& std::get(
variant<Types...>&& v);
template <std::size_t I, class... Types>
friend constexpr const typename variant_index<I, Types...>::type& std::get(
const variant<Types...>& v);
template <std::size_t I, class... Types>
friend constexpr const typename variant_index<I, Types...>::type&& std::get(
const variant<Types...>&& v);
template <class T, class... Types>
friend constexpr T& std::get(variant<Types...>& v);
template <class T, class... Types>
friend constexpr T&& std::get(variant<Types...>&& v);
template <class T, class... Types>
friend constexpr const T& std::get(const variant<Types...>& v);
template <class T, class... Types>
friend constexpr const T&& std::get(const variant<Types...>&& v);
private:
void try_destory() {
if (mTypeID != 0) {
_traits::destroy(mTypeID, &mData);
mTypeID = 0;
}
}
static const std::size_t data_size = std::max({sizeof(T_0), sizeof(Ts)...});
static const std::size_t data_align =
std::max({alignof(T_0), alignof(Ts)...});
using data_t = typename std::aligned_storage<data_size, data_align>::type;
void reset() { mTypeID = 0; }
std::size_t mTypeID = 0;
data_t mData;
};
} // namespace cpp::std17
namespace std {
// variant size
template <class variant>
struct variant_size {};
template <class... Types>
struct variant_size<cpp::std17::variant<Types...>> {
inline static constexpr std::size_t value = sizeof...(Types);
};
// get helper
template <class T, class... Types>
constexpr T& get(cpp::std17::variant<Types...>& v) {
if (v.mTypeID == typeid(T).hash_code()) {
return (T&)v.mData;
}
throw std::runtime_error("");
}
template <class T, class... Types>
constexpr T&& get(cpp::std17::variant<Types...>&& v) {
if (v.mTypeID == typeid(T).hash_code()) {
return (T &&) v.mData;
}
throw std::runtime_error("");
}
template <class T, class... Types>
constexpr const T& get(const cpp::std17::variant<Types...>& v) {
if (v.mTypeID == typeid(T).hash_code()) {
return (const T&&)v.mData;
}
throw std::runtime_error("");
}
template <class T, class... Types>
constexpr const T&& get(const cpp::std17::variant<Types...>&& v) {
if (v.mTypeID == typeid(T).hash_code()) {
return (const T&&)v.mData;
}
throw std::runtime_error("");
}
template <std::size_t I, class... Types>
constexpr typename variant_index<I, Types...>::type& get(
cpp::std17::variant<Types...>& v) {
return get<typename variant_index<I, Types...>::type>(v);
}
template <std::size_t I, class... Types>
constexpr typename variant_index<I, Types...>::type&& get(
cpp::std17::variant<Types...>&& v) {
return get<typename variant_index<I, Types...>::type>(std::move(v));
}
template <std::size_t I, class... Types>
constexpr const typename variant_index<I, Types...>::type& get(
const cpp::std17::variant<Types...>& v) {
return get<typename variant_index<I, Types...>::type>(v);
}
template <std::size_t I, class... Types>
constexpr const typename variant_index<I, Types...>::type&& get(
const cpp::std17::variant<Types...>&& v) {
return get<typename variant_index<I, Types...>::type>(std::move(v));
}
} // namespace std | 30.792373 | 80 | 0.581671 | jrdbb |
cb21d206ec186d0c3d5384f95b276adcb2eb78e0 | 688 | cpp | C++ | FLOW017.cpp | SiddhantManze/My-Codechef-submission | 34214b578f2fe18b81d43e21dfca8d9f6d2fb264 | [
"MIT"
] | 1 | 2021-10-10T20:02:33.000Z | 2021-10-10T20:02:33.000Z | Codechef solutions/(CODECHEF)FLOW017.cpp | kothariji/Competitive-Programming | c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c | [
"MIT"
] | 1 | 2021-08-23T14:40:00.000Z | 2021-10-06T10:51:43.000Z | FLOW017.cpp | SiddhantManze/My-Codechef-submission | 34214b578f2fe18b81d43e21dfca8d9f6d2fb264 | [
"MIT"
] | null | null | null | /*
PROBLEM : FLOW017 (Second Largest)
*/
#include<iostream>
#define ll long long
using namespace std;
int main()
{
ll t;
cin>>t;
while(t--)
{
ll a,b,c;
cin>>a>>b>>c;
if(a>b && a>c && b>c)
{
cout<<b<<endl;
}
if(a>b && a>c && c>b)
{
cout<<c<<endl;
}
if(b>a && b>c && a>c)
{
cout<<a<<endl;
}
if(b>a && b>c && c>a)
{
cout<<c<<endl;
}
if(c>a && c>b && a>b)
{
cout<<a<<endl;
}
if(c>a && c>b && b>a)
{
cout<<b<<endl;
}
}
return 0;
}
| 15.636364 | 38 | 0.3125 | SiddhantManze |
cb2b204589e090f4a129915c08cf56bf9ec483ba | 3,546 | cpp | C++ | code/engine/xrCore/xrCore.cpp | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 58 | 2016-11-20T19:14:35.000Z | 2021-12-27T21:03:35.000Z | code/engine/xrCore/xrCore.cpp | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 59 | 2016-09-10T10:44:20.000Z | 2018-09-03T19:07:30.000Z | code/engine/xrCore/xrCore.cpp | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 39 | 2017-02-05T13:35:37.000Z | 2022-03-14T11:00:12.000Z | // xrCore.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include <mmsystem.h>
#include <objbase.h>
#include "xrCore.h"
#ifdef DEBUG
#include <malloc.h>
#endif // DEBUG
XRCORE_API xrCore Core;
XRCORE_API u32 build_id;
XRCORE_API LPCSTR build_date;
namespace CPU {
extern void Detect();
}
static u32 init_counter = 0;
void xrCore::_initialize(const char* _ApplicationName, LogCallback cb, bool init_fs,
const char* fs_fname) {
xr_strcpy(ApplicationName, _ApplicationName);
if (0 == init_counter) {
// Init COM so we can use CoCreateInstance
// HRESULT co_res =
if (!strstr(GetCommandLine(), "-editor"))
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
xr_strcpy(Params, sizeof(Params), GetCommandLine());
_strlwr_s(Params, sizeof(Params));
string_path fn, dr, di;
// application path
GetModuleFileName(GetModuleHandle(MODULE_NAME), fn, sizeof(fn));
_splitpath(fn, dr, di, nullptr, nullptr);
strconcat(sizeof(ApplicationPath), ApplicationPath, dr, di);
GetCurrentDirectory(sizeof(WorkingPath), WorkingPath);
// User/Comp Name
DWORD sz_user = sizeof(UserName);
GetUserName(UserName, &sz_user);
DWORD sz_comp = sizeof(CompName);
GetComputerName(CompName, &sz_comp);
// Mathematics & PSI detection
CPU::Detect();
Memory._initialize();
InitLog();
_initialize_cpu();
// Debug._initialize ();
rtc_initialize();
xr_FS = xr_new<CLocatorAPI>();
//. R_ASSERT (co_res==S_OK);
}
if (init_fs) {
u32 flags = 0u;
if (nullptr != strstr(Params, "-build"))
flags |= CLocatorAPI::flBuildCopy;
if (nullptr != strstr(Params, "-ebuild"))
flags |= CLocatorAPI::flBuildCopy | CLocatorAPI::flEBuildCopy;
#ifdef DEBUG
if (strstr(Params, "-cache"))
flags |= CLocatorAPI::flCacheFiles;
else
flags &= ~CLocatorAPI::flCacheFiles;
#endif // DEBUG
flags |= CLocatorAPI::flScanAppRoot;
#ifndef ELocatorAPIH
if (nullptr != strstr(Params, "-file_activity"))
flags |= CLocatorAPI::flDumpFileActivity;
#endif
FS._initialize(flags, nullptr, fs_fname);
Msg("'%s' build %d, %s\n", "xrCore", build_id, build_date);
#ifdef DEBUG
Msg("CRT heap 0x%08x", _get_heap_handle());
Msg("Process heap 0x%08x", GetProcessHeap());
#endif // DEBUG
}
SetLogCB(cb);
init_counter++;
}
void xrCore::_destroy() {
--init_counter;
if (0 == init_counter) {
FS._destroy();
xr_delete(xr_FS);
Memory._destroy();
}
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpvReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH: {
_clear87();
#ifdef _M_IX86
_control87(_PC_53, MCW_PC);
#endif
_control87(_RC_CHOP, MCW_RC);
_control87(_RC_NEAR, MCW_RC);
_control87(_MCW_EM, MCW_EM);
}
//. LogFile.reserve (256);
break;
case DLL_THREAD_ATTACH:
if (!strstr(GetCommandLine(), "-editor"))
CoInitializeEx(NULL, COINIT_MULTITHREADED);
timeBeginPeriod(1);
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
#ifdef USE_MEMORY_MONITOR
memory_monitor::flush_each_time(true);
#endif // USE_MEMORY_MONITOR
break;
}
return TRUE;
}
| 26.462687 | 85 | 0.618161 | InNoHurryToCode |
cb2fa8ae45ffc0962cd377cbfd5bb689dfe27136 | 6,872 | hpp | C++ | src/compressed-sensing/lib/include/Armadillo/armadillo_bits/operator_relational.hpp | HerrFroehlich/ns3-CompressedSensing | f5e4e56aeea97794695ecef6183bdaa1b72fd1de | [
"MIT"
] | null | null | null | src/compressed-sensing/lib/include/Armadillo/armadillo_bits/operator_relational.hpp | HerrFroehlich/ns3-CompressedSensing | f5e4e56aeea97794695ecef6183bdaa1b72fd1de | [
"MIT"
] | null | null | null | src/compressed-sensing/lib/include/Armadillo/armadillo_bits/operator_relational.hpp | HerrFroehlich/ns3-CompressedSensing | f5e4e56aeea97794695ecef6183bdaa1b72fd1de | [
"MIT"
] | null | null | null | // Copyright (C) 2009-2012 NICTA (www.nicta.com.au)
// Copyright (C) 2009-2012 Conrad Sanderson
//
// This file is part of the Armadillo C++ library.
// It is provided without any warranty of fitness
// for any purpose. You can redistribute this file
// and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published
// by the Free Software Foundation, either version 3
// of the License or (at your option) any later version.
// (see http://www.opensource.org/licenses for more info)
//! \addtogroup operator_relational
//! @{
// < : lt
// > : gt
// <= : lteq
// >= : gteq
// == : eq
// != : noteq
template<typename T1, typename T2>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && is_arma_type<T2>::value && (is_complex<typename T1::elem_type>::value == false) && (is_complex<typename T2::elem_type>::value == false)),
const mtGlue<uword, T1, T2, glue_rel_lt>
>::result
operator<
(const T1& X, const T2& Y)
{
arma_extra_debug_sigprint();
return mtGlue<uword, T1, T2, glue_rel_lt>( X, Y );
}
template<typename T1, typename T2>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && is_arma_type<T2>::value && (is_complex<typename T1::elem_type>::value == false) && (is_complex<typename T2::elem_type>::value == false)),
const mtGlue<uword, T1, T2, glue_rel_gt>
>::result
operator>
(const T1& X, const T2& Y)
{
arma_extra_debug_sigprint();
return mtGlue<uword, T1, T2, glue_rel_gt>( X, Y );
}
template<typename T1, typename T2>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && is_arma_type<T2>::value && (is_complex<typename T1::elem_type>::value == false) && (is_complex<typename T2::elem_type>::value == false)),
const mtGlue<uword, T1, T2, glue_rel_lteq>
>::result
operator<=
(const T1& X, const T2& Y)
{
arma_extra_debug_sigprint();
return mtGlue<uword, T1, T2, glue_rel_lteq>( X, Y );
}
template<typename T1, typename T2>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && is_arma_type<T2>::value && (is_complex<typename T1::elem_type>::value == false) && (is_complex<typename T2::elem_type>::value == false)),
const mtGlue<uword, T1, T2, glue_rel_gteq>
>::result
operator>=
(const T1& X, const T2& Y)
{
arma_extra_debug_sigprint();
return mtGlue<uword, T1, T2, glue_rel_gteq>( X, Y );
}
template<typename T1, typename T2>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && is_arma_type<T2>::value),
const mtGlue<uword, T1, T2, glue_rel_eq>
>::result
operator==
(const T1& X, const T2& Y)
{
arma_extra_debug_sigprint();
return mtGlue<uword, T1, T2, glue_rel_eq>( X, Y );
}
template<typename T1, typename T2>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && is_arma_type<T2>::value),
const mtGlue<uword, T1, T2, glue_rel_noteq>
>::result
operator!=
(const T1& X, const T2& Y)
{
arma_extra_debug_sigprint();
return mtGlue<uword, T1, T2, glue_rel_noteq>( X, Y );
}
//
//
//
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_lt_pre>
>::result
operator<
(const typename T1::elem_type val, const T1& X)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_lt_pre>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_lt_post>
>::result
operator<
(const T1& X, const typename T1::elem_type val)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_lt_post>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_gt_pre>
>::result
operator>
(const typename T1::elem_type val, const T1& X)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_gt_pre>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_gt_post>
>::result
operator>
(const T1& X, const typename T1::elem_type val)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_gt_post>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_lteq_pre>
>::result
operator<=
(const typename T1::elem_type val, const T1& X)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_lteq_pre>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_lteq_post>
>::result
operator<=
(const T1& X, const typename T1::elem_type val)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_lteq_post>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_gteq_pre>
>::result
operator>=
(const typename T1::elem_type val, const T1& X)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_gteq_pre>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
(is_arma_type<T1>::value && (is_complex<typename T1::elem_type>::value == false)),
const mtOp<uword, T1, op_rel_gteq_post>
>::result
operator>=
(const T1& X, const typename T1::elem_type val)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_gteq_post>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
is_arma_type<T1>::value,
const mtOp<uword, T1, op_rel_eq>
>::result
operator==
(const typename T1::elem_type val, const T1& X)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_eq>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
is_arma_type<T1>::value,
const mtOp<uword, T1, op_rel_eq>
>::result
operator==
(const T1& X, const typename T1::elem_type val)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_eq>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
is_arma_type<T1>::value,
const mtOp<uword, T1, op_rel_noteq>
>::result
operator!=
(const typename T1::elem_type val, const T1& X)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_noteq>(X, val);
}
template<typename T1>
inline
typename
enable_if2
<
is_arma_type<T1>::value,
const mtOp<uword, T1, op_rel_noteq>
>::result
operator!=
(const T1& X, const typename T1::elem_type val)
{
arma_extra_debug_sigprint();
return mtOp<uword, T1, op_rel_noteq>(X, val);
}
//! @}
| 19.195531 | 167 | 0.685099 | HerrFroehlich |
cb35e0b1b7981cd1a0c28b179782ba942760bf3b | 9,617 | cpp | C++ | master/core/third/stlport/src/ios.cpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 30 | 2017-02-08T02:53:36.000Z | 2022-03-24T14:26:17.000Z | master/core/third/stlport/src/ios.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-05-25T00:39:02.000Z | 2018-04-27T10:38:47.000Z | master/core/third/stlport/src/ios.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 8 | 2017-10-31T11:12:35.000Z | 2020-06-15T04:12:51.000Z | /*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <algorithm>
#include <ios>
#include <locale>
#include <ostream> // for __get_ostreambuf definition
#include "aligned_buffer.h"
_STLP_BEGIN_NAMESPACE
//----------------------------------------------------------------------
// ios_base members
// class ios_base::failure, a subclass of exception. It's used solely
// for reporting errors.
ios_base::failure::failure(const string& s)
: __Named_exception(s)
{}
ios_base::failure::~failure() _STLP_NOTHROW_INHERENTLY {}
#if !defined (_STLP_STATIC_CONST_INIT_BUG) && !defined (_STLP_NO_STATIC_CONST_DEFINITION)
// Definitions of ios_base's formatting flags.
const ios_base::fmtflags ios_base::left;
const ios_base::fmtflags ios_base::right;
const ios_base::fmtflags ios_base::internal;
const ios_base::fmtflags ios_base::dec;
const ios_base::fmtflags ios_base::hex;
const ios_base::fmtflags ios_base::oct;
const ios_base::fmtflags ios_base::fixed;
const ios_base::fmtflags ios_base::scientific;
const ios_base::fmtflags ios_base::boolalpha;
const ios_base::fmtflags ios_base::showbase;
const ios_base::fmtflags ios_base::showpoint;
const ios_base::fmtflags ios_base::showpos;
const ios_base::fmtflags ios_base::skipws;
const ios_base::fmtflags ios_base::unitbuf;
const ios_base::fmtflags ios_base::uppercase;
const ios_base::fmtflags ios_base::adjustfield;
const ios_base::fmtflags ios_base::basefield;
const ios_base::fmtflags ios_base::floatfield;
// Definitions of ios_base's state flags.
const ios_base::iostate ios_base::goodbit;
const ios_base::iostate ios_base::badbit;
const ios_base::iostate ios_base::eofbit;
const ios_base::iostate ios_base::failbit;
// Definitions of ios_base's openmode flags.
const ios_base::openmode ios_base::app;
const ios_base::openmode ios_base::ate;
const ios_base::openmode ios_base::binary;
const ios_base::openmode ios_base::in;
const ios_base::openmode ios_base::out;
const ios_base::openmode ios_base::trunc;
// Definitions of ios_base's seekdir flags.
const ios_base::seekdir ios_base::beg;
const ios_base::seekdir ios_base::cur;
const ios_base::seekdir ios_base::end;
#endif
// Internal functions used for managing exponentially-growing arrays of
// POD types.
// array is a pointer to N elements of type PODType. Expands the array,
// if necessary, so that array[index] is meaningful. All new elements are
// initialized to zero. Returns a pointer to the new array, and the new
// size.
template <class PODType>
static pair<PODType*, size_t>
_Stl_expand_array(PODType* __array, size_t N, int index) {
if ((int)N < index + 1) {
size_t new_N = (max)(2 * N, size_t(index + 1));
PODType* new_array
= __STATIC_CAST(PODType*,realloc(__array, new_N * sizeof(PODType)));
if (new_array) {
fill(new_array + N, new_array + new_N, PODType());
return pair<PODType*, size_t>(new_array, new_N);
}
else
return pair<PODType*, size_t>(__STATIC_CAST(PODType*,0), 0);
}
else
return pair<PODType*, size_t>(__array, N);
}
// array is a pointer to N elements of type PODType. Allocate a new
// array of N elements, copying the values from the old array to the new.
// Return a pointer to the new array. It is assumed that array is non-null
// and N is nonzero.
template <class PODType>
static PODType* _Stl_copy_array(const PODType* __array, size_t N) {
PODType* result = __STATIC_CAST(PODType*,malloc(N * sizeof(PODType)));
if (result)
copy(__array, __array + N, result);
return result;
}
locale ios_base::imbue(const locale& loc) {
if (loc != _M_locale) {
locale previous = _M_locale;
_M_locale = loc;
_M_invoke_callbacks(imbue_event);
return previous;
}
else {
_M_invoke_callbacks(imbue_event);
return _M_locale;
}
}
int _STLP_CALL ios_base::xalloc() {
#if defined (_STLP_THREADS) && \
defined (_STLP_WIN32THREADS) && defined (_STLP_NEW_PLATFORM_SDK)
static volatile __stl_atomic_t _S_index = 0;
return _STLP_ATOMIC_INCREMENT(&_S_index);
#else
static int _S_index = 0;
static _STLP_STATIC_MUTEX __lock _STLP_MUTEX_INITIALIZER;
_STLP_auto_lock sentry(__lock);
return _S_index++;
#endif
}
long& ios_base::iword(int index) {
static long dummy = 0;
pair<long*, size_t> tmp = _Stl_expand_array(_M_iwords, _M_num_iwords, index);
if (tmp.first) { // The allocation, if any, succeeded.
_M_iwords = tmp.first;
_M_num_iwords = tmp.second;
return _M_iwords[index];
}
else {
_M_setstate_nothrow(badbit);
_M_check_exception_mask();
return dummy;
}
}
void*& ios_base::pword(int index) {
static void* dummy = 0;
pair<void**, size_t> tmp = _Stl_expand_array(_M_pwords, _M_num_pwords, index);
if (tmp.first) { // The allocation, if any, succeeded.
_M_pwords = tmp.first;
_M_num_pwords = tmp.second;
return _M_pwords[index];
}
else {
_M_setstate_nothrow(badbit);
_M_check_exception_mask();
return dummy;
}
}
void ios_base::register_callback(event_callback __fn, int index) {
pair<pair<event_callback, int>*, size_t> tmp
= _Stl_expand_array(_M_callbacks, _M_num_callbacks, (int)_M_callback_index /* fbp: index ??? */ );
if (tmp.first) {
_M_callbacks = tmp.first;
_M_num_callbacks = tmp.second;
_M_callbacks[_M_callback_index++] = make_pair(__fn, index);
}
else {
_M_setstate_nothrow(badbit);
_M_check_exception_mask();
}
}
// Invokes all currently registered callbacks for a particular event.
// Behaves correctly even if one of the callbacks adds a new callback.
void ios_base::_M_invoke_callbacks(event E) {
for (size_t i = _M_callback_index; i > 0; --i) {
event_callback f = _M_callbacks[i-1].first;
int n = _M_callbacks[i-1].second;
f(E, *this, n);
}
}
// This function is called if the state, rdstate(), has a bit set
// that is also set in the exception mask exceptions().
void ios_base::_M_throw_failure() {
const char* arg ;
# if 0
char buffer[256];
char* ptr;
strcpy(buffer, "ios failure: rdstate = 0x");
ptr = __write_integer(buffer+strlen(buffer), ios_base::hex, __STATIC_CAST(unsigned long,_M_iostate));
strcpy(ptr, " mask = 0x");
ptr = __write_integer(buffer+strlen(buffer), ios_base::hex, __STATIC_CAST(unsigned long,_M_exception_mask));
*ptr = 0;
arg = buffer;
# else
arg = "ios failure";
# endif
# ifndef _STLP_USE_EXCEPTIONS
fputs(arg, stderr);
# else
throw failure(arg);
# endif
}
// Copy x's state to *this. This member function is used in the
// implementation of basic_ios::copyfmt. Does not copy _M_exception_mask
// or _M_iostate.
void ios_base::_M_copy_state(const ios_base& x) {
_M_fmtflags = x._M_fmtflags; // Copy the flags, except for _M_iostate
_M_openmode = x._M_openmode; // and _M_exception_mask.
_M_seekdir = x._M_seekdir;
_M_precision = x._M_precision;
_M_width = x._M_width;
_M_locale = x._M_locale;
if (x._M_callbacks) {
pair<event_callback, int>* tmp = _Stl_copy_array(x._M_callbacks, x._M_callback_index);
if (tmp) {
free(_M_callbacks);
_M_callbacks = tmp;
_M_num_callbacks = _M_callback_index = x._M_callback_index;
}
else {
_M_setstate_nothrow(badbit);
_M_check_exception_mask();
}
}
if (x._M_iwords) {
long* tmp = _Stl_copy_array(x._M_iwords, x._M_num_iwords);
if (tmp) {
free(_M_iwords);
_M_iwords = tmp;
_M_num_iwords = x._M_num_iwords;
}
else {
_M_setstate_nothrow(badbit);
_M_check_exception_mask();
}
}
if (x._M_pwords) {
void** tmp = _Stl_copy_array(x._M_pwords, x._M_num_pwords);
if (tmp) {
free(_M_pwords);
_M_pwords = tmp;
_M_num_pwords = x._M_num_pwords;
}
else {
_M_setstate_nothrow(badbit);
_M_check_exception_mask();
}
}
}
// ios's (protected) default constructor. The standard says that all
// fields have indeterminate values; we initialize them to zero for
// simplicity. The only thing that really matters is that the arrays
// are all initially null pointers, and the array element counts are all
// initially zero.
ios_base::ios_base()
: _M_fmtflags(0), _M_iostate(0), _M_openmode(0), _M_seekdir(0),
_M_exception_mask(0),
_M_precision(0), _M_width(0),
_M_locale(),
_M_callbacks(0), _M_num_callbacks(0), _M_callback_index(0),
_M_iwords(0), _M_num_iwords(0),
_M_pwords(0),
_M_num_pwords(0)
{}
// ios's destructor.
ios_base::~ios_base() {
_M_invoke_callbacks(erase_event);
free(_M_callbacks);
free(_M_iwords);
free(_M_pwords);
}
//----------------------------------------------------------------------
// Force instantiation of basic_ios
// For DLL exports, they are already instantiated.
#if !defined(_STLP_NO_FORCE_INSTANTIATE)
template class _STLP_CLASS_DECLSPEC basic_ios<char, char_traits<char> >;
# if !defined (_STLP_NO_WCHAR_T)
template class _STLP_CLASS_DECLSPEC basic_ios<wchar_t, char_traits<wchar_t> >;
# endif /* _STLP_NO_WCHAR_T */
#endif
_STLP_END_NAMESPACE
// Local Variables:
// mode:C++
// End:
| 30.147335 | 110 | 0.706353 | importlib |
cb3690ebe5483db5b3697e5073cd330b91454b8c | 19,465 | hpp | C++ | cell_based/test/population/TestCaUpdateRules.hpp | ktunya/ChasteMod | 88ac65b00473cd730d348c783bd74b2b39de5f69 | [
"Apache-2.0"
] | null | null | null | cell_based/test/population/TestCaUpdateRules.hpp | ktunya/ChasteMod | 88ac65b00473cd730d348c783bd74b2b39de5f69 | [
"Apache-2.0"
] | null | null | null | cell_based/test/population/TestCaUpdateRules.hpp | ktunya/ChasteMod | 88ac65b00473cd730d348c783bd74b2b39de5f69 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
#ifndef TESTCAUPDATERULES_HPP_
#define TESTCAUPDATERULES_HPP_
#include <cxxtest/TestSuite.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "AbstractCaUpdateRule.hpp"
#include "DiffusionCaUpdateRule.hpp"
#include "AbstractCaSwitchingUpdateRule.hpp"
#include "RandomCaSwitchingUpdateRule.hpp"
#include "CellsGenerator.hpp"
#include "FixedDurationGenerationBasedCellCycleModel.hpp"
#include "CaBasedCellPopulation.hpp"
#include "AbstractCellBasedTestSuite.hpp"
#include "WildTypeCellMutationState.hpp"
#include "CellLabel.hpp"
#include "PottsMeshGenerator.hpp"
#include "NodesOnlyMesh.hpp"
#include "NodeBasedCellPopulation.hpp"
#include "SmartPointers.hpp"
#include "FileComparison.hpp"
#include "PetscSetupAndFinalize.hpp"
class TestCaUpdateRules : public AbstractCellBasedTestSuite
{
public:
void TestDiffusionCaUpdateRuleIn2d() throw (Exception)
{
// Set the timestep and size of domain to let us calculate the probabilities of movement
double delta_t = 1;
double delta_x = 1;
double diffusion_parameter = 0.1;
// Create an update law system
DiffusionCaUpdateRule<2> diffusion_update_rule;
// Test get/set methods
TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 0.5, 1e-12);
diffusion_update_rule.SetDiffusionParameter(1.0);
TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 1.0, 1e-12);
diffusion_update_rule.SetDiffusionParameter(diffusion_parameter);
// Test EvaluateProbability()
// Create a simple 2D PottsMesh
PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0);
PottsMesh<2>* p_mesh = generator.GetMesh();
// Create cells
std::vector<CellPtr> cells;
MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type);
CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasicRandom(cells, 1u, p_diff_type);
// Specify where cells lie here we have one cell on the bottom left site
std::vector<unsigned> location_indices;
location_indices.push_back(0u);
// Create cell population
CaBasedCellPopulation<2u> cell_population(*p_mesh, cells, location_indices);
// Note we just pass a pointer to the only cell as DiffusionUpdateRule is independent of cell type.
CellPtr p_cell = cell_population.rGetCells().front();
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,5,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,10,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(6,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(7,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(10,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(12,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(15,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(16,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(17,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,19,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,18,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,23,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
}
void TestDiffusionCaUpdateRuleIn2dWithMultipleCells() throw (Exception)
{
// Set the timestep and size of domain to let us calculate the probabilities of movement
double delta_t = 1;
double delta_x = 1;
double diffusion_parameter = 0.1;
// Create an update law system
DiffusionCaUpdateRule<2> diffusion_update_rule;
// Test get/set methods
TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 0.5, 1e-12);
diffusion_update_rule.SetDiffusionParameter(1.0);
TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 1.0, 1e-12);
diffusion_update_rule.SetDiffusionParameter(diffusion_parameter);
// Test EvaluateProbability()
// Create a simple 2D PottsMesh
PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0);
PottsMesh<2>* p_mesh = generator.GetMesh();
// Create cells
std::vector<CellPtr> cells;
MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type);
CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasicRandom(cells, 10u, p_diff_type);
// Specify where cells lie here we have one cell on the bottom left site
std::vector<unsigned> location_indices;
// Two cells will be added in locations 0 and 1
location_indices.push_back(0u);
location_indices.push_back(0u);
location_indices.push_back(1u);
location_indices.push_back(1u);
// Then other cells are added to the lattice to check if the probabilities are still the same
for (unsigned i=4; i<10; i++)
{
location_indices.push_back(i);
}
// Create cell population
CaBasedCellPopulation<2u> cell_population(*p_mesh, cells, location_indices, 2);
// Note we just pass a pointer to the first cell as DiffusionUpdateRule is independent of cell type.
CellPtr p_cell = cell_population.rGetCells().front();
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,5,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,10,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(6,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(7,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(10,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(12,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(15,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(16,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(17,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,19,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,18,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6);
TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,23,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6);
}
void TestArchiveDiffusionCaUpdateRule() throw(Exception)
{
OutputFileHandler handler("archive", false);
std::string archive_filename = handler.GetOutputDirectoryFullPath() + "DiffusionCaUpdateRule.arch";
{
DiffusionCaUpdateRule<2> update_rule;
std::ofstream ofs(archive_filename.c_str());
boost::archive::text_oarchive output_arch(ofs);
// Set member variables
update_rule.SetDiffusionParameter(1.0);
// Serialize via pointer to most abstract class possible
AbstractCaUpdateRule<2>* const p_update_rule = &update_rule;
output_arch << p_update_rule;
}
{
AbstractCaUpdateRule<2>* p_update_rule;
// Create an input archive
std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
boost::archive::text_iarchive input_arch(ifs);
// Restore from the archive
input_arch >> p_update_rule;
// Test the member data
TS_ASSERT_DELTA((static_cast<DiffusionCaUpdateRule<2>*>(p_update_rule))->GetDiffusionParameter(), 1.0, 1e-6);
// Tidy up
delete p_update_rule;
}
}
void TestUpdateRuleOutputUpdateRuleInfo()
{
std::string output_directory = "TestCaUpdateRulesOutputParameters";
OutputFileHandler output_file_handler(output_directory, false);
// Test with VolumeConstraintPottsUpdateRule
DiffusionCaUpdateRule<2> diffusion_update_rule;
diffusion_update_rule.SetDiffusionParameter(1.0);
TS_ASSERT_EQUALS(diffusion_update_rule.GetIdentifier(), "DiffusionCaUpdateRule-2");
out_stream diffusion_update_rule_parameter_file = output_file_handler.OpenOutputFile("diffusion_update_rule_results.parameters");
diffusion_update_rule.OutputUpdateRuleInfo(diffusion_update_rule_parameter_file);
diffusion_update_rule_parameter_file->close();
// Compare the generated file in test output with a reference copy in the source code.
FileFinder generated = output_file_handler.FindFile("diffusion_update_rule_results.parameters");
FileFinder reference("cell_based/test/data/TestCaUpdateRules/diffusion_update_rule_results.parameters",
RelativeTo::ChasteSourceRoot);
FileComparison comparer(generated, reference);
TS_ASSERT(comparer.CompareFiles());
}
/*
* Now test the switching rules.
*/
void TestRandomCaSwitchingUpdateRuleIn2d() throw (Exception)
{
// Set the timestep and size of domain to let us calculate the probabilities of movement
double delta_t = 0.1;
double delta_x = 1;
double switching_parameter = 0.1;
// Create an update law system
RandomCaSwitchingUpdateRule<2> random_switching_update_rule;
// Test get/set methods
TS_ASSERT_DELTA(random_switching_update_rule.GetSwitchingParameter(), 0.5, 1e-12);
random_switching_update_rule.SetSwitchingParameter(1.0);
TS_ASSERT_DELTA(random_switching_update_rule.GetSwitchingParameter(), 1.0, 1e-12);
random_switching_update_rule.SetSwitchingParameter(switching_parameter);
// Test EvaluateProbability()
// Create a simple 2D PottsMesh
PottsMeshGenerator<2> generator(3, 0, 0, 3, 0, 0);
PottsMesh<2>* p_mesh = generator.GetMesh();
// Create cells
std::vector<CellPtr> cells;
MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type);
CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasicRandom(cells, 6u, p_diff_type);
// Specify where cells lie here we have cells on the bottom two rows
std::vector<unsigned> location_indices;
for (unsigned i=0; i<6; i++)
{
location_indices.push_back(i);
}
// Create cell population
CaBasedCellPopulation<2u> cell_population(*p_mesh, cells, location_indices);
TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(0,1,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6);
TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(0,6,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6);
TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(0,5,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6);
// Note this is independent of node index and population so even returns for nodes not in the mesh
TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(UNSIGNED_UNSET,UNSIGNED_UNSET,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6);
}
void TestArchiveRandomCaSwitchingUpdateRule() throw(Exception)
{
OutputFileHandler handler("archive", false);
std::string archive_filename = handler.GetOutputDirectoryFullPath() + "RandomCaSwitchingUpdateRule.arch";
{
RandomCaSwitchingUpdateRule<2> update_rule;
std::ofstream ofs(archive_filename.c_str());
boost::archive::text_oarchive output_arch(ofs);
// Set member variables
update_rule.SetSwitchingParameter(1.0);
// Serialize via pointer to most abstract class possible
AbstractCaSwitchingUpdateRule<2>* const p_update_rule = &update_rule;
output_arch << p_update_rule;
}
{
AbstractCaSwitchingUpdateRule<2>* p_update_rule;
// Create an input archive
std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
boost::archive::text_iarchive input_arch(ifs);
// Restore from the archive
input_arch >> p_update_rule;
// Test the member data
TS_ASSERT_DELTA((static_cast<RandomCaSwitchingUpdateRule<2>*>(p_update_rule))->GetSwitchingParameter(), 1.0, 1e-6);
// Tidy up
delete p_update_rule;
}
}
void TestSwitchingUpdateRuleOutputUpdateRuleInfo()
{
std::string output_directory = "TestCaSwitchingUpdateRulesOutputParameters";
OutputFileHandler output_file_handler(output_directory, false);
// Test with RandomCaSwitchingUpdateRule
RandomCaSwitchingUpdateRule<2> random_switching_update_rule;
random_switching_update_rule.SetSwitchingParameter(1.0);
TS_ASSERT_EQUALS(random_switching_update_rule.GetIdentifier(), "RandomCaSwitchingUpdateRule-2");
out_stream random_switching_update_rule_parameter_file = output_file_handler.OpenOutputFile("random_switching_update_rule_results.parameters");
random_switching_update_rule.OutputUpdateRuleInfo(random_switching_update_rule_parameter_file);
random_switching_update_rule_parameter_file->close();
// Compare the generated file in test output with a reference copy in the source code.
FileFinder generated = output_file_handler.FindFile("random_switching_update_rule_results.parameters");
FileFinder reference("cell_based/test/data/TestCaUpdateRules/random_switching_update_rule_results.parameters",
RelativeTo::ChasteSourceRoot);
FileComparison comparer(generated, reference);
TS_ASSERT(comparer.CompareFiles());
}
};
#endif /*TESTCAUPDATERULES_HPP_*/
| 52.045455 | 181 | 0.748369 | ktunya |
cb370095a6b4e8b18d585f0df5772a6ad543bb04 | 45,446 | cpp | C++ | deps/NVIDIATextureTools/src/nvimage/DirectDrawSurface.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | deps/NVIDIATextureTools/src/nvimage/DirectDrawSurface.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | deps/NVIDIATextureTools/src/nvimage/DirectDrawSurface.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | 1 | 2021-05-23T16:33:11.000Z | 2021-05-23T16:33:11.000Z | // Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.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 "DirectDrawSurface.h"
#include "ColorBlock.h"
#include "Image.h"
#include "BlockDXT.h"
#include "PixelFormat.h"
#include "nvcore/Debug.h"
#include "nvcore/Utils.h" // max
#include "nvcore/StdStream.h"
#include <string.h> // memset
using namespace nv;
namespace
{
static const uint DDSD_CAPS = 0x00000001U;
static const uint DDSD_PIXELFORMAT = 0x00001000U;
static const uint DDSD_WIDTH = 0x00000004U;
static const uint DDSD_HEIGHT = 0x00000002U;
static const uint DDSD_PITCH = 0x00000008U;
static const uint DDSD_MIPMAPCOUNT = 0x00020000U;
static const uint DDSD_LINEARSIZE = 0x00080000U;
static const uint DDSD_DEPTH = 0x00800000U;
static const uint DDSCAPS_COMPLEX = 0x00000008U;
static const uint DDSCAPS_TEXTURE = 0x00001000U;
static const uint DDSCAPS_MIPMAP = 0x00400000U;
static const uint DDSCAPS2_VOLUME = 0x00200000U;
static const uint DDSCAPS2_CUBEMAP = 0x00000200U;
static const uint DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
static const uint DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
static const uint DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
static const uint DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
static const uint DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
static const uint DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
static const uint DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
const char * getDxgiFormatString(DXGI_FORMAT dxgiFormat)
{
#define CASE(format) case DXGI_FORMAT_##format: return #format
switch(dxgiFormat)
{
CASE(UNKNOWN);
CASE(R32G32B32A32_TYPELESS);
CASE(R32G32B32A32_FLOAT);
CASE(R32G32B32A32_UINT);
CASE(R32G32B32A32_SINT);
CASE(R32G32B32_TYPELESS);
CASE(R32G32B32_FLOAT);
CASE(R32G32B32_UINT);
CASE(R32G32B32_SINT);
CASE(R16G16B16A16_TYPELESS);
CASE(R16G16B16A16_FLOAT);
CASE(R16G16B16A16_UNORM);
CASE(R16G16B16A16_UINT);
CASE(R16G16B16A16_SNORM);
CASE(R16G16B16A16_SINT);
CASE(R32G32_TYPELESS);
CASE(R32G32_FLOAT);
CASE(R32G32_UINT);
CASE(R32G32_SINT);
CASE(R32G8X24_TYPELESS);
CASE(D32_FLOAT_S8X24_UINT);
CASE(R32_FLOAT_X8X24_TYPELESS);
CASE(X32_TYPELESS_G8X24_UINT);
CASE(R10G10B10A2_TYPELESS);
CASE(R10G10B10A2_UNORM);
CASE(R10G10B10A2_UINT);
CASE(R11G11B10_FLOAT);
CASE(R8G8B8A8_TYPELESS);
CASE(R8G8B8A8_UNORM);
CASE(R8G8B8A8_UNORM_SRGB);
CASE(R8G8B8A8_UINT);
CASE(R8G8B8A8_SNORM);
CASE(R8G8B8A8_SINT);
CASE(R16G16_TYPELESS);
CASE(R16G16_FLOAT);
CASE(R16G16_UNORM);
CASE(R16G16_UINT);
CASE(R16G16_SNORM);
CASE(R16G16_SINT);
CASE(R32_TYPELESS);
CASE(D32_FLOAT);
CASE(R32_FLOAT);
CASE(R32_UINT);
CASE(R32_SINT);
CASE(R24G8_TYPELESS);
CASE(D24_UNORM_S8_UINT);
CASE(R24_UNORM_X8_TYPELESS);
CASE(X24_TYPELESS_G8_UINT);
CASE(R8G8_TYPELESS);
CASE(R8G8_UNORM);
CASE(R8G8_UINT);
CASE(R8G8_SNORM);
CASE(R8G8_SINT);
CASE(R16_TYPELESS);
CASE(R16_FLOAT);
CASE(D16_UNORM);
CASE(R16_UNORM);
CASE(R16_UINT);
CASE(R16_SNORM);
CASE(R16_SINT);
CASE(R8_TYPELESS);
CASE(R8_UNORM);
CASE(R8_UINT);
CASE(R8_SNORM);
CASE(R8_SINT);
CASE(A8_UNORM);
CASE(R1_UNORM);
CASE(R9G9B9E5_SHAREDEXP);
CASE(R8G8_B8G8_UNORM);
CASE(G8R8_G8B8_UNORM);
CASE(BC1_TYPELESS);
CASE(BC1_UNORM);
CASE(BC1_UNORM_SRGB);
CASE(BC2_TYPELESS);
CASE(BC2_UNORM);
CASE(BC2_UNORM_SRGB);
CASE(BC3_TYPELESS);
CASE(BC3_UNORM);
CASE(BC3_UNORM_SRGB);
CASE(BC4_TYPELESS);
CASE(BC4_UNORM);
CASE(BC4_SNORM);
CASE(BC5_TYPELESS);
CASE(BC5_UNORM);
CASE(BC5_SNORM);
CASE(B5G6R5_UNORM);
CASE(B5G5R5A1_UNORM);
CASE(B8G8R8A8_UNORM);
CASE(B8G8R8X8_UNORM);
default:
return "UNKNOWN";
}
#undef CASE
}
const char * getD3d10ResourceDimensionString(DDS_DIMENSION resourceDimension)
{
switch(resourceDimension)
{
default:
case DDS_DIMENSION_UNKNOWN: return "UNKNOWN";
case DDS_DIMENSION_BUFFER: return "BUFFER";
case DDS_DIMENSION_TEXTURE1D: return "TEXTURE1D";
case DDS_DIMENSION_TEXTURE2D: return "TEXTURE2D";
case DDS_DIMENSION_TEXTURE3D: return "TEXTURE3D";
}
}
static uint pixelSize(D3DFORMAT format) {
if (format == D3DFMT_R16F) return 8*2;
if (format == D3DFMT_G16R16F) return 8*4;
if (format == D3DFMT_A16B16G16R16F) return 8*8;
if (format == D3DFMT_R32F) return 8*4;
if (format == D3DFMT_G32R32F) return 8*8;
if (format == D3DFMT_A32B32G32R32F) return 8*16;
if (format == D3DFMT_R8G8B8) return 8*3;
if (format == D3DFMT_A8R8G8B8) return 8*4;
if (format == D3DFMT_X8R8G8B8) return 8*4;
if (format == D3DFMT_R5G6B5) return 8*2;
if (format == D3DFMT_X1R5G5B5) return 8*2;
if (format == D3DFMT_A1R5G5B5) return 8*2;
if (format == D3DFMT_A4R4G4B4) return 8*2;
if (format == D3DFMT_R3G3B2) return 8*1;
if (format == D3DFMT_A8) return 8*1;
if (format == D3DFMT_A8R3G3B2) return 8*2;
if (format == D3DFMT_X4R4G4B4) return 8*2;
if (format == D3DFMT_A2B10G10R10) return 8*4;
if (format == D3DFMT_A8B8G8R8) return 8*4;
if (format == D3DFMT_X8B8G8R8) return 8*4;
if (format == D3DFMT_G16R16) return 8*4;
if (format == D3DFMT_A2R10G10B10) return 8*4;
if (format == D3DFMT_A2B10G10R10) return 8*4;
if (format == D3DFMT_L8) return 8*1;
if (format == D3DFMT_L16) return 8*2;
return 0;
}
static uint pixelSize(DXGI_FORMAT format) {
switch(format) {
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
case DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT_R32G32B32A32_UINT:
case DXGI_FORMAT_R32G32B32A32_SINT:
return 8*16;
case DXGI_FORMAT_R32G32B32_TYPELESS:
case DXGI_FORMAT_R32G32B32_FLOAT:
case DXGI_FORMAT_R32G32B32_UINT:
case DXGI_FORMAT_R32G32B32_SINT:
return 8*12;
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
case DXGI_FORMAT_R16G16B16A16_FLOAT:
case DXGI_FORMAT_R16G16B16A16_UNORM:
case DXGI_FORMAT_R16G16B16A16_UINT:
case DXGI_FORMAT_R16G16B16A16_SNORM:
case DXGI_FORMAT_R16G16B16A16_SINT:
case DXGI_FORMAT_R32G32_TYPELESS:
case DXGI_FORMAT_R32G32_FLOAT:
case DXGI_FORMAT_R32G32_UINT:
case DXGI_FORMAT_R32G32_SINT:
case DXGI_FORMAT_R32G8X24_TYPELESS:
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
return 8*8;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
case DXGI_FORMAT_R10G10B10A2_UNORM:
case DXGI_FORMAT_R10G10B10A2_UINT:
case DXGI_FORMAT_R11G11B10_FLOAT:
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_R8G8B8A8_UINT:
case DXGI_FORMAT_R8G8B8A8_SNORM:
case DXGI_FORMAT_R8G8B8A8_SINT:
case DXGI_FORMAT_R16G16_TYPELESS:
case DXGI_FORMAT_R16G16_FLOAT:
case DXGI_FORMAT_R16G16_UNORM:
case DXGI_FORMAT_R16G16_UINT:
case DXGI_FORMAT_R16G16_SNORM:
case DXGI_FORMAT_R16G16_SINT:
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_D32_FLOAT:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_UINT:
case DXGI_FORMAT_R32_SINT:
case DXGI_FORMAT_R24G8_TYPELESS:
case DXGI_FORMAT_D24_UNORM_S8_UINT:
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
return 8*4;
case DXGI_FORMAT_R8G8_TYPELESS:
case DXGI_FORMAT_R8G8_UNORM:
case DXGI_FORMAT_R8G8_UINT:
case DXGI_FORMAT_R8G8_SNORM:
case DXGI_FORMAT_R8G8_SINT:
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_D16_UNORM:
case DXGI_FORMAT_R16_UNORM:
case DXGI_FORMAT_R16_UINT:
case DXGI_FORMAT_R16_SNORM:
case DXGI_FORMAT_R16_SINT:
return 8*2;
case DXGI_FORMAT_R8_TYPELESS:
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R8_UINT:
case DXGI_FORMAT_R8_SNORM:
case DXGI_FORMAT_R8_SINT:
case DXGI_FORMAT_A8_UNORM:
return 8*1;
case DXGI_FORMAT_R1_UNORM:
return 1;
case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
return 8*4;
case DXGI_FORMAT_R8G8_B8G8_UNORM:
case DXGI_FORMAT_G8R8_G8B8_UNORM:
return 8*4;
case DXGI_FORMAT_B5G6R5_UNORM:
case DXGI_FORMAT_B5G5R5A1_UNORM:
return 8*2;
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8X8_UNORM:
return 8*4;
case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
return 8*4;
}
return 0;
}
} // namespace
namespace nv
{
static Stream & operator<< (Stream & s, DDSPixelFormat & pf)
{
nvStaticCheck(sizeof(DDSPixelFormat) == 32);
s << pf.size;
s << pf.flags;
s << pf.fourcc;
s << pf.bitcount;
s.serialize(&pf.rmask, sizeof(pf.rmask));
s.serialize(&pf.gmask, sizeof(pf.gmask));
s.serialize(&pf.bmask, sizeof(pf.bmask));
s.serialize(&pf.amask, sizeof(pf.amask));
// s << pf.rmask;
// s << pf.gmask;
// s << pf.bmask;
// s << pf.amask;
return s;
}
static Stream & operator<< (Stream & s, DDSCaps & caps)
{
nvStaticCheck(sizeof(DDSCaps) == 16);
s << caps.caps1;
s << caps.caps2;
s << caps.caps3;
s << caps.caps4;
return s;
}
static Stream & operator<< (Stream & s, DDSHeader10 & header)
{
nvStaticCheck(sizeof(DDSHeader10) == 20);
s << header.dxgiFormat;
s << header.resourceDimension;
s << header.miscFlag;
s << header.arraySize;
s << header.reserved;
return s;
}
Stream & operator<< (Stream & s, DDSHeader & header)
{
nvStaticCheck(sizeof(DDSHeader) == 148);
s << header.fourcc;
s << header.size;
s << header.flags;
s << header.height;
s << header.width;
s << header.pitch;
s << header.depth;
s << header.mipmapcount;
for (int i = 0; i < 11; i++) {
s << header.reserved[i];
}
s << header.pf;
s << header.caps;
s << header.notused;
if (header.hasDX10Header())
{
s << header.header10;
}
return s;
}
} // nv namespace
namespace
{
struct FormatDescriptor
{
uint format;
uint bitcount;
uint rmask;
uint gmask;
uint bmask;
uint amask;
};
static const FormatDescriptor s_d3d9Formats[] =
{
{ D3DFMT_R8G8B8, 24, 0xFF0000, 0xFF00, 0xFF, 0 },
{ D3DFMT_A8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, // DXGI_FORMAT_B8G8R8A8_UNORM
{ D3DFMT_X8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0 }, // DXGI_FORMAT_B8G8R8X8_UNORM
{ D3DFMT_R5G6B5, 16, 0xF800, 0x7E0, 0x1F, 0 }, // DXGI_FORMAT_B5G6R5_UNORM
{ D3DFMT_X1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0 },
{ D3DFMT_A1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0x8000 }, // DXGI_FORMAT_B5G5R5A1_UNORM
{ D3DFMT_A4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0xF000 },
{ D3DFMT_R3G3B2, 8, 0xE0, 0x1C, 0x3, 0 },
{ D3DFMT_A8, 8, 0, 0, 0, 8 }, // DXGI_FORMAT_A8_UNORM
{ D3DFMT_A8R3G3B2, 16, 0xE0, 0x1C, 0x3, 0xFF00 },
{ D3DFMT_X4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0 },
{ D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 }, // DXGI_FORMAT_R10G10B10A2
{ D3DFMT_A8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000 }, // DXGI_FORMAT_R8G8B8A8_UNORM
{ D3DFMT_X8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0 },
{ D3DFMT_G16R16, 32, 0xFFFF, 0xFFFF0000, 0, 0 }, // DXGI_FORMAT_R16G16_UNORM
{ D3DFMT_A2R10G10B10, 32, 0x3FF00000, 0xFFC00, 0x3FF, 0xC0000000 },
{ D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 },
{ D3DFMT_L8, 8, 8, 0, 0, 0 }, // DXGI_FORMAT_R8_UNORM
{ D3DFMT_L16, 16, 16, 0, 0, 0 }, // DXGI_FORMAT_R16_UNORM
};
static const uint s_d3d9FormatCount = NV_ARRAY_SIZE(s_d3d9Formats);
} // namespace
uint nv::findD3D9Format(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
{
for (int i = 0; i < s_d3d9FormatCount; i++)
{
if (s_d3d9Formats[i].bitcount == bitcount &&
s_d3d9Formats[i].rmask == rmask &&
s_d3d9Formats[i].gmask == gmask &&
s_d3d9Formats[i].bmask == bmask &&
s_d3d9Formats[i].amask == amask)
{
return s_d3d9Formats[i].format;
}
}
return 0;
}
DDSHeader::DDSHeader()
{
this->fourcc = FOURCC_DDS;
this->size = 124;
this->flags = (DDSD_CAPS|DDSD_PIXELFORMAT);
this->height = 0;
this->width = 0;
this->pitch = 0;
this->depth = 0;
this->mipmapcount = 0;
memset(this->reserved, 0, sizeof(this->reserved));
// Store version information on the reserved header attributes.
this->reserved[9] = FOURCC_NVTT;
this->reserved[10] = (2 << 16) | (1 << 8) | (0); // major.minor.revision
this->pf.size = 32;
this->pf.flags = 0;
this->pf.fourcc = 0;
this->pf.bitcount = 0;
this->pf.rmask = 0;
this->pf.gmask = 0;
this->pf.bmask = 0;
this->pf.amask = 0;
this->caps.caps1 = DDSCAPS_TEXTURE;
this->caps.caps2 = 0;
this->caps.caps3 = 0;
this->caps.caps4 = 0;
this->notused = 0;
this->header10.dxgiFormat = DXGI_FORMAT_UNKNOWN;
this->header10.resourceDimension = DDS_DIMENSION_UNKNOWN;
this->header10.miscFlag = 0;
this->header10.arraySize = 0;
this->header10.reserved = 0;
}
void DDSHeader::setWidth(uint w)
{
this->flags |= DDSD_WIDTH;
this->width = w;
}
void DDSHeader::setHeight(uint h)
{
this->flags |= DDSD_HEIGHT;
this->height = h;
}
void DDSHeader::setDepth(uint d)
{
this->flags |= DDSD_DEPTH;
this->depth = d;
}
void DDSHeader::setMipmapCount(uint count)
{
if (count == 0 || count == 1)
{
this->flags &= ~DDSD_MIPMAPCOUNT;
this->mipmapcount = 1;
if (this->caps.caps2 == 0) {
this->caps.caps1 = DDSCAPS_TEXTURE;
}
else {
this->caps.caps1 = DDSCAPS_TEXTURE | DDSCAPS_COMPLEX;
}
}
else
{
this->flags |= DDSD_MIPMAPCOUNT;
this->mipmapcount = count;
this->caps.caps1 |= DDSCAPS_COMPLEX | DDSCAPS_MIPMAP;
}
}
void DDSHeader::setTexture2D()
{
this->header10.resourceDimension = DDS_DIMENSION_TEXTURE2D;
this->header10.miscFlag = 0;
this->header10.arraySize = 1;
}
void DDSHeader::setTexture3D()
{
this->caps.caps2 = DDSCAPS2_VOLUME;
this->header10.resourceDimension = DDS_DIMENSION_TEXTURE3D;
this->header10.miscFlag = 0;
this->header10.arraySize = 1;
}
void DDSHeader::setTextureCube()
{
this->caps.caps1 |= DDSCAPS_COMPLEX;
this->caps.caps2 = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_ALL_FACES;
this->header10.resourceDimension = DDS_DIMENSION_TEXTURE2D;
this->header10.miscFlag = DDS_MISC_TEXTURECUBE;
this->header10.arraySize = 1;
}
void DDSHeader::setLinearSize(uint size)
{
this->flags &= ~DDSD_PITCH;
this->flags |= DDSD_LINEARSIZE;
this->pitch = size;
}
void DDSHeader::setPitch(uint pitch)
{
this->flags &= ~DDSD_LINEARSIZE;
this->flags |= DDSD_PITCH;
this->pitch = pitch;
}
void DDSHeader::setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3)
{
// set fourcc pixel format.
this->pf.flags = DDPF_FOURCC;
this->pf.fourcc = MAKEFOURCC(c0, c1, c2, c3);
this->pf.bitcount = 0;
this->pf.rmask = 0;
this->pf.gmask = 0;
this->pf.bmask = 0;
this->pf.amask = 0;
}
void DDSHeader::setFormatCode(uint32 code)
{
// set fourcc pixel format.
this->pf.flags = DDPF_FOURCC;
this->pf.fourcc = code;
this->pf.bitcount = 0;
this->pf.rmask = 0;
this->pf.gmask = 0;
this->pf.bmask = 0;
this->pf.amask = 0;
}
void DDSHeader::setSwizzleCode(uint8 c0, uint8 c1, uint8 c2, uint8 c3)
{
this->pf.bitcount = MAKEFOURCC(c0, c1, c2, c3);
}
void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
{
// Make sure the masks are correct.
nvCheck((rmask & gmask) == 0);
nvCheck((rmask & bmask) == 0);
nvCheck((rmask & amask) == 0);
nvCheck((gmask & bmask) == 0);
nvCheck((gmask & amask) == 0);
nvCheck((bmask & amask) == 0);
if (rmask != 0 || gmask != 0 || bmask != 0)
{
if (gmask == 0 && bmask == 0)
{
this->pf.flags = DDPF_LUMINANCE;
}
else
{
this->pf.flags = DDPF_RGB;
}
if (amask != 0) {
this->pf.flags |= DDPF_ALPHAPIXELS;
}
}
else if (amask != 0)
{
this->pf.flags |= DDPF_ALPHA;
}
if (bitcount == 0)
{
// Compute bit count from the masks.
uint total = rmask | gmask | bmask | amask;
while(total != 0) {
bitcount++;
total >>= 1;
}
}
// D3DX functions do not like this:
this->pf.fourcc = 0; //findD3D9Format(bitcount, rmask, gmask, bmask, amask);
/*if (this->pf.fourcc) {
this->pf.flags |= DDPF_FOURCC;
}*/
nvCheck(bitcount > 0 && bitcount <= 32);
this->pf.bitcount = bitcount;
this->pf.rmask = rmask;
this->pf.gmask = gmask;
this->pf.bmask = bmask;
this->pf.amask = amask;
}
void DDSHeader::setDX10Format(uint format)
{
this->pf.flags = DDPF_FOURCC;
this->pf.fourcc = FOURCC_DX10;
this->header10.dxgiFormat = format;
}
void DDSHeader::setNormalFlag(bool b)
{
if (b) this->pf.flags |= DDPF_NORMAL;
else this->pf.flags &= ~DDPF_NORMAL;
}
void DDSHeader::setSrgbFlag(bool b)
{
if (b) this->pf.flags |= DDPF_SRGB;
else this->pf.flags &= ~DDPF_SRGB;
}
void DDSHeader::setHasAlphaFlag(bool b)
{
if (b) this->pf.flags |= DDPF_ALPHAPIXELS;
else this->pf.flags &= ~DDPF_ALPHAPIXELS;
}
void DDSHeader::setUserVersion(int version)
{
this->reserved[7] = FOURCC_UVER;
this->reserved[8] = version;
}
void DDSHeader::swapBytes()
{
this->fourcc = POSH_LittleU32(this->fourcc);
this->size = POSH_LittleU32(this->size);
this->flags = POSH_LittleU32(this->flags);
this->height = POSH_LittleU32(this->height);
this->width = POSH_LittleU32(this->width);
this->pitch = POSH_LittleU32(this->pitch);
this->depth = POSH_LittleU32(this->depth);
this->mipmapcount = POSH_LittleU32(this->mipmapcount);
for(int i = 0; i < 11; i++) {
this->reserved[i] = POSH_LittleU32(this->reserved[i]);
}
this->pf.size = POSH_LittleU32(this->pf.size);
this->pf.flags = POSH_LittleU32(this->pf.flags);
this->pf.fourcc = POSH_LittleU32(this->pf.fourcc);
this->pf.bitcount = POSH_LittleU32(this->pf.bitcount);
this->pf.rmask = POSH_LittleU32(this->pf.rmask);
this->pf.gmask = POSH_LittleU32(this->pf.gmask);
this->pf.bmask = POSH_LittleU32(this->pf.bmask);
this->pf.amask = POSH_LittleU32(this->pf.amask);
this->caps.caps1 = POSH_LittleU32(this->caps.caps1);
this->caps.caps2 = POSH_LittleU32(this->caps.caps2);
this->caps.caps3 = POSH_LittleU32(this->caps.caps3);
this->caps.caps4 = POSH_LittleU32(this->caps.caps4);
this->notused = POSH_LittleU32(this->notused);
this->header10.dxgiFormat = POSH_LittleU32(this->header10.dxgiFormat);
this->header10.resourceDimension = POSH_LittleU32(this->header10.resourceDimension);
this->header10.miscFlag = POSH_LittleU32(this->header10.miscFlag);
this->header10.arraySize = POSH_LittleU32(this->header10.arraySize);
this->header10.reserved = POSH_LittleU32(this->header10.reserved);
}
bool DDSHeader::hasDX10Header() const
{
//if (pf.flags & DDPF_FOURCC) {
return this->pf.fourcc == FOURCC_DX10;
//}
//return false;
}
uint DDSHeader::signature() const
{
return this->reserved[9];
}
uint DDSHeader::toolVersion() const
{
return this->reserved[10];
}
uint DDSHeader::userVersion() const
{
if (this->reserved[7] == FOURCC_UVER) {
return this->reserved[8];
}
return 0;
}
bool DDSHeader::isNormalMap() const
{
return (pf.flags & DDPF_NORMAL) != 0;
}
bool DDSHeader::isSrgb() const
{
return (pf.flags & DDPF_SRGB) != 0;
}
bool DDSHeader::hasAlpha() const
{
return (pf.flags & DDPF_ALPHAPIXELS) != 0;
}
uint DDSHeader::d3d9Format() const
{
if (pf.flags & DDPF_FOURCC) {
return pf.fourcc;
}
else {
return findD3D9Format(pf.bitcount, pf.rmask, pf.gmask, pf.bmask, pf.amask);
}
}
uint DDSHeader::pixelSize() const
{
if (hasDX10Header()) {
return ::pixelSize((DXGI_FORMAT)header10.dxgiFormat);
}
else {
if (flags & DDPF_FOURCC) {
return ::pixelSize((D3DFORMAT)pf.fourcc);
}
else {
nvDebugCheck((pf.flags & DDPF_RGB) || (pf.flags & DDPF_LUMINANCE));
return pf.bitcount;
}
}
}
uint DDSHeader::blockSize() const
{
switch(pf.fourcc)
{
case FOURCC_DXT1:
case FOURCC_ATI1:
return 8;
case FOURCC_DXT2:
case FOURCC_DXT3:
case FOURCC_DXT4:
case FOURCC_DXT5:
case FOURCC_RXGB:
case FOURCC_ATI2:
return 16;
case FOURCC_DX10:
switch(header10.dxgiFormat)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC4_SNORM:
return 8;
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return 16;
};
};
// Not a block image.
return 0;
}
bool DDSHeader::isBlockFormat() const
{
return blockSize() != 0;
}
DirectDrawSurface::DirectDrawSurface() : stream(NULL)
{
}
DirectDrawSurface::DirectDrawSurface(const char * name) : stream(NULL)
{
load(name);
}
DirectDrawSurface::DirectDrawSurface(Stream * s) : stream(NULL)
{
load(s);
}
DirectDrawSurface::~DirectDrawSurface()
{
delete stream;
}
bool DirectDrawSurface::load(const char * filename)
{
return load(new StdInputStream(filename));
}
bool DirectDrawSurface::load(Stream * stream)
{
delete this->stream;
this->stream = stream;
if (!stream->isError())
{
(*stream) << header;
return true;
}
return false;
}
bool DirectDrawSurface::isValid() const
{
if (stream == NULL || stream->isError())
{
return false;
}
if (header.fourcc != FOURCC_DDS || header.size != 124)
{
return false;
}
const uint required = (DDSD_WIDTH|DDSD_HEIGHT/*|DDSD_CAPS|DDSD_PIXELFORMAT*/);
if( (header.flags & required) != required ) {
return false;
}
if (header.pf.size != 32) {
return false;
}
if( !(header.caps.caps1 & DDSCAPS_TEXTURE) ) {
return false;
}
return true;
}
bool DirectDrawSurface::isSupported() const
{
nvDebugCheck(isValid());
if (header.hasDX10Header())
{
if (header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM ||
header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM ||
header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM ||
header.header10.dxgiFormat == DXGI_FORMAT_BC4_UNORM ||
header.header10.dxgiFormat == DXGI_FORMAT_BC5_UNORM)
{
return true;
}
return false;
}
else
{
if (header.pf.flags & DDPF_FOURCC)
{
if (header.pf.fourcc != FOURCC_DXT1 &&
header.pf.fourcc != FOURCC_DXT2 &&
header.pf.fourcc != FOURCC_DXT3 &&
header.pf.fourcc != FOURCC_DXT4 &&
header.pf.fourcc != FOURCC_DXT5 &&
header.pf.fourcc != FOURCC_RXGB &&
header.pf.fourcc != FOURCC_ATI1 &&
header.pf.fourcc != FOURCC_ATI2)
{
// Unknown fourcc code.
return false;
}
}
else if ((header.pf.flags & DDPF_RGB) || (header.pf.flags & DDPF_LUMINANCE))
{
// All RGB and luminance formats are supported now.
}
else
{
return false;
}
if (isTextureCube()) {
if (header.width != header.height) return false;
if ((header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES)
{
// Cubemaps must contain all faces.
return false;
}
}
}
return true;
}
bool DirectDrawSurface::hasAlpha() const
{
if (header.hasDX10Header())
{
#pragma NV_MESSAGE("TODO: Update hasAlpha to handle all DX10 formats.")
return
header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM ||
header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM ||
header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM;
}
else
{
if (header.pf.flags & DDPF_RGB)
{
return header.pf.amask != 0;
}
else if (header.pf.flags & DDPF_FOURCC)
{
if (header.pf.fourcc == FOURCC_RXGB ||
header.pf.fourcc == FOURCC_ATI1 ||
header.pf.fourcc == FOURCC_ATI2 ||
header.pf.flags & DDPF_NORMAL)
{
return false;
}
else
{
// @@ Here we could check the ALPHA_PIXELS flag, but nobody sets it. (except us?)
return true;
}
}
return false;
}
}
uint DirectDrawSurface::mipmapCount() const
{
nvDebugCheck(isValid());
if (header.flags & DDSD_MIPMAPCOUNT) return header.mipmapcount;
else return 1;
}
uint DirectDrawSurface::width() const
{
nvDebugCheck(isValid());
if (header.flags & DDSD_WIDTH) return header.width;
else return 1;
}
uint DirectDrawSurface::height() const
{
nvDebugCheck(isValid());
if (header.flags & DDSD_HEIGHT) return header.height;
else return 1;
}
uint DirectDrawSurface::depth() const
{
nvDebugCheck(isValid());
if (header.flags & DDSD_DEPTH) return header.depth;
else return 1;
}
bool DirectDrawSurface::isTexture1D() const
{
nvDebugCheck(isValid());
if (header.hasDX10Header())
{
return header.header10.resourceDimension == DDS_DIMENSION_TEXTURE1D;
}
return false;
}
bool DirectDrawSurface::isTexture2D() const
{
nvDebugCheck(isValid());
if (header.hasDX10Header())
{
return header.header10.resourceDimension == DDS_DIMENSION_TEXTURE2D;
}
else
{
return !isTexture3D() && !isTextureCube();
}
}
bool DirectDrawSurface::isTexture3D() const
{
nvDebugCheck(isValid());
if (header.hasDX10Header())
{
return header.header10.resourceDimension == DDS_DIMENSION_TEXTURE3D;
}
else
{
return (header.caps.caps2 & DDSCAPS2_VOLUME) != 0;
}
}
bool DirectDrawSurface::isTextureCube() const
{
nvDebugCheck(isValid());
return (header.caps.caps2 & DDSCAPS2_CUBEMAP) != 0;
}
void DirectDrawSurface::setNormalFlag(bool b)
{
nvDebugCheck(isValid());
header.setNormalFlag(b);
}
void DirectDrawSurface::setHasAlphaFlag(bool b)
{
nvDebugCheck(isValid());
header.setHasAlphaFlag(b);
}
void DirectDrawSurface::setUserVersion(int version)
{
nvDebugCheck(isValid());
header.setUserVersion(version);
}
void DirectDrawSurface::mipmap(Image * img, uint face, uint mipmap)
{
nvDebugCheck(isValid());
stream->seek(offset(face, mipmap));
uint w = width();
uint h = height();
uint d = depth();
// Compute width and height.
for (uint m = 0; m < mipmap; m++)
{
w = max(1U, w / 2);
h = max(1U, h / 2);
d = max(1U, d / 2);
}
img->allocate(w, h, d);
if (hasAlpha())
{
img->setFormat(Image::Format_ARGB);
}
else
{
img->setFormat(Image::Format_RGB);
}
if (header.hasDX10Header())
{
// So far only block formats supported.
readBlockImage(img);
}
else
{
if (header.pf.flags & DDPF_RGB)
{
readLinearImage(img);
}
else if (header.pf.flags & DDPF_FOURCC)
{
readBlockImage(img);
}
}
}
/*void * DirectDrawSurface::readData(uint * sizePtr)
{
uint header_size = 128; // sizeof(DDSHeader);
if (header.hasDX10Header())
{
header_size += 20; // sizeof(DDSHeader10);
}
stream->seek(header_size);
int size = stream->size() - header_size;
*sizePtr = size;
void * data = new unsigned char [size];
size = stream->serialize(data, size);
nvDebugCheck(size == *sizePtr);
return data;
}*/
/*uint DirectDrawSurface::surfaceSize(uint mipmap) const
{
uint w = header.width();
uint h = header.height();
uint d = header.depth();
for (int m = 0; m < mipmap; m++) {
w = (w + 1) / 2;
h = (h + 1) / 2;
d = (d + 1) / 2;
}
bool isBlockFormat;
uint blockOrPixelSize;
if (header.hasDX10Header()) {
blockOrPixelSize = blockSize(header10.dxgiFormat);
isBlockFormat = (blockOrPixelSize != 0);
if (isBlockFormat) {
blockOrPixelSize = pixelSize(header10.dxgiFormat);
}
}
else {
header.pf.flags
}
if (isBlockFormat) {
w = (w + 3) / 4;
h = (h + 3) / 4;
d = (d + 3) / 4; // @@ Is it necessary to align the depths?
}
uint blockOrPixelCount = w * h * d;
return blockCount = blockOrPixelSize;
}*/
bool DirectDrawSurface::readSurface(uint face, uint mipmap, void * data, uint size)
{
if (size != surfaceSize(mipmap)) return false;
stream->seek(offset(face, mipmap));
if (stream->isError()) return false;
return stream->serialize(data, size) == size;
}
void DirectDrawSurface::readLinearImage(Image * img)
{
nvDebugCheck(stream != NULL);
nvDebugCheck(img != NULL);
const uint w = img->width();
const uint h = img->height();
uint rshift, rsize;
PixelFormat::maskShiftAndSize(header.pf.rmask, &rshift, &rsize);
uint gshift, gsize;
PixelFormat::maskShiftAndSize(header.pf.gmask, &gshift, &gsize);
uint bshift, bsize;
PixelFormat::maskShiftAndSize(header.pf.bmask, &bshift, &bsize);
uint ashift, asize;
PixelFormat::maskShiftAndSize(header.pf.amask, &ashift, &asize);
uint byteCount = (header.pf.bitcount + 7) / 8;
#pragma NV_MESSAGE("TODO: Support floating point linear images and other FOURCC codes.")
// Read linear RGB images.
for (uint y = 0; y < h; y++)
{
for (uint x = 0; x < w; x++)
{
uint c = 0;
stream->serialize(&c, byteCount);
Color32 pixel(0, 0, 0, 0xFF);
pixel.r = PixelFormat::convert((c & header.pf.rmask) >> rshift, rsize, 8);
pixel.g = PixelFormat::convert((c & header.pf.gmask) >> gshift, gsize, 8);
pixel.b = PixelFormat::convert((c & header.pf.bmask) >> bshift, bsize, 8);
pixel.a = PixelFormat::convert((c & header.pf.amask) >> ashift, asize, 8);
img->pixel(x, y) = pixel;
}
}
}
void DirectDrawSurface::readBlockImage(Image * img)
{
nvDebugCheck(stream != NULL);
nvDebugCheck(img != NULL);
const uint w = img->width();
const uint h = img->height();
const uint bw = (w + 3) / 4;
const uint bh = (h + 3) / 4;
for (uint by = 0; by < bh; by++)
{
for (uint bx = 0; bx < bw; bx++)
{
ColorBlock block;
// Read color block.
readBlock(&block);
// Write color block.
for (uint y = 0; y < min(4U, h-4*by); y++)
{
for (uint x = 0; x < min(4U, w-4*bx); x++)
{
img->pixel(4*bx+x, 4*by+y) = block.color(x, y);
}
}
}
}
}
static Color32 buildNormal(uint8 x, uint8 y)
{
float nx = 2 * (x / 255.0f) - 1;
float ny = 2 * (y / 255.0f) - 1;
float nz = 0.0f;
if (1 - nx*nx - ny*ny > 0) nz = sqrtf(1 - nx*nx - ny*ny);
uint8 z = clamp(int(255.0f * (nz + 1) / 2.0f), 0, 255);
return Color32(x, y, z);
}
void DirectDrawSurface::readBlock(ColorBlock * rgba)
{
nvDebugCheck(stream != NULL);
nvDebugCheck(rgba != NULL);
uint fourcc = header.pf.fourcc;
// Map DX10 block formats to fourcc codes.
if (header.hasDX10Header())
{
if (header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM) fourcc = FOURCC_DXT1;
if (header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM) fourcc = FOURCC_DXT3;
if (header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM) fourcc = FOURCC_DXT5;
if (header.header10.dxgiFormat == DXGI_FORMAT_BC4_UNORM) fourcc = FOURCC_ATI1;
if (header.header10.dxgiFormat == DXGI_FORMAT_BC5_UNORM) fourcc = FOURCC_ATI2;
}
if (fourcc == FOURCC_DXT1)
{
BlockDXT1 block;
*stream << block;
block.decodeBlock(rgba);
}
else if (fourcc == FOURCC_DXT2 || fourcc == FOURCC_DXT3)
{
BlockDXT3 block;
*stream << block;
block.decodeBlock(rgba);
}
else if (fourcc == FOURCC_DXT4 || fourcc == FOURCC_DXT5 || fourcc == FOURCC_RXGB)
{
BlockDXT5 block;
*stream << block;
block.decodeBlock(rgba);
if (fourcc == FOURCC_RXGB)
{
// Swap R & A.
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
uint tmp = c.r;
c.r = c.a;
c.a = tmp;
}
}
}
else if (fourcc == FOURCC_ATI1)
{
BlockATI1 block;
*stream << block;
block.decodeBlock(rgba);
}
else if (fourcc == FOURCC_ATI2)
{
BlockATI2 block;
*stream << block;
block.decodeBlock(rgba);
}
// If normal flag set, convert to normal.
if (header.pf.flags & DDPF_NORMAL)
{
if (fourcc == FOURCC_ATI2)
{
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
c = buildNormal(c.r, c.g);
}
}
else if (fourcc == FOURCC_DXT5)
{
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
c = buildNormal(c.a, c.g);
}
}
}
}
static uint mipmapExtent(uint mipmap, uint x)
{
for (uint m = 0; m < mipmap; m++) {
x = max(1U, x / 2);
}
return x;
}
uint DirectDrawSurface::surfaceWidth(uint mipmap) const
{
return mipmapExtent(mipmap, width());
}
uint DirectDrawSurface::surfaceHeight(uint mipmap) const
{
return mipmapExtent(mipmap, height());
}
uint DirectDrawSurface::surfaceDepth(uint mipmap) const
{
return mipmapExtent(mipmap, depth());
}
uint DirectDrawSurface::surfaceSize(uint mipmap) const
{
uint w = surfaceWidth(mipmap);
uint h = surfaceHeight(mipmap);
uint d = surfaceDepth(mipmap);
uint blockSize = header.blockSize();
if (blockSize == 0) {
uint bitCount = header.pixelSize();
uint pitch = computeBytePitch(w, bitCount, 1); // Asuming 1 byte alignment, which is the same D3DX expects.
return pitch * h * d;
}
else {
w = (w + 3) / 4;
h = (h + 3) / 4;
d = d; // @@ How are 3D textures aligned?
return blockSize * w * h * d;
}
}
uint DirectDrawSurface::faceSize() const
{
const uint count = mipmapCount();
uint size = 0;
for (uint m = 0; m < count; m++)
{
size += surfaceSize(m);
}
return size;
}
uint DirectDrawSurface::offset(const uint face, const uint mipmap)
{
uint size = 128; // sizeof(DDSHeader);
if (header.hasDX10Header())
{
size += 20; // sizeof(DDSHeader10);
}
if (face != 0)
{
size += face * faceSize();
}
for (uint m = 0; m < mipmap; m++)
{
size += surfaceSize(m);
}
return size;
}
void DirectDrawSurface::printInfo() const
{
printf("Flags: 0x%.8X\n", header.flags);
if (header.flags & DDSD_CAPS) printf("\tDDSD_CAPS\n");
if (header.flags & DDSD_PIXELFORMAT) printf("\tDDSD_PIXELFORMAT\n");
if (header.flags & DDSD_WIDTH) printf("\tDDSD_WIDTH\n");
if (header.flags & DDSD_HEIGHT) printf("\tDDSD_HEIGHT\n");
if (header.flags & DDSD_DEPTH) printf("\tDDSD_DEPTH\n");
if (header.flags & DDSD_PITCH) printf("\tDDSD_PITCH\n");
if (header.flags & DDSD_LINEARSIZE) printf("\tDDSD_LINEARSIZE\n");
if (header.flags & DDSD_MIPMAPCOUNT) printf("\tDDSD_MIPMAPCOUNT\n");
printf("Height: %d\n", header.height);
printf("Width: %d\n", header.width);
printf("Depth: %d\n", header.depth);
if (header.flags & DDSD_PITCH) printf("Pitch: %d\n", header.pitch);
else if (header.flags & DDSD_LINEARSIZE) printf("Linear size: %d\n", header.pitch);
printf("Mipmap count: %d\n", header.mipmapcount);
printf("Pixel Format:\n");
printf("\tFlags: 0x%.8X\n", header.pf.flags);
if (header.pf.flags & DDPF_RGB) printf("\t\tDDPF_RGB\n");
if (header.pf.flags & DDPF_LUMINANCE) printf("\t\tDDPF_LUMINANCE\n");
if (header.pf.flags & DDPF_FOURCC) printf("\t\tDDPF_FOURCC\n");
if (header.pf.flags & DDPF_ALPHAPIXELS) printf("\t\tDDPF_ALPHAPIXELS\n");
if (header.pf.flags & DDPF_ALPHA) printf("\t\tDDPF_ALPHA\n");
if (header.pf.flags & DDPF_PALETTEINDEXED1) printf("\t\tDDPF_PALETTEINDEXED1\n");
if (header.pf.flags & DDPF_PALETTEINDEXED2) printf("\t\tDDPF_PALETTEINDEXED2\n");
if (header.pf.flags & DDPF_PALETTEINDEXED4) printf("\t\tDDPF_PALETTEINDEXED4\n");
if (header.pf.flags & DDPF_PALETTEINDEXED8) printf("\t\tDDPF_PALETTEINDEXED8\n");
if (header.pf.flags & DDPF_ALPHAPREMULT) printf("\t\tDDPF_ALPHAPREMULT\n");
if (header.pf.flags & DDPF_NORMAL) printf("\t\tDDPF_NORMAL\n");
if (header.pf.fourcc != 0) {
// Display fourcc code even when DDPF_FOURCC flag not set.
printf("\tFourCC: '%c%c%c%c' (0x%.8X)\n",
((header.pf.fourcc >> 0) & 0xFF),
((header.pf.fourcc >> 8) & 0xFF),
((header.pf.fourcc >> 16) & 0xFF),
((header.pf.fourcc >> 24) & 0xFF),
header.pf.fourcc);
}
if ((header.pf.flags & DDPF_FOURCC) && (header.pf.bitcount != 0))
{
printf("\tSwizzle: '%c%c%c%c' (0x%.8X)\n",
(header.pf.bitcount >> 0) & 0xFF,
(header.pf.bitcount >> 8) & 0xFF,
(header.pf.bitcount >> 16) & 0xFF,
(header.pf.bitcount >> 24) & 0xFF,
header.pf.bitcount);
}
else
{
printf("\tBit count: %d\n", header.pf.bitcount);
}
printf("\tRed mask: 0x%.8X\n", header.pf.rmask);
printf("\tGreen mask: 0x%.8X\n", header.pf.gmask);
printf("\tBlue mask: 0x%.8X\n", header.pf.bmask);
printf("\tAlpha mask: 0x%.8X\n", header.pf.amask);
printf("Caps:\n");
printf("\tCaps 1: 0x%.8X\n", header.caps.caps1);
if (header.caps.caps1 & DDSCAPS_COMPLEX) printf("\t\tDDSCAPS_COMPLEX\n");
if (header.caps.caps1 & DDSCAPS_TEXTURE) printf("\t\tDDSCAPS_TEXTURE\n");
if (header.caps.caps1 & DDSCAPS_MIPMAP) printf("\t\tDDSCAPS_MIPMAP\n");
printf("\tCaps 2: 0x%.8X\n", header.caps.caps2);
if (header.caps.caps2 & DDSCAPS2_VOLUME) printf("\t\tDDSCAPS2_VOLUME\n");
else if (header.caps.caps2 & DDSCAPS2_CUBEMAP)
{
printf("\t\tDDSCAPS2_CUBEMAP\n");
if ((header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) == DDSCAPS2_CUBEMAP_ALL_FACES) printf("\t\tDDSCAPS2_CUBEMAP_ALL_FACES\n");
else {
if (header.caps.caps2 & DDSCAPS2_CUBEMAP_POSITIVEX) printf("\t\tDDSCAPS2_CUBEMAP_POSITIVEX\n");
if (header.caps.caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) printf("\t\tDDSCAPS2_CUBEMAP_NEGATIVEX\n");
if (header.caps.caps2 & DDSCAPS2_CUBEMAP_POSITIVEY) printf("\t\tDDSCAPS2_CUBEMAP_POSITIVEY\n");
if (header.caps.caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) printf("\t\tDDSCAPS2_CUBEMAP_NEGATIVEY\n");
if (header.caps.caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) printf("\t\tDDSCAPS2_CUBEMAP_POSITIVEZ\n");
if (header.caps.caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) printf("\t\tDDSCAPS2_CUBEMAP_NEGATIVEZ\n");
}
}
printf("\tCaps 3: 0x%.8X\n", header.caps.caps3);
printf("\tCaps 4: 0x%.8X\n", header.caps.caps4);
if (header.hasDX10Header())
{
printf("DX10 Header:\n");
printf("\tDXGI Format: %u (%s)\n", header.header10.dxgiFormat, getDxgiFormatString((DXGI_FORMAT)header.header10.dxgiFormat));
printf("\tResource dimension: %u (%s)\n", header.header10.resourceDimension, getD3d10ResourceDimensionString((DDS_DIMENSION)header.header10.resourceDimension));
printf("\tMisc flag: %u\n", header.header10.miscFlag);
printf("\tArray size: %u\n", header.header10.arraySize);
}
if (header.reserved[9] == FOURCC_NVTT)
{
int major = (header.reserved[10] >> 16) & 0xFF;
int minor = (header.reserved[10] >> 8) & 0xFF;
int revision= header.reserved[10] & 0xFF;
printf("Version:\n");
printf("\tNVIDIA Texture Tools %d.%d.%d\n", major, minor, revision);
}
if (header.reserved[7] == FOURCC_UVER)
{
printf("User Version: %d\n", header.reserved[8]);
}
}
| 28.386009 | 168 | 0.591449 | akumetsuv |
cb3a5839c72970f0ae673fc5132628081defae05 | 3,016 | cpp | C++ | Practice/2018/2018.6.5/ZOJ2676.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.6.5/ZOJ2676.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.6.5/ZOJ2676.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define ld long double
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define NAME "network"
const int maxN=101;
const int maxM=410*2;
const ld eps=1e-6;
const int inf=2147483647;
class EDGE
{
public:
int u,v,w;
};
class Edge
{
public:
int v;
ld flow;
};
int n,m;
EDGE EE[maxM];
int S,T;
int edgecnt=0,Head[maxN],Next[maxM];
Edge E[maxM];
int Q[maxN],Depth[maxN],cur[maxN],Id[maxM];
bool vis[maxN];
ld Calc(ld K);
void Add_Edge(int u,int v,ld flow,int id);
bool Bfs();
ld dfs(int u,ld flow);
void dfs(int u);
int main()
{
freopen(NAME".in","r",stdin);freopen(NAME".out","w",stdout);
bool first=0;
while (scanf("%d%d",&n,&m)!=EOF)
{
ld L=inf,R=0,Ans=0;
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&EE[i].u,&EE[i].v,&EE[i].w);
//R+=EE[i].w;
L=min(L,(ld)EE[i].w);R=max(R,(ld)EE[i].w);
}
L-=eps;R+=eps;
//cout<<Calc(2.0)<<endl;
//cout<<"("<<L<<","<<R<<")"<<endl;
do
{
//cout<<"("<<L<<","<<R<<")"<<endl;
ld mid=(L+R)/2.0;
if (Calc(mid)>=-eps) Ans=mid,L=mid+eps;
else R=mid-eps;
}
while(L+eps<=R);
Calc(Ans);
//cout<<"Ans:"<<Ans<<endl;
mem(vis,0);
dfs(S);
int cnt=0;
for (int i=1;i<=m;i++)
if (EE[i].w<=Ans) cnt++;
else if (vis[EE[i].u]!=vis[EE[i].v]) cnt++;
if (first) printf("\n");
first=1;
printf("%d\n",cnt);
bool ot=0;
for (int i=1;i<=m;i++)
if (EE[i].w<=Ans)
{
if (ot) printf(" ");
ot=1;
printf("%d",i);
}
else if (vis[EE[i].u]!=vis[EE[i].v])
{
if (ot) printf(" ");
ot=1;
printf("%d",i);
}
printf("\n");
}
return 0;
}
ld Calc(ld K)
{
//cout<<"Check:"<<K<<endl;
edgecnt=-1;mem(Head,-1);
ld Ret=0;
S=1;T=n;
for (int i=1;i<=m;i++)
{
if (EE[i].w>K) Add_Edge(EE[i].u,EE[i].v,EE[i].w-K,i);
else Ret+=EE[i].w-K;
}
while (Bfs())
{
for (int i=1;i<=n;i++) cur[i]=Head[i];
while (ld di=dfs(S,inf)) Ret+=di;
}
//cout<<"Check:"<<K<<" "<<Ret<<endl;
return Ret;
}
void Add_Edge(int u,int v,ld flow,int id)
{
Id[id]=edgecnt+1;
edgecnt++;Next[edgecnt]=Head[u];Head[u]=edgecnt;E[edgecnt]=((Edge){v,flow});
edgecnt++;Next[edgecnt]=Head[v];Head[v]=edgecnt;E[edgecnt]=((Edge){u,flow});
return;
}
bool Bfs()
{
int h=1,t=0;mem(Depth,-1);
Q[1]=S;Depth[S]=1;
do
{
int u=Q[++t];
for (int i=Head[u];i!=-1;i=Next[i])
if ((E[i].flow>eps)&&(Depth[E[i].v]==-1))
Depth[Q[++h]=E[i].v]=Depth[u]+1;
}
while (t!=h);
return Depth[T]!=-1;
}
ld dfs(int u,ld flow)
{
if (u==T) return flow;
for (int &i=cur[u];i!=-1;i=Next[i])
if ((E[i].flow>eps)&&(Depth[E[i].v]==Depth[u]+1))
{
ld di=dfs(E[i].v,min(flow,E[i].flow));
if (di)
{
E[i].flow-=di;
E[i^1].flow+=di;
return di;
}
}
return 0.0;
}
void dfs(int u)
{
vis[u]=1;
for (int i=Head[u];i!=-1;i=Next[i])
if ((E[i].flow>eps)&&(vis[E[i].v]==0))
dfs(E[i].v);
return;
}
/*
6 8
1 2 3
1 3 3
2 4 2
2 5 2
3 4 2
3 5 2
5 6 3
4 6 3
4 5
1 2 2
1 3 2
2 3 1
2 4 2
3 4 2
*/
| 16.128342 | 77 | 0.532162 | SYCstudio |
cb3a5b11985ed7ef1edc060d07c0094c318463f4 | 1,969 | hpp | C++ | src/base/parameter/ParameterDatabase.hpp | ddj116/gmat | 39673be967d856f14616462fb6473b27b21b149f | [
"NASA-1.3"
] | 1 | 2020-05-16T16:58:21.000Z | 2020-05-16T16:58:21.000Z | src/base/parameter/ParameterDatabase.hpp | ddj116/gmat | 39673be967d856f14616462fb6473b27b21b149f | [
"NASA-1.3"
] | null | null | null | src/base/parameter/ParameterDatabase.hpp | ddj116/gmat | 39673be967d856f14616462fb6473b27b21b149f | [
"NASA-1.3"
] | null | null | null | //$Id: ParameterDatabase.hpp 9513 2011-04-30 21:23:06Z djcinsb $
//------------------------------------------------------------------------------
// ParameterDatabase
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002-2011 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Linda Jun
// Created: 2003/09/18
//
/**
* Declares parameter database class.
*/
//------------------------------------------------------------------------------
#ifndef ParameterDatabase_hpp
#define ParameterDatabase_hpp
#include "gmatdefs.hpp"
#include "paramdefs.hpp"
#include "Parameter.hpp"
class GMAT_API ParameterDatabase
{
public:
ParameterDatabase();
ParameterDatabase(const ParameterDatabase ©);
ParameterDatabase& operator=(const ParameterDatabase &right);
virtual ~ParameterDatabase();
Integer GetNumParameters() const;
const StringArray& GetNamesOfParameters();
ParameterPtrArray GetParameters() const;
bool HasParameter(const std::string &name) const;
bool RenameParameter(const std::string &oldName, const std::string &newName);
Integer GetParameterCount(const std::string &name) const;
Parameter* GetParameter(const std::string &name) const;
std::string GetFirstParameterName() const;
bool SetParameter(const std::string &name, Parameter *param);
void Add(const std::string &name, Parameter *param = NULL);
void Add(Parameter *param);
void Remove(const std::string &name);
void Remove(const Parameter *param);
protected:
private:
StringParamPtrMap *mStringParamPtrMap;
StringArray mParamNames;
Integer mNumParams;
};
#endif // ParameterDatabase_hpp
| 30.292308 | 80 | 0.638903 | ddj116 |
cb3c810d5ab741626c9778b8d940740865c00cc3 | 183 | cpp | C++ | Runic/Src/Runic/Renderer/RenderCommand.cpp | Swarmley/Runic-Engine | 80a471728ae10e77e5370414ec45341a75df2469 | [
"Apache-2.0"
] | null | null | null | Runic/Src/Runic/Renderer/RenderCommand.cpp | Swarmley/Runic-Engine | 80a471728ae10e77e5370414ec45341a75df2469 | [
"Apache-2.0"
] | null | null | null | Runic/Src/Runic/Renderer/RenderCommand.cpp | Swarmley/Runic-Engine | 80a471728ae10e77e5370414ec45341a75df2469 | [
"Apache-2.0"
] | null | null | null | #include "runicpch.h"
#include "RenderCommand.h"
#include "Platform/OpenGL/OpenGLRenderAPI.h"
namespace Runic {
Scope<RenderAPI> RenderCommand::s_RenderAPI = RenderAPI::Create();
} | 26.142857 | 68 | 0.770492 | Swarmley |
cb44bb2dbe6aa4db4986df699b9645d7bf9212f6 | 2,342 | cpp | C++ | lib/Target/LLVMIR/Dialect/RVV/RVVToLLVMIRTranslation.cpp | taiqzheng/buddy-mlir | dde20faa02bc0c8a7195747b1c13f564732bbe7a | [
"Apache-2.0"
] | null | null | null | lib/Target/LLVMIR/Dialect/RVV/RVVToLLVMIRTranslation.cpp | taiqzheng/buddy-mlir | dde20faa02bc0c8a7195747b1c13f564732bbe7a | [
"Apache-2.0"
] | null | null | null | lib/Target/LLVMIR/Dialect/RVV/RVVToLLVMIRTranslation.cpp | taiqzheng/buddy-mlir | dde20faa02bc0c8a7195747b1c13f564732bbe7a | [
"Apache-2.0"
] | null | null | null | //======- RVVToLLVMIRTranslation.cpp - Translate RVV to LLVM IR ----------====//
//
// 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.
//
//===----------------------------------------------------------------------===//
//
// This file implements a translation between the RVV dialect and LLVM IR.
//
//===----------------------------------------------------------------------===//
#include "mlir/IR/Operation.h"
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicsRISCV.h"
#include "RVV/RVVDialect.h"
#include "Target/LLVMIR/Dialect/RVV/RVVToLLVMIRTranslation.h"
using namespace mlir;
using namespace mlir::LLVM;
using namespace buddy;
namespace {
/// Implementation of the dialect interface that converts operations belonging
/// to the RVV dialect to LLVM IR.
class RVVDialectLLVMIRTranslationInterface
: public LLVMTranslationDialectInterface {
public:
using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
/// Translates the given operation to LLVM IR using the provided IR builder
/// and saving the state in `moduleTranslation`.
LogicalResult
convertOperation(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) const final {
Operation &opInst = *op;
#include "RVV/RVVConversions.inc"
return failure();
}
};
} // end namespace
void buddy::registerRVVDialectTranslation(DialectRegistry ®istry) {
registry.insert<rvv::RVVDialect>();
registry.addExtension(+[](MLIRContext *ctx, rvv::RVVDialect *dialect) {
dialect->addInterfaces<RVVDialectLLVMIRTranslationInterface>();
});
}
void buddy::registerRVVDialectTranslation(MLIRContext &context) {
DialectRegistry registry;
registerRVVDialectTranslation(registry);
context.appendDialectRegistry(registry);
}
| 34.955224 | 80 | 0.701964 | taiqzheng |
cb45a96b5193176846511b0dfe6a29417d98379c | 10,279 | hpp | C++ | src/uml/src_gen/uml/InformationFlow.hpp | MDE4CPP/MDE4CPP | 9db9352dd3b1ae26a5f640e614ed3925499b93f1 | [
"MIT"
] | 12 | 2017-02-17T10:33:51.000Z | 2022-03-01T02:48:10.000Z | src/uml/src_gen/uml/InformationFlow.hpp | ndongmo/MDE4CPP | 9db9352dd3b1ae26a5f640e614ed3925499b93f1 | [
"MIT"
] | 28 | 2017-10-17T20:23:52.000Z | 2021-03-04T16:07:13.000Z | src/uml/src_gen/uml/InformationFlow.hpp | ndongmo/MDE4CPP | 9db9352dd3b1ae26a5f640e614ed3925499b93f1 | [
"MIT"
] | 22 | 2017-03-24T19:03:58.000Z | 2022-03-31T12:10:07.000Z | //********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************
#ifndef UML_INFORMATIONFLOW_HPP
#define UML_INFORMATIONFLOW_HPP
#include <map>
#include <list>
#include <memory>
#include <string>
// forward declarations
template<class T> class Bag;
template<class T, class ... U> class Subset;
class AnyObject;
typedef std::shared_ptr<AnyObject> Any;
//*********************************
// generated Includes
#include <map>
namespace persistence
{
namespace interfaces
{
class XLoadHandler; // used for Persistence
class XSaveHandler; // used for Persistence
}
}
namespace uml
{
class umlFactory;
}
//Forward Declaration for used types
namespace uml
{
class ActivityEdge;
}
namespace uml
{
class Classifier;
}
namespace uml
{
class Comment;
}
namespace uml
{
class Connector;
}
namespace uml
{
class Dependency;
}
namespace uml
{
class DirectedRelationship;
}
namespace uml
{
class Element;
}
namespace uml
{
class Message;
}
namespace uml
{
class NamedElement;
}
namespace uml
{
class Namespace;
}
namespace uml
{
class Package;
}
namespace uml
{
class PackageableElement;
}
namespace uml
{
class Relationship;
}
namespace uml
{
class StringExpression;
}
namespace uml
{
class TemplateParameter;
}
// base class includes
#include "uml/DirectedRelationship.hpp"
#include "uml/PackageableElement.hpp"
// enum includes
#include "uml/VisibilityKind.hpp"
//*********************************
namespace uml
{
/*!
InformationFlows describe circulation of information through a system in a general manner. They do not specify the nature of the information, mechanisms by which it is conveyed, sequences of exchange or any control conditions. During more detailed modeling, representation and realization links may be added to specify which model elements implement an InformationFlow and to show how information is conveyed. InformationFlows require some kind of “information channel” for unidirectional transmission of information items from sources to targets. They specify the information channel’s realizations, if any, and identify the information that flows along them. Information moving along the information channel may be represented by abstract InformationItems and by concrete Classifiers.
<p>From package UML::InformationFlows.</p>
*/
class InformationFlow:virtual public DirectedRelationship,virtual public PackageableElement
{
public:
InformationFlow(const InformationFlow &) {}
InformationFlow& operator=(InformationFlow const&) = delete;
protected:
InformationFlow(){}
public:
virtual std::shared_ptr<ecore::EObject> copy() const = 0;
//destructor
virtual ~InformationFlow() {}
//*********************************
// Operations
//*********************************
/*!
An information flow can only convey classifiers that are allowed to represent an information item.
self.conveyed->forAll(oclIsKindOf(Class) or oclIsKindOf(Interface)
or oclIsKindOf(InformationItem) or oclIsKindOf(Signal) or oclIsKindOf(Component))
*/
virtual bool convey_classifiers(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The sources and targets of the information flow must conform to the sources and targets or conversely the targets and sources of the realization relationships.
*/
virtual bool must_conform(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The sources and targets of the information flow can only be one of the following kind: Actor, Node, UseCase, Artifact, Class, Component, Port, Property, Interface, Package, ActivityNode, ActivityPartition,
Behavior and InstanceSpecification except when its classifier is a relationship (i.e. it represents a link).
(self.informationSource->forAll( sis |
oclIsKindOf(Actor) or oclIsKindOf(Node) or oclIsKindOf(UseCase) or oclIsKindOf(Artifact) or
oclIsKindOf(Class) or oclIsKindOf(Component) or oclIsKindOf(Port) or oclIsKindOf(Property) or
oclIsKindOf(Interface) or oclIsKindOf(Package) or oclIsKindOf(ActivityNode) or oclIsKindOf(ActivityPartition) or
(oclIsKindOf(InstanceSpecification) and not sis.oclAsType(InstanceSpecification).classifier->exists(oclIsKindOf(Relationship)))))
and
(self.informationTarget->forAll( sit |
oclIsKindOf(Actor) or oclIsKindOf(Node) or oclIsKindOf(UseCase) or oclIsKindOf(Artifact) or
oclIsKindOf(Class) or oclIsKindOf(Component) or oclIsKindOf(Port) or oclIsKindOf(Property) or
oclIsKindOf(Interface) or oclIsKindOf(Package) or oclIsKindOf(ActivityNode) or oclIsKindOf(ActivityPartition) or
(oclIsKindOf(InstanceSpecification) and not sit.oclAsType(InstanceSpecification).classifier->exists(oclIsKindOf(Relationship)))))
*/
virtual bool sources_and_targets_kind(Any diagnostics,std::map < Any, Any > context) = 0;
//*********************************
// Attributes Getter Setter
//*********************************
//*********************************
// Reference
//*********************************
/*!
Specifies the information items that may circulate on this information flow.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Bag<uml::Classifier>> getConveyed() const = 0;
/*!
Defines from which source the conveyed InformationItems are initiated.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Subset<uml::NamedElement, uml::Element>> getInformationSource() const = 0;
/*!
Defines to which target the conveyed InformationItems are directed.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Subset<uml::NamedElement, uml::Element>> getInformationTarget() const = 0;
/*!
Determines which Relationship will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Bag<uml::Relationship>> getRealization() const = 0;
/*!
Determines which ActivityEdges will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Bag<uml::ActivityEdge>> getRealizingActivityEdge() const = 0;
/*!
Determines which Connectors will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Bag<uml::Connector>> getRealizingConnector() const = 0;
/*!
Determines which Messages will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
virtual std::shared_ptr<Bag<uml::Message>> getRealizingMessage() const = 0;
protected:
//*********************************
// Attribute Members
//*********************************
//*********************************
// Reference Members
//*********************************
/*!
Specifies the information items that may circulate on this information flow.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Bag<uml::Classifier>> m_conveyed;/*!
Defines from which source the conveyed InformationItems are initiated.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Subset<uml::NamedElement, uml::Element>> m_informationSource;/*!
Defines to which target the conveyed InformationItems are directed.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Subset<uml::NamedElement, uml::Element>> m_informationTarget;/*!
Determines which Relationship will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Bag<uml::Relationship>> m_realization;/*!
Determines which ActivityEdges will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Bag<uml::ActivityEdge>> m_realizingActivityEdge;/*!
Determines which Connectors will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Bag<uml::Connector>> m_realizingConnector;/*!
Determines which Messages will realize the specified flow.
<p>From package UML::InformationFlows.</p>
*/
mutable std::shared_ptr<Bag<uml::Message>> m_realizingMessage;
public:
//*********************************
// Union Getter
//*********************************
/*!
Specifies the Namespace that owns the NamedElement.
<p>From package UML::CommonStructure.</p>
*/
virtual std::weak_ptr<uml::Namespace > getNamespace() const = 0;/*!
The Elements owned by this Element.
<p>From package UML::CommonStructure.</p>
*/
virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;/*!
The Element that owns this Element.
<p>From package UML::CommonStructure.</p>
*/
virtual std::weak_ptr<uml::Element > getOwner() const = 0;/*!
Specifies the elements related by the Relationship.
<p>From package UML::CommonStructure.</p>
*/
virtual std::shared_ptr<Union<uml::Element>> getRelatedElement() const = 0;/*!
Specifies the source Element(s) of the DirectedRelationship.
<p>From package UML::CommonStructure.</p>
*/
virtual std::shared_ptr<SubsetUnion<uml::Element, uml::Element>> getSource() const = 0;/*!
Specifies the target Element(s) of the DirectedRelationship.
<p>From package UML::CommonStructure.</p>
*/
virtual std::shared_ptr<SubsetUnion<uml::Element, uml::Element>> getTarget() const = 0;
virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;
//*********************************
// Persistence Functions
//*********************************
virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) = 0;
virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;
};
}
#endif /* end of include guard: UML_INFORMATIONFLOW_HPP */
| 29.2849 | 790 | 0.669618 | MDE4CPP |
cb49898a12f9bf4528452f4caf95e37e5fe74f28 | 2,257 | cpp | C++ | stage0/src/library/time_task.cpp | tballmsft/lean4 | fb57b73e1f07828fa9aad91c2112bf072b3e79f2 | [
"Apache-2.0"
] | 1,538 | 2019-04-25T11:00:03.000Z | 2022-03-30T02:35:48.000Z | stage0/src/library/time_task.cpp | tballmsft/lean4 | fb57b73e1f07828fa9aad91c2112bf072b3e79f2 | [
"Apache-2.0"
] | 812 | 2019-05-20T09:15:21.000Z | 2022-03-31T16:36:04.000Z | stage0/src/library/time_task.cpp | tballmsft/lean4 | fb57b73e1f07828fa9aad91c2112bf072b3e79f2 | [
"Apache-2.0"
] | 168 | 2019-04-25T12:49:34.000Z | 2022-03-29T05:07:14.000Z | /*
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich
*/
#include <string>
#include <map>
#include "library/time_task.h"
#include "library/trace.h"
namespace lean {
static std::map<std::string, second_duration> * g_cum_times;
static mutex * g_cum_times_mutex;
LEAN_THREAD_PTR(time_task, g_current_time_task);
void report_profiling_time(std::string const & category, second_duration time) {
lock_guard<mutex> _(*g_cum_times_mutex);
(*g_cum_times)[category] += time;
}
void display_cumulative_profiling_times(std::ostream & out) {
if (g_cum_times->empty())
return;
out << "cumulative profiling times:\n";
for (auto const & p : *g_cum_times)
out << "\t" << p.first << " " << display_profiling_time{p.second} << "\n";
}
void initialize_time_task() {
g_cum_times_mutex = new mutex;
g_cum_times = new std::map<std::string, second_duration>;
}
void finalize_time_task() {
delete g_cum_times;
delete g_cum_times_mutex;
}
time_task::time_task(std::string const & category, options const & opts, name decl) :
m_category(category) {
if (get_profiler(opts)) {
m_timeit = optional<xtimeit>(get_profiling_threshold(opts), [=](second_duration duration) mutable {
tout() << m_category;
if (decl)
tout() << " of " << decl;
tout() << " took " << display_profiling_time{duration} << "\n";
});
m_parent_task = g_current_time_task;
g_current_time_task = this;
}
}
time_task::~time_task() {
if (m_timeit) {
g_current_time_task = m_parent_task;
report_profiling_time(m_category, m_timeit->get_elapsed());
if (m_parent_task && m_parent_task->m_timeit)
// report exclusive times
m_parent_task->m_timeit->exclude_duration(m_timeit->get_elapsed_inclusive());
}
}
/* profileit {α : Type} (category : String) (opts : Options) (fn : Unit → α) : α */
extern "C" LEAN_EXPORT obj_res lean_profileit(b_obj_arg category, b_obj_arg opts, obj_arg fn) {
time_task t(string_to_std(category),
TO_REF(options, opts));
return apply_1(fn, box(0));
}
}
| 31.347222 | 107 | 0.663713 | tballmsft |
cb4cd4618dfc18e1368cd84d9e1ea241f5b8a267 | 23,102 | cc | C++ | src/file_sorter.cc | wurikiji/couchstore | ca6022cd2a6ab43d5a0d2fd1b34135589f51e410 | [
"Apache-2.0"
] | 1 | 2019-01-21T03:38:34.000Z | 2019-01-21T03:38:34.000Z | src/file_sorter.cc | wurikiji/couchstore | ca6022cd2a6ab43d5a0d2fd1b34135589f51e410 | [
"Apache-2.0"
] | null | null | null | src/file_sorter.cc | wurikiji/couchstore | ca6022cd2a6ab43d5a0d2fd1b34135589f51e410 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/**
* @copyright 2013 Couchbase, Inc.
*
* @author Filipe Manana <filipe@couchbase.com>
*
* 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 <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "file_sorter.h"
#include "file_name_utils.h"
#include "quicksort.h"
#define NSORT_RECORDS_INIT 500000
#define NSORT_RECORD_INCR 100000
#define NSORT_THREADS 2
typedef struct {
char *name;
unsigned level;
} tmp_file_t;
typedef struct {
const char *tmp_dir;
const char *source_file;
char *tmp_file_prefix;
unsigned num_tmp_files;
unsigned max_buffer_size;
file_merger_read_record_t read_record;
file_merger_write_record_t write_record;
file_merger_feed_record_t feed_record;
file_merger_compare_records_t compare_records;
file_merger_record_free_t free_record;
void *user_ctx;
FILE *f;
tmp_file_t *tmp_files;
unsigned active_tmp_files;
int skip_writeback;
} file_sort_ctx_t;
// For parallel sorter
typedef struct {
void **records;
tmp_file_t *tmp_file;
size_t n;
} sort_job_t;
typedef struct {
size_t nworkers;
size_t free_workers;
cb_cond_t cond;
cb_mutex_t mutex;
int finished;
file_sorter_error_t error;
sort_job_t *job;
file_sort_ctx_t *ctx;
cb_thread_t *threads;
} parallel_sorter_t;
static file_sorter_error_t do_sort_file(file_sort_ctx_t *ctx);
static void sort_records(void **records, size_t n,
file_sort_ctx_t *ctx);
static tmp_file_t *create_tmp_file(file_sort_ctx_t *ctx);
static file_sorter_error_t write_record_list(void **records,
size_t n,
tmp_file_t *tmp_file,
file_sort_ctx_t *ctx);
static void pick_merge_files(file_sort_ctx_t *ctx,
unsigned *start,
unsigned *end,
unsigned *next_level);
static file_sorter_error_t merge_tmp_files(file_sort_ctx_t *ctx,
unsigned start,
unsigned end,
unsigned next_level);
static file_sorter_error_t iterate_records_file(file_sort_ctx_t *ctx,
const char *file);
static sort_job_t *create_sort_job(void **recs, size_t n, tmp_file_t *t);
static void free_sort_job(sort_job_t *job, parallel_sorter_t *sorter);
static parallel_sorter_t *create_parallel_sorter(size_t workers,
file_sort_ctx_t *ctx);
static void free_parallel_sorter(parallel_sorter_t *s);
static void sort_worker(void *args);
static file_sorter_error_t parallel_sorter_add_job(parallel_sorter_t *s,
void **records,
size_t n);
static file_sorter_error_t parallel_sorter_wait(parallel_sorter_t *s, size_t n);
static file_sorter_error_t parallel_sorter_finish(parallel_sorter_t *s);
file_sorter_error_t sort_file(const char *source_file,
const char *tmp_dir,
unsigned num_tmp_files,
unsigned max_buffer_size,
file_merger_read_record_t read_record,
file_merger_write_record_t write_record,
file_merger_feed_record_t feed_record,
file_merger_compare_records_t compare_records,
file_merger_record_free_t free_record,
int skip_writeback,
void *user_ctx)
{
file_sort_ctx_t ctx;
unsigned i;
file_sorter_error_t ret;
if (num_tmp_files <= 1) {
return FILE_SORTER_ERROR_BAD_ARG;
}
ctx.tmp_file_prefix = file_basename(source_file);
if (ctx.tmp_file_prefix == NULL) {
return FILE_SORTER_ERROR_TMP_FILE_BASENAME;
}
ctx.tmp_dir = tmp_dir;
ctx.source_file = source_file;
ctx.num_tmp_files = num_tmp_files;
ctx.max_buffer_size = max_buffer_size;
ctx.read_record = read_record;
ctx.write_record = write_record;
ctx.feed_record = feed_record;
ctx.compare_records = compare_records;
ctx.free_record = free_record;
ctx.user_ctx = user_ctx;
ctx.active_tmp_files = 0;
ctx.skip_writeback = skip_writeback;
if (skip_writeback && !feed_record) {
return FILE_SORTER_ERROR_MISSING_CALLBACK;
}
ctx.f = fopen(source_file, "rb");
if (ctx.f == NULL) {
free(ctx.tmp_file_prefix);
return FILE_SORTER_ERROR_OPEN_FILE;
}
ctx.tmp_files = (tmp_file_t *) malloc(sizeof(tmp_file_t) * num_tmp_files);
if (ctx.tmp_files == NULL) {
fclose(ctx.f);
free(ctx.tmp_file_prefix);
return FILE_SORTER_ERROR_ALLOC;
}
for (i = 0; i < num_tmp_files; ++i) {
ctx.tmp_files[i].name = NULL;
ctx.tmp_files[i].level = 0;
}
ret = do_sort_file(&ctx);
if (ctx.f != NULL) {
fclose(ctx.f);
}
for (i = 0; i < ctx.active_tmp_files; ++i) {
if (ctx.tmp_files[i].name != NULL) {
remove(ctx.tmp_files[i].name);
free(ctx.tmp_files[i].name);
}
}
free(ctx.tmp_files);
free(ctx.tmp_file_prefix);
return ret;
}
static sort_job_t *create_sort_job(void **recs, size_t n, tmp_file_t *t)
{
sort_job_t *job = (sort_job_t *) calloc(1, sizeof(sort_job_t));
if (job) {
job->records = recs;
job->n = n;
job->tmp_file = t;
}
return job;
}
static void free_sort_job(sort_job_t *job, parallel_sorter_t *sorter)
{
size_t i;
if (job) {
for (i = 0; i < job->n; i++) {
(*sorter->ctx->free_record)(job->records[i], sorter->ctx->user_ctx);
}
free(job->records);
free(job);
}
}
static parallel_sorter_t *create_parallel_sorter(size_t workers,
file_sort_ctx_t *ctx)
{
size_t i, j;
parallel_sorter_t *s = (parallel_sorter_t *) calloc(1, sizeof(parallel_sorter_t));
if (!s) {
return NULL;
}
s->nworkers = workers;
s->free_workers = workers;
cb_mutex_initialize(&s->mutex);
cb_cond_initialize(&s->cond);
s->finished = 0;
s->error = FILE_SORTER_SUCCESS;
s->job = NULL;
s->ctx = ctx;
s->threads = (cb_thread_t *) calloc(workers, sizeof(cb_thread_t));
if (!s->threads) {
goto failure;
}
for (i = 0; i < workers; i++) {
if (cb_create_thread(&s->threads[i], &sort_worker, (void *) s, 0) < 0) {
cb_mutex_enter(&s->mutex);
s->finished = 1;
cb_mutex_exit(&s->mutex);
cb_cond_broadcast(&s->cond);
for (j = 0; j < i; j++) {
cb_join_thread(s->threads[j]);
}
goto failure;
}
}
return s;
failure:
cb_mutex_destroy(&s->mutex);
cb_cond_destroy(&s->cond);
free(s->threads);
free(s);
return NULL;
}
static void free_parallel_sorter(parallel_sorter_t *s)
{
if (s) {
cb_mutex_destroy(&s->mutex);
cb_cond_destroy(&s->cond);
free_sort_job(s->job, s);
free(s->threads);
free(s);
}
}
static void sort_worker(void *args)
{
file_sorter_error_t ret;
sort_job_t *job;
parallel_sorter_t *s = (parallel_sorter_t *) args;
/*
* If a job is available, pick it up and notify all waiters
* If job is not available, wait on condition variable
* Once a job is complete, notify all waiters
* Loop it over until finished flag becomes true
*/
while (1) {
cb_mutex_enter(&s->mutex);
if (s->finished) {
cb_mutex_exit(&s->mutex);
return;
}
if (s->job) {
job = s->job;
s->job = NULL;
s->free_workers -= 1;
cb_mutex_exit(&s->mutex);
cb_cond_broadcast(&s->cond);
ret = write_record_list(job->records, job->n, job->tmp_file, s->ctx);
free_sort_job(job, s);
if (ret != FILE_SORTER_SUCCESS) {
cb_mutex_enter(&s->mutex);
s->finished = 1;
s->error = ret;
cb_mutex_exit(&s->mutex);
cb_cond_broadcast(&s->cond);
return;
}
cb_mutex_enter(&s->mutex);
s->free_workers += 1;
cb_mutex_exit(&s->mutex);
cb_cond_broadcast(&s->cond);
} else {
cb_cond_wait(&s->cond, &s->mutex);
cb_mutex_exit(&s->mutex);
}
}
}
// Add a job and block wait until a worker picks up the job
static file_sorter_error_t parallel_sorter_add_job(parallel_sorter_t *s,
void **records,
size_t n)
{
file_sorter_error_t ret;
sort_job_t *job;
tmp_file_t *tmp_file = create_tmp_file(s->ctx);
if (tmp_file == NULL) {
return FILE_SORTER_ERROR_MK_TMP_FILE;
}
job = create_sort_job(records, n, tmp_file);
if (!job) {
return FILE_SORTER_ERROR_ALLOC;
}
cb_mutex_enter(&s->mutex);
if (s->finished) {
ret = s->error;
cb_mutex_exit(&s->mutex);
return ret;
}
s->job = job;
cb_mutex_exit(&s->mutex);
cb_cond_signal(&s->cond);
cb_mutex_enter(&s->mutex);
while (s->job) {
cb_cond_wait(&s->cond, &s->mutex);
}
cb_mutex_exit(&s->mutex);
return FILE_SORTER_SUCCESS;
}
// Wait until n or more workers become idle after processing current jobs
static file_sorter_error_t parallel_sorter_wait(parallel_sorter_t *s, size_t n)
{
while (1) {
cb_mutex_enter(&s->mutex);
if (s->finished) {
cb_mutex_exit(&s->mutex);
return s->error;
}
if (s->free_workers >= n) {
cb_mutex_exit(&s->mutex);
return FILE_SORTER_SUCCESS;
}
cb_cond_wait(&s->cond, &s->mutex);
cb_mutex_exit(&s->mutex);
}
}
// Notify all workers that we have no more jobs and wait for them to join
static file_sorter_error_t parallel_sorter_finish(parallel_sorter_t *s)
{
file_sorter_error_t ret;
size_t i;
cb_mutex_enter(&s->mutex);
s->finished = 1;
cb_mutex_exit(&s->mutex);
cb_cond_broadcast(&s->cond);
for (i = 0; i < s->nworkers; i++) {
ret = (file_sorter_error_t) cb_join_thread(s->threads[i]);
if (ret != 0) {
return ret;
}
}
return FILE_SORTER_SUCCESS;
}
static file_sorter_error_t do_sort_file(file_sort_ctx_t *ctx)
{
unsigned buffer_size = 0;
size_t i = 0;
size_t record_count = NSORT_RECORDS_INIT;
void *record;
int record_size;
file_sorter_error_t ret;
file_merger_feed_record_t feed_record = ctx->feed_record;
parallel_sorter_t *sorter;
void **records = (void **) calloc(record_count, sizeof(void *));
if (records == NULL) {
return FILE_SORTER_ERROR_ALLOC;
}
sorter = create_parallel_sorter(NSORT_THREADS, ctx);
if (sorter == NULL) {
return FILE_SORTER_ERROR_ALLOC;
}
ctx->feed_record = NULL;
i = 0;
while (1) {
record_size = (*ctx->read_record)(ctx->f, &record, ctx->user_ctx);
if (record_size < 0) {
ret = (file_sorter_error_t) record_size;
goto failure;
} else if (record_size == 0) {
break;
}
if (records == NULL) {
records = (void **) calloc(record_count, sizeof(void *));
if (records == NULL) {
ret = FILE_SORTER_ERROR_ALLOC;
goto failure;
}
}
records[i++] = record;
if (i == record_count) {
record_count += NSORT_RECORD_INCR;
records = (void **) realloc(records, record_count * sizeof(void *));
if (records == NULL) {
ret = FILE_SORTER_ERROR_ALLOC;
goto failure;
}
}
buffer_size += (unsigned) record_size;
if (buffer_size >= ctx->max_buffer_size) {
ret = parallel_sorter_add_job(sorter, records, i);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
ret = parallel_sorter_wait(sorter, 1);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
records = NULL;
record_count = NSORT_RECORDS_INIT;
buffer_size = 0;
i = 0;
}
if (ctx->active_tmp_files >= ctx->num_tmp_files) {
unsigned start, end, next_level;
ret = parallel_sorter_wait(sorter, NSORT_THREADS);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
pick_merge_files(ctx, &start, &end, &next_level);
assert(next_level > 1);
ret = merge_tmp_files(ctx, start, end, next_level);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
}
}
fclose(ctx->f);
ctx->f = NULL;
if (ctx->active_tmp_files == 0 && buffer_size == 0) {
/* empty source file */
return FILE_SORTER_SUCCESS;
}
if (buffer_size > 0) {
ret = parallel_sorter_add_job(sorter, records, i);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
}
ret = parallel_sorter_finish(sorter);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
assert(ctx->active_tmp_files > 0);
if (!ctx->skip_writeback && remove(ctx->source_file) != 0) {
ret = FILE_SORTER_ERROR_DELETE_FILE;
goto failure;
}
// Restore feed_record callback for final merge */
ctx->feed_record = feed_record;
if (ctx->active_tmp_files == 1) {
if (ctx->feed_record) {
ret = iterate_records_file(ctx, ctx->tmp_files[0].name);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
if (ctx->skip_writeback && remove(ctx->tmp_files[0].name) != 0) {
ret = FILE_SORTER_ERROR_DELETE_FILE;
goto failure;
}
}
if (!ctx->skip_writeback &&
rename(ctx->tmp_files[0].name, ctx->source_file) != 0) {
ret = FILE_SORTER_ERROR_RENAME_FILE;
goto failure;
}
} else if (ctx->active_tmp_files > 1) {
ret = merge_tmp_files(ctx, 0, ctx->active_tmp_files, 0);
if (ret != FILE_SORTER_SUCCESS) {
goto failure;
}
}
ret = FILE_SORTER_SUCCESS;
failure:
free_parallel_sorter(sorter);
return ret;
}
static file_sorter_error_t write_record_list(void **records,
size_t n,
tmp_file_t *tmp_file,
file_sort_ctx_t *ctx)
{
size_t i;
FILE *f;
sort_records(records, n, ctx);
remove(tmp_file->name);
f = fopen(tmp_file->name, "ab");
if (f == NULL) {
return FILE_SORTER_ERROR_MK_TMP_FILE;
}
if (ftell(f) != 0) {
/* File already existed. It's not supposed to exist, and if it
* exists it means a temporary file name collision happened or
* some previous sort left temporary files that were never
* deleted. */
return FILE_SORTER_ERROR_NOT_EMPTY_TMP_FILE;
}
for (i = 0; i < n; i++) {
file_sorter_error_t err;
err = static_cast<file_sorter_error_t>((*ctx->write_record)(f, records[i], ctx->user_ctx));
(*ctx->free_record)(records[i], ctx->user_ctx);
records[i] = NULL;
if (err != FILE_SORTER_SUCCESS) {
fclose(f);
return err;
}
}
fclose(f);
return FILE_SORTER_SUCCESS;
}
static tmp_file_t *create_tmp_file(file_sort_ctx_t *ctx)
{
unsigned i = ctx->active_tmp_files;
assert(ctx->active_tmp_files < ctx->num_tmp_files);
assert(ctx->tmp_files[i].name == NULL);
assert(ctx->tmp_files[i].level == 0);
ctx->tmp_files[i].name = tmp_file_path(ctx->tmp_dir, ctx->tmp_file_prefix);
if (ctx->tmp_files[i].name == NULL) {
return NULL;
}
ctx->tmp_files[i].level = 1;
ctx->active_tmp_files += 1;
return &ctx->tmp_files[i];
}
static int qsort_cmp(const void *a, const void *b, void *ctx)
{
file_sort_ctx_t *sort_ctx = (file_sort_ctx_t *) ctx;
const void **k1 = (const void **) a, **k2 = (const void **) b;
return (*sort_ctx->compare_records)(*k1, *k2, sort_ctx->user_ctx);
}
static void sort_records(void **records, size_t n,
file_sort_ctx_t *ctx)
{
quicksort(records, n, sizeof(void *), &qsort_cmp, ctx);
}
static int tmp_file_cmp(const void *a, const void *b)
{
unsigned x = ((const tmp_file_t *) a)->level;
unsigned y = ((const tmp_file_t *) b)->level;
if (x == 0) {
return 1;
}
if (y == 0) {
return -1;
}
return x - y;
}
static void pick_merge_files(file_sort_ctx_t *ctx,
unsigned *start,
unsigned *end,
unsigned *next_level)
{
unsigned i, j, level;
qsort(ctx->tmp_files, ctx->active_tmp_files, sizeof(tmp_file_t), tmp_file_cmp);
for (i = 0; i < ctx->active_tmp_files; i = j) {
level = ctx->tmp_files[i].level;
assert(level > 0);
j = i + 1;
while (j < ctx->active_tmp_files) {
assert(ctx->tmp_files[j].level > 0);
if (ctx->tmp_files[j].level != level) {
break;
}
j += 1;
}
if ((j - i) > 1) {
*start = i;
*end = j;
*next_level = (j - i) * level;
return;
}
}
/* All files have a different level. */
assert(ctx->active_tmp_files == ctx->num_tmp_files);
assert(ctx->active_tmp_files >= 2);
*start = 0;
*end = 2;
*next_level = ctx->tmp_files[0].level + ctx->tmp_files[1].level;
}
static file_sorter_error_t merge_tmp_files(file_sort_ctx_t *ctx,
unsigned start,
unsigned end,
unsigned next_level)
{
char *dest_tmp_file;
const char **files;
unsigned nfiles, i;
file_sorter_error_t ret;
file_merger_feed_record_t feed_record = NULL;
nfiles = end - start;
files = (const char **) malloc(sizeof(char *) * nfiles);
if (files == NULL) {
return FILE_SORTER_ERROR_ALLOC;
}
for (i = start; i < end; ++i) {
files[i - start] = ctx->tmp_files[i].name;
assert(files[i - start] != NULL);
}
if (next_level == 0) {
/* Final merge iteration. */
if (ctx->skip_writeback) {
dest_tmp_file = NULL;
} else {
dest_tmp_file = (char *) ctx->source_file;
}
feed_record = ctx->feed_record;
} else {
dest_tmp_file = tmp_file_path(ctx->tmp_dir, ctx->tmp_file_prefix);
if (dest_tmp_file == NULL) {
free(files);
return FILE_SORTER_ERROR_MK_TMP_FILE;
}
}
ret = (file_sorter_error_t) merge_files(files,
nfiles,
dest_tmp_file,
ctx->read_record,
ctx->write_record,
feed_record,
ctx->compare_records,
ctx->free_record,
ctx->skip_writeback,
ctx->user_ctx);
free(files);
if (ret != FILE_SORTER_SUCCESS) {
if (dest_tmp_file != NULL && dest_tmp_file != ctx->source_file) {
remove(dest_tmp_file);
free(dest_tmp_file);
}
return ret;
}
for (i = start; i < end; ++i) {
if (remove(ctx->tmp_files[i].name) != 0) {
if (dest_tmp_file != ctx->source_file) {
free(dest_tmp_file);
}
return FILE_SORTER_ERROR_DELETE_FILE;
}
free(ctx->tmp_files[i].name);
ctx->tmp_files[i].name = NULL;
ctx->tmp_files[i].level = 0;
}
qsort(ctx->tmp_files + start, ctx->num_tmp_files - start,
sizeof(tmp_file_t), tmp_file_cmp);
ctx->active_tmp_files -= nfiles;
if (dest_tmp_file != ctx->source_file) {
i = ctx->active_tmp_files;
ctx->tmp_files[i].name = dest_tmp_file;
ctx->tmp_files[i].level = next_level;
ctx->active_tmp_files += 1;
}
return FILE_SORTER_SUCCESS;
}
static file_sorter_error_t iterate_records_file(file_sort_ctx_t *ctx,
const char *file)
{
void *record_data = NULL;
int record_len;
FILE *f = fopen(file, "rb");
int ret = FILE_SORTER_SUCCESS;
if (f == NULL) {
return FILE_SORTER_ERROR_OPEN_FILE;
}
while (1) {
record_len = (*ctx->read_record)(f, &record_data, ctx->user_ctx);
if (record_len == 0) {
record_data = NULL;
break;
} else if (record_len < 0) {
ret = record_len;
goto cleanup;
} else {
ret = (*ctx->feed_record)(record_data, ctx->user_ctx);
if (ret != FILE_SORTER_SUCCESS) {
goto cleanup;
}
(*ctx->free_record)(record_data, ctx->user_ctx);
}
}
cleanup:
(*ctx->free_record)(record_data, ctx->user_ctx);
if (f != NULL) {
fclose(f);
}
return (file_sorter_error_t) ret;
}
| 28.002424 | 99 | 0.544412 | wurikiji |
cb4ec5774633bf9c88ee3dde240a206ed97c7111 | 58,998 | cpp | C++ | FlightComputerV2/lib/SPIMemory/SPIMemory.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | FlightComputerV2/lib/SPIMemory/SPIMemory.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | FlightComputerV2/lib/SPIMemory/SPIMemory.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | /* Arduino SPIFlash Library v.2.6.0
* Copyright (C) 2017 by Prajwal Bhattaram
* Created by Prajwal Bhattaram - 19/05/2015
* Modified by @boseji <salearj@hotmail.com> - 02/03/2017
* Modified by Prajwal Bhattaram - 14/04/2017
*
* This file is part of the Arduino SPIFlash Library. This library is for
* Winbond NOR flash memory modules. In its current form it enables reading
* and writing individual data variables, structs and arrays from and to various locations;
* reading and writing pages; continuous read functions; sector, block and chip erase;
* suspending and resuming programming/erase and powering down for low power operation.
*
* This Library 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 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License v3.0
* along with the Arduino SPIFlash Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "SPIMemory.h"
// Constructor
#if defined(ARDUINO_ARCH_AVR)
SPIFlash::SPIFlash(uint8_t cs, bool overflow)
{
csPin = cs;
#ifndef __AVR_ATtiny85__
cs_port = portOutputRegister(digitalPinToPort(csPin));
#endif
cs_mask = digitalPinToBitMask(csPin);
pageOverflow = overflow;
pinMode(csPin, OUTPUT);
}
// Adding Low level HAL API to initialize the Chip select pinMode on RTL8195A - @boseji <salearj@hotmail.com> 2nd March 2017
#elif defined(BOARD_RTL8195A)
SPIFlash::SPIFlash(PinName cs, bool overflow)
{
gpio_init(&csPin, cs);
gpio_dir(&csPin, PIN_OUTPUT);
gpio_mode(&csPin, PullNone);
gpio_write(&csPin, 1);
pageOverflow = overflow;
}
#else
SPIFlash::SPIFlash(uint8_t cs, bool overflow)
{
csPin = cs;
pageOverflow = overflow;
pinMode(csPin, OUTPUT);
}
#endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Private functions used by read, write and erase operations //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Double checks all parameters before calling a read or write. Comes in two variants
//Variant A: Takes address and returns the address if true, else returns false. Throws an error if there is a problem.
bool SPIFlash::_prep(uint8_t opcode, uint32_t address, uint32_t size)
{
switch (opcode)
{
case PAGEPROG:
if (!_addressCheck(address, size))
{
return false;
}
if (!_notBusy() || !_writeEnable())
{
return false;
}
#ifndef HIGHSPEED
if (!_notPrevWritten(address, size))
{
return false;
}
#endif
return true;
break;
default:
if (!_addressCheck(address, size))
{
return false;
}
if (!_notBusy())
{
return false;
}
return true;
break;
}
}
//Variant B: Take the opcode, page number, offset and size of data block as arguments
bool SPIFlash::_prep(uint8_t opcode, uint32_t page_number, uint8_t offset, uint32_t size)
{
uint32_t address = _getAddress(page_number, offset);
return _prep(opcode, address, size);
}
bool SPIFlash::_transferAddress(void)
{
_nextByte(_currentAddress >> 16);
_nextByte(_currentAddress >> 8);
_nextByte(_currentAddress);
}
bool SPIFlash::_startSPIBus(void)
{
#ifndef SPI_HAS_TRANSACTION
noInterrupts();
#endif
#if defined(ARDUINO_ARCH_SAM)
_dueSPIInit(DUE_SPI_CLK);
#else
#if defined(ARDUINO_ARCH_AVR)
//save current SPI settings
_SPCR = SPCR;
_SPSR = SPSR;
#endif
#ifdef SPI_HAS_TRANSACTION
SPI.beginTransaction(_settings);
#else
SPI.setClockDivider(SPI_CLOCK_DIV_4)
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
#endif
#endif
SPIBusState = true;
return true;
}
//Initiates SPI operation - but data is not transferred yet. Always call _prep() before this function (especially when it involves writing or reading to/from an address)
bool SPIFlash::_beginSPI(uint8_t opcode)
{
if (!SPIBusState)
{
//Serial.println("Starting SPI Bus");
_startSPIBus();
}
CHIP_SELECT
switch (opcode)
{
case FASTREAD:
_nextByte(opcode);
_nextByte(DUMMYBYTE);
_transferAddress();
break;
case READDATA:
_nextByte(opcode);
_transferAddress();
break;
case PAGEPROG:
_nextByte(opcode);
_transferAddress();
break;
default:
_nextByte(opcode);
break;
}
return true;
}
//SPI data lines are left open until _endSPI() is called
//Reads/Writes next byte. Call 'n' times to read/write 'n' number of bytes. Should be called after _beginSPI()
uint8_t SPIFlash::_nextByte(uint8_t data)
{
#if defined(ARDUINO_ARCH_SAM)
return _dueSPITransfer(data);
#else
return xfer(data);
#endif
}
//Reads/Writes next int. Call 'n' times to read/write 'n' number of bytes. Should be called after _beginSPI()
uint16_t SPIFlash::_nextInt(uint16_t data)
{
//return xfer16(data);
return SPI.transfer16(data);
}
//Reads/Writes next data buffer. Call 'n' times to read/write 'n' number of bytes. Should be called after _beginSPI()
void SPIFlash::_nextBuf(uint8_t opcode, uint8_t *data_buffer, uint32_t size)
{
uint8_t *_dataAddr = &(*data_buffer);
switch (opcode)
{
case READDATA:
#if defined(ARDUINO_ARCH_SAM)
_dueSPIRecByte(&(*data_buffer), size);
#elif defined(ARDUINO_ARCH_AVR)
SPI.transfer(&data_buffer[0], size);
#else
for (uint16_t i = 0; i < size; i++)
{
*_dataAddr = xfer(NULLBYTE);
_dataAddr++;
}
#endif
break;
case PAGEPROG:
#if defined(ARDUINO_ARCH_SAM)
_dueSPISendByte(&(*data_buffer), size);
#elif defined(ARDUINO_ARCH_AVR)
SPI.transfer(&(*data_buffer), size);
#else
for (uint16_t i = 0; i < size; i++)
{
xfer(*_dataAddr);
_dataAddr++;
}
#endif
break;
}
}
//Stops all operations. Should be called after all the required data is read/written from repeated _nextByte() calls
void SPIFlash::_endSPI(void)
{
CHIP_DESELECT
#ifdef SPI_HAS_TRANSACTION
SPI.endTransaction();
#else
interrupts();
#endif
#if defined(ARDUINO_ARCH_AVR)
SPCR = _SPCR;
SPSR = _SPSR;
#endif
SPIBusState = false;
}
// Checks if status register 1 can be accessed - used during powerdown and power up and for debugging
uint8_t SPIFlash::_readStat1(void)
{
_beginSPI(READSTAT1);
uint8_t stat1 = _nextByte();
CHIP_DESELECT
return stat1;
}
// Checks if status register 2 can be accessed, if yes, reads and returns it
uint8_t SPIFlash::_readStat2(void)
{
_beginSPI(READSTAT2);
uint8_t stat2 = _nextByte();
stat2 = _nextByte();
CHIP_DESELECT
return stat2;
}
// Checks the erase/program suspend flag before enabling/disabling a program/erase suspend operation
bool SPIFlash::_noSuspend(void)
{
switch (_chip.manufacturerID)
{
case WINBOND_MANID:
if (_readStat2() & SUS)
{
errorcode = SYSSUSPEND;
return false;
}
return true;
break;
case MICROCHIP_MANID:
if (_readStat1() & WSE || _readStat1() & WSP)
{
errorcode = SYSSUSPEND;
return false;
}
return true;
}
}
// Polls the status register 1 until busy flag is cleared or timeout
bool SPIFlash::_notBusy(uint32_t timeout)
{
uint32_t startTime = millis();
do
{
state = _readStat1();
if ((millis() - startTime) > timeout)
{
errorcode = CHIPBUSY;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
_endSPI();
return false;
}
} while (state & BUSY);
return true;
}
//Enables writing to chip by setting the WRITEENABLE bit
bool SPIFlash::_writeEnable(uint32_t timeout)
{
uint32_t startTime = millis();
if (!(state & WRTEN))
{
do
{
_beginSPI(WRITEENABLE);
CHIP_DESELECT
state = _readStat1();
if ((millis() - startTime) > timeout)
{
errorcode = CANTENWRITE;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
_endSPI();
return false;
}
} while (!(state & WRTEN));
}
return true;
}
//Disables writing to chip by setting the Write Enable Latch (WEL) bit in the Status Register to 0
//_writeDisable() is not required under the following conditions because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, Block Erase, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
bool SPIFlash::_writeDisable(void)
{
_beginSPI(WRITEDISABLE);
CHIP_DESELECT
return true;
}
//Gets address from page number and offset. Takes two arguments:
// 1. page_number --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
uint32_t SPIFlash::_getAddress(uint16_t page_number, uint8_t offset)
{
uint32_t address = page_number;
return ((address << 8) + offset);
}
//Checks the device ID to establish storage parameters
bool SPIFlash::_getManId(uint8_t *b1, uint8_t *b2)
{
if (!_notBusy())
return false;
_beginSPI(MANID);
_nextByte();
_nextByte();
_nextByte();
*b1 = _nextByte();
*b2 = _nextByte();
CHIP_DESELECT
return true;
}
//Checks for presence of chip by requesting JEDEC ID
bool SPIFlash::_getJedecId(void)
{
if (!_notBusy())
{
return false;
}
_beginSPI(JEDECID);
_chip.manufacturerID = _nextByte(NULLBYTE); // manufacturer id
_chip.memoryTypeID = _nextByte(NULLBYTE); // memory type
_chip.capacityID = _nextByte(NULLBYTE); // capacity
CHIP_DESELECT
if (!_chip.manufacturerID || !_chip.memoryTypeID || !_chip.capacityID)
{
errorcode = NORESPONSE;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
else
{
return true;
}
}
bool SPIFlash::_getSFDP(void)
{
if (!_notBusy())
{
return false;
}
_beginSPI(READSFDP);
_currentAddress = 0x00;
_transferAddress();
_nextByte(DUMMYBYTE);
for (uint8_t i = 0; i < 4; i++)
{
_chip.sfdp += (_nextByte() << (8 * i));
}
CHIP_DESELECT
if (_chip.sfdp = 0x50444653)
{
//Serial.print("_chip.sfdp: ");
//Serial.println(_chip.sfdp, HEX);
return true;
}
else
{
return false;
}
}
//Identifies the chip
bool SPIFlash::_chipID(void)
{
//Get Manfucturer/Device ID so the library can identify the chip
_getSFDP();
if (!_getJedecId())
{
return false;
}
// If no capacity is defined in user code
if (!_chip.capacity)
{
_chip.supported = _chip.manufacturerID;
if (_chip.supported == WINBOND_MANID || _chip.supported == MICROCHIP_MANID)
{
//Identify capacity
for (uint8_t i = 0; i < sizeof(_capID); i++)
{
if (_chip.capacityID == _capID[i])
{
_chip.capacity = (_memSize[i]);
_chip.eraseTime = _eraseTime[i];
}
}
return true;
}
else
{
errorcode = UNKNOWNCAP; //Error code for unidentified capacity
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
}
else
{
// If a custom chip size is defined
_chip.eraseTime = _chip.capacity / KB8;
_chip.supported = false; // This chip is not officially supported
errorcode = UNKNOWNCHIP; //Error code for unidentified chip
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
//while(1); //Enable this if usercode is not meant to be run on unsupported chips
}
return true;
}
//Checks to see if pageOverflow is permitted and assists with determining next address to read/write.
//Sets the global address variable
bool SPIFlash::_addressCheck(uint32_t address, uint32_t size)
{
if (errorcode == UNKNOWNCAP || errorcode == NORESPONSE)
{
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
if (!_chip.eraseTime)
{
errorcode = CALLBEGIN;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
for (uint32_t i = 0; i < size; i++)
{
if (address + i >= _chip.capacity)
{
if (!pageOverflow)
{
errorcode = OUTOFBOUNDS;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false; // At end of memory - (!pageOverflow)
}
else
{
_currentAddress = 0x00;
return true; // At end of memory - (pageOverflow)
}
}
}
_currentAddress = address;
return true; // Not at end of memory if (address < _chip.capacity)
}
bool SPIFlash::_notPrevWritten(uint32_t address, uint32_t size)
{
_beginSPI(READDATA);
for (uint16_t i = 0; i < size; i++)
{
if (_nextByte() != 0xFF)
{
CHIP_DESELECT;
return false;
}
}
CHIP_DESELECT
return true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Public functions used for read, write and erase operations //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Identifies chip and establishes parameters
bool SPIFlash::begin(uint32_t _chipSize)
{
if (_chipSize)
{
_chip.capacity = _chipSize / 8;
}
BEGIN_SPI
#ifdef SPI_HAS_TRANSACTION
//Define the settings to be used by the SPI bus
_settings = SPISettings(SPI_CLK, MSBFIRST, SPI_MODE0);
#endif
if (!_chipID())
{
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
}
//Allows the setting of a custom clock speed for the SPI bus to communicate with the chip.
//Only works if the SPI library in use supports SPI Transactions
#ifdef SPI_HAS_TRANSACTION
void SPIFlash::setClock(uint32_t clockSpeed)
{
_settings = SPISettings(clockSpeed, MSBFIRST, SPI_MODE0);
}
#endif
uint8_t SPIFlash::error(bool _verbosity)
{
if (!_verbosity)
{
return errorcode;
}
else
{
_troubleshoot();
return errorcode;
}
}
//Returns capacity of chip
uint32_t SPIFlash::getCapacity(void)
{
return _chip.capacity;
}
//Returns maximum number of pages
uint32_t SPIFlash::getMaxPage(void)
{
return (_chip.capacity / PAGESIZE);
}
//Returns the library version as a string
bool SPIFlash::libver(uint8_t *b1, uint8_t *b2, uint8_t *b3)
{
*b1 = LIBVER;
*b2 = LIBSUBVER;
*b3 = BUGFIXVER;
return true;
}
//Checks for and initiates the chip by requesting the Manufacturer ID which is returned as a 16 bit int
uint16_t SPIFlash::getManID(void)
{
uint8_t b1, b2;
_getManId(&b1, &b2);
uint32_t id = b1;
id = (id << 8) | (b2 << 0);
return id;
}
//Returns JEDEC ID which is returned as a 32 bit int
uint32_t SPIFlash::getJEDECID(void)
{
uint32_t id = _chip.manufacturerID;
id = (id << 8) | (_chip.memoryTypeID << 0);
id = (id << 8) | (_chip.capacityID << 0);
return id;
}
//Gets the next available address for use. Has two variants:
// A. Takes the size of the data as an argument and returns a 32-bit address
// B. Takes a three variables, the size of the data and two other variables to return a page number value & an offset into.
// All addresses in the in the sketch must be obtained via this function or not at all.
// Variant A
uint32_t SPIFlash::getAddress(uint16_t size)
{
if (!_addressCheck(currentAddress, size))
{
errorcode = OUTOFBOUNDS;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
else
{
uint32_t address = currentAddress;
currentAddress += size;
return address;
}
}
// Variant B
bool SPIFlash::getAddress(uint16_t size, uint16_t &page_number, uint8_t &offset)
{
uint32_t address = getAddress(size);
offset = (address >> 0);
page_number = (address >> 8);
return true;
}
//Function for returning the size of the string (only to be used for the getAddress() function)
uint16_t SPIFlash::sizeofStr(String &inputStr)
{
uint16_t size;
size = (sizeof(char) * (inputStr.length() + 1));
size += sizeof(inputStr.length() + 1);
return size;
}
// Reads a byte of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint8_t SPIFlash::readByte(uint32_t address, bool fastRead)
{
uint8_t data;
if (!_prep(READDATA, address, sizeof(data)))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
data = _nextByte();
_endSPI();
return data;
}
// Variant B
uint8_t SPIFlash::readByte(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readByte(address, fastRead);
}
// Reads a char of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int8_t SPIFlash::readChar(uint32_t address, bool fastRead)
{
int8_t data;
if (!_prep(READDATA, address, sizeof(data)))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
data = _nextByte();
_endSPI();
return data;
}
// Variant B
int8_t SPIFlash::readChar(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readChar(address, fastRead);
}
// Reads an array of bytes starting from a specific location in a page.// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to capacity
// 2. data_buffer --> The array of bytes to be read from the flash memory - starting at the address indicated
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data_buffer --> The array of bytes to be read from the flash memory - starting at the offset on the page indicated
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
bool SPIFlash::readByteArray(uint32_t address, uint8_t *data_buffer, uint16_t bufferSize, bool fastRead)
{
if (!_prep(READDATA, address, bufferSize))
{
return false;
}
if (fastRead)
{
_beginSPI(FASTREAD);
}
else
{
_beginSPI(READDATA);
}
_nextBuf(READDATA, &(*data_buffer), bufferSize);
_endSPI();
return true;
}
// Variant B
bool SPIFlash::readByteArray(uint16_t page_number, uint8_t offset, uint8_t *data_buffer, uint16_t bufferSize, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readByteArray(address, data_buffer, bufferSize, fastRead);
}
// Reads an array of chars starting from a specific location in a page.// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to capacity
// 2. data_buffer --> The array of bytes to be read from the flash memory - starting at the address indicated
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data_buffer --> The array of bytes to be read from the flash memory - starting at the offset on the page indicated
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
bool SPIFlash::readCharArray(uint32_t address, char *data_buffer, uint16_t bufferSize, bool fastRead)
{
if (!_prep(READDATA, address, bufferSize))
{
return false;
}
if (fastRead)
{
_beginSPI(FASTREAD);
}
else
{
_beginSPI(READDATA);
}
_nextBuf(READDATA, (uint8_t *)&(*data_buffer), bufferSize);
_endSPI();
return true;
}
// Variant B
bool SPIFlash::readCharArray(uint16_t page_number, uint8_t offset, char *data_buffer, uint16_t bufferSize, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readCharArray(address, data_buffer, bufferSize, fastRead);
}
// Reads an unsigned int of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint16_t SPIFlash::readWord(uint32_t address, bool fastRead)
{
const uint8_t size = sizeof(uint16_t);
union
{
uint8_t b[size];
uint16_t I;
} data;
if (!_prep(READDATA, address, size))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.I;
}
// Variant B
uint16_t SPIFlash::readWord(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readWord(address, fastRead);
}
// Reads a signed int of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int16_t SPIFlash::readShort(uint32_t address, bool fastRead)
{
const uint8_t size = sizeof(int16_t);
union
{
byte b[size];
int16_t s;
} data;
if (!_prep(READDATA, address, size))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.s;
}
// Variant B
int16_t SPIFlash::readShort(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readShort(address, fastRead);
}
// Reads an unsigned long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint32_t SPIFlash::readULong(uint32_t address, bool fastRead)
{
const uint8_t size = (sizeof(uint32_t));
union
{
uint8_t b[size];
uint32_t l;
} data;
if (!_prep(READDATA, address, size))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.l;
}
// Variant B
uint32_t SPIFlash::readULong(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readULong(address, fastRead);
}
// Reads a signed long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int32_t SPIFlash::readLong(uint32_t address, bool fastRead)
{
const uint8_t size = (sizeof(int32_t));
union
{
byte b[size];
int32_t l;
} data;
if (!_prep(READDATA, address, size))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.l;
}
// Variant B
int32_t SPIFlash::readLong(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readLong(address, fastRead);
}
// Reads a signed long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
float SPIFlash::readFloat(uint32_t address, bool fastRead)
{
const uint8_t size = (sizeof(float));
union
{
byte b[size];
float f;
} data;
if (!_prep(READDATA, address, size))
{
return false;
}
switch (fastRead)
{
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.f;
}
// Variant B
float SPIFlash::readFloat(uint16_t page_number, uint8_t offset, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readFloat(address, fastRead);
}
// Reads a string from a specific location on a page.
// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to capacity
// 2. outputString --> String variable to write the output to
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. outputString --> String variable to write the output to
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// This function first reads a short from the address to figure out the size of the String object stored and
// then reads the String object data
// Variant A
bool SPIFlash::readStr(uint32_t address, String &outStr, bool fastRead)
{
uint16_t strLen;
//_delay_us(20);
strLen = readWord(address);
address += (sizeof(strLen));
char outputChar[strLen];
readCharArray(address, outputChar, strLen, fastRead);
outStr = String(outputChar);
return true;
}
// Variant B
bool SPIFlash::readStr(uint16_t page_number, uint8_t offset, String &outStr, bool fastRead)
{
uint32_t address = _getAddress(page_number, offset);
return readStr(address, outStr, fastRead);
}
// Writes a byte of data to a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One byte of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One byte of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeByte(uint32_t address, uint8_t data, bool errorCheck)
{
if (!_prep(PAGEPROG, address, sizeof(data)))
{
return false;
}
_beginSPI(PAGEPROG);
_nextByte(data);
CHIP_DESELECT
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
return _writeErrorCheck(address, data);
}
}
// Variant B
bool SPIFlash::writeByte(uint16_t page_number, uint8_t offset, uint8_t data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeByte(address, data, errorCheck);
}
// Writes a char of data to a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One char of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One char of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeChar(uint32_t address, int8_t data, bool errorCheck)
{
if (!_prep(PAGEPROG, address, sizeof(data)))
{
return false;
}
_beginSPI(PAGEPROG);
_nextByte(data);
CHIP_DESELECT
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
return _writeErrorCheck(address, data);
}
}
// Variant B
bool SPIFlash::writeChar(uint16_t page_number, uint8_t offset, int8_t data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeChar(address, data, errorCheck);
}
// Writes an array of bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> An array of bytes to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> An array of bytes to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeByteArray(uint32_t address, uint8_t *data_buffer, uint16_t bufferSize, bool errorCheck)
{
if (!_prep(PAGEPROG, address, bufferSize))
{
return false;
}
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
uint16_t length = bufferSize;
uint16_t writeBufSz;
uint16_t data_offset = 0;
while (length > 0)
{
writeBufSz = (length <= maxBytes) ? length : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(data_buffer[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
length -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
if (!_notBusy())
{
return false;
}
_currentAddress = address;
CHIP_SELECT
_nextByte(READDATA);
_transferAddress();
for (uint16_t j = 0; j < bufferSize; j++)
{
if (_nextByte(NULLBYTE) != data_buffer[j])
{
return false;
}
}
_endSPI();
return true;
}
}
// Variant B
bool SPIFlash::writeByteArray(uint16_t page_number, uint8_t offset, uint8_t *data_buffer, uint16_t bufferSize, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeByteArray(address, data_buffer, bufferSize, errorCheck);
}
// Writes an array of bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> An array of chars to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> An array of chars to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeCharArray(uint32_t address, char *data_buffer, uint16_t bufferSize, bool errorCheck)
{
uint16_t writeBufSz;
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
uint16_t data_offset = 0;
uint16_t length = bufferSize;
if (!_prep(PAGEPROG, address, bufferSize))
{
return false;
}
while (length > 0)
{
writeBufSz = (length <= maxBytes) ? length : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(data_buffer[data_offset + i]);
Serial.print(data_buffer[data_offset + i]);
Serial.print(", ");
}
Serial.println();
_currentAddress += writeBufSz;
data_offset += writeBufSz;
length -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
if (!_notBusy())
{
return false;
}
_currentAddress = address;
CHIP_SELECT
_nextByte(READDATA);
_transferAddress();
for (uint16_t j = 0; j < bufferSize; j++)
{
if (_nextByte(NULLBYTE) != data_buffer[j])
{
return false;
}
}
_endSPI();
return true;
}
}
// Variant B
bool SPIFlash::writeCharArray(uint16_t page_number, uint8_t offset, char *data_buffer, uint16_t bufferSize, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeCharArray(address, data_buffer, bufferSize, errorCheck);
}
// Writes an unsigned int as two bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One unsigned int of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One unsigned int of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeWord(uint32_t address, uint16_t data, bool errorCheck)
{
const uint8_t size = sizeof(uint16_t);
if (!_prep(PAGEPROG, address, size))
{
return false;
}
union
{
uint8_t b[size];
uint16_t w;
} var;
var.w = data;
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
if (maxBytes > size)
{
_beginSPI(PAGEPROG);
_nextBuf(PAGEPROG, &var.b[0], size);
CHIP_DESELECT
}
else
{
uint16_t writeBufSz;
uint16_t data_offset = 0;
uint16_t _sz = size;
while (_sz > 0)
{
writeBufSz = (_sz <= maxBytes) ? _sz : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(var.b[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
_sz -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeWord(uint16_t page_number, uint8_t offset, uint16_t data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeWord(address, data, errorCheck);
}
// Writes a signed int as two bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One signed int of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One signed int of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeShort(uint32_t address, int16_t data, bool errorCheck)
{
const uint8_t size = sizeof(data);
if (!_prep(PAGEPROG, address, size))
{
return false;
}
union
{
uint8_t b[size];
int16_t s;
} var;
var.s = data;
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
if (maxBytes > size)
{
_beginSPI(PAGEPROG);
_nextBuf(PAGEPROG, &var.b[0], size);
CHIP_DESELECT
}
else
{
uint16_t writeBufSz;
uint16_t data_offset = 0;
uint16_t _sz = size;
while (_sz > 0)
{
writeBufSz = (_sz <= maxBytes) ? _sz : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(var.b[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
_sz -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeShort(uint16_t page_number, uint8_t offset, int16_t data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeShort(address, data, errorCheck);
}
// Writes an unsigned long as four bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One unsigned long of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One unsigned long of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeULong(uint32_t address, uint32_t data, bool errorCheck)
{
const uint8_t size = (sizeof(data));
if (!_prep(PAGEPROG, address, size))
{
return false;
}
union
{
uint8_t b[size];
uint32_t l;
} var;
var.l = data;
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
if (maxBytes > size)
{
_beginSPI(PAGEPROG);
_nextBuf(PAGEPROG, &var.b[0], size);
CHIP_DESELECT
}
else
{
uint16_t writeBufSz;
uint16_t data_offset = 0;
uint16_t _sz = size;
while (_sz > 0)
{
writeBufSz = (_sz <= maxBytes) ? _sz : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(var.b[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
_sz -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
return _writeErrorCheck(address, data);
}
}
// Variant B
bool SPIFlash::writeULong(uint16_t page_number, uint8_t offset, uint32_t data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeULong(address, data, errorCheck);
}
// Writes a signed long as four bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One signed long of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One signed long of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeLong(uint32_t address, int32_t data, bool errorCheck)
{
const uint8_t size = sizeof(data);
if (!_prep(PAGEPROG, address, size))
{
return false;
}
union
{
uint8_t b[size];
int32_t l;
} var;
var.l = data;
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
if (maxBytes > size)
{
_beginSPI(PAGEPROG);
_nextBuf(PAGEPROG, &var.b[0], size);
CHIP_DESELECT
}
else
{
uint16_t writeBufSz;
uint16_t data_offset = 0;
uint16_t _sz = size;
while (_sz > 0)
{
writeBufSz = (_sz <= maxBytes) ? _sz : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(var.b[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
_sz -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
return _writeErrorCheck(address, data);
}
}
// Variant B
bool SPIFlash::writeLong(uint16_t page_number, uint8_t offset, int32_t data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeLong(address, data, errorCheck);
}
// Writes a float as four bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to capacity
// 2. data --> One float of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One float of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeFloat(uint32_t address, float data, bool errorCheck)
{
const uint8_t size = (sizeof(data));
if (!_prep(PAGEPROG, address, size))
{
return false;
}
union
{
uint8_t b[size];
float f;
} var;
var.f = data;
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
if (maxBytes > size)
{
_beginSPI(PAGEPROG);
_nextBuf(PAGEPROG, &var.b[0], size);
CHIP_DESELECT
}
else
{
uint16_t writeBufSz;
uint16_t data_offset = 0;
uint16_t _sz = size;
while (_sz > 0)
{
writeBufSz = (_sz <= maxBytes) ? _sz : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
_nextByte(var.b[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
_sz -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
return _writeErrorCheck(address, data);
}
}
// Variant B
bool SPIFlash::writeFloat(uint16_t page_number, uint8_t offset, float data, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeFloat(address, data, errorCheck);
}
// Reads a string from a specific location on a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to capacity
// 2. inputString --> String variable to write the data from
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. inputString --> String variable to write the data from
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// This function first writes the size of the string as an unsigned int to the address to figure out the size of the String object stored and
// then writes the String object data. Therefore it takes up two bytes more than the size of the String itself.
// Variant A
bool SPIFlash::writeStr(uint32_t address, String &inputStr, bool errorCheck)
{
uint16_t inStrLen = inputStr.length() + 1;
if (!_prep(PAGEPROG, address, inStrLen))
{
return false;
}
const uint16_t size = sizeof(inStrLen);
union
{
uint8_t b[size];
uint16_t w;
} var;
var.w = inStrLen;
char inputChar[inStrLen];
inputStr.toCharArray(inputChar, inStrLen);
uint16_t maxBytes = PAGESIZE - (address % PAGESIZE); // Force the first set of bytes to stay within the first page
if (maxBytes > inStrLen)
{
_beginSPI(PAGEPROG);
_nextBuf(PAGEPROG, &var.b[0], size);
_nextBuf(PAGEPROG, (uint8_t *)&inputChar, inStrLen);
CHIP_DESELECT
}
else
{
uint16_t writeBufSz;
uint16_t data_offset = 0;
bool strLenWritten = false;
while (inStrLen > 0)
{
writeBufSz = (inStrLen <= maxBytes) ? inStrLen : maxBytes;
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < writeBufSz; ++i)
{
if (!strLenWritten)
{
for (uint8_t j = 0; j < size; j++)
{
_nextByte(var.b[j]);
}
strLenWritten = true;
}
_nextByte(inputChar[data_offset + i]);
}
_currentAddress += writeBufSz;
data_offset += writeBufSz;
inStrLen -= writeBufSz;
maxBytes = 256; // Now we can do up to 256 bytes per loop
CHIP_DESELECT
}
}
if (!errorCheck)
{
_endSPI();
return true;
}
else
{
String tempStr;
readStr(address, tempStr);
return inputStr.equals(tempStr);
}
}
// Variant B
bool SPIFlash::writeStr(uint16_t page_number, uint8_t offset, String &inputStr, bool errorCheck)
{
uint32_t address = _getAddress(page_number, offset);
return writeStr(address, inputStr, errorCheck);
}
//Erases one 4k sector. Has two variants:
// A. Takes the address as the argument and erases the sector containing the address.
// B. Takes page to be erased as the argument and erases the sector containing the page.
// The sectors are numbered 0 - 255 containing 16 pages each.
// Page 0-15 --> Sector 0; Page 16-31 --> Sector 1;......Page 4080-4095 --> Sector 255
// Variant A
bool SPIFlash::eraseSector(uint32_t address)
{
if (!_notBusy() || !_writeEnable())
return false;
_beginSPI(SECTORERASE);
_nextByte(address >> 16);
_nextByte(address >> 8);
_nextByte(0);
_endSPI();
if (!_notBusy(500L))
return false; //Datasheet says erasing a sector takes 400ms max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, ``Sector Erase``, Block Erase, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
// Variant B
bool SPIFlash::eraseSector(uint16_t page_number, uint8_t offset)
{
uint32_t address = _getAddress(page_number, offset);
return eraseSector(address);
}
//Erases one 32k block. Has two variants:
// A. Takes the address as the argument and erases the block containing the address.
// B. Takes page to be erased as the argument and erases the block containing the page.
// The blocks are numbered 0 - 31 containing 128 pages each.
// Page 0-127 --> Block 0; Page 128-255 --> Block 1;......Page 3968-4095 --> Block 31
// Variant A
bool SPIFlash::eraseBlock32K(uint32_t address)
{
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(BLOCK32ERASE);
_nextByte(address >> 16);
_nextByte(address >> 8);
_nextByte(0);
_endSPI();
if (!_notBusy(1 * S))
return false; //Datasheet says erasing a sector takes 400ms max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, ``Block Erase``, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
// Variant B
bool SPIFlash::eraseBlock32K(uint16_t page_number, uint8_t offset)
{
uint32_t address = _getAddress(page_number, offset);
return eraseBlock32K(address);
}
//Erases one 64k block. Has two variants:
// A. Takes the address as the argument and erases the block containing the address.
// B. Takes page to be erased as the argument and erases the block containing the page.
// The blocks are numbered 0 - 15 containing 256 pages each.
// Page 0-255 --> Block 0; Page 256-511 --> Block 1;......Page 3840-4095 --> Block 15
// Variant A
bool SPIFlash::eraseBlock64K(uint32_t address)
{
if (!_notBusy() || !_writeEnable())
{
return false;
}
_beginSPI(BLOCK64ERASE);
_nextByte(address >> 16);
_nextByte(address >> 8);
_nextByte(0);
_endSPI();
if (!_notBusy(1200L))
return false; //Datasheet says erasing a sector takes 400ms max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, ``Block Erase``, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
// Variant B
bool SPIFlash::eraseBlock64K(uint16_t page_number, uint8_t offset)
{
uint32_t address = _getAddress(page_number, offset);
return eraseBlock64K(address);
}
//Erases whole chip. Think twice before using.
bool SPIFlash::eraseChip(void)
{
if (!_notBusy() || !_writeEnable())
return false;
_beginSPI(CHIPERASE);
_endSPI();
if (!_notBusy(_chip.eraseTime))
return false; //Datasheet says erasing chip takes 6s max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, Block Erase, ``Chip Erase``, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
//Suspends current Block Erase/Sector Erase/Page Program. Does not suspend chipErase().
//Page Program, Write Status Register, Erase instructions are not allowed.
//Erase suspend is only allowed during Block/Sector erase.
//Program suspend is only allowed during Page/Quad Page Program
bool SPIFlash::suspendProg(void)
{
if (_notBusy())
{
return false;
}
if (!_noSuspend())
{
return true;
}
else
{
_beginSPI(SUSPEND);
_endSPI();
_delay_us(20);
if (!_notBusy(50) || _noSuspend())
{ //Max suspend Enable time according to datasheet
return false;
}
return true;
}
}
//Resumes previously suspended Block Erase/Sector Erase/Page Program.
bool SPIFlash::resumeProg(void)
{
if (!_notBusy() || _noSuspend())
{
return false;
}
_beginSPI(RESUME);
_endSPI();
_delay_us(20);
if (_notBusy(10) || !_noSuspend())
{
return false;
}
return true;
}
//Puts device in low power state. Good for battery powered operations.
//Typical current consumption during power-down is 1mA with a maximum of 5mA. (Datasheet 7.4)
//In powerDown() the chip will only respond to powerUp()
bool SPIFlash::powerDown(void)
{
if (!_notBusy(20))
return false;
_beginSPI(POWERDOWN);
_endSPI();
_delay_us(5);
_beginSPI(WRITEENABLE);
CHIP_DESELECT
if (_readStat1() & WRTEN)
{
_endSPI();
return false;
}
else
{
return true;
}
}
//Wakes chip from low power state.
bool SPIFlash::powerUp(void)
{
_beginSPI(RELEASE);
_endSPI();
_delay_us(3); //Max release enable time according to the Datasheet
_beginSPI(WRITEENABLE);
CHIP_DESELECT
if (_readStat1() & WRTEN)
{
_endSPI();
return true;
}
else
{
return false;
}
}
| 28.584302 | 169 | 0.628547 | jowallace1 |
cb51d8d46f665db798c6e191cee2e488173712be | 9,172 | cpp | C++ | gui_source/guimainwindow.cpp | horsicq/DIE-engine | cefb338649ef99ca03d78cbdb2b2de1b1a750e1b | [
"MIT"
] | 1,136 | 2015-02-03T21:10:11.000Z | 2022-03-31T23:30:11.000Z | gui_source/guimainwindow.cpp | horsicq/DIE-engine | cefb338649ef99ca03d78cbdb2b2de1b1a750e1b | [
"MIT"
] | 55 | 2015-03-24T06:46:00.000Z | 2022-03-17T13:37:16.000Z | gui_source/guimainwindow.cpp | horsicq/DIE-engine | cefb338649ef99ca03d78cbdb2b2de1b1a750e1b | [
"MIT"
] | 230 | 2015-01-04T13:53:52.000Z | 2022-02-28T08:45:31.000Z | // Copyright (c) 2020-2021 hors<horsicq@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 "guimainwindow.h"
#include "ui_guimainwindow.h"
GuiMainWindow::GuiMainWindow(QWidget *pParent)
: QMainWindow(pParent)
, ui(new Ui::GuiMainWindow)
{
ui->setupUi(this);
setWindowTitle(XOptions::getTitle(X_APPLICATIONDISPLAYNAME,X_APPLICATIONVERSION));
setAcceptDrops(true);
g_xOptions.setName(X_OPTIONSFILE);
QList<XOptions::ID> listOptionsIDs;
listOptionsIDs.append(XOptions::ID_STYLE);
listOptionsIDs.append(XOptions::ID_QSS);
listOptionsIDs.append(XOptions::ID_LANG);
listOptionsIDs.append(XOptions::ID_STAYONTOP);
listOptionsIDs.append(XOptions::ID_SCANAFTEROPEN);
listOptionsIDs.append(XOptions::ID_SAVELASTDIRECTORY);
listOptionsIDs.append(XOptions::ID_SINGLEAPPLICATION);
listOptionsIDs.append(XOptions::ID_SAVEBACKUP);
listOptionsIDs.append(XOptions::ID_DATABASEPATH);
listOptionsIDs.append(XOptions::ID_INFOPATH);
listOptionsIDs.append(XOptions::ID_SCANENGINE);
listOptionsIDs.append(XOptions::ID_SEARCHSIGNATURESPATH);
g_xOptions.setValueIDs(listOptionsIDs);
g_xOptions.load();
g_xShortcuts.setName(X_SHORTCUTSFILE);
g_xShortcuts.setNative(g_xOptions.isNative());
g_xShortcuts.addGroup(XShortcuts::ID_STRINGS);
g_xShortcuts.addGroup(XShortcuts::ID_SIGNATURES);
g_xShortcuts.addGroup(XShortcuts::ID_HEX);
g_xShortcuts.addGroup(XShortcuts::ID_DISASM);
g_xShortcuts.addGroup(XShortcuts::ID_ARCHIVE);
g_xShortcuts.load();
adjust();
if(QCoreApplication::arguments().count()>1)
{
QString sFileName=QCoreApplication::arguments().at(1);
processFile(sFileName);
}
}
GuiMainWindow::~GuiMainWindow()
{
g_xOptions.save();
g_xShortcuts.save();
delete ui;
}
void GuiMainWindow::on_pushButtonExit_clicked()
{
this->close();
}
void GuiMainWindow::on_pushButtonAbout_clicked()
{
DialogAbout dialogAbout(this);
dialogAbout.exec();
}
void GuiMainWindow::on_pushButtonOptions_clicked()
{
DialogOptions dialogOptions(this,&g_xOptions);
dialogOptions.exec();
adjust();
adjustFile();
}
void GuiMainWindow::on_pushButtonMIME_clicked()
{
QString sFileName=getCurrentFileName();
if(sFileName!="")
{
QFile file;
file.setFileName(sFileName);
if(XBinary::tryToOpen(&file))
{
DialogMIME dialogMIME(this,&file);
dialogMIME.setShortcuts(&g_xShortcuts);
dialogMIME.exec();
file.close();
}
}
}
void GuiMainWindow::on_pushButtonHex_clicked()
{
QString sFileName=getCurrentFileName();
if(sFileName!="")
{
QFile file;
file.setFileName(sFileName);
if(XBinary::tryToOpen(&file))
{
XHexView::OPTIONS hexOptions={};
hexOptions.sSignaturesPath=g_xOptions.getSearchSignaturesPath();
// hexOptions.sBackupFileName=XBinary::getBackupName(&file);
DialogHexView dialogHex(this,&file,hexOptions);
dialogHex.setShortcuts(&g_xShortcuts);
dialogHex.exec();
file.close();
}
}
}
void GuiMainWindow::on_pushButtonStrings_clicked()
{
QString sFileName=getCurrentFileName();
if(sFileName!="")
{
QFile file;
file.setFileName(sFileName);
if(file.open(QIODevice::ReadOnly))
{
SearchStringsWidget::OPTIONS stringsOptions={};
stringsOptions.bAnsi=true;
stringsOptions.bUTF8=false;
stringsOptions.bUnicode=true;
stringsOptions.bCStrings=true;
DialogSearchStrings dialogSearchStrings(this);
dialogSearchStrings.setData(&file,stringsOptions,true);
dialogSearchStrings.setShortcuts(&g_xShortcuts);
dialogSearchStrings.exec();
file.close();
}
}
}
void GuiMainWindow::on_pushButtonSignatures_clicked()
{
QString sFileName=getCurrentFileName();
if(sFileName!="")
{
QFile file;
file.setFileName(sFileName);
if(file.open(QIODevice::ReadOnly))
{
SearchSignaturesWidget::OPTIONS signaturesOptions={};
signaturesOptions.sSignaturesPath=g_xOptions.getSearchSignaturesPath();
DialogSearchSignatures dialogSearchSignatures(this);
dialogSearchSignatures.setData(&file,XBinary::FT_UNKNOWN,signaturesOptions);
dialogSearchSignatures.setShortcuts(&g_xShortcuts);
dialogSearchSignatures.exec();
file.close();
}
}
}
void GuiMainWindow::on_pushButtonEntropy_clicked()
{
QString sFileName=getCurrentFileName();
if(sFileName!="")
{
QFile file;
file.setFileName(sFileName);
if(file.open(QIODevice::ReadOnly))
{
DialogEntropy dialogEntropy(this);
dialogEntropy.setData(&file);
dialogEntropy.setShortcuts(&g_xShortcuts);
dialogEntropy.exec();
file.close();
}
}
}
void GuiMainWindow::on_pushButtonHash_clicked()
{
QString sFileName=getCurrentFileName();
if(sFileName!="")
{
QFile file;
file.setFileName(sFileName);
if(file.open(QIODevice::ReadOnly))
{
DialogHash dialogHash(this);
dialogHash.setData(&file,XBinary::FT_UNKNOWN);
dialogHash.setShortcuts(&g_xShortcuts);
dialogHash.exec();
file.close();
}
}
}
void GuiMainWindow::on_pushButtonDemangle_clicked()
{
DialogDemangle dialogDemangle(this);
dialogDemangle.exec();
}
QString GuiMainWindow::getCurrentFileName()
{
return ui->lineEditFileName->text();
}
void GuiMainWindow::adjust()
{
g_xOptions.adjustStayOnTop(this);
FormatsWidget::OPTIONS options={};
options.sDatabasePath=g_xOptions.getDatabasePath();
options.sInfoPath=g_xOptions.getInfoPath();
options.bIsSaveBackup=g_xOptions.isSaveBackup();
options.sSearchSignaturesPath=g_xOptions.getSearchSignaturesPath();
ui->widgetFormats->setOptions(options);
ui->widgetFormats->setScanEngine(g_xOptions.getScanEngine());
ui->widgetFormats->setShortcuts(&g_xShortcuts);
// TODO setShortcuts for mainWindow ...
}
void GuiMainWindow::adjustFile()
{
QString sFileName=getCurrentFileName();
g_xOptions.setLastDirectory(sFileName);
}
void GuiMainWindow::processFile(QString sFileName)
{
ui->lineEditFileName->setText(sFileName);
if(sFileName!="")
{
ui->widgetFormats->setFileName(sFileName,g_xOptions.isScanAfterOpen());
adjustFile();
}
}
void GuiMainWindow::dragEnterEvent(QDragEnterEvent *event)
{
event->acceptProposedAction();
}
void GuiMainWindow::dragMoveEvent(QDragMoveEvent *event)
{
event->acceptProposedAction();
}
void GuiMainWindow::dropEvent(QDropEvent *event)
{
const QMimeData* mimeData=event->mimeData();
if(mimeData->hasUrls())
{
QList<QUrl> urlList=mimeData->urls();
if(urlList.count())
{
QString sFileName=urlList.at(0).toLocalFile();
sFileName=XBinary::convertFileName(sFileName);
processFile(sFileName);
}
}
}
void GuiMainWindow::on_pushButtonOpenFile_clicked()
{
QString sDirectory=g_xOptions.getLastDirectory();
QString sFileName=QFileDialog::getOpenFileName(this,tr("Open file")+QString("..."),sDirectory,tr("All files")+QString(" (*)"));
if(!sFileName.isEmpty())
{
processFile(sFileName);
}
}
void GuiMainWindow::on_pushButtonShortcuts_clicked()
{
DialogShortcuts dialogShortcuts(this);
dialogShortcuts.setData(&g_xShortcuts);
dialogShortcuts.exec();
adjust();
}
| 26.356322 | 132 | 0.656345 | horsicq |
cb5268a626a5272cf1654d2a63bc0b314bc0186a | 13,774 | cpp | C++ | testing/testing_cgesvd.cpp | shengren/magma-1.6.1 | 1adfee30b763e9491a869403e0f320b3888923b6 | [
"BSD-3-Clause"
] | 21 | 2017-10-06T05:05:05.000Z | 2022-03-13T15:39:20.000Z | testing/testing_cgesvd.cpp | shengren/magma-1.6.1 | 1adfee30b763e9491a869403e0f320b3888923b6 | [
"BSD-3-Clause"
] | 1 | 2017-03-23T00:27:24.000Z | 2017-03-23T00:27:24.000Z | testing/testing_cgesvd.cpp | shengren/magma-1.6.1 | 1adfee30b763e9491a869403e0f320b3888923b6 | [
"BSD-3-Clause"
] | 4 | 2018-01-09T15:49:58.000Z | 2022-03-13T15:39:27.000Z | /*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@generated from testing_zgesvd.cpp normal z -> c, Fri Jan 30 19:00:26 2015
@author Mark Gates
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "magma.h"
#include "magma_lapack.h"
#include "testings.h"
#define COMPLEX
/* ////////////////////////////////////////////////////////////////////////////
-- Testing cgesvd (SVD with QR iteration)
Please keep code in testing_cgesdd.cpp and testing_cgesvd.cpp similar.
*/
int main( int argc, char** argv)
{
TESTING_INIT();
real_Double_t gpu_time, cpu_time;
magmaFloatComplex *h_A, *h_R, *U, *VT, *h_work;
magmaFloatComplex dummy[1];
float *S1, *S2;
#ifdef COMPLEX
float *rwork;
#endif
magma_int_t M, N, N_U, M_VT, lda, ldu, ldv, n2, min_mn, info, nb, lwork;
magma_int_t ione = 1;
magma_int_t ISEED[4] = {0,0,0,1};
magma_vec_t jobu, jobvt;
magma_int_t status = 0;
magma_opts opts;
parse_opts( argc, argv, &opts );
float tol = opts.tolerance * lapackf77_slamch("E");
jobu = opts.jobu;
jobvt = opts.jobvt;
magma_vec_t jobs[] = { MagmaNoVec, MagmaSomeVec, MagmaOverwriteVec, MagmaAllVec };
if ( opts.check && ! opts.all && (jobu == MagmaNoVec || jobvt == MagmaNoVec)) {
printf( "NOTE: some checks require that singular vectors are computed;\n"
" set both jobu (option -U[NASO]) and jobvt (option -V[NASO]) to be S, O, or A.\n\n" );
}
printf("jobu jobv M N CPU time (sec) GPU time (sec) |S1-S2|/. |A-USV'|/. |I-UU'|/M |I-VV'|/N S sorted\n");
printf("===========================================================================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int ijobu = 0; ijobu < 4; ++ijobu ) {
for( int ijobv = 0; ijobv < 4; ++ijobv ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
if ( opts.all ) {
jobu = jobs[ ijobu ];
jobvt = jobs[ ijobv ];
}
else if ( ijobu > 0 || ijobv > 0 ) {
// if not testing all, run only once, when ijobu = ijobv = 0,
// but jobu and jobv come from opts (above loops).
continue;
}
if ( jobu == MagmaOverwriteVec && jobvt == MagmaOverwriteVec ) {
// illegal combination; skip
continue;
}
M = opts.msize[itest];
N = opts.nsize[itest];
min_mn = min(M, N);
N_U = (jobu == MagmaAllVec ? M : min_mn);
M_VT = (jobvt == MagmaAllVec ? N : min_mn);
lda = M;
ldu = M;
ldv = M_VT;
n2 = lda*N;
nb = magma_get_cgesvd_nb(N);
// query or use formula for workspace size
switch( opts.svd_work ) {
case 0: { // query for workspace size
lwork = -1;
magma_cgesvd( jobu, jobvt, M, N,
h_R, lda, S1, U, ldu, VT, ldv, dummy, lwork,
#ifdef COMPLEX
rwork,
#endif
&info );
lwork = (int) MAGMA_C_REAL( dummy[0] );
break;
}
// these are not tight bounds:
// if (m >> n), it may need only (2*N)*nb instead of (M+N)*nb.
// if (n >> m), it may need only (2*M)*nb instead of (M+N)*nb.
#ifdef COMPLEX
case 1: lwork = (M+N)*nb + 2*min_mn; break; // minimum
case 2: lwork = (M+N)*nb + 2*min_mn + min_mn*min_mn; break; // optimal for some paths
case 3: lwork = (M+N)*nb + 2*min_mn + 2*min_mn*min_mn; break; // optimal for all paths
#else
case 1: lwork = (M+N)*nb + 3*min_mn; break; // minimum
case 2: lwork = (M+N)*nb + 3*min_mn + min_mn*min_mn; break; // optimal for some paths
case 3: lwork = (M+N)*nb + 3*min_mn + 2*min_mn*min_mn; break; // optimal for all paths
#endif
default: {
fprintf( stderr, "Error: unknown option svd_work %d\n", (int) opts.svd_work );
exit(1);
break;
}
}
TESTING_MALLOC_CPU( h_A, magmaFloatComplex, lda*N );
TESTING_MALLOC_CPU( VT, magmaFloatComplex, ldv*N ); // N x N (jobvt=A) or min(M,N) x N
TESTING_MALLOC_CPU( U, magmaFloatComplex, ldu*N_U ); // M x M (jobu=A) or M x min(M,N)
TESTING_MALLOC_CPU( S1, float, min_mn );
TESTING_MALLOC_CPU( S2, float, min_mn );
TESTING_MALLOC_PIN( h_R, magmaFloatComplex, lda*N );
TESTING_MALLOC_PIN( h_work, magmaFloatComplex, lwork );
#ifdef COMPLEX
TESTING_MALLOC_CPU( rwork, float, 5*min_mn );
#endif
/* Initialize the matrix */
lapackf77_clarnv( &ione, ISEED, &n2, h_A );
lapackf77_clacpy( MagmaUpperLowerStr, &M, &N, h_A, &lda, h_R, &lda );
/* ====================================================================
Performs operation using MAGMA
=================================================================== */
gpu_time = magma_wtime();
magma_cgesvd( jobu, jobvt, M, N,
h_R, lda, S1, U, ldu, VT, ldv, h_work, lwork,
#ifdef COMPLEX
rwork,
#endif
&info );
gpu_time = magma_wtime() - gpu_time;
if (info != 0)
printf("magma_cgesvd returned error %d: %s.\n",
(int) info, magma_strerror( info ));
float eps = lapackf77_slamch( "E" );
float result[5] = { -1/eps, -1/eps, -1/eps, -1/eps, -1/eps };
if ( opts.check ) {
/* =====================================================================
Check the results following the LAPACK's [zcds]drvbd routine.
A is factored as A = U diag(S) VT and the following 4 tests computed:
(1) | A - U diag(S) VT | / ( |A| max(M,N) )
(2) | I - U'U | / ( M )
(3) | I - VT VT' | / ( N )
(4) S contains MNMIN nonnegative values in decreasing order.
(Return 0 if true, 1/ULP if false.)
=================================================================== */
magma_int_t izero = 0;
// get size and location of U and V^T depending on jobu and jobvt
// U2=NULL and VT2=NULL if they were not computed (e.g., jobu=N)
magmaFloatComplex *U2 = NULL;
magmaFloatComplex *VT2 = NULL;
if ( jobu == MagmaSomeVec || jobu == MagmaAllVec ) {
U2 = U;
}
else if ( jobu == MagmaOverwriteVec ) {
U2 = h_R;
ldu = lda;
}
if ( jobvt == MagmaSomeVec || jobvt == MagmaAllVec ) {
VT2 = VT;
}
else if ( jobvt == MagmaOverwriteVec ) {
VT2 = h_R;
ldv = lda;
}
// cbdt01 needs M+N
// cunt01 prefers N*(N+1) to check U; M*(M+1) to check V
magma_int_t lwork_err = M+N;
if ( U2 != NULL ) {
lwork_err = max( lwork_err, N_U*(N_U+1) );
}
if ( VT2 != NULL ) {
lwork_err = max( lwork_err, M_VT*(M_VT+1) );
}
magmaFloatComplex *h_work_err;
TESTING_MALLOC_CPU( h_work_err, magmaFloatComplex, lwork_err );
// cbdt01 and cunt01 need max(M,N), depending
float *rwork_err;
TESTING_MALLOC_CPU( rwork_err, float, max(M,N) );
if ( U2 != NULL && VT2 != NULL ) {
// since KD=0 (3rd arg), E is not referenced so pass NULL (9th arg)
lapackf77_cbdt01(&M, &N, &izero, h_A, &lda,
U2, &ldu, S1, NULL, VT2, &ldv,
h_work_err,
#ifdef COMPLEX
rwork_err,
#endif
&result[0]);
}
if ( U2 != NULL ) {
lapackf77_cunt01("Columns", &M, &N_U, U2, &ldu, h_work_err, &lwork_err,
#ifdef COMPLEX
rwork_err,
#endif
&result[1]);
}
if ( VT2 != NULL ) {
lapackf77_cunt01("Rows", &M_VT, &N, VT2, &ldv, h_work_err, &lwork_err,
#ifdef COMPLEX
rwork_err,
#endif
&result[2]);
}
result[3] = 0.;
for(int j=0; j < min_mn-1; j++){
if ( S1[j] < S1[j+1] )
result[3] = 1.;
if ( S1[j] < 0. )
result[3] = 1.;
}
if (min_mn > 1 && S1[min_mn-1] < 0.)
result[3] = 1.;
result[0] *= eps;
result[1] *= eps;
result[2] *= eps;
TESTING_FREE_CPU( h_work_err );
TESTING_FREE_CPU( rwork_err );
}
/* =====================================================================
Performs operation using LAPACK
=================================================================== */
if ( opts.lapack ) {
cpu_time = magma_wtime();
lapackf77_cgesvd( lapack_vec_const(jobu), lapack_vec_const(jobvt), &M, &N,
h_A, &lda, S2, U, &ldu, VT, &ldv, h_work, &lwork,
#ifdef COMPLEX
rwork,
#endif
&info);
cpu_time = magma_wtime() - cpu_time;
if (info != 0)
printf("lapackf77_cgesvd returned error %d: %s.\n",
(int) info, magma_strerror( info ));
/* =====================================================================
Check the result compared to LAPACK
=================================================================== */
float work[1], c_neg_one = -1;
magma_int_t one = 1;
blasf77_saxpy(&min_mn, &c_neg_one, S1, &one, S2, &one);
result[4] = lapackf77_slange("f", &min_mn, &one, S2, &min_mn, work);
result[4] /= lapackf77_slange("f", &min_mn, &one, S1, &min_mn, work);
printf(" %c %c %5d %5d %7.2f %7.2f %8.2e",
lapack_vec_const(jobu)[0], lapack_vec_const(jobvt)[0],
(int) M, (int) N, cpu_time, gpu_time, result[4] );
}
else {
printf(" %c %c %5d %5d --- %7.2f --- ",
lapack_vec_const(jobu)[0], lapack_vec_const(jobvt)[0],
(int) M, (int) N, gpu_time );
}
if ( opts.check ) {
if ( result[0] < 0. ) { printf(" --- "); } else { printf(" %#9.3g", result[0]); }
if ( result[1] < 0. ) { printf(" --- "); } else { printf(" %#9.3g", result[1]); }
if ( result[2] < 0. ) { printf(" --- "); } else { printf(" %#9.3g", result[2]); }
int success = (result[0] < tol) && (result[1] < tol) && (result[2] < tol) && (result[3] == 0.) && (result[4] < tol);
printf(" %3s %s\n", (result[3] == 0. ? "yes" : "no"), (success ? "ok" : "failed"));
status += ! success;
}
else {
printf("\n");
}
TESTING_FREE_CPU( h_A );
TESTING_FREE_CPU( VT );
TESTING_FREE_CPU( U );
TESTING_FREE_CPU( S1 );
TESTING_FREE_CPU( S2 );
#ifdef COMPLEX
TESTING_FREE_CPU( rwork );
#endif
TESTING_FREE_PIN( h_R );
TESTING_FREE_PIN( h_work );
fflush( stdout );
}}}
if ( opts.all || opts.niter > 1 ) {
printf("\n");
}
}
TESTING_FINALIZE();
return status;
}
| 43.588608 | 132 | 0.389575 | shengren |
cb527ed6f06d280e174b56713dc7decf9c1e69a7 | 1,679 | cpp | C++ | kattis/pick_up_sticks/PickUpSticks.cpp | FredrikWallstrom/Kattis | aee103c8d97d2aba61dae59146a015ccb5a7a634 | [
"MIT"
] | 1 | 2020-11-11T12:12:19.000Z | 2020-11-11T12:12:19.000Z | kattis/pick_up_sticks/PickUpSticks.cpp | FredrikWallstrom/Kattis | aee103c8d97d2aba61dae59146a015ccb5a7a634 | [
"MIT"
] | null | null | null | kattis/pick_up_sticks/PickUpSticks.cpp | FredrikWallstrom/Kattis | aee103c8d97d2aba61dae59146a015ccb5a7a634 | [
"MIT"
] | null | null | null | /* -*- Mode: C++ -*- */
/**
* Author: Fredrik Wallström
* Date:
*
* Comments: 22/2 - 18
*
* Lessons Learned:
*/
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iomanip>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <iostream>
using namespace std;
typedef vector<int> vi;
void explore(int curr, vi &visited, map<int, vi> &sticks, stack<int> &res){
// We are visiting current node for the moment.
visited[curr] = 1;
for (int i = 0; i < sticks[curr].size(); ++i) {
// Already visited.
if(visited[sticks[curr][i]] == 2) continue;
// Impossible, cycle detected.
else if(visited[sticks[curr][i]] == 1) return;
// Keep explore.
else explore(sticks[curr][i], visited, sticks, res);
}
res.push(curr);
visited[curr] = 2;
}
int main() {
int nrSticks, nrLines;
int a, b;
scanf("%d%d", &nrSticks, &nrLines);
map<int, vi> sticks;
vi visited(static_cast<unsigned long>(nrSticks + 1), 0);
stack<int> res;
for (int k = 1; k <= nrLines; ++k) scanf("%d%d", &a, &b), sticks[a].push_back(b);
for (int i = 1; i <= nrSticks; ++i) {
if(visited[i] == 0) explore(i, visited, sticks, res);
else if(visited[i] == 1) {
printf("IMPOSSIBLE");
return 0;
}
}
auto loopSize = static_cast<int>(res.size());
for (int i = 0; i < loopSize; ++i) {
printf("%d\n", res.top());
res.pop();
}
return 0;
} | 22.689189 | 85 | 0.562239 | FredrikWallstrom |
cb5356dd952d8f0b228483b5d04803b9d35f485b | 1,176 | hpp | C++ | NWNXLib/API/Mac/API/CNWSExpressionList.hpp | acaos/nwnxee-unified | 0e4c318ede64028c1825319f39c012e168e0482c | [
"MIT"
] | 1 | 2019-06-04T04:30:24.000Z | 2019-06-04T04:30:24.000Z | NWNXLib/API/Mac/API/CNWSExpressionList.hpp | presscad/nwnee | 0f36b281524e0b7e9796bcf30f924792bf9b8a38 | [
"MIT"
] | null | null | null | NWNXLib/API/Mac/API/CNWSExpressionList.hpp | presscad/nwnee | 0f36b281524e0b7e9796bcf30f924792bf9b8a38 | [
"MIT"
] | 1 | 2019-10-20T07:54:45.000Z | 2019-10-20T07:54:45.000Z | #pragma once
#include <cstdint>
namespace NWNXLib {
namespace API {
// Forward class declarations (defined in the source file)
struct CNWSExpressionNode;
struct CNWSExpressionList
{
CNWSExpressionNode* m_pHead;
CNWSExpressionNode* m_pAfter;
CNWSExpressionNode* m_pTail;
// The below are auto generated stubs.
CNWSExpressionList(const CNWSExpressionList&) = default;
CNWSExpressionList& operator=(const CNWSExpressionList&) = default;
CNWSExpressionList();
~CNWSExpressionList();
void AddNode(CNWSExpressionNode*);
void AddNodeToHead(CNWSExpressionNode*);
void DeleteAlternate(CNWSExpressionNode*);
void DeleteList();
};
void CNWSExpressionList__CNWSExpressionListCtor__0(CNWSExpressionList* thisPtr);
void CNWSExpressionList__CNWSExpressionListDtor__0(CNWSExpressionList* thisPtr);
void CNWSExpressionList__AddNode(CNWSExpressionList* thisPtr, CNWSExpressionNode*);
void CNWSExpressionList__AddNodeToHead(CNWSExpressionList* thisPtr, CNWSExpressionNode*);
void CNWSExpressionList__DeleteAlternate(CNWSExpressionList* thisPtr, CNWSExpressionNode*);
void CNWSExpressionList__DeleteList(CNWSExpressionList* thisPtr);
}
}
| 29.4 | 91 | 0.806973 | acaos |
cb536634efb9391df7634b12a71f16194d248a9b | 2,915 | hpp | C++ | libs/boost_1_72_0/boost/spirit/home/support/iterators/istream_iterator.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/spirit/home/support/iterators/istream_iterator.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/spirit/home/support/iterators/istream_iterator.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2001-2011 Hartmut Kaiser
//
// 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)
#if !defined(BOOST_SPIRIT_ISTREAM_ITERATOR_JAN_03_2010_0522PM)
#define BOOST_SPIRIT_ISTREAM_ITERATOR_JAN_03_2010_0522PM
#include <boost/spirit/home/support/iterators/detail/ref_counted_policy.hpp>
#if defined(BOOST_SPIRIT_DEBUG)
#include <boost/spirit/home/support/iterators/detail/buf_id_check_policy.hpp>
#else
#include <boost/spirit/home/support/iterators/detail/no_check_policy.hpp>
#endif
#include <boost/spirit/home/support/iterators/detail/combine_policies.hpp>
#include <boost/spirit/home/support/iterators/detail/istream_policy.hpp>
#include <boost/spirit/home/support/iterators/detail/split_std_deque_policy.hpp>
#include <boost/spirit/home/support/iterators/multi_pass.hpp>
namespace boost {
namespace spirit {
///////////////////////////////////////////////////////////////////////////
template <typename Elem, typename Traits = std::char_traits<Elem>>
class basic_istream_iterator
: public multi_pass<
std::basic_istream<Elem, Traits>,
iterator_policies::default_policy<
iterator_policies::ref_counted
#if defined(BOOST_SPIRIT_DEBUG)
,
iterator_policies::buf_id_check
#else
,
iterator_policies::no_check
#endif
,
iterator_policies::istream, iterator_policies::split_std_deque>> {
private:
typedef multi_pass<
std::basic_istream<Elem, Traits>,
iterator_policies::default_policy<iterator_policies::ref_counted
#if defined(BOOST_SPIRIT_DEBUG)
,
iterator_policies::buf_id_check
#else
,
iterator_policies::no_check
#endif
,
iterator_policies::istream,
iterator_policies::split_std_deque>>
base_type;
public:
basic_istream_iterator() : base_type() {}
explicit basic_istream_iterator(std::basic_istream<Elem, Traits> &x)
: base_type(x) {}
basic_istream_iterator(basic_istream_iterator const &x) : base_type(x) {}
#if BOOST_WORKAROUND(__GLIBCPP__, == 20020514)
basic_istream_iterator(int) // workaround for a bug in the library
: base_type() {} // shipped with gcc 3.1
#endif // BOOST_WORKAROUND(__GLIBCPP__, == 20020514)
basic_istream_iterator operator=(base_type const &rhs) {
this->base_type::operator=(rhs);
return *this;
}
// default generated operators, destructor and assignment operator are ok.
};
typedef basic_istream_iterator<char> istream_iterator;
} // namespace spirit
} // namespace boost
#endif
| 35.987654 | 80 | 0.650772 | henrywarhurst |
cb5550eb21419795c12efa71aec4704879d987d0 | 255 | cpp | C++ | leetcode/53. Maximum Subarray/s2.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | 1 | 2021-02-09T11:38:51.000Z | 2021-02-09T11:38:51.000Z | leetcode/53. Maximum Subarray/s2.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | null | null | null | leetcode/53. Maximum Subarray/s2.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | null | null | null | class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = INT_MIN, sum = 0;
for (int n : nums) {
sum += n;
ans = max(sum, ans);
sum = max(sum, 0);
}
return ans;
}
}; | 21.25 | 40 | 0.427451 | contacttoakhil |
cb595922ceffae3078edc74771054e32f8cc700d | 5,378 | cpp | C++ | libcassandra/src/Cassandra.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | 1 | 2016-05-09T03:34:51.000Z | 2016-05-09T03:34:51.000Z | libcassandra/src/Cassandra.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | null | null | null | libcassandra/src/Cassandra.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | null | null | null | /* Sirikata Cassandra Plugin
* Cassandra.cpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* 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 Sirikata 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.
*/
#include <sirikata/cassandra/Cassandra.hpp>
#include <boost/thread.hpp>
AUTO_SINGLETON_INSTANCE(Sirikata::Cassandra);
namespace Sirikata {
CassandraDB::CassandraDB(const String& host, int port) {
libcassandra::CassandraFactory cf(host, port);
client=boost::shared_ptr<libcassandra::Cassandra>(cf.create());
try {
client->setKeyspace("sirikata");
}
catch (org::apache::cassandra::InvalidRequestException &ire) {
initSchema();
}
}
CassandraDB::~CassandraDB() {
}
boost::shared_ptr<libcassandra::Cassandra> CassandraDB::db() const {
return client;
}
void CassandraDB::initSchema() {
try {
// create keyspace
libcassandra::KeyspaceDefinition ks_def;
ks_def.setName("sirikata");
client->createKeyspace(ks_def);
client->setKeyspace("sirikata");
libcassandra::ColumnFamilyDefinition cf_def_1;
cf_def_1.setName("persistence");
cf_def_1.setColumnType("Super");
cf_def_1.setKeyspaceName("sirikata");
client->createColumnFamily(cf_def_1);
libcassandra::ColumnFamilyDefinition cf_def_2;
cf_def_2.setName("objects");
cf_def_2.setColumnType("Super");
cf_def_2.setKeyspaceName("sirikata");
client->createColumnFamily(cf_def_2);
}
catch (org::apache::cassandra::NotFoundException &ire) {
SILOG(cassandra, error, "NotFoundException Caught");
}
catch (org::apache::cassandra::InvalidRequestException &ire) {
SILOG(cassandra, error, ire.why);
}
catch (...) {
SILOG(cassandra, error, "Other Exception Caught");
}
}
namespace {
boost::shared_mutex sSingletonMutex;
}
Cassandra::Cassandra() {
}
Cassandra::~Cassandra() {
}
Cassandra& Cassandra::getSingleton() {
boost::unique_lock<boost::shared_mutex> lck(sSingletonMutex);
return AutoSingleton<Cassandra>::getSingleton();
}
void Cassandra::destroy() {
boost::unique_lock<boost::shared_mutex> lck(sSingletonMutex);
AutoSingleton<Cassandra>::destroy();
}
CassandraDBPtr Cassandra::open(const String& host, int port) {
UpgradeLock upgrade_lock(mDBMutex);
// First get the thread local storage for this database
DBMap::iterator it = mDBs.find(host);
if (it == mDBs.end()) {
// the thread specific store hasn't even been allocated
UpgradedLock upgraded_lock(upgrade_lock);
// verify another thread hasn't added it, then add it
it = mDBs.find(host);
if (it == mDBs.end()) {
std::tr1::shared_ptr<ThreadDBPtr> newDb(new ThreadDBPtr());
mDBs[host]=newDb;
it = mDBs.find(host);
}
}
assert(it != mDBs.end());
std::tr1::shared_ptr<ThreadDBPtr> thread_db_ptr_ptr = it->second;
assert(thread_db_ptr_ptr);
// Now get the thread specific weak database connection
WeakCassandraDBPtr* weak_db_ptr_ptr = thread_db_ptr_ptr->get();
if (weak_db_ptr_ptr == NULL) {
// we don't have a weak pointer for this thread
UpgradedLock upgraded_lock(upgrade_lock);
weak_db_ptr_ptr = thread_db_ptr_ptr->get();
if (weak_db_ptr_ptr == NULL) { // verify and create
weak_db_ptr_ptr = new WeakCassandraDBPtr();
thread_db_ptr_ptr->reset( weak_db_ptr_ptr );
}
}
assert(weak_db_ptr_ptr != NULL);
CassandraDBPtr db;
db = weak_db_ptr_ptr->lock();
if (!db) {
// the weak pointer for this thread is NULL
UpgradedLock upgraded_lock(upgrade_lock);
db = weak_db_ptr_ptr->lock();
if (!db) {
db = CassandraDBPtr(new CassandraDB(host, port));
*weak_db_ptr_ptr = db;
}
}
assert(db);
return db;
}
} // namespace Sirikata
| 32.993865 | 75 | 0.68334 | pathorn |
cb5a40e22ee37b6784e0c594e33f65f6df496c95 | 1,604 | cpp | C++ | tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/CWE675_Duplicate_Operations_on_Resource__open_62b.cpp | RanerL/analyzer | a401da4680f163201326881802ee535d6cf97f5a | [
"MIT"
] | 28 | 2017-01-20T15:25:54.000Z | 2020-03-17T00:28:31.000Z | testcases/CWE675_Duplicate_Operations_on_Resource/CWE675_Duplicate_Operations_on_Resource__open_62b.cpp | mellowCS/cwe_checker_juliet_suite | ae604f6fd94964251fbe88ef04d5287f6c1ffbe2 | [
"MIT"
] | 1 | 2017-01-20T15:26:27.000Z | 2018-08-20T00:55:37.000Z | testcases/CWE675_Duplicate_Operations_on_Resource/CWE675_Duplicate_Operations_on_Resource__open_62b.cpp | mellowCS/cwe_checker_juliet_suite | ae604f6fd94964251fbe88ef04d5287f6c1ffbe2 | [
"MIT"
] | 2 | 2019-07-15T19:07:04.000Z | 2019-09-07T14:21:04.000Z | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE675_Duplicate_Operations_on_Resource__open_62b.cpp
Label Definition File: CWE675_Duplicate_Operations_on_Resource__open.label.xml
Template File: sources-sinks-62b.tmpl.cpp
*/
/*
* @description
* CWE: 675 Duplicate Operations on Resource
* BadSource: Open and close a file using open() and close()
* GoodSource: Open a file using open()
* Sinks:
* GoodSink: Do nothing
* BadSink : Close the file
* Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifdef _WIN32
# define OPEN _open
# define CLOSE _close
#else
#include <unistd.h>
# define OPEN open
# define CLOSE close
#endif
namespace CWE675_Duplicate_Operations_on_Resource__open_62
{
#ifndef OMITBAD
void badSource(int &data)
{
data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
/* POTENTIAL FLAW: Close the file in the source */
CLOSE(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(int &data)
{
/* FIX: Open, but do not close the file in the source */
data = OPEN("GoodSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
}
/* goodB2G() uses the BadSource with the GoodSink */
void goodB2GSource(int &data)
{
data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
/* POTENTIAL FLAW: Close the file in the source */
CLOSE(data);
}
#endif /* OMITGOOD */
} /* close namespace */
| 25.460317 | 119 | 0.695761 | RanerL |
cb5ff6ee02a8b9b748d1f8bc78e3e37713852953 | 904 | cpp | C++ | src/plot_functions.cpp | grgomrton/kalman-filter | 5d47aab153d3d5ea8a6b12e35a9b3ee3ee25c1b7 | [
"MIT"
] | null | null | null | src/plot_functions.cpp | grgomrton/kalman-filter | 5d47aab153d3d5ea8a6b12e35a9b3ee3ee25c1b7 | [
"MIT"
] | 1 | 2018-03-08T23:02:04.000Z | 2018-10-08T04:49:02.000Z | src/plot_functions.cpp | grgomrton/kalman-filter | 5d47aab153d3d5ea8a6b12e35a9b3ee3ee25c1b7 | [
"MIT"
] | null | null | null | #include <plot_functions.h>
#include <cmath>
std::vector<double>
plot_functions::create_uniform_scale(double start, double end, unsigned int reference_point_count) { // todo exceptions
std::vector<double> scale(reference_point_count);
double step = (end - start) / (double) (reference_point_count - 1);
for (int i = 0; i < reference_point_count; i++) {
scale[i] = start + i * step;
}
return scale;
}
std::vector<double> plot_functions::plot_gaussian(double mean, double variance, const std::vector<double>& scale) {
auto fx = [](double x, double mean, double variance) {
return 1 / (sqrt(variance) * sqrt(2 * M_PI)) * pow(M_E, -0.5 * pow((x - mean) / sqrt(variance), 2)); // ugh
};
std::vector<double> y_values(scale.size());
for (int i = 0; i < y_values.size(); i++) {
y_values[i] = fx(scale[i], mean, variance);
}
return y_values;
} | 39.304348 | 119 | 0.640487 | grgomrton |
cb62d64a3994ca048cad325d2f8506049447bf0b | 6,409 | hpp | C++ | Pods/Headers/Private/GeoFeatures/boost/geometry/geometries/segment.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | null | null | null | Pods/Headers/Private/GeoFeatures/boost/geometry/geometries/segment.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | null | null | null | Pods/Headers/Private/GeoFeatures/boost/geometry/geometries/segment.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | null | null | null | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_GEOMETRIES_SEGMENT_HPP
#define BOOST_GEOMETRY_GEOMETRIES_SEGMENT_HPP
#include <cstddef>
#include <boost/concept/assert.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/geometry/geometries/concepts/point_concept.hpp>
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry
{
namespace model
{
/*!
\brief Class segment: small class containing two points
\ingroup geometries
\details From Wikipedia: In geometry, a line segment is a part of a line that is bounded
by two distinct end points, and contains every point on the line between its end points.
\note There is also a point-referring-segment, class referring_segment,
containing point references, where points are NOT copied
\qbk{[include reference/geometries/segment.qbk]}
\qbk{before.synopsis,
[heading Model of]
[link geometry.reference.concepts.concept_segment Segment Concept]
}
*/
template<typename Point>
class segment : public std::pair<Point, Point>
{
BOOST_CONCEPT_ASSERT( (concept::Point<Point>) );
public :
#ifndef BOOST_NO_CXX11_DEFAULTED_FUNCTIONS
/// \constructor_default_no_init
segment() = default;
#else
/// \constructor_default_no_init
inline segment()
{}
#endif
/*!
\brief Constructor taking the first and the second point
*/
inline segment(Point const& p1, Point const& p2)
{
this->first = p1;
this->second = p2;
}
};
/*!
\brief Class segment: small class containing two (templatized) point references
\ingroup geometries
\details From Wikipedia: In geometry, a line segment is a part of a line that is bounded
by two distinct end points, and contains every point on the line between its end points.
\note The structure is like std::pair, and can often be used interchangeable.
Difference is that it refers to points, does not have points.
\note Like std::pair, points are public available.
\note type is const or non const, so geometry::segment<P> or geometry::segment<P const>
\note We cannot derive from std::pair<P&, P&> because of
reference assignments.
\tparam ConstOrNonConstPoint point type of the segment, maybe a point or a const point
*/
template<typename ConstOrNonConstPoint>
class referring_segment
{
BOOST_CONCEPT_ASSERT( (
typename geofeatures_boost::mpl::if_
<
geofeatures_boost::is_const<ConstOrNonConstPoint>,
concept::Point<ConstOrNonConstPoint>,
concept::ConstPoint<ConstOrNonConstPoint>
>
) );
typedef ConstOrNonConstPoint point_type;
public:
point_type& first;
point_type& second;
/*!
\brief Constructor taking the first and the second point
*/
inline referring_segment(point_type& p1, point_type& p2)
: first(p1)
, second(p2)
{}
};
} // namespace model
// Traits specializations for segment above
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{
template <typename Point>
struct tag<model::segment<Point> >
{
typedef segment_tag type;
};
template <typename Point>
struct point_type<model::segment<Point> >
{
typedef Point type;
};
template <typename Point, std::size_t Dimension>
struct indexed_access<model::segment<Point>, 0, Dimension>
{
typedef model::segment<Point> segment_type;
typedef typename geometry::coordinate_type<segment_type>::type coordinate_type;
static inline coordinate_type get(segment_type const& s)
{
return geometry::get<Dimension>(s.first);
}
static inline void set(segment_type& s, coordinate_type const& value)
{
geometry::set<Dimension>(s.first, value);
}
};
template <typename Point, std::size_t Dimension>
struct indexed_access<model::segment<Point>, 1, Dimension>
{
typedef model::segment<Point> segment_type;
typedef typename geometry::coordinate_type<segment_type>::type coordinate_type;
static inline coordinate_type get(segment_type const& s)
{
return geometry::get<Dimension>(s.second);
}
static inline void set(segment_type& s, coordinate_type const& value)
{
geometry::set<Dimension>(s.second, value);
}
};
template <typename ConstOrNonConstPoint>
struct tag<model::referring_segment<ConstOrNonConstPoint> >
{
typedef segment_tag type;
};
template <typename ConstOrNonConstPoint>
struct point_type<model::referring_segment<ConstOrNonConstPoint> >
{
typedef ConstOrNonConstPoint type;
};
template <typename ConstOrNonConstPoint, std::size_t Dimension>
struct indexed_access<model::referring_segment<ConstOrNonConstPoint>, 0, Dimension>
{
typedef model::referring_segment<ConstOrNonConstPoint> segment_type;
typedef typename geometry::coordinate_type<segment_type>::type coordinate_type;
static inline coordinate_type get(segment_type const& s)
{
return geometry::get<Dimension>(s.first);
}
static inline void set(segment_type& s, coordinate_type const& value)
{
geometry::set<Dimension>(s.first, value);
}
};
template <typename ConstOrNonConstPoint, std::size_t Dimension>
struct indexed_access<model::referring_segment<ConstOrNonConstPoint>, 1, Dimension>
{
typedef model::referring_segment<ConstOrNonConstPoint> segment_type;
typedef typename geometry::coordinate_type<segment_type>::type coordinate_type;
static inline coordinate_type get(segment_type const& s)
{
return geometry::get<Dimension>(s.second);
}
static inline void set(segment_type& s, coordinate_type const& value)
{
geometry::set<Dimension>(s.second, value);
}
};
} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS
}} // namespace geofeatures_boost::geometry
#endif // BOOST_GEOMETRY_GEOMETRIES_SEGMENT_HPP
| 28.484444 | 116 | 0.734904 | xarvey |
cb63dbbb63b473f3313b0958ccad47cb5bde1024 | 5,327 | cpp | C++ | theatre-maintenance/theatre-maintenance.cpp | APf0x/not-payed-job | 5124d73b7e0370a9445d62573ae4d42070bf3765 | [
"MIT"
] | null | null | null | theatre-maintenance/theatre-maintenance.cpp | APf0x/not-payed-job | 5124d73b7e0370a9445d62573ae4d42070bf3765 | [
"MIT"
] | null | null | null | theatre-maintenance/theatre-maintenance.cpp | APf0x/not-payed-job | 5124d73b7e0370a9445d62573ae4d42070bf3765 | [
"MIT"
] | null | null | null | #include <iostream>
#include <time.h>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
const int platea = 40;
const int galleria = 30;
int posti_platea_rimasti, prezzotot, posti_galleria_rimasti, opzioni, posti, da_pagare, giorni, da_reimborsare, posti_galleria_totali, posti_platea_totali;
prezzotot = 0;
da_pagare = 0;
cout << "posti platea: ";
cin >> posti_platea_rimasti;
cout << "posti galleria: ";
cin >> posti_galleria_rimasti;
posti_platea_totali = posti_platea_rimasti;
posti_galleria_totali = posti_galleria_rimasti;
while (true){
cout << "\n1. Acquisto \n2. Restituzione \n3. Totale incasso \n0. Esci \n";
cin >> opzioni;
switch (opzioni){
case 1:
cout << "\n0=platea \n1=galleria\n";
cin >> opzioni;
if (opzioni == 1){
cout << "quanti posti?: ";
cin >> posti;
if(posti_galleria_rimasti >= posti){
prezzotot = prezzotot + galleria*posti;
da_pagare = galleria * posti;
posti_galleria_rimasti = posti_galleria_rimasti - posti;
cout << da_pagare << " euro da pagare e " << posti_galleria_rimasti << " posti rimasti in galleria.\n";
}else{
cout << "non ci sono posti disponibili \n";
}
}else if( opzioni == 0){
cout << "quanti posti?: ";
cin >> posti;
if(posti_platea_rimasti >= posti){
prezzotot = prezzotot + platea*posti;
da_pagare = platea * posti;
posti_platea_rimasti = posti_platea_rimasti - posti;
cout << da_pagare << " euro da pagare e " << posti_platea_rimasti << " posti rimasti in platea.\n";
}else{
cout << "non ci sono posti disponibili \n";
}
}else{
cout << "hai messo in input l'opzione sbagliata \nrestarting programm...\n";
break;
}
break;
case 2:
//case 2 reimborso stai lavorando qui non dimenticarti coglione che sei qui 5 ore------------------------------------------------
cout << "in quanti giorni di anticipo hai comprato i biglietti?; \n";
cin >> giorni;
cout << "\nper dove li hai comprati \n0=platea \n1=galleria\n";
cin >> opzioni;
cout << "quanti posti da reimborsare?: ";
cin >> da_reimborsare;
if (opzioni == 1){
if (da_reimborsare <= posti_galleria_totali-posti_galleria_rimasti){
posti_galleria_rimasti = posti_galleria_rimasti + da_reimborsare;
if (giorni < 15 && giorni >= 1){
prezzotot = prezzotot-da_reimborsare*galleria/2;
cout << "hai ricevuto indietro il 50% ovvero "<< (da_reimborsare*galleria)/2 << "euro\n";
}
else{
prezzotot = prezzotot-da_reimborsare*galleria;
cout << "hai ricevuto indietro i tuoi "<< da_reimborsare*galleria << "euro\n";
}
}
else{
cout << "mi pare che tu stia cercando di fregarmi è il cio non mi piace.\nauto spegnimento...\n";
return 0;
}
}else if (opzioni == 0){
if (da_reimborsare <= posti_platea_totali-posti_platea_rimasti){
posti_platea_rimasti = posti_platea_rimasti + da_reimborsare;
if (giorni < 15 && giorni >= 1){
prezzotot = prezzotot-da_reimborsare*platea/2;
cout << "hai ricevuto indietro il 50% ovvero "<< (da_reimborsare*platea)/2 << "euro\n";
}
else{
prezzotot = prezzotot-da_reimborsare*platea;
cout << "hai ricevuto indietro i tuoi "<< da_reimborsare*platea << "euro\n";
}
}
else{
cout << "mi pare che tu stia cercando di fregarmi è il cio non mi piace.\nauto spegnimento...\n";
return 0;
}
}else{
cout << "credo tu abbia messo un opzione non esistente...\n";
}
break;
case 3:
cout << "l'incasso totale per oggi e di "<< prezzotot << " euro\n";
cout << "e i posti liberi sono " << posti_platea_rimasti << " nella platea e "<< posti_galleria_rimasti << " in galleria\n";
break;
case 0:
cout << "arivederci...\n";
return 0;
default:
cout << "you put in input somethink that is not in the given list try again.\n";
break;
}
}
} | 49.324074 | 159 | 0.46987 | APf0x |
cb65966298787fd15f405cce415078d52823c07a | 217 | hpp | C++ | include/Game/Statics/boostatk.hpp | Lucrecious/DungeonGame | 9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5 | [
"MIT"
] | null | null | null | include/Game/Statics/boostatk.hpp | Lucrecious/DungeonGame | 9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5 | [
"MIT"
] | null | null | null | include/Game/Statics/boostatk.hpp | Lucrecious/DungeonGame | 9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5 | [
"MIT"
] | null | null | null | #ifndef BOOSTATK_H
#define BOOSTATK_H
#include <Game/Statics/neteffect.hpp>
class BoostAtk : public NetEffect {
public:
const int atkBoost;
BoostAtk(Effect* effect);
int getAtkNet();
int getDefNet();
};
#endif
| 14.466667 | 37 | 0.741935 | Lucrecious |
cb6661b306786d729c95110b4f45fdcfba124237 | 4,218 | cpp | C++ | IMS/Predator.cpp | PrasekMatej/IMS-CellularAutomata | 0ca11dab7c33eec3aa9695e4bffe535a1abf1258 | [
"MIT"
] | null | null | null | IMS/Predator.cpp | PrasekMatej/IMS-CellularAutomata | 0ca11dab7c33eec3aa9695e4bffe535a1abf1258 | [
"MIT"
] | null | null | null | IMS/Predator.cpp | PrasekMatej/IMS-CellularAutomata | 0ca11dab7c33eec3aa9695e4bffe535a1abf1258 | [
"MIT"
] | null | null | null | #include "Predator.h"
#include "Vole.h"
#include <algorithm>
Predator::Predator(int height, int width, int successChance)
{
fedUntilGeneration = 0;
nextGenerationHeight = height;
nextGenerationWidth = width;
sucessChance = successChance;
}
void Predator::NextGeneration(std::vector<std::vector<std::unique_ptr<Cell>>>* field, unsigned generation, int height, int width)
{
nextGenerationHeight = height;
nextGenerationWidth = width;
GetDirection(field, generation);
}
CellTypes Predator::WhatAmI()
{
return CellTypes::Predator;
}
void Predator::ResolveCollision(std::unique_ptr<Cell>* colliderPtr, std::vector<std::vector<std::unique_ptr<Cell>>>* field)
{
auto collider = colliderPtr->get();
std::unique_ptr<Cell>* target;
switch (collider->WhatAmI())
{
// Copy it on neighbor cell
case CellTypes::Predator:
target = GetCellToPlace(field, collider);
if (target != nullptr)
target->get()->ResolveCollision(colliderPtr, field);
break;
// Do not copy
case CellTypes::Blank:
case CellTypes::MaleVole:
case CellTypes::FemaleVole:
case CellTypes::Poison:
default:
break;
}
}
std::unique_ptr<Cell>* Predator::GetCellToPlace(std::vector<std::vector<std::unique_ptr<Cell>>>* field, Cell* collider)
{
const int maxHeight = (*field).size() - 1;
const int maxWidth = (*field)[0].size() - 1;
std::unique_ptr<Cell>* toReturn = nullptr;
for (auto i = -1; i <= 1; ++i)
{
const auto height = i < 0 ? std::max(collider->nextGenerationHeight + i, 0) : std::min(collider->nextGenerationHeight + i, maxHeight);
for (auto j = -1; j <= 1; ++j)
{
const auto width = j < 0 ? std::max(collider->nextGenerationWidth + j, 0) : std::min(collider->nextGenerationWidth + j, maxWidth);
std::unique_ptr<Cell>* unique_ptr = &(*field)[height][width];
if (*unique_ptr == nullptr)
continue;
const auto type = unique_ptr->get()->WhatAmI();
if (type == CellTypes::Blank)
{
return &(*field)[height][width];
}
else if (type == CellTypes::MaleVole || type == CellTypes::FemaleVole)
{
toReturn = &(*field)[height][width];
}
else if (toReturn == nullptr && type == CellTypes::Poison)
{
toReturn = &(*field)[height][width];
}
}
}
return toReturn;
}
void Predator::GetDirection(std::vector<std::vector<std::unique_ptr<Cell>>>* field, unsigned generation)
{
const int maxHeight = (*field).size() - 1;
const int maxWidth = (*field)[0].size() - 1;
auto closestHeight = maxHeight;
auto closestWidth = maxWidth;
if (fedUntilGeneration <= generation)
{
for (auto i = -5; i <= 5; ++i)
{
const auto height = nextGenerationHeight + i;
if(height < 0 || height > maxHeight)
continue;
for (auto j = -5; j <= 5; ++j)
{
const auto width = nextGenerationWidth + j;
if(width < 0 || width > maxWidth)
continue;
std::unique_ptr<Cell>* cell = &(*field)[height][width];
if(*cell == nullptr)
continue;
const auto type = (*field)[height][width]->WhatAmI();
if (type == CellTypes::MaleVole || type == CellTypes::FemaleVole)
{
if (std::abs(closestHeight) > std::abs(i) && std::abs(closestWidth) > std::abs(j))
{
closestHeight = i;
closestWidth = j;
}
}
}
}
}
// vole found
if (closestHeight < maxHeight || closestWidth < maxWidth)
{
if (std::abs(closestHeight) <= 2 && std::abs(closestWidth) <= 2)
{
if ((rand() % 100) < sucessChance)
{
dynamic_cast<Vole*>((*field)[nextGenerationHeight + closestHeight][nextGenerationWidth + closestWidth].get())->WillDie = true;
fedUntilGeneration = generation + fedDuration;
}
else
{
fedUntilGeneration = generation + failedHuntRestorationDuration;
}
}
else
{
if (closestHeight < -2)
closestHeight = -2;
if (closestHeight > 2)
closestHeight = 2;
if (closestWidth < -2)
closestWidth = -2;
if (closestWidth > 2)
closestWidth = 2;
}
}
// no vole found
else
{
closestHeight = rand() % 5 - 2;
closestWidth = rand() % 5 - 2;
}
nextGenerationHeight += closestHeight;
nextGenerationWidth += closestWidth;
nextGenerationHeight = std::min(std::max(nextGenerationHeight, 0), maxHeight);
nextGenerationWidth = std::min(std::max(nextGenerationWidth, 0), maxWidth);
}
| 27.933775 | 136 | 0.655524 | PrasekMatej |
cb69d971adacb7dc682695c8b9eb5e815bca21cc | 2,529 | cpp | C++ | Part 4/src/C_NeuralNetwork.cpp | thatgamesguy/ai_experiments_1-ufos | 3256ac397996c3e677bcdfe9cbb55360bb9b2cad | [
"MIT"
] | 1 | 2019-12-03T13:12:33.000Z | 2019-12-03T13:12:33.000Z | Part 4/src/C_NeuralNetwork.cpp | thatgamesguy/ai_experiments-evolution | 3256ac397996c3e677bcdfe9cbb55360bb9b2cad | [
"MIT"
] | null | null | null | Part 4/src/C_NeuralNetwork.cpp | thatgamesguy/ai_experiments-evolution | 3256ac397996c3e677bcdfe9cbb55360bb9b2cad | [
"MIT"
] | null | null | null | #include "C_NeuralNetwork.hpp"
C_NeuralNetwork::C_NeuralNetwork(Object* owner) : Component(owner), maxMoveForce(1400.f), neuralNetwork(neuralNumOfInput, neuralNumOfHiddenLayers, neuralNumOfNeuronsInHiddenLayer, neuralNumOfOutput), windowSize(1920, 1080)
{
}
void C_NeuralNetwork::Awake()
{
velocity = owner->GetComponent<C_Velocity>();
sight = owner->GetComponent<C_Sight>();
}
void C_NeuralNetwork::Update(float deltaTime)
{
std::vector<float> neuralNetInput = BuildNetworkInput();
// Get output from neural network
std::vector<float> neuralNetOutput = neuralNetwork.GetOutput(neuralNetInput);
float x = neuralNetOutput[0];
float y = neuralNetOutput[1];
const sf::Vector2f move = sf::Vector2f(x, y) * maxMoveForce * deltaTime;
velocity->Set(move);
}
void C_NeuralNetwork::SetWindowSize(const sf::Vector2u& windowSize)
{
this->windowSize = windowSize;
}
const NeuralNetwork& C_NeuralNetwork::Get() const
{
return neuralNetwork;
}
std::vector<float> C_NeuralNetwork::BuildNetworkInput()
{
std::vector<float> networkInput;
for (int i = 0; i < neuralNumOfInput; i++)
{
networkInput.push_back(0.f);
}
std::shared_ptr<UFOData> closest = sight->GetClosest();
if(closest)
{
sf::Vector2f to = closest->heading / closest->distance;
networkInput[0] = to.x;
networkInput[1] = to.y;
// We need to convert the distance to a number between 0 and 1 to be used as input.
float normalisedDistance = closest->distance / sight->GetRadius();
// We want a higher number to represent a closer agent so we invert the number.
networkInput[2] = 1 - normalisedDistance;
const sf::Vector2f& pos = owner->transform->GetPosition();
float leftDistance = pos.x;
float topDistance = pos.y;
float rightDistance = fabs(windowSize.x - pos.x);
float bottomDistance = fabs(windowSize.y - pos.y);
networkInput[3] = 1 - (leftDistance / windowSize.x);
networkInput[4] = 1 - (rightDistance / windowSize.x);
networkInput[5] = 1 - (topDistance / windowSize.y);
networkInput[6] = 1 - (bottomDistance / windowSize.y);
// Could use below but found agents evolve quicker when using discrete values for each wall.
//networkInput[3] = pos.x / screenWidth;
//networkInput[4] = pos.y / screenHeight;
}
return networkInput;
}
| 30.841463 | 222 | 0.648478 | thatgamesguy |
cb6e5591edd9091deb27f24537beb8c64b90c738 | 1,723 | hh | C++ | CalorimeterGeom/inc/SquareMapper.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:00:12.000Z | 2021-06-25T00:00:12.000Z | CalorimeterGeom/inc/SquareMapper.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 125 | 2020-04-03T13:44:30.000Z | 2021-10-15T21:29:57.000Z | CalorimeterGeom/inc/SquareMapper.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 2 | 2019-10-14T17:46:58.000Z | 2020-03-30T21:05:15.000Z | #ifndef CalorimeterGeom_SqaureMapper_hh
#define CalorimeterGeom_SqaureMapper_hh
#include "CalorimeterGeom/inc/CrystalMapper.hh"
#include "CLHEP/Vector/TwoVector.h"
#include "CLHEP/Vector/ThreeVector.h"
#include <vector>
namespace mu2e {
class SquLK {
public:
SquLK() : l_(0),k_(0) {}
SquLK(int l, int k) : l_(l),k_(k) {}
void add(const SquLK &x) {l_+=x.l_;k_+=x.k_;}
int l_;
int k_;
};
class SquareMapper : public CrystalMapper {
public:
SquareMapper();
virtual ~SquareMapper() {};
virtual int nCrystalMax(int maxRing) const {return (2*maxRing+1)*(2*maxRing+1);}
virtual CLHEP::Hep2Vector xyFromIndex(int thisIndex) const;
virtual int indexFromXY(double x, double y) const;
virtual int indexFromRowCol(int nRow, int nCol) const;
virtual bool isInsideCrystal(double x, double y,
const CLHEP::Hep3Vector& pos,
const CLHEP::Hep3Vector& size) const;
virtual std::vector<int> neighbors(int thisIndex, int level=1) const;
virtual const std::vector<double>& apexX() const {return apexY_;}
virtual const std::vector<double>& apexY() const {return apexY_;}
private:
SquLK lk(int index) const;
int index(const SquLK &lk) const;
int ring(const SquLK &lk) const;
std::vector<SquLK> step_;
std::vector<double> apexX_;
std::vector<double> apexY_;
};
}
#endif
| 26.507692 | 117 | 0.542658 | bonventre |
cb727420521be1b0f18c8ce0be2d31a5884d420e | 30,824 | cpp | C++ | src/alxr_engine/graphicsplugin_d3d12.cpp | korejan/ALVR-OpenXR-Engine | 9bdd6f73d881e46835dfc9af892e9a4184242764 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Unlicense"
] | null | null | null | src/alxr_engine/graphicsplugin_d3d12.cpp | korejan/ALVR-OpenXR-Engine | 9bdd6f73d881e46835dfc9af892e9a4184242764 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Unlicense"
] | 1 | 2022-02-20T16:14:51.000Z | 2022-02-20T16:14:51.000Z | src/alxr_engine/graphicsplugin_d3d12.cpp | korejan/ALVR-OpenXR-Engine | 9bdd6f73d881e46835dfc9af892e9a4184242764 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Unlicense"
] | null | null | null | // Copyright (c) 2017-2022, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
#include "pch.h"
#include "common.h"
#include "geometry.h"
#include "graphicsplugin.h"
#if defined(XR_USE_GRAPHICS_API_D3D12) && !defined(MISSING_DIRECTX_COLORS)
#include <common/xr_linear.h>
#include <DirectXColors.h>
#include <D3Dcompiler.h>
#include "d3d_common.h"
using namespace Microsoft::WRL;
using namespace DirectX;
namespace {
void InitializeD3D12DeviceForAdapter(IDXGIAdapter1* adapter, D3D_FEATURE_LEVEL minimumFeatureLevel, ID3D12Device** device) {
#if !defined(NDEBUG)
ComPtr<ID3D12Debug> debugCtrl;
if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(ID3D12Debug), &debugCtrl))) {
debugCtrl->EnableDebugLayer();
}
#endif
CHECK_HRCMD(D3D12CreateDevice(adapter, minimumFeatureLevel, __uuidof(ID3D12Device), reinterpret_cast<void**>(device)));
}
template <uint32_t alignment>
constexpr uint32_t AlignTo(uint32_t n) {
static_assert((alignment & (alignment - 1)) == 0, "The alignment must be power-of-two");
return (n + alignment - 1) & ~(alignment - 1);
}
ComPtr<ID3D12Resource> CreateBuffer(ID3D12Device* d3d12Device, uint32_t size, D3D12_HEAP_TYPE heapType) {
D3D12_RESOURCE_STATES d3d12ResourceState;
if (heapType == D3D12_HEAP_TYPE_UPLOAD) {
d3d12ResourceState = D3D12_RESOURCE_STATE_GENERIC_READ;
size = AlignTo<D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT>(size);
} else {
d3d12ResourceState = D3D12_RESOURCE_STATE_COMMON;
}
D3D12_HEAP_PROPERTIES heapProp{};
heapProp.Type = heapType;
heapProp.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
heapProp.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
D3D12_RESOURCE_DESC buffDesc{};
buffDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffDesc.Alignment = 0;
buffDesc.Width = size;
buffDesc.Height = 1;
buffDesc.DepthOrArraySize = 1;
buffDesc.MipLevels = 1;
buffDesc.Format = DXGI_FORMAT_UNKNOWN;
buffDesc.SampleDesc.Count = 1;
buffDesc.SampleDesc.Quality = 0;
buffDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
buffDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
ComPtr<ID3D12Resource> buffer;
CHECK_HRCMD(d3d12Device->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &buffDesc, d3d12ResourceState, nullptr,
__uuidof(ID3D12Resource),
reinterpret_cast<void**>(buffer.ReleaseAndGetAddressOf())));
return buffer;
}
class SwapchainImageContext {
public:
std::vector<XrSwapchainImageBaseHeader*> Create(ID3D12Device* d3d12Device, uint32_t capacity) {
m_d3d12Device = d3d12Device;
m_swapchainImages.resize(capacity);
std::vector<XrSwapchainImageBaseHeader*> bases(capacity);
for (uint32_t i = 0; i < capacity; ++i) {
m_swapchainImages[i] = {XR_TYPE_SWAPCHAIN_IMAGE_D3D12_KHR};
bases[i] = reinterpret_cast<XrSwapchainImageBaseHeader*>(&m_swapchainImages[i]);
}
CHECK_HRCMD(m_d3d12Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
reinterpret_cast<void**>(m_commandAllocator.ReleaseAndGetAddressOf())));
m_viewProjectionCBuffer = CreateBuffer(m_d3d12Device, sizeof(ViewProjectionConstantBuffer), D3D12_HEAP_TYPE_UPLOAD);
return bases;
}
uint32_t ImageIndex(const XrSwapchainImageBaseHeader* swapchainImageHeader) {
auto p = reinterpret_cast<const XrSwapchainImageD3D12KHR*>(swapchainImageHeader);
return (uint32_t)(p - &m_swapchainImages[0]);
}
ID3D12Resource* GetDepthStencilTexture(ID3D12Resource* colorTexture) {
if (!m_depthStencilTexture) {
// This back-buffer has no corresponding depth-stencil texture, so create one with matching dimensions.
const D3D12_RESOURCE_DESC colorDesc = colorTexture->GetDesc();
D3D12_HEAP_PROPERTIES heapProp{};
heapProp.Type = D3D12_HEAP_TYPE_DEFAULT;
heapProp.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
heapProp.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
D3D12_RESOURCE_DESC depthDesc{};
depthDesc.Dimension = colorDesc.Dimension;
depthDesc.Alignment = colorDesc.Alignment;
depthDesc.Width = colorDesc.Width;
depthDesc.Height = colorDesc.Height;
depthDesc.DepthOrArraySize = colorDesc.DepthOrArraySize;
depthDesc.MipLevels = 1;
depthDesc.Format = DXGI_FORMAT_R32_TYPELESS;
depthDesc.SampleDesc.Count = 1;
depthDesc.Layout = colorDesc.Layout;
depthDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
D3D12_CLEAR_VALUE clearValue{};
clearValue.DepthStencil.Depth = 1.0f;
clearValue.Format = DXGI_FORMAT_D32_FLOAT;
CHECK_HRCMD(m_d3d12Device->CreateCommittedResource(
&heapProp, D3D12_HEAP_FLAG_NONE, &depthDesc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clearValue,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(m_depthStencilTexture.ReleaseAndGetAddressOf())));
}
return m_depthStencilTexture.Get();
}
ID3D12CommandAllocator* GetCommandAllocator() const { return m_commandAllocator.Get(); }
uint64_t GetFrameFenceValue() const { return m_fenceValue; }
void SetFrameFenceValue(uint64_t fenceValue) { m_fenceValue = fenceValue; }
void ResetCommandAllocator() { CHECK_HRCMD(m_commandAllocator->Reset()); }
void RequestModelCBuffer(uint32_t requiredSize) {
if (!m_modelCBuffer || (requiredSize > m_modelCBuffer->GetDesc().Width)) {
m_modelCBuffer = CreateBuffer(m_d3d12Device, requiredSize, D3D12_HEAP_TYPE_UPLOAD);
}
}
ID3D12Resource* GetModelCBuffer() const { return m_modelCBuffer.Get(); }
ID3D12Resource* GetViewProjectionCBuffer() const { return m_viewProjectionCBuffer.Get(); }
private:
ID3D12Device* m_d3d12Device{nullptr};
std::vector<XrSwapchainImageD3D12KHR> m_swapchainImages;
ComPtr<ID3D12CommandAllocator> m_commandAllocator;
ComPtr<ID3D12Resource> m_depthStencilTexture;
ComPtr<ID3D12Resource> m_modelCBuffer;
ComPtr<ID3D12Resource> m_viewProjectionCBuffer;
uint64_t m_fenceValue = 0;
};
struct D3D12GraphicsPlugin : public IGraphicsPlugin {
D3D12GraphicsPlugin(const std::shared_ptr<Options>&, std::shared_ptr<IPlatformPlugin>)
: m_vertexShaderBytes(CompileShader(ShaderHlsl, "MainVS", "vs_5_1")),
m_pixelShaderBytes(CompileShader(ShaderHlsl, "MainPS", "ps_5_1")) {}
~D3D12GraphicsPlugin() override { CloseHandle(m_fenceEvent); }
std::vector<std::string> GetInstanceExtensions() const override { return {XR_KHR_D3D12_ENABLE_EXTENSION_NAME}; }
void InitializeDevice(XrInstance instance, XrSystemId systemId) override {
PFN_xrGetD3D12GraphicsRequirementsKHR pfnGetD3D12GraphicsRequirementsKHR = nullptr;
CHECK_XRCMD(xrGetInstanceProcAddr(instance, "xrGetD3D12GraphicsRequirementsKHR",
reinterpret_cast<PFN_xrVoidFunction*>(&pfnGetD3D12GraphicsRequirementsKHR)));
// Create the D3D12 device for the adapter associated with the system.
XrGraphicsRequirementsD3D12KHR graphicsRequirements{XR_TYPE_GRAPHICS_REQUIREMENTS_D3D12_KHR};
CHECK_XRCMD(pfnGetD3D12GraphicsRequirementsKHR(instance, systemId, &graphicsRequirements));
const ComPtr<IDXGIAdapter1> adapter = GetAdapter(graphicsRequirements.adapterLuid);
// Create a list of feature levels which are both supported by the OpenXR runtime and this application.
InitializeD3D12DeviceForAdapter(adapter.Get(), graphicsRequirements.minFeatureLevel, m_device.ReleaseAndGetAddressOf());
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
CHECK_HRCMD(m_device->CreateCommandQueue(&queueDesc, __uuidof(ID3D12CommandQueue),
reinterpret_cast<void**>(m_cmdQueue.ReleaseAndGetAddressOf())));
InitializeResources();
m_graphicsBinding.device = m_device.Get();
m_graphicsBinding.queue = m_cmdQueue.Get();
}
void InitializeResources() {
{
D3D12_DESCRIPTOR_HEAP_DESC heapDesc{};
heapDesc.NumDescriptors = 1;
heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
CHECK_HRCMD(m_device->CreateDescriptorHeap(&heapDesc, __uuidof(ID3D12DescriptorHeap),
reinterpret_cast<void**>(m_rtvHeap.ReleaseAndGetAddressOf())));
}
{
D3D12_DESCRIPTOR_HEAP_DESC heapDesc{};
heapDesc.NumDescriptors = 1;
heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
CHECK_HRCMD(m_device->CreateDescriptorHeap(&heapDesc, __uuidof(ID3D12DescriptorHeap),
reinterpret_cast<void**>(m_dsvHeap.ReleaseAndGetAddressOf())));
}
D3D12_ROOT_PARAMETER rootParams[2];
rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParams[0].Descriptor.ShaderRegister = 0;
rootParams[0].Descriptor.RegisterSpace = 0;
rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParams[1].Descriptor.ShaderRegister = 1;
rootParams[1].Descriptor.RegisterSpace = 0;
rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc{};
rootSignatureDesc.NumParameters = (UINT)ArraySize(rootParams);
rootSignatureDesc.pParameters = rootParams;
rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
ComPtr<ID3DBlob> rootSignatureBlob;
ComPtr<ID3DBlob> error;
CHECK_HRCMD(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1_0,
rootSignatureBlob.ReleaseAndGetAddressOf(), error.ReleaseAndGetAddressOf()));
CHECK_HRCMD(m_device->CreateRootSignature(0, rootSignatureBlob->GetBufferPointer(), rootSignatureBlob->GetBufferSize(),
__uuidof(ID3D12RootSignature),
reinterpret_cast<void**>(m_rootSignature.ReleaseAndGetAddressOf())));
SwapchainImageContext initializeContext;
std::vector<XrSwapchainImageBaseHeader*> _ = initializeContext.Create(m_device.Get(), 1);
ComPtr<ID3D12GraphicsCommandList> cmdList;
CHECK_HRCMD(m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, initializeContext.GetCommandAllocator(), nullptr,
__uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(cmdList.ReleaseAndGetAddressOf())));
ComPtr<ID3D12Resource> cubeVertexBufferUpload;
m_cubeVertexBuffer = CreateBuffer(m_device.Get(), sizeof(Geometry::c_cubeVertices), D3D12_HEAP_TYPE_DEFAULT);
{
cubeVertexBufferUpload = CreateBuffer(m_device.Get(), sizeof(Geometry::c_cubeVertices), D3D12_HEAP_TYPE_UPLOAD);
void* data;
const D3D12_RANGE readRange{0, 0};
CHECK_HRCMD(cubeVertexBufferUpload->Map(0, &readRange, &data));
memcpy(data, Geometry::c_cubeVertices, sizeof(Geometry::c_cubeVertices));
cubeVertexBufferUpload->Unmap(0, nullptr);
cmdList->CopyBufferRegion(m_cubeVertexBuffer.Get(), 0, cubeVertexBufferUpload.Get(), 0,
sizeof(Geometry::c_cubeVertices));
}
ComPtr<ID3D12Resource> cubeIndexBufferUpload;
m_cubeIndexBuffer = CreateBuffer(m_device.Get(), sizeof(Geometry::c_cubeIndices), D3D12_HEAP_TYPE_DEFAULT);
{
cubeIndexBufferUpload = CreateBuffer(m_device.Get(), sizeof(Geometry::c_cubeIndices), D3D12_HEAP_TYPE_UPLOAD);
void* data;
const D3D12_RANGE readRange{0, 0};
CHECK_HRCMD(cubeIndexBufferUpload->Map(0, &readRange, &data));
memcpy(data, Geometry::c_cubeIndices, sizeof(Geometry::c_cubeIndices));
cubeIndexBufferUpload->Unmap(0, nullptr);
cmdList->CopyBufferRegion(m_cubeIndexBuffer.Get(), 0, cubeIndexBufferUpload.Get(), 0, sizeof(Geometry::c_cubeIndices));
}
CHECK_HRCMD(cmdList->Close());
ID3D12CommandList* cmdLists[] = {cmdList.Get()};
m_cmdQueue->ExecuteCommandLists((UINT)ArraySize(cmdLists), cmdLists);
CHECK_HRCMD(m_device->CreateFence(m_fenceValue, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
reinterpret_cast<void**>(m_fence.ReleaseAndGetAddressOf())));
m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
CHECK(m_fenceEvent != nullptr);
WaitForGpu();
}
int64_t SelectColorSwapchainFormat(const std::vector<int64_t>& runtimeFormats) const override {
// List of supported color swapchain formats.
constexpr DXGI_FORMAT SupportedColorSwapchainFormats[] = {
DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
};
auto swapchainFormatIt =
std::find_first_of(runtimeFormats.begin(), runtimeFormats.end(), std::begin(SupportedColorSwapchainFormats),
std::end(SupportedColorSwapchainFormats));
if (swapchainFormatIt == runtimeFormats.end()) {
THROW("No runtime swapchain format supported for color swapchain");
}
return *swapchainFormatIt;
}
const XrBaseInStructure* GetGraphicsBinding() const override {
return reinterpret_cast<const XrBaseInStructure*>(&m_graphicsBinding);
}
std::vector<XrSwapchainImageBaseHeader*> AllocateSwapchainImageStructs(
uint32_t capacity, const XrSwapchainCreateInfo& /*swapchainCreateInfo*/) override {
// Allocate and initialize the buffer of image structs (must be sequential in memory for xrEnumerateSwapchainImages).
// Return back an array of pointers to each swapchain image struct so the consumer doesn't need to know the type/size.
m_swapchainImageContexts.emplace_back();
SwapchainImageContext& swapchainImageContext = m_swapchainImageContexts.back();
std::vector<XrSwapchainImageBaseHeader*> bases = swapchainImageContext.Create(m_device.Get(), capacity);
// Map every swapchainImage base pointer to this context
for (auto& base : bases) {
m_swapchainImageContextMap[base] = &swapchainImageContext;
}
return bases;
}
ID3D12PipelineState* GetOrCreatePipelineState(DXGI_FORMAT swapchainFormat) {
auto iter = m_pipelineStates.find(swapchainFormat);
if (iter != m_pipelineStates.end()) {
return iter->second.Get();
}
const D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT,
D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
0},
};
D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineStateDesc{};
pipelineStateDesc.pRootSignature = m_rootSignature.Get();
pipelineStateDesc.VS = {m_vertexShaderBytes->GetBufferPointer(), m_vertexShaderBytes->GetBufferSize()};
pipelineStateDesc.PS = {m_pixelShaderBytes->GetBufferPointer(), m_pixelShaderBytes->GetBufferSize()};
{
pipelineStateDesc.BlendState.AlphaToCoverageEnable = false;
pipelineStateDesc.BlendState.IndependentBlendEnable = false;
for (size_t i = 0; i < ArraySize(pipelineStateDesc.BlendState.RenderTarget); ++i) {
pipelineStateDesc.BlendState.RenderTarget[i].BlendEnable = false;
pipelineStateDesc.BlendState.RenderTarget[i].SrcBlend = D3D12_BLEND_ONE;
pipelineStateDesc.BlendState.RenderTarget[i].DestBlend = D3D12_BLEND_ZERO;
pipelineStateDesc.BlendState.RenderTarget[i].BlendOp = D3D12_BLEND_OP_ADD;
pipelineStateDesc.BlendState.RenderTarget[i].SrcBlendAlpha = D3D12_BLEND_ONE;
pipelineStateDesc.BlendState.RenderTarget[i].DestBlendAlpha = D3D12_BLEND_ZERO;
pipelineStateDesc.BlendState.RenderTarget[i].BlendOpAlpha = D3D12_BLEND_OP_ADD;
pipelineStateDesc.BlendState.RenderTarget[i].LogicOp = D3D12_LOGIC_OP_NOOP;
pipelineStateDesc.BlendState.RenderTarget[i].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
}
}
pipelineStateDesc.SampleMask = 0xFFFFFFFF;
{
pipelineStateDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
pipelineStateDesc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK;
pipelineStateDesc.RasterizerState.FrontCounterClockwise = FALSE;
pipelineStateDesc.RasterizerState.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
pipelineStateDesc.RasterizerState.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
pipelineStateDesc.RasterizerState.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
pipelineStateDesc.RasterizerState.DepthClipEnable = TRUE;
pipelineStateDesc.RasterizerState.MultisampleEnable = FALSE;
pipelineStateDesc.RasterizerState.AntialiasedLineEnable = FALSE;
pipelineStateDesc.RasterizerState.ForcedSampleCount = 0;
pipelineStateDesc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
}
{
pipelineStateDesc.DepthStencilState.DepthEnable = TRUE;
pipelineStateDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
pipelineStateDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
pipelineStateDesc.DepthStencilState.StencilEnable = FALSE;
pipelineStateDesc.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
pipelineStateDesc.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
pipelineStateDesc.DepthStencilState.FrontFace = pipelineStateDesc.DepthStencilState.BackFace = {
D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS};
}
{
pipelineStateDesc.InputLayout.pInputElementDescs = inputElementDescs;
pipelineStateDesc.InputLayout.NumElements = (UINT)ArraySize(inputElementDescs);
}
pipelineStateDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF;
pipelineStateDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
pipelineStateDesc.NumRenderTargets = 1;
pipelineStateDesc.RTVFormats[0] = swapchainFormat;
pipelineStateDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
pipelineStateDesc.SampleDesc = {1, 0};
pipelineStateDesc.NodeMask = 0;
pipelineStateDesc.CachedPSO = {nullptr, 0};
pipelineStateDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
ComPtr<ID3D12PipelineState> pipelineState;
CHECK_HRCMD(m_device->CreateGraphicsPipelineState(&pipelineStateDesc, __uuidof(ID3D12PipelineState),
reinterpret_cast<void**>(pipelineState.ReleaseAndGetAddressOf())));
ID3D12PipelineState* pipelineStateRaw = pipelineState.Get();
m_pipelineStates.emplace(swapchainFormat, std::move(pipelineState));
return pipelineStateRaw;
}
void RenderView(const XrCompositionLayerProjectionView& layerView, const XrSwapchainImageBaseHeader* swapchainImage,
int64_t swapchainFormat, const std::vector<Cube>& cubes) override {
CHECK(layerView.subImage.imageArrayIndex == 0); // Texture arrays not supported.
auto& swapchainContext = *m_swapchainImageContextMap[swapchainImage];
CpuWaitForFence(swapchainContext.GetFrameFenceValue());
swapchainContext.ResetCommandAllocator();
ComPtr<ID3D12GraphicsCommandList> cmdList;
CHECK_HRCMD(m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, swapchainContext.GetCommandAllocator(), nullptr,
__uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(cmdList.ReleaseAndGetAddressOf())));
ID3D12PipelineState* pipelineState = GetOrCreatePipelineState((DXGI_FORMAT)swapchainFormat);
cmdList->SetPipelineState(pipelineState);
cmdList->SetGraphicsRootSignature(m_rootSignature.Get());
ID3D12Resource* const colorTexture = reinterpret_cast<const XrSwapchainImageD3D12KHR*>(swapchainImage)->texture;
const D3D12_RESOURCE_DESC colorTextureDesc = colorTexture->GetDesc();
const D3D12_VIEWPORT viewport = {(float)layerView.subImage.imageRect.offset.x,
(float)layerView.subImage.imageRect.offset.y,
(float)layerView.subImage.imageRect.extent.width,
(float)layerView.subImage.imageRect.extent.height,
0,
1};
cmdList->RSSetViewports(1, &viewport);
const D3D12_RECT scissorRect = {layerView.subImage.imageRect.offset.x, layerView.subImage.imageRect.offset.y,
layerView.subImage.imageRect.offset.x + layerView.subImage.imageRect.extent.width,
layerView.subImage.imageRect.offset.y + layerView.subImage.imageRect.extent.height};
cmdList->RSSetScissorRects(1, &scissorRect);
// Create RenderTargetView with original swapchain format (swapchain is typeless).
D3D12_CPU_DESCRIPTOR_HANDLE renderTargetView = m_rtvHeap->GetCPUDescriptorHandleForHeapStart();
D3D12_RENDER_TARGET_VIEW_DESC renderTargetViewDesc{};
renderTargetViewDesc.Format = (DXGI_FORMAT)swapchainFormat;
if (colorTextureDesc.DepthOrArraySize > 1) {
if (colorTextureDesc.SampleDesc.Count > 1) {
renderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
renderTargetViewDesc.Texture2DMSArray.ArraySize = colorTextureDesc.DepthOrArraySize;
} else {
renderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
renderTargetViewDesc.Texture2DArray.ArraySize = colorTextureDesc.DepthOrArraySize;
}
} else {
if (colorTextureDesc.SampleDesc.Count > 1) {
renderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
} else {
renderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
}
}
m_device->CreateRenderTargetView(colorTexture, &renderTargetViewDesc, renderTargetView);
ID3D12Resource* depthStencilTexture = swapchainContext.GetDepthStencilTexture(colorTexture);
const D3D12_RESOURCE_DESC depthStencilTextureDesc = depthStencilTexture->GetDesc();
D3D12_CPU_DESCRIPTOR_HANDLE depthStencilView = m_dsvHeap->GetCPUDescriptorHandleForHeapStart();
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc{};
depthStencilViewDesc.Format = DXGI_FORMAT_D32_FLOAT;
if (depthStencilTextureDesc.DepthOrArraySize > 1) {
if (depthStencilTextureDesc.SampleDesc.Count > 1) {
depthStencilViewDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
depthStencilViewDesc.Texture2DMSArray.ArraySize = colorTextureDesc.DepthOrArraySize;
} else {
depthStencilViewDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
depthStencilViewDesc.Texture2DArray.ArraySize = colorTextureDesc.DepthOrArraySize;
}
} else {
if (depthStencilTextureDesc.SampleDesc.Count > 1) {
depthStencilViewDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
} else {
depthStencilViewDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
}
}
m_device->CreateDepthStencilView(depthStencilTexture, &depthStencilViewDesc, depthStencilView);
// Clear swapchain and depth buffer. NOTE: This will clear the entire render target view, not just the specified view.
// TODO: Do not clear to a color when using a pass-through view configuration.
cmdList->ClearRenderTargetView(renderTargetView, DirectX::Colors::DarkSlateGray, 0, nullptr);
cmdList->ClearDepthStencilView(depthStencilView, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
D3D12_CPU_DESCRIPTOR_HANDLE renderTargets[] = {renderTargetView};
cmdList->OMSetRenderTargets((UINT)ArraySize(renderTargets), renderTargets, true, &depthStencilView);
const XMMATRIX spaceToView = XMMatrixInverse(nullptr, LoadXrPose(layerView.pose));
XrMatrix4x4f projectionMatrix;
XrMatrix4x4f_CreateProjectionFov(&projectionMatrix, GRAPHICS_D3D, layerView.fov, 0.05f, 100.0f);
// Set shaders and constant buffers.
ID3D12Resource* viewProjectionCBuffer = swapchainContext.GetViewProjectionCBuffer();
ViewProjectionConstantBuffer viewProjection;
XMStoreFloat4x4(&viewProjection.ViewProjection, XMMatrixTranspose(spaceToView * LoadXrMatrix(projectionMatrix)));
{
void* data;
const D3D12_RANGE readRange{0, 0};
CHECK_HRCMD(viewProjectionCBuffer->Map(0, &readRange, &data));
memcpy(data, &viewProjection, sizeof(viewProjection));
viewProjectionCBuffer->Unmap(0, nullptr);
}
cmdList->SetGraphicsRootConstantBufferView(1, viewProjectionCBuffer->GetGPUVirtualAddress());
// Set cube primitive data.
if (cubes.size() > 0) {
const D3D12_VERTEX_BUFFER_VIEW vertexBufferView[] = {
{m_cubeVertexBuffer->GetGPUVirtualAddress(), sizeof(Geometry::c_cubeVertices), sizeof(Geometry::Vertex)} };
cmdList->IASetVertexBuffers(0, (UINT)ArraySize(vertexBufferView), vertexBufferView);
D3D12_INDEX_BUFFER_VIEW indexBufferView{ m_cubeIndexBuffer->GetGPUVirtualAddress(), sizeof(Geometry::c_cubeIndices),
DXGI_FORMAT_R16_UINT };
cmdList->IASetIndexBuffer(&indexBufferView);
cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
constexpr uint32_t cubeCBufferSize = AlignTo<D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT>(sizeof(ModelConstantBuffer));
swapchainContext.RequestModelCBuffer(static_cast<uint32_t>(cubeCBufferSize * cubes.size()));
ID3D12Resource* modelCBuffer = swapchainContext.GetModelCBuffer();
// Render each cube
uint32_t offset = 0;
for (const Cube& cube : cubes) {
// Compute and update the model transform.
ModelConstantBuffer model;
XMStoreFloat4x4(&model.Model,
XMMatrixTranspose(XMMatrixScaling(cube.Scale.x, cube.Scale.y, cube.Scale.z) * LoadXrPose(cube.Pose)));
{
uint8_t* data;
const D3D12_RANGE readRange{ 0, 0 };
CHECK_HRCMD(modelCBuffer->Map(0, &readRange, reinterpret_cast<void**>(&data)));
memcpy(data + offset, &model, sizeof(model));
const D3D12_RANGE writeRange{ offset, offset + cubeCBufferSize };
modelCBuffer->Unmap(0, &writeRange);
}
cmdList->SetGraphicsRootConstantBufferView(0, modelCBuffer->GetGPUVirtualAddress() + offset);
// Draw the cube.
cmdList->DrawIndexedInstanced((UINT)ArraySize(Geometry::c_cubeIndices), 1, 0, 0, 0);
offset += cubeCBufferSize;
}
}
CHECK_HRCMD(cmdList->Close());
ID3D12CommandList* cmdLists[] = {cmdList.Get()};
m_cmdQueue->ExecuteCommandLists((UINT)ArraySize(cmdLists), cmdLists);
SignalFence();
swapchainContext.SetFrameFenceValue(m_fenceValue);
}
void SignalFence() {
++m_fenceValue;
CHECK_HRCMD(m_cmdQueue->Signal(m_fence.Get(), m_fenceValue));
}
void CpuWaitForFence(uint64_t fenceValue) {
if (m_fence->GetCompletedValue() < fenceValue) {
CHECK_HRCMD(m_fence->SetEventOnCompletion(fenceValue, m_fenceEvent));
const uint32_t retVal = WaitForSingleObjectEx(m_fenceEvent, INFINITE, FALSE);
if (retVal != WAIT_OBJECT_0) {
CHECK_HRCMD(E_FAIL);
}
}
}
void WaitForGpu() {
SignalFence();
CpuWaitForFence(m_fenceValue);
}
private:
const ComPtr<ID3DBlob> m_vertexShaderBytes;
const ComPtr<ID3DBlob> m_pixelShaderBytes;
ComPtr<ID3D12Device> m_device;
ComPtr<ID3D12CommandQueue> m_cmdQueue;
ComPtr<ID3D12Fence> m_fence;
uint64_t m_fenceValue = 0;
HANDLE m_fenceEvent = INVALID_HANDLE_VALUE;
std::list<SwapchainImageContext> m_swapchainImageContexts;
std::map<const XrSwapchainImageBaseHeader*, SwapchainImageContext*> m_swapchainImageContextMap;
XrGraphicsBindingD3D12KHR m_graphicsBinding{XR_TYPE_GRAPHICS_BINDING_D3D12_KHR};
ComPtr<ID3D12RootSignature> m_rootSignature;
std::map<DXGI_FORMAT, ComPtr<ID3D12PipelineState>> m_pipelineStates;
ComPtr<ID3D12Resource> m_cubeVertexBuffer;
ComPtr<ID3D12Resource> m_cubeIndexBuffer;
ComPtr<ID3D12DescriptorHeap> m_rtvHeap;
ComPtr<ID3D12DescriptorHeap> m_dsvHeap;
};
} // namespace
std::shared_ptr<IGraphicsPlugin> CreateGraphicsPlugin_D3D12(const std::shared_ptr<Options>& options,
std::shared_ptr<IPlatformPlugin> platformPlugin) {
return std::make_shared<D3D12GraphicsPlugin>(options, platformPlugin);
}
#endif
| 50.78089 | 134 | 0.690793 | korejan |
cb73a7a562513f2c8baede2d6eb758f43db1bd5b | 280 | cpp | C++ | search array element.cpp | 0ishita-jana/-dev-info-day1 | e6053be728856b3a92d3137bdfd30e16700f7d06 | [
"MIT"
] | null | null | null | search array element.cpp | 0ishita-jana/-dev-info-day1 | e6053be728856b3a92d3137bdfd30e16700f7d06 | [
"MIT"
] | null | null | null | search array element.cpp | 0ishita-jana/-dev-info-day1 | e6053be728856b3a92d3137bdfd30e16700f7d06 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<conio.h>
int main()
{
int n,i,s;
int a[]={2,3,5,9,6};
s=sizeof(a);
printf("enter the search element");
scanf("%d",&n);
for(i=0;i<s;i++)
{
if(a[i]==n)
{
printf("found%d",n);
return 0;
}
}
printf("not found");
return 0;
}
| 10 | 36 | 0.514286 | 0ishita-jana |
cb75217540a8625de58d257728eb649eb26dcbc7 | 6,618 | hpp | C++ | include/sprout/iterator/value_iterator.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/iterator/value_iterator.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/iterator/value_iterator.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_ITERATOR_VALUE_ITERATOR_HPP
#define SPROUT_ITERATOR_VALUE_ITERATOR_HPP
#include <iterator>
#include <utility>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/workaround/std/cstddef.hpp>
#include <sprout/limits.hpp>
#include <sprout/iterator/iterator.hpp>
#include <sprout/iterator/next.hpp>
#include <sprout/iterator/prev.hpp>
#include <sprout/iterator/distance.hpp>
#include <sprout/utility/value_holder/value_holder.hpp>
#include <sprout/utility/swap.hpp>
namespace sprout {
//
// value_iterator
//
template<typename T>
class value_iterator
: public sprout::iterator<
std::random_access_iterator_tag,
typename sprout::value_holder<T>::value_type,
std::ptrdiff_t,
typename sprout::value_holder<T>::mutable_or_const_pointer,
typename sprout::value_holder<T>::mutable_or_const_reference
>
{
public:
typedef T type;
typedef typename std::conditional<
std::is_reference<type>::value,
typename std::decay<type>::type const&,
typename std::decay<type>::type const
>::type const_type;
private:
typedef sprout::iterator<
std::random_access_iterator_tag,
typename sprout::value_holder<T>::value_type,
std::ptrdiff_t,
typename sprout::value_holder<T>::mutable_or_const_pointer,
typename sprout::value_holder<T>::mutable_or_const_reference
> base_type;
public:
typedef typename base_type::iterator_category iterator_category;
typedef typename base_type::value_type value_type;
typedef typename base_type::difference_type difference_type;
typedef typename base_type::pointer pointer;
typedef typename base_type::reference reference;
private:
sprout::value_holder<T> holder_;
difference_type index_;
private:
SPROUT_CONSTEXPR value_iterator(sprout::value_holder<T> const& r, difference_type index)
: holder_(r), index_(index)
{}
public:
SPROUT_CONSTEXPR value_iterator()
: holder_(), index_()
{}
value_iterator(value_iterator const&) = default;
explicit SPROUT_CONSTEXPR value_iterator(
typename sprout::value_holder<T>::param_type p,
difference_type index = sprout::numeric_limits<difference_type>::max()
)
: holder_(p), index_(index)
{}
SPROUT_CONSTEXPR operator value_iterator<const_type>() const {
return value_iterator<const_type>(holder_.get(), index_);
}
SPROUT_CONSTEXPR difference_type index() const {
return index_;
}
SPROUT_CONSTEXPR value_iterator next() const {
return value_iterator(holder_, index_ - 1);
}
SPROUT_CONSTEXPR value_iterator prev() const {
return value_iterator(holder_, index_ + 1);
}
SPROUT_CXX14_CONSTEXPR void swap(value_iterator& other)
SPROUT_NOEXCEPT_IF_EXPR(sprout::swap(holder_, other.holder_))
{
sprout::swap(holder_, other.holder_);
sprout::swap(index_, other.index_);
}
SPROUT_CONSTEXPR reference operator*() const {
return holder_.get();
}
SPROUT_CONSTEXPR pointer operator->() const {
return holder_.get_pointer();
}
SPROUT_CXX14_CONSTEXPR value_iterator& operator++() {
value_iterator temp(next());
temp.swap(*this);
return *this;
}
SPROUT_CXX14_CONSTEXPR value_iterator operator++(int) {
value_iterator result(*this);
++*this;
return result;
}
SPROUT_CXX14_CONSTEXPR value_iterator& operator--() {
value_iterator temp(prev());
temp.swap(*this);
return *this;
}
SPROUT_CXX14_CONSTEXPR value_iterator operator--(int) {
value_iterator result(*this);
--*this;
return result;
}
SPROUT_CONSTEXPR value_iterator operator+(difference_type n) const {
return value_iterator(holder_, index_ - n);
}
SPROUT_CONSTEXPR value_iterator operator-(difference_type n) const {
return value_iterator(holder_, index_ + n);
}
SPROUT_CXX14_CONSTEXPR value_iterator& operator+=(difference_type n) {
value_iterator temp(holder_, index_ - n);
temp.swap(*this);
return *this;
}
SPROUT_CXX14_CONSTEXPR value_iterator& operator-=(difference_type n) {
value_iterator temp(holder_, index_ + n);
temp.swap(*this);
return *this;
}
SPROUT_CONSTEXPR reference operator[](difference_type) const {
return holder_.get();
}
};
template<typename T>
inline SPROUT_CONSTEXPR bool
operator==(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return lhs.index() == rhs.index();
}
template<typename T>
inline SPROUT_CONSTEXPR bool
operator!=(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return !(lhs == rhs);
}
template<typename T>
inline SPROUT_CONSTEXPR bool
operator<(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return rhs.index() < lhs.index();
}
template<typename T>
inline SPROUT_CONSTEXPR bool
operator>(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return rhs < lhs;
}
template<typename T>
inline SPROUT_CONSTEXPR bool
operator<=(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return !(rhs < lhs);
}
template<typename T>
inline SPROUT_CONSTEXPR bool
operator>=(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return !(lhs < rhs);
}
template<typename T>
inline SPROUT_CONSTEXPR typename sprout::value_iterator<T>::difference_type
operator-(sprout::value_iterator<T> const& lhs, sprout::value_iterator<T> const& rhs) {
return rhs.index() - lhs.index();
}
template<typename T>
inline SPROUT_CONSTEXPR sprout::value_iterator<T>
operator+(typename sprout::value_iterator<T>::difference_type n, sprout::value_iterator<T> const& it) {
return it + n;
}
//
// swap
//
template<typename T>
inline SPROUT_CXX14_CONSTEXPR void
swap(sprout::value_iterator<T>& lhs, sprout::value_iterator<T>& rhs)
SPROUT_NOEXCEPT_IF_EXPR(lhs.swap(rhs))
{
lhs.swap(rhs);
}
//
// iterator_next
//
template<typename T>
inline SPROUT_CONSTEXPR sprout::value_iterator<T>
iterator_next(sprout::value_iterator<T> const& it) {
return it.next();
}
//
// iterator_prev
//
template<typename T>
inline SPROUT_CONSTEXPR sprout::value_iterator<T>
iterator_prev(sprout::value_iterator<T> const& it) {
return it.prev();
}
} // namespace sprout
#endif // #ifndef SPROUT_ITERATOR_VALUE_ITERATOR_HPP
| 30.925234 | 104 | 0.722575 | thinkoid |
cb7d2f46c6dafe7ac4acec95c520cd9c3d9d1c8b | 4,884 | cpp | C++ | lumino/LuminoEngine/src/Tilemap/TilemapComponent.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoEngine/src/Tilemap/TilemapComponent.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 13 | 2020-03-23T20:36:44.000Z | 2022-02-28T11:07:32.000Z | lumino/LuminoEngine/src/Tilemap/TilemapComponent.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include "Internal.hpp"
#include <LuminoEngine/Scene/World.hpp>
#include <LuminoEngine/Scene/Level.hpp>
#include <LuminoEngine/Tilemap/TilemapModel.hpp>
#include <LuminoEngine/Tilemap/TilemapComponent.hpp>
#include "TilemapPhysicsObject.hpp"
#include <LuminoEngine/Scene/WorldObject.hpp> // for WorldObjectTransform
#include <LuminoEngine/Rendering/RenderView.hpp> // for RenderViewPoint
// Test
#include <LuminoEngine/Tilemap/Tileset.hpp>
#include <LuminoEngine/Tilemap/TilemapLayer.hpp>
namespace ln {
//==============================================================================
// TilemapComponent
LN_OBJECT_IMPLEMENT(TilemapComponent, VisualComponent) {}
TilemapComponent::TilemapComponent()
{
}
TilemapComponent::~TilemapComponent()
{
}
void TilemapComponent::init()
{
VisualComponent::init();
}
TilemapModel* TilemapComponent::tilemapModel() const
{
return m_tilemapModel;
}
void TilemapComponent::setTilemapModel(TilemapModel* tilemapModel)
{
m_tilemapModel = tilemapModel;
}
bool TilemapComponent::intersectTile(const Ray& rayOnWorld, PointI* tilePoint)
{
if (!m_tilemapModel) return false;
Matrix worldInverse = Matrix::makeInverse(worldObject()->worldMatrix());
Ray localRay(Vector3::transformCoord(rayOnWorld.origin, worldInverse), Vector3::transformCoord(rayOnWorld.direction, worldInverse), rayOnWorld.distance);
TilemapLayer* layer = m_tilemapModel->layer(0);
// TODO: ひとまず、 Z- を正面とする
Plane plane(Vector3::Zero, -Vector3::UnitZ);
Vector3 pt;
if (plane.intersects(localRay, &pt)) {
if (pt.x < 0.0 || pt.y < 0.0) return false; // 小数切り捨てで、-0.99..~0.0 が 0 として扱われる問題の回避
// TODO: スケールを考慮したい
int x = static_cast<int>(pt.x);
int y = static_cast<int>(pt.y);
if (m_tilemapModel->isValidTilePosition(x, y)) {
if (tilePoint) {
tilePoint->x = x;
tilePoint->y = (layer->getHeight() - y) - 1;
}
return true;
}
}
return false;
}
void TilemapComponent::onStart()
{
m_rigidBody = makeObject<RigidBody2D>();
m_rigidBody->addCollisionShape(detail::TilemapPhysicsObject::createTilemapCollisionShape(m_tilemapModel));
// TODO: addPhysicsObject をどうにかする
//worldObject()->scene()->world()->physicsWorld2D()->addPhysicsObject(m_rigidBody);
// TODO: m_rigidBody->removeFromPhysicsWorld(); をどうにかする
LN_NOTIMPLEMENTED();
}
void TilemapComponent::onRender(RenderingContext* context)
{
Matrix worldInverse = Matrix::makeInverse(worldObject()->worldMatrix());
Matrix viewLocal = context->viewPoint()->worldMatrix * worldInverse;
#ifdef LN_COORD_RH
Matrix viewMatrix = Matrix::makeLookAtRH(viewLocal.position(), viewLocal.position() + viewLocal.front(), viewLocal.up());
#else
Matrix viewMatrix = Matrix::makeLookAtLH(viewLocal.position(), viewLocal.position() + viewLocal.front(), viewLocal.up());
#endif
ViewFrustum frustum(viewMatrix * context->viewPoint()->projMatrix);
// TODO: ひとまず、 Z- を正面とする
Plane plane(transrom()->position(), -transrom()->getFront());
// TODO: 原点と正面方向
Vector3 corners[8];
Vector3 pt;
frustum.getCornerPoints(corners);
// TileMap の平面とカメラの視錐台から描画するべき範囲を求める
detail::TilemapBounds bounds;
for (int i = 0; i < 4; ++i)
{
if (plane.intersects(corners[i], corners[i + 4], &pt))
{
// pt をそのまま使う
}
else
{
// XY 平面上での最遠点を求める
Vector2 pt2 = Vector2::normalize(corners[i + 4].xy() - corners[i].xy()) * context->viewPoint()->farClip;
pt = Vector3(pt2, 0);
}
if (i == 0)
{
bounds.l = pt.x;
bounds.t = pt.y;
bounds.r = pt.x;
bounds.b = pt.y;
}
else
{
bounds.l = std::min(bounds.l, pt.x);
bounds.r = std::max(bounds.r, pt.x);
bounds.t = std::max(bounds.t, pt.y);
bounds.b = std::min(bounds.b, pt.y);
}
}
m_tilemapModel->render(context, worldObject()->worldMatrix(), bounds);
}
void TilemapComponent::onRenderGizmo(RenderingContext* context)
{
if (m_tilemapModel) {
Vector2 tileSize = m_tilemapModel->tileSize();
int w = m_tilemapModel->width();
int h = m_tilemapModel->height();
float l = 0;
float r = tileSize.x * (w + 1);
float t = tileSize.y * (h + 1);
float b = 0;
for (int y = 0; y <= h; y++) {
float p = tileSize.y * y;
context->drawLine(Vector3(l, p, 0), Color::Orange, Vector3(r, p, 0), Color::Orange);
}
for (int x = 0; x <= w; x++) {
float p = tileSize.x * x;
context->drawLine(Vector3(p, t, 0), Color::Orange, Vector3(p, b, 0), Color::Orange);
}
}
}
//void TilemapComponent::serialize(Archive& ar)
//{
// VisualComponent::serialize(ar);
// ar & makeNVP(u"Model", m_tilemapModel);
//}
} // namespace ln
| 27.284916 | 154 | 0.63104 | GameDevery |
cb874bf5cc1827599310b925044154217cdc079e | 4,354 | cc | C++ | examples/memcached/server/MemcacheServer.cc | Itsposs/muduo | 90920bbad80e544da9a8a94b16ad8ab4bb66e652 | [
"BSD-3-Clause"
] | 10,948 | 2015-01-01T04:48:50.000Z | 2022-03-31T16:58:54.000Z | examples/memcached/server/MemcacheServer.cc | Itsposs/muduo | 90920bbad80e544da9a8a94b16ad8ab4bb66e652 | [
"BSD-3-Clause"
] | 351 | 2015-01-03T10:48:01.000Z | 2022-03-17T07:01:15.000Z | examples/memcached/server/MemcacheServer.cc | Itsposs/muduo | 90920bbad80e544da9a8a94b16ad8ab4bb66e652 | [
"BSD-3-Clause"
] | 4,994 | 2015-01-01T07:17:50.000Z | 2022-03-31T15:58:01.000Z | #include "examples/memcached/server/MemcacheServer.h"
#include "muduo/base/Atomic.h"
#include "muduo/base/Logging.h"
#include "muduo/net/EventLoop.h"
using namespace muduo;
using namespace muduo::net;
muduo::AtomicInt64 g_cas;
MemcacheServer::Options::Options()
{
memZero(this, sizeof(*this));
}
struct MemcacheServer::Stats
{
};
MemcacheServer::MemcacheServer(muduo::net::EventLoop* loop, const Options& options)
: loop_(loop),
options_(options),
startTime_(::time(NULL)-1),
server_(loop, InetAddress(options.tcpport), "muduo-memcached"),
stats_(new Stats)
{
server_.setConnectionCallback(
std::bind(&MemcacheServer::onConnection, this, _1));
}
MemcacheServer::~MemcacheServer() = default;
void MemcacheServer::start()
{
server_.start();
}
void MemcacheServer::stop()
{
loop_->runAfter(3.0, std::bind(&EventLoop::quit, loop_));
}
bool MemcacheServer::storeItem(const ItemPtr& item, const Item::UpdatePolicy policy, bool* exists)
{
assert(item->neededBytes() == 0);
MutexLock& mutex = shards_[item->hash() % kShards].mutex;
ItemMap& items = shards_[item->hash() % kShards].items;
MutexLockGuard lock(mutex);
ItemMap::const_iterator it = items.find(item);
*exists = it != items.end();
if (policy == Item::kSet)
{
item->setCas(g_cas.incrementAndGet());
if (*exists)
{
items.erase(it);
}
items.insert(item);
}
else
{
if (policy == Item::kAdd)
{
if (*exists)
{
return false;
}
else
{
item->setCas(g_cas.incrementAndGet());
items.insert(item);
}
}
else if (policy == Item::kReplace)
{
if (*exists)
{
item->setCas(g_cas.incrementAndGet());
items.erase(it);
items.insert(item);
}
else
{
return false;
}
}
else if (policy == Item::kAppend || policy == Item::kPrepend)
{
if (*exists)
{
const ConstItemPtr& oldItem = *it;
int newLen = static_cast<int>(item->valueLength() + oldItem->valueLength() - 2);
ItemPtr newItem(Item::makeItem(item->key(),
oldItem->flags(),
oldItem->rel_exptime(),
newLen,
g_cas.incrementAndGet()));
if (policy == Item::kAppend)
{
newItem->append(oldItem->value(), oldItem->valueLength() - 2);
newItem->append(item->value(), item->valueLength());
}
else
{
newItem->append(item->value(), item->valueLength() - 2);
newItem->append(oldItem->value(), oldItem->valueLength());
}
assert(newItem->neededBytes() == 0);
assert(newItem->endsWithCRLF());
items.erase(it);
items.insert(newItem);
}
else
{
return false;
}
}
else if (policy == Item::kCas)
{
if (*exists && (*it)->cas() == item->cas())
{
item->setCas(g_cas.incrementAndGet());
items.erase(it);
items.insert(item);
}
else
{
return false;
}
}
else
{
assert(false);
}
}
return true;
}
ConstItemPtr MemcacheServer::getItem(const ConstItemPtr& key) const
{
MutexLock& mutex = shards_[key->hash() % kShards].mutex;
const ItemMap& items = shards_[key->hash() % kShards].items;
MutexLockGuard lock(mutex);
ItemMap::const_iterator it = items.find(key);
return it != items.end() ? *it : ConstItemPtr();
}
bool MemcacheServer::deleteItem(const ConstItemPtr& key)
{
MutexLock& mutex = shards_[key->hash() % kShards].mutex;
ItemMap& items = shards_[key->hash() % kShards].items;
MutexLockGuard lock(mutex);
return items.erase(key) == 1;
}
void MemcacheServer::onConnection(const TcpConnectionPtr& conn)
{
if (conn->connected())
{
SessionPtr session(new Session(this, conn));
MutexLockGuard lock(mutex_);
assert(sessions_.find(conn->name()) == sessions_.end());
sessions_[conn->name()] = session;
// assert(sessions_.size() == stats_.current_conns);
}
else
{
MutexLockGuard lock(mutex_);
assert(sessions_.find(conn->name()) != sessions_.end());
sessions_.erase(conn->name());
// assert(sessions_.size() == stats_.current_conns);
}
}
| 24.88 | 98 | 0.585668 | Itsposs |
cb8e5c327cd825eee61da3415d443d59b8f81cf1 | 11,308 | cpp | C++ | test/test-200-types/sources/tools/types/common/degradate/test-degradate-new.cpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | null | null | null | test/test-200-types/sources/tools/types/common/degradate/test-degradate-new.cpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | 49 | 2021-02-20T12:08:15.000Z | 2021-05-07T19:59:08.000Z | test/test-200-types/sources/tools/types/common/degradate/test-degradate-new.cpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | null | null | null | // [2021y-02m-20d][18:40:18] Idrisov Denis R.
// [2021y-03m-17d][20:49:29] Idrisov Denis R.
#include <mygtest/modern.hpp>
#ifdef TEST_TOOLS_DEGRADATE
#include <tools/features.hpp>
#ifdef dHAS_USING_ALIAS
// #pragma message("build for msvc2013 (or newer) or other compiler")
#define dTEST_COMPONENT tools, types, common
#define dTEST_METHOD degradate
#define dTEST_TAG new
#include <tools/types/common.hpp>
#include <string>
//==============================================================================
//=== make_test ================================================================
namespace
{
#define make_test(type, etalon) \
static_assert( \
::std::is_same< \
::tools::degradate_t<type>, \
etalon \
>::value, \
"tools::degradate<" #type "> -> '" #etalon "'" \
) \
make_test(int , int);
make_test(const int , int);
make_test(const int&, int);
}//namespace
//==============================================================================
//=== stringed(char) ===========================================================
namespace
{
make_test(signed char , signed char );
make_test(unsigned char , unsigned char );
make_test(const char , char ); // 00
make_test(char , char ); // 01
make_test(const std::string&&, std::string ); // 02
make_test(std::string&& , std::string ); // 03
make_test(const std::string& , std::string ); // 04
make_test(std::string& , std::string ); // 05
make_test(const std::string , std::string ); // 06
make_test(std::string , std::string ); // 07
make_test(char*const&& , char* ); // 09
make_test(char*&& , char* ); // 10
make_test(char*const& , char* ); // 11
make_test(char*& , char* ); // 12
make_test(char*const , char* ); // 13
make_test(char* , char* ); // 14
make_test(const char*const&& , const char* ); // 15
make_test(const char*&& , const char* ); // 16
make_test(const char*const& , const char* ); // 17
make_test(const char*& , const char* ); // 18
make_test(const char*const , const char* ); // 19
make_test(const char* , const char* ); // 20
make_test(const char(&&)[255], char[255] ); // 21
make_test(char(&&)[255] , char[255] ); // 22
make_test(const char(&)[255] , char[255] ); // 23
make_test(char(&)[255] , char[255] ); // 24
make_test(const char[255] , char[255] ); // 25
make_test(char[255] , char[255] ); // 26
make_test(const char(&&)[] , char[] ); // 27
make_test(char(&&)[] , char[] ); // 28
make_test(const char(&)[] , char[] ); // 29
make_test(char(&)[] , char[] ); // 30
make_test(const char[] , char[] ); // 31
make_test(char[] , char[] ); // 32
#ifdef dHAS_ZERO_SIZE_ARRAY
dPRAGMA_PUSH_WARNING_ZERO_SIZE_ARRAY
make_test(const char(&&)[0] , char[0] ); // 33 invalid types
make_test(char(&&)[0] , char[0] ); // 34 invalid types
make_test(const char(&)[0] , char[0] ); // 35 invalid types
make_test(char(&)[0] , char[0] ); // 36 invalid types
make_test(const char[0] , char[0] ); // 37 invalid types
make_test(char[0] , char[0] ); // 38 invalid types
dPRAGMA_POP
#endif // !dHAS_ZERO_SIZE_ARRAY
}//namespace
//==============================================================================
//=== stringed(wchar_t) ========================================================
namespace
{
make_test(const wchar_t , wchar_t ); // 00
make_test(wchar_t , wchar_t ); // 01
make_test(const std::wstring&& , std::wstring ); // 02
make_test(std::wstring&& , std::wstring ); // 03
make_test(const std::wstring& , std::wstring ); // 04
make_test(std::wstring& , std::wstring ); // 05
make_test(const std::wstring , std::wstring ); // 06
make_test(std::wstring , std::wstring ); // 07
make_test(wchar_t*const&& , wchar_t* ); // 09
make_test(wchar_t*&& , wchar_t* ); // 10
make_test(wchar_t*const& , wchar_t* ); // 11
make_test(wchar_t*& , wchar_t* ); // 12
make_test(wchar_t*const , wchar_t* ); // 13
make_test(wchar_t* , wchar_t* ); // 14
make_test(const wchar_t*const&& , const wchar_t* ); // 15
make_test(const wchar_t*&& , const wchar_t* ); // 16
make_test(const wchar_t*const& , const wchar_t* ); // 17
make_test(const wchar_t*& , const wchar_t* ); // 18
make_test(const wchar_t*const , const wchar_t* ); // 19
make_test(const wchar_t* , const wchar_t* ); // 20
make_test(const wchar_t(&&)[255], wchar_t[255] ); // 21
make_test(wchar_t(&&)[255] , wchar_t[255] ); // 22
make_test(const wchar_t(&)[255] , wchar_t[255] ); // 23
make_test(wchar_t(&)[255] , wchar_t[255] ); // 24
make_test(const wchar_t[255] , wchar_t[255] ); // 25
make_test(wchar_t[255] , wchar_t[255] ); // 26
make_test(const wchar_t(&&)[] , wchar_t[] ); // 27
make_test(wchar_t(&&)[] , wchar_t[] ); // 28
make_test(const wchar_t(&)[] , wchar_t[] ); // 29
make_test(wchar_t(&)[] , wchar_t[] ); // 30
make_test(const wchar_t[] , wchar_t[] ); // 31
make_test(wchar_t[] , wchar_t[] ); // 32
#ifdef dHAS_ZERO_SIZE_ARRAY
dPRAGMA_PUSH_WARNING_ZERO_SIZE_ARRAY
make_test(const wchar_t(&&)[0] , wchar_t[0] ); // 33 invalid types
make_test(wchar_t(&&)[0] , wchar_t[0] ); // 34 invalid types
make_test(const wchar_t(&)[0] , wchar_t[0] ); // 35 invalid types
make_test(wchar_t(&)[0] , wchar_t[0] ); // 36 invalid types
make_test(const wchar_t[0] , wchar_t[0] ); // 37 invalid types
make_test(wchar_t[0] , wchar_t[0] ); // 38 invalid types
dPRAGMA_POP
#endif
} // namespace
//==============================================================================
//=== stringed(int) ============================================================
namespace
{
using string_t = std::basic_string<int>;
make_test(const int , int ); // 00
make_test(int , int ); // 01
make_test(const string_t&& , string_t ); // 02
make_test(string_t&& , string_t ); // 03
make_test(const string_t& , string_t ); // 04
make_test(string_t& , string_t ); // 05
make_test(const string_t , string_t ); // 06
make_test(string_t , string_t ); // 07
make_test(int*const&& , int* ); // 09
make_test(int*&& , int* ); // 10
make_test(int*const& , int* ); // 11
make_test(int*& , int* ); // 12
make_test(int*const , int* ); // 13
make_test(int* , int* ); // 14
make_test(const int*const&& , const int* ); // 15
make_test(const int*&& , const int* ); // 16
make_test(const int*const& , const int* ); // 17
make_test(const int*& , const int* ); // 18
make_test(const int*const , const int* ); // 19
make_test(const int* , const int* ); // 20
make_test(const int(&&)[255], int[255] ); // 21
make_test(int(&&)[255] , int[255] ); // 22
make_test(const int(&)[255] , int[255] ); // 23
make_test(int(&)[255] , int[255] ); // 24
make_test(const int[255] , int[255] ); // 25
make_test(int[255] , int[255] ); // 26
make_test(const int(&&)[] , int[] ); // 27
make_test(int(&&)[] , int[] ); // 28
make_test(const int(&)[] , int[] ); // 29
make_test(int(&)[] , int[] ); // 30
make_test(const int[] , int[] ); // 31
make_test(int[] , int[] ); // 32
#ifdef dHAS_ZERO_SIZE_ARRAY
dPRAGMA_PUSH_WARNING_ZERO_SIZE_ARRAY
make_test(const int(&&)[0] , int[0] ); // 33 invalid types
make_test(int(&&)[0] , int[0] ); // 34 invalid types
make_test(const int(&)[0] , int[0] ); // 35 invalid types
make_test(int(&)[0] , int[0] ); // 36 invalid types
make_test(const int[0] , int[0] ); // 37 invalid types
make_test(int[0] , int[0] ); // 38 invalid types
dPRAGMA_POP
#endif
} // namespace
//==============================================================================
//==============================================================================
TEST_COMPONENT(000){}
//==============================================================================
//==============================================================================
#endif // !dHAS_USING_ALIAS
#endif // !TEST_TOOLS_DEGRADATE
| 51.87156 | 88 | 0.380881 | Kartonagnick |
cb8e7b7b4c4fa36969fa6f859c1b810605ebbc74 | 657 | hpp | C++ | rlTut/Actor.hpp | vrum/rlTut | 0907b357c51a0b983ff8812f5c4887ecb185c9fa | [
"MIT"
] | null | null | null | rlTut/Actor.hpp | vrum/rlTut | 0907b357c51a0b983ff8812f5c4887ecb185c9fa | [
"MIT"
] | null | null | null | rlTut/Actor.hpp | vrum/rlTut | 0907b357c51a0b983ff8812f5c4887ecb185c9fa | [
"MIT"
] | null | null | null | class Actor {
public :
int x,y; // position on map
int ch; // ascii code
TCODColor col; // color
const char *name; // the actor's name
bool blocks; // can we walk on this actor?
Attacker *attacker; // something that deals damages
Destructible *destructible; // something that can be damaged
Ai *ai; // something self-updating
Pickable *pickable; // something that can be picked and used
Container *container; // something that can contain actors
Actor(int x, int y, int ch, const char *name, const TCODColor &col);
~Actor();
void update();
void render() const;
float getDistance(int cx, int cy) const;
};
| 32.85 | 70 | 0.668189 | vrum |
cb9031533cf8369be3567f261e7fdccf1e073063 | 2,781 | cc | C++ | src/main/cpp/blaze_util_mingw.cc | cloudpanda/bazel | 981b7bc1ce793a484f9a39178d57f9e24bfc487a | [
"Apache-2.0"
] | 2 | 2016-02-06T16:36:44.000Z | 2019-03-30T07:56:11.000Z | src/main/cpp/blaze_util_mingw.cc | shwenzhang/bazel | 03bad4619075aa77876698c55827aa54e7426ea9 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/blaze_util_mingw.cc | shwenzhang/bazel | 03bad4619075aa77876698c55827aa54e7426ea9 | [
"Apache-2.0"
] | 2 | 2016-02-06T16:36:46.000Z | 2018-12-06T07:41:36.000Z | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <errno.h>
#include <limits.h>
#include <string.h> // strerror
#include <sys/statfs.h>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>
#include "blaze_exit_code.h"
#include "blaze_util_platform.h"
#include "blaze_util.h"
#include "util/file.h"
#include "util/strings.h"
namespace blaze {
using std::string;
void WarnFilesystemType(const string& output_base) {
}
string GetSelfPath() {
char buffer[PATH_MAX] = {};
ssize_t bytes = readlink("/proc/self/exe", buffer, sizeof(buffer));
if (bytes == sizeof(buffer)) {
// symlink contents truncated
bytes = -1;
errno = ENAMETOOLONG;
}
if (bytes == -1) {
pdie(blaze_exit_code::INTERNAL_ERROR, "error reading /proc/self/exe");
}
buffer[bytes] = '\0'; // readlink does not NUL-terminate
return string(buffer);
}
string GetOutputRoot() {
return "/var/tmp";
}
pid_t GetPeerProcessId(int socket) {
struct ucred creds = {};
socklen_t len = sizeof creds;
if (getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &creds, &len) == -1) {
pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
"can't get server pid from connection");
}
return creds.pid;
}
uint64 MonotonicClock() {
struct timespec ts = {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
uint64 ProcessClock() {
struct timespec ts = {};
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
return ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
void SetScheduling(bool batch_cpu_scheduling, int io_nice_level) {
// TODO(bazel-team): There should be a similar function on Windows.
}
string GetProcessCWD(int pid) {
char server_cwd[PATH_MAX] = {};
if (readlink(
("/proc/" + std::to_string(pid) + "/cwd").c_str(),
server_cwd, sizeof(server_cwd)) < 0) {
return "";
}
return string(server_cwd);
}
bool IsSharedLibrary(string filename) {
return blaze_util::ends_with(filename, ".dll");
}
string GetDefaultHostJavabase() {
const char *javahome = getenv("JAVA_HOME");
if (javahome == NULL) {
die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
"Error: JAVA_HOME not set.");
}
return javahome;
}
} // namespace blaze
| 25.990654 | 75 | 0.695433 | cloudpanda |
cb90d75dd73aa285ff525cfb4dba1ef5b10c6f34 | 213 | cpp | C++ | jp.atcoder/abc156/abc156_a/11412312.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-09T03:06:25.000Z | 2022-02-09T03:06:25.000Z | jp.atcoder/abc156/abc156_a/11412312.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-05T22:53:18.000Z | 2022-02-09T01:29:30.000Z | jp.atcoder/abc156/abc156_a/11412312.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, r;
cin >> n >> r;
r += 100 * max(10 - n, 0);
cout << r << endl;
return 0;
}
| 14.2 | 31 | 0.502347 | kagemeka |
cb93749db348ab19811caf722e6a09b57538e9ee | 7,929 | cpp | C++ | src/rmath.cpp | nicovanbentum/Raekor | 131e68490aa119213467ef295d3bfb94e5dd7046 | [
"MIT"
] | 6 | 2019-07-16T05:39:18.000Z | 2022-02-17T10:10:18.000Z | src/rmath.cpp | nicovanbentum/Raekor | 131e68490aa119213467ef295d3bfb94e5dd7046 | [
"MIT"
] | null | null | null | src/rmath.cpp | nicovanbentum/Raekor | 131e68490aa119213467ef295d3bfb94e5dd7046 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "rmath.h"
#include "camera.h"
namespace Raekor {
namespace Math {
Ray::Ray(Viewport& viewport, glm::vec2 coords) {
glm::vec3 rayNDC = {
(2.0f * coords.x) / viewport.size.x - 1.0f,
1.0f - (2.0f * coords.y) / viewport.size.y,
1.0f
};
glm::vec4 rayClip = { rayNDC.x, rayNDC.y, -1.0f, 1.0f };
glm::vec4 rayCamera = glm::inverse(viewport.getCamera().getProjection()) * rayClip;
rayCamera.z = -1.0f, rayCamera.w = 0.0f;
glm::vec3 rayWorld = glm::inverse(viewport.getCamera().getView()) * rayCamera;
rayWorld = glm::normalize(rayWorld);
direction = rayWorld;
origin = viewport.getCamera().getPosition();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
std::optional<float> Ray::hitsOBB(const glm::vec3& min, const glm::vec3& max, const glm::mat4& modelMatrix) {
float tMin = 0.0f;
float tMax = 100000.0f;
glm::vec3 OBBposition_worldspace(modelMatrix[3]);
glm::vec3 delta = OBBposition_worldspace - origin;
{
glm::vec3 xaxis(modelMatrix[0]);
float e = glm::dot(xaxis, delta);
float f = glm::dot(direction, xaxis);
if (fabs(f) > 0.001f) {
float t1 = (e + min.x) / f;
float t2 = (e + max.x) / f;
if (t1 > t2) std::swap(t1, t2);
if (t2 < tMax) tMax = t2;
if (t1 > tMin) tMin = t1;
if (tMin > tMax) return std::nullopt;
}
else {
//if (-e + min.x > 0.0f || -e + max.x < 0.0f) return std::nullopt;
}
}
{
glm::vec3 yaxis(modelMatrix[1]);
float e = glm::dot(yaxis, delta);
float f = glm::dot(direction, yaxis);
if (fabs(f) > 0.001f) {
float t1 = (e + min.y) / f;
float t2 = (e + max.y) / f;
if (t1 > t2) std::swap(t1, t2);
if (t2 < tMax) tMax = t2;
if (t1 > tMin) tMin = t1;
if (tMin > tMax) return std::nullopt;
}
else {
//if (-e + min.y > 0.0f || -e + max.y < 0.0f) return std::nullopt;
}
}
{
glm::vec3 zaxis(modelMatrix[2]);
float e = glm::dot(zaxis, delta);
float f = glm::dot(direction, zaxis);
if (fabs(f) > 0.001f) {
float t1 = (e + min.z) / f;
float t2 = (e + max.z) / f;
if (t1 > t2) std::swap(t1, t2);
if (t2 < tMax) tMax = t2;
if (t1 > tMin) tMin = t1;
if (tMin > tMax) return std::nullopt;
}
else {
//if (-e + min.z > 0.0f || -e + max.z < 0.0f) return std::nullopt;
}
}
return tMin;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
std::optional<float> Ray::hitsAABB(const glm::vec3& min, const glm::vec3& max) {
auto tnear = (min.x - origin.x) / direction.x;
auto tfar = (max.x - origin.x) / direction.x;
if (tnear > tfar) std::swap(tnear, tfar);
auto t1y = (min.y - origin.y) / direction.y;
auto t2y = (max.y - origin.y) / direction.y;
if (t1y > t2y) std::swap(t1y, t2y);
if ((tnear > t2y) || (t1y > tfar)) return false;
if (t1y > tnear) tnear = t1y;
if (t2y < tfar) tfar = t2y;
auto t1z = (min.z - origin.z) / direction.z;
auto t2z = (max.z - origin.z) / direction.z;
if (t1z > t2z) std::swap(t1z, t2z);
if ((tnear > t2z) || (t1z > tfar)) return false;
if (t1z > tnear) tnear = t1z;
if (t2z < tfar) tfar = t2z;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
std::optional<float> Ray::hitsTriangle(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2) {
auto p1 = v1 - v0;
auto p2 = v2 - v0;
auto pvec = glm::cross(direction, p2);
float det = glm::dot(p1, pvec);
if (fabs(det) < std::numeric_limits<float>::epsilon()) return std::nullopt;
float invDet = 1 / det;
auto tvec = origin - v0;
auto u = glm::dot(tvec, pvec) * invDet;
if (u < 0 || u > 1) return std::nullopt;
auto qvec = glm::cross(tvec, p1);
auto v = glm::dot(direction, qvec) * invDet;
if (v < 0 || u + v > 1) return std::nullopt;
return glm::dot(p2, qvec) * invDet;
}
std::optional<float> Ray::hitsSphere(const glm::vec3& o, float radius, float t_min, float t_max) {
float R2 = radius * radius;
glm::vec3 L = o - origin;
float tca = glm::dot(L, glm::normalize(direction));
if (tca < 0) return std::nullopt;
float D2 = dot(L, L) - tca * tca;
if (D2 > R2) return std::nullopt;
float thc = sqrt(R2 - D2);
float t0 = tca - thc;
float t1 = tca + thc;
float closest_t = std::min(t0, t1);
if (closest_t < t_max && closest_t > t_min) {
return closest_t / glm::length(direction);
}
return std::nullopt;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool pointInAABB(const glm::vec3& point, const glm::vec3& min, const glm::vec3& max) {
return (point.x >= min.x && point.x <= max.x) &&
(point.y >= min.y && point.y <= max.y) &&
(point.z >= min.z && point.z <= max.z);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
/*
Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix by G. Gribb & K. Hartmann
https://www.gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf
*/
void Frustrum::update(const glm::mat4& vp, bool normalize) {
planes[0].x = vp[0][3] + vp[0][0];
planes[0].y = vp[1][3] + vp[1][0];
planes[0].z = vp[2][3] + vp[2][0];
planes[0].w = vp[3][3] + vp[3][0];
planes[1].x = vp[0][3] - vp[0][0];
planes[1].y = vp[1][3] - vp[1][0];
planes[1].z = vp[2][3] - vp[2][0];
planes[1].w = vp[3][3] - vp[3][0];
planes[2].x = vp[0][3] - vp[0][1];
planes[2].y = vp[1][3] - vp[1][1];
planes[2].z = vp[2][3] - vp[2][1];
planes[2].w = vp[3][3] - vp[3][1];
planes[3].x = vp[0][3] + vp[0][1];
planes[3].y = vp[1][3] + vp[1][1];
planes[3].z = vp[2][3] + vp[2][1];
planes[3].w = vp[3][3] + vp[3][1];
planes[4].x = vp[0][3] + vp[0][2];
planes[4].y = vp[1][3] + vp[1][2];
planes[4].z = vp[2][3] + vp[2][2];
planes[4].w = vp[3][3] + vp[3][2];
planes[5].x = vp[0][3] - vp[0][2];
planes[5].y = vp[1][3] - vp[1][2];
planes[5].z = vp[2][3] - vp[2][2];
planes[5].w = vp[3][3] - vp[3][2];
if (normalize) {
for (auto& plane : planes) {
const float mag = sqrt(plane.x * plane.x + plane.y * plane.y + plane.z * plane.z);
plane.x = plane.x / mag;
plane.y = plane.y / mag;
plane.z = plane.z / mag;
plane.w = plane.w / mag;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool Frustrum::vsAABB(const glm::vec3& min, const glm::vec3& max) {
for (const auto& plane : planes) {
int out = 0;
out += ((glm::dot(plane, glm::vec4(min.x, min.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(max.x, min.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(min.x, max.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(max.x, max.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(min.x, min.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(max.x, min.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(min.x, max.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(plane, glm::vec4(max.x, max.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
if (out == 8) return false;
}
return true;
}
} // raekor
} // math | 31.094118 | 113 | 0.472695 | nicovanbentum |
cb991c100f908016b0f24a84e4d83d56ad2e3a47 | 108,452 | cpp | C++ | samples/golf/src/golf/GolfState.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | samples/golf/src/golf/GolfState.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | samples/golf/src/golf/GolfState.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2021
http://trederia.blogspot.com
crogine application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include "GolfState.hpp"
#include "GameConsts.hpp"
#include "MenuConsts.hpp"
#include "CommandIDs.hpp"
#include "PacketIDs.hpp"
#include "SharedStateData.hpp"
#include "InterpolationSystem.hpp"
#include "ClientPacketData.hpp"
#include "MessageIDs.hpp"
#include "Clubs.hpp"
#include "TextAnimCallback.hpp"
#include "ClientCollisionSystem.hpp"
#include "GolfParticleDirector.hpp"
#include "PlayerAvatar.hpp"
#include "GolfSoundDirector.hpp"
#include "TutorialDirector.hpp"
#include "BallSystem.hpp"
#include <crogine/audio/AudioScape.hpp>
#include <crogine/core/ConfigFile.hpp>
#include <crogine/core/GameController.hpp>
#include <crogine/core/SysTime.hpp>
#include <crogine/ecs/systems/ModelRenderer.hpp>
#include <crogine/ecs/systems/CameraSystem.hpp>
#include <crogine/ecs/systems/RenderSystem2D.hpp>
#include <crogine/ecs/systems/SpriteSystem2D.hpp>
#include <crogine/ecs/systems/SpriteAnimator.hpp>
#include <crogine/ecs/systems/TextSystem.hpp>
#include <crogine/ecs/systems/CommandSystem.hpp>
#include <crogine/ecs/systems/CallbackSystem.hpp>
#include <crogine/ecs/systems/SkeletalAnimator.hpp>
#include <crogine/ecs/systems/BillboardSystem.hpp>
#include <crogine/ecs/systems/ParticleSystem.hpp>
#include <crogine/ecs/systems/AudioSystem.hpp>
#include <crogine/ecs/components/Transform.hpp>
#include <crogine/ecs/components/Model.hpp>
#include <crogine/ecs/components/Drawable2D.hpp>
#include <crogine/ecs/components/Camera.hpp>
#include <crogine/ecs/components/Sprite.hpp>
#include <crogine/ecs/components/SpriteAnimation.hpp>
#include <crogine/ecs/components/Text.hpp>
#include <crogine/ecs/components/CommandTarget.hpp>
#include <crogine/ecs/components/Callback.hpp>
#include <crogine/ecs/components/BillboardCollection.hpp>
#include <crogine/ecs/components/AudioEmitter.hpp>
#include <crogine/ecs/components/AudioListener.hpp>
#include <crogine/graphics/SpriteSheet.hpp>
#include <crogine/graphics/DynamicMeshBuilder.hpp>
#include <crogine/graphics/CircleMeshBuilder.hpp>
#include <crogine/network/NetClient.hpp>
#include <crogine/gui/Gui.hpp>
#include <crogine/util/Constants.hpp>
#include <crogine/util/Matrix.hpp>
#include <crogine/util/Network.hpp>
#include <crogine/util/Random.hpp>
#include <crogine/util/Easings.hpp>
#include <crogine/util/Maths.hpp>
#include <crogine/detail/glm/gtc/matrix_transform.hpp>
#include "../ErrorCheck.hpp"
#include <sstream>
namespace
{
#include "WaterShader.inl"
#include "TerrainShader.inl"
#include "MinimapShader.inl"
#include "WireframeShader.inl"
const cro::Time ReadyPingFreq = cro::seconds(1.f);
const cro::Time MouseHideTime = cro::seconds(3.f);
//used to set the camera target
struct TargetInfo final
{
float targetHeight = CameraStrokeHeight;
float targetOffset = CameraStrokeOffset;
float startHeight = 0.f;
float startOffset = 0.f;
glm::vec3 targetLookAt = glm::vec3(0.f);
glm::vec3 currentLookAt = glm::vec3(0.f);
glm::vec3 prevLookAt = glm::vec3(0.f);
cro::Entity waterPlane;
};
//use to move the flag as the player approaches
struct FlagCallbackData final
{
static constexpr float MaxHeight = 1.f;
float targetHeight = 0.f;
float currentHeight = 0.f;
};
}
GolfState::GolfState(cro::StateStack& stack, cro::State::Context context, SharedStateData& sd)
: cro::State (stack, context),
m_sharedData (sd),
m_gameScene (context.appInstance.getMessageBus(), 512),
m_uiScene (context.appInstance.getMessageBus(), 512),
m_mouseVisible (true),
m_inputParser (sd.inputBinding, context.appInstance.getMessageBus()),
m_wantsGameState (true),
m_currentHole (0),
m_terrainBuilder (m_holeData),
m_currentCamera (CameraID::Player),
m_camRotation (0.f),
m_roundEnded (false),
m_viewScale (1.f),
m_scoreColumnCount (2)
{
context.mainWindow.loadResources([this]() {
loadAssets();
addSystems();
initAudio();
buildScene();
});
sd.baseState = StateID::Game;
//glLineWidth(1.5f);
#ifdef CRO_DEBUG_
//registerWindow([&]()
// {
// if (ImGui::Begin("buns"))
// {
// /*auto pin = m_holeData[m_currentHole].pin;
// auto target = m_holeData[m_currentHole].target;
// auto currLookAt = m_gameScene.getActiveCamera().getComponent<TargetInfo>().currentLookAt;
// ImGui::Text("Pin: %3.3f, %3.3f", pin.x, pin.z);
// ImGui::Text("Target: %3.3f, %3.3f", target.x, target.z);
// ImGui::Text("Look At: %3.3f, %3.3f", currLookAt.x, currLookAt.z);*/
// ImGui::Text("Cam Rotation: %3.3f", m_camRotation);
// auto pos = m_cameras[CameraID::Player].getComponent<cro::Transform>().getWorldPosition();
// ImGui::Text("Cam Position: %3.3f, %3.3f, %3.3f", pos.x, pos.y, pos.z);
// //ImGui::Image(m_gameScene.getActiveCamera().getComponent<cro::Camera>().reflectionBuffer.getTexture(), { 300.f, 300.f }, { 0.f, 1.f }, { 1.f, 0.f });
// //ImGui::Image(m_gameScene.getActiveCamera().getComponent<cro::Camera>().shadowMapBuffer.getTexture(), { 300.f, 300.f }, { 0.f, 1.f }, { 1.f, 0.f });
// }
// ImGui::End();
// });
#endif
}
//public
bool GolfState::handleEvent(const cro::Event& evt)
{
if (ImGui::GetIO().WantCaptureKeyboard
|| ImGui::GetIO().WantCaptureMouse)
{
return true;
}
const auto scrollScores = [&](std::int32_t step)
{
cro::Command cmd;
cmd.targetFlags = CommandID::UI::ScoreScroll;
cmd.action = [step](cro::Entity e, float)
{
e.getComponent<cro::Callback>().getUserData<std::int32_t>() = step;
e.getComponent<cro::Callback>().active = true;
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
};
if (evt.type == SDL_KEYUP)
{
switch (evt.key.keysym.sym)
{
default: break;
case SDLK_TAB:
showScoreboard(false);
break;
#ifdef CRO_DEBUG_
case SDLK_F2:
m_sharedData.clientConnection.netClient.sendPacket(PacketID::ServerCommand, std::uint8_t(ServerCommand::NextHole), cro::NetFlag::Reliable);
break;
case SDLK_F3:
m_sharedData.clientConnection.netClient.sendPacket(PacketID::ServerCommand, std::uint8_t(ServerCommand::NextPlayer), cro::NetFlag::Reliable);
break;
case SDLK_F4:
m_sharedData.clientConnection.netClient.sendPacket(PacketID::ServerCommand, std::uint8_t(ServerCommand::GotoGreen), cro::NetFlag::Reliable);
break;
case SDLK_F6:
m_sharedData.clientConnection.netClient.sendPacket(PacketID::ServerCommand, std::uint8_t(ServerCommand::EndGame), cro::NetFlag::Reliable);
break;
case SDLK_F7:
//showCountdown(10);
//showMessageBoard(MessageBoardID::Scrub);
requestStackPush(StateID::Tutorial);
break;
case SDLK_F8:
//showMessageBoard(MessageBoardID::Bunker);
//updateMiniMap();
//removeClient(1);
//floatingMessage("Hooked!");
break;
case SDLK_KP_0:
setActiveCamera(0);
break;
case SDLK_KP_1:
setActiveCamera(1);
m_cameras[CameraID::Sky].getComponent<CameraFollower>().state = CameraFollower::Zoom;
break;
case SDLK_KP_2:
setActiveCamera(2);
break;
case SDLK_PAGEUP:
{
cro::Command cmd;
cmd.targetFlags = CommandID::Flag;
cmd.action = [](cro::Entity e, float)
{
e.getComponent<cro::Callback>().getUserData<FlagCallbackData>().targetHeight = FlagCallbackData::MaxHeight;
e.getComponent<cro::Callback>().active = true;
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
break;
case SDLK_PAGEDOWN:
{
cro::Command cmd;
cmd.targetFlags = CommandID::Flag;
cmd.action = [](cro::Entity e, float)
{
e.getComponent<cro::Callback>().getUserData<FlagCallbackData>().targetHeight = 0.f;
e.getComponent<cro::Callback>().active = true;
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
break;
#endif
}
}
else if (evt.type == SDL_KEYDOWN)
{
switch (evt.key.keysym.sym)
{
default: break;
case SDLK_TAB:
showScoreboard(true);
break;
case SDLK_UP:
case SDLK_LEFT:
scrollScores(-19);
break;
case SDLK_DOWN:
case SDLK_RIGHT:
scrollScores(19);
break;
case SDLK_RETURN:
showScoreboard(false);
break;
case SDLK_ESCAPE:
case SDLK_p:
case SDLK_PAUSE:
requestStackPush(StateID::Pause);
break;
}
}
else if (evt.type == SDL_CONTROLLERBUTTONDOWN
&& evt.cbutton.which == cro::GameController::deviceID(m_sharedData.inputBinding.controllerID))
{
switch (evt.cbutton.button)
{
default: break;
case cro::GameController::ButtonBack:
showScoreboard(true);
break;
case cro::GameController::ButtonB:
showScoreboard(false);
break;
case cro::GameController::DPadUp:
case cro::GameController::DPadLeft:
scrollScores(-19);
break;
case cro::GameController::DPadDown:
case cro::GameController::DPadRight:
scrollScores(19);
break;
}
}
else if (evt.type == SDL_CONTROLLERBUTTONUP
&& evt.cbutton.which == cro::GameController::deviceID(m_sharedData.inputBinding.controllerID))
{
switch (evt.cbutton.button)
{
default: break;
case cro::GameController::ButtonBack:
showScoreboard(false);
break;
case cro::GameController::ButtonStart:
requestStackPush(StateID::Pause);
break;
}
}
else if (evt.type == SDL_MOUSEWHEEL)
{
if (evt.wheel.y > 0)
{
scrollScores(-19);
}
else if (evt.wheel.y < 0)
{
scrollScores(19);
}
}
else if (evt.type == SDL_CONTROLLERDEVICEREMOVED)
{
//check if any players are using the controller
//and reassign any still connected devices
for (auto i = 0; i < 4; ++i)
{
if (evt.cdevice.which == cro::GameController::deviceID(i))
{
for (auto& idx : m_sharedData.controllerIDs)
{
idx = std::max(0, i - 1);
}
//update the input parser in case this player is active
m_sharedData.inputBinding.controllerID = m_sharedData.controllerIDs[m_currentPlayer.player];
break;
}
}
}
else if (evt.type == SDL_MOUSEMOTION)
{
cro::App::getWindow().setMouseCaptured(false);
m_mouseVisible = true;
m_mouseClock.restart();
}
m_inputParser.handleEvent(evt);
m_gameScene.forwardEvent(evt);
m_uiScene.forwardEvent(evt);
return true;
}
void GolfState::handleMessage(const cro::Message& msg)
{
switch (msg.id)
{
default: break;
case MessageID::SystemMessage:
{
const auto& data = msg.getData<SystemEvent>();
if (data.type == SystemEvent::StateRequest)
{
requestStackPush(data.data);
}
}
break;
case cro::Message::SpriteAnimationMessage:
{
const auto& data = msg.getData<cro::Message::SpriteAnimationEvent>();
if (data.userType == 0)
{
//relay this message with the info needed for particle/sound effects
auto* msg2 = cro::App::getInstance().getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg2->type = GolfEvent::ClubSwing;
msg2->position = m_currentPlayer.position;
msg2->terrain = m_currentPlayer.terrain;
msg2->club = static_cast<std::uint8_t>(getClub());
m_gameScene.getSystem<ClientCollisionSystem>()->setActiveClub(getClub());
if (m_currentPlayer.client == m_sharedData.localConnectionData.connectionID)
{
cro::GameController::rumbleStart(m_sharedData.inputBinding.controllerID, 50000, 35000, 200);
}
//check if we hooked/sliced
if (getClub() != ClubID::Putter)
{
auto hook = m_inputParser.getHook();
if (hook < -0.15f)
{
auto* msg2 = cro::App::getInstance().getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg2->type = GolfEvent::HookedBall;
floatingMessage("Hook");
}
else if (hook > 0.15f)
{
auto* msg2 = cro::App::getInstance().getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg2->type = GolfEvent::SlicedBall;
floatingMessage("Slice");
}
auto power = m_inputParser.getPower();
hook *= 20.f;
hook = std::round(hook);
hook /= 20.f;
if (power > 0.9f
&& std::fabs(hook) < 0.05f)
{
auto* msg2 = cro::App::getInstance().getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg2->type = GolfEvent::NiceShot;
}
//enable the camera following
m_gameScene.setSystemActive<CameraFollowSystem>(true);
}
}
}
break;
case MessageID::SceneMessage:
{
const auto& data = msg.getData<SceneEvent>();
switch(data.type)
{
default: break;
case SceneEvent::TransitionComplete:
{
updateMiniMap();
}
break;
case SceneEvent::RequestSwitchCamera:
setActiveCamera(data.data);
break;
}
}
break;
case MessageID::GolfMessage:
{
const auto& data = msg.getData<GolfEvent>();
if (data.type == GolfEvent::HitBall)
{
hitBall();
}
else if (data.type == GolfEvent::ClubChanged)
{
cro::Command cmd;
cmd.targetFlags = CommandID::StrokeIndicator;
cmd.action = [&](cro::Entity e, float)
{
float scale = Clubs[getClub()].power / Clubs[ClubID::Driver].power;
e.getComponent<cro::Transform>().setScale({ scale, 1.f });
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//update the sprite with correct club
cmd.targetFlags = CommandID::UI::PlayerSprite;
cmd.action = [&](cro::Entity e, float)
{
auto colour = e.getComponent<cro::Sprite>().getColour();
if (getClub() < ClubID::FiveIron)
{
e.getComponent<cro::Sprite>() = m_avatars[m_currentPlayer.client][m_currentPlayer.player].wood;
}
else
{
e.getComponent<cro::Sprite>() = m_avatars[m_currentPlayer.client][m_currentPlayer.player].iron;
}
e.getComponent<cro::Sprite>().setColour(colour);
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//update club text colour based on distance
cmd.targetFlags = CommandID::UI::ClubName;
cmd.action = [&](cro::Entity e, float)
{
if (m_currentPlayer.client == m_sharedData.clientConnection.connectionID)
{
e.getComponent<cro::Text>().setString(Clubs[getClub()].name);
auto dist = glm::length(m_currentPlayer.position - m_holeData[m_currentHole].pin) * 1.67f;
if (getClub() < ClubID::NineIron &&
Clubs[getClub()].target > dist)
{
e.getComponent<cro::Text>().setFillColour(TextHighlightColour);
}
else
{
e.getComponent<cro::Text>().setFillColour(TextNormalColour);
}
}
else
{
e.getComponent<cro::Text>().setString(" ");
}
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
else if (data.type == GolfEvent::BallLanded)
{
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<float>(1.5f);
entity.getComponent<cro::Callback>().function =
[&](cro::Entity e, float dt)
{
auto& currTime = e.getComponent<cro::Callback>().getUserData<float>();
currTime -= dt;
if (currTime < 0)
{
setActiveCamera(CameraID::Player);
e.getComponent<cro::Callback>().active = false;
m_gameScene.destroyEntity(e);
}
};
}
}
break;
case cro::Message::ConsoleMessage:
{
const auto& data = msg.getData<cro::Message::ConsoleEvent>();
switch (data.type)
{
default: break;
case cro::Message::ConsoleEvent::Closed:
cro::App::getWindow().setMouseCaptured(true);
break;
case cro::Message::ConsoleEvent::Opened:
cro::App::getWindow().setMouseCaptured(false);
break;
}
}
break;
case cro::Message::StateMessage:
{
const auto& data = msg.getData<cro::Message::StateEvent>();
if (data.action == cro::Message::StateEvent::Popped)
{
if (data.id == StateID::Pause
|| data.id == StateID::Tutorial)
{
cro::App::getWindow().setMouseCaptured(true);
//make sure to set the correct controller
m_sharedData.inputBinding.controllerID = m_sharedData.controllerIDs[m_currentPlayer.player];
}
}
}
break;
}
m_gameScene.forwardMessage(msg);
m_uiScene.forwardMessage(msg);
}
bool GolfState::simulate(float dt)
{
if (m_sharedData.clientConnection.connected)
{
cro::NetEvent evt;
while (m_sharedData.clientConnection.netClient.pollEvent(evt))
{
//handle events
handleNetEvent(evt);
}
if (m_wantsGameState)
{
if (m_readyClock.elapsed() > ReadyPingFreq)
{
m_sharedData.clientConnection.netClient.sendPacket(PacketID::ClientReady, m_sharedData.clientConnection.connectionID, cro::NetFlag::Reliable);
m_readyClock.restart();
}
}
}
else
{
//we've been disconnected somewhere - push error state
m_sharedData.errorMessage = "Lost connection to host.";
requestStackPush(StateID::Error);
}
//update time uniforms
static float elapsed = dt;
elapsed += dt;
glUseProgram(m_waterShader.shaderID);
glUniform1f(m_waterShader.timeUniform, elapsed * 15.f);
//glUseProgram(0);
m_terrainBuilder.updateTime(elapsed * 10.f);
m_inputParser.update(dt);
m_gameScene.simulate(dt);
m_uiScene.simulate(dt);
//tell the flag to raise or lower
if (m_currentPlayer.terrain == TerrainID::Green)
{
cro::Command cmd;
cmd.targetFlags = CommandID::Flag;
cmd.action = [&](cro::Entity e, float)
{
auto camDist = glm::length2(m_gameScene.getActiveCamera().getComponent<cro::Transform>().getPosition() - m_holeData[m_currentHole].pin);
auto& data = e.getComponent<cro::Callback>().getUserData<FlagCallbackData>();
if (data.targetHeight < FlagCallbackData::MaxHeight
&& camDist < FlagRaiseDistance)
{
data.targetHeight = FlagCallbackData::MaxHeight;
e.getComponent<cro::Callback>().active = true;
}
else if (data.targetHeight > 0
&& camDist > FlagRaiseDistance)
{
data.targetHeight = 0.f;
e.getComponent<cro::Callback>().active = true;
}
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
//auto hide the mouse
if (m_mouseVisible
&& getStateCount() == 1)
{
if (m_mouseClock.elapsed() > MouseHideTime)
{
m_mouseVisible = false;
cro::App::getWindow().setMouseCaptured(true);
}
}
return true;
}
void GolfState::render()
{
//render reflections first
auto& cam = m_gameScene.getActiveCamera().getComponent<cro::Camera>();
auto oldVP = cam.viewport;
cam.viewport = { 0.f,0.f,1.f,1.f };
cam.setActivePass(cro::Camera::Pass::Reflection);
cam.reflectionBuffer.clear(cro::Colour::Red);
m_gameScene.render(cam.reflectionBuffer);
cam.reflectionBuffer.display();
cam.setActivePass(cro::Camera::Pass::Final);
cam.viewport = oldVP;
//then render scene
glCheck(glEnable(GL_PROGRAM_POINT_SIZE));
m_gameSceneTexture.clear();
m_gameScene.render(m_gameSceneTexture);
m_gameSceneTexture.display();
//update mini green if ball is there
if (m_currentPlayer.terrain == TerrainID::Green)
{
auto oldCam = m_gameScene.setActiveCamera(m_greenCam);
m_greenBuffer.clear();
m_gameScene.render(m_greenBuffer);
m_greenBuffer.display();
m_gameScene.setActiveCamera(oldCam);
}
m_uiScene.render(*GolfGame::getActiveTarget());
}
//private
void GolfState::loadAssets()
{
//load materials
std::fill(m_materialIDs.begin(), m_materialIDs.end(), -1);
//cel shaded material
m_resources.shaders.loadFromString(ShaderID::Cel, CelVertexShader, CelFragmentShader, "#define VERTEX_COLOURED\n");
auto* shader = &m_resources.shaders.get(ShaderID::Cel);
m_materialIDs[MaterialID::Cel] = m_resources.materials.add(*shader);
m_resources.shaders.loadFromString(ShaderID::CelTextured, CelVertexShader, CelFragmentShader, "#define TEXTURED\n");
shader = &m_resources.shaders.get(ShaderID::CelTextured);
m_materialIDs[MaterialID::CelTextured] = m_resources.materials.add(*shader);
m_resources.shaders.loadFromString(ShaderID::Course, CelVertexShader, CelFragmentShader, "#define TEXTURED\n#define NORMAL_MAP\n");
shader = &m_resources.shaders.get(ShaderID::Course);
m_materialIDs[MaterialID::Course] = m_resources.materials.add(*shader);
m_resources.shaders.loadFromString(ShaderID::Wireframe, WireframeVertex, WireframeFragment);
m_materialIDs[MaterialID::WireFrame] = m_resources.materials.add(m_resources.shaders.get(ShaderID::Wireframe));
m_resources.materials.get(m_materialIDs[MaterialID::WireFrame]).blendMode = cro::Material::BlendMode::Alpha;
m_resources.shaders.loadFromString(ShaderID::WireframeCulled, WireframeVertex, WireframeFragment, "#define CULLED\n");
m_materialIDs[MaterialID::WireFrameCulled] = m_resources.materials.add(m_resources.shaders.get(ShaderID::WireframeCulled));
m_resources.materials.get(m_materialIDs[MaterialID::WireFrameCulled]).blendMode = cro::Material::BlendMode::Alpha;
m_resources.shaders.loadFromString(ShaderID::Minimap, MinimapVertex, MinimapFragment);
m_resources.shaders.loadFromString(ShaderID::Water, WaterVertex, WaterFragment);
m_materialIDs[MaterialID::Water] = m_resources.materials.add(m_resources.shaders.get(ShaderID::Water));
m_waterShader.shaderID = m_resources.shaders.get(ShaderID::Water).getGLHandle();
m_waterShader.timeUniform = m_resources.shaders.get(ShaderID::Water).getUniformMap().at("u_time");
//model definitions
for (auto& md : m_modelDefs)
{
md = std::make_unique<cro::ModelDefinition>(m_resources);
}
m_modelDefs[ModelID::BallShadow]->loadFromFile("assets/golf/models/ball_shadow.cmt");
//ball models - the menu should never have let us get this far if it found no ball files
for (const auto& [colour, uid, path] : m_sharedData.ballModels)
{
std::unique_ptr<cro::ModelDefinition> def = std::make_unique<cro::ModelDefinition>(m_resources);
if (def->loadFromFile(path))
{
m_ballModels.insert(std::make_pair(uid, std::move(def)));
}
}
//UI stuffs
cro::SpriteSheet spriteSheet;
spriteSheet.loadFromFile("assets/golf/sprites/ui.spt", m_resources.textures);
m_sprites[SpriteID::PowerBar] = spriteSheet.getSprite("power_bar");
m_sprites[SpriteID::PowerBarInner] = spriteSheet.getSprite("power_bar_inner");
m_sprites[SpriteID::HookBar] = spriteSheet.getSprite("hook_bar");
m_sprites[SpriteID::WindIndicator] = spriteSheet.getSprite("wind_dir");
m_sprites[SpriteID::MessageBoard] = spriteSheet.getSprite("message_board");
m_sprites[SpriteID::Bunker] = spriteSheet.getSprite("bunker");
m_sprites[SpriteID::Foul] = spriteSheet.getSprite("foul");
auto flagSprite = spriteSheet.getSprite("flag03");
m_flagQuad.setTexture(*flagSprite.getTexture());
m_flagQuad.setTextureRect(flagSprite.getTextureRect());
//these are doubled because odd skinIDs are flipped
//versions of even numbered
spriteSheet.loadFromFile("assets/golf/sprites/player.spt", m_resources.textures);
std::vector<cro::Sprite> ironSprites =
{
spriteSheet.getSprite("female_iron"),
spriteSheet.getSprite("female_iron"),
spriteSheet.getSprite("male_iron"),
spriteSheet.getSprite("male_iron"),
spriteSheet.getSprite("female_iron_02"),
spriteSheet.getSprite("female_iron_02"),
spriteSheet.getSprite("male_iron_02"),
spriteSheet.getSprite("male_iron_02")
};
std::vector<cro::Sprite> woodSprites =
{
spriteSheet.getSprite("female_wood"),
spriteSheet.getSprite("female_wood"),
spriteSheet.getSprite("male_wood"),
spriteSheet.getSprite("male_wood"),
spriteSheet.getSprite("female_wood_02"),
spriteSheet.getSprite("female_wood_02"),
spriteSheet.getSprite("male_wood_02"),
spriteSheet.getSprite("male_wood_02")
};
for (auto i = 0u; i < m_sharedData.connectionData.size(); ++i)
{
for (auto j = 0u; j < m_sharedData.connectionData[i].playerCount; ++j)
{
auto skinID = std::min(m_sharedData.connectionData[i].playerData[j].skinID, std::uint8_t(PlayerAvatar::MaxSkins - 1));
m_avatars[i][j].iron = ironSprites[skinID];
m_avatars[i][j].wood = woodSprites[skinID];
m_avatars[i][j].flipped = (skinID % 2);
m_avatars[i][j].iron.setTexture(m_sharedData.avatarTextures[i][j], false);
m_avatars[i][j].wood.setTexture(m_sharedData.avatarTextures[i][j], false);
}
}
//ball resources - ball is rendered as a single point
//at a distance, and as a model when closer
glCheck(glPointSize(BallPointSize));
m_ballResources.materialID = m_materialIDs[MaterialID::WireFrameCulled];
m_ballResources.ballMeshID = m_resources.meshes.loadMesh(cro::DynamicMeshBuilder(cro::VertexProperty::Position | cro::VertexProperty::Colour, 1, GL_POINTS));
m_ballResources.shadowMeshID = m_resources.meshes.loadMesh(cro::DynamicMeshBuilder(cro::VertexProperty::Position | cro::VertexProperty::Colour, 1, GL_POINTS));
auto* meshData = &m_resources.meshes.getMesh(m_ballResources.ballMeshID);
std::vector<float> verts =
{
0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f
};
std::vector<std::uint32_t> indices =
{
0
};
meshData->vertexCount = 1;
glCheck(glBindBuffer(GL_ARRAY_BUFFER, meshData->vbo));
glCheck(glBufferData(GL_ARRAY_BUFFER, meshData->vertexSize * meshData->vertexCount, verts.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ARRAY_BUFFER, 0));
auto* submesh = &meshData->indexData[0];
submesh->indexCount = 1;
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, submesh->ibo));
glCheck(glBufferData(GL_ELEMENT_ARRAY_BUFFER, submesh->indexCount * sizeof(std::uint32_t), indices.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
meshData = &m_resources.meshes.getMesh(m_ballResources.shadowMeshID);
verts =
{
0.f, 0.f, 0.f, 0.5f, 0.5f, 0.5f, 1.f,
};
meshData->vertexCount = 1;
glCheck(glBindBuffer(GL_ARRAY_BUFFER, meshData->vbo));
glCheck(glBufferData(GL_ARRAY_BUFFER, meshData->vertexSize * meshData->vertexCount, verts.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ARRAY_BUFFER, 0));
submesh = &meshData->indexData[0];
submesh->indexCount = 1;
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, submesh->ibo));
glCheck(glBufferData(GL_ELEMENT_ARRAY_BUFFER, submesh->indexCount * sizeof(std::uint32_t), indices.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
//pre-process the crowd geometry
cro::ModelDefinition billboardDef(m_resources);
cro::SpriteSheet crowdSprites;
crowdSprites.loadFromFile("assets/golf/sprites/crowd.spt", m_resources.textures);
const auto& sprites = crowdSprites.getSprites();
std::vector<cro::Billboard> billboards;
for (const auto& [name, spr] : sprites)
{
billboards.push_back(spriteToBillboard(spr));
}
//used when parsing holes
auto addCrowd = [&](HoleData& holeData, glm::vec3 position, float rotation)
{
//reload to ensure unique VBO
if (!billboards.empty() &&
billboardDef.loadFromFile("assets/golf/models/crowd.cmt"))
{
auto ent = m_gameScene.createEntity();
ent.addComponent<cro::Transform>().setPosition(position);
ent.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, rotation * cro::Util::Const::degToRad);
billboardDef.createModel(ent);
glm::vec3 bbPos(-8.f, 0.f, 0.f);
for (auto i = 0; i < 16; ++i)
{
bbPos.x += 0.5f + (static_cast<float>(cro::Util::Random::value(5, 10)) / 10.f);
bbPos.z = static_cast<float>(cro::Util::Random::value(-10, 10)) / 10.f;
//images are a little oversized at 2.5m...
auto bb = billboards[(i + cro::Util::Random::value(0, 2)) % billboards.size()];
bb.size *= static_cast<float>(cro::Util::Random::value(65, 75)) / 100.f;
bb.position = bbPos;
ent.getComponent<cro::BillboardCollection>().addBillboard(bb);
}
ent.getComponent<cro::Model>().setHidden(true);
holeData.modelEntity.getComponent<cro::Transform>().addChild(ent.getComponent<cro::Transform>());
holeData.propEntities.push_back(ent);
}
};
//load the map data
bool error = false;
auto mapDir = m_sharedData.mapDirectory.toAnsiString();
auto mapPath = ConstVal::MapPath + mapDir + "/course.data";
if (!cro::FileSystem::fileExists(mapPath))
{
LOG("Course file doesn't exist", cro::Logger::Type::Error);
error = true;
}
cro::ConfigFile courseFile;
if (!courseFile.loadFromFile(mapPath))
{
error = true;
}
ThemeSettings theme;
std::vector<std::string> holeStrings;
const auto& props = courseFile.getProperties();
for (const auto& prop : props)
{
const auto& name = prop.getName();
if (name == "hole"
&& holeStrings.size() < MaxHoles)
{
holeStrings.push_back(prop.getValue<std::string>());
}
else if (name == "skybox")
{
m_gameScene.setCubemap(prop.getValue<std::string>());
//disable smoothing for super-pixels
glCheck(glBindTexture(GL_TEXTURE_CUBE_MAP, m_gameScene.getCubemap().textureID));
glCheck(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
glCheck(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
}
else if (name == "billboard_model")
{
theme.billboardModel = prop.getValue<std::string>();
}
else if (name == "billboard_sprites")
{
theme.billboardSprites = prop.getValue<std::string>();
}
else if (name == "grass")
{
theme.grassColour = prop.getValue<cro::Colour>();
}
}
if (theme.billboardModel.empty()
|| !cro::FileSystem::fileExists(theme.billboardModel))
{
LogE << "Missing or invalid billboard model definition" << std::endl;
error = true;
}
if (theme.billboardSprites.empty()
|| !cro::FileSystem::fileExists(theme.billboardSprites))
{
LogE << "Missing or invalid billboard sprite sheet" << std::endl;
error = true;
}
if (holeStrings.empty())
{
LOG("No hole files in course data", cro::Logger::Type::Error);
error = true;
}
cro::ConfigFile holeCfg;
cro::ModelDefinition modelDef(m_resources);
for (const auto& hole : holeStrings)
{
if (!cro::FileSystem::fileExists(hole))
{
LOG("Hole file is missing", cro::Logger::Type::Error);
error = true;
}
if (!holeCfg.loadFromFile(hole))
{
LOG("Failed opening hole file", cro::Logger::Type::Error);
error = true;
}
static constexpr std::int32_t MaxProps = 6;
std::int32_t propCount = 0;
auto& holeData = m_holeData.emplace_back();
const auto& holeProps = holeCfg.getProperties();
for (const auto& holeProp : holeProps)
{
const auto& name = holeProp.getName();
if (name == "map")
{
if (!m_currentMap.loadFromFile(holeProp.getValue<std::string>()))
{
error = true;
}
holeData.mapPath = holeProp.getValue<std::string>();
propCount++;
}
else if (name == "pin")
{
//TODO not sure how we ensure these are sane values?
auto pin = holeProp.getValue<glm::vec2>();
holeData.pin = { pin.x, 0.f, -pin.y };
propCount++;
}
else if (name == "tee")
{
auto tee = holeProp.getValue<glm::vec2>();
holeData.tee = { tee.x, 0.f, -tee.y };
propCount++;
}
else if (name == "target")
{
auto target = holeProp.getValue<glm::vec2>();
holeData.target = { target.x, 0.f, -target.y };
if (glm::length2(holeData.target) > 0)
{
propCount++;
}
}
else if (name == "par")
{
holeData.par = holeProp.getValue<std::int32_t>();
if (holeData.par < 1 || holeData.par > 10)
{
LOG("Invalid PAR value", cro::Logger::Type::Error);
error = true;
}
propCount++;
}
else if (name == "model")
{
if (modelDef.loadFromFile(holeProp.getValue<std::string>()))
{
auto material = m_resources.materials.get(m_materialIDs[MaterialID::Course]);
setTexture(modelDef, material);
holeData.modelEntity = m_gameScene.createEntity();
holeData.modelEntity.addComponent<cro::Transform>();
holeData.modelEntity.addComponent<cro::Callback>();
modelDef.createModel(holeData.modelEntity);
holeData.modelEntity.getComponent<cro::Model>().setHidden(true);
holeData.modelEntity.getComponent<cro::Model>().setMaterial(0, material);
propCount++;
}
else
{
LOG("Failed loading model file", cro::Logger::Type::Error);
error = true;
}
}
}
if (propCount != MaxProps)
{
LOG("Missing hole property", cro::Logger::Type::Error);
error = true;
}
else
{
//look for prop models (are optional and can fail to load no problem)
const auto& propObjs = holeCfg.getObjects();
for (const auto& obj : propObjs)
{
const auto& name = obj.getName();
if (name == "prop")
{
const auto& modelProps = obj.getProperties();
glm::vec3 position(0.f);
float rotation = 0.f;
std::string path;
for (const auto& modelProp : modelProps)
{
auto propName = modelProp.getName();
if (propName == "position")
{
position = modelProp.getValue<glm::vec3>();
}
else if (propName == "model")
{
path = modelProp.getValue<std::string>();
}
else if (propName == "rotation")
{
rotation = modelProp.getValue<float>();
}
}
if (!path.empty()
&& cro::FileSystem::fileExists(path))
{
if (modelDef.loadFromFile(path))
{
auto ent = m_gameScene.createEntity();
ent.addComponent<cro::Transform>().setPosition(position);
ent.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, rotation* cro::Util::Const::degToRad);
modelDef.createModel(ent);
if (modelDef.hasSkeleton())
{
ent.getComponent<cro::Skeleton>().play(0);
//TODO we need to specialise the material for skinned models.
}
else
{
auto texturedMat = m_resources.materials.get(m_materialIDs[MaterialID::CelTextured]);
setTexture(modelDef, texturedMat);
ent.getComponent<cro::Model>().setMaterial(0, texturedMat);
}
ent.getComponent<cro::Model>().setHidden(true);
ent.getComponent<cro::Model>().setRenderFlags(~(RenderFlags::MiniGreen | RenderFlags::MiniMap));
holeData.modelEntity.getComponent<cro::Transform>().addChild(ent.getComponent<cro::Transform>());
holeData.propEntities.push_back(ent);
}
}
}
else if (name == "crowd")
{
const auto& modelProps = obj.getProperties();
glm::vec3 position(0.f);
float rotation = 0.f;
for (const auto& modelProp : modelProps)
{
auto propName = modelProp.getName();
if (propName == "position")
{
position = modelProp.getValue<glm::vec3>();
}
else if (propName == "rotation")
{
rotation = modelProp.getValue<float>();
}
}
addCrowd(holeData, position, rotation);
}
}
}
}
if (error)
{
m_sharedData.errorMessage = "Failed to load course data";
requestStackPush(StateID::Error);
}
//else
{
m_terrainBuilder.create(m_resources, m_gameScene, theme);
}
//reserve the slots for each hole score
for (auto& client : m_sharedData.connectionData)
{
for (auto& player : client.playerData)
{
player.score = 0;
player.holeScores.clear();
player.holeScores.resize(holeStrings.size());
std::fill(player.holeScores.begin(), player.holeScores.end(), 0);
}
}
}
void GolfState::addSystems()
{
auto& mb = m_gameScene.getMessageBus();
m_gameScene.addSystem<InterpolationSystem>(mb);
m_gameScene.addSystem<ClientCollisionSystem>(mb, m_holeData);
m_gameScene.addSystem<cro::CommandSystem>(mb);
m_gameScene.addSystem<cro::CallbackSystem>(mb);
m_gameScene.addSystem<cro::SkeletalAnimator>(mb);
m_gameScene.addSystem<cro::BillboardSystem>(mb);
m_gameScene.addSystem<CameraFollowSystem>(mb);
m_gameScene.addSystem<cro::CameraSystem>(mb);
m_gameScene.addSystem<cro::ModelRenderer>(mb);
m_gameScene.addSystem<cro::ParticleSystem>(mb);
m_gameScene.addSystem<cro::AudioSystem>(mb);
m_gameScene.setSystemActive<CameraFollowSystem>(false);
m_gameScene.addDirector<GolfParticleDirector>(m_resources.textures);
m_gameScene.addDirector<GolfSoundDirector>(m_resources.audio);
if (m_sharedData.tutorial)
{
m_gameScene.addDirector<TutorialDirector>(m_sharedData, m_inputParser);
}
m_uiScene.addSystem<cro::CallbackSystem>(mb);
m_uiScene.addSystem<cro::CommandSystem>(mb);
m_uiScene.addSystem<cro::CameraSystem>(mb);
m_uiScene.addSystem<cro::TextSystem>(mb);
m_uiScene.addSystem<cro::SpriteSystem2D>(mb);
m_uiScene.addSystem<cro::SpriteAnimator>(mb);
m_uiScene.addSystem<cro::RenderSystem2D>(mb);
}
void GolfState::buildScene()
{
if (m_holeData.empty())
{
return;
}
//quality holing
cro::ModelDefinition md(m_resources);
md.loadFromFile("assets/golf/models/cup.cmt");
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>();
md.createModel(entity);
auto holeEntity = entity;
md.loadFromFile("assets/golf/models/flag.cmt");
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>();
entity.addComponent<cro::CommandTarget>().ID = CommandID::Flag;
entity.addComponent<float>() = 0.f;
md.createModel(entity);
if (md.hasSkeleton())
{
entity.getComponent<cro::Skeleton>().play(0);
}
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<FlagCallbackData>();
entity.getComponent<cro::Callback>().function =
[](cro::Entity e, float dt)
{
auto pos = e.getComponent<cro::Transform>().getPosition();
auto& data = e.getComponent<cro::Callback>().getUserData<FlagCallbackData>();
if (data.currentHeight < data.targetHeight)
{
data.currentHeight = std::min(FlagCallbackData::MaxHeight, data.currentHeight + dt);
pos.y = cro::Util::Easing::easeOutExpo(data.currentHeight / FlagCallbackData::MaxHeight);
}
else
{
data.currentHeight = std::max(0.f, data.currentHeight - dt);
pos.y = cro::Util::Easing::easeInExpo(data.currentHeight / FlagCallbackData::MaxHeight);
}
e.getComponent<cro::Transform>().setPosition(pos);
if (data.currentHeight == data.targetHeight)
{
e.getComponent<cro::Callback>().active = false;
}
};
auto flagEntity = entity;
//displays the stroke direction
auto pos = m_holeData[0].tee;
pos.y += 0.01f;
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(pos);
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().function =
[&](cro::Entity e, float)
{
e.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, m_inputParser.getYaw());
};
entity.addComponent<cro::CommandTarget>().ID = CommandID::StrokeIndicator;
auto meshID = m_resources.meshes.loadMesh(cro::DynamicMeshBuilder(cro::VertexProperty::Position | cro::VertexProperty::Colour, 1, GL_LINE_STRIP));
auto material = m_resources.materials.get(m_materialIDs[MaterialID::WireFrame]);
entity.addComponent<cro::Model>(m_resources.meshes.getMesh(meshID), material);
auto* meshData = &entity.getComponent<cro::Model>().getMeshData();
std::vector<float> verts =
{
0.f, 0.05f, 0.f, 1.f, 0.97f, 0.88f, 1.f,
5.f, 0.1f, 0.f, 1.f, 0.97f, 0.88f, 0.2f
};
std::vector<std::uint32_t> indices =
{
0,1
};
auto vertStride = (meshData->vertexSize / sizeof(float));
meshData->vertexCount = verts.size() / vertStride;
glCheck(glBindBuffer(GL_ARRAY_BUFFER, meshData->vbo));
glCheck(glBufferData(GL_ARRAY_BUFFER, meshData->vertexSize * meshData->vertexCount, verts.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ARRAY_BUFFER, 0));
auto* submesh = &meshData->indexData[0];
submesh->indexCount = static_cast<std::uint32_t>(indices.size());
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, submesh->ibo));
glCheck(glBufferData(GL_ELEMENT_ARRAY_BUFFER, submesh->indexCount * sizeof(std::uint32_t), indices.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
entity.getComponent<cro::Model>().setHidden(true);
entity.getComponent<cro::Model>().setRenderFlags(~(RenderFlags::MiniGreen | RenderFlags::MiniMap));
//draw the flag pole as a single line which can be
//see from a distance - hole and model are also attached to this
material = m_resources.materials.get(m_materialIDs[MaterialID::WireFrameCulled]);
material.setProperty("u_colour", cro::Colour::White);
meshID = m_resources.meshes.loadMesh(cro::DynamicMeshBuilder(cro::VertexProperty::Position | cro::VertexProperty::Colour, 1, GL_LINE_STRIP));
entity = m_gameScene.createEntity();
entity.addComponent<cro::CommandTarget>().ID = CommandID::Hole;
entity.addComponent<cro::Model>(m_resources.meshes.getMesh(meshID), material);
entity.addComponent<cro::Transform>().setPosition(m_holeData[0].pin);
entity.getComponent<cro::Transform>().addChild(holeEntity.getComponent<cro::Transform>());
entity.getComponent<cro::Transform>().addChild(flagEntity.getComponent<cro::Transform>());
meshData = &entity.getComponent<cro::Model>().getMeshData();
verts =
{
0.f, 2.f, 0.f, LeaderboardTextLight.getRed(), LeaderboardTextLight.getGreen(), LeaderboardTextLight.getBlue(), 1.f,
0.f, 0.f, 0.f, LeaderboardTextLight.getRed(), LeaderboardTextLight.getGreen(), LeaderboardTextLight.getBlue(), 1.f,
0.f, 0.001f, 0.f, 0.f, 0.f, 0.f, 0.5f,
1.4f, 0.001f, 1.4f, 0.f, 0.f, 0.f, 0.01f,
};
indices =
{
0,1,2,3
};
meshData->vertexCount = verts.size() / vertStride;
glCheck(glBindBuffer(GL_ARRAY_BUFFER, meshData->vbo));
glCheck(glBufferData(GL_ARRAY_BUFFER, meshData->vertexSize * meshData->vertexCount, verts.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ARRAY_BUFFER, 0));
submesh = &meshData->indexData[0];
submesh->indexCount = static_cast<std::uint32_t>(indices.size());
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, submesh->ibo));
glCheck(glBufferData(GL_ELEMENT_ARRAY_BUFFER, submesh->indexCount * sizeof(std::uint32_t), indices.data(), GL_STATIC_DRAW));
glCheck(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
//attach a water plane to the camera
//this is updated when positioning the camera
meshID = m_resources.meshes.loadMesh(cro::CircleMeshBuilder(150.f, 30));
auto waterEnt = m_gameScene.createEntity();
waterEnt.addComponent<cro::Transform>().setPosition(m_holeData[0].pin);
waterEnt.getComponent<cro::Transform>().move({ 0.f, 0.f, -30.f });
waterEnt.getComponent<cro::Transform>().rotate(cro::Transform::X_AXIS, -cro::Util::Const::PI / 2.f);
waterEnt.addComponent<cro::Model>(m_resources.meshes.getMesh(meshID), m_resources.materials.get(m_materialIDs[MaterialID::Water]));
waterEnt.getComponent<cro::Model>().setRenderFlags(~RenderFlags::MiniMap);
m_gameScene.setWaterLevel(WaterLevel);
//tee marker
md.loadFromFile("assets/golf/models/tee_balls.cmt");
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(m_holeData[0].tee);
entity.addComponent<cro::CommandTarget>().ID = CommandID::Tee;
md.createModel(entity);
entity.getComponent<cro::Model>().setMaterial(0, m_resources.materials.get(m_materialIDs[MaterialID::Cel]));
auto targetDir = m_holeData[m_currentHole].target - m_holeData[0].tee;
m_camRotation = std::atan2(-targetDir.z, targetDir.x);
entity.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, m_camRotation);
auto teeEnt = entity;
//player shadow
static constexpr float ShadowScale = 20.f;
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(m_holeData[0].tee);
entity.getComponent<cro::Transform>().setOrigin({0.f, 0.f, PlayerShadowOffset});
entity.getComponent<cro::Transform>().setScale(glm::vec3(0.f, 1.f, ShadowScale));
entity.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, m_camRotation);
entity.addComponent<cro::CommandTarget>().ID = CommandID::PlayerShadow;
entity.addComponent<cro::Callback>().setUserData<float>(0.f);
entity.getComponent<cro::Callback>().function =
[](cro::Entity e, float dt)
{
auto& currTime = e.getComponent<cro::Callback>().getUserData<float>();
currTime = std::min(1.f, currTime + (dt * 2.f));
e.getComponent<cro::Transform>().setScale({ ShadowScale * cro::Util::Easing::easeOutBounce(currTime), 1.f, ShadowScale });
if(currTime == 1)
{
currTime = 0.f;
e.getComponent<cro::Callback>().active = false;
}
};
m_modelDefs[ModelID::BallShadow]->createModel(entity);
//carts
md.loadFromFile("assets/golf/models/cart.cmt");
auto texturedMat = m_resources.materials.get(m_materialIDs[MaterialID::CelTextured]);
setTexture(md, texturedMat);
std::array cartPositions =
{
glm::vec3(-0.4f, 0.f, -5.9f),
glm::vec3(2.6f, 0.f, -6.9f),
glm::vec3(2.2f, 0.f, 6.9f),
glm::vec3(-1.2f, 0.f, 5.2f)
};
//add a cart for each connected client :3
for (auto i = 0u; i < m_sharedData.connectionData.size(); ++i)
{
if (m_sharedData.connectionData[i].playerCount > 0)
{
auto r = i + cro::Util::Random::value(0, 8);
float rotation = (cro::Util::Const::PI / 4.f) * r;
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(cartPositions[i]);
entity.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, rotation);
entity.addComponent<cro::CommandTarget>().ID = CommandID::Cart;
md.createModel(entity);
entity.getComponent<cro::Model>().setMaterial(0, texturedMat);
teeEnt.getComponent<cro::Transform>().addChild(entity.getComponent<cro::Transform>());
}
}
//update the 3D view
auto updateView = [&](cro::Camera& cam)
{
auto vpSize = calcVPSize();
auto winSize = glm::vec2(cro::App::getWindow().getSize());
float scale = std::floor(winSize.y / vpSize.y);
auto texSize = vpSize;
if (texSize.x * scale <= winSize.x)
{
//for odd res like 720x480 expand out to the sides
texSize *= 1.6f;
}
m_gameSceneTexture.create(static_cast<std::uint32_t>(texSize.x), static_cast<std::uint32_t>(texSize.y));
//the resize actually extends the target vertically so we need to maintain a
//horizontal FOV, not the vertical one expected by default.
cam.setPerspective(FOV * (texSize.y / ViewportHeight), vpSize.x / vpSize.y, 0.1f, vpSize.x);
cam.viewport = { 0.f, 0.f, 1.f, 1.f };
//because we don't know in which order the cam callbacks are raised
//we need to send the player repos command from here when we know the view is correct
cro::Command cmd;
cmd.targetFlags = CommandID::UI::PlayerSprite;
cmd.action = [&](cro::Entity e, float)
{
const auto& camera = m_cameras[CameraID::Player].getComponent<cro::Camera>();
auto pos = camera.coordsToPixel(m_currentPlayer.position, m_gameSceneTexture.getSize());
e.getComponent<cro::Transform>().setPosition(pos);
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
};
auto camEnt = m_gameScene.getActiveCamera();
m_cameras[CameraID::Player] = camEnt;
auto& cam = camEnt.getComponent<cro::Camera>();
cam.resizeCallback = updateView;
updateView(cam);
//used by transition callback to interp camera
camEnt.addComponent<TargetInfo>().waterPlane = waterEnt;
camEnt.getComponent<TargetInfo>().targetLookAt = m_holeData[0].target;
cam.reflectionBuffer.create(1024, 1024);
//create an overhead camera
auto setPerspective = [](cro::Camera& cam)
{
auto vpSize = calcVPSize();
//the resize actually extends the target vertically so we need to maintain a
//horizontal FOV, not the vertical one expected by default.
cam.setPerspective(FOV * (vpSize.y / ViewportHeight), vpSize.x / vpSize.y, 0.1f, vpSize.x);
cam.viewport = { 0.f, 0.f, 1.f, 1.f };
};
camEnt = m_gameScene.createEntity();
camEnt.addComponent<cro::Transform>().setPosition({ MapSize.x / 2.f, 16.f, -static_cast<float>(MapSize.y) / 2.f });
camEnt.addComponent<cro::Camera>().resizeCallback =
[camEnt](cro::Camera& cam) //use explicit callback so we can capture the entity and use it to zoom via CamFollowSystem
{
auto vpSize = calcVPSize();
cam.setPerspective(FOV * (vpSize.y / ViewportHeight) * camEnt.getComponent<CameraFollower>().zoom.fov, vpSize.x / vpSize.y, 0.1f, vpSize.x);
cam.viewport = { 0.f, 0.f, 1.f, 1.f };
};
camEnt.getComponent<cro::Camera>().reflectionBuffer.create(1024, 1024);
camEnt.addComponent<cro::CommandTarget>().ID = CommandID::SpectatorCam;
camEnt.addComponent<CameraFollower>().radius = 80.f * 80.f;
camEnt.getComponent<CameraFollower>().id = CameraID::Sky;
camEnt.getComponent<CameraFollower>().zoom.target = 0.1f;
camEnt.getComponent<CameraFollower>().zoom.speed = 3.f;
camEnt.addComponent<cro::AudioListener>();
setPerspective(camEnt.getComponent<cro::Camera>());
m_cameras[CameraID::Sky] = camEnt;
//and a green camera
camEnt = m_gameScene.createEntity();
camEnt.addComponent<cro::Transform>();
camEnt.addComponent<cro::Camera>().resizeCallback =
[camEnt](cro::Camera& cam)
{
auto vpSize = calcVPSize();
cam.setPerspective(FOV * (vpSize.y / ViewportHeight) * camEnt.getComponent<CameraFollower>().zoom.fov, vpSize.x / vpSize.y, 0.1f, vpSize.x);
cam.viewport = { 0.f, 0.f, 1.f, 1.f };
};
camEnt.getComponent<cro::Camera>().reflectionBuffer.create(1024, 1024);
camEnt.addComponent<cro::CommandTarget>().ID = CommandID::SpectatorCam;
camEnt.addComponent<CameraFollower>().radius = 30.f * 30.f;
camEnt.getComponent<CameraFollower>().id = CameraID::Green;
camEnt.getComponent<CameraFollower>().zoom.speed = 2.f;
camEnt.addComponent<cro::AudioListener>();
setPerspective(camEnt.getComponent<cro::Camera>());
m_cameras[CameraID::Green] = camEnt;
m_currentPlayer.position = m_holeData[m_currentHole].tee; //prevents the initial camera movement
buildUI(); //put this here because we don't want to do this if the map data didn't load
setCurrentHole(0);
//careful with these values - they are fine tuned for shadowing of terrain
auto sunEnt = m_gameScene.getSunlight();
//sunEnt.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, /*-0.967f*/-45.f * cro::Util::Const::degToRad);
sunEnt.getComponent<cro::Transform>().setRotation(cro::Transform::X_AXIS, /*-1.5f*/-38.746f * cro::Util::Const::degToRad);
#ifdef CRO_DEBUG_
//createWeather();
#endif
}
void GolfState::initAudio()
{
//4 evenly spaced points with ambient audio
auto envOffset = glm::vec2(MapSize) / 3.f;
cro::AudioScape as;
as.loadFromFile("assets/golf/sound/ambience.xas", m_resources.audio);
std::array emitterNames =
{
std::string("01"),
std::string("02"),
std::string("03"),
std::string("04"),
std::string("05"),
std::string("06"),
std::string("05"),
std::string("06"),
};
for (auto i = 0; i < 2; ++i)
{
for (auto j = 0; j < 2; ++j)
{
static constexpr float height = 4.f;
glm::vec3 position(envOffset.x * (i + 1), height, -envOffset.y * (j + 1));
auto idx = i * 2 + j;
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(position);
entity.addComponent<cro::AudioEmitter>() = as.getEmitter(emitterNames[idx + 4]);
entity.getComponent<cro::AudioEmitter>().play();
position = { i * MapSize.x, height, -static_cast<float>(MapSize.y) * j };
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(position);
entity.addComponent<cro::AudioEmitter>() = as.getEmitter(emitterNames[idx]);
entity.getComponent<cro::AudioEmitter>().play();
}
}
//random plane audio
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::AudioEmitter>() = as.getEmitter("plane");
auto plane01 = entity;
entity = m_gameScene.createEntity();
entity.addComponent<cro::AudioEmitter>() = as.getEmitter("plane02");
auto plane02 = entity;
entity = m_gameScene.createEntity();
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<std::pair<float, float>>(0.f, static_cast<float>(cro::Util::Random::value(12, 64)));
entity.getComponent<cro::Callback>().function =
[plane01, plane02](cro::Entity e, float dt) mutable
{
auto& [currTime, timeOut] = e.getComponent<cro::Callback>().getUserData<std::pair<float, float>>();
currTime += dt;
if (currTime > timeOut)
{
currTime = 0.f;
timeOut = static_cast<float>(cro::Util::Random::value(90, 170));
auto ent = cro::Util::Random::value(0, 20) % 2 == 0 ? plane01 : plane02;
if (ent.getComponent<cro::AudioEmitter>().getState() == cro::AudioEmitter::State::Stopped)
{
ent.getComponent<cro::AudioEmitter>().play();
}
}
};
//put the new hole music on the cam for accessabilty
//this is done *before* m_cameras is updated
m_gameScene.getActiveCamera().addComponent<cro::AudioEmitter>() = as.getEmitter("music");
}
void GolfState::spawnBall(const ActorInfo& info)
{
auto ballID = m_sharedData.connectionData[info.clientID].playerData[info.playerID].ballID;
//render the ball as a point so no perspective is applied to the scale
auto material = m_resources.materials.get(m_ballResources.materialID);
auto ball = std::find_if(m_sharedData.ballModels.begin(), m_sharedData.ballModels.end(),
[ballID](const SharedStateData::BallInfo& ballPair)
{
return ballPair.uid == ballID;
});
if (ball != m_sharedData.ballModels.end())
{
material.setProperty("u_colour", ball->tint);
}
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(info.position);
entity.getComponent<cro::Transform>().setOrigin({ 0.f, -0.003f, 0.f }); //pushes the ent above the ground a bit to stop Z fighting
entity.addComponent<cro::CommandTarget>().ID = CommandID::Ball;
entity.addComponent<InterpolationComponent>().setID(info.serverID);
entity.addComponent<ClientCollider>().previousPosition = info.position;
entity.addComponent<cro::Model>(m_resources.meshes.getMesh(m_ballResources.ballMeshID), material);
//ball shadow
auto ballEnt = entity;
material.setProperty("u_colour", cro::Colour::White);
material.blendMode = cro::Material::BlendMode::Multiply;
//point shadow seen from distance
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(info.position);
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().function =
[&, ballEnt](cro::Entity e, float)
{
if (ballEnt.destroyed())
{
e.getComponent<cro::Callback>().active = false;
m_gameScene.destroyEntity(e);
}
else
{
auto ballPos = ballEnt.getComponent<cro::Transform>().getPosition();
ballPos.y = std::min(0.003f, ballPos.y); //just to prevent z-fighting
e.getComponent<cro::Transform>().setPosition(ballPos);
}
};
entity.addComponent<cro::Model>(m_resources.meshes.getMesh(m_ballResources.shadowMeshID), material);
//large shadow seen close up
auto shadowEnt = entity;
entity = m_gameScene.createEntity();
shadowEnt.getComponent<cro::Transform>().addChild(entity.addComponent<cro::Transform>());
m_modelDefs[ModelID::BallShadow]->createModel(entity);
entity.getComponent<cro::Transform>().setScale(glm::vec3(1.3f));
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().function =
[&,ballEnt](cro::Entity e, float)
{
if (ballEnt.destroyed())
{
e.getComponent<cro::Callback>().active = false;
m_gameScene.destroyEntity(e);
}
};
//adding a ball model means we see something a bit more reasonable when close up
entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>();
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().function =
[&, ballEnt](cro::Entity e, float)
{
if (ballEnt.destroyed())
{
e.getComponent<cro::Callback>().active = false;
m_gameScene.destroyEntity(e);
}
};
if (m_ballModels.count(ballID) != 0)
{
m_ballModels[ballID]->createModel(entity);
}
else
{
//a bit dangerous assuming we're not empty, but we
//shouldn't have made it this far without loading at least something...
LogW << "Ball with ID " << (int)ballID << " not found" << std::endl;
m_ballModels.begin()->second->createModel(entity);
}
entity.getComponent<cro::Model>().setMaterial(0, m_resources.materials.get(m_materialIDs[MaterialID::Cel]));
ballEnt.getComponent<cro::Transform>().addChild(entity.getComponent<cro::Transform>());
//name label for the ball's owner
glm::vec2 texSize(LabelTextureSize);
auto playerID = info.playerID;
auto clientID = info.clientID;
entity = m_uiScene.createEntity();
entity.addComponent<cro::Transform>().setOrigin({ texSize.x / 2.f, 0.f, 0.f });
entity.addComponent<cro::Drawable2D>();
entity.addComponent<cro::Sprite>().setTexture(m_sharedData.nameTextures[info.clientID].getTexture());
entity.getComponent<cro::Sprite>().setTextureRect({ 0.f, playerID * (texSize.y / 4.f), texSize.x, texSize.y / 4.f });
entity.getComponent<cro::Sprite>().setColour(cro::Colour(1.f, 1.f, 1.f, 0.f));
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().function =
[&, ballEnt, playerID, clientID](cro::Entity e, float dt)
{
if (ballEnt.destroyed())
{
e.getComponent<cro::Callback>().active = false;
m_uiScene.destroyEntity(e);
}
auto terrain = ballEnt.getComponent<ClientCollider>().terrain;
auto colour = e.getComponent<cro::Sprite>().getColour();
auto position = ballEnt.getComponent<cro::Transform>().getPosition();
position.y += Ball::Radius * 3.f;
auto labelPos = m_gameScene.getActiveCamera().getComponent<cro::Camera>().coordsToPixel(position, m_gameSceneTexture.getSize());
const float halfWidth = m_gameSceneTexture.getSize().x / 2.f;
/*static constexpr float MaxLabelOffset = 70.f;
float diff = labelPos.x - halfWidth;
if (diff < -1)
{
labelPos.x = std::min(labelPos.x, halfWidth - MaxLabelOffset);
}
else
{
labelPos.x = std::max(labelPos.x, halfWidth + MaxLabelOffset);
}*/
e.getComponent<cro::Transform>().setPosition(labelPos);
if (terrain == TerrainID::Green)
{
if (m_currentPlayer.player == playerID
&& m_sharedData.clientConnection.connectionID == clientID)
{
//set target fade to zero
colour.setAlpha(std::max(0.f, colour.getAlpha() - dt));
}
else
{
//calc target fade based on distance to the camera
const auto& camTx = m_cameras[CameraID::Player].getComponent<cro::Transform>();
auto camPos = camTx.getPosition();
auto ballVec = position - camPos;
auto len2 = glm::length2(ballVec);
static constexpr float MinLength = 64.f; //8m^2
float alpha = smoothstep(0.05f, 0.5f, 1.f - std::min(1.f, std::max(0.f, len2 / MinLength)));
//fade slightly near the centre of the screen
//prevent blocking the view
float halfPos = labelPos.x - halfWidth;
float amount = std::min(1.f, std::max(0.f, std::abs(halfPos) / halfWidth));
amount = 0.1f + (smoothstep(0.12f, 0.26f, amount) * 0.85f); //remember tex size is probably a lot wider than the window
alpha *= amount;
float currentAlpha = colour.getAlpha();
colour.setAlpha(std::max(0.f, std::min(1.f, currentAlpha + (dt * cro::Util::Maths::sgn(alpha - currentAlpha)))));
}
e.getComponent<cro::Sprite>().setColour(colour);
}
else
{
colour.setAlpha(std::max(0.f, colour.getAlpha() - dt));
e.getComponent<cro::Sprite>().setColour(colour);
}
};
m_courseEnt.getComponent<cro::Transform>().addChild(entity.getComponent<cro::Transform>());
}
void GolfState::handleNetEvent(const cro::NetEvent& evt)
{
switch (evt.type)
{
case cro::NetEvent::PacketReceived:
switch (evt.packet.getID())
{
default: break;
case PacketID::BallLanded:
{
auto update = evt.packet.as<BallUpdate>();
switch (update.terrain)
{
default: break;
case TerrainID::Bunker:
showMessageBoard(MessageBoardID::Bunker);
break;
case TerrainID::Scrub:
showMessageBoard(MessageBoardID::Scrub);
break;
case TerrainID::Water:
showMessageBoard(MessageBoardID::Water);
break;
case TerrainID::Hole:
showMessageBoard(MessageBoardID::HoleScore);
break;
}
auto* msg = cro::App::getInstance().getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg->type = GolfEvent::BallLanded;
msg->terrain = update.terrain;
msg->club = getClub();
msg->travelDistance = glm::length2(update.position - m_currentPlayer.position);
msg->pinDistance = glm::length2(update.position - m_holeData[m_currentHole].pin);
}
break;
case PacketID::ClientDisconnected:
{
removeClient(evt.packet.as<std::uint8_t>());
}
break;
case PacketID::ServerError:
switch (evt.packet.as<std::uint8_t>())
{
default:
m_sharedData.errorMessage = "Server Error (Unknown)";
break;
case MessageType::MapNotFound:
m_sharedData.errorMessage = "Server Failed To Load Map";
break;
}
requestStackPush(StateID::Error);
break;
case PacketID::SetPlayer:
m_wantsGameState = false;
{
auto playerData = evt.packet.as<ActivePlayer>();
createTransition(playerData);
}
break;
case PacketID::ActorSpawn:
spawnBall(evt.packet.as<ActorInfo>());
break;
case PacketID::ActorUpdate:
updateActor( evt.packet.as<ActorInfo>());
break;
case PacketID::ActorAnimation:
{
auto animID = evt.packet.as<std::uint8_t>();
cro::Command cmd;
cmd.targetFlags = CommandID::UI::PlayerSprite;
cmd.action = [animID](cro::Entity e, float)
{
e.getComponent<cro::SpriteAnimation>().play(animID);
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
break;
case PacketID::WindDirection:
updateWindDisplay(cro::Util::Net::decompressVec3(evt.packet.as<std::array<std::int16_t, 3u>>()));
break;
case PacketID::SetHole:
setCurrentHole(evt.packet.as<std::uint8_t>());
break;
case PacketID::ScoreUpdate:
{
auto su = evt.packet.as<ScoreUpdate>();
auto& player = m_sharedData.connectionData[su.client].playerData[su.player];
if (su.hole < player.holeScores.size())
{
player.score = su.score;
player.holeScores[su.hole] = su.stroke;
}
}
break;
case PacketID::GameEnd:
showCountdown(evt.packet.as<std::uint8_t>());
break;
case PacketID::StateChange:
if (evt.packet.as<std::uint8_t>() == sv::StateID::Lobby)
{
requestStackClear();
requestStackPush(StateID::Menu);
}
break;
case PacketID::EntityRemoved:
{
auto idx = evt.packet.as<std::uint32_t>();
cro::Command cmd;
cmd.targetFlags = CommandID::Ball;
cmd.action = [&,idx](cro::Entity e, float)
{
if (e.getComponent<InterpolationComponent>().getID() == idx)
{
m_gameScene.destroyEntity(e);
}
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
break;
}
break;
case cro::NetEvent::ClientDisconnect:
m_sharedData.errorMessage = "Disconnected From Server (Host Quit)";
requestStackPush(StateID::Error);
break;
default: break;
}
}
void GolfState::removeClient(std::uint8_t clientID)
{
cro::String str = m_sharedData.connectionData[clientID].playerData[0].name;
for (auto i = 1u; i < m_sharedData.connectionData[clientID].playerCount; ++i)
{
str += ", " + m_sharedData.connectionData[clientID].playerData[i].name;
}
str += " left the game";
auto entity = m_uiScene.createEntity();
entity.addComponent<cro::Transform>().setPosition({ 4.f, UIBarHeight * m_viewScale.y * 2.f });
entity.addComponent<cro::Drawable2D>();
entity.addComponent<cro::Text>(m_sharedData.sharedResources->fonts.get(FontID::UI)).setString(str);
entity.getComponent<cro::Text>().setCharacterSize(8u * static_cast<std::uint32_t>(m_viewScale.y));
entity.getComponent<cro::Text>().setFillColour(LeaderboardTextLight);
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<float>(5.f);
entity.getComponent<cro::Callback>().function =
[&](cro::Entity e, float dt)
{
auto& currTime = e.getComponent<cro::Callback>().getUserData<float>();
currTime -= dt;
if (currTime < 0)
{
e.getComponent<cro::Callback>().active = false;
m_uiScene.destroyEntity(e);
}
};
m_sharedData.connectionData[clientID].playerCount = 0;
}
void GolfState::setCurrentHole(std::uint32_t hole)
{
updateScoreboard();
showScoreboard(!m_sharedData.tutorial);
//CRO_ASSERT(hole < m_holeData.size(), "");
if (hole >= m_holeData.size())
{
m_sharedData.errorMessage = "Server requested hole\nnot found";
requestStackPush(StateID::Error);
return;
}
m_terrainBuilder.update(hole);
m_gameScene.getSystem<ClientCollisionSystem>()->setMap(hole);
//create hole model transition
auto* propModels = &m_holeData[m_currentHole].propEntities;
m_holeData[m_currentHole].modelEntity.getComponent<cro::Callback>().active = true;
m_holeData[m_currentHole].modelEntity.getComponent<cro::Callback>().setUserData<float>(0.f);
m_holeData[m_currentHole].modelEntity.getComponent<cro::Callback>().function =
[&, propModels](cro::Entity e, float dt)
{
auto& progress = e.getComponent<cro::Callback>().getUserData<float>();
progress = std::min(1.f, progress + dt);
float scale = 1.f - progress;
e.getComponent<cro::Transform>().setScale({ scale, 1.f, scale });
if (progress == 1)
{
e.getComponent<cro::Callback>().active = false;
e.getComponent<cro::Model>().setHidden(true);
for (auto i = 0u; i < propModels->size(); ++i)
{
propModels->at(i).getComponent<cro::Model>().setHidden(true);
}
//index should be updated by now (as this is a callback)
//so we're actually targetting the next hole entity
auto entity = m_holeData[m_currentHole].modelEntity;
entity.getComponent<cro::Model>().setHidden(false);
entity.getComponent<cro::Transform>().setScale({ 0.f, 1.f, 0.f });
entity.getComponent<cro::Callback>().setUserData<float>(0.f);
entity.getComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().function =
[](cro::Entity ent, float dt)
{
auto& progress = ent.getComponent<cro::Callback>().getUserData<float>();
progress = std::min(1.f, progress + dt);
float scale = progress;
ent.getComponent<cro::Transform>().setScale({ scale, 1.f, scale });
if (progress == 1)
{
ent.getComponent<cro::Callback>().active = false;
}
};
//unhide any prop models
for (auto prop : m_holeData[m_currentHole].propEntities)
{
prop.getComponent<cro::Model>().setHidden(false);
}
}
};
m_currentHole = hole;
//map collision data
m_currentMap.loadFromFile(m_holeData[m_currentHole].mapPath);
glm::vec2 size(m_currentMap.getSize());
m_holeData[m_currentHole].modelEntity.getComponent<cro::Transform>().setPosition({ size.x / 2.f, 0.f, -size.y / 2.f });
//make sure we have the correct target position
m_cameras[CameraID::Player].getComponent<TargetInfo>().targetHeight = CameraStrokeHeight;
m_cameras[CameraID::Player].getComponent<TargetInfo>().targetOffset = CameraStrokeOffset;
m_cameras[CameraID::Player].getComponent<TargetInfo>().targetLookAt = m_holeData[m_currentHole].target;
//creates an entity which calls setCamPosition() in an
//interpolated manner until we reach the dest,
//at which point the ent destroys itself - also interps the position of the tee/flag
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(m_currentPlayer.position);
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<glm::vec3>(m_currentPlayer.position);
entity.getComponent<cro::Callback>().function =
[&, hole](cro::Entity e, float dt)
{
auto currPos = e.getComponent<cro::Transform>().getPosition();
auto travel = m_holeData[m_currentHole].tee - currPos;
auto& targetInfo = m_cameras[CameraID::Player].getComponent<TargetInfo>();
//if we're moving on to any other than the first hole, interp the
//tee and hole position based on how close to the tee the camera is
float percent = 1.f;
if (hole > 0)
{
auto startPos = e.getComponent<cro::Callback>().getUserData<glm::vec3>();
auto totalDist = glm::length(m_holeData[m_currentHole].tee - startPos);
auto currentDist = glm::length(travel);
percent = (totalDist - currentDist) / totalDist;
percent = std::min(1.f, std::max(0.f, percent));
targetInfo.currentLookAt = targetInfo.prevLookAt + ((targetInfo.targetLookAt - targetInfo.prevLookAt) * percent);
auto pinMove = m_holeData[m_currentHole].pin - m_holeData[m_currentHole - 1].pin;
auto pinPos = m_holeData[m_currentHole - 1].pin + (pinMove * percent);
cro::Command cmd;
cmd.targetFlags = CommandID::Hole;
cmd.action = [pinPos](cro::Entity e, float)
{
e.getComponent<cro::Transform>().setPosition(pinPos);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
auto teeMove = m_holeData[m_currentHole].tee - m_holeData[m_currentHole - 1].tee;
auto teePos = m_holeData[m_currentHole - 1].tee + (teeMove * percent);
cmd.targetFlags = CommandID::Tee;
cmd.action = [&, teePos](cro::Entity e, float)
{
e.getComponent<cro::Transform>().setPosition(teePos);
auto pinDir = m_holeData[m_currentHole].target - teePos;
auto rotation = std::atan2(-pinDir.z, pinDir.x);
e.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, rotation);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
auto targetDir = m_holeData[m_currentHole].target - currPos;
m_camRotation = std::atan2(-targetDir.z, targetDir.x);
//randomise the cart positions a bit
cmd.targetFlags = CommandID::Cart;
cmd.action = [](cro::Entity e, float dt)
{
e.getComponent<cro::Transform>().rotate(cro::Transform::Y_AXIS, dt * 0.5f);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
else
{
auto targetDir = m_holeData[m_currentHole].target - currPos;
m_camRotation = std::atan2(-targetDir.z, targetDir.x);
}
if (glm::length2(travel) < 0.0001f)
{
targetInfo.prevLookAt = targetInfo.currentLookAt = targetInfo.targetLookAt;
targetInfo.startHeight = targetInfo.targetHeight;
targetInfo.startOffset = targetInfo.targetOffset;
//we're there
setCameraPosition(m_holeData[m_currentHole].tee, targetInfo.targetHeight, targetInfo.targetOffset);
//set tee / flag
cro::Command cmd;
cmd.targetFlags = CommandID::Hole;
cmd.action = [&](cro::Entity en, float)
{
en.getComponent<cro::Transform>().setPosition(m_holeData[m_currentHole].pin);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
cmd.targetFlags = CommandID::Tee;
cmd.action = [&](cro::Entity en, float)
{
en.getComponent<cro::Transform>().setPosition(m_holeData[m_currentHole].tee);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//remove the transition ent
e.getComponent<cro::Callback>().active = false;
m_gameScene.destroyEntity(e);
//play the music
m_cameras[CameraID::Player].getComponent<cro::AudioEmitter>().play();
}
else
{
auto height = targetInfo.targetHeight - targetInfo.startHeight;
auto offset = targetInfo.targetOffset - targetInfo.startOffset;
static constexpr float Speed = 4.f;
e.getComponent<cro::Transform>().move(travel * Speed * dt);
setCameraPosition(e.getComponent<cro::Transform>().getPosition(),
targetInfo.startHeight + (height * percent),
targetInfo.startOffset + (offset * percent));
}
};
m_currentPlayer.position = m_holeData[m_currentHole].tee;
//this is called by setCurrentPlayer, but doing it here ensures that
//each player starts a new hole on a driver/3 wood
m_inputParser.setHoleDirection(m_holeData[m_currentHole].target - m_currentPlayer.position, true);
m_currentPlayer.terrain = TerrainID::Fairway;
//hide the slope indicator
cro::Command cmd;
cmd.targetFlags = CommandID::SlopeIndicator;
cmd.action = [](cro::Entity e, float)
{
//e.getComponent<cro::Model>().setHidden(true);
e.getComponent<cro::Callback>().getUserData<std::pair<float, std::int32_t>>().second = 1;
e.getComponent<cro::Callback>().active = true;
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//update the UI
cmd.targetFlags = CommandID::UI::HoleNumber;
cmd.action =
[&](cro::Entity e, float)
{
auto& data = e.getComponent<cro::Callback>().getUserData<TextCallbackData>();
data.string = "Hole: " + std::to_string(m_currentHole + 1);
e.getComponent<cro::Callback>().active = true;
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
m_terrainBuilder.setSlopePosition(m_holeData[m_currentHole].pin);
//set green cam position
auto holePos = m_holeData[m_currentHole].pin;
m_greenCam.getComponent<cro::Transform>().setPosition({ holePos.x, 0.9f, holePos.z });
//and the uh, other green cam. The spectator one
m_cameras[CameraID::Green].getComponent<cro::Transform>().setPosition({ holePos.x, 2.f, holePos.z });
//TODO what's a reasonable way to find an offset for this?
//perhaps move at least 15m away in opposite direction from map centre?
auto centre = glm::vec3(MapSize.x / 2.f, 0.f, -static_cast<float>(MapSize.y) / 2.f);
auto direction = holePos - centre;
direction = glm::normalize(direction) * 15.f;
m_cameras[CameraID::Green].getComponent<cro::Transform>().move(direction);
//we also have to check the camera hasn't ended up too close to the centre one, else the
//camera director gets confused as to which should be active when the ball is in both radii
auto distVec = m_cameras[CameraID::Sky].getComponent<cro::Transform>().getPosition();
distVec -= m_cameras[CameraID::Green].getComponent<cro::Transform>().getPosition();
auto len2 = glm::length2(distVec);
auto minLen = m_cameras[CameraID::Sky].getComponent<CameraFollower>().radius + m_cameras[CameraID::Green].getComponent<CameraFollower>().radius;
if (len2 < minLen)
{
auto len = std::sqrt(len2);
auto diff = std::sqrt(minLen) - len;
distVec /= len;
distVec *= (diff * 1.1f);
m_cameras[CameraID::Green].getComponent<cro::Transform>().move(-distVec);
}
//reset the flag
cmd.targetFlags = CommandID::Flag;
cmd.action = [](cro::Entity e, float)
{
e.getComponent<cro::Callback>().getUserData<FlagCallbackData>().targetHeight = 0.f;
e.getComponent<cro::Callback>().active = true;
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
void GolfState::setCameraPosition(glm::vec3 position, float height, float viewOffset)
{
static constexpr float MinDist = 6.f;
static constexpr float MaxDist = 270.f;
static constexpr float DistDiff = MaxDist - MinDist;
float heightMultiplier = 1.f; //goes to -1.f at max dist
auto camEnt = m_cameras[CameraID::Player];
auto& targetInfo = camEnt.getComponent<TargetInfo>();
auto target = targetInfo.currentLookAt - position;
auto dist = glm::length(target);
float distNorm = std::min(1.f, (dist - MinDist) / DistDiff);
heightMultiplier -= (2.f * distNorm);
target *= 1.f - ((1.f - 0.08f) * distNorm);
target += position;
camEnt.getComponent<cro::Transform>().setPosition({ position.x, height, position.z });
auto lookat = glm::lookAt(camEnt.getComponent<cro::Transform>().getPosition(), glm::vec3(target.x, height * heightMultiplier, target.z), cro::Transform::Y_AXIS);
camEnt.getComponent<cro::Transform>().setRotation(glm::inverse(lookat));
auto offset = -camEnt.getComponent<cro::Transform>().getForwardVector();
camEnt.getComponent<cro::Transform>().move(offset * viewOffset);
targetInfo.waterPlane.getComponent<cro::Transform>().setPosition({ target.x, WaterLevel, target.z });
}
void GolfState::setCurrentPlayer(const ActivePlayer& player)
{
updateScoreboard();
showScoreboard(false);
auto localPlayer = (player.client == m_sharedData.clientConnection.connectionID);
//self destructing ent to provide delay before popping up player name
if (!m_sharedData.tutorial)
{
auto entity = m_uiScene.createEntity();
entity.addComponent<cro::Transform>();
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<float>(1.5f);
entity.getComponent<cro::Callback>().function =
[&, localPlayer](cro::Entity e, float dt)
{
auto& currTime = e.getComponent<cro::Callback>().getUserData<float>();
currTime -= dt;
if (currTime <= 0)
{
showMessageBoard(MessageBoardID::PlayerName);
e.getComponent<cro::Callback>().active = false;
m_uiScene.destroyEntity(e);
m_inputParser.setActive(localPlayer);
}
};
}
else
{
m_inputParser.setActive(localPlayer);
}
//player UI name
cro::Command cmd;
cmd.targetFlags = CommandID::UI::PlayerName;
cmd.action =
[&](cro::Entity e, float)
{
auto& data = e.getComponent<cro::Callback>().getUserData<TextCallbackData>();
data.string = m_sharedData.connectionData[m_currentPlayer.client].playerData[m_currentPlayer.player].name;
e.getComponent<cro::Callback>().active = true;
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
cmd.targetFlags = CommandID::UI::PinDistance;
cmd.action =
[&, player](cro::Entity e, float)
{
//if we're on the green convert to cm
float ballDist = glm::length(player.position - m_holeData[m_currentHole].pin);
std::int32_t distance = 0;
if (ballDist > 5)
{
distance = static_cast<std::int32_t>(ballDist);
e.getComponent<cro::Text>().setString("Distance: " + std::to_string(distance) + "m");
}
else
{
distance = static_cast<std::int32_t>(ballDist * 100.f);
e.getComponent<cro::Text>().setString("Distance: " + std::to_string(distance) + "cm");
}
auto bounds = cro::Text::getLocalBounds(e);
bounds.width = std::floor(bounds.width / 2.f);
e.getComponent<cro::Transform>().setOrigin({ bounds.width, 0.f });
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
cmd.targetFlags = CommandID::UI::MiniBall;
cmd.action =
[player](cro::Entity e, float)
{
auto pos = glm::vec3(player.position.x, -player.position.z, 0.1f);
e.getComponent<cro::Transform>().setPosition(pos / 2.f);
//play the callback animation
e.getComponent<cro::Callback>().active = true;
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//show ui if this is our client
cmd.targetFlags = CommandID::UI::Root;
cmd.action = [&,localPlayer](cro::Entity e, float)
{
float sizeX = static_cast<float>(GolfGame::getActiveTarget()->getSize().x);
sizeX /= m_viewScale.x;
auto uiPos = localPlayer ? glm::vec2(sizeX / 2.f, UIBarHeight / 2.f) : UIHiddenPosition;
e.getComponent<cro::Transform>().setPosition(uiPos);
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//stroke indicator is in model scene...
cmd.targetFlags = CommandID::StrokeIndicator;
cmd.action = [localPlayer, player](cro::Entity e, float)
{
auto position = player.position;
position.y = 0.01f;
e.getComponent<cro::Transform>().setPosition(position);
e.getComponent<cro::Model>().setHidden(!localPlayer);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//if client is ours activate input/set initial stroke direction
auto target = m_cameras[CameraID::Player].getComponent<TargetInfo>().targetLookAt;
m_inputParser.resetPower();
m_inputParser.setHoleDirection(target - player.position, m_currentPlayer != player); // this also selects the nearest club
//if the pause/options menu is open, don't take control
//from the active input (this will be set when the state is closed)
if (getStateCount() == 1)
{
m_sharedData.inputBinding.controllerID = m_sharedData.controllerIDs[player.player];
}
//this just makes sure to update the direction indicator
//regardless of whether or not we actually switched clubs
//it's a hack where above case tells the input parser not to update the club (because we're the same player)
//but we've also landed on th green and therefor auto-switched to a putter
auto* msg = getContext().appInstance.getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg->type = GolfEvent::ClubChanged;
//apply the correct sprite to the player entity
cmd.targetFlags = CommandID::UI::PlayerSprite;
cmd.action = [&,player](cro::Entity e, float)
{
if (player.terrain != TerrainID::Green)
{
if (getClub() < ClubID::FiveIron)
{
e.getComponent<cro::Sprite>() = m_avatars[m_currentPlayer.client][m_currentPlayer.player].wood;
}
else
{
e.getComponent<cro::Sprite>() = m_avatars[m_currentPlayer.client][m_currentPlayer.player].iron;
}
e.getComponent<cro::Callback>().active = true;
if (m_avatars[m_currentPlayer.client][m_currentPlayer.player].flipped)
{
e.getComponent<cro::Transform>().setScale({ -1.f, 0.f });
e.getComponent<cro::Drawable2D>().setFacing(cro::Drawable2D::Facing::Back);
}
else
{
e.getComponent<cro::Transform>().setScale({ 1.f, 0.f });
e.getComponent<cro::Drawable2D>().setFacing(cro::Drawable2D::Facing::Front);
}
const auto& camera = m_cameras[CameraID::Player].getComponent<cro::Camera>();
auto pos = camera.coordsToPixel(player.position, m_gameSceneTexture.getSize());
e.getComponent<cro::Transform>().setPosition(pos);
//make sure we reset to player camera just in case
setActiveCamera(CameraID::Player);
}
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//show or hide the slope indicator depending if we're on the green
cmd.targetFlags = CommandID::SlopeIndicator;
cmd.action = [player](cro::Entity e, float)
{
bool hidden = (player.terrain != TerrainID::Green);
if (!hidden)
{
e.getComponent<cro::Model>().setHidden(hidden);
e.getComponent<cro::Callback>().getUserData<std::pair<float, std::int32_t>>().second = 0;
e.getComponent<cro::Callback>().active = true;
}
else
{
e.getComponent<cro::Callback>().getUserData<std::pair<float, std::int32_t>>().second = 1;
e.getComponent<cro::Callback>().active = true;
}
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//update player shadow position
cmd.targetFlags = CommandID::PlayerShadow;
cmd.action = [&,player](cro::Entity e, float)
{
float rotation = m_camRotation;
if (m_avatars[m_currentPlayer.client][m_currentPlayer.player].flipped)
{
rotation += cro::Util::Const::PI;
}
e.getComponent<cro::Transform>().setPosition(player.position);
e.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, rotation);
e.getComponent<cro::Model>().setHidden(player.terrain == TerrainID::Green);
e.getComponent<cro::Callback>().active = true;
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//also check if we need to display mini map for green
cmd.targetFlags = CommandID::UI::MiniGreen;
cmd.action = [player](cro::Entity e, float)
{
bool hidden = (player.terrain != TerrainID::Green);
if (!hidden)
{
e.getComponent<cro::Callback>().getUserData<std::pair<float, std::int32_t>>().second = 0;
e.getComponent<cro::Callback>().active = true;
}
else
{
e.getComponent<cro::Callback>().getUserData<std::pair<float, std::int32_t>>().second = 1;
e.getComponent<cro::Callback>().active = true;
}
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
m_currentPlayer = player;
//announce player has changed
auto* msg2 = getContext().appInstance.getMessageBus().post<GolfEvent>(MessageID::GolfMessage);
msg2->position = m_currentPlayer.position;
msg2->terrain = m_currentPlayer.terrain;
msg2->type = GolfEvent::SetNewPlayer;
m_gameScene.setSystemActive<CameraFollowSystem>(false);
}
void GolfState::hitBall()
{
auto pitch = Clubs[getClub()].angle;// cro::Util::Const::PI / 4.f;
auto yaw = m_inputParser.getYaw();
//add hook/slice to yaw
yaw += MaxHook * m_inputParser.getHook();
glm::vec3 impulse(1.f, 0.f, 0.f);
auto rotation = glm::rotate(glm::quat(1.f, 0.f, 0.f, 0.f), yaw, cro::Transform::Y_AXIS);
rotation = glm::rotate(rotation, pitch, cro::Transform::Z_AXIS);
impulse = glm::toMat3(rotation) * impulse;
impulse *= Clubs[getClub()].power * m_inputParser.getPower();
impulse *= Dampening[m_currentPlayer.terrain];
InputUpdate update;
update.clientID = m_sharedData.localConnectionData.connectionID;
update.playerID = m_currentPlayer.player;
update.impulse = impulse;
m_sharedData.clientConnection.netClient.sendPacket(PacketID::InputUpdate, update, cro::NetFlag::Reliable, ConstVal::NetChannelReliable);
m_inputParser.setActive(false);
//increase the local stroke count so that the UI is updated
//the server will set the actual value
m_sharedData.connectionData[m_currentPlayer.client].playerData[m_currentPlayer.player].holeScores[m_currentHole]++;
//hide the indicator
cro::Command cmd;
cmd.targetFlags = CommandID::StrokeIndicator;
cmd.action = [](cro::Entity e, float)
{
e.getComponent<cro::Model>().setHidden(true);
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
void GolfState::updateActor(const ActorInfo& update)
{
cro::Command cmd;
cmd.targetFlags = CommandID::Ball;
cmd.action = [update](cro::Entity e, float)
{
if (e.isValid())
{
auto& interp = e.getComponent<InterpolationComponent>();
if (interp.getID() == update.serverID)
{
interp.setTarget({ update.position, {1.f,0.f,0.f,0.f}, update.timestamp });
}
}
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
if (update == m_currentPlayer)
{
//set the green cam zoom as appropriate
float ballDist = glm::length(update.position - m_holeData[m_currentHole].pin);
if (ballDist < 0)
{
LogE << "Ball dist is wrong! value: " << ballDist << " with position " << update.position << std::endl;
}
m_greenCam.getComponent<cro::Callback>().getUserData<MiniCamData>().targetSize =
interpolate(MiniCamData::MinSize, MiniCamData::MaxSize, smoothstep(MiniCamData::MinSize, MiniCamData::MaxSize, ballDist));
//this is the active ball so update the UI
cmd.targetFlags = CommandID::UI::PinDistance;
cmd.action = [&, update, ballDist](cro::Entity e, float)
{
//if we're on the green convert to cm
std::int32_t distance = 0;
if (ballDist > 5)
{
distance = static_cast<std::int32_t>(ballDist);
if (distance < 0)
{
LogE << "Distance got mangled, now: " << distance << std::endl;
}
e.getComponent<cro::Text>().setString("Distance: " + std::to_string(distance) + "m");
}
else
{
distance = static_cast<std::int32_t>(ballDist * 100.f);
e.getComponent<cro::Text>().setString("Distance: " + std::to_string(distance) + "cm");
}
auto bounds = cro::Text::getLocalBounds(e);
bounds.width = std::floor(bounds.width / 2.f);
e.getComponent<cro::Transform>().setOrigin({ bounds.width, 0.f });
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
cmd.targetFlags = CommandID::UI::MiniBall;
cmd.action =
[update](cro::Entity e, float)
{
auto pos = glm::vec3(update.position.x, -update.position.z, 0.1f);
e.getComponent<cro::Transform>().setPosition(pos / 2.f); //need to tie into the fact the mini map is 1/2 scale
//set scale based on height
static constexpr float MaxHeight = 40.f;
float scale = 1.f + ((update.position.y / MaxHeight) * 2.f);
e.getComponent<cro::Transform>().setScale(glm::vec2(scale));
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//update spectator camera
cmd.targetFlags = CommandID::SpectatorCam;
cmd.action = [&,update](cro::Entity e, float)
{
e.getComponent<CameraFollower>().target = update.position;
e.getComponent<CameraFollower>().playerPosition = m_currentPlayer.position;
e.getComponent<CameraFollower>().holePosition = m_holeData[m_currentHole].pin;
};
m_gameScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
}
void GolfState::createTransition(const ActivePlayer& playerData)
{
//hide player sprite
cro::Command cmd;
cmd.targetFlags = CommandID::UI::PlayerSprite;
cmd.action = [](cro::Entity e, float)
{
e.getComponent<cro::Transform>().setScale(glm::vec2(1.f, 0.f));
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
//hide hud
cmd.targetFlags = CommandID::UI::Root;
cmd.action = [](cro::Entity e, float)
{
e.getComponent<cro::Transform>().setPosition(UIHiddenPosition);
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
auto& targetInfo = m_cameras[CameraID::Player].getComponent<TargetInfo>();
if (playerData.terrain == TerrainID::Green)
{
targetInfo.targetHeight = CameraPuttHeight;
targetInfo.targetOffset = CameraPuttOffset;
}
else
{
targetInfo.targetHeight = CameraStrokeHeight;
targetInfo.targetOffset = CameraStrokeOffset;
}
auto targetDir = m_holeData[m_currentHole].target - playerData.position;
auto pinDir = m_holeData[m_currentHole].pin - playerData.position;
targetInfo.prevLookAt = targetInfo.currentLookAt = targetInfo.targetLookAt;
//if both the pin and the target are in front of the player
if (glm::dot(glm::normalize(targetDir), glm::normalize(pinDir)) > 0.4)
{
//set the target depending on how close it is
auto pinDist = glm::length2(pinDir);
auto targetDist = glm::length2(targetDir);
if (pinDist < targetDist)
{
//always target pin if its closer
targetInfo.targetLookAt = m_holeData[m_currentHole].pin;
}
else
{
//target the pin if the target is too close
if (targetDist < 5625) //remember this in len2
{
targetInfo.targetLookAt = m_holeData[m_currentHole].pin;
}
else
{
targetInfo.targetLookAt = m_holeData[m_currentHole].target;
}
}
}
else
{
//else set the pin as the target
targetInfo.targetLookAt = m_holeData[m_currentHole].pin;
}
//creates an entity which calls setCamPosition() in an
//interpolated manner until we reach the dest,
//at which point we update the active player and
//the ent destroys itself
auto startPos = m_currentPlayer.position;
auto entity = m_gameScene.createEntity();
entity.addComponent<cro::Transform>().setPosition(startPos);
entity.addComponent<cro::Callback>().active = true;
entity.getComponent<cro::Callback>().setUserData<ActivePlayer>(playerData);
entity.getComponent<cro::Callback>().function =
[&, startPos](cro::Entity e, float dt)
{
const auto& playerData = e.getComponent<cro::Callback>().getUserData<ActivePlayer>();
auto currPos = e.getComponent<cro::Transform>().getPosition();
auto travel = playerData.position - currPos;
auto& targetInfo = m_cameras[CameraID::Player].getComponent<TargetInfo>();
auto targetDir = targetInfo.currentLookAt - currPos;
m_camRotation = std::atan2(-targetDir.z, targetDir.x);
float minTravel = playerData.terrain == TerrainID::Green ? 0.000001f : 0.005f;
if (glm::length2(travel) < minTravel)
{
//we're there
targetInfo.prevLookAt = targetInfo.currentLookAt = targetInfo.targetLookAt;
targetInfo.startHeight = targetInfo.targetHeight;
targetInfo.startOffset = targetInfo.targetOffset;
setCameraPosition(playerData.position, targetInfo.targetHeight, targetInfo.targetOffset);
setCurrentPlayer(playerData);
m_gameScene.getActiveListener().getComponent<cro::AudioListener>().setVelocity(glm::vec3(0.f));
e.getComponent<cro::Callback>().active = false;
m_gameScene.destroyEntity(e);
}
else
{
const auto totalDist = glm::length(playerData.position - startPos);
const auto currentDist = glm::length(travel);
const auto percent = 1.f - (currentDist / totalDist);
targetInfo.currentLookAt = targetInfo.prevLookAt + ((targetInfo.targetLookAt - targetInfo.prevLookAt) * percent);
auto height = targetInfo.targetHeight - targetInfo.startHeight;
auto offset = targetInfo.targetOffset - targetInfo.startOffset;
static constexpr float Speed = 4.f;
e.getComponent<cro::Transform>().move(travel * Speed * dt);
setCameraPosition(e.getComponent<cro::Transform>().getPosition(),
targetInfo.startHeight + (height * percent),
targetInfo.startOffset + (offset * percent));
m_gameScene.getActiveListener().getComponent<cro::AudioListener>().setVelocity(travel * Speed);
}
};
}
std::int32_t GolfState::getClub() const
{
switch (m_currentPlayer.terrain)
{
default: return m_inputParser.getClub();
case TerrainID::Bunker: return ClubID::PitchWedge + (m_inputParser.getClub() % 2);
case TerrainID::Green: return ClubID::Putter;
}
}
void GolfState::setActiveCamera(std::int32_t camID)
{
CRO_ASSERT(camID >= 0 && camID < CameraID::Count, "");
if (m_cameras[camID].isValid()
&& camID != m_currentCamera)
{
//set scene camera
m_gameScene.setActiveCamera(m_cameras[camID]);
m_gameScene.setActiveListener(m_cameras[camID]);
m_currentCamera = camID;
//hide player based on cam id
cro::Command cmd;
cmd.targetFlags = CommandID::UI::PlayerSprite;
cmd.action = [&,camID](cro::Entity e, float)
{
//show/hide player based on camera
if (m_avatars[m_currentPlayer.client][m_currentPlayer.player].flipped)
{
if (camID == CameraID::Player)
{
e.getComponent<cro::Drawable2D>().setFacing(cro::Drawable2D::Facing::Back);
}
else
{
e.getComponent<cro::Drawable2D>().setFacing(cro::Drawable2D::Facing::Front);
}
}
else
{
if (camID == CameraID::Player)
{
e.getComponent<cro::Drawable2D>().setFacing(cro::Drawable2D::Facing::Front);
}
else
{
e.getComponent<cro::Drawable2D>().setFacing(cro::Drawable2D::Facing::Back);
}
}
};
m_uiScene.getSystem<cro::CommandSystem>()->sendCommand(cmd);
}
} | 38.719029 | 168 | 0.606711 | fallahn |
ed80a8729716e8ed8f0a8efe039bf45697dd63b1 | 758 | cpp | C++ | EyeCandy3D/src/Gui/Backend/OpenGLFontLoader.cpp | Nelaty/EyeCandy3D | 7daee9451460f5a98e3b6a28e14089b8059bf485 | [
"MIT"
] | null | null | null | EyeCandy3D/src/Gui/Backend/OpenGLFontLoader.cpp | Nelaty/EyeCandy3D | 7daee9451460f5a98e3b6a28e14089b8059bf485 | [
"MIT"
] | 14 | 2019-10-11T17:58:54.000Z | 2021-01-22T09:54:55.000Z | EyeCandy3D/src/Gui/Backend/OpenGLFontLoader.cpp | Nelaty/EyeCandy3D | 7daee9451460f5a98e3b6a28e14089b8059bf485 | [
"MIT"
] | 1 | 2019-05-14T19:31:23.000Z | 2019-05-14T19:31:23.000Z | #include "EC3D/Gui/Backend/OpenGLFontLoader.h"
#include "EC3D/Gui/Backend/OpenGLFont.h"
namespace ec
{
OpenGLFontLoader::OpenGLFontLoader()
= default;
OpenGLFontLoader::~OpenGLFontLoader()
= default;
agui::Font* OpenGLFontLoader::loadFont(const std::string &fileName,
const int height,
const agui::FontFlags fontFlags,
const float borderWidth,
const agui::Color borderColor)
{
return new OpenGLFont(fileName,
height,
fontFlags,
borderWidth,
borderColor);
}
agui::Font* OpenGLFontLoader::loadEmptyFont()
{
return new ec::OpenGLFont();
}
}
| 22.294118 | 72 | 0.556728 | Nelaty |
ed8107972d0881dd396e480e62c494ab4ddb20f5 | 1,161 | cpp | C++ | SECOND_LEVEL/1092.cpp | BLUECARVIN/PAT | e8519552ce2c398b5e8bb84cd709c2a271363d29 | [
"MIT"
] | null | null | null | SECOND_LEVEL/1092.cpp | BLUECARVIN/PAT | e8519552ce2c398b5e8bb84cd709c2a271363d29 | [
"MIT"
] | null | null | null | SECOND_LEVEL/1092.cpp | BLUECARVIN/PAT | e8519552ce2c398b5e8bb84cd709c2a271363d29 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1010;
char Buy[maxn], Want[maxn];
int Hash[26 * 2 + 10] = {0};
int main()
{
cin.getline(Buy, 1000);
cin.getline(Want, 1000);
int len1 = strlen(Buy);
int len2 = strlen(Want);
for(int i = 0; i < len1; i++) //每遍历一个珠子,将对应位置的hash值++
{
if(Buy[i] >= 'a' && Buy[i] <= 'z') Hash[Buy[i] - 'a']++;
else if(Buy[i] >= 'A' && Buy[i] <= 'Z') Hash[Buy[i] - 'A' + 26]++;
else Hash[Buy[i] - '0' + 52] ++;
}
for (int i = 0; i < len2; i++) //每需要一颗珠子,将对应位置的hash值--
{
if(Want[i] >= 'a' && Want[i] <= 'z') Hash[Want[i] - 'a']--;
else if(Want[i] >= 'A' && Want[i] <= 'Z') Hash[Want[i] - 'A' + 26]--;
else Hash[Want[i] - '0' + 52]--;
}
int miss = 0; //记录Hash中缺失的珠子个数
for(int i = 0; i < 26*2+10; i++)
{
if(Hash[i] < 0)
{
miss++;
}
}
if(miss == 0) //没有缺失的珠子说明能满足需要
{
printf("Yes %d\n", len1 - len2);
}
else //出现sum_neg 小于零则说明有缺失的珠子,则不能满足需要
{
printf("No %d\n", miss);
}
system("pause");
return 0;
} | 24.1875 | 77 | 0.458226 | BLUECARVIN |
ed821cf4f97becf6a1eb57bd7771a3ad9fade8a7 | 28,195 | cc | C++ | ThirdParty/webrtc/src/net/base/network_interfaces_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 8 | 2018-12-27T14:57:13.000Z | 2021-04-07T07:03:15.000Z | ThirdParty/webrtc/src/net/base/network_interfaces_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 1 | 2019-03-13T01:35:03.000Z | 2020-10-08T04:13:04.000Z | ThirdParty/webrtc/src/net/base/network_interfaces_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 9 | 2018-12-28T11:45:12.000Z | 2021-05-11T02:15:31.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/network_interfaces.h"
#include <string>
#include <ostream>
// TODO(eroman): Remove unneeeded headers.
#include "base/files/file_path.h"
#include "base/format_macros.h"
#include "base/scoped_native_library.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_byteorder.h"
#include "base/time/time.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_util.h"
#if !defined(OS_NACL) && !defined(OS_WIN)
#include <net/if.h>
#include <netinet/in.h>
#if defined(OS_MACOSX)
#include <ifaddrs.h>
#if !defined(OS_IOS)
#include <netinet/in_var.h>
#endif // !OS_IOS
#endif // OS_MACOSX
#endif // !OS_NACL && !OS_WIN
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#if defined(OS_WIN)
#include <iphlpapi.h>
#include <objbase.h>
#include "base/win/windows_version.h"
#endif // OS_WIN
#if !defined(OS_MACOSX) && !defined(OS_NACL) && !defined(OS_WIN)
#include "net/base/address_tracker_linux.h"
#endif // !OS_MACOSX && !OS_NACL && !OS_WIN
#if defined(OS_WIN)
#include "net/base/network_interfaces_win.h"
#else // OS_WIN
#include "net/base/network_interfaces_posix.h"
#if defined(OS_MACOSX)
#include "net/base/network_interfaces_mac.h"
#else // OS_MACOSX
#include "net/base/network_interfaces_linux.h"
#endif // OS_MACOSX
#endif // OS_WIN
namespace net {
namespace {
#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)
const char kWiFiSSID[] = "TestWiFi";
const char kInterfaceWithDifferentSSID[] = "wlan999";
std::string TestGetInterfaceSSID(const std::string& ifname) {
return (ifname == kInterfaceWithDifferentSSID) ? "AnotherSSID" : kWiFiSSID;
}
#endif
#if defined(OS_MACOSX)
class IPAttributesGetterTest : public internal::IPAttributesGetterMac {
public:
IPAttributesGetterTest() : native_attributes_(0) {}
bool IsInitialized() const override { return true; }
bool GetIPAttributes(const char* ifname,
const sockaddr* sock_addr,
int* native_attributes) override {
*native_attributes = native_attributes_;
return true;
}
void set_native_attributes(int native_attributes) {
native_attributes_ = native_attributes;
}
private:
int native_attributes_;
};
// Helper function to create a single valid ifaddrs
bool FillIfaddrs(ifaddrs* interfaces,
const char* ifname,
uint flags,
const IPAddressNumber& ip_address,
const IPAddressNumber& ip_netmask,
sockaddr_storage sock_addrs[2]) {
interfaces->ifa_next = NULL;
interfaces->ifa_name = const_cast<char*>(ifname);
interfaces->ifa_flags = flags;
socklen_t sock_len = sizeof(sockaddr_storage);
// Convert to sockaddr for next check.
if (!IPEndPoint(ip_address, 0)
.ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[0]),
&sock_len)) {
return false;
}
interfaces->ifa_addr = reinterpret_cast<sockaddr*>(&sock_addrs[0]);
sock_len = sizeof(sockaddr_storage);
if (!IPEndPoint(ip_netmask, 0)
.ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[1]),
&sock_len)) {
return false;
}
interfaces->ifa_netmask = reinterpret_cast<sockaddr*>(&sock_addrs[1]);
return true;
}
#endif // OS_MACOSX
// Verify GetNetworkList().
TEST(NetUtilTest, GetNetworkList) {
NetworkInterfaceList list;
ASSERT_TRUE(GetNetworkList(&list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES));
for (NetworkInterfaceList::iterator it = list.begin();
it != list.end(); ++it) {
// Verify that the names are not empty.
EXPECT_FALSE(it->name.empty());
EXPECT_FALSE(it->friendly_name.empty());
// Verify that the address is correct.
EXPECT_TRUE(it->address.size() == kIPv4AddressSize ||
it->address.size() == kIPv6AddressSize)
<< "Invalid address of size " << it->address.size();
bool all_zeroes = true;
for (size_t i = 0; i < it->address.size(); ++i) {
if (it->address[i] != 0) {
all_zeroes = false;
break;
}
}
EXPECT_FALSE(all_zeroes);
EXPECT_GT(it->prefix_length, 1u);
EXPECT_LE(it->prefix_length, it->address.size() * 8);
#if defined(OS_WIN)
// On Windows |name| is NET_LUID.
base::ScopedNativeLibrary phlpapi_lib(
base::FilePath(FILE_PATH_LITERAL("iphlpapi.dll")));
ASSERT_TRUE(phlpapi_lib.is_valid());
typedef NETIO_STATUS (WINAPI* ConvertInterfaceIndexToLuid)(NET_IFINDEX,
PNET_LUID);
ConvertInterfaceIndexToLuid interface_to_luid =
reinterpret_cast<ConvertInterfaceIndexToLuid>(
phlpapi_lib.GetFunctionPointer("ConvertInterfaceIndexToLuid"));
typedef NETIO_STATUS (WINAPI* ConvertInterfaceLuidToGuid)(NET_LUID*,
GUID*);
ConvertInterfaceLuidToGuid luid_to_guid =
reinterpret_cast<ConvertInterfaceLuidToGuid>(
phlpapi_lib.GetFunctionPointer("ConvertInterfaceLuidToGuid"));
if (interface_to_luid && luid_to_guid) {
NET_LUID luid;
EXPECT_EQ(interface_to_luid(it->interface_index, &luid), NO_ERROR);
GUID guid;
EXPECT_EQ(luid_to_guid(&luid, &guid), NO_ERROR);
LPOLESTR name;
StringFromCLSID(guid, &name);
EXPECT_STREQ(base::UTF8ToWide(it->name).c_str(), name);
CoTaskMemFree(name);
continue;
} else {
EXPECT_LT(base::win::GetVersion(), base::win::VERSION_VISTA);
EXPECT_LT(it->interface_index, 1u << 24u); // Must fit 0.x.x.x.
EXPECT_NE(it->interface_index, 0u); // 0 means to use default.
}
if (it->type == NetworkChangeNotifier::CONNECTION_WIFI) {
EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE, GetWifiPHYLayerProtocol());
}
#elif !defined(OS_ANDROID)
char name[IF_NAMESIZE];
EXPECT_TRUE(if_indextoname(it->interface_index, name));
EXPECT_STREQ(it->name.c_str(), name);
#endif
}
}
static const char ifname_em1[] = "em1";
#if defined(OS_WIN)
static const char ifname_vm[] = "VMnet";
#else
static const char ifname_vm[] = "vmnet";
#endif // OS_WIN
static const unsigned char kIPv6LocalAddr[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
// The following 3 addresses need to be changed together. IPv6Addr is the IPv6
// address. IPv6Netmask is the mask address with as many leading bits set to 1
// as the prefix length. IPv6AddrPrefix needs to match IPv6Addr with the same
// number of bits as the prefix length.
static const unsigned char kIPv6Addr[] =
{0x24, 0x01, 0xfa, 0x00, 0x00, 0x04, 0x10, 0x00, 0xbe, 0x30, 0x5b, 0xff,
0xfe, 0xe5, 0x00, 0xc3};
#if defined(OS_WIN)
static const unsigned char kIPv6AddrPrefix[] =
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
#endif // OS_WIN
#if defined(OS_MACOSX)
static const unsigned char kIPv6Netmask[] =
{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
#endif // OS_MACOSX
#if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_NACL)
char* CopyInterfaceName(const char* ifname, int ifname_size, char* output) {
EXPECT_LT(ifname_size, IF_NAMESIZE);
memcpy(output, ifname, ifname_size);
return output;
}
char* GetInterfaceName(int interface_index, char* ifname) {
return CopyInterfaceName(ifname_em1, arraysize(ifname_em1), ifname);
}
char* GetInterfaceNameVM(int interface_index, char* ifname) {
return CopyInterfaceName(ifname_vm, arraysize(ifname_vm), ifname);
}
TEST(NetUtilTest, GetNetworkListTrimming) {
IPAddressNumber ipv6_local_address(
kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
NetworkInterfaceList results;
::base::hash_set<int> online_links;
internal::AddressTrackerLinux::AddressMap address_map;
// Interface 1 is offline.
struct ifaddrmsg msg = {
AF_INET6,
1, /* prefix length */
IFA_F_TEMPORARY, /* address flags */
0, /* link scope */
1 /* link index */
};
// Address of offline links should be ignored.
ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceName));
EXPECT_EQ(results.size(), 0ul);
// Mark interface 1 online.
online_links.insert(1);
// Local address should be trimmed out.
address_map.clear();
ASSERT_TRUE(
address_map.insert(std::make_pair(ipv6_local_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceName));
EXPECT_EQ(results.size(), 0ul);
// vmware address should return by default.
address_map.clear();
ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceNameVM));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_vm);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
results.clear();
// vmware address should be trimmed out if policy specified so.
address_map.clear();
ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceNameVM));
EXPECT_EQ(results.size(), 0ul);
results.clear();
// Addresses with banned attributes should be ignored.
address_map.clear();
msg.ifa_flags = IFA_F_TENTATIVE;
ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceName));
EXPECT_EQ(results.size(), 0ul);
results.clear();
// Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
// attributes should be translated correctly.
address_map.clear();
msg.ifa_flags = IFA_F_TEMPORARY;
ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceName));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_em1);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
results.clear();
// Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
// attributes should be translated correctly.
address_map.clear();
msg.ifa_flags = IFA_F_DEPRECATED;
ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
address_map, GetInterfaceName));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_em1);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
results.clear();
}
#elif defined(OS_MACOSX)
TEST(NetUtilTest, GetNetworkListTrimming) {
IPAddressNumber ipv6_local_address(
kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
IPAddressNumber ipv6_netmask(kIPv6Netmask,
kIPv6Netmask + arraysize(kIPv6Netmask));
NetworkInterfaceList results;
IPAttributesGetterTest ip_attributes_getter;
sockaddr_storage addresses[2];
ifaddrs interface;
// Address of offline links should be ignored.
ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_UP, ipv6_address,
ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 0ul);
// Local address should be trimmed out.
ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING,
ipv6_local_address, ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 0ul);
// vmware address should return by default.
ASSERT_TRUE(FillIfaddrs(&interface, ifname_vm, IFF_RUNNING, ipv6_address,
ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_vm);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
results.clear();
// vmware address should be trimmed out if policy specified so.
ASSERT_TRUE(FillIfaddrs(&interface, ifname_vm, IFF_RUNNING, ipv6_address,
ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 0ul);
results.clear();
#if !defined(OS_IOS)
// Addresses with banned attributes should be ignored.
ip_attributes_getter.set_native_attributes(IN6_IFF_ANYCAST);
ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 0ul);
results.clear();
// Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
// attributes should be translated correctly.
ip_attributes_getter.set_native_attributes(IN6_IFF_TEMPORARY);
ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_em1);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
results.clear();
// Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
// attributes should be translated correctly.
ip_attributes_getter.set_native_attributes(IN6_IFF_DEPRECATED);
ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
ipv6_netmask, addresses));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
&ip_attributes_getter));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_em1);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
results.clear();
#endif // !OS_IOS
}
#elif defined(OS_WIN) // !OS_MACOSX && !OS_WIN && !OS_NACL
// Helper function to create a valid IP_ADAPTER_ADDRESSES with reasonable
// default value. The output is the |adapter_address|. All the rests are input
// to fill the |adapter_address|. |sock_addrs| are temporary storage used by
// |adapter_address| once the function is returned.
bool FillAdapterAddress(IP_ADAPTER_ADDRESSES* adapter_address,
const char* ifname,
const IPAddressNumber& ip_address,
const IPAddressNumber& ip_netmask,
sockaddr_storage sock_addrs[2]) {
adapter_address->AdapterName = const_cast<char*>(ifname);
adapter_address->FriendlyName = const_cast<PWCHAR>(L"interface");
adapter_address->IfType = IF_TYPE_ETHERNET_CSMACD;
adapter_address->OperStatus = IfOperStatusUp;
adapter_address->FirstUnicastAddress->DadState = IpDadStatePreferred;
adapter_address->FirstUnicastAddress->PrefixOrigin = IpPrefixOriginOther;
adapter_address->FirstUnicastAddress->SuffixOrigin = IpSuffixOriginOther;
adapter_address->FirstUnicastAddress->PreferredLifetime = 100;
adapter_address->FirstUnicastAddress->ValidLifetime = 1000;
socklen_t sock_len = sizeof(sockaddr_storage);
// Convert to sockaddr for next check.
if (!IPEndPoint(ip_address, 0)
.ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[0]),
&sock_len)) {
return false;
}
adapter_address->FirstUnicastAddress->Address.lpSockaddr =
reinterpret_cast<sockaddr*>(&sock_addrs[0]);
adapter_address->FirstUnicastAddress->Address.iSockaddrLength = sock_len;
adapter_address->FirstUnicastAddress->OnLinkPrefixLength = 1;
sock_len = sizeof(sockaddr_storage);
if (!IPEndPoint(ip_netmask, 0)
.ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[1]),
&sock_len)) {
return false;
}
adapter_address->FirstPrefix->Address.lpSockaddr =
reinterpret_cast<sockaddr*>(&sock_addrs[1]);
adapter_address->FirstPrefix->Address.iSockaddrLength = sock_len;
adapter_address->FirstPrefix->PrefixLength = 1;
DCHECK_EQ(sock_addrs[0].ss_family, sock_addrs[1].ss_family);
if (sock_addrs[0].ss_family == AF_INET6) {
adapter_address->Ipv6IfIndex = 0;
} else {
DCHECK_EQ(sock_addrs[0].ss_family, AF_INET);
adapter_address->IfIndex = 0;
}
return true;
}
TEST(NetUtilTest, GetNetworkListTrimming) {
IPAddressNumber ipv6_local_address(
kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
IPAddressNumber ipv6_prefix(kIPv6AddrPrefix,
kIPv6AddrPrefix + arraysize(kIPv6AddrPrefix));
NetworkInterfaceList results;
sockaddr_storage addresses[2];
IP_ADAPTER_ADDRESSES adapter_address = {0};
IP_ADAPTER_UNICAST_ADDRESS address = {0};
IP_ADAPTER_PREFIX adapter_prefix = {0};
adapter_address.FirstUnicastAddress = &address;
adapter_address.FirstPrefix = &adapter_prefix;
// Address of offline links should be ignored.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_em1 /* ifname */,
ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
adapter_address.OperStatus = IfOperStatusDown;
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 0ul);
// Address on loopback interface should be trimmed out.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_em1 /* ifname */,
ipv6_local_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
adapter_address.IfType = IF_TYPE_SOFTWARE_LOOPBACK;
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 0ul);
// vmware address should return by default.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_vm /* ifname */,
ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_vm);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_NONE);
results.clear();
// vmware address should be trimmed out if policy specified so.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_vm /* ifname */,
ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 0ul);
results.clear();
// Addresses with incompleted DAD should be ignored.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_em1 /* ifname */,
ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
adapter_address.FirstUnicastAddress->DadState = IpDadStateTentative;
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 0ul);
results.clear();
// Addresses with allowed attribute IpSuffixOriginRandom should be returned
// and attributes should be translated correctly to
// IP_ADDRESS_ATTRIBUTE_TEMPORARY.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_em1 /* ifname */,
ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
adapter_address.FirstUnicastAddress->PrefixOrigin =
IpPrefixOriginRouterAdvertisement;
adapter_address.FirstUnicastAddress->SuffixOrigin = IpSuffixOriginRandom;
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].name, ifname_em1);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
results.clear();
// Addresses with preferred lifetime 0 should be returned and
// attributes should be translated correctly to
// IP_ADDRESS_ATTRIBUTE_DEPRECATED.
ASSERT_TRUE(FillAdapterAddress(
&adapter_address /* adapter_address */, ifname_em1 /* ifname */,
ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
addresses /* sock_addrs */));
adapter_address.FirstUnicastAddress->PreferredLifetime = 0;
adapter_address.FriendlyName = const_cast<PWCHAR>(L"FriendlyInterfaceName");
EXPECT_TRUE(internal::GetNetworkListImpl(
&results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
EXPECT_EQ(results.size(), 1ul);
EXPECT_EQ(results[0].friendly_name, "FriendlyInterfaceName");
EXPECT_EQ(results[0].name, ifname_em1);
EXPECT_EQ(results[0].prefix_length, 1ul);
EXPECT_EQ(results[0].address, ipv6_address);
EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
results.clear();
}
#endif // !OS_MACOSX && !OS_WIN && !OS_NACL
TEST(NetUtilTest, GetWifiSSID) {
// We can't check the result of GetWifiSSID() directly, since the result
// will differ across machines. Simply exercise the code path and hope that it
// doesn't crash.
EXPECT_NE((const char*)NULL, GetWifiSSID().c_str());
}
#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)
TEST(NetUtilTest, GetWifiSSIDFromInterfaceList) {
NetworkInterfaceList list;
EXPECT_EQ(std::string(), internal::GetWifiSSIDFromInterfaceListInternal(
list, TestGetInterfaceSSID));
NetworkInterface interface1;
interface1.name = "wlan0";
interface1.type = NetworkChangeNotifier::CONNECTION_WIFI;
list.push_back(interface1);
ASSERT_EQ(1u, list.size());
EXPECT_EQ(std::string(kWiFiSSID),
internal::GetWifiSSIDFromInterfaceListInternal(
list, TestGetInterfaceSSID));
NetworkInterface interface2;
interface2.name = "wlan1";
interface2.type = NetworkChangeNotifier::CONNECTION_WIFI;
list.push_back(interface2);
ASSERT_EQ(2u, list.size());
EXPECT_EQ(std::string(kWiFiSSID),
internal::GetWifiSSIDFromInterfaceListInternal(
list, TestGetInterfaceSSID));
NetworkInterface interface3;
interface3.name = kInterfaceWithDifferentSSID;
interface3.type = NetworkChangeNotifier::CONNECTION_WIFI;
list.push_back(interface3);
ASSERT_EQ(3u, list.size());
EXPECT_EQ(std::string(), internal::GetWifiSSIDFromInterfaceListInternal(
list, TestGetInterfaceSSID));
list.pop_back();
NetworkInterface interface4;
interface4.name = "eth0";
interface4.type = NetworkChangeNotifier::CONNECTION_ETHERNET;
list.push_back(interface4);
ASSERT_EQ(3u, list.size());
EXPECT_EQ(std::string(), internal::GetWifiSSIDFromInterfaceListInternal(
list, TestGetInterfaceSSID));
}
#endif // OS_LINUX
#if defined(OS_WIN)
bool read_int_or_bool(DWORD data_size,
PVOID data) {
switch (data_size) {
case 1:
return !!*reinterpret_cast<uint8_t*>(data);
case 4:
return !!*reinterpret_cast<uint32_t*>(data);
default:
LOG(FATAL) << "That is not a type I know!";
return false;
}
}
int GetWifiOptions() {
const internal::WlanApi& wlanapi = internal::WlanApi::GetInstance();
if (!wlanapi.initialized)
return -1;
internal::WlanHandle client;
DWORD cur_version = 0;
const DWORD kMaxClientVersion = 2;
DWORD result = wlanapi.OpenHandle(
kMaxClientVersion, &cur_version, &client);
if (result != ERROR_SUCCESS)
return -1;
WLAN_INTERFACE_INFO_LIST* interface_list_ptr = NULL;
result = wlanapi.enum_interfaces_func(client.Get(), NULL,
&interface_list_ptr);
if (result != ERROR_SUCCESS)
return -1;
scoped_ptr<WLAN_INTERFACE_INFO_LIST, internal::WlanApiDeleter> interface_list(
interface_list_ptr);
for (unsigned i = 0; i < interface_list->dwNumberOfItems; ++i) {
WLAN_INTERFACE_INFO* info = &interface_list->InterfaceInfo[i];
DWORD data_size;
PVOID data;
int options = 0;
result = wlanapi.query_interface_func(
client.Get(),
&info->InterfaceGuid,
wlan_intf_opcode_background_scan_enabled,
NULL,
&data_size,
&data,
NULL);
if (result != ERROR_SUCCESS)
continue;
if (!read_int_or_bool(data_size, data)) {
options |= WIFI_OPTIONS_DISABLE_SCAN;
}
internal::WlanApi::GetInstance().free_memory_func(data);
result = wlanapi.query_interface_func(
client.Get(),
&info->InterfaceGuid,
wlan_intf_opcode_media_streaming_mode,
NULL,
&data_size,
&data,
NULL);
if (result != ERROR_SUCCESS)
continue;
if (read_int_or_bool(data_size, data)) {
options |= WIFI_OPTIONS_MEDIA_STREAMING_MODE;
}
internal::WlanApi::GetInstance().free_memory_func(data);
// Just the the options from the first succesful
// interface.
return options;
}
// No wifi interface found.
return -1;
}
#else // OS_WIN
int GetWifiOptions() {
// Not supported.
return -1;
}
#endif // OS_WIN
void TryChangeWifiOptions(int options) {
int previous_options = GetWifiOptions();
scoped_ptr<ScopedWifiOptions> scoped_options = SetWifiOptions(options);
EXPECT_EQ(previous_options | options, GetWifiOptions());
scoped_options.reset();
EXPECT_EQ(previous_options, GetWifiOptions());
}
// Test SetWifiOptions().
TEST(NetUtilTest, SetWifiOptionsTest) {
TryChangeWifiOptions(0);
TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN);
TryChangeWifiOptions(WIFI_OPTIONS_MEDIA_STREAMING_MODE);
TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN |
WIFI_OPTIONS_MEDIA_STREAMING_MODE);
}
} // namespace
} // namespace net
| 37.294974 | 80 | 0.716723 | JokeJoe8806 |
ed84387e87a348fc2b439e7189003a98d50e7349 | 1,317 | hpp | C++ | libraries/plugins/apis/block_api/include/sophiatx/plugins/block_api/block_api_objects.hpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 8 | 2018-07-25T20:42:43.000Z | 2019-03-11T03:14:09.000Z | libraries/plugins/apis/block_api/include/sophiatx/plugins/block_api/block_api_objects.hpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 13 | 2018-07-25T17:41:28.000Z | 2019-01-25T13:38:11.000Z | libraries/plugins/apis/block_api/include/sophiatx/plugins/block_api/block_api_objects.hpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 11 | 2018-07-25T14:34:13.000Z | 2019-05-03T13:29:37.000Z | #pragma once
#include <sophiatx/chain/account_object.hpp>
#include <sophiatx/chain/block_summary_object.hpp>
#include <sophiatx/chain/global_property_object.hpp>
#include <sophiatx/chain/history_object.hpp>
#include <sophiatx/chain/sophiatx_objects.hpp>
#include <sophiatx/chain/transaction_object.hpp>
#include <sophiatx/chain/witness_objects.hpp>
#include <sophiatx/chain/database/database_interface.hpp>
namespace sophiatx { namespace plugins { namespace block_api {
using namespace sophiatx::chain;
struct api_signed_block_object : public signed_block
{
api_signed_block_object( const signed_block& block ) : signed_block( block )
{
block_id = id();
signing_key = signee();
transaction_ids.reserve( transactions.size() );
for( const signed_transaction& tx : transactions )
transaction_ids.push_back( tx.id() );
}
api_signed_block_object() {}
block_id_type block_id;
public_key_type signing_key;
vector< transaction_id_type > transaction_ids;
};
} } } // sophiatx::plugins::database_api
FC_REFLECT_DERIVED( sophiatx::plugins::block_api::api_signed_block_object, (sophiatx::protocol::signed_block),
(block_id)
(signing_key)
(transaction_ids)
)
| 33.769231 | 110 | 0.700835 | SophiaTX |
ed8737f8c54099919d8485790962c2ce52e29e39 | 35 | cpp | C++ | jusin2/220328/Girl.cpp | HeroJho/Jusin_c_cpp | 5fbb014fffc34b52b780486755de3576b07e4b64 | [
"MIT"
] | null | null | null | jusin2/220328/Girl.cpp | HeroJho/Jusin_c_cpp | 5fbb014fffc34b52b780486755de3576b07e4b64 | [
"MIT"
] | null | null | null | jusin2/220328/Girl.cpp | HeroJho/Jusin_c_cpp | 5fbb014fffc34b52b780486755de3576b07e4b64 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Girl.h"
| 11.666667 | 17 | 0.657143 | HeroJho |
ed87b39be34862b56db44e9b7678981111a0ec16 | 838 | hpp | C++ | Platforms/Vulkan/include/VulkanVertexInputPool.hpp | JoshuaMasci/Genesis | 761060626a92e3df7b860a97209fca341cdda240 | [
"MIT"
] | 2 | 2020-01-22T05:57:12.000Z | 2020-04-06T01:15:30.000Z | Platforms/Vulkan/include/VulkanVertexInputPool.hpp | JoshuaMasci/Genesis | 761060626a92e3df7b860a97209fca341cdda240 | [
"MIT"
] | null | null | null | Platforms/Vulkan/include/VulkanVertexInputPool.hpp | JoshuaMasci/Genesis | 761060626a92e3df7b860a97209fca341cdda240 | [
"MIT"
] | null | null | null | #pragma once
#include "Genesis/RenderingBackend/RenderingTypes.hpp"
#include "Genesis/RenderingBackend/VertexInputDescription.hpp"
#include "VulkanInclude.hpp"
#include "Genesis/Core/Types.hpp"
#include <mutex>
namespace Genesis
{
struct VulkanVertexInputDescription
{
VkVertexInputBindingDescription binding_description;
vector<VkVertexInputAttributeDescription> attribute_descriptions;
};
class VulkanVertexInputPool
{
public:
VulkanVertexInputPool();
~VulkanVertexInputPool();
VulkanVertexInputDescription* getVertexInputDescription(vector<VertexElementType>& input_elements);
VulkanVertexInputDescription* getVertexInputDescription(const VertexInputDescriptionCreateInfo& create_info);
private:
VkDevice device;
std::mutex map_lock;
map<uint32_t, VulkanVertexInputDescription> input_descriptions;
};
} | 25.393939 | 111 | 0.826969 | JoshuaMasci |
ed87dfdc34bef78a7809ce0f790c5cde5ac6bb2b | 1,361 | cpp | C++ | src/main.cpp | Exus1/TeamSpeak3-C-Query-API | c0cf094180f4217c456edfaaa6021c64b74edd3c | [
"MIT"
] | 2 | 2017-09-29T14:57:04.000Z | 2017-11-05T20:54:26.000Z | src/main.cpp | karolkrupa/TeamSpeak3-C-Query-API | c0cf094180f4217c456edfaaa6021c64b74edd3c | [
"MIT"
] | null | null | null | src/main.cpp | karolkrupa/TeamSpeak3-C-Query-API | c0cf094180f4217c456edfaaa6021c64b74edd3c | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <Server.hpp>
using namespace std;
int main() {
Ts3Api::Server server("e-bot.eu", "10011");
server.login("serveradmin", "PASSWORD");
server.selectServer("9987");
server.setNickname("eBot TRAIL");
auto client = server.getClientByNickname("Exus");
//cout << client.getChannel().getID() << endl;
/*
// if(server.receiverStart())
// cout << "Receiver Started" << endl;
// else
// cout << "Receiver Error" << endl;
// if(server.receiverStop())
// cout << "Receiver Stoped" << endl;
// else
// cout << "Receiver stop error" << endl;
// if(server.receiverStatus())
// cout << "Reveiver Runing" << endl;
auto client = server.getClientByNickname("adasdas");
if(client.good())
cout << "OK" << endl;
else
cout << "ERROR" << endl;
//cout << client.clientInfo.getProperty("cid").value << endl;
//client.sendMessage("Siema ziomuś");
//client.poke("Siema tutaj też");
client.addChannelGroup("10", "40");
//cout << client.getDescription().change("Lol").data << endl;
//cout << client.clientInfo.getProperty("cid").value << endl;
// auto ret = server.executeCommand("clientlist2");
// cout << "Poczatek:" << ret.errorMsg << ":Koniec" << endl;
// if(ret.error) cout << "ERROR" << endl;
cout << "Koniec" << endl;
*/
return 1;
}
| 22.311475 | 63 | 0.606907 | Exus1 |
ed8a90e423c2a29d6e6b5f76e8f6054539ca644b | 28,967 | cpp | C++ | api/modules/SAM_Windpower.cpp | JordanMalan/SAM | a4951b841987e0ccd66fe4d011cc6b5dd7b4f27c | [
"BSD-3-Clause"
] | 1 | 2021-04-27T23:06:44.000Z | 2021-04-27T23:06:44.000Z | api/modules/SAM_Windpower.cpp | JordanMalan/SAM | a4951b841987e0ccd66fe4d011cc6b5dd7b4f27c | [
"BSD-3-Clause"
] | null | null | null | api/modules/SAM_Windpower.cpp | JordanMalan/SAM | a4951b841987e0ccd66fe4d011cc6b5dd7b4f27c | [
"BSD-3-Clause"
] | 1 | 2021-09-15T11:15:24.000Z | 2021-09-15T11:15:24.000Z | #include <string>
#include <utility>
#include <vector>
#include <memory>
#include <iostream>
#include <ssc/sscapi.h>
#include "SAM_api.h"
#include "ErrorHandler.h"
#include "SAM_Windpower.h"
SAM_EXPORT int SAM_Windpower_execute(SAM_table data, int verbosity, SAM_error* err){
return SAM_module_exec("windpower", data, verbosity, err);
}
SAM_EXPORT void SAM_Windpower_Resource_weibull_k_factor_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "weibull_k_factor", number);
});
}
SAM_EXPORT void SAM_Windpower_Resource_weibull_reference_height_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "weibull_reference_height", number);
});
}
SAM_EXPORT void SAM_Windpower_Resource_weibull_wind_speed_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "weibull_wind_speed", number);
});
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_data_tset(SAM_table ptr, SAM_table tab, SAM_error *err){
SAM_table_set_table(ptr, "wind_resource_data", tab, err);
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_distribution_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "wind_resource_distribution", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_filename_sset(SAM_table ptr, const char* str, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_string(ptr, "wind_resource_filename", str);
});
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_model_choice_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_resource_model_choice", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_resource_shear_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_resource_shear", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_hub_ht_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_turbine_hub_ht", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_max_cp_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_turbine_max_cp", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_powercurve_powerout_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_turbine_powercurve_powerout", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_powercurve_windspeeds_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_turbine_powercurve_windspeeds", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_rotor_diameter_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_turbine_rotor_diameter", number);
});
}
SAM_EXPORT void SAM_Windpower_Farm_system_capacity_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "system_capacity", number);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_farm_wake_model_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_farm_wake_model", number);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_farm_xCoordinates_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_farm_xCoordinates", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_farm_yCoordinates_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_farm_yCoordinates", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_resource_turbulence_coeff_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_resource_turbulence_coeff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_avail_bop_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "avail_bop_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_avail_grid_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "avail_grid_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_avail_turb_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "avail_turb_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_elec_eff_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "elec_eff_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_elec_parasitic_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "elec_parasitic_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_en_icing_cutoff_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "en_icing_cutoff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_en_low_temp_cutoff_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "en_low_temp_cutoff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_degrad_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_degrad_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_env_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_env_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_exposure_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_exposure_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_icing_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_icing_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_icing_cutoff_rh_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "icing_cutoff_rh", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_icing_cutoff_temp_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "icing_cutoff_temp", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_low_temp_cutoff_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "low_temp_cutoff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_env_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_env_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_grid_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_grid_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_load_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_load_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_strategies_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_strategies_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_generic_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_generic_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_hysteresis_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_hysteresis_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_perf_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_perf_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_specific_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_specific_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_wake_ext_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wake_ext_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_wake_future_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wake_future_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_wake_int_loss_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wake_int_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Uncertainty_total_uncert_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "total_uncert", number);
});
}
SAM_EXPORT double SAM_Windpower_Resource_weibull_k_factor_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "weibull_k_factor", &result))
make_access_error("SAM_Windpower", "weibull_k_factor");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Resource_weibull_reference_height_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "weibull_reference_height", &result))
make_access_error("SAM_Windpower", "weibull_reference_height");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Resource_weibull_wind_speed_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "weibull_wind_speed", &result))
make_access_error("SAM_Windpower", "weibull_wind_speed");
});
return result;
}
SAM_EXPORT SAM_table SAM_Windpower_Resource_wind_resource_data_tget(SAM_table ptr, SAM_error *err){
SAM_table result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_table(ptr, "wind_resource_data");
if (!result)
make_access_error("SAM_Windpower", "wind_resource_data");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Resource_wind_resource_distribution_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "wind_resource_distribution", nrows, ncols);
if (!result)
make_access_error("SAM_Windpower", "wind_resource_distribution");
});
return result;
}
SAM_EXPORT const char* SAM_Windpower_Resource_wind_resource_filename_sget(SAM_table ptr, SAM_error *err){
const char* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_string(ptr, "wind_resource_filename");
if (!result)
make_access_error("SAM_Windpower", "wind_resource_filename");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Resource_wind_resource_model_choice_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_resource_model_choice", &result))
make_access_error("SAM_Windpower", "wind_resource_model_choice");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_resource_shear_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_resource_shear", &result))
make_access_error("SAM_Windpower", "wind_resource_shear");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_turbine_hub_ht_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_turbine_hub_ht", &result))
make_access_error("SAM_Windpower", "wind_turbine_hub_ht");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_turbine_max_cp_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_turbine_max_cp", &result))
make_access_error("SAM_Windpower", "wind_turbine_max_cp");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Turbine_wind_turbine_powercurve_powerout_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_turbine_powercurve_powerout", length);
if (!result)
make_access_error("SAM_Windpower", "wind_turbine_powercurve_powerout");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Turbine_wind_turbine_powercurve_windspeeds_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_turbine_powercurve_windspeeds", length);
if (!result)
make_access_error("SAM_Windpower", "wind_turbine_powercurve_windspeeds");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_turbine_rotor_diameter_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_turbine_rotor_diameter", &result))
make_access_error("SAM_Windpower", "wind_turbine_rotor_diameter");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Farm_system_capacity_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "system_capacity", &result))
make_access_error("SAM_Windpower", "system_capacity");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Farm_wind_farm_wake_model_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_farm_wake_model", &result))
make_access_error("SAM_Windpower", "wind_farm_wake_model");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Farm_wind_farm_xCoordinates_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_farm_xCoordinates", length);
if (!result)
make_access_error("SAM_Windpower", "wind_farm_xCoordinates");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Farm_wind_farm_yCoordinates_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_farm_yCoordinates", length);
if (!result)
make_access_error("SAM_Windpower", "wind_farm_yCoordinates");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Farm_wind_resource_turbulence_coeff_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_resource_turbulence_coeff", &result))
make_access_error("SAM_Windpower", "wind_resource_turbulence_coeff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_avail_bop_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_bop_loss", &result))
make_access_error("SAM_Windpower", "avail_bop_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_avail_grid_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_grid_loss", &result))
make_access_error("SAM_Windpower", "avail_grid_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_avail_turb_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_turb_loss", &result))
make_access_error("SAM_Windpower", "avail_turb_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_elec_eff_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "elec_eff_loss", &result))
make_access_error("SAM_Windpower", "elec_eff_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_elec_parasitic_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "elec_parasitic_loss", &result))
make_access_error("SAM_Windpower", "elec_parasitic_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_en_icing_cutoff_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "en_icing_cutoff", &result))
make_access_error("SAM_Windpower", "en_icing_cutoff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_en_low_temp_cutoff_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "en_low_temp_cutoff", &result))
make_access_error("SAM_Windpower", "en_low_temp_cutoff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_degrad_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_degrad_loss", &result))
make_access_error("SAM_Windpower", "env_degrad_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_env_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_env_loss", &result))
make_access_error("SAM_Windpower", "env_env_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_exposure_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_exposure_loss", &result))
make_access_error("SAM_Windpower", "env_exposure_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_icing_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_icing_loss", &result))
make_access_error("SAM_Windpower", "env_icing_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_icing_cutoff_rh_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "icing_cutoff_rh", &result))
make_access_error("SAM_Windpower", "icing_cutoff_rh");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_icing_cutoff_temp_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "icing_cutoff_temp", &result))
make_access_error("SAM_Windpower", "icing_cutoff_temp");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_low_temp_cutoff_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "low_temp_cutoff", &result))
make_access_error("SAM_Windpower", "low_temp_cutoff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_env_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_env_loss", &result))
make_access_error("SAM_Windpower", "ops_env_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_grid_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_grid_loss", &result))
make_access_error("SAM_Windpower", "ops_grid_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_load_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_load_loss", &result))
make_access_error("SAM_Windpower", "ops_load_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_strategies_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_strategies_loss", &result))
make_access_error("SAM_Windpower", "ops_strategies_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_generic_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_generic_loss", &result))
make_access_error("SAM_Windpower", "turb_generic_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_hysteresis_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_hysteresis_loss", &result))
make_access_error("SAM_Windpower", "turb_hysteresis_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_perf_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_perf_loss", &result))
make_access_error("SAM_Windpower", "turb_perf_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_specific_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_specific_loss", &result))
make_access_error("SAM_Windpower", "turb_specific_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_wake_ext_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wake_ext_loss", &result))
make_access_error("SAM_Windpower", "wake_ext_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_wake_future_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wake_future_loss", &result))
make_access_error("SAM_Windpower", "wake_future_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_wake_int_loss_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wake_int_loss", &result))
make_access_error("SAM_Windpower", "wake_int_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Uncertainty_total_uncert_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "total_uncert", &result))
make_access_error("SAM_Windpower", "total_uncert");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_energy_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_energy", &result))
make_access_error("SAM_Windpower", "annual_energy");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_energy_p75_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_energy_p75", &result))
make_access_error("SAM_Windpower", "annual_energy_p75");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_energy_p90_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_energy_p90", &result))
make_access_error("SAM_Windpower", "annual_energy_p90");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_energy_p95_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_energy_p95", &result))
make_access_error("SAM_Windpower", "annual_energy_p95");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_gross_energy_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_gross_energy", &result))
make_access_error("SAM_Windpower", "annual_gross_energy");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_avail_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_losses", &result))
make_access_error("SAM_Windpower", "avail_losses");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_capacity_factor_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "capacity_factor", &result))
make_access_error("SAM_Windpower", "capacity_factor");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_cutoff_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "cutoff_losses", &result))
make_access_error("SAM_Windpower", "cutoff_losses");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_elec_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "elec_losses", &result))
make_access_error("SAM_Windpower", "elec_losses");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_env_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_losses", &result))
make_access_error("SAM_Windpower", "env_losses");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_gen_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "gen", length);
if (!result)
make_access_error("SAM_Windpower", "gen");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_kwh_per_kw_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "kwh_per_kw", &result))
make_access_error("SAM_Windpower", "kwh_per_kw");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_monthly_energy_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "monthly_energy", length);
if (!result)
make_access_error("SAM_Windpower", "monthly_energy");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_ops_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_losses", &result))
make_access_error("SAM_Windpower", "ops_losses");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_pressure_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "pressure", length);
if (!result)
make_access_error("SAM_Windpower", "pressure");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_temp_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "temp", length);
if (!result)
make_access_error("SAM_Windpower", "temp");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_turb_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_losses", &result))
make_access_error("SAM_Windpower", "turb_losses");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_turbine_output_by_windspeed_bin_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "turbine_output_by_windspeed_bin", length);
if (!result)
make_access_error("SAM_Windpower", "turbine_output_by_windspeed_bin");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_wake_losses_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wake_losses", &result))
make_access_error("SAM_Windpower", "wake_losses");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_wind_direction_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_direction", length);
if (!result)
make_access_error("SAM_Windpower", "wind_direction");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_wind_speed_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_speed", length);
if (!result)
make_access_error("SAM_Windpower", "wind_speed");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_wind_speed_average_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_speed_average", &result))
make_access_error("SAM_Windpower", "wind_speed_average");
});
return result;
}
| 28.371205 | 137 | 0.776228 | JordanMalan |
ed8ba0e4609386872332d21e23a8c58c55ebfd2a | 34,898 | cpp | C++ | WasapiIODLL/WasapiUser.cpp | yamamoto2002/bitspersampleconv2 | 331a9fc531269e5dfdc78548e583f793a7687dc0 | [
"MIT"
] | null | null | null | WasapiIODLL/WasapiUser.cpp | yamamoto2002/bitspersampleconv2 | 331a9fc531269e5dfdc78548e583f793a7687dc0 | [
"MIT"
] | null | null | null | WasapiIODLL/WasapiUser.cpp | yamamoto2002/bitspersampleconv2 | 331a9fc531269e5dfdc78548e583f793a7687dc0 | [
"MIT"
] | 1 | 2020-11-12T06:55:18.000Z | 2020-11-12T06:55:18.000Z | // 日本語 UTF-8
// WASAPIの機能を使って音を出したり録音したりするWasapiUserクラス。
#include "WasapiUser.h"
#include "WWWasapiIOUtil.h"
#include <assert.h>
#include <strsafe.h>
#include <mmsystem.h>
#include <malloc.h>
#include <stdint.h>
#include "WWCommonUtil.h"
#define FOOTER_SEND_FRAME_NUM (2)
#define PERIODS_PER_BUFFER_ON_TIMER_DRIVEN_MODE (4)
// define: レンダーバッファ上で再生データを作る
// undef : 一旦スタック上にて再生データを作ってからレンダーバッファにコピーする
#define CREATE_PLAYPCM_ON_RENDER_BUFFER
// DoPマーカーが正しく付いているかチェックする。
#define CHECK_DOP_MARKER
static AUDCLNT_SHAREMODE
WWShareModeToAudClientShareMode(WWShareMode sm)
{
switch (sm) {
case WWSMShared:
return AUDCLNT_SHAREMODE_SHARED;
case WWSMExclusive:
return AUDCLNT_SHAREMODE_EXCLUSIVE;
default:
assert(0);
return AUDCLNT_SHAREMODE_EXCLUSIVE;
}
}
/* これは、サポートフォーマットが減ってしまう。
static void
PcmFormatToWfex16(const WWPcmFormat &pcmFormat, WAVEFORMATEX *wfex)
{
wfex->wFormatTag = WAVE_FORMAT_PCM;
wfex->nChannels = (WORD)pcmFormat.numChannels;
wfex->nSamplesPerSec = pcmFormat.sampleRate;
wfex->wBitsPerSample = (WORD)WWPcmDataSampleFormatTypeToBitsPerSample(pcmFormat.sampleFormat);
wfex->cbSize = 0;
// あとは計算で決まる。
wfex->nBlockAlign = (WORD)((wfex->wBitsPerSample / 8) * wfex->nChannels);
wfex->nAvgBytesPerSec = wfex->nSamplesPerSec * wfex->nBlockAlign;
}
*/
static void
PcmFormatToWfex40(const WWPcmFormat &pcmFormat, WAVEFORMATEXTENSIBLE *wfex)
{
wfex->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
wfex->Format.nChannels = (WORD)pcmFormat.numChannels;
wfex->Format.nSamplesPerSec = pcmFormat.sampleRate;
wfex->Format.wBitsPerSample = (WORD)WWPcmDataSampleFormatTypeToBitsPerSample(pcmFormat.sampleFormat);
wfex->Format.cbSize = 22;
wfex->Samples.wValidBitsPerSample = (WORD)WWPcmDataSampleFormatTypeToValidBitsPerSample(pcmFormat.sampleFormat);
wfex->dwChannelMask = pcmFormat.dwChannelMask;
if (WWPcmDataSampleFormatTypeIsInt(pcmFormat.sampleFormat)) {
wfex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
} else {
wfex->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
}
// あとは計算で決まる。
wfex->Format.nBlockAlign = (WORD)((wfex->Format.wBitsPerSample / 8) * wfex->Format.nChannels);
wfex->Format.nAvgBytesPerSec = wfex->Format.nSamplesPerSec * wfex->Format.nBlockAlign;
}
static void
WfexToPcmFormat(const WAVEFORMATEXTENSIBLE *wfex, WWPcmFormat &pcmFormat)
{
pcmFormat.Set(
wfex->Format.nSamplesPerSec,
WWPcmDataSampleFormatTypeGenerate(wfex->Format.wBitsPerSample,
wfex->Samples.wValidBitsPerSample,
wfex->SubFormat),
wfex->Format.nChannels,
wfex->dwChannelMask,
WWStreamUnknown);
}
static EDataFlow
WWDeviceTypeToEDataFlow(WWDeviceType t)
{
switch (t) {
case WWDTPlay:
return eRender;
case WWDTRec:
return eCapture;
default:
assert(0);
return eRender;
}
}
WasapiUser::WasapiUser(void)
{
m_shutdownEvent = nullptr;
m_audioSamplesReadyEvent = nullptr;
m_deviceToUse = nullptr;
m_audioClient = nullptr;
m_bufferFrameNum = 0;
m_pcmFormat.Clear();
m_deviceFormat.Clear();
m_dataFeedMode = WWDFMEventDriven;
m_shareMode = WWSMExclusive;
m_latencyMillisec = 0;
m_renderClient = nullptr;
m_captureClient = nullptr;
m_thread = nullptr;
m_mutex = nullptr;
m_coInitializeSuccess = false;
m_footerNeedSendCount = 0;
m_dataFlow = eRender;
m_glitchCount = 0;
m_footerCount = 0;
m_captureCallback = nullptr;
m_endpointVolume = nullptr;
}
WasapiUser::~WasapiUser(void)
{
assert(!m_deviceToUse);
}
HRESULT
WasapiUser::Init(void)
{
HRESULT hr = S_OK;
dprintf("D: %s()\n", __FUNCTION__);
assert(!m_deviceToUse);
hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (S_OK == hr) {
m_coInitializeSuccess = true;
} else {
// Managed applicationから呼び出すと0x80010106が起こる。
dprintf("D: WasapiUser::Init() CoInitializeEx() failed %08x\n", hr);
hr = S_OK;
}
assert(!m_mutex);
m_mutex = CreateMutex(nullptr, FALSE, nullptr);
m_audioFilterSequencer.Init();
return hr;
}
void
WasapiUser::Term(void)
{
dprintf("D: %s() m_deviceToUse=%p m_mutex=%p\n", __FUNCTION__, m_deviceToUse, m_mutex);
m_captureCallback = nullptr;
m_audioFilterSequencer.Term();
SafeRelease(&m_deviceToUse);
if (m_mutex) {
CloseHandle(m_mutex);
m_mutex = nullptr;
}
if (m_coInitializeSuccess) {
CoUninitialize();
}
}
HRESULT
WasapiUser::GetMixFormat(IMMDevice *device, WWPcmFormat *mixFormat_return)
{
HRESULT hr;
WAVEFORMATEX *waveFormat = nullptr;
IAudioClient *audioClient = nullptr;
HRG(device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, (void**)&audioClient));
assert(!waveFormat);
HRG(audioClient->GetMixFormat(&waveFormat));
assert(waveFormat);
WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE*)waveFormat;
dprintf("original Mix Format:\n");
WWWaveFormatDebug(waveFormat);
WWWFEXDebug(wfex);
WfexToPcmFormat(wfex, *mixFormat_return);
end:
SafeRelease(&device);
SafeRelease(&audioClient);
if (waveFormat) {
CoTaskMemFree(waveFormat);
waveFormat = nullptr;
}
return hr;
}
HRESULT
WasapiUser::GetDevicePeriod(IMMDevice *device, int64_t *defaultPeriod, int64_t *minimumPeriod)
{
HRESULT hr;
IAudioClient *audioClient = nullptr;
HRG(device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, (void**)&audioClient));
HRG(audioClient->GetDevicePeriod(defaultPeriod, minimumPeriod));
end:
SafeRelease(&device);
SafeRelease(&audioClient);
return hr;
}
int
WasapiUser::GetVolumeParams(WWVolumeParams *volumeParams_return)
{
HRESULT hr = S_OK;
if (nullptr == m_endpointVolume) {
return E_FAIL;
}
HRG(m_endpointVolume->GetVolumeRange(
&volumeParams_return->levelMinDB,
&volumeParams_return->levelMaxDB,
&volumeParams_return->volumeIncrementDB));
DWORD dwHardwareSupport;
HRG(m_endpointVolume->QueryHardwareSupport(&dwHardwareSupport));
volumeParams_return->hardwareSupport = dwHardwareSupport;
HRG(m_endpointVolume->GetMasterVolumeLevel(&volumeParams_return->defaultLevel));
dprintf("WasapiUser::GetVolumeParams() levelMinDb=%f levelMaxDb=%f volumeIncrementDb=%f defaultLevel=%f hardwareSupport=0x%x\n",
volumeParams_return->levelMinDB, volumeParams_return->levelMaxDB,
volumeParams_return->volumeIncrementDB,
volumeParams_return->defaultLevel, volumeParams_return->hardwareSupport);
end:
return hr;
}
int
WasapiUser::SetMasterVolumeLevelInDb(float db)
{
HRESULT hr = S_OK;
if (nullptr == m_endpointVolume) {
return E_FAIL;
}
HRG(m_endpointVolume->SetMasterVolumeLevel(db, nullptr));
end:
return hr;
}
HRESULT
WasapiUser::InspectDevice(IMMDevice *device, const WWPcmFormat &pcmFormat)
{
HRESULT hr;
WAVEFORMATEX *waveFormat = nullptr;
HRG(device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, (void**)&m_audioClient));
assert(!waveFormat);
HRG(m_audioClient->GetMixFormat(&waveFormat));
assert(waveFormat);
WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE*)waveFormat;
dprintf("original Mix Format:\n");
WWWaveFormatDebug(waveFormat);
WWWFEXDebug(wfex);
if (waveFormat->wFormatTag != WAVE_FORMAT_EXTENSIBLE) {
dprintf("E: unsupported device ! mixformat == 0x%08x\n", waveFormat->wFormatTag);
hr = E_FAIL;
goto end;
}
#if 0
PcmFormatToWfex16(pcmFormat, waveFormat);
#else
PcmFormatToWfex40(pcmFormat, wfex);
#endif
dprintf("preferred Format:\n");
WWWaveFormatDebug(waveFormat);
WWWFEXDebug(wfex);
hr = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, waveFormat, nullptr);
dprintf("IsFormatSupported=%08x\n", hr);
end:
SafeRelease(&device);
SafeRelease(&m_audioClient);
if (waveFormat) {
CoTaskMemFree(waveFormat);
waveFormat = nullptr;
}
return hr;
}
HRESULT
WasapiUser::Setup(IMMDevice *device, WWDeviceType deviceType, const WWPcmFormat &pcmFormat,
WWShareMode sm, WWDataFeedMode dfm, int latencyMillisec, bool isFormatSupportedCall)
{
HRESULT hr = 0;
WAVEFORMATEX *waveFormat = nullptr;
m_shareMode = sm;
m_dataFeedMode = dfm;
m_latencyMillisec = latencyMillisec;
m_dataFlow = WWDeviceTypeToEDataFlow(deviceType);
auto audClientSm = WWShareModeToAudClientShareMode(sm);
dprintf("D: %s(%d %s %d)\n", __FUNCTION__, pcmFormat.sampleRate, WWPcmDataSampleFormatTypeToStr(pcmFormat.sampleFormat), pcmFormat.numChannels);
m_pcmFormat = pcmFormat;
m_pcmStream.SetStreamType(m_pcmFormat.streamType);
m_audioSamplesReadyEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE);
CHK(m_audioSamplesReadyEvent);
assert(!m_deviceToUse);
m_deviceToUse = device;
assert(!m_audioClient);
HRG(m_deviceToUse->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, (void**)&m_audioClient));
assert(!waveFormat);
HRG(m_audioClient->GetMixFormat(&waveFormat));
assert(waveFormat);
WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE*)waveFormat;
dprintf("original Mix Format:\n");
WWWaveFormatDebug(waveFormat);
WWWFEXDebug(wfex);
assert(waveFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE);
if (WWSMExclusive == m_shareMode) {
// exclusive mode specific task
// on exclusive mode, sampleRate, bitsPerSample can be changed on most devices.
// also nChannels can be changed on some audio devices.
PcmFormatToWfex40(m_pcmFormat, wfex);
dprintf("preferred Format:\n");
WWWaveFormatDebug(waveFormat);
WWWFEXDebug(wfex);
if (isFormatSupportedCall) {
// 20150907:
// On iFi nano iDSD, IAudioClient::IsFormatSupported(705600Hz) returns false
// but IAudioClient::Initialize(705600Hz) succeeds and play 705600Hz PCM smoothly
// therefore following line is commented out.
// 20160811:
// Some realtek HD Audio device driver accepts IAudioClient::Initialize(24bit) but
// IAudioClient::IsFormatSupported(24bit) returns false
// when playing 24bit, it produces large static noise so I think the following line is necessary
HRG(m_audioClient->IsFormatSupported(audClientSm, waveFormat, nullptr));
}
} else {
// shared mode specific task
// on shared mode, wBitsPerSample, nSamplesPerSec, wValidBitsPerSample and subFormat are fixed.
// numChannels and dwChannelMask can be changed on some devices.
// 32bit float is used to represent sample value on wasapi shared
assert(wfex->Format.wBitsPerSample == 32);
assert(wfex->Samples.wValidBitsPerSample == 32);
assert(wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT);
// sample rate cannot be changed. use MixFormat sample rate. m_pcmFormat.sampleRate is not used.
// On shared mode, after this Setup() call, caller must change sample rate to m_deviceFormat.sampleRate
// assert(wfex->Format.nSamplesPerSec == m_pcmFormat.sampleRate);
// try changing channel count
wfex->Format.nChannels = (WORD)m_pcmFormat.numChannels;
wfex->Format.nBlockAlign = (WORD)((wfex->Format.wBitsPerSample / 8) * wfex->Format.nChannels);
wfex->Format.nAvgBytesPerSec = wfex->Format.nSamplesPerSec*wfex->Format.nBlockAlign;
wfex->dwChannelMask = m_pcmFormat.dwChannelMask;
}
// Note: AUDCLNT_STREAMFLAGS_RATEADJUST is only for Asynchronous SRC such as 44100.001Hz to 44100Hz conversion
DWORD streamFlags = 0;
int periodsPerBuffer = 1;
switch (m_dataFeedMode) {
case WWDFMTimerDriven:
streamFlags = AUDCLNT_STREAMFLAGS_NOPERSIST;
periodsPerBuffer = PERIODS_PER_BUFFER_ON_TIMER_DRIVEN_MODE;
break;
case WWDFMEventDriven:
streamFlags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST;
periodsPerBuffer = 1;
break;
default:
assert(0);
break;
}
REFERENCE_TIME bufferPeriodicity = m_latencyMillisec * 10000;
REFERENCE_TIME bufferDuration = bufferPeriodicity * periodsPerBuffer;
m_deviceFormat.sampleRate = waveFormat->nSamplesPerSec;
m_deviceFormat.numChannels = waveFormat->nChannels;
m_deviceFormat.dwChannelMask = wfex->dwChannelMask;
if (WWSMExclusive == m_shareMode) {
// exclusive mode specific task.
m_deviceFormat.sampleFormat = m_pcmFormat.sampleFormat;
} else {
// shared mode specific task.
m_deviceFormat.sampleFormat = WWPcmDataSampleFormatSfloat;
if (WWDFMEventDriven == m_dataFeedMode) {
// shared mode event driven specific task.
bufferPeriodicity = 0;
}
}
hr = m_audioClient->Initialize(audClientSm, streamFlags, bufferDuration, bufferPeriodicity, waveFormat, nullptr);
if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) {
HRG(m_audioClient->GetBufferSize(&m_bufferFrameNum));
SafeRelease(&m_audioClient);
bufferPeriodicity = (REFERENCE_TIME)(
10000.0 * // (REFERENCE_TIME(100ns) / ms) *
1000 * // (ms / s) *
m_bufferFrameNum / // frames /
waveFormat->nSamplesPerSec + // (frames / s)
0.5);
bufferDuration = bufferPeriodicity * periodsPerBuffer;
HRG(m_deviceToUse->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, (void**)&m_audioClient));
hr = m_audioClient->Initialize(audClientSm, streamFlags, bufferDuration, bufferPeriodicity, waveFormat, nullptr);
}
if (FAILED(hr)) {
dprintf("E: audioClient->Initialize failed 0x%08x\n", hr);
goto end;
}
HRG(m_audioClient->GetBufferSize(&m_bufferFrameNum));
dprintf("m_audioClient->GetBufferSize() rv=%u\n", m_bufferFrameNum);
if (WWDFMEventDriven == m_dataFeedMode) {
HRG(m_audioClient->SetEventHandle(m_audioSamplesReadyEvent));
}
switch (m_dataFlow) {
case eRender:
HRG(m_audioClient->GetService(IID_PPV_ARGS(&m_renderClient)));
m_pcmStream.PrepareSilenceBuffers(m_latencyMillisec, m_deviceFormat.sampleFormat, m_deviceFormat.sampleRate, m_deviceFormat.numChannels, m_deviceFormat.BytesPerFrame());
break;
case eCapture:
HRG(m_audioClient->GetService(IID_PPV_ARGS(&m_captureClient)));
HRG(m_deviceToUse->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr, (void**)&m_endpointVolume));
assert(m_endpointVolume);
break;
default:
assert(0);
break;
}
end:
if (waveFormat) {
CoTaskMemFree(waveFormat);
waveFormat = nullptr;
}
return hr;
}
bool
WasapiUser::IsResampleNeeded(void) const
{
if (WWSMExclusive == m_shareMode) {
return false;
}
if (m_deviceFormat.sampleRate != m_pcmFormat.sampleRate ||
m_deviceFormat.numChannels != m_pcmFormat.numChannels ||
m_deviceFormat.dwChannelMask != m_pcmFormat.dwChannelMask ||
WWPcmDataSampleFormatSfloat != m_pcmFormat.sampleFormat) {
return true;
}
return false;
}
void
WasapiUser::UpdatePcmDataFormat(const WWPcmFormat &fmt)
{
assert(WWSMShared == m_shareMode);
m_pcmFormat = fmt;
m_pcmStream.SetStreamType(fmt.streamType);
}
void
WasapiUser::Unsetup(void)
{
dprintf("D: %s() ASRE=%p CC=%p RC=%p AC=%p\n", __FUNCTION__, m_audioSamplesReadyEvent, m_captureClient, m_renderClient, m_audioClient);
if (m_audioSamplesReadyEvent) {
CloseHandle(m_audioSamplesReadyEvent);
m_audioSamplesReadyEvent = nullptr;
}
m_pcmStream.ReleaseBuffers();
SafeRelease(&m_endpointVolume);
SafeRelease(&m_deviceToUse);
SafeRelease(&m_captureClient);
SafeRelease(&m_renderClient);
SafeRelease(&m_audioClient);
}
HRESULT
WasapiUser::Start(void)
{
HRESULT hr = 0;
BYTE *pData = nullptr;
UINT32 nFrames = 0;
DWORD flags = 0;
dprintf("D: %s()\n", __FUNCTION__);
HRG(m_audioClient->Reset());
assert(!m_shutdownEvent);
m_shutdownEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE);
CHK(m_shutdownEvent);
switch (m_dataFlow) {
case eRender:
{
WWPcmData *pcm = m_pcmStream.GetPcm(WWPDUNowPlaying);
assert(pcm);
assert(nullptr == m_thread);
m_thread = CreateThread(nullptr, 0, RenderEntry, this, 0, nullptr);
assert(m_thread);
nFrames = m_bufferFrameNum;
if (WWDFMTimerDriven == m_dataFeedMode || WWSMShared == m_shareMode) {
// 排他タイマー駆動の場合、パッド計算必要。
// 共有モードの場合タイマー駆動でもイベント駆動でもパッドが必要。
// RenderSharedEventDrivenのWASAPIRenderer.cpp参照。
UINT32 padding = 0; //< frame now using
HRG(m_audioClient->GetCurrentPadding(&padding));
nFrames = m_bufferFrameNum - padding;
}
if (0 <= nFrames) {
assert(m_renderClient);
HRG(m_renderClient->GetBuffer(nFrames, &pData));
memset(pData, 0, nFrames * m_deviceFormat.BytesPerFrame());
HRG(m_renderClient->ReleaseBuffer(nFrames, 0));
}
m_footerCount = 0;
m_audioFilterSequencer.UpdateSampleFormat(m_pcmFormat.sampleRate,
pcm->SampleFormat(), pcm->StreamType(), pcm->Channels());
}
break;
case eCapture:
assert(m_captureCallback);
m_thread = CreateThread(nullptr, 0, CaptureEntry, this, 0, nullptr);
assert(m_thread);
hr = m_captureClient->GetBuffer(&pData, &nFrames, &flags, nullptr, nullptr);
if (SUCCEEDED(hr)) {
// if succeeded, release buffer pData
m_captureClient->ReleaseBuffer(nFrames);
pData = nullptr;
}
hr = S_OK;
m_glitchCount = 0;
break;
default:
assert(0);
break;
}
assert(m_audioClient);
HRG(m_audioClient->Start());
end:
return hr;
}
HRESULT
WasapiUser::Stop(void)
{
HRESULT hr = S_OK;
BOOL b;
DWORD dw = S_OK;
dprintf("D: %s() AC=%p SE=%p T=%p\n", __FUNCTION__, m_audioClient, m_shutdownEvent, m_thread);
// ポーズ中の場合、ポーズを解除。
m_pcmStream.SetPauseResumePcmData(nullptr);
if (nullptr != m_audioClient) {
hr = m_audioClient->Stop();
if (FAILED(hr)) {
dprintf("E: %s m_audioClient->Stop() failed 0x%x\n", __FUNCTION__, hr);
}
}
if (nullptr != m_shutdownEvent) {
SetEvent(m_shutdownEvent);
}
if (nullptr != m_thread) {
WaitForSingleObject(m_thread, INFINITE);
b = GetExitCodeThread(m_thread, &dw);
if (b && SUCCEEDED(hr)) {
hr = dw;
dprintf("D: Thread exit code = 0x%x\n", hr);
}
dprintf("D: %s:%d CloseHandle(%p)\n", __FILE__, __LINE__, m_thread);
if (m_thread) {
CloseHandle(m_thread);
}
m_thread = nullptr;
}
if (nullptr != m_shutdownEvent) {
dprintf("D: %s:%d CloseHandle(%p)\n", __FILE__, __LINE__, m_shutdownEvent);
CloseHandle(m_shutdownEvent);
m_shutdownEvent = nullptr;
}
return hr;
}
HRESULT
WasapiUser::Pause(void)
{
// HRESULT hr = S_OK;
bool pauseDataSetSucceeded = false;
assert(m_mutex);
WaitForSingleObject(m_mutex, INFINITE);
{
WWPcmData *nowPlaying = m_pcmStream.GetPcm(WWPDUNowPlaying);
if (nowPlaying && nowPlaying->ContentType() == WWPcmDataContentMusicData) {
// 通常データを再生中の場合ポーズが可能。
// m_nowPlayingPcmDataをpauseBuffer(フェードアウトするPCMデータ)に差し替え、
// 再生が終わるまでブロッキングで待つ。
pauseDataSetSucceeded = true;
m_pcmStream.Paused(nowPlaying);
}
if (nowPlaying && nowPlaying->ContentType() == WWPcmDataContentSilenceForTrailing) {
// 再生開始前無音を再生中。ポーズが可能。
pauseDataSetSucceeded = true;
m_pcmStream.Paused(nowPlaying->Next());
}
}
ReleaseMutex(m_mutex);
if (pauseDataSetSucceeded) {
// ここで再生一時停止までブロックする。
WWPcmData *nowPlayingPcmData = nullptr;
do {
assert(m_mutex);
WaitForSingleObject(m_mutex, INFINITE);
{
nowPlayingPcmData = m_pcmStream.GetPcm(WWPDUNowPlaying);
}
ReleaseMutex(m_mutex);
Sleep(100);
} while (nowPlayingPcmData != nullptr);
//再生一時停止状態はnowPlayingPcmData==nullptrで、再生スレッドは無音を送出し続ける。
} else {
dprintf("%s pauseDataSet failed\n", __FUNCTION__);
}
//end:
return (pauseDataSetSucceeded) ? S_OK : E_FAIL;
}
HRESULT
WasapiUser::Unpause(void)
{
if (m_pcmStream.GetPcm(WWPDUPauseResumeToPlay) == nullptr) {
// ポーズ中ではないのにUnpause()が呼び出された。
return E_FAIL;
}
WWPcmData *restartBuffer = m_pcmStream.UnpausePrepare();
assert(m_mutex);
WaitForSingleObject(m_mutex, INFINITE);
{
m_pcmStream.UpdateNowPlaying(restartBuffer);
}
ReleaseMutex(m_mutex);
m_pcmStream.UnpauseDone();
return S_OK;
}
bool
WasapiUser::Run(int millisec)
{
DWORD rv = WaitForSingleObject(m_thread, millisec);
if (rv == WAIT_TIMEOUT) {
Sleep(10);
return false;
}
return true;
}
void
WasapiUser::UpdatePlayPcmData(WWPcmData &pcmData)
{
if (m_thread != nullptr) {
UpdatePlayPcmDataWhenPlaying(pcmData);
} else {
m_pcmStream.UpdateStartPcm(&pcmData);
}
}
void
WasapiUser::UpdatePlayPcmDataWhenPlaying(WWPcmData &pcmData)
{
dprintf("D: %s(%d)\n", __FUNCTION__, pcmData.Id());
assert(m_mutex);
WaitForSingleObject(m_mutex, INFINITE);
{
WWPcmData *nowPlaying = m_pcmStream.GetPcm(WWPDUNowPlaying);
if (nowPlaying) {
WWPcmData *splice = m_pcmStream.GetPcm(WWPDUSplice);
// m_nowPlayingPcmDataをpcmDataに移動する。
// Issue3: いきなり移動するとブチッと言うのでsplice bufferを経由してなめらかにつなげる。
int advance = splice->CreateCrossfadeData(*nowPlaying, nowPlaying->PosFrame(), pcmData, pcmData.PosFrame());
if (nowPlaying != &pcmData) {
// 別の再生曲に移動した場合、それまで再生していた曲は頭出ししておく。
nowPlaying->SetPosFrame(0);
}
splice->SetNext(WWPcmData::AdvanceFrames(&pcmData, advance));
m_pcmStream.UpdateNowPlaying(splice);
} else {
// 一時停止中。
WWPcmData *pauseResumePcm = m_pcmStream.GetPcm(WWPDUPauseResumeToPlay);
if (pauseResumePcm != &pcmData) {
// 別の再生曲に移動した場合、それまで再生していた曲は頭出ししておく。
pauseResumePcm->SetPosFrame(0);
m_pcmStream.UpdatePauseResume(&pcmData);
// 再生シークをしたあと再生一時停止し再生曲を変更し再生再開すると
// 一瞬再生曲表示が再生シークした曲になる問題の修正w
m_pcmStream.GetPcm(WWPDUSplice)->SetNext(nullptr);
}
}
}
ReleaseMutex(m_mutex);
}
bool
WasapiUser::SetPosFrame(int64_t v)
{
if (m_dataFlow != eRender) {
assert(0);
return false;
}
if (v < 0) {
return false;
}
if (WWStreamDop == m_pcmStream.StreamType()) {
// 必ず2の倍数の位置にジャンプする。
v &= ~(1LL);
}
bool result = false;
assert(m_mutex);
WaitForSingleObject(m_mutex, INFINITE);
{
WWPcmData *nowPlaying = m_pcmStream.GetPcm(WWPDUNowPlaying);
if (nowPlaying &&
nowPlaying->ContentType() == WWPcmDataContentMusicData && v < nowPlaying->Frames()) {
WWPcmData *splice = m_pcmStream.GetPcm(WWPDUSplice);
// 再生中。
// nowPlaying->posFrameをvに移動する。
// Issue3: いきなり移動するとブチッと言うのでsplice bufferを経由してなめらかにつなげる。
int advance = splice->CreateCrossfadeData(*nowPlaying, nowPlaying->PosFrame(), *nowPlaying, v);
// 移動先は、nowPlaying上の位置v + クロスフェードのためにadvanceフレーム進んだ位置となる。
nowPlaying->SetPosFrame(v);
WWPcmData *toPcm = WWPcmData::AdvanceFrames(nowPlaying, advance);
splice->SetNext(toPcm);
m_pcmStream.UpdateNowPlaying(splice);
#ifdef CHECK_DOP_MARKER
splice->CheckDopMarker();
#endif // CHECK_DOP_MARKER
result = true;
} else {
WWPcmData *pauseResumePcm = m_pcmStream.GetPcm(WWPDUPauseResumeToPlay);
if (pauseResumePcm && v < pauseResumePcm->Frames()) {
// pause中。Pause再開後に再生されるPCMの再生位置を更新する。
pauseResumePcm->SetPosFrame(v);
result = true;
}
}
}
ReleaseMutex(m_mutex);
return result;
}
void
WasapiUser::MutexWait(void) {
WaitForSingleObject(m_mutex, INFINITE);
}
void
WasapiUser::MutexRelease(void) {
ReleaseMutex(m_mutex);
}
/////////////////////////////////////////////////////////////////////////////////
// 再生スレッド
/// 再生スレッドの入り口。
/// @param lpThreadParameter WasapiUserインスタンスのポインタが渡ってくる。
DWORD
WasapiUser::RenderEntry(LPVOID lpThreadParameter)
{
WasapiUser* self = (WasapiUser*)lpThreadParameter;
return self->RenderMain();
}
/// PCMデータをwantFramesフレームだけpData_returnに戻す。
/// @return 実際にpData_returnに書き込んだフレーム数。
int
WasapiUser::CreateWritableFrames(BYTE *pData_return, int wantFrames)
{
int pos = 0;
WWPcmData *pcmData = m_pcmStream.GetPcm(WWPDUNowPlaying);
while (nullptr != pcmData && 0 < wantFrames) {
int copyFrames = wantFrames;
if (pcmData->Frames() <= pcmData->PosFrame() + wantFrames) {
// pcmDataが持っているフレーム数よりも要求フレーム数が多い。
copyFrames = (int)(pcmData->Frames() - pcmData->PosFrame());
}
dprintf("pcmData=%p next=%p posFrame/nframes=%lld/%lld copyFrames=%d\n",
pcmData, pcmData->Next(), pcmData->PosFrame(), pcmData->Frames(), copyFrames);
CopyMemory(&pData_return[pos*m_deviceFormat.BytesPerFrame()],
&(pcmData->Stream()[pcmData->PosFrame() * m_deviceFormat.BytesPerFrame()]),
copyFrames * m_deviceFormat.BytesPerFrame());
pos += copyFrames;
wantFrames -= copyFrames;
pcmData->SetPosFrame(pcmData->PosFrame() + copyFrames);
if (pcmData->Frames() <= pcmData->PosFrame()) {
// pcmDataの最後まで来た。
// このpcmDataの再生位置は巻き戻して、次のpcmDataの先頭をポイントする。
pcmData->SetPosFrame(0);
pcmData = pcmData->Next();
}
}
m_pcmStream.UpdateNowPlaying(pcmData);
return pos;
}
/// WASAPIデバイスにPCMデータを送れるだけ送る。
HRESULT
WasapiUser::AudioSamplesSendProc(bool &result)
{
result = true;
BYTE *to = nullptr;
HRESULT hr = 0;
int copyFrames = 0;
int writableFrames = 0;
WaitForSingleObject(m_mutex, INFINITE);
writableFrames = m_bufferFrameNum;
if (WWDFMTimerDriven == m_dataFeedMode || WWSMShared == m_shareMode) {
// 共有モードの場合イベント駆動でもパッドが必要になる。
// RenderSharedEventDrivenのWASAPIRenderer.cpp参照。
UINT32 padding = 0; //< frame num now using
assert(m_audioClient);
HRGR(m_audioClient->GetCurrentPadding(&padding));
writableFrames = m_bufferFrameNum - padding;
// dprintf("m_bufferFrameNum=%d padding=%d writableFrames=%d\n", m_bufferFrameNum, padding, writableFrames);
if (writableFrames <= 0) {
goto end;
}
}
assert(m_renderClient);
HRGR(m_renderClient->GetBuffer(writableFrames, &to));
assert(to);
copyFrames = CreateWritableFrames(to, writableFrames);
if (m_audioFilterSequencer.IsAvailable()) {
// エフェクトを掛ける
m_audioFilterSequencer.ProcessSamples(to, copyFrames*m_deviceFormat.BytesPerFrame());
}
if (0 < writableFrames - copyFrames) {
memset(&to[copyFrames*m_deviceFormat.BytesPerFrame()], 0, (writableFrames - copyFrames)*m_deviceFormat.BytesPerFrame());
// dprintf("fc=%d bs=%d cb=%d memset %d bytes\n", m_footerCount, m_bufferFrameNum, copyFrames, (m_bufferFrameNum - copyFrames)*m_deviceFormat.BytesPerFrame());
}
HRGR(m_renderClient->ReleaseBuffer(writableFrames, 0));
to = nullptr;
if (nullptr == m_pcmStream.GetPcm(WWPDUNowPlaying)) {
++m_footerCount;
if (m_footerNeedSendCount < m_footerCount) {
// PCMを全て送信完了。
if (nullptr != m_pcmStream.GetPcm(WWPDUPauseResumeToPlay)) {
// ポーズ中。スレッドを回し続ける。
} else {
// スレッドを停止する。
result = false;
}
}
}
end:
if (FAILED(hr)) {
result = false;
}
ReleaseMutex(m_mutex);
return hr;
}
/// 再生スレッド メイン。
/// イベントやタイマーによって起き、PCMデータを送って、寝る。
/// というのを繰り返す。
DWORD
WasapiUser::RenderMain(void)
{
bool stillPlaying = true;
HANDLE waitArray[2] = {m_shutdownEvent, m_audioSamplesReadyEvent};
int waitArrayCount;
DWORD timeoutMillisec;
DWORD waitResult;
HRESULT hr = 0;
HRG(CoInitializeEx(nullptr, COINIT_MULTITHREADED));
HRG(m_timerResolution.Setup());
m_threadCharacteristics.Setup();
if (m_dataFeedMode == WWDFMTimerDriven) {
waitArrayCount = 1;
m_footerNeedSendCount = FOOTER_SEND_FRAME_NUM * 2;
timeoutMillisec = m_latencyMillisec / 2;
} else {
waitArrayCount = 2;
m_footerNeedSendCount = FOOTER_SEND_FRAME_NUM;
timeoutMillisec = INFINITE;
}
// dprintf("D: %s() waitArrayCount=%d m_shutdownEvent=%p m_audioSamplesReadyEvent=%p\n", __FUNCTION__, waitArrayCount, m_shutdownEvent, m_audioSamplesReadyEvent);
while (stillPlaying) {
waitResult = WaitForMultipleObjects(
waitArrayCount, waitArray, FALSE, timeoutMillisec);
switch (waitResult) {
case WAIT_OBJECT_0 + 0: // m_shutdownEvent
// シャットダウン要求によって起きた場合。
dprintf("D: %s() shutdown event flagged\n", __FUNCTION__);
stillPlaying = false;
break;
case WAIT_OBJECT_0 + 1: // m_audioSamplesReadyEvent
// イベント駆動モードの時だけ起こる。
hr = AudioSamplesSendProc(stillPlaying);
break;
case WAIT_TIMEOUT:
// タイマー駆動モードの時だけ起こる。
hr = AudioSamplesSendProc(stillPlaying);
break;
default:
break;
}
}
end:
m_threadCharacteristics.Unsetup();
m_timerResolution.Unsetup();
CoUninitialize();
return hr;
}
//////////////////////////////////////////////////////////////////////////////
// 録音スレッド
DWORD
WasapiUser::CaptureEntry(LPVOID lpThreadParameter)
{
WasapiUser* self = (WasapiUser*)lpThreadParameter;
return self->CaptureMain();
}
DWORD
WasapiUser::CaptureMain(void)
{
bool stillRecording = true;
HANDLE waitArray[2] = {m_shutdownEvent, m_audioSamplesReadyEvent};
int waitArrayCount;
DWORD timeoutMillisec;
DWORD waitResult;
HRESULT hr = 0;
HRG(CoInitializeEx(nullptr, COINIT_MULTITHREADED));
HRG(m_timerResolution.Setup());
m_threadCharacteristics.Setup();
if (m_dataFeedMode == WWDFMTimerDriven) {
waitArrayCount = 1;
timeoutMillisec = m_latencyMillisec / 2;
} else {
waitArrayCount = 2;
timeoutMillisec = INFINITE;
}
while (stillRecording) {
waitResult = WaitForMultipleObjects(waitArrayCount, waitArray, FALSE, timeoutMillisec);
switch (waitResult) {
case WAIT_OBJECT_0 + 0: // m_shutdownEvent
stillRecording = false;
break;
case WAIT_OBJECT_0 + 1: // m_audioSamplesReadyEvent
// only in EventDriven mode
hr = AudioSamplesRecvProc(stillRecording);
break;
case WAIT_TIMEOUT:
// only in TimerDriven mode
hr = AudioSamplesRecvProc(stillRecording);
break;
default:
break;
}
}
end:
m_threadCharacteristics.Unsetup();
m_timerResolution.Unsetup();
CoUninitialize();
return hr;
}
HRESULT
WasapiUser::AudioSamplesRecvProc(bool &result)
{
result = true;
UINT32 packetLength = 0;
UINT32 numFramesAvailable = 0;
DWORD flags = 0;
BYTE *pData = nullptr;
HRESULT hr = 0;
UINT64 devicePosition = 0;
WaitForSingleObject(m_mutex, INFINITE);
HRG(m_captureClient->GetNextPacketSize(&packetLength));
if (packetLength == 0) {
goto end;
}
numFramesAvailable = packetLength;
flags = 0;
HRG(m_captureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, nullptr));
if (flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) {
++m_glitchCount;
}
if (m_captureCallback != nullptr) {
// 都度コールバックを呼ぶ
m_captureCallback(pData, numFramesAvailable * m_deviceFormat.BytesPerFrame());
HRG(m_captureClient->ReleaseBuffer(numFramesAvailable));
goto end;
}
end:
ReleaseMutex(m_mutex);
return hr;
}
| 30.346087 | 178 | 0.621268 | yamamoto2002 |
ed8cfc57ec1737e6c5ddec0b44e69583befc5939 | 2,449 | hpp | C++ | libvast/vast/detail/narrow.hpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | null | null | null | libvast/vast/detail/narrow.hpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | 1 | 2019-11-29T12:43:41.000Z | 2019-11-29T12:43:41.000Z | libvast/vast/detail/narrow.hpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
// This file comes from a 3rd party and has been adapted to fit into the VAST
// code base. Details about the original file:
//
// - Repository: https://github.com/Microsoft/GSL
// - Commit: d6b26b367b294aca43ff2d28c50293886ad1d5d4
// - Path: GSL/include/gsl/gsl_util
// - Author: Microsoft
// - Copyright: (c) 2015 Microsoft Corporation. All rights reserved.
// - License: MIT
#pragma once
#include <type_traits>
#include "vast/config.hpp"
#include "vast/detail/raise_error.hpp"
namespace vast::detail {
#ifndef VAST_NO_EXCEPTIONS
/// @relates narrow
struct narrowing_error : std::runtime_error {
using super = std::runtime_error;
using super::super;
};
#endif // VAST_NO_EXCEPTIONS
/// A searchable way to do narrowing casts of values.
template <class T, class U>
constexpr T narrow_cast(U&& u) noexcept {
return static_cast<T>(std::forward<U>(u));
}
template <class T, class U>
struct is_same_signedness
: public std::integral_constant<bool, std::is_signed<T>::value
== std::is_signed<U>::value> {};
/// A checked version of narrow_cast that throws if the cast changed the value.
template <class T, class U>
T narrow(U y) {
T x = narrow_cast<T>(y);
if (static_cast<U>(x) != y)
VAST_RAISE_ERROR(narrowing_error, "narrowing error");
if (!is_same_signedness<T, U>::value && ((x < T{}) != (y < U{})))
VAST_RAISE_ERROR(narrowing_error, "narrowing error");
return x;
}
} // namespace vast::detail
| 38.265625 | 80 | 0.541854 | knapperzbusch |
ed8efa5d49b6befa077a1718606278c341d74040 | 5,735 | cpp | C++ | src/Magnum/Platform/WindowlessCglApplication.cpp | felixguendling/magnum | 8439cb792b3af9a878591186596e2f0c406b0897 | [
"MIT"
] | 3 | 2018-01-16T09:26:20.000Z | 2020-06-23T13:26:36.000Z | src/Magnum/Platform/WindowlessCglApplication.cpp | felixguendling/magnum | 8439cb792b3af9a878591186596e2f0c406b0897 | [
"MIT"
] | null | null | null | src/Magnum/Platform/WindowlessCglApplication.cpp | felixguendling/magnum | 8439cb792b3af9a878591186596e2f0c406b0897 | [
"MIT"
] | 1 | 2016-10-09T14:53:45.000Z | 2016-10-09T14:53:45.000Z | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021 Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2013 <https://github.com/ArEnSc>
Copyright © 2014 Travis Watkins <https://github.com/amaranth>
Copyright © 2021 Konstantinos Chatzilygeroudis <costashatz@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 "WindowlessCglApplication.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Debug.h>
#include "Magnum/GL/Version.h"
namespace Magnum { namespace Platform {
WindowlessCglContext::WindowlessCglContext(const Configuration& configuration, GLContext*) {
int formatCount;
CGLPixelFormatAttribute attributes32[] = {
kCGLPFAAccelerated,
kCGLPFAOpenGLProfile,
CGLPixelFormatAttribute(kCGLOGLPVersion_3_2_Core),
CGLPixelFormatAttribute(0)
};
if(CGLChoosePixelFormat(attributes32, &_pixelFormat, &formatCount) != kCGLNoError) {
Warning() << "Platform::WindowlessCglContext: cannot choose pixel format for GL 3.2, falling back to 3.0";
CGLPixelFormatAttribute attributes30[] = {
kCGLPFAAccelerated,
kCGLPFAOpenGLProfile,
CGLPixelFormatAttribute(kCGLOGLPVersion_GL3_Core),
CGLPixelFormatAttribute(0)
};
if(CGLChoosePixelFormat(attributes30, &_pixelFormat, &formatCount) != kCGLNoError) {
Warning() << "Platform::WindowlessCglContext: cannot choose pixel format for GL 3.0, falling back to 2.1";
CGLPixelFormatAttribute attributes21[] = {
kCGLPFAAccelerated,
kCGLPFAOpenGLProfile,
CGLPixelFormatAttribute(kCGLOGLPVersion_Legacy),
CGLPixelFormatAttribute(0)
};
if(CGLChoosePixelFormat(attributes21, &_pixelFormat, &formatCount) != kCGLNoError) {
Error() << "Platform::WindowlessCglContext: cannot choose pixel format";
return;
}
}
}
if(CGLCreateContext(_pixelFormat, configuration.sharedContext(), &_context) != kCGLNoError)
Error() << "Platform::WindowlessCglContext: cannot create context";
}
WindowlessCglContext::WindowlessCglContext(WindowlessCglContext&& other): _pixelFormat{other._pixelFormat}, _context{other._context} {
other._pixelFormat = {};
other._context = {};
}
WindowlessCglContext::~WindowlessCglContext() {
if(_context) CGLDestroyContext(_context);
if(_pixelFormat) CGLDestroyPixelFormat(_pixelFormat);
}
WindowlessCglContext& WindowlessCglContext::operator=(WindowlessCglContext&& other) {
using std::swap;
swap(other._pixelFormat, _pixelFormat);
swap(other._context, _context);
return *this;
}
bool WindowlessCglContext::makeCurrent() {
if(CGLSetCurrentContext(_context) == kCGLNoError)
return true;
Error() << "Platform::WindowlessCglContext::makeCurrent(): cannot make context current";
return false;
}
bool WindowlessCglContext::release() {
if(CGLSetCurrentContext(0) == kCGLNoError)
return true;
Error() << "Platform::WindowlessCglContext::release(): cannot release current context";
return false;
}
WindowlessCglContext::Configuration::Configuration() {
GL::Context::Configuration::addFlags(GL::Context::Configuration::Flag::Windowless);
}
#ifndef DOXYGEN_GENERATING_OUTPUT
WindowlessCglApplication::WindowlessCglApplication(const Arguments& arguments): WindowlessCglApplication{arguments, Configuration{}} {}
#endif
WindowlessCglApplication::WindowlessCglApplication(const Arguments& arguments, const Configuration& configuration): WindowlessCglApplication{arguments, NoCreate} {
createContext(configuration);
}
WindowlessCglApplication::WindowlessCglApplication(const Arguments& arguments, NoCreateT): _glContext{NoCreate}, _context{NoCreate, arguments.argc, arguments.argv} {}
WindowlessCglApplication::~WindowlessCglApplication() = default;
void WindowlessCglApplication::createContext() { createContext({}); }
void WindowlessCglApplication::createContext(const Configuration& configuration) {
if(!tryCreateContext(configuration)) std::exit(1);
}
bool WindowlessCglApplication::tryCreateContext(const Configuration& configuration) {
CORRADE_ASSERT(_context.version() == GL::Version::None, "Platform::WindowlessCglApplication::tryCreateContext(): context already created", false);
WindowlessCglContext glContext{configuration, &_context};
if(!glContext.isCreated() || !glContext.makeCurrent() || !_context.tryCreate(configuration))
return false;
_glContext = std::move(glContext);
return true;
}
}}
| 40.387324 | 166 | 0.729381 | felixguendling |
ed9a3751c9d53677847ef8bce51550a59dddb4b1 | 336 | cpp | C++ | 11172 - Relational Operator.cpp | Rodagui/UVa-Solutions | d4273fc1f2ce843a23bf94d3b3037e66b9d285d1 | [
"MIT"
] | null | null | null | 11172 - Relational Operator.cpp | Rodagui/UVa-Solutions | d4273fc1f2ce843a23bf94d3b3037e66b9d285d1 | [
"MIT"
] | null | null | null | 11172 - Relational Operator.cpp | Rodagui/UVa-Solutions | d4273fc1f2ce843a23bf94d3b3037e66b9d285d1 | [
"MIT"
] | 1 | 2020-06-22T03:34:27.000Z | 2020-06-22T03:34:27.000Z | /*11172 - Relational Operator*/
#include <iostream>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int casos, a, b;
cin>>casos;
while(casos--){
cin>>a>>b;
if(a>b)
cout<<">\n";
if(a<b)
cout<<"<\n";
if(a==b)
cout<<"=\n";
}
return 0;
}
| 10.5 | 32 | 0.46131 | Rodagui |
ed9b41cce8216d4a7a53c67aadbf0f4b711f1c2a | 12,872 | cpp | C++ | far/plugsettings.cpp | tralivali1234/FarManager | 24d88b4382af3a4853e6883aaa2d0a8db60bf299 | [
"BSD-3-Clause"
] | null | null | null | far/plugsettings.cpp | tralivali1234/FarManager | 24d88b4382af3a4853e6883aaa2d0a8db60bf299 | [
"BSD-3-Clause"
] | null | null | null | far/plugsettings.cpp | tralivali1234/FarManager | 24d88b4382af3a4853e6883aaa2d0a8db60bf299 | [
"BSD-3-Clause"
] | null | null | null | /*
plugsettings.cpp
API для хранения плагинами настроек.
*/
/*
Copyright © 2011 Far Group
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 authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
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.
*/
// Self:
#include "plugsettings.hpp"
// Internal:
#include "ctrlobj.hpp"
#include "history.hpp"
#include "uuids.far.hpp"
#include "shortcuts.hpp"
#include "dizlist.hpp"
#include "config.hpp"
#include "pathmix.hpp"
#include "plugins.hpp"
#include "configdb.hpp"
#include "global.hpp"
#include "exception.hpp"
// Platform:
// Common:
#include "common/bytes_view.hpp"
#include "common/function_ref.hpp"
#include "common/string_utils.hpp"
#include "common/uuid.hpp"
// External:
//----------------------------------------------------------------------------
const wchar_t* AbstractSettings::Add(string_view const String)
{
return static_cast<const wchar_t*>(Add(String.data(), (String.size() + 1) * sizeof(wchar_t)));
}
const void* AbstractSettings::Add(const void* Data, size_t Size)
{
const auto Dest = Allocate(Size);
copy_memory(Data, Dest, Size);
return Dest;
}
void* AbstractSettings::Allocate(size_t Size)
{
m_Data.emplace_back(Size);
return m_Data.back().data();
}
class PluginSettings: public AbstractSettings
{
public:
PluginSettings(const Plugin* pPlugin, bool Local);
~PluginSettings() override;
bool Set(const FarSettingsItem& Item) override;
bool Get(FarSettingsItem& Item) override;
bool Enum(FarSettingsEnum& Enum) override;
bool Delete(const FarSettingsValue& Value) override;
int SubKey(const FarSettingsValue& Value, bool bCreate) override;
class FarSettingsNameItems;
private:
std::vector<FarSettingsNameItems> m_Enum;
std::vector<HierarchicalConfig::key> m_Keys;
HierarchicalConfigUniquePtr PluginsCfg;
};
std::unique_ptr<AbstractSettings> AbstractSettings::CreatePluginSettings(const UUID& Uuid, bool const Local)
{
const auto pPlugin = Global->CtrlObject->Plugins->FindPlugin(Uuid);
if (!pPlugin)
return nullptr;
try
{
return std::make_unique<PluginSettings>(pPlugin, Local);
}
catch (const far_exception&)
{
return nullptr;
}
}
PluginSettings::PluginSettings(const Plugin* const pPlugin, bool const Local)
{
const auto strUuid = uuid::str(pPlugin->Id());
PluginsCfg = ConfigProvider().CreatePluginsConfig(strUuid, Local, false);
PluginsCfg->BeginTransaction();
const auto Key = PluginsCfg->CreateKey(HierarchicalConfig::root_key, strUuid);
PluginsCfg->SetKeyDescription(Key, pPlugin->Title());
m_Keys.emplace_back(Key);
if (!Global->Opt->ReadOnlyConfig)
{
DizList Diz;
const auto DbPath = path::join(Local? Global->Opt->LocalProfilePath : Global->Opt->ProfilePath, L"PluginsData"sv);
Diz.Read(DbPath);
const string DbName(PointToName(PluginsCfg->GetName()));
const auto Description = concat(pPlugin->Title(), L" ("sv, pPlugin->Description(), L')');
if (Description != Diz.Get(DbName, {}, 0))
{
Diz.Set(DbName, {}, Description);
Diz.Flush(DbPath);
}
}
}
PluginSettings::~PluginSettings()
{
if (PluginsCfg)
PluginsCfg->EndTransaction();
}
bool PluginSettings::Set(const FarSettingsItem& Item)
{
if (Item.Root >= m_Keys.size())
return false;
const auto name = NullToEmpty(Item.Name);
switch(Item.Type)
{
case FST_SUBKEY:
return false;
case FST_QWORD:
PluginsCfg->SetValue(m_Keys[Item.Root], name, Item.Number);
return true;
case FST_STRING:
PluginsCfg->SetValue(m_Keys[Item.Root], name, NullToEmpty(Item.String));
return true;
case FST_DATA:
PluginsCfg->SetValue(m_Keys[Item.Root], name, view_bytes(Item.Data.Data, Item.Data.Size));
return true;
default:
return false;
}
}
bool PluginSettings::Get(FarSettingsItem& Item)
{
if (Item.Root >= m_Keys.size())
return false;
const auto name = NullToEmpty(Item.Name);
switch(Item.Type)
{
case FST_SUBKEY:
return false;
case FST_QWORD:
{
unsigned long long value;
if (PluginsCfg->GetValue(m_Keys[Item.Root], name, value))
{
Item.Number = value;
return true;
}
}
break;
case FST_STRING:
{
string data;
if (PluginsCfg->GetValue(m_Keys[Item.Root], name, data))
{
Item.String = Add(data);
return true;
}
}
break;
case FST_DATA:
{
bytes data;
if (PluginsCfg->GetValue(m_Keys[Item.Root], name, data))
{
Item.Data.Data = Add(data.data(), data.size());
Item.Data.Size = data.size();
return true;
}
}
break;
default:
return false;
}
return false;
}
class PluginSettings::FarSettingsNameItems
{
public:
NONCOPYABLE(FarSettingsNameItems);
MOVE_CONSTRUCTIBLE(FarSettingsNameItems);
FarSettingsNameItems() = default;
void add(FarSettingsName& Item, string&& String)
{
m_Strings.emplace_front(std::move(String));
Item.Name = m_Strings.front().c_str();
m_Items.emplace_back(Item);
}
void get(FarSettingsEnum& e) const
{
e.Count = m_Items.size();
e.Items = e.Count? m_Items.data() : nullptr;
}
private:
std::vector<FarSettingsName> m_Items;
// String address must always remain valid, hence the list
std::forward_list<string> m_Strings;
};
class FarSettings: public AbstractSettings
{
public:
bool Set(const FarSettingsItem& Item) override;
bool Get(FarSettingsItem& Item) override;
bool Enum(FarSettingsEnum& Enum) override;
bool Delete(const FarSettingsValue& Value) override;
int SubKey(const FarSettingsValue& Value, bool bCreate) override;
class FarSettingsHistoryItems;
private:
bool FillHistory(int Type, string_view HistoryName, FarSettingsEnum& Enum, function_ref<bool(history_record_type)> Filter);
std::vector<FarSettingsHistoryItems> m_Enum;
std::vector<string> m_Keys;
};
std::unique_ptr<AbstractSettings> AbstractSettings::CreateFarSettings()
{
return std::make_unique<FarSettings>();
}
class FarSettings::FarSettingsHistoryItems
{
public:
NONCOPYABLE(FarSettingsHistoryItems);
MOVE_CONSTRUCTIBLE(FarSettingsHistoryItems);
FarSettingsHistoryItems() = default;
void add(FarSettingsHistory& Item, string&& Name, string&& Param, string&& File, const UUID& Uuid)
{
m_Names.emplace_front(std::move(Name));
m_Params.emplace_front(std::move(Param));
m_Files.emplace_front(std::move(File));
Item.Name = m_Names.front().c_str();
Item.Param = m_Params.front().c_str();
Item.File = m_Files.front().c_str();
Item.PluginId = Uuid;
m_Items.emplace_back(Item);
}
void get(FarSettingsEnum& e) const
{
e.Count = m_Items.size();
e.Histories = e.Count? m_Items.data() : nullptr;
}
private:
std::vector<FarSettingsHistory> m_Items;
// String address must always remain valid, hence the list
std::forward_list<string> m_Names, m_Params, m_Files;
};
bool PluginSettings::Enum(FarSettingsEnum& Enum)
{
if (Enum.Root >= m_Keys.size())
return false;
FarSettingsName item{ nullptr, FST_SUBKEY };
FarSettingsNameItems NewEnumItem;
const auto& root = m_Keys[Enum.Root];
{
string KeyName;
for (const auto& Key : PluginsCfg->KeysEnumerator(root))
{
if (PluginsCfg->GetKeyName(root, Key, KeyName))
NewEnumItem.add(item, std::move(KeyName));
}
}
for(auto& [Name, Value]: PluginsCfg->ValuesEnumerator(root))
{
item.Type = static_cast<FARSETTINGSTYPES>(PluginsCfg->ToSettingsType(Value));
if(item.Type!=FST_UNKNOWN)
{
NewEnumItem.add(item, std::move(Name));
}
}
NewEnumItem.get(Enum);
m_Enum.emplace_back(std::move(NewEnumItem));
return true;
}
bool PluginSettings::Delete(const FarSettingsValue& Value)
{
if (Value.Root >= m_Keys.size())
return false;
Value.Value?
PluginsCfg->DeleteValue(m_Keys[Value.Root], Value.Value) :
PluginsCfg->DeleteKeyTree(m_Keys[Value.Root]);
return true;
}
int PluginSettings::SubKey(const FarSettingsValue& Value, bool bCreate)
{
//Don't allow illegal key names - empty names or with backslashes
if (Value.Root >= m_Keys.size() || !Value.Value || !*Value.Value || contains(Value.Value, '\\'))
return 0;
const auto root = bCreate? PluginsCfg->CreateKey(m_Keys[Value.Root], Value.Value) : PluginsCfg->FindByName(m_Keys[Value.Root], Value.Value);
if (!bCreate && !root)
return 0;
m_Keys.emplace_back(root);
return static_cast<int>(m_Keys.size() - 1);
}
bool FarSettings::Set(const FarSettingsItem& Item)
{
return false;
}
bool FarSettings::Get(FarSettingsItem& Item)
{
const auto Data = Global->Opt->GetConfigValue(Item.Root, Item.Name);
if (!Data)
return false;
Data->Export(Item);
if (Item.Type == FST_STRING)
Item.String = Add(Item.String);
return true;
}
bool FarSettings::Enum(FarSettingsEnum& Enum)
{
const auto FilterNone = [](history_record_type) { return true; };
switch(Enum.Root)
{
case FSSF_HISTORY_CMD:
return FillHistory(HISTORYTYPE_CMD, {}, Enum, FilterNone);
case FSSF_HISTORY_FOLDER:
return FillHistory(HISTORYTYPE_FOLDER, {}, Enum, FilterNone);
case FSSF_HISTORY_VIEW:
return FillHistory(HISTORYTYPE_VIEW, {}, Enum, [](history_record_type Type) { return Type == HR_VIEWER; });
case FSSF_HISTORY_EDIT:
return FillHistory(HISTORYTYPE_VIEW, {}, Enum, [](history_record_type Type) { return Type == HR_EDITOR || Type == HR_EDITOR_RO; });
case FSSF_HISTORY_EXTERNAL:
return FillHistory(HISTORYTYPE_VIEW, {}, Enum, [](history_record_type Type) { return Type == HR_EXTERNAL || Type == HR_EXTERNAL_WAIT; });
case FSSF_FOLDERSHORTCUT_0:
case FSSF_FOLDERSHORTCUT_1:
case FSSF_FOLDERSHORTCUT_2:
case FSSF_FOLDERSHORTCUT_3:
case FSSF_FOLDERSHORTCUT_4:
case FSSF_FOLDERSHORTCUT_5:
case FSSF_FOLDERSHORTCUT_6:
case FSSF_FOLDERSHORTCUT_7:
case FSSF_FOLDERSHORTCUT_8:
case FSSF_FOLDERSHORTCUT_9:
{
FarSettingsHistory item{};
FarSettingsHistoryItems NewEnumItem;
for(auto& i: Shortcuts(Enum.Root - FSSF_FOLDERSHORTCUT_0).Enumerator())
{
NewEnumItem.add(item, std::move(i.Folder), std::move(i.PluginData), std::move(i.PluginFile), i.PluginUuid);
}
NewEnumItem.get(Enum);
m_Enum.emplace_back(std::move(NewEnumItem));
return true;
}
default:
if(Enum.Root >= FSSF_COUNT)
{
const auto root = Enum.Root - FSSF_COUNT;
if(root < m_Keys.size())
{
return FillHistory(HISTORYTYPE_DIALOG, m_Keys[root], Enum, FilterNone);
}
}
return false;
}
}
bool FarSettings::Delete(const FarSettingsValue& Value)
{
return false;
}
int FarSettings::SubKey(const FarSettingsValue& Value, bool bCreate)
{
if (bCreate || Value.Root != FSSF_ROOT)
return 0;
const size_t Position = std::find(ALL_CONST_RANGE(m_Keys), Value.Value) - m_Keys.cbegin();
if (Position == m_Keys.size())
m_Keys.emplace_back(Value.Value);
return static_cast<int>(Position + FSSF_COUNT);
}
static const auto& HistoryRef(int Type)
{
const auto IsPersistent = [Type]() -> bool
{
switch (Type)
{
case HISTORYTYPE_CMD: return Global->Opt->SaveHistory;
case HISTORYTYPE_FOLDER: return Global->Opt->SaveFoldersHistory;
case HISTORYTYPE_VIEW: return Global->Opt->SaveViewHistory;
case HISTORYTYPE_DIALOG: return Global->Opt->Dialogs.EditHistory;
default: return true;
}
};
return IsPersistent()? ConfigProvider().HistoryCfg() : ConfigProvider().HistoryCfgMem();
}
bool FarSettings::FillHistory(int Type, string_view const HistoryName, FarSettingsEnum& Enum, function_ref<bool(history_record_type)> const Filter)
{
FarSettingsHistory item = {};
FarSettingsHistoryItems NewEnumItem;
for(auto& i: HistoryRef(Type)->Enumerator(Type, HistoryName))
{
if (!Filter(i.Type))
continue;
item.Time = os::chrono::nt_clock::to_filetime(i.Time);
item.Lock = i.Lock;
const auto Uuid = uuid::try_parse(i.Uuid);
NewEnumItem.add(item, std::move(i.Name), std::move(i.Data), std::move(i.File), Uuid? *Uuid : FarUuid);
}
NewEnumItem.get(Enum);
m_Enum.emplace_back(std::move(NewEnumItem));
return true;
}
| 25.692615 | 147 | 0.7305 | tralivali1234 |
ed9cea9679b55a987af466105cd79032f92f1729 | 80,844 | cpp | C++ | test/model_component/test_expression_proxy.cpp | snowberryfield/printemps | 53f14da11bfddc90a561be08f6bd73cf7df7399c | [
"MIT"
] | 16 | 2020-12-07T03:47:54.000Z | 2022-03-16T02:14:48.000Z | test/model_component/test_expression_proxy.cpp | snowberryfield/printemps | 53f14da11bfddc90a561be08f6bd73cf7df7399c | [
"MIT"
] | null | null | null | test/model_component/test_expression_proxy.cpp | snowberryfield/printemps | 53f14da11bfddc90a561be08f6bd73cf7df7399c | [
"MIT"
] | null | null | null | /*****************************************************************************/
// Copyright (c) 2020-2021 Yuji KOGUMA
// Released under the MIT license
// https://opensource.org/licenses/mit-license.php
/*****************************************************************************/
#include <gtest/gtest.h>
#include <random>
#include <printemps.h>
namespace {
/*****************************************************************************/
class TestExpressionProxy : public ::testing::Test {
protected:
printemps::utility::IntegerUniformRandom m_random_integer;
printemps::utility::IntegerUniformRandom m_random_positive_integer;
virtual void SetUp(void) {
m_random_integer.setup(-1000, 1000, 0);
m_random_positive_integer.setup(1, 1000, 0);
}
virtual void TearDown() {
/// nothing to do
}
int random_integer(void) {
return m_random_integer.generate_random();
}
int random_positive_integer(void) {
return m_random_positive_integer.generate_random();
}
};
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_create_instance) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
/// Check the initial values of the base class members.
EXPECT_EQ(0, expression_proxy.index());
EXPECT_EQ(1, expression_proxy.shape()[0]);
EXPECT_EQ(1, expression_proxy.strides()[0]);
EXPECT_EQ(1, expression_proxy.number_of_dimensions());
EXPECT_EQ(1, expression_proxy.number_of_elements());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_sensitivities) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity = random_integer();
expression_proxy = sensitivity * variable;
EXPECT_EQ(sensitivity, expression_proxy.sensitivities().at(&variable));
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_constant_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto constant = random_integer();
expression_proxy = constant;
EXPECT_EQ(constant, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_evaluate_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
auto expected_result =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
EXPECT_EQ(expected_result, expression_proxy.evaluate());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_evaluate_arg_move) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression.setup_fixed_sensitivities();
}
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
expression_proxy.update();
printemps::neighborhood::Move<int, double> move;
value_0 = random_integer();
value_1 = random_integer();
move.alterations.emplace_back(&variable_0, value_0);
move.alterations.emplace_back(&variable_1, value_1);
auto expected_result =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
EXPECT_EQ(expected_result, expression_proxy.evaluate(move));
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_update_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
expression_proxy.update();
auto expected_result =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
EXPECT_EQ(expected_result, expression_proxy.value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_update_arg_move) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression.setup_fixed_sensitivities();
}
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
expression_proxy.update();
printemps::neighborhood::Move<int, double> move;
value_0 = random_integer();
value_1 = random_integer();
move.alterations.emplace_back(&variable_0, value_0);
move.alterations.emplace_back(&variable_1, value_1);
expression_proxy.update(move);
auto expected_result =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
EXPECT_EQ(expected_result, expression_proxy.value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_value) {
/// This method is tested in other cases.
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_set_name) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
expression_proxy.set_name("_e");
EXPECT_EQ("_e", expression_proxy.name());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_name) {
/// This method is tested in scalar_set_name().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_flat_indexed_expressions_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression *= 2;
}
EXPECT_EQ(2 * sensitivity_0,
expression_proxy.flat_indexed_expressions()[0].sensitivities().at(
&variable_0));
EXPECT_EQ(2 * sensitivity_1,
expression_proxy.flat_indexed_expressions()[0].sensitivities().at(
&variable_1));
EXPECT_EQ(2 * constant,
expression_proxy.flat_indexed_expressions()[0].constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_flat_indexed_expressions_arg_int) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy.flat_indexed_expressions(0) *= 2;
EXPECT_EQ(2 * sensitivity_0,
expression_proxy.flat_indexed_expressions(0).sensitivities().at(
&variable_0));
EXPECT_EQ(2 * sensitivity_1,
expression_proxy.flat_indexed_expressions(0).sensitivities().at(
&variable_1));
EXPECT_EQ(2 * constant,
expression_proxy.flat_indexed_expressions(0).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_export_values_and_names) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
expression_proxy.update();
auto expected_value =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
EXPECT_EQ(expected_value,
expression_proxy.export_values_and_names().value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_to_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
auto expression = expression_proxy.to_expression();
EXPECT_EQ(sensitivity_0, expression.sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_1, expression.sensitivities().at(&variable_1));
EXPECT_EQ(constant, expression.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_sum_arg_void) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy = model.create_expression("e");
expression_proxy = variable_proxy;
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = expression_proxy.sum();
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression.evaluate());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_sum_arg_indices) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy = model.create_expression("e");
expression_proxy = variable_proxy;
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = expression_proxy.sum({printemps::model_component::Range::All});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression.evaluate());
ASSERT_THROW(
variable_proxy.sum({printemps::model_component::Range::All, 0}),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_dot_arg_vector) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy = model.create_expression("e");
expression_proxy = variable_proxy;
std::vector<double> sensitivities;
sensitivities.push_back(random_integer());
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = variable_proxy.dot(sensitivities);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(sensitivities[0],
expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(sensitivities[0], expression.evaluate());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_dot_arg_indice_vector) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy = model.create_expression("e");
expression_proxy = variable_proxy;
std::vector<double> sensitivities;
sensitivities.push_back(random_integer());
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = variable_proxy.dot({printemps::model_component::Range::All},
sensitivities);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(sensitivities[0],
expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(sensitivities[0], expression.evaluate());
ASSERT_THROW(
expression_proxy.dot({0, printemps::model_component::Range::All},
sensitivities),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_is_enabled) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
expression_proxy.disable();
EXPECT_FALSE(expression_proxy.is_enabled());
expression_proxy.enable();
EXPECT_TRUE(expression_proxy.is_enabled());
expression_proxy.disable();
EXPECT_FALSE(expression_proxy.is_enabled());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_enable) {
/// This method is tested in scalar_is_enabled().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_disable) {
/// This method is tested in scalar_is_enabled().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_plus) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
EXPECT_EQ(sensitivity_0,
(+expression_proxy).sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_1,
(+expression_proxy).sensitivities().at(&variable_1));
EXPECT_EQ(constant, (+expression_proxy).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_minus) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
EXPECT_EQ(-sensitivity_0,
(-expression_proxy).sensitivities().at(&variable_0));
EXPECT_EQ(-sensitivity_1,
(-expression_proxy).sensitivities().at(&variable_1));
EXPECT_EQ(-constant, (-expression_proxy).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto value = random_integer();
EXPECT_EQ(value, (expression_proxy = value).constant_value());
EXPECT_EQ(value, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
EXPECT_EQ(1, (expression_proxy = variable_proxy)
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(1, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// variable
EXPECT_EQ(1, (expression_proxy = variable_proxy[0])
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(1, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// expression proxy
EXPECT_EQ(1, (expression_proxy = expression_proxy_other)
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(1, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// If the size of variable_proxy or expression_proxy_other > 1, an error
/// will be thrown at the to_expression()
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_equal_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
EXPECT_EQ(sensitivity_0,
(expression_proxy += expression).sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_1, expression_proxy.sensitivities().at(&variable_1));
EXPECT_EQ(constant, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_plus_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto value_0 = random_integer();
auto value_1 = random_integer();
EXPECT_EQ(value_0, (expression_proxy += value_0).constant_value());
EXPECT_EQ(value_0, expression_proxy.constant_value());
EXPECT_EQ(value_0 + value_1,
(expression_proxy += value_1).constant_value());
EXPECT_EQ(value_0 + value_1, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_plus_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
EXPECT_EQ(1, (expression_proxy += variable_proxy)
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(1, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// variable
EXPECT_EQ(2, (expression_proxy += variable_proxy[0])
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(2, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// expression proxy
EXPECT_EQ(3, (expression_proxy += expression_proxy_other)
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(3, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// If the size of variable_proxy or expression_proxy_other > 1, an error
/// will be thrown at the to_expression()
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, operator_plus_equal_arg_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0_0 = random_integer();
auto sensitivity_0_1 = random_integer();
auto sensitivity_1_0 = random_integer();
auto sensitivity_1_1 = random_integer();
auto constant_0 = random_integer();
auto constant_1 = random_integer();
expression_proxy = sensitivity_0_0 * variable_0 +
sensitivity_1_0 * variable_1 + constant_0;
expression = sensitivity_0_1 * variable_0 + sensitivity_1_1 * variable_1 +
constant_1;
EXPECT_EQ(sensitivity_0_0 + sensitivity_0_1,
(expression_proxy += expression).sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_0_0 + sensitivity_0_1,
expression_proxy.sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_1_0 + sensitivity_1_1,
expression_proxy.sensitivities().at(&variable_1));
EXPECT_EQ(constant_0 + constant_1, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_minus_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto value_0 = random_integer();
auto value_1 = random_integer();
EXPECT_EQ(-value_0, (expression_proxy -= value_0).constant_value());
EXPECT_EQ(-value_0, expression_proxy.constant_value());
EXPECT_EQ(-value_0 - value_1,
(expression_proxy -= value_1).constant_value());
EXPECT_EQ(-value_0 - value_1, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_minus_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
EXPECT_EQ(-1, (expression_proxy -= variable_proxy)
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(-1, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// variable
EXPECT_EQ(-2, (expression_proxy -= variable_proxy[0])
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(-2, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// expression proxy
EXPECT_EQ(-3, (expression_proxy -= expression_proxy_other)
.sensitivities()
.at(&variable_proxy[0]));
EXPECT_EQ(-3, expression_proxy.sensitivities().at(&variable_proxy[0]));
/// If the size of variable_proxy or expression_proxy_other > 1, an error
/// will be thrown at the to_expression()
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_minus_equal_arg_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0_0 = random_integer();
auto sensitivity_0_1 = random_integer();
auto sensitivity_1_0 = random_integer();
auto sensitivity_1_1 = random_integer();
auto constant_0 = random_integer();
auto constant_1 = random_integer();
expression_proxy = sensitivity_0_0 * variable_0 +
sensitivity_1_0 * variable_1 + constant_0;
expression = sensitivity_0_1 * variable_0 + sensitivity_1_1 * variable_1 +
constant_1;
EXPECT_EQ(sensitivity_0_0 - sensitivity_0_1,
(expression_proxy -= expression).sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_0_0 - sensitivity_0_1,
expression_proxy.sensitivities().at(&variable_0));
EXPECT_EQ(sensitivity_1_0 - sensitivity_1_1,
expression_proxy.sensitivities().at(&variable_1));
EXPECT_EQ(constant_0 - constant_1, expression_proxy.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_product_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity = random_integer();
auto constant = random_integer();
expression_proxy = sensitivity * variable + constant;
auto value_0 = random_integer();
auto value_1 = random_integer();
EXPECT_EQ(constant * value_0,
(expression_proxy *= value_0).constant_value());
EXPECT_EQ(constant * value_0, expression_proxy.constant_value());
EXPECT_EQ(sensitivity * value_0 * value_1,
(expression_proxy *= value_1).sensitivities().at(&variable));
EXPECT_EQ(sensitivity * value_0 * value_1,
expression_proxy.sensitivities().at(&variable));
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, scalar_operator_divide_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expression("e");
auto variable =
printemps::model_component::Variable<int, double>::create_instance();
expression_proxy = 100 * variable + 200;
EXPECT_EQ(100, (expression_proxy /= 2).constant_value());
EXPECT_EQ(100, expression_proxy.constant_value());
EXPECT_EQ(25, (expression_proxy /= 2).sensitivities().at(&variable));
EXPECT_EQ(25, expression_proxy.sensitivities().at(&variable));
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_create_instance) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
/// Check the initial values of the base class members.
EXPECT_EQ(0, expression_proxy.index());
EXPECT_EQ(2, expression_proxy.shape()[0]);
EXPECT_EQ(1, expression_proxy.strides()[0]);
EXPECT_EQ(1, expression_proxy.number_of_dimensions());
EXPECT_EQ(2, expression_proxy.number_of_elements());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_sensitivities) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(auto sensitivities = expression_proxy.sensitivities(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_constant_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(
[[maybe_unused]] auto constant = expression_proxy.constant_value(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_evaluate_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(expression_proxy.evaluate(), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_evaluate_arg_move) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(expression_proxy.evaluate({}), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_update_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(expression_proxy.update(), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_update_arg_move) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(expression_proxy.update({}), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW([[maybe_unused]] auto value = expression_proxy.value(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_set_name) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(expression_proxy.set_name("_e"), std::logic_error);
ASSERT_THROW(expression_proxy.name(), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_name) {
/// This method is tested in two_dimensional_set_name().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_flat_indexed_expressions_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy[1] = expression_proxy[0] * 2;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression *= 2;
}
EXPECT_EQ(2 * sensitivity_0,
expression_proxy.flat_indexed_expressions()[0].sensitivities().at(
&variable_0));
EXPECT_EQ(2 * sensitivity_1,
expression_proxy.flat_indexed_expressions()[0].sensitivities().at(
&variable_1));
EXPECT_EQ(2 * constant,
expression_proxy.flat_indexed_expressions()[0].constant_value());
EXPECT_EQ(4 * sensitivity_0,
expression_proxy.flat_indexed_expressions()[1].sensitivities().at(
&variable_0));
EXPECT_EQ(4 * sensitivity_1,
expression_proxy.flat_indexed_expressions()[1].sensitivities().at(
&variable_1));
EXPECT_EQ(4 * constant,
expression_proxy.flat_indexed_expressions()[1].constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_flat_indexed_expressions_arg_int) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy[1] = expression_proxy[0] * 2;
expression_proxy.flat_indexed_expressions(0) *= 2;
expression_proxy.flat_indexed_expressions(1) *= 2;
EXPECT_EQ(2 * sensitivity_0,
expression_proxy.flat_indexed_expressions(0).sensitivities().at(
&variable_0));
EXPECT_EQ(2 * sensitivity_1,
expression_proxy.flat_indexed_expressions(0).sensitivities().at(
&variable_1));
EXPECT_EQ(2 * constant,
expression_proxy.flat_indexed_expressions(0).constant_value());
EXPECT_EQ(4 * sensitivity_0,
expression_proxy.flat_indexed_expressions(1).sensitivities().at(
&variable_0));
EXPECT_EQ(4 * sensitivity_1,
expression_proxy.flat_indexed_expressions(1).sensitivities().at(
&variable_1));
EXPECT_EQ(4 * constant,
expression_proxy.flat_indexed_expressions(1).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_export_values_and_names) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy[1] = expression_proxy[0] * 2;
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression.update();
}
auto expected_value_0 =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
auto expected_value_1 = expected_value_0 * 2;
EXPECT_EQ(expected_value_0,
expression_proxy.export_values_and_names().values(0));
EXPECT_EQ(expected_value_1,
expression_proxy.export_values_and_names().values(1));
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_to_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(auto expression = expression_proxy.to_expression(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_sum_arg_void) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", 2);
auto& expression_proxy = model.create_expressions("e", 2);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = variable_proxy.sum();
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[1])));
EXPECT_EQ(2, expression.evaluate());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_sum_arg_indices) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", 2);
auto& expression_proxy = model.create_expressions("e", 2);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = variable_proxy.sum({printemps::model_component::Range::All});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[1])));
EXPECT_EQ(2, expression.evaluate());
ASSERT_THROW(
expression_proxy.sum({printemps::model_component::Range::All, 0}),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_dot_arg_vector) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", 2);
auto& expression_proxy = model.create_expressions("e", 2);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
std::vector<double> sensitivities;
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
sensitivities.push_back(random_integer());
}
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = expression_proxy.dot(sensitivities);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(sensitivities[0],
expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(sensitivities[1],
expression.sensitivities().at(&(variable_proxy[1])));
EXPECT_EQ(sensitivities[0] + sensitivities[1], expression.evaluate());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_dot_arg_indice_vector) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", 2);
auto& expression_proxy = model.create_expressions("e", 2);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
std::vector<double> sensitivities;
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
sensitivities.push_back(random_integer());
}
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = expression_proxy.dot(sensitivities);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(sensitivities[0],
expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(sensitivities[1],
expression.sensitivities().at(&(variable_proxy[1])));
EXPECT_EQ(sensitivities[0] + sensitivities[1], expression.evaluate());
ASSERT_THROW(
expression_proxy.dot({0, printemps::model_component::Range::All},
sensitivities),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_is_enabled) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
expression_proxy.disable();
ASSERT_THROW(expression_proxy.is_enabled(), std::logic_error);
EXPECT_FALSE(expression_proxy[0].is_enabled());
EXPECT_FALSE(expression_proxy[1].is_enabled());
expression_proxy.enable();
ASSERT_THROW(expression_proxy.is_enabled(), std::logic_error);
EXPECT_TRUE(expression_proxy[0].is_enabled());
EXPECT_TRUE(expression_proxy[1].is_enabled());
expression_proxy.disable();
ASSERT_THROW(expression_proxy.is_enabled(), std::logic_error);
EXPECT_FALSE(expression_proxy[0].is_enabled());
EXPECT_FALSE(expression_proxy[1].is_enabled());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_enable) {
/// This method is tested in one_dimensional_is_enabled().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_disable) {
/// This method is tested in one_dimensional_is_enabled().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_plus) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(auto expression = +expression_proxy, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_minus) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
ASSERT_THROW(auto expression = -expression_proxy, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value = random_integer();
ASSERT_THROW(expression_proxy = value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
ASSERT_THROW(expression_proxy = variable_proxy, std::logic_error);
/// variable
ASSERT_THROW(expression_proxy = variable_proxy[0], std::logic_error);
/// expression proxy
ASSERT_THROW(expression_proxy = expression_proxy_other, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_equal_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
ASSERT_THROW(expression_proxy = expression, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_plus_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value = random_integer();
ASSERT_THROW(expression_proxy += value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_plus_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
ASSERT_THROW(expression_proxy += variable_proxy, std::logic_error);
/// variable
ASSERT_THROW(expression_proxy += variable_proxy[0], std::logic_error);
/// expression proxy
ASSERT_THROW(expression_proxy += expression_proxy_other, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_plus_equal_arg_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
ASSERT_THROW(expression_proxy += expression, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_minus_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value = random_integer();
ASSERT_THROW(expression_proxy -= value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_minus_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
ASSERT_THROW(expression_proxy -= variable_proxy, std::logic_error);
/// variable
ASSERT_THROW(expression_proxy -= variable_proxy[0], std::logic_error);
/// expression proxy
ASSERT_THROW(expression_proxy -= expression_proxy_other, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_minus_equal_arg_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
ASSERT_THROW(expression_proxy -= expression, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_product_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value = random_integer();
ASSERT_THROW(expression_proxy *= value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_divide_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value = random_integer();
ASSERT_THROW(expression_proxy /= value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_square_bracket) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy[0] = value_0;
expression_proxy[1] = value_1;
EXPECT_EQ(value_0, expression_proxy[0].constant_value());
EXPECT_EQ(value_1, expression_proxy[1].constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, one_dimensional_operator_round_bracket) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy(0) = value_0;
expression_proxy(1) = value_1;
EXPECT_EQ(value_0, expression_proxy(0).constant_value());
EXPECT_EQ(value_1, expression_proxy(1).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
one_dimensional_operator_round_bracket_with_indices) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", 2);
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy({0}) = value_0;
expression_proxy({1}) = value_1;
EXPECT_EQ(value_0, expression_proxy({0}).constant_value());
EXPECT_EQ(value_1, expression_proxy({1}).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_create_instance) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
/// Check the initial values of the base class members.
EXPECT_EQ(0, expression_proxy.index());
EXPECT_EQ(2, expression_proxy.shape()[0]);
EXPECT_EQ(3, expression_proxy.shape()[1]);
EXPECT_EQ(3, expression_proxy.strides()[0]);
EXPECT_EQ(1, expression_proxy.strides()[1]);
EXPECT_EQ(2, expression_proxy.number_of_dimensions());
EXPECT_EQ(2 * 3, expression_proxy.number_of_elements());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_sensitivities) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(auto sensitivities = expression_proxy.sensitivities(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_constant_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(
[[maybe_unused]] auto constant = expression_proxy.constant_value(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_evaluate_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(expression_proxy.evaluate(), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_evaluate_arg_move) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(expression_proxy.evaluate({}), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_update_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(expression_proxy.update(), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_update_arg_move) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(expression_proxy.update({}), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW([[maybe_unused]] auto value = expression_proxy.value(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_set_name) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(expression_proxy.set_name("_e"), std::logic_error);
ASSERT_THROW(expression_proxy.name(), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_name) {
/// This method is tested in two_dimensional_set_name().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_flat_indexed_expressions_arg_void) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy[2 * 3 - 1] = expression_proxy[0] * 2;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression *= 2;
}
EXPECT_EQ(2 * sensitivity_0,
expression_proxy.flat_indexed_expressions()[0].sensitivities().at(
&variable_0));
EXPECT_EQ(2 * sensitivity_1,
expression_proxy.flat_indexed_expressions()[0].sensitivities().at(
&variable_1));
EXPECT_EQ(2 * constant,
expression_proxy.flat_indexed_expressions()[0].constant_value());
EXPECT_EQ(4 * sensitivity_0,
expression_proxy.flat_indexed_expressions()[2 * 3 - 1]
.sensitivities()
.at(&variable_0));
EXPECT_EQ(4 * sensitivity_1,
expression_proxy.flat_indexed_expressions()[2 * 3 - 1]
.sensitivities()
.at(&variable_1));
EXPECT_EQ(4 * constant,
expression_proxy.flat_indexed_expressions()[2 * 3 - 1]
.constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_flat_indexed_expressions_arg_int) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy[2 * 3 - 1] = expression_proxy[0] * 2;
expression_proxy.flat_indexed_expressions(0) *= 2;
expression_proxy.flat_indexed_expressions(2 * 3 - 1) *= 2;
EXPECT_EQ(2 * sensitivity_0,
expression_proxy.flat_indexed_expressions(0).sensitivities().at(
&variable_0));
EXPECT_EQ(2 * sensitivity_1,
expression_proxy.flat_indexed_expressions(0).sensitivities().at(
&variable_1));
EXPECT_EQ(2 * constant,
expression_proxy.flat_indexed_expressions(0).constant_value());
EXPECT_EQ(
4 * sensitivity_0,
expression_proxy.flat_indexed_expressions(2 * 3 - 1).sensitivities().at(
&variable_0));
EXPECT_EQ(
4 * sensitivity_1,
expression_proxy.flat_indexed_expressions(2 * 3 - 1).sensitivities().at(
&variable_1));
EXPECT_EQ(
4 * constant,
expression_proxy.flat_indexed_expressions(2 * 3 - 1).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_export_values_and_names) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto variable_0 =
printemps::model_component::Variable<int, double>::create_instance();
auto variable_1 =
printemps::model_component::Variable<int, double>::create_instance();
auto sensitivity_0 = random_integer();
auto sensitivity_1 = random_integer();
auto constant = random_integer();
expression_proxy[0] =
sensitivity_0 * variable_0 + sensitivity_1 * variable_1 + constant;
expression_proxy[2 * 3 - 1] = expression_proxy[0] * 2;
auto value_0 = random_integer();
auto value_1 = random_integer();
variable_0 = value_0;
variable_1 = value_1;
for (auto&& expression : expression_proxy.flat_indexed_expressions()) {
expression.update();
}
auto expected_value_0 =
sensitivity_0 * value_0 + sensitivity_1 * value_1 + constant;
auto expected_value_1 = expected_value_0 * 2;
EXPECT_EQ(expected_value_0,
expression_proxy.export_values_and_names().values(0, 0));
EXPECT_EQ(expected_value_1,
expression_proxy.export_values_and_names().values(1, 2));
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_to_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(auto expression = expression_proxy.to_expression(),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_sum_arg_void) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", {2, 3});
auto& expression_proxy = model.create_expressions("e", {2, 3});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
expression = expression_proxy.sum();
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression.sensitivities().at(&(variable_proxy[2 * 3 - 1])));
EXPECT_EQ(2 * 3, expression.evaluate());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_sum_arg_indices) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", {2, 3});
auto& expression_proxy = model.create_expressions("e", {2, 3});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
auto expression_0 =
printemps::model_component::Expression<int, double>::create_instance();
auto expression_1 =
printemps::model_component::Expression<int, double>::create_instance();
auto expression_01 =
printemps::model_component::Expression<int, double>::create_instance();
expression_0 =
expression_proxy.sum({printemps::model_component::Range::All, 0});
expression_1 =
expression_proxy.sum({0, printemps::model_component::Range::All});
expression_01 =
expression_proxy.sum({printemps::model_component::Range::All,
printemps::model_component::Range::All});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(1, expression_0.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression_0.sensitivities().at(&(variable_proxy[3])));
EXPECT_EQ(2, expression_0.evaluate());
EXPECT_EQ(1, expression_1.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1, expression_1.sensitivities().at(&(variable_proxy[2])));
EXPECT_EQ(3, expression_1.evaluate());
EXPECT_EQ(1, expression_01.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(1,
expression_01.sensitivities().at(&(variable_proxy[2 * 3 - 1])));
EXPECT_EQ(2 * 3, expression_01.evaluate());
ASSERT_THROW(expression_proxy.sum({printemps::model_component::Range::All}),
std::logic_error);
ASSERT_THROW(
expression_proxy.sum({printemps::model_component::Range::All, 0, 0}),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_dot_arg_vector) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", {2, 3});
auto& expression_proxy = model.create_expressions("e", {2, 3});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
std::vector<double> sensitivities;
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
sensitivities.push_back(random_integer());
}
ASSERT_THROW(expression_proxy.dot(sensitivities), std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_dot_arg_indice_vector) {
printemps::model::Model<int, double> model;
auto& variable_proxy = model.create_variables("x", {2, 3});
auto& expression_proxy = model.create_expressions("e", {2, 3});
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
expression_proxy[i] = variable_proxy[i];
}
std::vector<double> sensitivities_0;
auto sum_0 = 0;
for (auto i = 0; i < 2; i++) {
sensitivities_0.push_back(random_integer());
sum_0 += sensitivities_0.back();
}
std::vector<double> sensitivities_1;
auto sum_1 = 0;
for (auto i = 0; i < 3; i++) {
sensitivities_1.push_back(random_integer());
sum_1 += sensitivities_1.back();
}
std::vector<double> sensitivities_01;
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
sensitivities_01.push_back(random_integer());
}
auto expression_0 =
printemps::model_component::Expression<int, double>::create_instance();
auto expression_1 =
printemps::model_component::Expression<int, double>::create_instance();
expression_0 = expression_proxy.dot(
{printemps::model_component::Range::All, 0}, sensitivities_0);
expression_1 = expression_proxy.dot(
{0, printemps::model_component::Range::All}, sensitivities_1);
for (auto i = 0; i < variable_proxy.number_of_elements(); i++) {
variable_proxy[i] = 1;
}
EXPECT_EQ(sensitivities_0[0],
expression_0.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(sensitivities_0[1],
expression_0.sensitivities().at(&(variable_proxy[3])));
EXPECT_EQ(sum_0, expression_0.evaluate());
EXPECT_EQ(sensitivities_1[0],
expression_1.sensitivities().at(&(variable_proxy[0])));
EXPECT_EQ(sensitivities_1[2],
expression_1.sensitivities().at(&(variable_proxy[2])));
EXPECT_EQ(sum_1, expression_1.evaluate());
ASSERT_THROW(expression_proxy.dot({printemps::model_component::Range::All},
sensitivities_0),
std::logic_error);
ASSERT_THROW(expression_proxy.dot({printemps::model_component::Range::All,
printemps::model_component::Range::All},
sensitivities_01),
std::logic_error);
ASSERT_THROW(
expression_proxy.dot({printemps::model_component::Range::All, 0, 0},
sensitivities_0),
std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_is_enabled) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
expression_proxy.disable();
ASSERT_THROW(expression_proxy.is_enabled(), std::logic_error);
EXPECT_FALSE(expression_proxy[0].is_enabled());
EXPECT_FALSE(expression_proxy[2 * 3 - 1].is_enabled());
expression_proxy.enable();
ASSERT_THROW(expression_proxy.is_enabled(), std::logic_error);
EXPECT_TRUE(expression_proxy[0].is_enabled());
EXPECT_TRUE(expression_proxy[2 * 3 - 1].is_enabled());
expression_proxy.disable();
ASSERT_THROW(expression_proxy.is_enabled(), std::logic_error);
EXPECT_FALSE(expression_proxy[0].is_enabled());
EXPECT_FALSE(expression_proxy[2 * 3 - 1].is_enabled());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_enable) {
/// This method is tested in two_dimensional_is_enabled().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_disable) {
/// This method is tested in two_dimensional_is_enabled().
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_plus) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(auto expression = +expression_proxy, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_minus) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
ASSERT_THROW(auto expression = -expression_proxy, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto value = random_integer();
ASSERT_THROW(expression_proxy = value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
ASSERT_THROW(expression_proxy = variable_proxy, std::logic_error);
/// variable
ASSERT_THROW(expression_proxy = variable_proxy[0], std::logic_error);
/// expression proxy
ASSERT_THROW(expression_proxy = expression_proxy_other, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_equal_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
ASSERT_THROW(expression_proxy = expression, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_plus_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto value = random_integer();
ASSERT_THROW(expression_proxy += value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_plus_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
ASSERT_THROW(expression_proxy += variable_proxy, std::logic_error);
/// variable
ASSERT_THROW(expression_proxy += variable_proxy[0], std::logic_error);
/// expression proxy
ASSERT_THROW(expression_proxy += expression_proxy_other, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_plus_equal_arg_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
ASSERT_THROW(expression_proxy += expression, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_minus_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto value = random_integer();
ASSERT_THROW(expression_proxy -= value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_minus_equal_arg_t_expression_like) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto& variable_proxy = model.create_variable("x");
auto& expression_proxy_other = model.create_expression("y");
expression_proxy_other = variable_proxy;
/// variable proxy
ASSERT_THROW(expression_proxy -= variable_proxy, std::logic_error);
/// variable
ASSERT_THROW(expression_proxy -= variable_proxy[0], std::logic_error);
/// expression proxy
ASSERT_THROW(expression_proxy -= expression_proxy_other, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_minus_equal_arg_expression) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto expression =
printemps::model_component::Expression<int, double>::create_instance();
ASSERT_THROW(expression_proxy -= expression, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_product_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto value = random_integer();
ASSERT_THROW(expression_proxy *= value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_divide_equal_arg_t_value) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3});
auto value = random_integer();
ASSERT_THROW(expression_proxy /= value, std::logic_error);
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_square_bracket) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("x", {2, 3});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy[0] = value_0;
expression_proxy[2 * 3 - 1] = value_1;
EXPECT_EQ(value_0, expression_proxy[0].constant_value());
EXPECT_EQ(value_1, expression_proxy[2 * 3 - 1].constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, two_dimensional_operator_round_bracket) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("x", {2, 3});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy(0, 0) = value_0;
expression_proxy(1, 2) = value_1;
EXPECT_EQ(value_0, expression_proxy(0, 0).constant_value());
EXPECT_EQ(value_1, expression_proxy(1, 2).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
two_dimensional_operator_round_bracket_with_indices) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("x", {2, 3});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy({0, 0}) = value_0;
expression_proxy({1, 2}) = value_1;
EXPECT_EQ(value_0, expression_proxy({0, 0}).constant_value());
EXPECT_EQ(value_1, expression_proxy({1, 2}).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, three_dimensional_create_instance) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3, 4});
/// Check the initial values of the base class members.
EXPECT_EQ(0, expression_proxy.index());
EXPECT_EQ(2, expression_proxy.shape()[0]);
EXPECT_EQ(3, expression_proxy.shape()[1]);
EXPECT_EQ(4, expression_proxy.shape()[2]);
EXPECT_EQ(12, expression_proxy.strides()[0]);
EXPECT_EQ(4, expression_proxy.strides()[1]);
EXPECT_EQ(1, expression_proxy.strides()[2]);
EXPECT_EQ(3, expression_proxy.number_of_dimensions());
EXPECT_EQ(2 * 3 * 4, expression_proxy.number_of_elements());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, three_dimensional_operator_round_bracket) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3, 4});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy(0, 0, 0) = value_0;
expression_proxy(1, 2, 3) = value_1;
EXPECT_EQ(value_0, expression_proxy(0, 0, 0).constant_value());
EXPECT_EQ(value_1, expression_proxy(1, 2, 3).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
three_dimensional_operator_round_bracket_with_indices) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3, 4});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy({0, 0, 0}) = value_0;
expression_proxy({1, 2, 3}) = value_1;
EXPECT_EQ(value_0, expression_proxy({0, 0, 0}).constant_value());
EXPECT_EQ(value_1, expression_proxy({1, 2, 3}).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, four_dimensional_create_instance) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3, 4, 5});
/// Check the initial values of the base class members.
EXPECT_EQ(0, expression_proxy.index());
EXPECT_EQ(2, expression_proxy.shape()[0]);
EXPECT_EQ(3, expression_proxy.shape()[1]);
EXPECT_EQ(4, expression_proxy.shape()[2]);
EXPECT_EQ(5, expression_proxy.shape()[3]);
EXPECT_EQ(60, expression_proxy.strides()[0]);
EXPECT_EQ(20, expression_proxy.strides()[1]);
EXPECT_EQ(5, expression_proxy.strides()[2]);
EXPECT_EQ(1, expression_proxy.strides()[3]);
EXPECT_EQ(4, expression_proxy.number_of_dimensions());
EXPECT_EQ(2 * 3 * 4 * 5, expression_proxy.number_of_elements());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy, four_dimensional_operator_round_bracket) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3, 4, 5});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy(0, 0, 0, 0) = value_0;
expression_proxy(1, 2, 3, 4) = value_1;
EXPECT_EQ(value_0, expression_proxy(0, 0, 0, 0).constant_value());
EXPECT_EQ(value_1, expression_proxy(1, 2, 3, 4).constant_value());
}
/*****************************************************************************/
TEST_F(TestExpressionProxy,
four_dimensional_operator_round_bracket_with_indices) {
printemps::model::Model<int, double> model;
auto& expression_proxy = model.create_expressions("e", {2, 3, 4, 5});
auto value_0 = random_integer();
auto value_1 = random_integer();
expression_proxy({0, 0, 0, 0}) = value_0;
expression_proxy({1, 2, 3, 4}) = value_1;
EXPECT_EQ(value_0, expression_proxy({0, 0, 0, 0}).constant_value());
EXPECT_EQ(value_1, expression_proxy({1, 2, 3, 4}).constant_value());
}
} // namespace
/*****************************************************************************/
// END
/*****************************************************************************/ | 39.687776 | 80 | 0.610583 | snowberryfield |
ed9e82620c1c8b493a14a79082a2aa239a834c60 | 1,349 | cc | C++ | cc/modules/features2d/FeatureDetector.cc | bookjan/opencv4nodejs | d0a457ce40783cadaea79eb82ffef01d57ed97a3 | [
"MIT"
] | 2 | 2018-12-21T01:37:32.000Z | 2019-05-29T06:27:03.000Z | cc/modules/features2d/FeatureDetector.cc | sanksys/opencv4nodejs | 012b849a429aa199fb427321fdb2631c420efeb7 | [
"MIT"
] | null | null | null | cc/modules/features2d/FeatureDetector.cc | sanksys/opencv4nodejs | 012b849a429aa199fb427321fdb2631c420efeb7 | [
"MIT"
] | 1 | 2020-02-18T06:44:04.000Z | 2020-02-18T06:44:04.000Z | #include "FeatureDetector.h"
#include "FeatureDetectorBindings.h"
void FeatureDetector::Init(v8::Local<v8::FunctionTemplate> ctor) {
Nan::SetPrototypeMethod(ctor, "detect", FeatureDetector::Detect);
Nan::SetPrototypeMethod(ctor, "compute", FeatureDetector::Compute);
Nan::SetPrototypeMethod(ctor, "detectAsync", FeatureDetector::DetectAsync);
Nan::SetPrototypeMethod(ctor, "computeAsync", FeatureDetector::ComputeAsync);
};
NAN_METHOD(FeatureDetector::Detect) {
FF::SyncBinding(
std::make_shared<FeatureDetectorBindings::DetectWorker>(FF_UNWRAP(info.This(), FeatureDetector)->getDetector()),
"FeatureDetector::Detect",
info
);
}
NAN_METHOD(FeatureDetector::DetectAsync) {
FF::AsyncBinding(
std::make_shared<FeatureDetectorBindings::DetectWorker>(FF_UNWRAP(info.This(), FeatureDetector)->getDetector()),
"FeatureDetector::DetectAsync",
info
);
}
NAN_METHOD(FeatureDetector::Compute) {
FF::SyncBinding(
std::make_shared<FeatureDetectorBindings::ComputeWorker>(FF_UNWRAP(info.This(), FeatureDetector)->getDetector()),
"FeatureDetector::Compute",
info
);
}
NAN_METHOD(FeatureDetector::ComputeAsync) {
FF::AsyncBinding(
std::make_shared<FeatureDetectorBindings::ComputeWorker>(FF_UNWRAP(info.This(), FeatureDetector)->getDetector()),
"FeatureDetector::ComputeAsync",
info
);
}
| 32.119048 | 117 | 0.748703 | bookjan |
eda0abecefcae2c687280857f9eba52a6a3081c4 | 3,271 | hpp | C++ | src/boost/serialization/array_wrapper.hpp | 107-systems/107-Arduino-BoostUnits | fc3677ae79c1e75c99b3aa7813eb6ec83124b944 | [
"MIT"
] | null | null | null | src/boost/serialization/array_wrapper.hpp | 107-systems/107-Arduino-BoostUnits | fc3677ae79c1e75c99b3aa7813eb6ec83124b944 | [
"MIT"
] | 1 | 2021-08-30T18:02:49.000Z | 2021-08-30T18:02:49.000Z | src/boost/serialization/array_wrapper.hpp | 107-systems/107-Arduino-BoostUnits | fc3677ae79c1e75c99b3aa7813eb6ec83124b944 | [
"MIT"
] | null | null | null | #ifndef BOOST_SERIALIZATION_ARRAY_WRAPPER_HPP
#define BOOST_SERIALIZATION_ARRAY_WRAPPER_HPP
// (C) Copyright 2005 Matthias Troyer and Dave Abrahams
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "boost/config.hpp" // msvc 6.0 needs this for warning suppression
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::size_t;
} // namespace std
#endif
#include "boost/serialization/nvp.hpp"
#include "boost/serialization/split_member.hpp"
#include "boost/serialization/wrapper.hpp"
#include "boost/serialization/collection_size_type.hpp"
#include "boost/serialization/array_optimization.hpp"
#include "boost/mpl/always.hpp"
#include "boost/mpl/apply.hpp"
#include "boost/mpl/bool_fwd.hpp"
#include "boost/type_traits/remove_const.hpp"
namespace boost { namespace serialization {
template<class T>
class array_wrapper :
public wrapper_traits<const array_wrapper< T > >
{
private:
array_wrapper & operator=(const array_wrapper & rhs);
// note: I would like to make the copy constructor private but this breaks
// make_array. So I make make_array a friend
template<class Tx, class S>
friend const boost::serialization::array_wrapper<Tx> make_array(Tx * t, S s);
public:
array_wrapper(const array_wrapper & rhs) :
m_t(rhs.m_t),
m_element_count(rhs.m_element_count)
{}
public:
array_wrapper(T * t, std::size_t s) :
m_t(t),
m_element_count(s)
{}
// default implementation
template<class Archive>
void serialize_optimized(Archive &ar, const unsigned int, mpl::false_ ) const
{
// default implemention does the loop
std::size_t c = count();
T * t = address();
while(0 < c--)
ar & boost::serialization::make_nvp("item", *t++);
}
// optimized implementation
template<class Archive>
void serialize_optimized(Archive &ar, const unsigned int version, mpl::true_ )
{
boost::serialization::split_member(ar, *this, version);
}
// default implementation
template<class Archive>
void save(Archive &ar, const unsigned int version) const
{
ar.save_array(*this,version);
}
// default implementation
template<class Archive>
void load(Archive &ar, const unsigned int version)
{
ar.load_array(*this,version);
}
// default implementation
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
typedef typename
boost::serialization::use_array_optimization<Archive>::template apply<
typename remove_const< T >::type
>::type use_optimized;
serialize_optimized(ar,version,use_optimized());
}
T * address() const
{
return m_t;
}
std::size_t count() const
{
return m_element_count;
}
private:
T * const m_t;
const std::size_t m_element_count;
};
template<class T, class S>
inline
const array_wrapper< T > make_array(T* t, S s){
const array_wrapper< T > a(t, s);
return a;
}
} } // end namespace boost::serialization
#endif //BOOST_SERIALIZATION_ARRAY_WRAPPER_HPP
| 27.258333 | 82 | 0.685723 | 107-systems |
eda2cbf70f9697f3db41a0c1fa7165ba81419644 | 3,677 | cpp | C++ | src/Dist_Thresh.cpp | sd12832/zlab_drone | d046a0c6986b0af2e40db9bb8a1fbecd99050364 | [
"MIT"
] | 1 | 2019-06-29T02:50:54.000Z | 2019-06-29T02:50:54.000Z | src/Dist_Thresh.cpp | sd12832/zlab_drone | d046a0c6986b0af2e40db9bb8a1fbecd99050364 | [
"MIT"
] | null | null | null | src/Dist_Thresh.cpp | sd12832/zlab_drone | d046a0c6986b0af2e40db9bb8a1fbecd99050364 | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <zlab_drone/Circles.h>
#include <zlab_drone/Circle.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imageproc/imageproc.hpp>
#include <opencv2/highgui/highgui.hpp>
// Deprecated Function
/*
bool smaller_than (int i, int j) {
return ()
}
*/
// Global Variables
double stack [3][3];
cv::Mat main_image;
bool new_msg1, new_msg2, new_msg;
static const std::string OPENCV_WINDOW = "Image Window";
void image_callback (const sensor_msgs::ImageConstPtr& msg) {
// Image Processing
cv_bridge::CvImagePtr cv_ptr
try {
cv_ptr = cv_bridge::toCvCopy(msg,
sensor_msgs::image_encodings::BGR8);
} catch (cv::bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
main_image = cv_ptr->image;
}
// Make sure the different circles are organized properly
void organizer_callback(const
zlab_drone::Circles::ConstPtr& msg) {
// The Variables
std::vector<std::vector<float>> circles;
int center_x;
int center_y;
int radius;
// Initializing Stack to 0
for (int dim1 = 0; dim1 < 3; dim1++) {
for (int dim2 = 0; dim2 < 3; dim2++) {
stack[dim1][dim2] = 0;
}
}
// Gathering Data from the messages
for (std::vector<zlab_drone::Circles>::const_iterator gp =
msg->circles.begin(); gp!= msg->circles.end(), ++gp) {
for (std::vector<float>::const_iterator dp =
gp->circle.begin(); dp != gp->circle.end(); ++dp) {
circles[gp][dp] = gp->circle(dp);
}
}
double euclidian_distance [circles.size()][3];
for (int i = 0, i < circles.size(); ++i) {
center_x = circles[i][0];
center_y = circles[i][1];
//Calculate the distance from the center of the video
euclidian_distance[i][0] = ();
euclidian_distance[i][1] = center_x;
euclidian_distance[i][2] = center_y;
}
std::sort(euclidian_distance.begin(), euclidian_distance.end());
stack[1] = euclidian_distance[1];
stack[2] = euclidian_distance[2];
stack[3] = euclidian_distance[3];
circles_out1.publish(stack[1]);
circles_out2.publish(stack[2]);
circles_out3.publish(stack[3]);
}
int main (int argc, char** argv) {
ros::init(argc, argv, "distance_thresholder");
// Aim to organize the stack of the different circles that have
//been detected
ros::Nodehandle node;
ros::Subscriber circles_in;
ros::Publisher circles_out1;
ros::Publisher circles_out2;
ros::Publisher circles_out3;
// Subscribe to the Bottom Image of the Drone for Debugging
// Comment this out, if not needed.
image_sub = node.subscribe("/ardrone/bottom/image_raw", 1,
image_callback);
// Subscribe to the Circles topic
circles_in = node.subscribe("/circles", 1, &Thresholder::organizer_callback);
// Publish the organized circles topic
circles_out1 = node.advertise<zlab_drone::Circle>("/current", 1);
circles_out2 = node.advertise<zlab_drone::Circle>("/closest", 1);
circles_out3 = node.advertise<zlab_drone::Circle>("/furthest", 1);
if (new_msg1 == true && new_msg2 == true) {
// Debugging Flags
new_msg == true;
}
while ((ros::ok()) && (new_msg == true)) {
// Debugging Section ---------------------------------
for (int dim1 = 0; dim1 < 3; dim1++) {
cv::Point center(cvRound(stack[dim1][0]),
cvRound(stack[dim1][1]));
int radius = stack[dim1][2];
cv::circle(main_image, center, radius+1,
cv::Scalar(0,0,255));
}
cv::NamedWindow(OPENCV_WINDOW);
cv::imshow(OPENCV_WINDOW, main_image);
cv::waitkey(3);
}
ros::spin();
return 0;
}
| 25.713287 | 82 | 0.651074 | sd12832 |
eda6f106202a90b6367236633b43a0ad098a4b22 | 15,447 | cpp | C++ | XDKSamples/IntroGraphics/SimpleTexture12/SimpleTexture12.cpp | dephora/Xbox-ATG-Samples | 31e482c9e23def36073542ce614a0f0b145d7112 | [
"MIT"
] | null | null | null | XDKSamples/IntroGraphics/SimpleTexture12/SimpleTexture12.cpp | dephora/Xbox-ATG-Samples | 31e482c9e23def36073542ce614a0f0b145d7112 | [
"MIT"
] | null | null | null | XDKSamples/IntroGraphics/SimpleTexture12/SimpleTexture12.cpp | dephora/Xbox-ATG-Samples | 31e482c9e23def36073542ce614a0f0b145d7112 | [
"MIT"
] | 1 | 2020-07-30T11:13:23.000Z | 2020-07-30T11:13:23.000Z | //--------------------------------------------------------------------------------------
// SimpleTexture12.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SimpleTexture12.h"
#include "ATGColors.h"
#include "ReadData.h"
extern void ExitSample() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
struct Vertex
{
XMFLOAT4 position;
XMFLOAT2 texcoord;
};
std::vector<uint8_t> LoadBGRAImage(const wchar_t* filename, uint32_t& width, uint32_t& height)
{
ComPtr<IWICImagingFactory> wicFactory;
DX::ThrowIfFailed(CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wicFactory)));
ComPtr<IWICBitmapDecoder> decoder;
DX::ThrowIfFailed(wicFactory->CreateDecoderFromFilename(filename, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()));
ComPtr<IWICBitmapFrameDecode> frame;
DX::ThrowIfFailed(decoder->GetFrame(0, frame.GetAddressOf()));
DX::ThrowIfFailed(frame->GetSize(&width, &height));
WICPixelFormatGUID pixelFormat;
DX::ThrowIfFailed(frame->GetPixelFormat(&pixelFormat));
uint32_t rowPitch = width * sizeof(uint32_t);
uint32_t imageSize = rowPitch * height;
std::vector<uint8_t> image;
image.resize(size_t(imageSize));
if (memcmp(&pixelFormat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID)) == 0)
{
DX::ThrowIfFailed(frame->CopyPixels(nullptr, rowPitch, imageSize, reinterpret_cast<BYTE*>(image.data())));
}
else
{
ComPtr<IWICFormatConverter> formatConverter;
DX::ThrowIfFailed(wicFactory->CreateFormatConverter(formatConverter.GetAddressOf()));
BOOL canConvert = FALSE;
DX::ThrowIfFailed(formatConverter->CanConvert(pixelFormat, GUID_WICPixelFormat32bppBGRA, &canConvert));
if (!canConvert)
{
throw std::exception("CanConvert");
}
DX::ThrowIfFailed(formatConverter->Initialize(frame.Get(), GUID_WICPixelFormat32bppBGRA,
WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut));
DX::ThrowIfFailed(formatConverter->CopyPixels(nullptr, rowPitch, imageSize, reinterpret_cast<BYTE*>(image.data())));
}
return image;
}
}
Sample::Sample() :
m_frame(0)
{
// Use gamma-correct rendering.
m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_D32_FLOAT, 2,
DX::DeviceResources::c_Enable4K_UHD);
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(IUnknown* window)
{
m_gamePad = std::make_unique<GamePad>();
m_deviceResources->SetWindow(window);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %I64u", m_frame);
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
PIXEndEvent();
m_frame++;
}
// Updates the world.
void Sample::Update(DX::StepTimer const&)
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
auto pad = m_gamePad->GetState(0);
if (pad.IsConnected())
{
if (pad.IsViewPressed())
{
ExitSample();
}
}
PIXEndEvent();
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Prepare the command list to render a new frame.
m_deviceResources->Prepare();
Clear();
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render");
commandList->SetGraphicsRootSignature(m_rootSignature.Get());
commandList->SetPipelineState(m_pipelineState.Get());
auto heap = m_srvHeap.Get();
commandList->SetDescriptorHeaps(1, &heap);
commandList->SetGraphicsRootDescriptorTable(0, m_srvHeap->GetGPUDescriptorHandleForHeapStart());
// Set necessary state.
commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
commandList->IASetVertexBuffers(0, 1, &m_vertexBufferView);
commandList->IASetIndexBuffer(&m_indexBufferView);
// Draw quad.
commandList->DrawIndexedInstanced(6, 1, 0, 0, 0);
PIXEndEvent(commandList);
// Show the new frame.
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue());
PIXEndEvent();
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto dsvDescriptor = m_deviceResources->GetDepthStencilView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor);
// Use linear clear color for gamma-correct rendering.
commandList->ClearRenderTargetView(rtvDescriptor, ATG::ColorsLinear::Background, 0, nullptr);
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
PIXEndEvent(commandList);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnSuspending()
{
auto queue = m_deviceResources->GetCommandQueue();
queue->SuspendX(0);
}
void Sample::OnResuming()
{
auto queue = m_deviceResources->GetCommandQueue();
queue->ResumeX();
m_timer.ResetElapsedTime();
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
m_graphicsMemory = std::make_unique<GraphicsMemory>(device);
// Create descriptor heaps.
{
// Describe and create a shader resource view (SRV) heap for the texture.
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = 1;
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
DX::ThrowIfFailed(
device->CreateDescriptorHeap(&srvHeapDesc, IID_GRAPHICS_PPV_ARGS(m_srvHeap.ReleaseAndGetAddressOf())));
}
// Create root signature.
auto vertexShaderBlob = DX::ReadData(L"VertexShader.cso");
// Xbox One best practice is to use HLSL-based root signatures to support shader precompilation.
DX::ThrowIfFailed(
device->CreateRootSignature(0, vertexShaderBlob.data(), vertexShaderBlob.size(),
IID_GRAPHICS_PPV_ARGS(m_rootSignature.ReleaseAndGetAddressOf())));
// Create the pipeline state, which includes loading shaders.
auto pixelShaderBlob = DX::ReadData(L"PixelShader.cso");
static const D3D12_INPUT_ELEMENT_DESC s_inputElementDesc[2] =
{
{ "SV_Position", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
// Describe and create the graphics pipeline state object (PSO).
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.InputLayout = { s_inputElementDesc, _countof(s_inputElementDesc) };
psoDesc.pRootSignature = m_rootSignature.Get();
psoDesc.VS = { vertexShaderBlob.data(), vertexShaderBlob.size() };
psoDesc.PS = { pixelShaderBlob.data(), pixelShaderBlob.size() };
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState.DepthEnable = FALSE;
psoDesc.DepthStencilState.StencilEnable = FALSE;
psoDesc.DSVFormat = m_deviceResources->GetDepthBufferFormat();
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = m_deviceResources->GetBackBufferFormat();
psoDesc.SampleDesc.Count = 1;
DX::ThrowIfFailed(
device->CreateGraphicsPipelineState(&psoDesc,
IID_GRAPHICS_PPV_ARGS(m_pipelineState.ReleaseAndGetAddressOf())));
CD3DX12_HEAP_PROPERTIES heapUpload(D3D12_HEAP_TYPE_UPLOAD);
// Create vertex buffer.
{
static const Vertex s_vertexData[4] =
{
{ { -0.5f, -0.5f, 0.5f, 1.0f },{ 0.f, 1.f } },
{ { 0.5f, -0.5f, 0.5f, 1.0f },{ 1.f, 1.f } },
{ { 0.5f, 0.5f, 0.5f, 1.0f },{ 1.f, 0.f } },
{ { -0.5f, 0.5f, 0.5f, 1.0f },{ 0.f, 0.f } },
};
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(s_vertexData));
DX::ThrowIfFailed(
device->CreateCommittedResource(&heapUpload,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_GRAPHICS_PPV_ARGS(m_vertexBuffer.ReleaseAndGetAddressOf())));
// Copy the quad data to the vertex buffer.
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
DX::ThrowIfFailed(
m_vertexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin)));
memcpy(pVertexDataBegin, s_vertexData, sizeof(s_vertexData));
m_vertexBuffer->Unmap(0, nullptr);
// Initialize the vertex buffer view.
m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();
m_vertexBufferView.StrideInBytes = sizeof(Vertex);
m_vertexBufferView.SizeInBytes = sizeof(s_vertexData);
}
// Create index buffer.
{
static const uint16_t s_indexData[6] =
{
3,1,0,
2,1,3,
};
// See note above
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(s_indexData));
DX::ThrowIfFailed(
device->CreateCommittedResource(&heapUpload,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_GRAPHICS_PPV_ARGS(m_indexBuffer.ReleaseAndGetAddressOf())));
// Copy the data to the index buffer.
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
DX::ThrowIfFailed(
m_indexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin)));
memcpy(pVertexDataBegin, s_indexData, sizeof(s_indexData));
m_indexBuffer->Unmap(0, nullptr);
// Initialize the index buffer view.
m_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress();
m_indexBufferView.Format = DXGI_FORMAT_R16_UINT;
m_indexBufferView.SizeInBytes = sizeof(s_indexData);
}
// Create texture.
auto commandList = m_deviceResources->GetCommandList();
commandList->Reset(m_deviceResources->GetCommandAllocator(), nullptr);
ComPtr<ID3D12Resource> textureUploadHeap;
{
D3D12_RESOURCE_DESC txtDesc = {};
txtDesc.MipLevels = txtDesc.DepthOrArraySize = 1;
txtDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; // sunset.jpg is in sRGB colorspace
txtDesc.SampleDesc.Count = 1;
txtDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
UINT width, height;
auto image = LoadBGRAImage(L"sunset.jpg", width, height);
txtDesc.Width = width;
txtDesc.Height = height;
CD3DX12_HEAP_PROPERTIES heapDefault(D3D12_HEAP_TYPE_DEFAULT);
DX::ThrowIfFailed(
device->CreateCommittedResource(
&heapDefault,
D3D12_HEAP_FLAG_NONE,
&txtDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_GRAPHICS_PPV_ARGS(m_texture.ReleaseAndGetAddressOf())));
const UINT64 uploadBufferSize = GetRequiredIntermediateSize(m_texture.Get(), 0, 1);
// Create the GPU upload buffer.
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize);
DX::ThrowIfFailed(
device->CreateCommittedResource(
&heapUpload,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_GRAPHICS_PPV_ARGS(textureUploadHeap.GetAddressOf())));
D3D12_SUBRESOURCE_DATA textureData = {};
textureData.pData = image.data();
textureData.RowPitch = static_cast<LONG_PTR>(txtDesc.Width * sizeof(uint32_t));
textureData.SlicePitch = image.size();
UpdateSubresources(commandList, m_texture.Get(), textureUploadHeap.Get(), 0, 0, 1, &textureData);
auto barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
commandList->ResourceBarrier(1, &barrier);
// Describe and create a SRV for the texture.
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Format = txtDesc.Format;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
device->CreateShaderResourceView(m_texture.Get(), &srvDesc, m_srvHeap->GetCPUDescriptorHandleForHeapStart());
}
DX::ThrowIfFailed(commandList->Close());
m_deviceResources->GetCommandQueue()->ExecuteCommandLists(1, CommandListCast(&commandList));
// Wait until assets have been uploaded to the GPU.
m_deviceResources->WaitForGpu();
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
}
#pragma endregion | 36.778571 | 155 | 0.657927 | dephora |
eda9b871b97420122185215bdbdcbe44fe4dc689 | 25,328 | hpp | C++ | Sisyphe/cppbase/src/interpreter/debugTypeInfoInterpreter.hpp | tedi21/SisypheReview | f7c05bad1ccc036f45870535149d9685e1120c2c | [
"Unlicense"
] | null | null | null | Sisyphe/cppbase/src/interpreter/debugTypeInfoInterpreter.hpp | tedi21/SisypheReview | f7c05bad1ccc036f45870535149d9685e1120c2c | [
"Unlicense"
] | null | null | null | Sisyphe/cppbase/src/interpreter/debugTypeInfoInterpreter.hpp | tedi21/SisypheReview | f7c05bad1ccc036f45870535149d9685e1120c2c | [
"Unlicense"
] | null | null | null | /*
* debugTypeInfoInterpreter.hpp
*
*
* @date 14-07-2020
* @author Teddy DIDE
* @version 1.00
* cppBase generated by gensources.
*/
#ifndef _DEBUGTYPEINFO_INTERPRETER_HPP_
#define _DEBUGTYPEINFO_INTERPRETER_HPP_
#include "config.hpp"
#include "Macros.hpp"
#include "Base.hpp"
#include "Array.hpp"
#include "cppBaseExport.hpp"
#include "cppBaseData.h"
#define A(str) encode<EncodingT,ansi>(str)
#define C(str) encode<ansi,EncodingT>(str)
NAMESPACE_BEGIN(interp)
using namespace log4cpp;
using namespace fctr;
using namespace enc;
using namespace entity;
using namespace boost;
template <class EncodingT>
class DebugTypeInfoInterpreter;
template <class EncodingT>
class DebugFunctionInfoInterpreter;
template <class EncodingT>
class DebugVariableInfoInterpreter;
template <class EncodingT>
class DebugTypeInfoInterpreter;
template <class EncodingT>
class DebugTypeInfoInterpreter
: public Base<EncodingT>
{
private:
boost::shared_ptr< _DebugTypeInfo<EncodingT> > m_value;
public:
DebugTypeInfoInterpreter();
DebugTypeInfoInterpreter(boost::shared_ptr< _DebugTypeInfo<EncodingT> > const& value);
FACTORY_PROTOTYPE22(DebugTypeInfoInterpreter,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >,
In< boost::shared_ptr< Base<EncodingT> > >)
DebugTypeInfoInterpreter(boost::shared_ptr< Base<EncodingT> > const& isChar,
boost::shared_ptr< Base<EncodingT> > const& isString,
boost::shared_ptr< Base<EncodingT> > const& isBool,
boost::shared_ptr< Base<EncodingT> > const& isFloat,
boost::shared_ptr< Base<EncodingT> > const& isSigned,
boost::shared_ptr< Base<EncodingT> > const& isWide,
boost::shared_ptr< Base<EncodingT> > const& isPointer,
boost::shared_ptr< Base<EncodingT> > const& isReference,
boost::shared_ptr< Base<EncodingT> > const& isArray,
boost::shared_ptr< Base<EncodingT> > const& isConst,
boost::shared_ptr< Base<EncodingT> > const& isVolatile,
boost::shared_ptr< Base<EncodingT> > const& isStruct,
boost::shared_ptr< Base<EncodingT> > const& isClass,
boost::shared_ptr< Base<EncodingT> > const& isUnion,
boost::shared_ptr< Base<EncodingT> > const& isInterface,
boost::shared_ptr< Base<EncodingT> > const& isEnum,
boost::shared_ptr< Base<EncodingT> > const& isFunction,
boost::shared_ptr< Base<EncodingT> > const& baseName,
boost::shared_ptr< Base<EncodingT> > const& name,
boost::shared_ptr< Base<EncodingT> > const& sizeOf,
boost::shared_ptr< Base<EncodingT> > const& typeId,
boost::shared_ptr< Base<EncodingT> > const& arrayDim);
boost::shared_ptr< _DebugTypeInfo<EncodingT> > value() const;
void value(boost::shared_ptr< _DebugTypeInfo<EncodingT> > const& value);
virtual typename EncodingT::string_t toString() const;
virtual boost::shared_ptr< Base<EncodingT> > clone() const;
virtual typename EncodingT::string_t getClassName() const;
virtual boost::shared_ptr< Base<EncodingT> > invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params);
boost::shared_ptr< Base<EncodingT> > getIdentifier() const;
boost::shared_ptr< Base<EncodingT> > getIsChar() const;
boost::shared_ptr< Base<EncodingT> > getIsString() const;
boost::shared_ptr< Base<EncodingT> > getIsBool() const;
boost::shared_ptr< Base<EncodingT> > getIsFloat() const;
boost::shared_ptr< Base<EncodingT> > getIsSigned() const;
boost::shared_ptr< Base<EncodingT> > getIsWide() const;
boost::shared_ptr< Base<EncodingT> > getIsPointer() const;
boost::shared_ptr< Base<EncodingT> > getIsReference() const;
boost::shared_ptr< Base<EncodingT> > getIsArray() const;
boost::shared_ptr< Base<EncodingT> > getIsConst() const;
boost::shared_ptr< Base<EncodingT> > getIsVolatile() const;
boost::shared_ptr< Base<EncodingT> > getIsStruct() const;
boost::shared_ptr< Base<EncodingT> > getIsClass() const;
boost::shared_ptr< Base<EncodingT> > getIsUnion() const;
boost::shared_ptr< Base<EncodingT> > getIsInterface() const;
boost::shared_ptr< Base<EncodingT> > getIsEnum() const;
boost::shared_ptr< Base<EncodingT> > getIsFunction() const;
boost::shared_ptr< Base<EncodingT> > getBaseName() const;
boost::shared_ptr< Base<EncodingT> > getName() const;
boost::shared_ptr< Base<EncodingT> > getSizeOf() const;
boost::shared_ptr< Base<EncodingT> > getTypeId() const;
boost::shared_ptr< Base<EncodingT> > getArrayDim() const;
boost::shared_ptr< Base<EncodingT> > getPrimitiveType();
FACTORY_PROTOTYPE1(setPrimitiveType, In< boost::shared_ptr< Base<EncodingT> > >)
void setPrimitiveType(boost::shared_ptr< Base<EncodingT> > const& primitiveType);
FACTORY_PROTOTYPE1(setIsChar, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsChar(boost::shared_ptr< Base<EncodingT> > const& isChar);
FACTORY_PROTOTYPE1(setIsString, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsString(boost::shared_ptr< Base<EncodingT> > const& isString);
FACTORY_PROTOTYPE1(setIsBool, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsBool(boost::shared_ptr< Base<EncodingT> > const& isBool);
FACTORY_PROTOTYPE1(setIsFloat, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsFloat(boost::shared_ptr< Base<EncodingT> > const& isFloat);
FACTORY_PROTOTYPE1(setIsSigned, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsSigned(boost::shared_ptr< Base<EncodingT> > const& isSigned);
FACTORY_PROTOTYPE1(setIsWide, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsWide(boost::shared_ptr< Base<EncodingT> > const& isWide);
FACTORY_PROTOTYPE1(setIsPointer, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsPointer(boost::shared_ptr< Base<EncodingT> > const& isPointer);
FACTORY_PROTOTYPE1(setIsReference, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsReference(boost::shared_ptr< Base<EncodingT> > const& isReference);
FACTORY_PROTOTYPE1(setIsArray, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsArray(boost::shared_ptr< Base<EncodingT> > const& isArray);
FACTORY_PROTOTYPE1(setIsConst, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsConst(boost::shared_ptr< Base<EncodingT> > const& isConst);
FACTORY_PROTOTYPE1(setIsVolatile, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsVolatile(boost::shared_ptr< Base<EncodingT> > const& isVolatile);
FACTORY_PROTOTYPE1(setIsStruct, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsStruct(boost::shared_ptr< Base<EncodingT> > const& isStruct);
FACTORY_PROTOTYPE1(setIsClass, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsClass(boost::shared_ptr< Base<EncodingT> > const& isClass);
FACTORY_PROTOTYPE1(setIsUnion, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsUnion(boost::shared_ptr< Base<EncodingT> > const& isUnion);
FACTORY_PROTOTYPE1(setIsInterface, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsInterface(boost::shared_ptr< Base<EncodingT> > const& isInterface);
FACTORY_PROTOTYPE1(setIsEnum, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsEnum(boost::shared_ptr< Base<EncodingT> > const& isEnum);
FACTORY_PROTOTYPE1(setIsFunction, In< boost::shared_ptr< Base<EncodingT> > >)
void setIsFunction(boost::shared_ptr< Base<EncodingT> > const& isFunction);
FACTORY_PROTOTYPE1(setBaseName, In< boost::shared_ptr< Base<EncodingT> > >)
void setBaseName(boost::shared_ptr< Base<EncodingT> > const& baseName);
FACTORY_PROTOTYPE1(setName, In< boost::shared_ptr< Base<EncodingT> > >)
void setName(boost::shared_ptr< Base<EncodingT> > const& name);
FACTORY_PROTOTYPE1(setSizeOf, In< boost::shared_ptr< Base<EncodingT> > >)
void setSizeOf(boost::shared_ptr< Base<EncodingT> > const& sizeOf);
FACTORY_PROTOTYPE1(setTypeId, In< boost::shared_ptr< Base<EncodingT> > >)
void setTypeId(boost::shared_ptr< Base<EncodingT> > const& typeId);
FACTORY_PROTOTYPE1(setArrayDim, In< boost::shared_ptr< Base<EncodingT> > >)
void setArrayDim(boost::shared_ptr< Base<EncodingT> > const& arrayDim);
boost::shared_ptr< Base<EncodingT> > hasPrimitiveType() const;
void removePrimitiveType();
FACTORY_PROTOTYPE1(removeRichType, In< boost::shared_ptr< Base<EncodingT> > >)
void removeRichType(boost::shared_ptr< Base<EncodingT> > const& n);
FACTORY_PROTOTYPE1(removeDebugFunctionInfo, In< boost::shared_ptr< Base<EncodingT> > >)
void removeDebugFunctionInfo(boost::shared_ptr< Base<EncodingT> > const& n);
FACTORY_PROTOTYPE1(removeDebugVariableInfo, In< boost::shared_ptr< Base<EncodingT> > >)
void removeDebugVariableInfo(boost::shared_ptr< Base<EncodingT> > const& n);
FACTORY_PROTOTYPE2(insertRichType, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >)
void insertRichType(boost::shared_ptr< Base<EncodingT> > const& n, boost::shared_ptr< Base<EncodingT> > const& richType);
FACTORY_PROTOTYPE2(insertDebugFunctionInfo, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >)
void insertDebugFunctionInfo(boost::shared_ptr< Base<EncodingT> > const& n, boost::shared_ptr< Base<EncodingT> > const& debugFunctionInfo);
FACTORY_PROTOTYPE2(insertDebugVariableInfo, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >)
void insertDebugVariableInfo(boost::shared_ptr< Base<EncodingT> > const& n, boost::shared_ptr< Base<EncodingT> > const& debugVariableInfo);
FACTORY_PROTOTYPE1(getRichType, In< boost::shared_ptr< Base<EncodingT> > >)
boost::shared_ptr< Base<EncodingT> > getRichType(boost::shared_ptr< Base<EncodingT> > const& n);
FACTORY_PROTOTYPE1(getDebugFunctionInfo, In< boost::shared_ptr< Base<EncodingT> > >)
boost::shared_ptr< Base<EncodingT> > getDebugFunctionInfo(boost::shared_ptr< Base<EncodingT> > const& n);
FACTORY_PROTOTYPE1(getDebugVariableInfo, In< boost::shared_ptr< Base<EncodingT> > >)
boost::shared_ptr< Base<EncodingT> > getDebugVariableInfo(boost::shared_ptr< Base<EncodingT> > const& n);
void clearRichTypes();
void clearDebugFunctionInfos();
void clearDebugVariableInfos();
boost::shared_ptr< Base<EncodingT> > hasRichTypes() const;
boost::shared_ptr< Base<EncodingT> > hasDebugFunctionInfos() const;
boost::shared_ptr< Base<EncodingT> > hasDebugVariableInfos() const;
boost::shared_ptr< Base<EncodingT> > richTypesCount() const;
boost::shared_ptr< Base<EncodingT> > debugFunctionInfosCount() const;
boost::shared_ptr< Base<EncodingT> > debugVariableInfosCount() const;
FACTORY_BEGIN_REGISTER
CLASS_KEY_REGISTER ( DebugTypeInfoInterpreter, UCS("DebugTypeInfo") );
CLASS_KEY_REGISTER22( DebugTypeInfoInterpreter, UCS("DebugTypeInfo") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setPrimitiveType, no_const_t, UCS("DebugTypeInfo::PrimitiveType") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getPrimitiveType, no_const_t, UCS("DebugTypeInfo::PrimitiveType") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, hasPrimitiveType, const_t, UCS("DebugTypeInfo::HasPrimitiveType") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, void, removePrimitiveType, no_const_t, UCS("DebugTypeInfo::removePrimitiveType") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIdentifier, const_t, UCS("DebugTypeInfo::Identifier") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsChar, const_t, UCS("DebugTypeInfo::IsChar") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsChar, no_const_t, UCS("DebugTypeInfo::IsChar") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsString, const_t, UCS("DebugTypeInfo::IsString") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsString, no_const_t, UCS("DebugTypeInfo::IsString") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsBool, const_t, UCS("DebugTypeInfo::IsBool") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsBool, no_const_t, UCS("DebugTypeInfo::IsBool") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsFloat, const_t, UCS("DebugTypeInfo::IsFloat") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsFloat, no_const_t, UCS("DebugTypeInfo::IsFloat") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsSigned, const_t, UCS("DebugTypeInfo::IsSigned") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsSigned, no_const_t, UCS("DebugTypeInfo::IsSigned") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsWide, const_t, UCS("DebugTypeInfo::IsWide") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsWide, no_const_t, UCS("DebugTypeInfo::IsWide") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsPointer, const_t, UCS("DebugTypeInfo::IsPointer") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsPointer, no_const_t, UCS("DebugTypeInfo::IsPointer") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsReference, const_t, UCS("DebugTypeInfo::IsReference") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsReference, no_const_t, UCS("DebugTypeInfo::IsReference") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsArray, const_t, UCS("DebugTypeInfo::IsArray") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsArray, no_const_t, UCS("DebugTypeInfo::IsArray") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsConst, const_t, UCS("DebugTypeInfo::IsConst") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsConst, no_const_t, UCS("DebugTypeInfo::IsConst") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsVolatile, const_t, UCS("DebugTypeInfo::IsVolatile") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsVolatile, no_const_t, UCS("DebugTypeInfo::IsVolatile") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsStruct, const_t, UCS("DebugTypeInfo::IsStruct") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsStruct, no_const_t, UCS("DebugTypeInfo::IsStruct") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsClass, const_t, UCS("DebugTypeInfo::IsClass") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsClass, no_const_t, UCS("DebugTypeInfo::IsClass") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsUnion, const_t, UCS("DebugTypeInfo::IsUnion") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsUnion, no_const_t, UCS("DebugTypeInfo::IsUnion") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsInterface, const_t, UCS("DebugTypeInfo::IsInterface") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsInterface, no_const_t, UCS("DebugTypeInfo::IsInterface") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsEnum, const_t, UCS("DebugTypeInfo::IsEnum") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsEnum, no_const_t, UCS("DebugTypeInfo::IsEnum") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getIsFunction, const_t, UCS("DebugTypeInfo::IsFunction") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setIsFunction, no_const_t, UCS("DebugTypeInfo::IsFunction") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getBaseName, const_t, UCS("DebugTypeInfo::BaseName") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setBaseName, no_const_t, UCS("DebugTypeInfo::BaseName") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getName, const_t, UCS("DebugTypeInfo::Name") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setName, no_const_t, UCS("DebugTypeInfo::Name") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getSizeOf, const_t, UCS("DebugTypeInfo::SizeOf") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setSizeOf, no_const_t, UCS("DebugTypeInfo::SizeOf") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getTypeId, const_t, UCS("DebugTypeInfo::TypeId") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setTypeId, no_const_t, UCS("DebugTypeInfo::TypeId") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getArrayDim, const_t, UCS("DebugTypeInfo::ArrayDim") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, setArrayDim, no_const_t, UCS("DebugTypeInfo::ArrayDim") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, removeRichType, no_const_t, UCS("DebugTypeInfo::removeRichTypes") );
METHOD_KEY_REGISTER2( DebugTypeInfoInterpreter, void, insertRichType, no_const_t, UCS("DebugTypeInfo::RichTypes") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getRichType, no_const_t, UCS("DebugTypeInfo::RichTypes") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, void, clearRichTypes, no_const_t, UCS("DebugTypeInfo::ClearRichTypes") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, hasRichTypes, const_t, UCS("DebugTypeInfo::HasRichTypes") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, richTypesCount, const_t, UCS("DebugTypeInfo::RichTypesCount") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, removeDebugFunctionInfo, no_const_t, UCS("DebugTypeInfo::removeDebugFunctionInfos") );
METHOD_KEY_REGISTER2( DebugTypeInfoInterpreter, void, insertDebugFunctionInfo, no_const_t, UCS("DebugTypeInfo::DebugFunctionInfos") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getDebugFunctionInfo, no_const_t, UCS("DebugTypeInfo::DebugFunctionInfos") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, void, clearDebugFunctionInfos, no_const_t, UCS("DebugTypeInfo::ClearDebugFunctionInfos") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, hasDebugFunctionInfos, const_t, UCS("DebugTypeInfo::HasDebugFunctionInfos") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, debugFunctionInfosCount, const_t, UCS("DebugTypeInfo::DebugFunctionInfosCount") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, void, removeDebugVariableInfo, no_const_t, UCS("DebugTypeInfo::removeDebugVariableInfos") );
METHOD_KEY_REGISTER2( DebugTypeInfoInterpreter, void, insertDebugVariableInfo, no_const_t, UCS("DebugTypeInfo::DebugVariableInfos") );
METHOD_KEY_REGISTER1( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, getDebugVariableInfo, no_const_t, UCS("DebugTypeInfo::DebugVariableInfos") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, void, clearDebugVariableInfos, no_const_t, UCS("DebugTypeInfo::ClearDebugVariableInfos") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, hasDebugVariableInfos, const_t, UCS("DebugTypeInfo::HasDebugVariableInfos") );
METHOD_KEY_REGISTER ( DebugTypeInfoInterpreter, boost::shared_ptr< Base<EncodingT> >, debugVariableInfosCount, const_t, UCS("DebugTypeInfo::DebugVariableInfosCount") );
FACTORY_END_REGISTER
FACTORY_BEGIN_UNREGISTER
CLASS_KEY_UNREGISTER ( UCS("DebugTypeInfo") );
CLASS_KEY_UNREGISTER22( UCS("DebugTypeInfo") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::PrimitiveType") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::PrimitiveType") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::HasPrimitiveType") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::removePrimitiveType") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::Identifier") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsChar") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsChar") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsString") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsString") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsBool") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsBool") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsFloat") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsFloat") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsSigned") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsSigned") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsWide") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsWide") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsPointer") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsPointer") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsReference") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsReference") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsArray") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsArray") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsConst") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsConst") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsVolatile") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsVolatile") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsStruct") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsStruct") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsClass") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsClass") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsUnion") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsUnion") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsInterface") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsInterface") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsEnum") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsEnum") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::IsFunction") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::IsFunction") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::BaseName") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::BaseName") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::Name") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::Name") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::SizeOf") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::SizeOf") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::TypeId") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::TypeId") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::ArrayDim") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::ArrayDim") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::removeRichTypes") );
METHOD_KEY_UNREGISTER2( UCS("DebugTypeInfo::RichTypes") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::RichTypes") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::ClearRichTypes") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::HasRichTypes") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::RichTypesCount") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::removeDebugFunctionInfos") );
METHOD_KEY_UNREGISTER2( UCS("DebugTypeInfo::DebugFunctionInfos") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::DebugFunctionInfos") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::ClearDebugFunctionInfos") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::HasDebugFunctionInfos") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::DebugFunctionInfosCount") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::removeDebugVariableInfos") );
METHOD_KEY_UNREGISTER2( UCS("DebugTypeInfo::DebugVariableInfos") );
METHOD_KEY_UNREGISTER1( UCS("DebugTypeInfo::DebugVariableInfos") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::ClearDebugVariableInfos") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::HasDebugVariableInfos") );
METHOD_KEY_UNREGISTER ( UCS("DebugTypeInfo::DebugVariableInfosCount") );
FACTORY_END_UNREGISTER
};
template <class EncodingT>
bool check_debugTypeInfo(boost::shared_ptr< Base<EncodingT> > const& val, boost::shared_ptr< _DebugTypeInfo<EncodingT> >& o);
template <class EncodingT>
bool reset_debugTypeInfo(boost::shared_ptr< Base<EncodingT> >& val, boost::shared_ptr< _DebugTypeInfo<EncodingT> > const& o);
NAMESPACE_END
#undef C
#undef A
#include "debugTypeInfoInterpreter_impl.hpp"
#endif
| 57.694761 | 170 | 0.770649 | tedi21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.