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
108
| 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
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2390ce9b12915def58828d146a76a85e540b6710
| 136,156
|
cc
|
C++
|
firmware/src/shared/Menu.cc
|
togetherPeter/Sailfish-G3Firmware3
|
af5ffb1648825e03563c3c488c4d45685b957960
|
[
"AAL"
] | null | null | null |
firmware/src/shared/Menu.cc
|
togetherPeter/Sailfish-G3Firmware3
|
af5ffb1648825e03563c3c488c4d45685b957960
|
[
"AAL"
] | null | null | null |
firmware/src/shared/Menu.cc
|
togetherPeter/Sailfish-G3Firmware3
|
af5ffb1648825e03563c3c488c4d45685b957960
|
[
"AAL"
] | null | null | null |
// Future things that could be consolidated into 1 to save code space when required:
//
// Combined lcd.clear() and lcd.setCursor(0, 0) -> lcd.clearHomeCursor(): savings 184 bytes
// lcd.setCursor(0, r) --> lcd.setRow(r): savings 162 bytes
//
// ValueSetScreen
// BuzzerSetRepeatsMode
// ABPCopiesSetScreen
#include "Configuration.hh"
// TODO: Kill this, should be hanlded by build system.
#ifdef HAS_INTERFACE_BOARD
#include "Menu.hh"
#include "StepperAccel.hh"
#include "Steppers.hh"
#include "Commands.hh"
#include "Errors.hh"
#include "Tool.hh"
#include "Host.hh"
#include "Timeout.hh"
#include "InterfaceBoard.hh"
#include "Interface.hh"
#include "Motherboard.hh"
#include "Version.hh"
#include <util/delay.h>
#include <stdlib.h>
#include "SDCard.hh"
#include "EepromMap.hh"
#include "Eeprom.hh"
#include "EepromDefaults.hh"
#include <avr/eeprom.h>
#include "ExtruderControl.hh"
#include "Main.hh"
#include "locale.h"
#include "lib_sd/sd_raw_err.h"
// Maximum length of an SD card file
#define SD_MAXFILELEN 64
#define HOST_PACKET_TIMEOUT_MS 20
#define HOST_PACKET_TIMEOUT_MICROS (1000L*HOST_PACKET_TIMEOUT_MS)
#define HOST_TOOL_RESPONSE_TIMEOUT_MS 50
#define HOST_TOOL_RESPONSE_TIMEOUT_MICROS (1000L*HOST_TOOL_RESPONSE_TIMEOUT_MS)
#define MAX_ITEMS_PER_SCREEN 4
#define LCD_TYPE_CHANGE_BUTTON_HOLD_TIME 10.0
int16_t overrideExtrudeSeconds = 0;
int8_t autoPause;
Point homePosition;
static uint16_t genericOnOff_offset;
static uint8_t genericOnOff_default;
static const prog_uchar *genericOnOff_msg1;
static const prog_uchar *genericOnOff_msg2;
static const prog_uchar *genericOnOff_msg3;
static const prog_uchar *genericOnOff_msg4;
static const PROGMEM prog_uchar eof_msg1[] = "Extruder Hold:";
static const PROGMEM prog_uchar generic_off[] = "Off";
static const PROGMEM prog_uchar generic_on[] = "On";
static const PROGMEM prog_uchar updnset_msg[] = "Up/Dn/Ent to Set";
static const PROGMEM prog_uchar unknown_temp[] = "XXX";
static const PROGMEM prog_uchar aof_msg1[] = "Accelerated";
static const PROGMEM prog_uchar aof_msg2[] = "Printing:";
static const PROGMEM prog_uchar ts_msg1[] = "Toolhead offset";
static const PROGMEM prog_uchar ts_msg2[] = "system:";
static const PROGMEM prog_uchar ts_old[] = "Old";
static const PROGMEM prog_uchar ts_new[] = "New";
static const PROGMEM prog_uchar dp_msg1[] = "Ditto Printing:";
static const PROGMEM prog_uchar ogct_msg1[] = "Override GCode";
static const PROGMEM prog_uchar ogct_msg2[] = "Temperature:";
static const PROGMEM prog_uchar sdcrc_msg1[] = "Perform SD card";
static const PROGMEM prog_uchar sdcrc_msg2[] = "error checking:";
#ifdef PSTOP_SUPPORT
static const PROGMEM prog_uchar pstop_msg1[] = "P-Stop:";
#endif
//Macros to expand SVN revision macro into a str
#define STR_EXPAND(x) #x //Surround the supplied macro by double quotes
#define STR(x) STR_EXPAND(x)
const static PROGMEM prog_uchar units_mm[] = "mm";
static const char dumpFilename[] = "eeprom_dump.bin";
static void timedMessage(LiquidCrystal& lcd, uint8_t which);
void VersionMode::reset() {
}
// Assumes room for up to 7 + NUL
static void formatTime(char *buf, uint32_t val)
{
bool hasdigit = false;
uint8_t idx = 0;
uint8_t radidx = 0;
const uint8_t radixcount = 5;
const uint8_t houridx = 2;
const uint8_t minuteidx = 4;
uint32_t radixes[radixcount] = {360000, 36000, 3600, 600, 60};
if (val >= 3600000)
val %= 3600000;
for (radidx = 0; radidx < radixcount; radidx++) {
char digit = '0';
uint8_t bit = 8;
uint32_t radshift = radixes[radidx] << 3;
for (; bit > 0; bit >>= 1, radshift >>= 1) {
if (val > radshift) {
val -= radshift;
digit += bit;
}
}
if (hasdigit || digit != '0' || radidx >= houridx) {
buf[idx++] = digit;
hasdigit = true;
} else
buf[idx++] = ' ';
if (radidx == houridx)
buf[idx++] = 'h';
else if (radidx == minuteidx)
buf[idx++] = 'm';
}
buf[idx] = '\0';
}
// Assumes at least 3 spare bytes
static void digits3(char *buf, uint8_t val)
{
uint8_t v;
if ( val >= 100 )
{
v = val / 100;
buf[0] = v + '0';
val -= v * 100;
}
else
buf[0] = ' ';
if ( val >= 10 || buf[0] != ' ')
{
v = val / 10;
buf[1] = v + '0';
val -= v * 10;
}
else
buf[1] = ' ';
buf[2] = val + '0';
buf[3] = '\0';
}
void SplashScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar splash1[] = " Sailfish v" VERSION_STR " ";
#if defined(__AVR_ATmega2560__)
const static PROGMEM prog_uchar splash2[] = "- ATmega 2560 - ";
#else
const static PROGMEM prog_uchar splash2[] = "- ATmega 1280 - ";
#endif
const static PROGMEM prog_uchar splash3[] = " Thing 32084 ";
const static PROGMEM prog_uchar splash4[] = " r" SVN_VERSION_STR " " DATE_STR;
if (forceRedraw) {
lcd.homeCursor();
lcd.writeFromPgmspace(LOCALIZE(splash1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(splash2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(splash3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(splash4));
#ifdef MENU_L10N_H_
lcd.setCursor(9,3);
lcd.writeString((char *)SVN_VERSION_STR);
#endif
}
else {
// The machine has started, so we're done!
interface::popScreen();
}
}
void SplashScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
// We can't really do anything, since the machine is still loading, so ignore.
}
void SplashScreen::reset() {
}
UserViewMenu::UserViewMenu() {
itemCount = 4;
reset();
}
void UserViewMenu::resetState() {
uint8_t jogModeSettings = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS);
if ( jogModeSettings & 0x01 ) itemIndex = 3;
else itemIndex = 2;
firstItemIndex = 2;
}
void UserViewMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar uv_msg[] = "X/Y Direction:";
const static PROGMEM prog_uchar uv_model[]= "Model View";
const static PROGMEM prog_uchar uv_user[] = "User View";
const prog_uchar *msg;
switch (index) {
case 0:
msg = LOCALIZE(uv_msg);
break;
default:
case 1:
return;
case 2:
msg = LOCALIZE(uv_model);
break;
case 3:
msg = LOCALIZE(uv_user);
break;
}
lcd.writeFromPgmspace(msg);
}
void UserViewMenu::handleSelect(uint8_t index) {
uint8_t jogModeSettings = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS);
switch (index) {
default:
return;
case 2:
// Model View
jogModeSettings &= (uint8_t)0xFE;
break;
case 3:
// User View
jogModeSettings |= (uint8_t)0x01;
break;
}
eeprom_write_byte((uint8_t *)eeprom::JOG_MODE_SETTINGS,
jogModeSettings);
interface::popScreen();
}
void JoggerMenu::jog(ButtonArray::ButtonName direction, bool pauseModeJog) {
int32_t interval = 1000;
float speed = 1.5; //In mm's
if ( pauseModeJog ) jogDistance = DISTANCE_CONT;
else {
switch(jogDistance) {
case DISTANCE_0_1MM:
speed = 0.1; //0.1mm
break;
case DISTANCE_1MM:
speed = 1.0; //1mm
break;
case DISTANCE_CONT:
speed = 1.5; //1.5mm
break;
}
}
//Reverse direction of X and Y if we're in User View Mode and
//not model mode
int32_t vMode = 1;
if ( userViewMode ) vMode = -1;
float stepsPerSecond;
enum AxisEnum axisIndex = X_AXIS;
uint16_t eepromLocation = eeprom::HOMING_FEED_RATE_X;
uint8_t activeToolhead;
Point position = steppers::getStepperPosition(&activeToolhead);
switch(direction) {
case ButtonArray::XMINUS:
position[0] -= vMode * stepperAxisMMToSteps(speed,X_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_X; axisIndex = X_AXIS;
break;
case ButtonArray::XPLUS:
position[0] += vMode * stepperAxisMMToSteps(speed,X_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_X; axisIndex = X_AXIS;
break;
case ButtonArray::YMINUS:
position[1] -= vMode * stepperAxisMMToSteps(speed,Y_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Y; axisIndex = Y_AXIS;
break;
case ButtonArray::YPLUS:
position[1] += vMode * stepperAxisMMToSteps(speed,Y_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Y; axisIndex = Y_AXIS;
break;
case ButtonArray::ZMINUS:
position[2] -= stepperAxisMMToSteps(speed,Z_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Z; axisIndex = Z_AXIS;
break;
case ButtonArray::ZPLUS:
position[2] += stepperAxisMMToSteps(speed,Z_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Z; axisIndex = Z_AXIS;
break;
case ButtonArray::CANCEL:
break;
case ButtonArray::OK:
case ButtonArray::ZERO:
if ( ! pauseModeJog ) break;
eepromLocation = 0;
float mms = (float)eeprom::getEeprom8(eeprom::EXTRUDE_MMS, EEPROM_DEFAULT_EXTRUDE_MMS);
stepsPerSecond = mms * stepperAxisStepsPerMM(A_AXIS);
interval = (int32_t)(1000000.0 / stepsPerSecond);
//Handle reverse
if ( direction == ButtonArray::OK ) stepsPerSecond *= -1;
if ( ! ACCELERATION_EXTRUDE_WHEN_NEGATIVE_A ) stepsPerSecond *= -1;
//Extrude for 0.5 seconds
position[activeToolhead + A_AXIS] += (int32_t)(0.5 * stepsPerSecond);
break;
}
if ( jogDistance == DISTANCE_CONT ) lastDirectionButtonPressed = direction;
else lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
if ( eepromLocation != 0 ) {
//60.0, because feed rate is in mm/min units, we convert to seconds
float feedRate = (float)eeprom::getEepromUInt32(eepromLocation, 500) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisStepsPerMM(axisIndex);
interval = (int32_t)(1000000.0 / stepsPerSecond);
}
steppers::setTarget(position, interval);
}
bool MessageScreen::screenWaiting(void){
return (timeout.isActive() || incomplete);
}
void MessageScreen::addMessage(CircularBuffer& buf) {
char c = buf.pop();
while (c != '\0' && buf.getLength() > 0) {
if ( cursor < BUF_SIZE ) message[cursor++] = c;
c = buf.pop();
}
// ensure that message is always null-terminated
if (cursor >= BUF_SIZE) {
message[BUF_SIZE-1] = '\0';
} else {
message[cursor] = '\0';
}
}
void MessageScreen::addMessage(const prog_uchar msg[]) {
if ( cursor >= BUF_SIZE )
return;
cursor += strlcpy_P(message + cursor, (const prog_char *)msg,
BUF_SIZE - cursor);
// ensure that message is always null-terminated
if (cursor >= BUF_SIZE) {
message[BUF_SIZE-1] = '\0';
} else {
message[cursor] = '\0';
}
}
void MessageScreen::clearMessage() {
x = y = 0;
message[0] = '\0';
cursor = 0;
needsRedraw = false;
timeout = Timeout();
incomplete = false;
}
void MessageScreen::setTimeout(uint8_t seconds) {
timeout.start((micros_t)seconds * (micros_t)1000 * (micros_t)1000);
}
void MessageScreen::refreshScreen(){
needsRedraw = true;
}
void MessageScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
char* b = message;
int ycursor = y, xcursor = x;
if (timeout.hasElapsed()) {
InterfaceBoard& ib = Motherboard::getBoard().getInterfaceBoard();
ib.hideMessageScreen();
return;
}
if (forceRedraw || needsRedraw) {
needsRedraw = false;
lcd.clear();
lcd.setCursor(xcursor, ycursor);
while (*b != '\0') {
if (( *b == '\n' ) || ( xcursor >= lcd.getDisplayWidth() )) {
xcursor = 0;
ycursor++;
lcd.setCursor(xcursor, ycursor);
}
if ( *b != '\n' ) {
lcd.write(*b);
xcursor ++;
}
b ++;
}
}
}
void MessageScreen::reset() {
timeout = Timeout();
buttonsDisabled = false;
}
void MessageScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( buttonsDisabled ) return;
}
void JogMode::reset() {
uint8_t jogModeSettings = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS);
jogDistance = (enum distance_t)((jogModeSettings >> 1 ) & 0x07);
if ( jogDistance > DISTANCE_CONT ) jogDistance = DISTANCE_0_1MM;
distanceChanged = false;
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
userViewMode = jogModeSettings & 0x01;
userViewModeChanged = false;
steppers::setSegmentAccelState(true);
}
void JogMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar j_jog1[] = "Jog mode: ";
const static PROGMEM prog_uchar j_jog2[] = " Y+ Z+";
const static PROGMEM prog_uchar j_jog3[] = "X- V X+ (mode)";
const static PROGMEM prog_uchar j_jog4[] = " Y- Z-";
const static PROGMEM prog_uchar j_jog2_user[] = " Y Z+";
const static PROGMEM prog_uchar j_jog3_user[] = "X V X (mode)";
const static PROGMEM prog_uchar j_jog4_user[] = " Y Z-";
const static PROGMEM prog_uchar j_distance0_1mm[] = ".1mm";
const static PROGMEM prog_uchar j_distance1mm[] = "1mm";
const static PROGMEM prog_uchar j_distanceCont[] = "Cont..";
if ( userViewModeChanged ) userViewMode = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS) & 0x01;
if (forceRedraw || distanceChanged || userViewModeChanged) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(j_jog1));
switch (jogDistance) {
case DISTANCE_0_1MM:
lcd.write(0xF3); //Write tilde
lcd.writeFromPgmspace(LOCALIZE(j_distance0_1mm));
break;
case DISTANCE_1MM:
lcd.write(0xF3); //Write tilde
lcd.writeFromPgmspace(LOCALIZE(j_distance1mm));
break;
case DISTANCE_CONT:
lcd.writeFromPgmspace(LOCALIZE(j_distanceCont));
break;
}
lcd.setRow(1);
lcd.writeFromPgmspace(userViewMode ? LOCALIZE(j_jog2_user) : LOCALIZE(j_jog2));
lcd.setRow(2);
lcd.writeFromPgmspace(userViewMode ? LOCALIZE(j_jog3_user) : LOCALIZE(j_jog3));
lcd.setRow(3);
lcd.writeFromPgmspace(userViewMode ? LOCALIZE(j_jog4_user) : LOCALIZE(j_jog4));
distanceChanged = false;
userViewModeChanged = false;
}
if ( jogDistance == DISTANCE_CONT ) {
if ( lastDirectionButtonPressed ) {
if (!interface::isButtonPressed(lastDirectionButtonPressed)) {
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
steppers::abort();
}
}
}
}
void JogMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::ZERO:
userViewModeChanged = true;
interface::pushScreen(&userViewMenu);
break;
case ButtonArray::OK:
switch(jogDistance)
{
case DISTANCE_0_1MM:
jogDistance = DISTANCE_1MM;
break;
case DISTANCE_1MM:
jogDistance = DISTANCE_CONT;
break;
case DISTANCE_CONT:
jogDistance = DISTANCE_0_1MM;
break;
}
distanceChanged = true;
eeprom_write_byte((uint8_t *)eeprom::JOG_MODE_SETTINGS, userViewMode | (jogDistance << 1));
break;
default:
if (( lastDirectionButtonPressed ) && (lastDirectionButtonPressed != button ))
steppers::abort();
jog(button, false);
break;
case ButtonArray::CANCEL:
steppers::abort();
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
interface::popScreen();
steppers::setSegmentAccelState(true);
break;
}
}
void ExtruderMode::reset() {
extrudeSeconds = (enum extrudeSeconds)eeprom::getEeprom8(eeprom::EXTRUDE_DURATION, EEPROM_DEFAULT_EXTRUDE_DURATION);
updatePhase = 0;
timeChanged = false;
lastDirection = 1;
overrideExtrudeSeconds = 0;
steppers::setSegmentAccelState(false);
}
void ExtruderMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar e_extrude1[] = "Extrude: ";
const static PROGMEM prog_uchar e_extrude2[] = "(set mm/s) Fwd";
const static PROGMEM prog_uchar e_extrude3[] = " (stop) (dur)";
const static PROGMEM prog_uchar e_extrude4[] = "---/---C Rev";
const static PROGMEM prog_uchar e_secs[] = "SECS";
const static PROGMEM prog_uchar e_blank[] = " ";
if (overrideExtrudeSeconds) extrude((int32_t)overrideExtrudeSeconds, true);
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(e_extrude1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(e_extrude2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(e_extrude3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(e_extrude4));
}
if ((forceRedraw) || (timeChanged)) {
lcd.setCursor(9,0);
lcd.writeFromPgmspace(LOCALIZE(e_blank));
lcd.setCursor(9,0);
lcd.writeFloat((float)extrudeSeconds, 0);
lcd.writeFromPgmspace(LOCALIZE(e_secs));
timeChanged = false;
}
OutPacket responsePacket;
Point position;
uint8_t activeToolhead;
// Redraw tool info
steppers::getStepperPosition(&activeToolhead);
switch (updatePhase) {
case 0:
lcd.setRow(3);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_TEMP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
case 1:
lcd.setCursor(4,3);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
}
updatePhase++;
if (updatePhase > 1) {
updatePhase = 0;
}
}
void ExtruderMode::extrude(int32_t seconds, bool overrideTempCheck) {
uint8_t activeToolhead;
Point position = steppers::getStepperPosition(&activeToolhead);
//Check we're hot enough
if ( ! overrideTempCheck )
{
OutPacket responsePacket;
if (extruderControl(activeToolhead, SLAVE_CMD_IS_TOOL_READY, EXTDR_CMD_GET, responsePacket, 0)) {
uint8_t data = responsePacket.read8(1);
if ( ! data )
{
overrideExtrudeSeconds = seconds;
interface::pushScreen(&extruderTooColdMenu);
return;
}
}
}
float mms = (float)eeprom::getEeprom8(eeprom::EXTRUDE_MMS, EEPROM_DEFAULT_EXTRUDE_MMS);
float stepsPerSecond = mms * stepperAxisStepsPerMM(A_AXIS);
int32_t interval = (int32_t)(1000000.0 / stepsPerSecond);
//Handle 5D
float direction = 1.0;
if ( ACCELERATION_EXTRUDE_WHEN_NEGATIVE_A ) direction = -1.0;
if ( seconds == 0 ) steppers::abort();
else {
position[A_AXIS + activeToolhead] += direction * seconds * stepsPerSecond;
steppers::setTarget(position, interval);
}
if (overrideTempCheck) overrideExtrudeSeconds = 0;
}
void ExtruderMode::notifyButtonPressed(ButtonArray::ButtonName button) {
static const PROGMEM prog_uchar e_message1[] = "Extruder speed:";
static const PROGMEM prog_uchar e_units[] = " mm/s ";
switch (button) {
case ButtonArray::OK:
switch(extrudeSeconds) {
case EXTRUDE_SECS_1S:
extrudeSeconds = EXTRUDE_SECS_2S;
break;
case EXTRUDE_SECS_2S:
extrudeSeconds = EXTRUDE_SECS_5S;
break;
case EXTRUDE_SECS_5S:
extrudeSeconds = EXTRUDE_SECS_10S;
break;
case EXTRUDE_SECS_10S:
extrudeSeconds = EXTRUDE_SECS_30S;
break;
case EXTRUDE_SECS_30S:
extrudeSeconds = EXTRUDE_SECS_60S;
break;
case EXTRUDE_SECS_60S:
extrudeSeconds = EXTRUDE_SECS_90S;
break;
case EXTRUDE_SECS_90S:
extrudeSeconds = EXTRUDE_SECS_120S;
break;
case EXTRUDE_SECS_120S:
extrudeSeconds = EXTRUDE_SECS_240S;
break;
case EXTRUDE_SECS_240S:
extrudeSeconds = EXTRUDE_SECS_1S;
break;
default:
extrudeSeconds = EXTRUDE_SECS_1S;
break;
}
eeprom_write_byte((uint8_t *)eeprom::EXTRUDE_DURATION, (uint8_t)extrudeSeconds);
//If we're already extruding, change the time running
if (steppers::isRunning())
extrude((int32_t)(lastDirection * extrudeSeconds), false);
timeChanged = true;
break;
case ButtonArray::YPLUS:
// Show Extruder MMS Setting Screen
extruderSetMMSScreen.location = eeprom::EXTRUDE_MMS;
extruderSetMMSScreen.default_value = EEPROM_DEFAULT_EXTRUDE_MMS;
extruderSetMMSScreen.message1 = LOCALIZE(e_message1);
extruderSetMMSScreen.units = LOCALIZE(e_units);
interface::pushScreen(&extruderSetMMSScreen);
break;
case ButtonArray::ZERO:
case ButtonArray::YMINUS:
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
extrude((int32_t)EXTRUDE_SECS_CANCEL, true);
break;
case ButtonArray::ZMINUS:
case ButtonArray::ZPLUS:
if ( button == ButtonArray::ZPLUS ) lastDirection = 1;
else lastDirection = -1;
extrude((int32_t)(lastDirection * extrudeSeconds), false);
break;
case ButtonArray::CANCEL:
steppers::abort();
steppers::enableAxis(3, false);
interface::popScreen();
steppers::setSegmentAccelState(true);
steppers::enableAxis(3, false);
break;
}
}
ExtruderTooColdMenu::ExtruderTooColdMenu() {
itemCount = 4;
reset();
}
void ExtruderTooColdMenu::resetState() {
itemIndex = 2;
firstItemIndex = 2;
}
void ExtruderTooColdMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar etc_warning[] = "Tool0 too cold!";
const static PROGMEM prog_uchar etc_cancel[] = "Cancel";
const static PROGMEM prog_uchar etc_override[] = "Override";
const prog_uchar *msg;
switch (index) {
case 0:
msg = LOCALIZE(etc_warning);
break;
default:
return;
case 2:
msg = LOCALIZE(etc_cancel);
break;
case 3:
msg = LOCALIZE(etc_override);
break;
}
lcd.writeFromPgmspace(msg);
}
void ExtruderTooColdMenu::handleCancel() {
overrideExtrudeSeconds = 0;
interface::popScreen();
}
void ExtruderTooColdMenu::handleSelect(uint8_t index) {
switch (index) {
default :
return;
case 2:
// Cancel extrude
overrideExtrudeSeconds = 0;
break;
case 3:
// Override and extrude
break;
}
interface::popScreen();
}
void MoodLightMode::reset() {
updatePhase = 0;
scriptId = eeprom_read_byte((uint8_t *)eeprom::MOOD_LIGHT_SCRIPT);
}
void MoodLightMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ml_mood1[] = "Mood: ";
const static PROGMEM prog_uchar ml_mood3_1[] = "(set RGB)";
const static PROGMEM prog_uchar ml_blank[] = " ";
const static PROGMEM prog_uchar ml_moodNotPresent1[] = "Mood Light not";
const static PROGMEM prog_uchar ml_moodNotPresent2[] = "present!!";
const static PROGMEM prog_uchar ml_moodNotPresent3[] = "See Thingiverse";
const static PROGMEM prog_uchar ml_moodNotPresent4[] = " thing:15347";
//If we have no mood light, point to thingiverse to make one
if ( ! interface::moodLightController().blinkM.blinkMIsPresent ) {
//Try once more to restart the mood light controller
if ( ! interface::moodLightController().start() ) {
if ( forceRedraw ) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent4));
}
return;
}
}
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ml_mood1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
//Redraw tool info
switch (updatePhase) {
case 0:
lcd.setCursor(6, 0);
lcd.writeFromPgmspace(LOCALIZE(ml_blank));
lcd.setCursor(6, 0);
lcd.writeFromPgmspace(interface::moodLightController().scriptIdToStr(scriptId));
break;
case 1:
lcd.setRow(2);
lcd.writeFromPgmspace((scriptId == 1) ? LOCALIZE(ml_mood3_1) : LOCALIZE(ml_blank));
break;
}
if (++updatePhase > 1)
updatePhase = 0;
}
void MoodLightMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( ! interface::moodLightController().blinkM.blinkMIsPresent )
interface::popScreen();
uint8_t i;
switch (button) {
case ButtonArray::OK:
eeprom_write_byte((uint8_t *)eeprom::MOOD_LIGHT_SCRIPT,
scriptId);
interface::popScreen();
break;
case ButtonArray::ZERO:
if ( scriptId == 1 )
//Set RGB Values
interface::pushScreen(&moodLightSetRGBScreen);
break;
case ButtonArray::ZPLUS:
// increment more
for ( i = 0; i < 5; i ++ )
scriptId = interface::moodLightController().nextScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
case ButtonArray::ZMINUS:
// decrement more
for ( i = 0; i < 5; i ++ )
scriptId = interface::moodLightController().prevScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
case ButtonArray::YPLUS:
// increment less
scriptId = interface::moodLightController().nextScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
case ButtonArray::YMINUS:
// decrement less
scriptId = interface::moodLightController().prevScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
default:
break;
case ButtonArray::CANCEL:
scriptId = eeprom_read_byte((uint8_t *)eeprom::MOOD_LIGHT_SCRIPT);
interface::moodLightController().playScript(scriptId);
interface::popScreen();
break;
}
}
void MoodLightSetRGBScreen::reset() {
inputMode = 0; //Red
redrawScreen = false;
red = eeprom::getEeprom8(eeprom::MOOD_LIGHT_CUSTOM_RED, EEPROM_DEFAULT_MOOD_LIGHT_CUSTOM_RED);;
green = eeprom::getEeprom8(eeprom::MOOD_LIGHT_CUSTOM_GREEN, EEPROM_DEFAULT_MOOD_LIGHT_CUSTOM_GREEN);;
blue = eeprom::getEeprom8(eeprom::MOOD_LIGHT_CUSTOM_BLUE, EEPROM_DEFAULT_MOOD_LIGHT_CUSTOM_BLUE);;
}
void MoodLightSetRGBScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar mlsrgb_message1_red[] = "Red:";
const static PROGMEM prog_uchar mlsrgb_message1_green[] = "Green:";
const static PROGMEM prog_uchar mlsrgb_message1_blue[] = "Blue:";
if ((forceRedraw) || (redrawScreen)) {
lcd.clearHomeCursor();
if ( inputMode == 0 ) lcd.writeFromPgmspace(LOCALIZE(mlsrgb_message1_red));
else if ( inputMode == 1 ) lcd.writeFromPgmspace(LOCALIZE(mlsrgb_message1_green));
else if ( inputMode == 2 ) lcd.writeFromPgmspace(LOCALIZE(mlsrgb_message1_blue));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
redrawScreen = false;
}
// Redraw tool info
lcd.setRow(1);
if ( inputMode == 0 ) lcd.writeInt(red, 3);
else if ( inputMode == 1 ) lcd.writeInt(green,3);
else if ( inputMode == 2 ) lcd.writeInt(blue, 3);
}
void MoodLightSetRGBScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
uint8_t *value = &red;
if ( inputMode == 1 ) value = &green;
else if ( inputMode == 2 ) value = &blue;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
if ( inputMode < 2 ) {
inputMode ++;
redrawScreen = true;
} else {
eeprom_write_byte((uint8_t*)eeprom::MOOD_LIGHT_CUSTOM_RED, red);
eeprom_write_byte((uint8_t*)eeprom::MOOD_LIGHT_CUSTOM_GREEN,green);
eeprom_write_byte((uint8_t*)eeprom::MOOD_LIGHT_CUSTOM_BLUE, blue);
//Set the color
interface::moodLightController().playScript(1);
interface::popScreen();
}
break;
case ButtonArray::ZPLUS:
// increment more
if (*value <= 245) *value += 10;
break;
case ButtonArray::ZMINUS:
// decrement more
if (*value >= 10) *value -= 10;
break;
case ButtonArray::YPLUS:
// increment less
if (*value <= 254) *value += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if (*value >= 1) *value -= 1;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
void MonitorMode::reset() {
updatePhase = UPDATE_PHASE_FIRST;
buildTimePhase = BUILD_TIME_PHASE_FIRST;
lastBuildTimePhase = BUILD_TIME_PHASE_FIRST;
lastElapsedSeconds = 0.0;
pausePushLockout = false;
autoPause = 0;
buildCompleteBuzzPlayed = false;
overrideForceRedraw = false;
flashingTool = false;
flashingPlatform = false;
}
void MonitorMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar mon_extruder_temp[] = "Tool ---/---\001";
const static PROGMEM prog_uchar mon_platform_temp[] = "Bed ---/---\001";
const static PROGMEM prog_uchar mon_elapsed_time[] = "Elapsed: 0h00m";
const static PROGMEM prog_uchar mon_completed_percent[] = "Completed: 0% ";
const static PROGMEM prog_uchar mon_time_left[] = "TimeLeft: 0h00m";
const static PROGMEM prog_uchar mon_time_left_secs[] = "secs";
const static PROGMEM prog_uchar mon_time_left_none[] = " none";
const static PROGMEM prog_uchar mon_zpos[] = "ZPos: ";
const static PROGMEM prog_uchar mon_speed[] = "Acc: ";
const static PROGMEM prog_uchar mon_filament[] = "Filament:0.00m ";
const static PROGMEM prog_uchar mon_copies[] = "Copy: ";
const static PROGMEM prog_uchar mon_of[] = " of ";
const static PROGMEM prog_uchar mon_error[] = "error!";
char buf[17];
if ( command::isPaused() ) {
if ( ! pausePushLockout ) {
pausePushLockout = true;
autoPause = 1;
interface::pushScreen(&pauseMode);
return;
}
} else pausePushLockout = false;
//Check for a build complete, and if we have more than one copy
//to print, setup another one
if ( host::isBuildComplete() ) {
if ( command::copiesToPrint > 1 ) {
if ( command::copiesPrinted < (command::copiesToPrint - 1)) {
command::copiesPrinted ++;
overrideForceRedraw = true;
command::buildAnotherCopy();
}
}
}
if ((forceRedraw) || (overrideForceRedraw)) {
lcd.clearHomeCursor();
switch(host::getHostState()) {
case host::HOST_STATE_READY:
lcd.writeString(host::getMachineName());
break;
case host::HOST_STATE_BUILDING:
case host::HOST_STATE_BUILDING_FROM_SD:
lcd.writeString(host::getBuildName());
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_completed_percent));
break;
case host::HOST_STATE_ERROR:
lcd.writeFromPgmspace(LOCALIZE(mon_error));
break;
case host::HOST_STATE_CANCEL_BUILD :
break;
}
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(mon_extruder_temp));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(mon_platform_temp));
lcd.setCursor(15,3);
lcd.write((command::getPauseAtZPos() == 0) ? ' ' : '*');
}
overrideForceRedraw = false;
//Flash the temperature indicators
toggleHeating ^= true;
if ( flashingTool ) {
lcd.setCursor(5,2);
lcd.write(toggleHeating ? LCD_CUSTOM_CHAR_EXTRUDER_NORMAL : LCD_CUSTOM_CHAR_EXTRUDER_HEATING);
}
if ( flashingPlatform ) {
lcd.setCursor(5,3);
lcd.write(toggleHeating ? LCD_CUSTOM_CHAR_PLATFORM_NORMAL : LCD_CUSTOM_CHAR_PLATFORM_HEATING);
}
OutPacket responsePacket;
uint8_t activeToolhead;
steppers::getStepperPosition(&activeToolhead);
// Redraw tool info
switch (updatePhase) {
case UPDATE_PHASE_TOOL_TEMP:
lcd.setCursor(7,2);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_TEMP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
case UPDATE_PHASE_TOOL_TEMP_SET_POINT:
lcd.setCursor(11,2);
uint16_t data;
data = 0;
if (extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0)) {
data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
lcd.setCursor(5,2);
if (extruderControl(activeToolhead, SLAVE_CMD_IS_TOOL_READY, EXTDR_CMD_GET, responsePacket, 0)) {
flashingTool = false;
uint8_t ready = responsePacket.read8(1);
if ( data != 0 ) {
if ( ready ) lcd.write(LCD_CUSTOM_CHAR_EXTRUDER_HEATING);
else flashingTool = true;
}
else lcd.write(LCD_CUSTOM_CHAR_EXTRUDER_NORMAL);
}
break;
case UPDATE_PHASE_PLATFORM_TEMP:
lcd.setCursor(7,3);
if (extruderControl(0, SLAVE_CMD_GET_PLATFORM_TEMP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
case UPDATE_PHASE_PLATFORM_SET_POINT:
lcd.setCursor(11,3);
data = 0;
if (extruderControl(0, SLAVE_CMD_GET_PLATFORM_SP, EXTDR_CMD_GET, responsePacket, 0)) {
data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
lcd.setCursor(5,3);
if (extruderControl(0, SLAVE_CMD_IS_PLATFORM_READY, EXTDR_CMD_GET, responsePacket, 0)) {
flashingPlatform = false;
uint8_t ready = responsePacket.read8(1);
if ( data != 0 ) {
if ( ready ) lcd.write(LCD_CUSTOM_CHAR_PLATFORM_HEATING);
else flashingPlatform = true;
}
else lcd.write(LCD_CUSTOM_CHAR_PLATFORM_NORMAL);
}
lcd.setCursor(15,3);
lcd.write((command::getPauseAtZPos() == 0) ? ' ' : '*');
break;
case UPDATE_PHASE_LAST:
break;
case UPDATE_PHASE_BUILD_PHASE_SCROLLER:
enum host::HostState hostState = host::getHostState();
if ( (hostState != host::HOST_STATE_BUILDING ) && ( hostState != host::HOST_STATE_BUILDING_FROM_SD )) break;
//Signal buzzer if we're complete
if (( ! buildCompleteBuzzPlayed ) && ( sdcard::getPercentPlayed() >= 100.0 )) {
buildCompleteBuzzPlayed = true;
Motherboard::getBoard().buzz(2, 3, eeprom::getEeprom8(eeprom::BUZZER_REPEATS, EEPROM_DEFAULT_BUZZER_REPEATS));
}
bool okButtonHeld = interface::isButtonPressed(ButtonArray::OK);
//Holding the ok button stops rotation
if ( okButtonHeld ) buildTimePhase = lastBuildTimePhase;
float secs;
int32_t tsecs;
Point position;
uint8_t precision;
uint8_t completedPercent;
float filamentUsed;
switch (buildTimePhase) {
case BUILD_TIME_PHASE_COMPLETED_PERCENT:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_completed_percent));
lcd.setCursor(11,1);
completedPercent = command::getBuildPercentage();
if ( completedPercent > 100 )
// displaying 101% confuses some people
completedPercent = 0;
digits3(buf, (uint8_t)completedPercent);
lcd.writeString(buf);
lcd.write('%');
break;
case BUILD_TIME_PHASE_ELAPSED_TIME:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_elapsed_time));
lcd.setCursor(9,1);
if ( host::isBuildComplete() ) secs = lastElapsedSeconds; //We stop counting elapsed seconds when we are done
else {
lastElapsedSeconds = Motherboard::getBoard().getCurrentSeconds();
secs = lastElapsedSeconds;
}
formatTime(buf, (uint32_t)secs);
lcd.writeString(buf);
break;
case BUILD_TIME_PHASE_TIME_LEFT:
tsecs = command::estimatedTimeLeftInSeconds();
if ( tsecs > 0 ) {
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_time_left));
lcd.setCursor(9,1);
if ((tsecs > 0 ) && (tsecs < 60) && ( host::isBuildComplete() ) ) {
digits3(buf, (uint8_t)tsecs);
lcd.writeString(buf);
lcd.writeFromPgmspace(LOCALIZE(mon_time_left_secs));
} else if (( tsecs <= 0) || ( host::isBuildComplete()) ) {
#ifdef HAS_FILAMENT_COUNTER
command::addFilamentUsed();
#endif
lcd.writeFromPgmspace(LOCALIZE(mon_time_left_none));
} else {
formatTime(buf, (uint32_t)tsecs);
lcd.writeString(buf);
}
break;
}
//We can't display the time left, so we drop into ZPosition instead
else buildTimePhase = (enum BuildTimePhase)((uint8_t)buildTimePhase + 1);
case BUILD_TIME_PHASE_ZPOS:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_zpos));
lcd.setCursor(6,1);
position = steppers::getStepperPosition();
//Divide by the axis steps to mm's
lcd.writeFloat(stepperAxisStepsToMM(position[2], Z_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
break;
case BUILD_TIME_PHASE_FILAMENT:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_filament));
lcd.setCursor(9,1);
filamentUsed =
stepperAxisStepsToMM(command::getLastFilamentLength(0) + command::getLastFilamentLength(1), A_AXIS) +
stepperAxisStepsToMM((command::getFilamentLength(0) + command::getFilamentLength(1)), A_AXIS);
filamentUsed /= 1000.0; //convert to meters
if ( filamentUsed < 0.1 ) {
filamentUsed *= 1000.0; //Back to mm's
precision = 1;
}
else if ( filamentUsed < 10.0 ) precision = 4;
else if ( filamentUsed < 100.0 ) precision = 3;
else precision = 2;
lcd.writeFloat(filamentUsed, precision);
if ( precision == 1 ) lcd.write('m');
lcd.write('m');
break;
case BUILD_TIME_PHASE_COPIES_PRINTED:
if ( command::copiesToPrint ) {
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_copies));
lcd.setCursor(7,1);
lcd.writeFloat((float)(command::copiesPrinted + 1), 0);
lcd.writeFromPgmspace(LOCALIZE(mon_of));
lcd.writeFloat((float)command::copiesToPrint, 0);
}
break;
case BUILD_TIME_PHASE_LAST:
break;
case BUILD_TIME_PHASE_ACCEL_STATS:
float minSpeed, avgSpeed, maxSpeed;
accelStatsGet(&minSpeed, &avgSpeed, &maxSpeed);
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_speed));
lcd.setCursor(4,1);
if ( minSpeed < 100.0 ) lcd.write(' '); //If we have space, pad out a bit
lcd.writeFloat(minSpeed,0);
lcd.write('/');
lcd.writeFloat(avgSpeed,0);
lcd.write('/');
lcd.writeFloat(maxSpeed,0);
lcd.write(' ');
break;
}
if ( ! okButtonHeld ) {
//Advance buildTimePhase and wrap around
lastBuildTimePhase = buildTimePhase;
buildTimePhase = (enum BuildTimePhase)((uint8_t)buildTimePhase + 1);
//If we're setup to print more than one copy, then show that build phase,
//otherwise skip it
if ( buildTimePhase == BUILD_TIME_PHASE_COPIES_PRINTED ) {
uint8_t totalCopies = eeprom::getEeprom8(eeprom::ABP_COPIES, EEPROM_DEFAULT_ABP_COPIES);
if ( totalCopies <= 1 )
buildTimePhase = (enum BuildTimePhase)((uint8_t)buildTimePhase + 1);
}
if ( buildTimePhase >= BUILD_TIME_PHASE_LAST )
buildTimePhase = BUILD_TIME_PHASE_FIRST;
}
break;
}
//Advance updatePhase and wrap around
updatePhase = (enum UpdatePhase)((uint8_t)updatePhase + 1);
if (updatePhase >= UPDATE_PHASE_LAST)
updatePhase = UPDATE_PHASE_FIRST;
#ifdef DEBUG_ONSCREEN
lcd.homeCursor();
lcd.writeString((char *)"DOS1: ");
lcd.writeFloat(debug_onscreen1, 3);
lcd.writeString((char *)" ");
lcd.setRow(1);
lcd.writeString((char *)"DOS2: ");
lcd.writeFloat(debug_onscreen2, 3);
lcd.writeString((char *)" ");
#endif
}
void MonitorMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
switch(host::getHostState()) {
case host::HOST_STATE_BUILDING:
case host::HOST_STATE_BUILDING_FROM_SD:
interface::pushScreen(&cancelBuildMenu);
break;
default:
interface::popScreen();
break;
}
case ButtonArray::ZPLUS:
if ( host::getHostState() == host::HOST_STATE_BUILDING_FROM_SD )
updatePhase = UPDATE_PHASE_BUILD_PHASE_SCROLLER;
break;
default:
break;
}
}
void VersionMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar v_version1[] = "Motherboard _._";
const static PROGMEM prog_uchar v_version2[] = " Extruder _._";
const static PROGMEM prog_uchar v_version3[] = " Revision " SVN_VERSION_STR;
const static PROGMEM prog_uchar v_version4[] = "Free SRAM ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(v_version1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(v_version2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(v_version3));
//Display the motherboard version
lcd.setCursor(13, 0);
lcd.writeInt(firmware_version / 100, 1);
lcd.setCursor(15, 0);
lcd.writeInt(firmware_version % 100, 1);
//Display the extruder version
OutPacket responsePacket;
if (extruderControl(0, SLAVE_CMD_VERSION, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t extruderVersion = responsePacket.read16(1);
lcd.setCursor(13, 1);
lcd.writeInt(extruderVersion / 100, 1);
lcd.setCursor(15, 1);
lcd.writeInt(extruderVersion % 100, 1);
} else {
lcd.setCursor(13, 1);
lcd.writeString((char *)"X.X");
}
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(v_version4));
lcd.writeFloat((float)StackCount(),0);
} else {
}
}
void VersionMode::notifyButtonPressed(ButtonArray::ButtonName button) {
interface::popScreen();
}
void Menu::update(LiquidCrystal& lcd, bool forceRedraw) {
uint8_t height = lcd.getDisplayHeight();
// Do we need to redraw the whole menu?
if ((itemIndex/height) != (lastDrawIndex/height)
|| forceRedraw ) {
// Redraw the whole menu
lcd.clear();
for (uint8_t i = 0; i < height; i++) {
// Instead of using lcd.clear(), clear one line at a time so there
// is less screen flickr.
if (i+(itemIndex/height)*height +1 > itemCount) {
break;
}
lcd.setCursor(1,i);
// Draw one page of items at a time
drawItem(i+(itemIndex/height)*height, lcd);
}
}
else {
// Only need to clear the previous cursor
lcd.setRow(lastDrawIndex%height);
lcd.write(' ');
}
lcd.setRow(itemIndex%height);
lcd.write(LCD_CUSTOM_CHAR_ARROW);
lastDrawIndex = itemIndex;
}
void Menu::reset() {
firstItemIndex = 0;
itemIndex = 0;
lastDrawIndex = 255;
resetState();
}
void Menu::resetState() {
}
void Menu::handleSelect(uint8_t index) {
}
void Menu::handleCancel() {
// Remove ourselves from the menu list
interface::popScreen();
}
void Menu::notifyButtonPressed(ButtonArray::ButtonName button) {
uint8_t steps = MAX_ITEMS_PER_SCREEN;
switch (button) {
case ButtonArray::ZERO:
case ButtonArray::OK:
handleSelect(itemIndex);
break;
case ButtonArray::CANCEL:
handleCancel();
break;
case ButtonArray::YMINUS:
steps = 1;
case ButtonArray::ZMINUS:
// increment index
if (itemIndex < itemCount - steps)
itemIndex+=steps;
else if (itemIndex==itemCount-1)
itemIndex=firstItemIndex;
else itemIndex=itemCount-1;
break;
case ButtonArray::YPLUS:
steps = 1;
case ButtonArray::ZPLUS:
// decrement index
if (itemIndex-steps > firstItemIndex)
itemIndex-=steps;
else if (itemIndex==firstItemIndex)
itemIndex=itemCount - 1;
else itemIndex=firstItemIndex;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
CancelBuildMenu::CancelBuildMenu() :
pauseDisabled(false) {
itemCount = 7;
autoPause = 0;
reset();
if (( steppers::isHoming() ) || (sdcard::getPercentPlayed() >= 100.0)) pauseDisabled = true;
if ( host::isBuildComplete() )
printAnotherEnabled = true;
else printAnotherEnabled = false;
}
void CancelBuildMenu::resetState() {
autoPause = 0;
pauseDisabled = false;
if (( steppers::isHoming() ) || (sdcard::getPercentPlayed() >= 100.0)) pauseDisabled = true;
if ( host::isBuildComplete() )
printAnotherEnabled = true;
else printAnotherEnabled = false;
if ( pauseDisabled ) {
itemIndex = 2;
itemCount = 3;
} else {
itemIndex = 1;
itemCount = 9;
}
if ( printAnotherEnabled )
itemCount++;
#if 0
if ( printAnotherEnabled ) {
itemIndex = 1;
}
#endif
firstItemIndex = 1;
}
void CancelBuildMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
if ( command::isPaused() ) interface::popScreen();
else Menu::update(lcd, forceRedraw);
}
void CancelBuildMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
// --- first screen ---
const static PROGMEM prog_uchar cb_choose[] = "Please Choose:";
const static PROGMEM prog_uchar cb_abort[] = "Abort Print";
const static PROGMEM prog_uchar cb_pause[] = "Pause";
const static PROGMEM prog_uchar cb_pauseZ[] = "Pause at ZPos";
// --- second screen ---
const static PROGMEM prog_uchar cb_pauseHBPHeat[] = "Pause, HBP on";
const static PROGMEM prog_uchar cb_pauseNoHeat[] = "Pause, No Heat";
const static PROGMEM prog_uchar cb_speed[] = "Change Speed";
const static PROGMEM prog_uchar cb_temp[] = "Change Temp";
// --- third screen ---
const static PROGMEM prog_uchar cb_printAnother[] = "Print Another";
const static PROGMEM prog_uchar cb_cont[] = "Continue Build";
const static PROGMEM prog_uchar cb_back[] = "Return to Menu";
if (( steppers::isHoming() ) || (sdcard::getPercentPlayed() >= 100.0)) pauseDisabled = true;
//Implement variable length menu
uint8_t lind = 0;
// ---- first screen ----
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_choose));
lind ++;
// skip abort if paused...
if (( pauseDisabled ) && ( ! printAnotherEnabled )) lind ++;
if ( index == lind) lcd.writeFromPgmspace(LOCALIZE(cb_abort));
lind ++;
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pause));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pauseZ));
lind ++;
}
// ---- second screen ----
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pauseHBPHeat));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pauseNoHeat));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_speed));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_temp));
lind ++;
}
// ---- third screen ----
if ( printAnotherEnabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_printAnother));
lind ++;
}
if ( index == lind ) {
if ( printAnotherEnabled ) lcd.writeFromPgmspace(LOCALIZE(cb_back));
else lcd.writeFromPgmspace(LOCALIZE(cb_cont));
}
}
void CancelBuildMenu::handleSelect(uint8_t index) {
//Implement variable length menu
uint8_t lind = 0;
if (( pauseDisabled ) && ( ! printAnotherEnabled )) lind ++;
lind ++;
if ( index == lind ) {
#ifdef HAS_FILAMENT_COUNTER
command::addFilamentUsed();
#endif
// Cancel build, returning to whatever menu came before monitor mode.
// TODO: Cancel build.
interface::popScreen();
host::stopBuild();
return;
}
lind ++;
if ( ! pauseDisabled ) {
if ( index == lind ) {
command::pause(true, PAUSE_HEAT_ON); // pause, all heaters left on
autoPause = 0;
interface::pushScreen(&pauseMode);
return;
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) {
interface::pushScreen(&pauseAtZPosScreen);
return;
}
lind ++;
}
// ---- second screen ----
if ( ! pauseDisabled ) {
if ( index == lind ) {
command::pause(true, PAUSE_EXT_OFF); // pause, HBP left on
autoPause = 0;
interface::pushScreen(&pauseMode);
return;
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) {
command::pause(true, PAUSE_EXT_OFF | PAUSE_HBP_OFF); // pause no heat
autoPause = 0;
interface::pushScreen(&pauseMode);
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind )
{
interface::pushScreen(&changeSpeedScreen);
return;
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind )
{
interface::pushScreen(&changeTempScreen);
return;
}
lind ++;
}
// ---- third screen ----
if ( printAnotherEnabled ) {
if ( index == lind ) {
command::buildAnotherCopy();
interface::popScreen();
return;
}
lind ++;
}
if ( index == lind ) {
// Don't cancel print, just close dialog.
interface::popScreen();
}
}
MainMenu::MainMenu() {
itemCount = 20;
#ifdef EEPROM_MENU_ENABLE
itemCount ++;
#endif
reset();
lcdTypeChangeTimer = 0.0;
}
void MainMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar main_monitor[] = "Monitor";
const static PROGMEM prog_uchar main_build[] = "Build from SD";
const static PROGMEM prog_uchar main_jog[] = "Jog";
const static PROGMEM prog_uchar main_preheat[] = "Preheat";
const static PROGMEM prog_uchar main_extruder[] = "Extrude";
const static PROGMEM prog_uchar main_homeAxis[] = "Home Axis";
const static PROGMEM prog_uchar main_advanceABP[] = "Advance ABP";
const static PROGMEM prog_uchar main_steppersS[] = "Steppers";
const static PROGMEM prog_uchar main_moodlight[] = "Mood Light";
const static PROGMEM prog_uchar main_buzzer[] = "Buzzer";
const static PROGMEM prog_uchar main_buildSettings[] = "Build Settings";
const static PROGMEM prog_uchar main_profiles[] = "Profiles";
const static PROGMEM prog_uchar main_extruderFan[] = "Extruder Fan";
const static PROGMEM prog_uchar main_calibrate[] = "Calibrate";
const static PROGMEM prog_uchar main_homeOffsets[] = "Home Offsets";
const static PROGMEM prog_uchar main_filamentUsed[] = "Filament Used";
const static PROGMEM prog_uchar main_currentPosition[] = "Position";
const static PROGMEM prog_uchar main_endStops[] = "Test End Stops";
const static PROGMEM prog_uchar main_homingRates[] = "Homing Rates";
const static PROGMEM prog_uchar main_versions[] = "Version";
#ifdef EEPROM_MENU_ENABLE
const static PROGMEM prog_uchar main_eeprom[] = "Eeprom";
#endif
const static prog_uchar *messages[20
#ifdef EEPROM_MENU_ENABLE
+1
#endif
] = { LOCALIZE(main_monitor), // 0
LOCALIZE(main_build), // 1
LOCALIZE(main_preheat), // 2
LOCALIZE(main_extruder), // 3
LOCALIZE(main_buildSettings), // 4
LOCALIZE(main_homeAxis), // 5
LOCALIZE(main_jog), // 6
LOCALIZE(main_filamentUsed), // 7
LOCALIZE(main_advanceABP), // 8
LOCALIZE(main_steppersS), // 9
LOCALIZE(main_moodlight), // 10
LOCALIZE(main_buzzer), // 11
LOCALIZE(main_profiles), // 12
LOCALIZE(main_calibrate), // 13
LOCALIZE(main_homeOffsets), // 14
LOCALIZE(main_homingRates), // 15
LOCALIZE(main_extruderFan), // 16
LOCALIZE(main_endStops), // 17
LOCALIZE(main_currentPosition), // 18
LOCALIZE(main_versions), // 19
#ifdef EEPROM_MENU_ENABLE
LOCALIZE(main_eeprom), // 20
#endif
};
if ( index < sizeof(messages)/sizeof(prog_uchar *) )
lcd.writeFromPgmspace(messages[index]);
}
void MainMenu::handleSelect(uint8_t index) {
switch (index) {
case 0:
interface::pushScreen(&monitorMode);
break;
case 1:
interface::pushScreen(&sdMenu);
break;
case 2:
interface::pushScreen(&preheatMenu);
preheatMenu.fetchTargetTemps();
break;
case 3:
interface::pushScreen(&extruderMenu);
break;
case 4:
interface::pushScreen(&buildSettingsMenu);
break;
case 5:
interface::pushScreen(&homeAxisMode);
break;
case 6:
interface::pushScreen(&jogger);
break;
case 7:
interface::pushScreen(&filamentUsedMode);
break;
case 8:
interface::pushScreen(&advanceABPMode);
break;
case 9:
interface::pushScreen(&steppersMenu);
break;
case 10:
interface::pushScreen(&moodLightMode);
break;
case 11:
interface::pushScreen(&buzzerSetRepeats);
break;
case 12:
interface::pushScreen(&profilesMenu);
break;
case 13:
interface::pushScreen(&calibrateMode);
break;
case 14:
interface::pushScreen(&homeOffsetsMode);
break;
case 15:
interface::pushScreen(&homingFeedRatesMode);
break;
case 16:
interface::pushScreen(&extruderFanMenu);
break;
case 17:
interface::pushScreen(&testEndStopsMode);
break;
case 18:
interface::pushScreen(¤tPositionMode);
break;
case 19:
interface::pushScreen(&versionMode);
break;
#ifdef EEPROM_MENU_ENABLE
case 20:
interface::pushScreen(&eepromMenu);
break;
#endif
}
}
void MainMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
Menu::update(lcd, forceRedraw);
if (interface::isButtonPressed(ButtonArray::XMINUS)) {
if (( lcdTypeChangeTimer != -1.0 ) && ( lcdTypeChangeTimer + LCD_TYPE_CHANGE_BUTTON_HOLD_TIME ) <= Motherboard::getBoard().getCurrentSeconds()) {
Motherboard::getBoard().buzz(1, 1, 1);
lcdTypeChangeTimer = -1.0;
lcd.nextLcdType();
lcd.reloadDisplayType();
host::stopBuildNow();
}
} else lcdTypeChangeTimer = Motherboard::getBoard().getCurrentSeconds();
}
SDMenu::SDMenu() :
updatePhase(0),
drawItemLockout(false),
selectable(false),
folderStackIndex(-1) {
reset();
}
void SDMenu::resetState() {
itemCount = countFiles();
if ( !itemCount ) {
folderStackIndex = -1;
itemCount = 1;
selectable = false;
}
else selectable = true;
updatePhase = 0;
lastItemIndex = 0;
drawItemLockout = false;
}
// Count the number of files on the SD card
static uint8_t fileCount;
uint8_t SDMenu::countFiles() {
fileCount = 0;
// First, reset the directory index
if ( sdcard::directoryReset() != sdcard::SD_SUCCESS )
// TODO: Report
return 0;
char fnbuf[3];
// Count the files
do {
bool isdir;
sdcard::directoryNextEntry(fnbuf,sizeof(fnbuf),&isdir);
if ( fnbuf[0] == 0 )
return fileCount;
// Count .. and anyfile which doesn't begin with .
else if ( (fnbuf[0] != '.') ||
( isdir && fnbuf[1] == '.' && fnbuf[2] == 0) )
fileCount++;
} while (true);
// Never reached
return fileCount;
}
bool SDMenu::getFilename(uint8_t index, char buffer[], uint8_t buffer_size, bool *isdir) {
*isdir = false;
// First, reset the directory list
if ( sdcard::directoryReset() != sdcard::SD_SUCCESS )
return false;
bool my_isdir;
#ifdef REVERSE_SD_FILES
// Reverse order the files in hopes of listing the newer files first
// HOWEVER, with wrap around on the LCD menu, this isn't too useful
index = (fileCount - 1) - index;
#endif
for(uint8_t i = 0; i < index+1; i++) {
do {
sdcard::directoryNextEntry(buffer, buffer_size, &my_isdir);
if ( buffer[0] == 0 )
// No more files
return false;
// Count only .. and any file not beginning with .
if ( (buffer[0] != '.' ) ||
( my_isdir && buffer[1] == '.' && buffer[2] == 0) )
break;
} while (true);
}
*isdir = my_isdir;
return true;
}
void SDMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
uint8_t idx, filenameLength;
uint8_t longFilenameOffset = 0;
uint8_t displayWidth = lcd.getDisplayWidth() - 1;
uint8_t offset = 1;
char fnbuf[SD_MAXFILELEN+2]; // extra +1 as we may precede the name with a folder indicator
bool isdir;
if ( !selectable || index > itemCount - 1 )
return;
if ( !getFilename(index, fnbuf + 1, sizeof(fnbuf) - 1, &isdir) ) {
selectable = false;
return;
}
if ( isdir )
{
fnbuf[0] = ( fnbuf[1] == '.' && fnbuf[2] == '.' ) ? LCD_CUSTOM_CHAR_RETURN : LCD_CUSTOM_CHAR_FOLDER;
offset = 0;
}
//Figure out length of filename
for (filenameLength = 0; (filenameLength < sizeof(fnbuf)) && (fnbuf[offset+filenameLength] != 0); filenameLength++) ;
//Support scrolling filenames that are longer than the lcd screen
if (filenameLength >= displayWidth) longFilenameOffset = updatePhase % (filenameLength - displayWidth + 1);
for (idx = 0; (idx < displayWidth) && ((longFilenameOffset + idx) < sizeof(fnbuf)) &&
(fnbuf[offset+longFilenameOffset + idx] != 0); idx++)
lcd.write(fnbuf[offset+longFilenameOffset + idx]);
//Clear out the rest of the line
while ( idx < displayWidth ) {
lcd.write(' ');
idx ++;
}
return;
}
void SDMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
uint8_t height = lcd.getDisplayHeight();
if (( ! forceRedraw ) && ( ! drawItemLockout )) {
//Redraw the last item if we have changed
if (((itemIndex/height) == (lastDrawIndex/height)) &&
( itemIndex != lastItemIndex )) {
lcd.setCursor(1,lastItemIndex % height);
drawItem(lastItemIndex, lcd);
}
lastItemIndex = itemIndex;
lcd.setCursor(1,itemIndex % height);
drawItem(itemIndex, lcd);
}
if ( selectable ) {
Menu::update(lcd, forceRedraw);
updatePhase ++;
}
else {
// This was actually triggered in drawItem() but popping a screen
// from there is not a good idea
timedMessage(lcd, 0);
interface::popScreen();
}
}
void SDMenu::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( button == ButtonArray::XMINUS && folderStackIndex >= 0 )
SDMenu::handleSelect(0);
else {
updatePhase = 0;
Menu::notifyButtonPressed(button);
}
}
void SDMenu::handleSelect(uint8_t index) {
if (host::getHostState() != host::HOST_STATE_READY || !selectable)
// TODO: report error
return;
drawItemLockout = true;
char fnbuf[SD_MAXFILELEN+1];
bool isdir;
if ( !getFilename(index, fnbuf, sizeof(fnbuf), &isdir) )
goto badness;
if ( isdir ) {
// Attempt to change the directory
if ( !sdcard::changeDirectory(fnbuf) )
goto badness;
// Find our way around this folder
// Doing a resetState() will determine the new itemCount
resetState();
itemIndex = 0;
// If we're not selectable, don't bother
if ( selectable ) {
// Recall last itemIndex in this folder if we popped up
if ( fnbuf[0] != '.' || fnbuf[1] != '.' || fnbuf[2] != 0 ) {
// We've moved down into a child folder
if ( folderStackIndex < (int8_t)(sizeof(folderStack) - 1) )
folderStack[++folderStackIndex] = index;
}
else {
// We've moved up into our parent folder
if ( folderStackIndex >= 0 ) {
itemIndex = folderStack[folderStackIndex--];
if (itemIndex >= itemCount) {
// Something is wrong; invalidate the entire stack
itemIndex = 0;
folderStackIndex = -1;
}
}
}
}
// Repaint the display
// Really ensure that the entire screen is wiped
lastDrawIndex = index; // so that the old cursor can be cleared
Menu::update(Motherboard::getBoard().getInterfaceBoard().lcd, true);
return;
}
if ( host::startBuildFromSD(fnbuf) == sdcard::SD_SUCCESS )
return;
badness:
// TODO: report error
interface::pushScreen(&unableToOpenFileMenu);
}
void ValueSetScreen::reset() {
value = eeprom::getEeprom8(location, default_value);
}
void ValueSetScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(message1);
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeInt(value,3);
if ( units ) lcd.writeFromPgmspace(units);
}
void ValueSetScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t*)location,value);
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (value <= 249) {
value += 5;
}
break;
case ButtonArray::ZMINUS:
// decrement more
if (value >= 6) {
value -= 5;
}
break;
case ButtonArray::YPLUS:
// increment less
if (value <= 253) {
value += 1;
}
break;
case ButtonArray::YMINUS:
// decrement less
if (value >= 2) {
value -= 1;
}
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
PreheatMenu::PreheatMenu() {
itemCount = 4;
reset();
}
void PreheatMenu::fetchTargetTemps() {
OutPacket responsePacket;
uint8_t activeToolhead;
steppers::getStepperPosition(&activeToolhead);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0)) {
tool0Temp = responsePacket.read16(1);
}
if (extruderControl(activeToolhead, SLAVE_CMD_GET_PLATFORM_SP, EXTDR_CMD_GET, responsePacket, 0)) {
platformTemp = responsePacket.read16(1);
}
}
void PreheatMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar ph_heat[] = "Heat ";
const static PROGMEM prog_uchar ph_cool[] = "Cool ";
const static PROGMEM prog_uchar ph_tool0[] = "Tool0";
const static PROGMEM prog_uchar ph_platform[] = "Bed";
const static PROGMEM prog_uchar ph_tool0set[] = "Set Tool0 Temp";
const static PROGMEM prog_uchar ph_platset[] = "Set Bed Temp";
switch (index) {
case 0:
fetchTargetTemps();
if (tool0Temp > 0) {
lcd.writeFromPgmspace(LOCALIZE(ph_cool));
} else {
lcd.writeFromPgmspace(LOCALIZE(ph_heat));
}
lcd.writeFromPgmspace(LOCALIZE(ph_tool0));
break;
case 1:
if (platformTemp > 0) {
lcd.writeFromPgmspace(LOCALIZE(ph_cool));
} else {
lcd.writeFromPgmspace(LOCALIZE(ph_heat));
}
lcd.writeFromPgmspace(LOCALIZE(ph_platform));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(ph_tool0set));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(ph_platset));
break;
}
}
void PreheatMenu::handleSelect(uint8_t index) {
static const PROGMEM prog_uchar ph_message1[] = "Tool0 Targ Temp:";
const static PROGMEM prog_uchar ph_message2[] = "Bed Target Temp:";
uint8_t activeToolhead;
steppers::getStepperPosition(&activeToolhead);
OutPacket responsePacket;
switch (index) {
case 0:
// Toggle Extruder heater on/off
if (tool0Temp > 0) {
extruderControl(activeToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, 0);
} else {
uint8_t value = eeprom::getEeprom8(eeprom::TOOL0_TEMP, EEPROM_DEFAULT_TOOL0_TEMP);
extruderControl(activeToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)value);
}
fetchTargetTemps();
lastDrawIndex = 255; // forces redraw.
break;
case 1:
// Toggle Platform heater on/off
if (platformTemp > 0) {
extruderControl(0, SLAVE_CMD_SET_PLATFORM_TEMP, EXTDR_CMD_SET, responsePacket, 0);
} else {
uint8_t value = eeprom::getEeprom8(eeprom::PLATFORM_TEMP, EEPROM_DEFAULT_PLATFORM_TEMP);
extruderControl(0, SLAVE_CMD_SET_PLATFORM_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)value);
}
fetchTargetTemps();
lastDrawIndex = 255; // forces redraw.
break;
case 2:
// Show Extruder Temperature Setting Screen
heaterTempSetScreen.location = eeprom::TOOL0_TEMP;
heaterTempSetScreen.default_value = EEPROM_DEFAULT_TOOL0_TEMP;
heaterTempSetScreen.message1 = LOCALIZE(ph_message1);
heaterTempSetScreen.units = NULL;
interface::pushScreen(&heaterTempSetScreen);
break;
case 3:
// Show Platform Temperature Setting Screen
heaterTempSetScreen.location = eeprom::PLATFORM_TEMP;
heaterTempSetScreen.default_value = EEPROM_DEFAULT_PLATFORM_TEMP;
heaterTempSetScreen.message1 = LOCALIZE(ph_message2);
heaterTempSetScreen.units = NULL;
interface::pushScreen(&heaterTempSetScreen);
break;
}
}
void HomeAxisMode::reset() {
}
void HomeAxisMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ha_home1[] = "Home Axis: ";
const static PROGMEM prog_uchar ha_home2[] = " Y Z";
const static PROGMEM prog_uchar ha_home3[] = "X X (endstops)";
const static PROGMEM prog_uchar ha_home4[] = " Y Z";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ha_home1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(ha_home2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(ha_home3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(ha_home4));
}
}
void HomeAxisMode::home(ButtonArray::ButtonName direction) {
uint8_t axis = 0, axisIndex = 0;
bool maximums = false;
uint8_t endstops = eeprom::getEeprom8(eeprom::ENDSTOPS_USED, EEPROM_DEFAULT_ENDSTOPS_USED);
switch(direction) {
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
axis = 0x01;
if ( endstops & 0x02 ) maximums = true;
if ( endstops & 0x01 ) maximums = false;
axisIndex = 0;
break;
case ButtonArray::YMINUS:
case ButtonArray::YPLUS:
axis = 0x02;
if ( endstops & 0x08 ) maximums = true;
if ( endstops & 0x04 ) maximums = false;
axisIndex = 1;
break;
case ButtonArray::ZMINUS:
case ButtonArray::ZPLUS:
axis = 0x04;
if ( endstops & 0x20 ) maximums = true;
if ( endstops & 0x10 ) maximums = false;
axisIndex = 2;
break;
default:
break;
}
//60.0, because feed rate is in mm/min units, we convert to seconds
float feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_X + (axisIndex * sizeof(uint32_t)), 500) / 60.0;
float stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, (enum AxisEnum)axisIndex);
int32_t interval = (int32_t)(1000000.0 / stepsPerSecond);
steppers::startHoming(maximums, axis, (uint32_t)interval);
}
void HomeAxisMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
#if 0
case ButtonArray::YMINUS:
case ButtonArray::ZMINUS:
case ButtonArray::YPLUS:
case ButtonArray::ZPLUS:
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
#else
default:
#endif
home(button);
break;
case ButtonArray::ZERO:
case ButtonArray::OK:
interface::pushScreen(&endStopConfigScreen);
break;
case ButtonArray::CANCEL:
steppers::abort();
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
interface::popScreen();
break;
}
}
EnabledDisabledMenu::EnabledDisabledMenu() {
itemCount = 4;
reset();
}
void EnabledDisabledMenu::resetState() {
setupTitle();
if ( isEnabled() ) itemIndex = 3;
else itemIndex = 2;
firstItemIndex = 2;
}
void EnabledDisabledMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const prog_uchar *msg;
switch (index) {
default: return;
case 0: msg = msg1; break;
case 1: msg = msg2; break;
case 2: msg = LOCALIZE(generic_off); break;
case 3: msg = LOCALIZE(generic_on); break;
}
if (msg) lcd.writeFromPgmspace(msg);
}
void EnabledDisabledMenu::handleSelect(uint8_t index) {
if ( index == 2 ) enable(false);
if ( index == 3 ) enable(true);
interface::popScreen();
}
bool SteppersMenu::isEnabled() {
for ( uint8_t j = 0; j < STEPPER_COUNT; j++ )
if ( stepperAxisIsEnabled(j) )
return true;
return false;
}
void SteppersMenu::enable(bool enabled) {
for ( uint8_t j = 0; j < STEPPER_COUNT; j++ )
steppers::enableAxis(j, enabled);
}
void SteppersMenu::setupTitle() {
const static PROGMEM prog_uchar step_msg1[] = "Stepper Motors:";
msg1 = LOCALIZE(step_msg1);
msg2 = 0;
}
void TestEndStopsMode::reset() {
#ifdef PSTOP_SUPPORT
pstop = eeprom::getEeprom8(eeprom::PSTOP_ENABLE,
EEPROM_DEFAULT_PSTOP_ENABLE);
#endif
}
void TestEndStopsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar tes_test1[] = "Test End Stops: ";
const static PROGMEM prog_uchar tes_test2[] = "XMin:N XMax:N";
#ifdef PSTOP_SUPPORT
const static PROGMEM prog_uchar tes_test2a[] = "XMin:N PStop:N";
#endif
const static PROGMEM prog_uchar tes_test3[] = "YMin:N YMax:N";
const static PROGMEM prog_uchar tes_test4[] = "ZMin:N ZMax:N";
const static PROGMEM prog_uchar tes_strY[] = "Y";
const static PROGMEM prog_uchar tes_strN[] = "N";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(tes_test1));
lcd.setRow(1);
#ifdef PSTOP_SUPPORT
lcd.writeFromPgmspace(pstop ? LOCALIZE(tes_test2a) : LOCALIZE(tes_test2));
#else
lcd.writeFromPgmspace(LOCALIZE(tes_test2));
#endif
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(tes_test3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(tes_test4));
}
lcd.setCursor(5, 1);
if ( stepperAxisIsAtMinimum(0) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(15, 1);
#ifdef PSTOP_SUPPORT
if ( (pstop && (PSTOP_PORT.getValue() == 0)) || (!pstop && stepperAxisIsAtMaximum(0)) )
lcd.writeFromPgmspace(LOCALIZE(tes_strY));
#else
if ( stepperAxisIsAtMaximum(0) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
#endif
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(5, 2);
if ( stepperAxisIsAtMinimum(1) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(15, 2);
if ( stepperAxisIsAtMaximum(1) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(5, 3);
if ( stepperAxisIsAtMinimum(2) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(15, 3);
if ( stepperAxisIsAtMaximum(2) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
}
void TestEndStopsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
// That above list is exhaustive
interface::popScreen();
}
void PauseMode::reset() {
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
lastPauseState = PAUSE_STATE_NONE;
userViewMode = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS) & 0x01;
}
void PauseMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar p_waitForCurrentCommand[] = "Entering pause..";
const static PROGMEM prog_uchar p_retractFilament[] = "Retract filament";
const static PROGMEM prog_uchar p_clearingBuild[] = "Clearing build..";
const static PROGMEM prog_uchar p_heating[] = "Heating... ";
const static PROGMEM prog_uchar p_leavingPaused[] = "Leaving pause...";
const static PROGMEM prog_uchar p_paused1[] = "Paused(";
const static PROGMEM prog_uchar p_paused2[] = " Y+ Z+";
const static PROGMEM prog_uchar p_paused3[] = "X- Rev X+ (Fwd)";
const static PROGMEM prog_uchar p_paused4[] = " Y- Z-";
const static PROGMEM prog_uchar p_close[] = "):";
const static PROGMEM prog_uchar p_cancel1[] = "SD card error";
const static PROGMEM prog_uchar p_cancel2[] = "Build cancelled";
const static PROGMEM prog_uchar p_cancel3[] = "Press any button";
const static PROGMEM prog_uchar p_cancel4[] = "to continue ";
enum PauseState pauseState = command::pauseState();
if ( forceRedraw || ( lastPauseState != pauseState) )
lcd.clear();
OutPacket responsePacket;
lcd.homeCursor();
bool foo = false;
switch ( pauseState ) {
case PAUSE_STATE_ENTER_START_PIPELINE_DRAIN:
case PAUSE_STATE_ENTER_WAIT_PIPELINE_DRAIN:
lcd.writeFromPgmspace(LOCALIZE(p_waitForCurrentCommand));
foo = true;
break;
case PAUSE_STATE_ENTER_START_RETRACT_FILAMENT:
case PAUSE_STATE_ENTER_WAIT_RETRACT_FILAMENT:
lcd.writeFromPgmspace(LOCALIZE(p_retractFilament));
foo = true;
break;
case PAUSE_STATE_ENTER_START_CLEARING_PLATFORM:
case PAUSE_STATE_ENTER_WAIT_CLEARING_PLATFORM:
lcd.writeFromPgmspace(LOCALIZE(p_clearingBuild));
foo = true;
break;
case PAUSE_STATE_PAUSED:
lcd.writeFromPgmspace(LOCALIZE(p_paused1));
lcd.writeFloat(stepperAxisStepsToMM(command::getPausedPosition()[Z_AXIS], Z_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(p_close));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(p_paused2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(p_paused3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(p_paused4));
break;
case PAUSE_STATE_EXIT_START_HEATERS:
case PAUSE_STATE_EXIT_WAIT_FOR_HEATERS:
lcd.writeFromPgmspace(LOCALIZE(p_heating));
break;
case PAUSE_STATE_EXIT_START_RETURNING_PLATFORM:
case PAUSE_STATE_EXIT_WAIT_RETURNING_PLATFORM:
case PAUSE_STATE_EXIT_START_UNRETRACT_FILAMENT:
case PAUSE_STATE_EXIT_WAIT_UNRETRACT_FILAMENT:
lcd.writeFromPgmspace(LOCALIZE(p_leavingPaused));
break;
case PAUSE_STATE_ERROR:
{
const prog_uchar *msg = command::pauseGetErrorMessage();
if ( !msg ) msg = LOCALIZE(p_cancel1);
lcd.writeFromPgmspace(msg);
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(p_cancel2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(p_cancel3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(p_cancel4));
break;
}
case PAUSE_STATE_NONE:
//Pop off the pause screen and the menu underneath to return to the monitor screen
interface::popScreen();
if ( autoPause == 1 ) interface::popScreen();
if ( autoPause == 2 ) interface::popScreen();
break;
}
if ( foo ) {
const prog_uchar *msg = command::pauseGetErrorMessage();
if ( msg ) {
lcd.setRow(1);
lcd.writeFromPgmspace(msg);
}
}
if ( lastDirectionButtonPressed ) {
if ( interface::isButtonPressed(lastDirectionButtonPressed) )
jog(lastDirectionButtonPressed, true);
else {
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
steppers::abort();
}
}
lastPauseState = pauseState;
}
void PauseMode::notifyButtonPressed(ButtonArray::ButtonName button) {
enum PauseState ps = command::pauseState();
if ( ps == PAUSE_STATE_PAUSED ) {
if ( button == ButtonArray::CANCEL )
// setting for second argument doesn't matter here as this cancels a pause
host::pauseBuild(false, 0);
else
jog(button, true);
}
else if ( ps == PAUSE_STATE_ERROR ) {
autoPause = 2;
command::pauseClearError(); // changes pause state to PAUSE_STATE_NONE
}
}
void PauseAtZPosScreen::reset() {
int32_t currentPause = command::getPauseAtZPos();
if ( currentPause == 0 ) {
Point position = steppers::getPlannerPosition();
pauseAtZPos = stepperAxisStepsToMM(position[2], Z_AXIS);
} else pauseAtZPos = stepperAxisStepsToMM(currentPause, Z_AXIS);
}
void PauseAtZPosScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar pz_message1[] = "Pause at ZPos:";
const static PROGMEM prog_uchar pz_mm[] = "mm ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(pz_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeFloat((float)pauseAtZPos, 3);
lcd.writeFromPgmspace(LOCALIZE(pz_mm));
}
void PauseAtZPosScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
default :
return;
case ButtonArray::OK:
//Set the pause
command::pauseAtZPos(stepperAxisMMToSteps(pauseAtZPos, Z_AXIS));
// FALL THROUGH
case ButtonArray::CANCEL:
interface::popScreen();
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (pauseAtZPos <= 250) pauseAtZPos += 1.0;
break;
case ButtonArray::ZMINUS:
// decrement more
if (pauseAtZPos >= 1.0) pauseAtZPos -= 1.0;
else pauseAtZPos = 0.0;
break;
case ButtonArray::YPLUS:
// increment less
if (pauseAtZPos <= 254) pauseAtZPos += 0.05;
break;
case ButtonArray::YMINUS:
// decrement less
if (pauseAtZPos >= 0.05) pauseAtZPos -= 0.05;
else pauseAtZPos = 0.0;
break;
}
if ( pauseAtZPos < 0.001 ) pauseAtZPos = 0.0;
}
void ChangeTempScreen::reset() {
// Make getTemp() think that a toolhead change has occurred
activeToolhead = 255;
altTemp = 0;
getTemp();
}
void ChangeTempScreen::getTemp() {
uint8_t at;
steppers::getStepperPosition(&at);
if ( at != activeToolhead ) {
activeToolhead = at;
altTemp = command::altTemp[activeToolhead];
if ( altTemp == 0 ) {
// Get the current set point
OutPacket responsePacket;
if ( extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0) ) {
altTemp = responsePacket.read16(1);
}
else {
// Cannot get the current set point.... Use pre-heat temp?
if ( activeToolhead == 0 )
altTemp = (uint16_t)eeprom::getEeprom8(eeprom::TOOL0_TEMP, EEPROM_DEFAULT_TOOL0_TEMP);
else
altTemp = (uint16_t)eeprom::getEeprom8(eeprom::TOOL1_TEMP, EEPROM_DEFAULT_TOOL1_TEMP);
}
}
if ( altTemp > (uint16_t)MAX_TEMP ) altTemp = MAX_TEMP;
}
}
void ChangeTempScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ct_message1[] = "Extruder temp:";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ct_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Since the print is still running, the active tool head may have changed
getTemp();
// Redraw tool info
lcd.setRow(1);
lcd.writeInt(altTemp, 3);
lcd.write('C');
}
void ChangeTempScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
// We change the actual steppers::speedFactor so that
// the user can see the change dynamically (after making it through
// the queue of planned blocks)
int16_t temp = (int16_t)(0x7fff & altTemp);
switch (button) {
case ButtonArray::OK:
{
OutPacket responsePacket;
// Set the temp
command::altTemp[activeToolhead] = altTemp;
// Only set the temp if the heater is active
if ( extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0) ) {
uint16_t data = responsePacket.read16(1);
if ( data != 0 )
extruderControl(activeToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)altTemp);
}
#ifdef DITTO_PRINT
if ( command::dittoPrinting ) {
uint8_t otherToolhead = activeToolhead ? 0 : 1;
command::altTemp[otherToolhead] = altTemp;
if ( extruderControl(otherToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0) ) {
uint16_t data = responsePacket.read16(1);
if ( data != 0 )
extruderControl(otherToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)altTemp);
}
}
#endif
}
// FALL THROUGH
case ButtonArray::CANCEL:
interface::popScreen();
interface::popScreen();
return;
case ButtonArray::ZPLUS:
// increment more
temp += 5;
break;
case ButtonArray::ZMINUS:
// decrement more
temp -= 5;
break;
case ButtonArray::YPLUS:
// increment less
temp += 1;
break;
case ButtonArray::YMINUS:
// decrement less
temp -= 1;
break;
default :
return;
}
if (temp > MAX_TEMP ) altTemp = MAX_TEMP;
else if ( temp < 0 ) altTemp = 0;
else altTemp = (uint16_t)(0x7fff & temp);
}
void ChangeSpeedScreen::reset() {
// So that we can restore the speed in case of a CANCEL
speedFactor = steppers::speedFactor;
alterSpeed = steppers::alterSpeed;
}
void ChangeSpeedScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar cs_message1[] = "Increase speed:";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(cs_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.write('x');
lcd.writeFloat(FPTOF(steppers::speedFactor), 2);
}
void ChangeSpeedScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
// We change the actual steppers::speedFactor so that
// the user can see the change dynamically (after making it through
// the queue of planned blocks)
FPTYPE sf = steppers::speedFactor;
switch (button) {
case ButtonArray::CANCEL:
// restore the original
steppers::alterSpeed = alterSpeed;
steppers::speedFactor = speedFactor;
// FALL THROUGH
case ButtonArray::OK:
interface::popScreen();
interface::popScreen();
return;
case ButtonArray::ZPLUS:
// increment more
sf += KCONSTANT_0_25;
break;
case ButtonArray::ZMINUS:
// decrement more
sf -= KCONSTANT_0_25;
break;
case ButtonArray::YPLUS:
// increment less
sf += KCONSTANT_0_05;
break;
case ButtonArray::YMINUS:
// decrement less
sf -= KCONSTANT_0_05;
break;
default :
return;
}
if ( sf > KCONSTANT_5 ) sf = KCONSTANT_5;
else if ( sf < KCONSTANT_0_1 ) sf = KCONSTANT_0_1;
// If sf == 1 then disable speedup
steppers::alterSpeed = (sf == KCONSTANT_1) ? 0x00 : 0x80;
steppers::speedFactor = sf;
}
void AdvanceABPMode::reset() {
abpForwarding = false;
}
void AdvanceABPMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar abp_msg1[] = "Advance ABP:";
const static PROGMEM prog_uchar abp_msg2[] = "hold key...";
const static PROGMEM prog_uchar abp_msg3[] = " (fwd)";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(abp_msg1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(abp_msg2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(abp_msg3));
}
if (( abpForwarding ) && ( ! interface::isButtonPressed(ButtonArray::OK) )) {
OutPacket responsePacket;
abpForwarding = false;
extruderControl(0, SLAVE_CMD_TOGGLE_ABP, EXTDR_CMD_SET8, responsePacket, (uint16_t)0);
}
}
void AdvanceABPMode::notifyButtonPressed(ButtonArray::ButtonName button) {
OutPacket responsePacket;
switch (button) {
case ButtonArray::OK:
abpForwarding = true;
extruderControl(0, SLAVE_CMD_TOGGLE_ABP, EXTDR_CMD_SET8, responsePacket, (uint16_t)1);
break;
default :
interface::popScreen();
break;
}
}
void CalibrateMode::reset() {
//Disable stepps on axis 0, 1, 2, 3, 4
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
steppers::enableAxis(3, false);
steppers::enableAxis(4, false);
lastCalibrationState = CS_NONE;
calibrationState = CS_START1;
}
void CalibrateMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar c_calib1[] = "Calibrate: Move ";
const static PROGMEM prog_uchar c_calib2[] = "build platform";
const static PROGMEM prog_uchar c_calib3[] = "until nozzle...";
const static PROGMEM prog_uchar c_calib4[] = " (cont)";
const static PROGMEM prog_uchar c_calib5[] = "lies in center,";
const static PROGMEM prog_uchar c_calib6[] = "turn threaded";
const static PROGMEM prog_uchar c_calib7[] = "rod until...";
const static PROGMEM prog_uchar c_calib8[] = "nozzle just";
const static PROGMEM prog_uchar c_calib9[] = "touches.";
const static PROGMEM prog_uchar c_homeZ[] = "Homing Z...";
const static PROGMEM prog_uchar c_homeY[] = "Homing Y...";
const static PROGMEM prog_uchar c_homeX[] = "Homing X...";
const static PROGMEM prog_uchar c_done[] = "! Calibrated !";
const static PROGMEM prog_uchar c_regen[] = "Regenerate gcode";
const static PROGMEM prog_uchar c_reset[] = " (reset)";
if ((forceRedraw) || (calibrationState != lastCalibrationState)) {
lcd.clearHomeCursor();
switch(calibrationState) {
case CS_START1:
lcd.writeFromPgmspace(LOCALIZE(c_calib1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_calib2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(c_calib3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_calib4));
break;
case CS_START2:
lcd.writeFromPgmspace(LOCALIZE(c_calib5));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_calib6));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(c_calib7));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_calib4));
break;
case CS_PROMPT_MOVE:
lcd.writeFromPgmspace(LOCALIZE(c_calib8));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_calib9));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_calib4));
break;
case CS_HOME_Z:
case CS_HOME_Z_WAIT:
lcd.writeFromPgmspace(LOCALIZE(c_homeZ));
break;
case CS_HOME_Y:
case CS_HOME_Y_WAIT:
lcd.writeFromPgmspace(LOCALIZE(c_homeY));
break;
case CS_HOME_X:
case CS_HOME_X_WAIT:
lcd.writeFromPgmspace(LOCALIZE(c_homeX));
break;
case CS_PROMPT_CALIBRATED:
lcd.writeFromPgmspace(LOCALIZE(c_done));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_regen));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_reset));
break;
default:
break;
}
}
lastCalibrationState = calibrationState;
//Change the state
//Some states are changed when a button is pressed via notifyButton
//Some states are changed when something completes, in which case we do it here
float interval = 2000.0;
bool maximums = false;
uint8_t endstops = eeprom::getEeprom8(eeprom::ENDSTOPS_USED, EEPROM_DEFAULT_ENDSTOPS_USED);
float feedRate, stepsPerSecond;
switch(calibrationState) {
case CS_HOME_Z:
//Declare current position to be x=0, y=0, z=0, a=0, b=0
steppers::definePosition(Point(0,0,0,0,0), false);
interval *= stepperAxisStepsToMM((int32_t)200.0, Z_AXIS); //Use ToM as baseline
if ( endstops & 0x20 ) maximums = true;
if ( endstops & 0x10 ) maximums = false;
feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Z, EEPROM_DEFAULT_HOMING_FEED_RATE_Z) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, Z_AXIS);
interval = 1000000.0 / stepsPerSecond;
steppers::startHoming(maximums, 0x04, (uint32_t)interval);
calibrationState = CS_HOME_Z_WAIT;
break;
case CS_HOME_Z_WAIT:
if ( ! steppers::isHoming() ) calibrationState = CS_HOME_Y;
break;
case CS_HOME_Y:
interval *= stepperAxisStepsToMM((int32_t)47.06, Y_AXIS); //Use ToM as baseline
if ( endstops & 0x08 ) maximums = true;
if ( endstops & 0x04 ) maximums = false;
feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Y, EEPROM_DEFAULT_HOMING_FEED_RATE_Y) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, Y_AXIS);
interval = 1000000.0 / stepsPerSecond;
steppers::startHoming(maximums, 0x02, (uint32_t)interval);
calibrationState = CS_HOME_Y_WAIT;
break;
case CS_HOME_Y_WAIT:
if ( ! steppers::isHoming() ) calibrationState = CS_HOME_X;
break;
case CS_HOME_X:
interval *= stepperAxisStepsToMM((int32_t)47.06, X_AXIS); //Use ToM as baseline
if ( endstops & 0x02 ) maximums = true;
if ( endstops & 0x01 ) maximums = false;
feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_X, EEPROM_DEFAULT_HOMING_FEED_RATE_X) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, X_AXIS);
interval = 1000000.0 / stepsPerSecond;
steppers::startHoming(maximums, 0x01, (uint32_t)interval);
calibrationState = CS_HOME_X_WAIT;
break;
case CS_HOME_X_WAIT:
if ( ! steppers::isHoming() ) {
//Record current X, Y, Z, A, B co-ordinates to the motherboard
for (uint8_t i = 0; i < STEPPER_COUNT; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*i;
uint32_t position = steppers::getStepperPosition()[i];
cli();
eeprom_write_block(&position, (void*) offset, 4);
sei();
}
//Disable stepps on axis 0, 1, 2, 3, 4
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
steppers::enableAxis(3, false);
steppers::enableAxis(4, false);
calibrationState = CS_PROMPT_CALIBRATED;
}
break;
default:
break;
}
}
void CalibrateMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( calibrationState == CS_PROMPT_CALIBRATED ) {
host::stopBuildNow();
return;
}
switch (button) {
default:
if (( calibrationState == CS_START1 ) || ( calibrationState == CS_START2 ) ||
(calibrationState == CS_PROMPT_MOVE )) calibrationState = (enum calibrateState)((uint8_t)calibrationState + 1);
break;
case ButtonArray::CANCEL:
interface::popScreen();
break;
}
}
void HomeOffsetsMode::reset() {
homePosition = steppers::getStepperPosition();
for (uint8_t i = 0; i < STEPPER_COUNT; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*i;
cli();
eeprom_read_block(&(homePosition[i]), (void*) offset, 4);
sei();
}
lastHomeOffsetState = HOS_NONE;
homeOffsetState = HOS_OFFSET_X;
}
void HomeOffsetsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ho_message1x[] = "X Offset:";
const static PROGMEM prog_uchar ho_message1y[] = "Y Offset:";
const static PROGMEM prog_uchar ho_message1z[] = "Z Offset:";
if ( homeOffsetState != lastHomeOffsetState ) forceRedraw = true;
if (forceRedraw) {
lcd.clearHomeCursor();
switch(homeOffsetState) {
case HOS_OFFSET_X:
lcd.writeFromPgmspace(LOCALIZE(ho_message1x));
break;
case HOS_OFFSET_Y:
lcd.writeFromPgmspace(LOCALIZE(ho_message1y));
break;
case HOS_OFFSET_Z:
lcd.writeFromPgmspace(LOCALIZE(ho_message1z));
break;
default:
break;
}
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
float position = 0.0;
switch(homeOffsetState) {
case HOS_OFFSET_X:
position = stepperAxisStepsToMM(homePosition[0], X_AXIS);
break;
case HOS_OFFSET_Y:
position = stepperAxisStepsToMM(homePosition[1], Y_AXIS);
break;
case HOS_OFFSET_Z:
position = stepperAxisStepsToMM(homePosition[2], Z_AXIS);
break;
default:
break;
}
lcd.setRow(1);
lcd.writeFloat((float)position, 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lastHomeOffsetState = homeOffsetState;
}
void HomeOffsetsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if (( homeOffsetState == HOS_OFFSET_Z ) && (button == ButtonArray::OK )) {
//Write the new home positions
for (uint8_t i = 0; i < STEPPER_COUNT; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*i;
uint32_t position = homePosition[i];
cli();
eeprom_write_block(&position, (void*) offset, 4);
sei();
}
host::stopBuildNow();
return;
}
uint8_t currentIndex = homeOffsetState - HOS_OFFSET_X;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
if ( homeOffsetState == HOS_OFFSET_X ) homeOffsetState = HOS_OFFSET_Y;
else if ( homeOffsetState == HOS_OFFSET_Y ) homeOffsetState = HOS_OFFSET_Z;
break;
case ButtonArray::ZPLUS:
// increment more
homePosition[currentIndex] += 20;
break;
case ButtonArray::ZMINUS:
// decrement more
homePosition[currentIndex] -= 20;
break;
case ButtonArray::YPLUS:
// increment less
homePosition[currentIndex] += 1;
break;
case ButtonArray::YMINUS:
// decrement less
homePosition[currentIndex] -= 1;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
void BuzzerSetRepeatsMode::reset() {
repeats = eeprom::getEeprom8(eeprom::BUZZER_REPEATS, EEPROM_DEFAULT_BUZZER_REPEATS);
}
void BuzzerSetRepeatsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar bsr_message1[] = "Repeat Buzzer:";
const static PROGMEM prog_uchar bsr_message2[] = "(0=Buzzer Off)";
const static PROGMEM prog_uchar bsr_times[] = " times ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(bsr_message1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(bsr_message2));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(2);
lcd.writeInt(repeats, 3);
lcd.writeFromPgmspace(LOCALIZE(bsr_times));
}
void BuzzerSetRepeatsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t *)eeprom::BUZZER_REPEATS, repeats);
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (repeats <= 249) repeats += 5;
break;
case ButtonArray::ZMINUS:
// decrement more
if (repeats >= 5) repeats -= 5;
break;
case ButtonArray::YPLUS:
// increment less
if (repeats <= 253) repeats += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if (repeats >= 1) repeats -= 1;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
bool ExtruderFanMenu::isEnabled() {
//Should really check the current status of the fan here
return false;
}
void ExtruderFanMenu::enable(bool enabled) {
OutPacket responsePacket;
extruderControl(0, SLAVE_CMD_TOGGLE_FAN, EXTDR_CMD_SET, responsePacket, (uint16_t)((enabled)?1:0));
}
void ExtruderFanMenu::setupTitle() {
static const PROGMEM prog_uchar ext_msg1[] = "Extruder Fan:";
static const PROGMEM prog_uchar ext_msg2[] = "";
msg1 = LOCALIZE(ext_msg1);
msg2 = LOCALIZE(ext_msg2);
}
FilamentUsedResetMenu::FilamentUsedResetMenu() {
itemCount = 4;
reset();
}
void FilamentUsedResetMenu::resetState() {
itemIndex = 2;
firstItemIndex = 2;
}
void FilamentUsedResetMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar fur_msg[] = "Reset To Zero?";
const static PROGMEM prog_uchar fur_no[] = "No";
const static PROGMEM prog_uchar fur_yes[] = "Yes";
switch (index) {
case 0:
lcd.writeFromPgmspace(LOCALIZE(fur_msg));
break;
case 1:
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(fur_no));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(fur_yes));
break;
}
}
void FilamentUsedResetMenu::handleSelect(uint8_t index) {
switch (index) {
case 3:
//Reset to zero
eeprom::putEepromInt64(eeprom::FILAMENT_LIFETIME_A, EEPROM_DEFAULT_FILAMENT_LIFETIME);
eeprom::putEepromInt64(eeprom::FILAMENT_LIFETIME_B, EEPROM_DEFAULT_FILAMENT_LIFETIME);
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_A, EEPROM_DEFAULT_FILAMENT_TRIP);
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_B, EEPROM_DEFAULT_FILAMENT_TRIP);
case 2:
interface::popScreen();
interface::popScreen();
break;
}
}
void FilamentUsedMode::reset() {
lifetimeDisplay = true;
overrideForceRedraw = false;
}
void FilamentUsedMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar fu_lifetime[] = "Lifetime Odo.:";
const static PROGMEM prog_uchar fu_trip[] = "Trip Odometer:";
const static PROGMEM prog_uchar fu_but_life[] = "(trip) (reset)";
const static PROGMEM prog_uchar fu_but_trip[] = "(life) (reset)";
if ((forceRedraw) || (overrideForceRedraw)) {
lcd.clearHomeCursor();
if ( lifetimeDisplay ) lcd.writeFromPgmspace(LOCALIZE(fu_lifetime));
else lcd.writeFromPgmspace(LOCALIZE(fu_trip));
int64_t filamentUsedA = eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_A, EEPROM_DEFAULT_FILAMENT_LIFETIME);
int64_t filamentUsedB = eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_B, EEPROM_DEFAULT_FILAMENT_LIFETIME);
if ( ! lifetimeDisplay ) {
int64_t tripA = eeprom::getEepromInt64(eeprom::FILAMENT_TRIP_A, EEPROM_DEFAULT_FILAMENT_TRIP);
int64_t tripB = eeprom::getEepromInt64(eeprom::FILAMENT_TRIP_B, EEPROM_DEFAULT_FILAMENT_TRIP);
filamentUsedA = filamentUsedA - tripA;
filamentUsedB = filamentUsedB - tripB;
}
float filamentUsedMMA = stepperAxisStepsToMM(filamentUsedA, A_AXIS);
#if EXTRUDERS > 1
float filamentUsedMMB = stepperAxisStepsToMM(filamentUsedB, B_AXIS);
#else
float filamentUsedMMB = 0.0f;
#endif
float filamentUsedMM = filamentUsedMMA + filamentUsedMMB;
lcd.setRow(1);
lcd.writeFloat(filamentUsedMM / 1000.0, 4);
lcd.write('m');
lcd.setRow(2);
if ( lifetimeDisplay ) lcd.writeFromPgmspace(LOCALIZE(fu_but_life));
else lcd.writeFromPgmspace(LOCALIZE(fu_but_trip));
lcd.setRow(3);
lcd.writeFloat(((filamentUsedMM / 25.4) / 12.0), 4);
lcd.writeString((char *)"ft");
overrideForceRedraw = false;
}
}
void FilamentUsedMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
lifetimeDisplay ^= true;
overrideForceRedraw = true;
break;
case ButtonArray::OK:
if ( lifetimeDisplay )
interface::pushScreen(&filamentUsedResetMenu);
else {
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_A, eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_A, EEPROM_DEFAULT_FILAMENT_LIFETIME));
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_B, eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_B, EEPROM_DEFAULT_FILAMENT_LIFETIME));
interface::popScreen();
}
break;
default:
break;
}
}
BuildSettingsMenu::BuildSettingsMenu() {
itemCount = 5;
reset();
}
void BuildSettingsMenu::resetState() {
acceleration = 1 == (eeprom::getEeprom8(eeprom::ACCELERATION_ON, EEPROM_DEFAULT_ACCELERATION_ON) & 0x01);
itemCount = acceleration ? 8 : 7;
#ifdef PSTOP_SUPPORT
itemCount++;
#endif
itemIndex = 0;
firstItemIndex = 0;
genericOnOff_msg1 = 0;
genericOnOff_msg2 = 0;
genericOnOff_msg3 = LOCALIZE(generic_off);
genericOnOff_msg4 = LOCALIZE(generic_on);
}
void BuildSettingsMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar bs_item0[] = "Override Temp";
const static PROGMEM prog_uchar bs_item1[] = "Ditto Print";
const static PROGMEM prog_uchar bs_item2[] = "Accel. On/Off";
const static PROGMEM prog_uchar bs_item3[] = "Accel. Settings";
const static PROGMEM prog_uchar bs_item4[] = "Extruder Hold";
const static PROGMEM prog_uchar bs_item5[] = "Toolhead System";
const static PROGMEM prog_uchar bs_item6[] = "SD Err Checking";
const static PROGMEM prog_uchar bs_item7[] = "ABP Copies (SD)";
const static PROGMEM prog_uchar bs_item8[] = "Pause Stop";
if ( !acceleration && index > 2 ) ++index;
const prog_uchar *msg;
switch (index) {
default:
return;
case 0:
msg = LOCALIZE(bs_item0);
break;
case 1:
msg = LOCALIZE(bs_item1);
break;
case 2:
msg = LOCALIZE(bs_item2);
break;
case 3:
msg = LOCALIZE(bs_item3);
break;
case 4:
msg = LOCALIZE(bs_item4);
break;
case 5:
msg = LOCALIZE(bs_item5);
break;
case 6:
msg = LOCALIZE(bs_item6);
break;
case 7:
msg = LOCALIZE(bs_item7);
break;
#ifdef PSTOP_SUPPORT
case 8:
msg = LOCALIZE(bs_item8);
break;
#endif
}
lcd.writeFromPgmspace(msg);
}
void BuildSettingsMenu::handleSelect(uint8_t index) {
OutPacket responsePacket;
if ( !acceleration && index > 2 ) ++index;
genericOnOff_msg2 = 0;
genericOnOff_msg3 = LOCALIZE(generic_off);
genericOnOff_msg4 = LOCALIZE(generic_on);
switch (index) {
case 0:
//Override the gcode temperature
genericOnOff_offset = eeprom::OVERRIDE_GCODE_TEMP;
genericOnOff_default = EEPROM_DEFAULT_OVERRIDE_GCODE_TEMP;
genericOnOff_msg1 = LOCALIZE(ogct_msg1);
genericOnOff_msg2 = LOCALIZE(ogct_msg2);
break;
case 1:
//Ditto Print
genericOnOff_offset = eeprom::DITTO_PRINT_ENABLED;
genericOnOff_default = EEPROM_DEFAULT_DITTO_PRINT_ENABLED;
genericOnOff_msg1 = LOCALIZE(dp_msg1);
break;
case 2:
//Acceleraton On/Off Menu
genericOnOff_offset = eeprom::ACCELERATION_ON;
genericOnOff_default = EEPROM_DEFAULT_ACCELERATION_ON;
genericOnOff_msg1 = LOCALIZE(aof_msg1);
genericOnOff_msg2 = LOCALIZE(aof_msg2);
break;
case 3:
interface::pushScreen(&acceleratedSettingsMode);
return;
case 4:
//Extruder Hold
genericOnOff_offset = eeprom::EXTRUDER_HOLD;
genericOnOff_default = EEPROM_DEFAULT_EXTRUDER_HOLD;
genericOnOff_msg1 = LOCALIZE(eof_msg1);
break;
case 5:
//Toolhead System
genericOnOff_offset = eeprom::TOOLHEAD_OFFSET_SYSTEM;
genericOnOff_default = EEPROM_DEFAULT_TOOLHEAD_OFFSET_SYSTEM;
genericOnOff_msg1 = LOCALIZE(ts_msg1);
genericOnOff_msg2 = LOCALIZE(ts_msg2);
genericOnOff_msg3 = LOCALIZE(ts_old);
genericOnOff_msg4 = LOCALIZE(ts_new);
break;
case 6:
// SD card error checking
genericOnOff_offset = eeprom::SD_USE_CRC;
genericOnOff_default = EEPROM_DEFAULT_SD_USE_CRC;
genericOnOff_msg1 = LOCALIZE(sdcrc_msg1);
genericOnOff_msg2 = LOCALIZE(sdcrc_msg2);
break;
case 7:
//Change number of ABP copies
interface::pushScreen(&abpCopiesSetScreen);
return;
#ifdef PSTOP_SUPPORT
case 8:
// Enable|disable the P-Stop
genericOnOff_offset = eeprom::PSTOP_ENABLE;
genericOnOff_default = EEPROM_DEFAULT_PSTOP_ENABLE;
genericOnOff_msg1 = LOCALIZE(pstop_msg1);
break;
#endif
}
interface::pushScreen(&genericOnOffMenu);
}
void ABPCopiesSetScreen::reset() {
value = eeprom::getEeprom8(eeprom::ABP_COPIES, EEPROM_DEFAULT_ABP_COPIES);
if ( value < 1 ) {
eeprom_write_byte((uint8_t*)eeprom::ABP_COPIES,EEPROM_DEFAULT_ABP_COPIES);
value = eeprom::getEeprom8(eeprom::ABP_COPIES, EEPROM_DEFAULT_ABP_COPIES); //Just in case
}
}
void ABPCopiesSetScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar abp_message1[] = "ABP Copies (SD):";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(abp_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeInt(value,3);
}
void ABPCopiesSetScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t*)eeprom::ABP_COPIES,value);
interface::popScreen();
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (value <= 249) {
value += 5;
}
break;
case ButtonArray::ZMINUS:
// decrement more
if (value >= 6) {
value -= 5;
}
break;
case ButtonArray::YPLUS:
// increment less
if (value <= 253) {
value += 1;
}
break;
case ButtonArray::YMINUS:
// decrement less
if (value >= 2) {
value -= 1;
}
break;
default:
break;
}
}
GenericOnOffMenu::GenericOnOffMenu() {
itemCount = 4;
reset();
}
void GenericOnOffMenu::resetState() {
uint8_t val = eeprom::getEeprom8(genericOnOff_offset, genericOnOff_default);
bool state = (genericOnOff_offset == eeprom::SD_USE_CRC) ? (val == 1) : (val != 0);
itemIndex = state ? 3 : 2;
firstItemIndex = 2;
}
void GenericOnOffMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const prog_uchar *msg;
switch (index) {
default :
return;
case 0:
msg = genericOnOff_msg1;
break;
case 1:
msg = genericOnOff_msg2;
break;
case 2:
msg = genericOnOff_msg3;
break;
case 3:
msg = genericOnOff_msg4;
break;
}
if (msg) lcd.writeFromPgmspace(msg);
}
void GenericOnOffMenu::handleSelect(uint8_t index) {
uint8_t oldValue = (eeprom::getEeprom8(genericOnOff_offset, genericOnOff_default)) != 0;
uint8_t newValue = oldValue;
switch (index) {
default:
return;
case 2:
newValue = 0x00;
break;
case 3:
newValue = 0x01;
break;
}
interface::popScreen();
//If the value has changed, do a reset
if ( newValue != oldValue ) {
cli();
eeprom_write_byte((uint8_t*)genericOnOff_offset, newValue);
sei();
//Reset
#ifndef BROKEN_SD
if ( genericOnOff_offset == eeprom::SD_USE_CRC )
sdcard::mustReinit = true;
else
#endif
host::stopBuildNow();
}
}
#define NUM_PROFILES 4
#define PROFILES_SAVED_AXIS 3
void writeProfileToEeprom(uint8_t pIndex, uint8_t *pName, int32_t homeX,
int32_t homeY, int32_t homeZ, uint8_t hbpTemp,
uint8_t tool0Temp, uint8_t tool1Temp, uint8_t extruderMMS) {
uint16_t offset = eeprom::PROFILE_BASE + (uint16_t)pIndex * PROFILE_NEXT_OFFSET;
cli();
//Write profile name
if ( pName ) eeprom_write_block(pName,(uint8_t*)offset, PROFILE_NAME_LENGTH);
offset += PROFILE_NAME_LENGTH;
//Write home axis
eeprom_write_block(&homeX, (void*) offset, 4); offset += 4;
eeprom_write_block(&homeY, (void*) offset, 4); offset += 4;
eeprom_write_block(&homeZ, (void*) offset, 4); offset += 4;
//Write temps and extruder MMS
eeprom_write_byte((uint8_t *)offset, hbpTemp); offset += 1;
eeprom_write_byte((uint8_t *)offset, tool0Temp); offset += 1;
eeprom_write_byte((uint8_t *)offset, tool1Temp); offset += 1;
eeprom_write_byte((uint8_t *)offset, extruderMMS); offset += 1;
sei();
}
void readProfileFromEeprom(uint8_t pIndex, uint8_t *pName, int32_t *homeX,
int32_t *homeY, int32_t *homeZ, uint8_t *hbpTemp,
uint8_t *tool0Temp, uint8_t *tool1Temp, uint8_t *extruderMMS) {
uint16_t offset = eeprom::PROFILE_BASE + (uint16_t)pIndex * PROFILE_NEXT_OFFSET;
cli();
//Read profile name
if ( pName ) eeprom_read_block(pName,(uint8_t*)offset, PROFILE_NAME_LENGTH);
offset += PROFILE_NAME_LENGTH;
//Write home axis
eeprom_read_block(homeX, (void*) offset, 4); offset += 4;
eeprom_read_block(homeY, (void*) offset, 4); offset += 4;
eeprom_read_block(homeZ, (void*) offset, 4); offset += 4;
//Write temps and extruder MMS
*hbpTemp = eeprom_read_byte((uint8_t *)offset); offset += 1;
*tool0Temp = eeprom_read_byte((uint8_t *)offset); offset += 1;
*tool1Temp = eeprom_read_byte((uint8_t *)offset); offset += 1;
*extruderMMS = eeprom_read_byte((uint8_t *)offset); offset += 1;
sei();
}
//buf should have length PROFILE_NAME_LENGTH + 1
void getProfileName(uint8_t pIndex, uint8_t *buf) {
uint16_t offset = eeprom::PROFILE_BASE + PROFILE_NEXT_OFFSET * (uint16_t)pIndex;
cli();
eeprom_read_block(buf,(void *)offset,PROFILE_NAME_LENGTH);
sei();
buf[PROFILE_NAME_LENGTH] = '\0';
}
#define NAME_CHAR_LOWER_LIMIT 32
#define NAME_CHAR_UPPER_LIMIT 126
bool isValidProfileName(uint8_t pIndex) {
uint8_t buf[PROFILE_NAME_LENGTH + 1];
getProfileName(pIndex, buf);
for ( uint8_t i = 0; i < PROFILE_NAME_LENGTH; i ++ ) {
if (( buf[i] < NAME_CHAR_LOWER_LIMIT ) || ( buf[i] > NAME_CHAR_UPPER_LIMIT ) || ( buf[i] == 0xff )) return false;
}
return true;
}
ProfilesMenu::ProfilesMenu() {
itemCount = NUM_PROFILES;
reset();
//Setup defaults if required
//If the value is 0xff, write the profile number
uint8_t buf[PROFILE_NAME_LENGTH+1];
const static PROGMEM prog_uchar pro_defaultProfile[] = "Profile?";
//Get the home axis positions, we may need this to write the defaults
homePosition = steppers::getStepperPosition();
for (uint8_t i = 0; i < PROFILES_SAVED_AXIS; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*(uint16_t)i;
cli();
eeprom_read_block(&homePosition[i], (void*)offset, 4);
sei();
}
for (int p = 0; p < NUM_PROFILES; p ++ ) {
if ( ! isValidProfileName(p)) {
//Create the default profile name
for( uint8_t i = 0; i < PROFILE_NAME_LENGTH; i ++ )
buf[i] = pgm_read_byte_near(pro_defaultProfile+i);
buf[PROFILE_NAME_LENGTH - 1] = '1' + p;
//Write the defaults
writeProfileToEeprom(p, buf, homePosition[0], homePosition[1], homePosition[2],
100, 210, 210, 19);
}
}
}
void ProfilesMenu::resetState() {
firstItemIndex = 0;
itemIndex = 0;
}
void ProfilesMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
uint8_t buf[PROFILE_NAME_LENGTH + 1];
getProfileName(index, buf);
lcd.writeString((char *)buf);
}
void ProfilesMenu::handleSelect(uint8_t index) {
profileSubMenu.profileIndex = index;
interface::pushScreen(&profileSubMenu);
}
ProfileSubMenu::ProfileSubMenu() {
itemCount = 4;
reset();
}
void ProfileSubMenu::resetState() {
itemIndex = 0;
firstItemIndex = 0;
}
void ProfileSubMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar ps_msg1[] = "Restore";
const static PROGMEM prog_uchar ps_msg2[] = "Display Config";
const static PROGMEM prog_uchar ps_msg3[] = "Change Name";
const static PROGMEM prog_uchar ps_msg4[] = "Save To Profile";
switch (index) {
case 0:
lcd.writeFromPgmspace(LOCALIZE(ps_msg1));
break;
case 1:
lcd.writeFromPgmspace(LOCALIZE(ps_msg2));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(ps_msg3));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(ps_msg4));
break;
}
}
void ProfileSubMenu::handleSelect(uint8_t index) {
uint8_t hbpTemp, tool0Temp, tool1Temp, extruderMMS;
switch (index) {
case 0:
//Restore
//Read settings from eeprom
readProfileFromEeprom(profileIndex, NULL, &homePosition[0], &homePosition[1], &homePosition[2],
&hbpTemp, &tool0Temp, &tool1Temp, &extruderMMS);
//Write out the home offsets
for (uint8_t i = 0; i < PROFILES_SAVED_AXIS; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*(uint16_t)i;
cli();
eeprom_write_block(&homePosition[i], (void*)offset, 4);
sei();
}
cli();
eeprom_write_byte((uint8_t *)eeprom::PLATFORM_TEMP, hbpTemp);
eeprom_write_byte((uint8_t *)eeprom::TOOL0_TEMP, tool0Temp);
eeprom_write_byte((uint8_t *)eeprom::TOOL1_TEMP, tool1Temp);
eeprom_write_byte((uint8_t *)eeprom::EXTRUDE_MMS, extruderMMS);
sei();
interface::popScreen();
interface::popScreen();
//Reset
host::stopBuildNow();
break;
case 1:
//Display settings
profileDisplaySettingsMenu.profileIndex = profileIndex;
interface::pushScreen(&profileDisplaySettingsMenu);
break;
case 2:
//Change Profile Name
profileChangeNameMode.profileIndex = profileIndex;
interface::pushScreen(&profileChangeNameMode);
break;
case 3: //Save To Profile
//Get the home axis positions
homePosition = steppers::getStepperPosition();
for (uint8_t i = 0; i < PROFILES_SAVED_AXIS; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*(uint16_t)i;
cli();
eeprom_read_block(&homePosition[i], (void*)offset, 4);
sei();
}
hbpTemp = eeprom::getEeprom8(eeprom::PLATFORM_TEMP, EEPROM_DEFAULT_PLATFORM_TEMP);
tool0Temp = eeprom::getEeprom8(eeprom::TOOL0_TEMP, EEPROM_DEFAULT_TOOL0_TEMP);
tool1Temp = eeprom::getEeprom8(eeprom::TOOL1_TEMP, EEPROM_DEFAULT_TOOL1_TEMP);
extruderMMS = eeprom::getEeprom8(eeprom::EXTRUDE_MMS, EEPROM_DEFAULT_EXTRUDE_MMS);
writeProfileToEeprom(profileIndex, NULL, homePosition[0], homePosition[1], homePosition[2],
hbpTemp, tool0Temp, tool1Temp, extruderMMS);
interface::popScreen();
break;
}
}
void ProfileChangeNameMode::reset() {
cursorLocation = 0;
getProfileName(profileIndex, profileName);
}
void ProfileChangeNameMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar pcn_message1[] = "Profile Name:";
const static PROGMEM prog_uchar pcn_blank[] = " ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(pcn_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
lcd.setRow(1);
lcd.writeString((char *)profileName);
//Draw the cursor
lcd.setCursor(cursorLocation,2);
lcd.write('^');
//Write a blank before and after the cursor if we're not at the ends
if ( cursorLocation >= 1 ) {
lcd.setCursor(cursorLocation-1, 2);
lcd.writeFromPgmspace(LOCALIZE(pcn_blank));
}
if ( cursorLocation < PROFILE_NAME_LENGTH ) {
lcd.setCursor(cursorLocation+1, 2);
lcd.writeFromPgmspace(LOCALIZE(pcn_blank));
}
}
void ProfileChangeNameMode::notifyButtonPressed(ButtonArray::ButtonName button) {
uint16_t offset;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
//Write the profile name
offset = eeprom::PROFILE_BASE + (uint16_t)profileIndex * PROFILE_NEXT_OFFSET;
cli();
eeprom_write_block(profileName,(uint8_t*)offset, PROFILE_NAME_LENGTH);
sei();
interface::popScreen();
break;
case ButtonArray::YPLUS:
profileName[cursorLocation] += 1;
break;
case ButtonArray::ZPLUS:
profileName[cursorLocation] += 5;
break;
case ButtonArray::YMINUS:
profileName[cursorLocation] -= 1;
break;
case ButtonArray::ZMINUS:
profileName[cursorLocation] -= 5;
break;
case ButtonArray::XMINUS:
if ( cursorLocation > 0 ) cursorLocation --;
break;
case ButtonArray::XPLUS:
if ( cursorLocation < (PROFILE_NAME_LENGTH-1) ) cursorLocation ++;
break;
}
//Hard limits
if ( profileName[cursorLocation] < NAME_CHAR_LOWER_LIMIT ) profileName[cursorLocation] = NAME_CHAR_LOWER_LIMIT;
if ( profileName[cursorLocation] > NAME_CHAR_UPPER_LIMIT ) profileName[cursorLocation] = NAME_CHAR_UPPER_LIMIT;
}
ProfileDisplaySettingsMenu::ProfileDisplaySettingsMenu() {
itemCount = 8;
reset();
}
void ProfileDisplaySettingsMenu::resetState() {
readProfileFromEeprom(profileIndex, profileName, &homeX, &homeY, &homeZ,
&hbpTemp, &tool0Temp, &tool1Temp, &extruderMMS);
itemIndex = 2;
firstItemIndex = 2;
}
void ProfileDisplaySettingsMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar pds_xOffset[] = "XOff: ";
const static PROGMEM prog_uchar pds_yOffset[] = "YOff: ";
const static PROGMEM prog_uchar pds_zOffset[] = "ZOff: ";
const static PROGMEM prog_uchar pds_hbp[] = "HBP Temp: ";
const static PROGMEM prog_uchar pds_tool0[] = "Tool0 Temp: ";
const static PROGMEM prog_uchar pds_extruder[] = "ExtrdrMM/s: ";
switch (index) {
case 0:
lcd.writeString((char *)profileName);
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(pds_xOffset));
lcd.writeFloat(stepperAxisStepsToMM(homeX, X_AXIS), 3);
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(pds_yOffset));
lcd.writeFloat(stepperAxisStepsToMM(homeY, Y_AXIS), 3);
break;
case 4:
lcd.writeFromPgmspace(LOCALIZE(pds_zOffset));
lcd.writeFloat(stepperAxisStepsToMM(homeZ, Z_AXIS), 3);
break;
case 5:
lcd.writeFromPgmspace(LOCALIZE(pds_hbp));
lcd.writeFloat((float)hbpTemp, 0);
break;
case 6:
lcd.writeFromPgmspace(LOCALIZE(pds_tool0));
lcd.writeFloat((float)tool0Temp, 0);
break;
case 7:
lcd.writeFromPgmspace(LOCALIZE(pds_extruder));
lcd.writeFloat((float)extruderMMS, 0);
break;
}
}
void ProfileDisplaySettingsMenu::handleSelect(uint8_t index) {
}
void CurrentPositionMode::reset() {
}
void CurrentPositionMode::update(LiquidCrystal& lcd, bool forceRedraw) {
uint8_t active_toolhead;
Point position = steppers::getStepperPosition(&active_toolhead);
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.write('X');
lcd.setRow(1);
lcd.write('Y');
lcd.setRow(2);
lcd.write('Z');
lcd.setRow(3);
lcd.write('A' + active_toolhead);
}
lcd.write(':');
lcd.setCursor(3, 0);
lcd.writeFloat(stepperAxisStepsToMM(position[0], X_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lcd.setCursor(3, 1);
lcd.writeFloat(stepperAxisStepsToMM(position[1], Y_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lcd.setCursor(3, 2);
lcd.writeFloat(stepperAxisStepsToMM(position[2], Z_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lcd.setCursor(3, 3);
lcd.writeFloat(stepperAxisStepsToMM(position[3 + active_toolhead], A_AXIS + active_toolhead), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
}
void CurrentPositionMode::notifyButtonPressed(ButtonArray::ButtonName button) {
interface::popScreen();
}
//Unable to open file, filename too long?
UnableToOpenFileMenu::UnableToOpenFileMenu() {
itemCount = 4;
reset();
}
void UnableToOpenFileMenu::resetState() {
itemIndex = 3;
firstItemIndex = 3;
}
void UnableToOpenFileMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar utof_msg1[] = "Failed to open";
const static PROGMEM prog_uchar utof_msg2[] = "file or folder.";
const static PROGMEM prog_uchar utof_msg3[] = "Name too long?";
const static PROGMEM prog_uchar utof_cont[] = "Continue";
switch (index) {
case 0:
lcd.writeFromPgmspace(LOCALIZE(utof_msg1));
break;
case 1:
lcd.writeFromPgmspace(LOCALIZE(utof_msg2));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(utof_msg3));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(utof_cont));
break;
}
}
void UnableToOpenFileMenu::handleSelect(uint8_t index) {
interface::popScreen();
}
void AcceleratedSettingsMode::reset() {
cli();
values[0] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_X, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_X);
values[1] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Y, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_Y);
values[2] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Z, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_Z);
values[3] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_A, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_A);
values[4] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_B, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_B);
// values[5] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_NORM, EEPROM_DEFAULT_ACCEL_MAX_EXTRUDER_NORM);
// values[6] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_RETRACT, EEPROM_DEFAULT_ACCEL_MAX_EXTRUDER_RETRACT);
values[5] = eeprom::getEepromUInt32(eeprom::ACCEL_ADVANCE_K, EEPROM_DEFAULT_ACCEL_ADVANCE_K);
values[6] = eeprom::getEepromUInt32(eeprom::ACCEL_ADVANCE_K2, EEPROM_DEFAULT_ACCEL_ADVANCE_K2);
values[7] = eeprom::getEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_A, EEPROM_DEFAULT_ACCEL_EXTRUDER_DEPRIME_A);
values[8] = eeprom::getEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_B, EEPROM_DEFAULT_ACCEL_EXTRUDER_DEPRIME_B);
values[9] = (uint32_t)(eeprom::getEeprom8(eeprom::ACCEL_SLOWDOWN_FLAG, EEPROM_DEFAULT_ACCEL_SLOWDOWN_FLAG)) ? 1 : 0;
values[10] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_X, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_X);
values[11] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Y, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_Y);
values[12] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Z, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_Z);
values[13] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_A, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_A);
values[14] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_B, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_B);
sei();
lastAccelerateSettingsState= AS_NONE;
accelerateSettingsState= AS_MAX_ACCELERATION_X;
}
void AcceleratedSettingsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar as_message1xMaxAccelRate[] = "X Max Accel:";
const static PROGMEM prog_uchar as_message1yMaxAccelRate[] = "Y Max Accel:";
const static PROGMEM prog_uchar as_message1zMaxAccelRate[] = "Z Max Accel:";
const static PROGMEM prog_uchar as_message1aMaxAccelRate[] = "Right Max Accel:";
const static PROGMEM prog_uchar as_message1bMaxAccelRate[] = "Left Max Accel:";
// const static PROGMEM prog_uchar as_message1ExtruderNorm[] = "Max Accel:";
// const static PROGMEM prog_uchar as_message1ExtruderRetract[] = "Max Accel Extdr:";
const static PROGMEM prog_uchar as_message1AdvanceK[] = "JKN Advance K:";
const static PROGMEM prog_uchar as_message1AdvanceK2[] = "JKN Advance K2:";
const static PROGMEM prog_uchar as_message1ExtruderDeprimeA[] = "Extdr.DeprimeR:";
const static PROGMEM prog_uchar as_message1ExtruderDeprimeB[] = "Extdr.DeprimeL:";
const static PROGMEM prog_uchar as_message1SlowdownLimit[] = "SlowdownEnabled:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeX[] = "MaxSpeedChangeX:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeY[] = "MaxSpeedChangeY:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeZ[] = "MaxSpeedChangeZ:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeA[] = "MaxSpeedChangeR:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeB[] = "MaxSpeedChangeL:";
const static PROGMEM prog_uchar as_blank[] = " ";
if ( accelerateSettingsState != lastAccelerateSettingsState ) forceRedraw = true;
if (forceRedraw) {
lcd.clearHomeCursor();
const prog_uchar *msg;
switch(accelerateSettingsState) {
case AS_MAX_ACCELERATION_X:
msg = LOCALIZE(as_message1xMaxAccelRate);
break;
case AS_MAX_ACCELERATION_Y:
msg = LOCALIZE(as_message1yMaxAccelRate);
break;
case AS_MAX_ACCELERATION_Z:
msg = LOCALIZE(as_message1zMaxAccelRate);
break;
case AS_MAX_ACCELERATION_A:
msg = LOCALIZE(as_message1aMaxAccelRate);
break;
case AS_MAX_ACCELERATION_B:
msg = LOCALIZE(as_message1bMaxAccelRate);
break;
// case AS_MAX_EXTRUDER_NORM:
// msg = LOCALIZE(as_message1ExtruderNorm);
// break;
// case AS_MAX_EXTRUDER_RETRACT:
// msg = LOCALIZE(as_message1ExtruderRetract);
// break;
case AS_ADVANCE_K:
msg = LOCALIZE(as_message1AdvanceK);
break;
case AS_ADVANCE_K2:
msg = LOCALIZE(as_message1AdvanceK2);
break;
case AS_EXTRUDER_DEPRIME_A:
msg = LOCALIZE(as_message1ExtruderDeprimeA);
break;
case AS_EXTRUDER_DEPRIME_B:
msg = LOCALIZE(as_message1ExtruderDeprimeB);
break;
case AS_SLOWDOWN_FLAG:
msg = LOCALIZE(as_message1SlowdownLimit);
break;
case AS_MAX_SPEED_CHANGE_X:
msg = LOCALIZE(as_message1MaxSpeedChangeX);
break;
case AS_MAX_SPEED_CHANGE_Y:
msg = LOCALIZE(as_message1MaxSpeedChangeY);
break;
case AS_MAX_SPEED_CHANGE_Z:
msg = LOCALIZE(as_message1MaxSpeedChangeZ);
break;
case AS_MAX_SPEED_CHANGE_A:
msg = LOCALIZE(as_message1MaxSpeedChangeA);
break;
case AS_MAX_SPEED_CHANGE_B:
msg = LOCALIZE(as_message1MaxSpeedChangeB);
break;
default:
msg = 0;
break;
}
if ( msg ) lcd.writeFromPgmspace(msg);
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
uint32_t value = 0;
uint8_t currentIndex = accelerateSettingsState - AS_MAX_ACCELERATION_X;
value = values[currentIndex];
lcd.setRow(1);
switch(accelerateSettingsState) {
case AS_MAX_SPEED_CHANGE_X:
case AS_MAX_SPEED_CHANGE_Y:
case AS_MAX_SPEED_CHANGE_Z:
case AS_MAX_SPEED_CHANGE_A:
case AS_MAX_SPEED_CHANGE_B:
lcd.writeFloat((float)value / 10.0, 1);
break;
case AS_ADVANCE_K:
case AS_ADVANCE_K2:
lcd.writeFloat((float)value / 100000.0, 5);
break;
default:
lcd.writeFloat((float)value, 0);
break;
}
lcd.writeFromPgmspace(LOCALIZE(as_blank));
lastAccelerateSettingsState = accelerateSettingsState;
}
void AcceleratedSettingsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if (( accelerateSettingsState == AS_LAST_ENTRY ) && (button == ButtonArray::OK )) {
//Write the data
cli();
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_X, values[0]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Y, values[1]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Z, values[2]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_A, values[3]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_B, values[4]);
// eeprom::putEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_NORM, values[5]);
// eeprom::putEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_RETRACT, values[6]);
eeprom::putEepromUInt32(eeprom::ACCEL_ADVANCE_K, values[5]);
eeprom::putEepromUInt32(eeprom::ACCEL_ADVANCE_K2, values[6]);
eeprom::putEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_A, values[7]);
eeprom::putEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_B, values[8]);
eeprom_write_byte((uint8_t*)eeprom::ACCEL_SLOWDOWN_FLAG,(uint8_t)values[9]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_X, values[10]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Y, values[11]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Z, values[12]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_A, values[13]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_B, values[14]);
sei();
host::stopBuildNow();
return;
}
uint8_t currentIndex = accelerateSettingsState - AS_MAX_ACCELERATION_X;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
accelerateSettingsState = (enum accelerateSettingsState)((uint8_t)accelerateSettingsState + 1);
return;
break;
case ButtonArray::ZPLUS:
// increment more
values[currentIndex] += 100;
break;
case ButtonArray::ZMINUS:
// decrement more
values[currentIndex] -= 100;
break;
case ButtonArray::YPLUS:
// increment less
values[currentIndex] += 1;
break;
case ButtonArray::YMINUS:
// decrement less
values[currentIndex] -= 1;
break;
default:
break;
}
//Settings that allow a zero value
if (!(
( accelerateSettingsState == AS_ADVANCE_K ) || ( accelerateSettingsState == AS_ADVANCE_K2 ) ||
( accelerateSettingsState == AS_EXTRUDER_DEPRIME_A ) || ( accelerateSettingsState == AS_EXTRUDER_DEPRIME_B ) ||
( accelerateSettingsState == AS_SLOWDOWN_FLAG ))) {
if ( values[currentIndex] < 1 ) values[currentIndex] = 1;
}
if ( values[currentIndex] > 200000 ) values[currentIndex] = 1;
//Settings that have a maximum value
if (( accelerateSettingsState == AS_SLOWDOWN_FLAG ) && ( values[currentIndex] > 1))
values[currentIndex] = 1;
}
void EndStopConfigScreen::reset() {
endstops = eeprom::getEeprom8(eeprom::ENDSTOPS_USED, EEPROM_DEFAULT_ENDSTOPS_USED);
}
void EndStopConfigScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar esc_message1[] = "EndstopsPresent:";
const static PROGMEM prog_uchar esc_blank[] = " ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(esc_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeFloat((float)endstops, 0);
lcd.writeFromPgmspace(LOCALIZE(esc_blank));
}
void EndStopConfigScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t *)eeprom::ENDSTOPS_USED, endstops);
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (endstops <= 122) endstops += 5;
break;
case ButtonArray::ZMINUS:
// decrement more
if (endstops >= 5) endstops -= 5;
break;
case ButtonArray::YPLUS:
// increment less
if (endstops <= 126) endstops += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if (endstops >= 1) endstops -= 1;
break;
default:
break;
}
}
void HomingFeedRatesMode::reset() {
cli();
homingFeedRate[0] = eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_X, EEPROM_DEFAULT_HOMING_FEED_RATE_X);
homingFeedRate[1] = eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Y, EEPROM_DEFAULT_HOMING_FEED_RATE_Y);
homingFeedRate[2] = eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Z, EEPROM_DEFAULT_HOMING_FEED_RATE_Z);
sei();
lastHomingFeedRateState = HFRS_NONE;
homingFeedRateState = HFRS_OFFSET_X;
}
void HomingFeedRatesMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar hfr_message1x[] = "X Home Feedrate:";
const static PROGMEM prog_uchar hfr_message1y[] = "Y Home Feedrate:";
const static PROGMEM prog_uchar hfr_message1z[] = "Z Home Feedrate:";
const static PROGMEM prog_uchar hfr_mm[] = "mm/min ";
if ( homingFeedRateState != lastHomingFeedRateState ) forceRedraw = true;
if (forceRedraw) {
lcd.clearHomeCursor();
switch(homingFeedRateState) {
case HFRS_OFFSET_X:
lcd.writeFromPgmspace(LOCALIZE(hfr_message1x));
break;
case HFRS_OFFSET_Y:
lcd.writeFromPgmspace(LOCALIZE(hfr_message1y));
break;
case HFRS_OFFSET_Z:
lcd.writeFromPgmspace(LOCALIZE(hfr_message1z));
break;
default:
break;
}
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
float feedRate = 0.0;
switch(homingFeedRateState) {
case HFRS_OFFSET_X:
feedRate = homingFeedRate[0];
break;
case HFRS_OFFSET_Y:
feedRate = homingFeedRate[1];
break;
case HFRS_OFFSET_Z:
feedRate = homingFeedRate[2];
break;
default:
break;
}
lcd.setRow(1);
lcd.writeFloat((float)feedRate, 0);
lcd.writeFromPgmspace(LOCALIZE(hfr_mm));
lastHomingFeedRateState = homingFeedRateState;
}
void HomingFeedRatesMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if (( homingFeedRateState == HFRS_OFFSET_Z ) && (button == ButtonArray::OK )) {
//Write the new homing feed rates
cli();
eeprom::putEepromUInt32(eeprom::HOMING_FEED_RATE_X, homingFeedRate[0]);
eeprom::putEepromUInt32(eeprom::HOMING_FEED_RATE_Y, homingFeedRate[1]);
eeprom::putEepromUInt32(eeprom::HOMING_FEED_RATE_Z, homingFeedRate[2]);
sei();
interface::popScreen();
}
uint8_t currentIndex = homingFeedRateState - HFRS_OFFSET_X;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
if ( homingFeedRateState == HFRS_OFFSET_X ) homingFeedRateState = HFRS_OFFSET_Y;
else if ( homingFeedRateState == HFRS_OFFSET_Y ) homingFeedRateState = HFRS_OFFSET_Z;
break;
case ButtonArray::ZPLUS:
// increment more
homingFeedRate[currentIndex] += 20;
break;
case ButtonArray::ZMINUS:
// decrement more
if ( homingFeedRate[currentIndex] >= 21 )
homingFeedRate[currentIndex] -= 20;
break;
case ButtonArray::YPLUS:
// increment less
homingFeedRate[currentIndex] += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if ( homingFeedRate[currentIndex] >= 2 )
homingFeedRate[currentIndex] -= 1;
break;
default:
break;
}
if (( homingFeedRate[currentIndex] < 1 ) || ( homingFeedRate[currentIndex] > 2000 ))
homingFeedRate[currentIndex] = 1;
}
#ifdef EEPROM_MENU_ENABLE
EepromMenu::EepromMenu() {
itemCount = 3;
reset();
}
void EepromMenu::resetState() {
itemIndex = 0;
firstItemIndex = 0;
safetyGuard = 0;
itemSelected = -1;
warningScreen = true;
}
void EepromMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
if ( warningScreen ) {
if ( forceRedraw ) {
const static PROGMEM prog_uchar eeprom_msg1[] = "This menu can";
const static PROGMEM prog_uchar eeprom_msg2[] = "make your bot";
const static PROGMEM prog_uchar eeprom_msg3[] = "inoperable.";
const static PROGMEM prog_uchar eeprom_msg4[] = "Press Y+ to cont";
lcd.homeCursor();
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg4));
}
}
else {
if ( itemSelected != -1 )
lcd.clearHomeCursor();
const static PROGMEM prog_uchar eeprom_message_dump[] = "Saving...";
const static PROGMEM prog_uchar eeprom_message_restore[] = "Restoring...";
switch ( itemSelected ) {
case 0: //Dump
//sdcard::forceReinit(); // to force return to / directory
if ( ! sdcard::fileExists(dumpFilename) ) {
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_dump));
if ( ! eeprom::saveToSDFile(dumpFilename) )
timedMessage(lcd, 1);
} else
timedMessage(lcd, 2);
interface::popScreen();
break;
case 1: //Restore
//sdcard::forceReinit(); // to return to root
if ( sdcard::fileExists(dumpFilename) ) {
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_restore));
if ( ! eeprom::restoreFromSDFile(dumpFilename) )
timedMessage(lcd, 3);
host::stopBuildNow();
} else {
timedMessage(lcd, 4);
interface::popScreen();
}
break;
case 2: //Erase
timedMessage(lcd, 5);
eeprom::erase();
interface::popScreen();
host::stopBuildNow();
break;
default:
Menu::update(lcd, forceRedraw);
break;
}
lcd.setRow(3);
if ( safetyGuard >= 1 ) {
const static PROGMEM prog_uchar eeprom_msg9[] = "* Press ";
const static PROGMEM prog_uchar eeprom_msg10[] = "x more!";
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg9));
lcd.writeInt((uint16_t)(4-safetyGuard),1);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg10));
} else {
const static PROGMEM prog_uchar eeprom_blank[] = " ";
lcd.writeFromPgmspace(LOCALIZE(eeprom_blank));
}
itemSelected = -1;
}
}
void EepromMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar e_message_dump[] = "EEPROM -> SD";
const static PROGMEM prog_uchar e_message_restore[] = "SD -> EEPROM";
const static PROGMEM prog_uchar e_message_erase[] = "Erase EEPROM";
switch (index)
{
case 0:
lcd.writeFromPgmspace(LOCALIZE(e_message_dump));
break;
case 1:
lcd.writeFromPgmspace(LOCALIZE(e_message_restore));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(e_message_erase));
break;
}
}
void EepromMenu::handleSelect(uint8_t index) {
switch (index)
{
case 0:
//Dump
safetyGuard = 0;
itemSelected = 0;
break;
case 1:
//Restore
safetyGuard ++;
if ( safetyGuard > 3 ) {
safetyGuard = 0;
itemSelected = 1;
}
break;
case 2:
//Erase
safetyGuard ++;
if ( safetyGuard > 3 ) {
safetyGuard = 0;
itemSelected = 2;
}
break;
}
}
void EepromMenu::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( warningScreen ) {
if ( button == ButtonArray::YPLUS )
warningScreen = false;
else
Menu::notifyButtonPressed(ButtonArray::CANCEL);
return;
}
if ( button == ButtonArray::YMINUS || button == ButtonArray::ZMINUS ||
button == ButtonArray::YPLUS || button == ButtonArray::ZPLUS )
safetyGuard = 0;
Menu::notifyButtonPressed(button);
}
#endif
// Clear the screen, display a message, and then count down from 5 to 0 seconds
// with a countdown timer to let folks know what's up
static void timedMessage(LiquidCrystal& lcd, uint8_t which)
{
const static PROGMEM prog_uchar sderr_badcard[] = "SD card error";
const static PROGMEM prog_uchar sderr_nofiles[] = "No files found";
const static PROGMEM prog_uchar sderr_nocard[] = "No SD card";
const static PROGMEM prog_uchar sderr_initfail[] = "Card init failed";
const static PROGMEM prog_uchar sderr_partition[] = "Bad partition";
const static PROGMEM prog_uchar sderr_filesys[] = "Is it FAT-16?";
const static PROGMEM prog_uchar sderr_noroot[] = "No root folder";
const static PROGMEM prog_uchar sderr_locked[] = "Read locked";
const static PROGMEM prog_uchar sderr_fnf[] = "File not found";
const static PROGMEM prog_uchar sderr_toobig[] = "Too big";
const static PROGMEM prog_uchar sderr_crcerr[] = "CRC error";
const static PROGMEM prog_uchar sderr_comms[] = "Comms failure";
const static PROGMEM prog_uchar eeprom_msg11[] = "Write Failed!";
const static PROGMEM prog_uchar eeprom_msg12[] = "File exists!";
const static PROGMEM prog_uchar eeprom_msg5[] = "Read Failed!";
const static PROGMEM prog_uchar eeprom_msg6[] = "EEPROM may be";
const static PROGMEM prog_uchar eeprom_msg7[] = "corrupt";
const static PROGMEM prog_uchar eeprom_msg8[] = "File not found!";
const static PROGMEM prog_uchar eeprom_message_erase[] = "Erasing...";
const static PROGMEM prog_uchar eeprom_message_error[] = "Error";
const static PROGMEM prog_uchar timed_message_clock[] = "00:00";
lcd.clearHomeCursor();
switch(which) {
case 0:
{
lcd.writeFromPgmspace(LOCALIZE(sderr_badcard));
const prog_uchar *msg = 0;
if ( sdcard::sdErrno == SDR_ERR_BADRESPONSE ||
sdcard::sdErrno == SDR_ERR_COMMS ||
sdcard::sdErrno == SDR_ERR_PATTERN ||
sdcard::sdErrno == SDR_ERR_VOLTAGE )
msg = LOCALIZE(sderr_comms);
else {
switch (sdcard::sdAvailable) {
case sdcard::SD_SUCCESS: msg = LOCALIZE(sderr_nofiles); break;
case sdcard::SD_ERR_NO_CARD_PRESENT: msg = LOCALIZE(sderr_nocard); break;
case sdcard::SD_ERR_INIT_FAILED: msg = LOCALIZE(sderr_initfail); break;
case sdcard::SD_ERR_PARTITION_READ: msg = LOCALIZE(sderr_partition); break;
case sdcard::SD_ERR_OPEN_FILESYSTEM: msg = LOCALIZE(sderr_filesys); break;
case sdcard::SD_ERR_NO_ROOT: msg = LOCALIZE(sderr_noroot); break;
case sdcard::SD_ERR_CARD_LOCKED: msg = LOCALIZE(sderr_locked); break;
case sdcard::SD_ERR_FILE_NOT_FOUND: msg = LOCALIZE(sderr_fnf); break;
case sdcard::SD_ERR_VOLUME_TOO_BIG: msg = LOCALIZE(sderr_toobig); break;
case sdcard::SD_ERR_CRC: msg = LOCALIZE(sderr_crcerr); break;
default:
case sdcard::SD_ERR_GENERIC:
break;
}
}
if ( msg ) {
lcd.setRow(1);
lcd.writeFromPgmspace(msg);
}
break;
}
case 1:
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg11));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_error));
lcd.setRow(1);
lcd.writeString((char *)dumpFilename);
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg12));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg5));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg6));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg7));
break;
case 4:
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_error));
lcd.setRow(1);
lcd.writeString((char *)dumpFilename);
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg8));
break;
case 5:
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_erase));
break;
}
lcd.setRow(3);
lcd.writeFromPgmspace(timed_message_clock);
for (uint8_t i = 0; i < 5; i++)
{
lcd.setCursor(4, 3);
lcd.write('5' - (char)i);
_delay_us(1000000);
}
}
#endif
| 28.864957
| 153
| 0.699448
|
togetherPeter
|
23930b18119937fc7644d72e096d087022e91ab1
| 864
|
cpp
|
C++
|
src/gfxtk/Buffer.cpp
|
NostalgicGhoul/gfxtk
|
6662d6d1b285e20806ecfef3cdcb620d6605e478
|
[
"BSD-2-Clause"
] | null | null | null |
src/gfxtk/Buffer.cpp
|
NostalgicGhoul/gfxtk
|
6662d6d1b285e20806ecfef3cdcb620d6605e478
|
[
"BSD-2-Clause"
] | null | null | null |
src/gfxtk/Buffer.cpp
|
NostalgicGhoul/gfxtk
|
6662d6d1b285e20806ecfef3cdcb620d6605e478
|
[
"BSD-2-Clause"
] | null | null | null |
#include "Buffer.hpp"
#ifdef GFXTK_GRAPHICS_BACKEND_VULKAN
#include <gfxtk/backend/vulkan/Buffer.hpp>
#elif GFXTK_GRAPHICS_BACKEND_METAL
#include <gfxtk/backend/metal/Buffer.hpp>
#else
#error target OS is not supported by any existing graphics backend!
#endif
gfxtk::Buffer gfxtk::Buffer::create(
std::shared_ptr<backend::Device> const& backendDevice,
size_t size,
gfxtk::BufferUsageFlags bufferUsageFlags,
gfxtk::MemoryUsage memoryUsage
) {
return Buffer(backend::Buffer::create(backendDevice, size, bufferUsageFlags, memoryUsage));
}
gfxtk::Buffer::Buffer(std::shared_ptr<backend::Buffer> backendBuffer)
: _backendBuffer(std::move(backendBuffer)) {}
gfxtk::Buffer::~Buffer() = default;
void* gfxtk::Buffer::map() {
return _backendBuffer->map();
}
void gfxtk::Buffer::unmap() {
_backendBuffer->unmap();
}
| 27
| 95
| 0.726852
|
NostalgicGhoul
|
2393d38d4a5a137d14b49a994ed5ea0b6f9fe7fa
| 2,091
|
hpp
|
C++
|
obs-studio/UI/window-basic-main-outputs.hpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
obs-studio/UI/window-basic-main-outputs.hpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
obs-studio/UI/window-basic-main-outputs.hpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
class OBSBasic;
struct BasicOutputHandler {
OBSOutputAutoRelease fileOutput;
OBSOutputAutoRelease streamOutput;
OBSOutputAutoRelease replayBuffer;
OBSOutputAutoRelease virtualCam;
bool streamingActive = false;
bool recordingActive = false;
bool delayActive = false;
bool replayBufferActive = false;
bool virtualCamActive = false;
OBSBasic *main;
std::string outputType;
std::string lastError;
std::string lastRecordingPath;
OBSSignal startRecording;
OBSSignal stopRecording;
OBSSignal startReplayBuffer;
OBSSignal stopReplayBuffer;
OBSSignal startStreaming;
OBSSignal stopStreaming;
OBSSignal startVirtualCam;
OBSSignal stopVirtualCam;
OBSSignal streamDelayStarting;
OBSSignal streamStopping;
OBSSignal recordStopping;
OBSSignal replayBufferStopping;
OBSSignal replayBufferSaved;
inline BasicOutputHandler(OBSBasic *main_);
virtual ~BasicOutputHandler(){};
virtual bool SetupStreaming(obs_service_t *service) = 0;
virtual bool StartStreaming(obs_service_t *service) = 0;
virtual bool StartRecording() = 0;
virtual bool StartReplayBuffer() { return false; }
virtual bool StartVirtualCam();
virtual void StopStreaming(bool force = false) = 0;
virtual void StopRecording(bool force = false) = 0;
virtual void StopReplayBuffer(bool force = false) { (void)force; }
virtual void StopVirtualCam();
virtual bool StreamingActive() const = 0;
virtual bool RecordingActive() const = 0;
virtual bool ReplayBufferActive() const { return false; }
virtual bool VirtualCamActive() const;
virtual void Update() = 0;
virtual void SetupOutputs() = 0;
inline bool Active() const
{
return streamingActive || recordingActive || delayActive ||
replayBufferActive || virtualCamActive;
}
protected:
void SetupAutoRemux(const char *&ext);
std::string GetRecordingFilename(const char *path, const char *ext,
bool noSpace, bool overwrite,
const char *format, bool ffmpeg);
};
BasicOutputHandler *CreateSimpleOutputHandler(OBSBasic *main);
BasicOutputHandler *CreateAdvancedOutputHandler(OBSBasic *main);
| 28.256757
| 68
| 0.780966
|
noelemahcz
|
239529e3a0656005ba014a4ca0e76a86b1b2136a
| 646
|
cpp
|
C++
|
mrJudge/problems/countfishes (197)/countfishes.cpp
|
object-oriented-human/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | 1
|
2022-02-21T15:43:01.000Z
|
2022-02-21T15:43:01.000Z
|
mrJudge/problems/countfishes (197)/countfishes.cpp
|
foooop/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | null | null | null |
mrJudge/problems/countfishes (197)/countfishes.cpp
|
foooop/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int tc, inf=1000001; cin >> tc;
vector<int> isprime(inf, 1), prefix(inf);
for (int i = 2; i*i < inf; i++) {
if (isprime[i]) {
for (int j = i*i; j < inf; j+= i) {
isprime[j] = 0;
}
}
}
prefix[0] = 0, prefix[1] = 0;
for (int i = 2; i < inf; i++) {
prefix[i] = prefix[i-1];
if (isprime[i]) {
prefix[i]++;
}
}
while (tc--) {
int p, q; cin >> p >> q;
cout << prefix[q] - prefix[p-1] << '\n';
}
}
| 21.533333
| 48
| 0.410217
|
object-oriented-human
|
239935d93d4706e23409398c03caf909a98d3cea
| 879
|
cpp
|
C++
|
atcoder/abc147c.cpp
|
sogapalag/problems
|
0ea7d65448e1177f8b3f81124a82d187980d659c
|
[
"MIT"
] | 1
|
2020-04-04T14:56:12.000Z
|
2020-04-04T14:56:12.000Z
|
atcoder/abc147c.cpp
|
sogapalag/problems
|
0ea7d65448e1177f8b3f81124a82d187980d659c
|
[
"MIT"
] | null | null | null |
atcoder/abc147c.cpp
|
sogapalag/problems
|
0ea7d65448e1177f8b3f81124a82d187980d659c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
vector<vector<pair<int,int>>> g(n);
for (int i = 0; i < n; i++) {
int m; cin >> m;
for (int _ = 0; _ < m; _++) {
int x, y;
cin >> x >> y;
x--;
g[i].emplace_back(x,y);
}
}
const int MSK = 1<<n;
int res = 0;
for (int msk = 0; msk < MSK; msk++) {
for (int i = 0; i < n; i++) {
if (msk & (1<<i)) {
for (auto& _: g[i]) {
int j, y;
tie(j, y) = _;
if (((msk>>j)&1) != y) goto end;
}
}
}
res = max(res, __builtin_popcount(msk));
end:;
}
cout << res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| 20.44186
| 52
| 0.366325
|
sogapalag
|
2399e24ba2dbf07647952ce82ee88f98e7b1095d
| 6,547
|
cpp
|
C++
|
src/structs.cpp
|
Algorithms-and-Data-Structures-2021/classwork-02-cpp-basics-demo
|
dccf30fd03a7ed4e8e68f85c395f786a643ea3db
|
[
"MIT"
] | null | null | null |
src/structs.cpp
|
Algorithms-and-Data-Structures-2021/classwork-02-cpp-basics-demo
|
dccf30fd03a7ed4e8e68f85c395f786a643ea3db
|
[
"MIT"
] | null | null | null |
src/structs.cpp
|
Algorithms-and-Data-Structures-2021/classwork-02-cpp-basics-demo
|
dccf30fd03a7ed4e8e68f85c395f786a643ea3db
|
[
"MIT"
] | 3
|
2021-03-10T06:20:27.000Z
|
2021-03-17T05:53:36.000Z
|
#include <iostream> // cout
// Подключаем свой заголовочный файл -
// целью заголовочных файлов является удобное хранение набора объявлений
// для их последующего использования в других программах.
// поиск заголовочного файла осуществляется в папках проекта (а не в системных директориях)
#include "structs.hpp"
// директива #pragma once (см. заголовочный файл) не позволит повторно подключить заголовочный файл
// поэтому, повторный include просто не сработает
#include "structs.hpp"
using namespace std;
int main() {
{
Student student; // { id = <мусор>, age = <мусор>, name = "", avg_score = <мусор> }
// инициализация структуры (aggregate initialization)
student = {0, 24, "Ramil Safin", 92.6};
// доступ к полям (оператор .)
const double avg_score = student.avg_score; // чтение
student.avg_score = avg_score - 0.3; // запись
// копирование
Student const student_copy = student; // { id = 0, age = 24, name = "Ramil Safin", avg_score = 92.3 }
// student_copy.name = ""; // <- ошибка компиляции
// указатель и ссылка
Student *ptr_to_student = &student;
// оператор обращения к полям структуры через указатель (->)
ptr_to_student->age = 32; // эквивалентно (*ptr_to_student).age = 32;
update_score(ptr_to_student, 86);
Student &ref_to_student = student;
// оператор обращения к полям . (точка)
ref_to_student.age += 1;
update_score(ref_to_student, 90);
print_details(ref_to_student /* ссылка на const */);
}
{ // конструкторы и деструкторы
{ // вошли в новую область видимости
University u1; // конструктор по-умолчанию (объект создается на стеке)
u1.~University(); // ручной вызов деструктора (объект НЕ удаляется со стека)
// здесь мы ещё можем продолжать использовать u1
} // вышли из области видимости => автоматический вызов деструктора u1
University u2("KFU"); // explicit конструктор по name
// University u2_str = string("KFU"); // <- ошибка компиляции (неявное приведение типа string к University)
University u2_str = static_cast<University>(string("KFU")); // явное приведение типа
University u3(1); // НЕ explicit конструктор по ranking
University u3_int = 1; // ОК, вызов конструктора с ranking (неявное преобразование типа int в University)
University u4("KFU", 1); // конструктор по name и ranking
}
{ // приватные/публичные поля и методы структуры
University uni; // вызов конструктора по-умолчанию (создание объекта класса uni)
// uni.name_ = ""; // <- ошибка компиляции (поле name_ приватное)
// для получения доступа к приватным полям используются публичные методы
string name = uni.GetName(); // копия поля name_
string &name_ref = uni.GetNameRef(); // ссылка на поле name_
name_ref = ""; // ОК, теперь uni.name_ = ""
uni.SetName("MSU");
string const &name_const_ref = uni.GetNameConstRef(); // ссылка на неизменяемое поле name_
// name_const_ref = ""; // <- ошибка компиляции
// вызов приватных функций - невозможен
// uni.private_function(); // <- ошибка компиляции
}
{ // неявный указатель this
University uni;
auto &this_ref = uni.GetThisRef();
// компилятор записывает строку кода выше примерно следующим образом:
// GetThisRef(&uni) - т.е. компилятор передает указатель на объект неявным аргументом
// Ex.: Python: self (явный), Java: this (неявный)
}
{ // статические методы и поля
int ID = University::ID; // получение значения статического поля структуры (объект не обязательно создавать)
int curr_id = University::CurrentID(); // вызов статического метода структуры
// можно получить доступ к публичному статическому полю и через объект
University u;
curr_id = u.ID;
}
{ // создание объектов структуры на куче, деструктор
auto *u_ptr = new University("KFU", 1);
string name = u_ptr->GetName();
delete u_ptr; // ручной вызов деструктора и освобождение памяти
} // при выходе из области видимости деструктор не вызовется (высвободится лишь память под указатель u_ptr)
return 0;
}
// определение функций, объявленных в заголовочном файле structs.hpp
void update_score(Student &student, double new_score) {
student.avg_score = new_score;
}
void update_score(Student *student, double new_score) {
student->avg_score = new_score;
}
void print_details(Student const &student) {
// student нужен только для чтения данных: id и пр.
std::cout << "Student: " << "ID = " << student.id << "\tName: " << student.name << endl;
}
// определение методов University из заголовочного файла
// <название структуры>::<название метода>(<параметры>) : <список инициализации полей> { <тело метода> }
// :: - оператор разрешение области, используется для идентификации и устранения неоднозначности идентификаторов
University::University(const string &name, int ranking) : name_{name}, ranking_{ranking} {
// генерация идентификатора на базе статического поля структуры
id_ = ID++; // эквивалентно: id_ = ID и ID += 1
}
int University::GetId() const {
// id_ = 0; // <- ошибка компиляции
return id_;
}
std::string University::GetName() const {
return name_;
}
int University::GetRanking() const {
return ranking_;
}
std::string &University::GetNameRef() /* const - нельзя, нет гарантии, что name_ не изменится */ {
// ranking_ = 0; // можно изменять поля объекта, но не стоит, это плохой код
return name_; // по ссылке можно будет изменять поле name_ у объекта типа University
}
std::string const &University::GetNameConstRef() const /* const - уже есть гарантии неизменности name_ */ {
// private_function(); // <- ошибка компиляции
private_const_function();
return name_;
}
University &University::GetThisRef() {
// std::string name = this->name_;
// эквивалентно: std::string name = name_;
return *this; // разыменуем указатель и получаем адрес объекта в памяти
// который можем вернуть как ссылку (можно и указатель вернуть)
}
void University::SetRanking(int ranking) {
ranking_ = ranking;
}
void University::SetName(const string &name) {
name_ = name;
}
void University::private_function() {
// блок кода
}
void University::private_const_function() const {
// блок кода
}
University::University(const std::string &name) : University(name, 0) {
std::cout << "explicit University(name)" << std::endl;
}
//University::University(const string &name)
| 31.781553
| 113
| 0.685352
|
Algorithms-and-Data-Structures-2021
|
239da9ca7eca15f56272f96c2085795d5c53472d
| 308
|
cpp
|
C++
|
cpp/other/terminal_input.cpp
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
cpp/other/terminal_input.cpp
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
cpp/other/terminal_input.cpp
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string mystr;
float price;
cout << "enter price :" << endl;
getline(cin,mystr);
//cin.getline(mystr);
stringstream (mystr) >> price;
cout << "the price is:" << price << endl;
return 0;
}
| 22
| 45
| 0.607143
|
danyfang
|
239dfe62dd54c7c176526a8d355e463822fe0611
| 32,683
|
cpp
|
C++
|
sam/sam2016.cpp
|
leandrohga/cs4298_MacNCheese
|
89e6b381341c5b647c98a0d84af6f71c57a4e147
|
[
"Apache-2.0"
] | null | null | null |
sam/sam2016.cpp
|
leandrohga/cs4298_MacNCheese
|
89e6b381341c5b647c98a0d84af6f71c57a4e147
|
[
"Apache-2.0"
] | null | null | null |
sam/sam2016.cpp
|
leandrohga/cs4298_MacNCheese
|
89e6b381341c5b647c98a0d84af6f71c57a4e147
|
[
"Apache-2.0"
] | null | null | null |
/* ____________________________________________________________________________
S A M 2 0 0 7
An Assembler for the MACC2 Virtual Computer
James L. Richards
Last Update: August 28, 2007
Last Update: January 2, 2016
by Marty J. Wolf
____________________________________________________________________________
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string.h>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <sstream>
#include <algorithm>
using namespace std;
const int MAXINT = 32767;
typedef unsigned char Byte;
typedef unsigned short Word;
enum OpKind {OIN, IA, IS, IM, IDENT, FN, FA, FS, FM, FD,
BI, BO, BA, IC, FC, JSR, BKT, LD, STO, LDA,
FLT, FIX, J, SR, SL, SRD, SLD, RD, WR, TRNG,
HALT, NOP, CLR, REALDIR, STRINGDIR, INTDIR,
SKIPDIR, LABELDIR};
enum ErrorKind {NO_ERROR, UNKNOWN_OP_NAME, BAD_REG_ADDR, BAD_GEN_ADDR,
BAD_INTEGER, BAD_REAL, BAD_STR, BAD_NAME, ILL_REG_ADDR,
ILL_MED_ADDR, BAD_SHFT_AMT, BAD_STRING, INVALID_NAME};
enum WarnKind {LONG_NAME, MISSING_R, MISSING_NUM, MISSING_RP,
MISSING_COMMA, NAME_DEFINED, BAD_SKIP, ESC_TOO_SHORT,
STR_TOO_SHORT, TEXT_FOLLOWS};
struct SymRec;
typedef SymRec* SymPtr;
struct SymRec
{
string id;
SymPtr left, right;
short patch, loc;
};
// GLOBAL VARIABLES
// ----------------
Word
Inop, Iaop, Isop, Imop, Idop, Fnop, Faop, Fsop, Fmop, Fdop,
Biop, Boop, Baop, Icop, Fcop, Jsrop, Bktop, Ldop, Stoop, Ldaop,
Fltop, Fixop, Jop, Srop, Slop, Rdop, Wrop, Trngop, Haltop;
string Source;
ifstream InFile;
ofstream ListFile;
bool Saved; // Flag for one character lookahead
char Ch; // Current character from the input
vector<Byte> Mem; // Memory Image being created
Word Lc; // Location Counter
ofstream MemFile; // File for the memory image
SymPtr Symbols;
int Line; // Number of the current input line
ErrorKind Error;
bool Errs;
bool Warning;
bool Morewarn;
WarnKind Warns[11];
int Windex;
string Arg,
Memfname,
Srcfname;
const Word BYTE_MASK = 0x00FF;
void WordToBytes(Word w, Byte& hiByte, Byte& loByte)
//
// Converts a word to two bytes.
//
{
loByte = Byte(w & BYTE_MASK);
hiByte = Byte((w >> 8) & BYTE_MASK);
}
void BytesToWord(Byte hiByte, Byte loByte, Word& w)
//
// Converts two bytes to a word.
{
w = (Word(hiByte) << 8) | Word(loByte);
}
void InsertMem(Word w)
//
// Puts one word into memory with the high byte first.
//
{
Byte loByte, hiByte;
WordToBytes(w, hiByte, loByte);
Mem.push_back(hiByte);
Mem.push_back(loByte);
Lc += 2;
}
void CheckTab(SymPtr cur)
//
// Checks for undefined symbols in the symbol table.
//
{
if (cur != NULL)
{
CheckTab(cur->left);
if (cur->loc < 0)
{
Warning = true;
ListFile << " WARNING -- " << cur->id << " Undefined"
<< endl;
cout << " WARNING -- " << cur->id << " Undefined"
<< endl;
}
CheckTab(cur->right);
}
}
void Warn(WarnKind w)
//
// Adds a warning to the list of warnings.
//
{
if (!Morewarn)
Windex = 1;
Morewarn = true;
Warns[Windex] = w;
Windex++;
}
void PrintWarn()
//
// Prints warning messages.
//
{
ListFile << "\n WARNING -- ";
cout << "\n WARNING -- ";
switch (Warns[1])
{
case TEXT_FOLLOWS:
ListFile << "Text follows instruction";
cout << "Text follows instruction";
break;
case ESC_TOO_SHORT:
ListFile <<
"Need 3 digits to specify an unprintable character";
cout << "Need 3 digits to specify an unprintable character";
break;
case STR_TOO_SHORT:
ListFile << "Missing \" in string";
cout << "Missing \" in string";
break;
case BAD_SKIP:
ListFile <<
"Skip value must be positive, skip directive ignored";
cout << "Skip value must be positive, skip directive ignored";
break;
case NAME_DEFINED:
ListFile <<
"Name already defined, earlier definition lost";
cout << "Name already defined, earlier definition lost";
break;
case LONG_NAME:
ListFile << "Name too long, only 7 characters used";
cout << "Name too long, only 7 characters used";
break;
case MISSING_R:
ListFile << "Missing R in Register Address";
cout << "Missing R in Register Address";
break;
case MISSING_NUM:
ListFile <<
"Missing Number in Register Address (0 assumed)";
cout << "Missing Number in Register Address (0 assumed)";
break;
case MISSING_RP:
ListFile << "Missing "" in Indexed Address";
cout << "Missing "" in Indexed Address";
break;
case MISSING_COMMA:
ListFile << "Missing ","";
cout << "Missing ","";
break;
default:;
}
ListFile << " on line " << Line << endl;
cout << " on line " << Line << endl;
for (int i = 2; i < Windex; i++)
Warns[i - 1] = Warns[i];
Windex--;
if (Windex <= 1)
Morewarn = false;
}
void InRegAddr (Word& w, int reg, int hbit)
//
// Insert a register address into a word
//
{
Word mask1 = 0xFFFF,
mask2 = 0xFFFF,
wreg;
wreg = Word(reg);
wreg <<= hbit - 3;
w &= ((mask1 << (hbit+1)) | (mask2 >> (19-hbit)));
w |= wreg;
}
bool Eoln(istream& in)
//
// Returns true iff the next in stream character is a new line
// character.
//
{
return (in.peek() == '\n');
}
void GetCh()
//
// Get a character from the input -- character may have been saved
//
{
if (!Saved)
{
if (InFile.eof())
Ch = '%';
else if (!Eoln(InFile))
{
do
{
InFile.get(Ch);
ListFile << Ch;
} while((Ch == ' ' || Ch == '\t') && !Eoln(InFile));
if (Ch == '%') // skip remainder of line
{
while (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
}
Ch = '%';
}
}
else
Ch = '%';
}
else
Saved = false;
}
void ScanName (string& id)
//
// Builds a label.
//
{
id = "";
while (id.length() < 7 && ((Ch >= 'A' && Ch <= 'Z')|| isdigit(Ch)))
{
id += Ch;
GetCh();
}
if ((Ch >= 'A' && Ch <= 'Z') || isdigit(Ch))
{
Warn(LONG_NAME);
while ((Ch >= 'A' && Ch <= 'Z') || isdigit(Ch))
GetCh();
}
Saved = true;
}
SymPtr FindName (const string& id)
//
// Returns a pointer to the symbol table record containing id
// or returns NULL pointer if id is not in the symbol table.
//
{
SymPtr temp;
bool found;
temp = Symbols;
found = false;
while (!found && (temp != NULL))
if (temp->id == id)
found = true;
else if (temp->id > id)
temp = temp->left;
else
temp = temp->right;
return temp;
}
SymPtr InName (const string& id)
//
// Inserts id into the symbol table and returns a pointer
// to its symbol table record.
//
{
SymPtr cur, prev;
cur = Symbols;
prev = NULL;
while (cur != NULL)
{
prev = cur;
if (cur->id > id)
cur = cur->left;
else
cur = cur->right;
}
cur = new SymRec;
cur->left = NULL;
cur->right = NULL;
cur->id = id;
if (prev == NULL)
Symbols = cur;
else if (prev->id > id)
prev->left = cur;
else
prev->right = cur;
return cur;
}
void ScanStr()
//
// Gets a quoted string from the input stream.
//
{
bool one;
int ival;
Byte byte1, byte2;
Word wf;
one = true;
GetCh();
if (Ch == '"')
{
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
}
while (Ch != '"' && !Eoln(InFile))
{
if (Ch == ':')
{
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
if (isdigit(Ch))
{
ival = int(Ch) - int('0');
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
if (isdigit(Ch))
{
ival = ival * 10
+ int(Ch) - int('0');
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
if (isdigit(Ch))
ival = ival * 10
+ int(Ch) - int('0');
else
Warn(ESC_TOO_SHORT);
}
else
Warn(ESC_TOO_SHORT);
}
else
Warn(ESC_TOO_SHORT);
}
else
Warn(ESC_TOO_SHORT);
Ch = char(ival);
}
}
else
Warn(ESC_TOO_SHORT);
}
if (one)
{
one = false;
byte1 = Byte(Ch);
}
else
{
one = true;
byte2 = Byte(Ch);
BytesToWord(byte1, byte2, wf);
InsertMem(wf);
}
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
}
}
if (one)
byte1 = Byte(0);
else
byte2 = Byte(0);
BytesToWord(byte1, byte2, wf);
InsertMem(wf);
if (Ch != '"')
Warn(STR_TOO_SHORT);
}
else
Error = BAD_STR;
}
void ScanReal (Word& w1, Word& w2)
//
// Gets a real number from the input stream.
//
{
union FloatRec
{
Byte b[4];
float rf;
};
FloatRec real;
float dval = 10.0f, rf = 0.0f;
bool neg = false;
real.rf = 0.0;
GetCh();
if (Ch == '-' || Ch == '+')
{
if (Ch == '-') neg = true;
GetCh();
}
while (isdigit(Ch))
{
real.rf = real.rf * 10 + int(Ch) - int('0');
GetCh();
}
if (Ch == '.')
{
GetCh();
while (isdigit(Ch))
{
real.rf = real.rf + (int(Ch) - int('0')) / dval;
dval = dval * 10.0f;
GetCh();
}
}
else
Saved = true;
if (neg) real.rf = -real.rf;
BytesToWord(real.b[3], real.b[2], w1);
BytesToWord(real.b[1], real.b[0], w2);
}
void ScanInt (Word& w)
//
// Gets an integer from the input stream.
//
{
int temp;
bool neg;
neg = false;
temp = 0;
GetCh();
if (Ch == '-' || Ch == '+')
{
if (Ch == '-')
neg = true;
GetCh();
}
while (isdigit(Ch))
{
temp = temp * 10 + int(Ch) - int('0');
GetCh();
}
Saved = true; // Note the lookahead.
if (neg)
temp = -temp;
if (temp > MAXINT || temp < -MAXINT-1)
Error = BAD_INTEGER;
else
w = Word(temp);
}
int GetRegAddr()
//
// Get a register address from the input stream.
//
{
int temp;
GetCh();
if (Ch == 'R')
GetCh();
else
Warn(MISSING_R);
if (isdigit(Ch))
{
temp = int(Ch) - int('0');
GetCh();
if (isdigit(Ch)) // check for two digits
temp = temp * 10 + int(Ch) - int('0');
else
Saved = true;
if (temp > 15)
Error = BAD_REG_ADDR;
}
else
Warn(MISSING_NUM);
return temp;
}
void GetGenAddr(OpKind op, Word& w1, Word& w2, bool& flag)
//
// Sets an addressing mode.
//
{
int reg;
string id;
SymPtr idrec;
flag = false;
GetCh();
if (Ch == '*')
{
w1 = w1 | 0x0040; // [6]
GetCh();
}
if (Ch >= 'A' && Ch <= 'Z' && Ch != 'R')
{
flag = true;
ScanName(id);
idrec = FindName(id);
if (idrec == NULL)
{
idrec = InName(id);
idrec->loc = -1;
idrec->patch = Lc + 2;
w2 = Word(-1);
}
else if (idrec->loc == -1)
{
w2 = Word(idrec->patch);
idrec->patch = Lc + 2;
}
else
w2 = Word(idrec->loc);
GetCh();
if (Ch == '(')
{
w1 = w1 | 0x0020; // [5]
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(w1, reg, 3);
GetCh();
if (Ch != ')')
Warn(MISSING_RP);
}
}
else // Ch != ')'
w1 = w1 | 0x0010; // [4]
}
else if (isdigit(Ch))
{
Saved = true;
w1 = w1 | 0x0010; // [4]
flag = true;
ScanInt(w2);
}
else
switch (Ch)
{
case 'R': // direct register
flag = false;
Saved = true;
reg = GetRegAddr();
InRegAddr(w1, reg, 3);
if ((op == JSR || op == BKT || op == LDA || op == J)
&& !(w1 & 0x0040))
Error = ILL_REG_ADDR;
break;
case '#': // immediate
flag = true;
if (w1 & 0x0040)
Error = BAD_GEN_ADDR;
else if (op == FN || op == FA || op == FS|| op == FM
|| op == FD || op == FC || op == FIX
|| op == JSR || op == BKT || op == STO
|| op == J || op == RD || op == TRNG)
Error = ILL_MED_ADDR;
else if (w1 == (Wrop | 0x0080))
Error = ILL_MED_ADDR;
else if (w1 == (Wrop | 0x0480))
Error = ILL_MED_ADDR;
else
{
w1 = w1 | 0x0030; // [4, 5]
ScanInt(w2);
}
break;
case '-': case '+': // indexed
w1 = w1 | 0x0020; // [5]
flag = true;
if (Ch == '-')
Saved = true;
ScanInt(w2);
GetCh();
if (Ch == '(')
{
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(w1, reg, 3);
GetCh();
if (Ch != ')')
Warn(MISSING_RP);
}
}
else // Ch != '('
Error = BAD_GEN_ADDR;
break;
case '&':
flag = true;
if (w1 & 0x0040) // [6]
Error = BAD_GEN_ADDR;
else
{
w1 = w1 | 0x0070; // [4, 5, 6]
ScanInt(w2);
}
break;
default:
Error = BAD_GEN_ADDR;
}
}
void GetBop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'B'.
//
{
GetCh();
switch (Ch)
{
case 'A':
op = BA;
wd = Baop;
break;
case 'I':
op = BI;
wd = Biop;
break;
case 'K':
GetCh();
if (Ch == 'T')
{
op = BKT;
wd = Bktop;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'O':
op = BO;
wd = Boop;
break;
default:
// character does not legally follow `B'
Error = UNKNOWN_OP_NAME;
}
}
void GetFop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'F'.
//
{
GetCh();
switch (Ch)
{
case 'A':
op = FA;
wd = Faop;
break;
case 'C':
op = FC;
wd = Fcop;
break;
case 'D':
op = FD;
wd = Fdop;
break;
case 'I':
GetCh();
if (Ch == 'X')
{
op = FIX;
wd = Fixop;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'L':
GetCh();
if (Ch == 'T')
{
op = FLT;
wd = Fltop;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'M':
op = FM;
wd = Fmop;
break;
case 'N':
op = FN;
wd = Fnop;
break;
case 'S':
op = FS;
wd = Fsop;
break;
default: // character does not legally follow `F'
Error = UNKNOWN_OP_NAME;
}
}
void GetIop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'I'.
//
{
GetCh();
switch (Ch)
{
case 'A':
op = IA;
wd = Iaop;
break;
case 'C':
op = IC;
wd = Icop;
break;
case 'D':
op = IDENT;
wd = Idop;
break;
case 'M':
op = IM;
wd = Imop;
break;
case 'N':
GetCh();
if (Ch == 'T')
op = INTDIR;
else
{
op = OIN;
wd = Inop;
Saved = true;
}
break;
case 'S':
op = IS;
wd = Isop;
break;
default:
// character does not legally follow `I'
Error = UNKNOWN_OP_NAME;
}
}
void GetJop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'J'.
//
{
GetCh();
op = J; // most are simple jumps--except JSR!!
switch (Ch)
{
case 'E':
GetCh();
if (Ch == 'Q')
wd = Jop | 0x0180; // [7, 8]
else
Error = UNKNOWN_OP_NAME;
break;
case 'G':
GetCh();
if (Ch == 'E')
wd = Jop | 0x0280; // [7, 9]
else if (Ch == 'T')
wd = Jop | 0x0300; // [8, 9]
else
Error = UNKNOWN_OP_NAME;
break;
case 'L':
GetCh();
if (Ch == 'E')
wd = Jop | 0x0100; // [8]
else if (Ch == 'T')
wd = Jop | 0x0080; // [7]
else
Error = UNKNOWN_OP_NAME;
break;
case 'M':
GetCh();
if (Ch == 'P')
wd = Jop;
else
Error = UNKNOWN_OP_NAME;
break;
case 'N':
GetCh();
if (Ch == 'E')
wd = Jop | 0x0200; // [9]
else
Error = UNKNOWN_OP_NAME;
break;
case 'S':
GetCh();
if (Ch == 'R')
{
op = JSR;
wd = Jsrop;
}
else
Error = UNKNOWN_OP_NAME;
break;
default:
//Ch not in ['E','G',...] }
Error = UNKNOWN_OP_NAME;
}
}
void GetLop(OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'L'.
//
{
GetCh();
switch (Ch)
{
case 'A':
GetCh();
if (Ch == 'B')
{
GetCh();
if (Ch == 'E')
{
GetCh();
if (Ch == 'L')
op = LABELDIR;
else
Error = UNKNOWN_OP_NAME;
}
else
Error = UNKNOWN_OP_NAME;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'D':
GetCh();
if (Ch == 'A')
{
op = LDA;
wd = Ldaop;
}
else
{
op = LD;
wd = Ldop;
Saved = true;
}
break;
default:
Error = UNKNOWN_OP_NAME;
}
}
void GetRop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'R'.
//
{
GetCh();
if (Ch == 'D')
{
op = RD;
GetCh();
switch (Ch)
{
case 'B':
GetCh();
if (Ch == 'D')
wd = Rdop | 0x0100; // [8]
else if (Ch == 'W')
wd = Rdop | 0x0180; // [7, 8]
else
Error = UNKNOWN_OP_NAME;
break;
case 'C':
GetCh();
if (Ch == 'H')
wd = Rdop | 0x0400; // [10]
else
Error = UNKNOWN_OP_NAME;
break;
case 'F':
wd = Rdop | 0x0080; // [7]
break;
case 'H':
GetCh();
if (Ch == 'D')
wd = Rdop | 0x0300; // [8, 9]
else if (Ch == 'W')
wd = Rdop | 0x0380; // [7, 8, 9]
else
Error = UNKNOWN_OP_NAME;
break;
case 'I':
wd = Rdop;
break;
case 'N':
GetCh();
if (Ch == 'L')
wd = Rdop | 0x0580; // [7, 8, 10]
else
Error = UNKNOWN_OP_NAME;
break;
case 'O':
GetCh();
if (Ch == 'D')
wd = Rdop | 0x0200; // [9]
else if (Ch == 'W')
wd = Rdop | 0x0280; // [7, 10]
else
Error = UNKNOWN_OP_NAME;
break;
case 'S':
GetCh();
if (Ch == 'T')
wd = Rdop | 0x0480; // [7, 10]
else
Error = UNKNOWN_OP_NAME;
break;
default:
// Ch not in ['B','C',...] }
Error = UNKNOWN_OP_NAME;
}
}
else if (Ch == 'E')
{
GetCh();
if (Ch == 'A')
{
GetCh();
if (Ch == 'L')
op = REALDIR;
else
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'A'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'E'
Error = UNKNOWN_OP_NAME;
}
void GetSop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'S'.
//
{
GetCh();
switch (Ch)
{
case 'K':
GetCh();
if (Ch == 'I')
{
GetCh();
if (Ch == 'P')
op = SKIPDIR;
else
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'I'
Error = UNKNOWN_OP_NAME;
break;
case 'L':
GetCh();
op = SL;
switch (Ch)
{
case 'D':
GetCh();
op = SLD;
switch (Ch)
{
case 'C':
wd = Slop | 0x0070; // [4, 5, 6]
break;
case 'E':
wd = Slop | 0x0060; // [5, 6]
break;
case 'O':
wd = Slop | 0x0050; // [4, 6]
break;
case 'Z':
wd = Slop | 0x0040; // [6]
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'C':
wd = Slop | 0x0030; // [4, 5]
break;
case 'E':
wd = Slop | 0x0020; // [5]
break;
case 'O':
wd = Slop | 0x0010; // [4]
break;
case 'Z':
wd = Slop;
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'R':
GetCh();
op = SR;
switch (Ch)
{
case 'D':
GetCh();
op = SRD;
switch (Ch)
{
case 'C':
wd = Srop | 0x0070; // [4, 5, 6]
break;
case 'E':
wd = Srop | 0x0060; // [5, 6]
break;
case 'O':
wd = Srop | 0x0050; // [4, 6]
break;
case 'Z':
wd = Srop | 0x0040; // [6]
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'C':
wd = Srop | 0x0030; // [4, 5]
break;
case 'E':
wd = Srop | 0x0020; // [5]
break;
case 'O':
wd = Srop | 0x0010; // [4]
break;
case 'Z':
wd = Srop;
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'T':
GetCh();
if (Ch == 'O')
{
op = STO;
wd = Stoop;
}
else if (Ch == 'R')
{
GetCh();
if (Ch == 'I')
{
GetCh();
if (Ch == 'N')
{
GetCh();
if (Ch == 'G')
op = STRINGDIR;
else
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'N'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'I'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
break;
default:
Error = UNKNOWN_OP_NAME;
}
}
void GetWop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'W'.
//
{
GetCh();
if (Ch == 'R')
{
op = WR;
GetCh();
switch (Ch)
{
case 'B':
GetCh();
if (Ch == 'D')
wd = Wrop | 0x0100; // WRBD
else if (Ch == 'W')
wd = Wrop | 0x0180; // WRBW
else
Error = UNKNOWN_OP_NAME;
break;
case 'C':
GetCh();
if (Ch == 'H')
wd = Wrop | 0x0400; // WRCH
else
Error = UNKNOWN_OP_NAME;
break;;
case 'F':
wd = Wrop | 0x0080; // WRF
break;
case 'H':
GetCh();
if (Ch == 'D')
wd = Wrop | 0x0300; // WRHD
else if (Ch == 'W')
wd = Wrop | 0x0380; // WRHW
else
Error = UNKNOWN_OP_NAME;
break;
case 'I': // WRI
wd = Wrop;
break;
case 'N':
GetCh();
if (Ch == 'L')
wd = Wrop | 0x0580; // WRNL
else
Error = UNKNOWN_OP_NAME;
break;
case 'O':
GetCh();
if (Ch == 'D')
wd = Wrop | 0x0200; // WROD
else if (Ch == 'W')
wd = Wrop | 0x0280; // WROW
else
Error = UNKNOWN_OP_NAME;
break;
case 'S':
GetCh();
if (Ch == 'T')
wd = Wrop | 0x0480; // WRST
else
Error = UNKNOWN_OP_NAME;
break;
default:
Error = UNKNOWN_OP_NAME;
}
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
}
void ProLine()
//
// Process the current line of input.
//
{
Word wd = 0, wd2;
Byte b1, b2;
OpKind op;
int reg;
bool twowds;
short i1, i2;
string id;
SymPtr idrec;
twowds = false;
Error = NO_ERROR;
switch (Ch)
{
case 'B':
GetBop(op, wd);
break;
case 'C':
GetCh();
if (Ch == 'L')
{
GetCh();
if (Ch == 'R')
{
op = CLR;
wd = Srop;
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'L'
Error = UNKNOWN_OP_NAME;
break;
case 'F':
GetFop(op, wd);
break;
case 'H':
GetCh();
if (Ch == 'A')
{
GetCh();
if (Ch == 'L')
{
GetCh();
if (Ch == 'T')
{
op = HALT;
wd = Haltop;
}
else // Ch != 'T'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'L'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'A'
Error = UNKNOWN_OP_NAME;
break;
case 'I':
GetIop(op, wd);
break;
case 'J':
GetJop(op, wd);
break;
case 'L':
GetLop(op, wd);
break;
case 'N':
GetCh();
if (Ch == 'O')
{
GetCh();
if (Ch == 'P')
{
op = NOP;
wd = Jop | 0x0380; // [7, 8, 9]
}
else // Ch != 'P'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'O'
Error = UNKNOWN_OP_NAME;
break;
case 'R':
GetRop(op, wd);
break;
case 'S':
GetSop(op, wd);
break;
case 'T':
GetCh();
if (Ch == 'R')
{
GetCh();
if (Ch == 'N')
{
GetCh();
if (Ch == 'G')
{
op = TRNG;
wd = Trngop;
}
else // Ch != 'G'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'N'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
break;
case 'W':
GetWop(op, wd);
break;
default:
Error = UNKNOWN_OP_NAME;
}
if (Error == NO_ERROR)
{
switch (op)
{
case CLR:
// need to find a reg address }
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(wd, reg, 10);
InsertMem (wd);
}
break;
case SL:
case SR:
case SLD:
case SRD:
reg = GetRegAddr();
if (Error == NO_ERROR)
InRegAddr(wd, reg, 10);
GetCh();
if (Ch != ',')
{
Warn(MISSING_COMMA);
Saved = true;
}
ScanInt(wd2);
if (Error == NO_ERROR)
{
reg = short(wd2) ;
if (reg == 16)
reg = 0;
if ((reg < 16) && (reg >= 0))
{
InRegAddr(wd, reg, 3);
InsertMem (wd);
}
else
Error = BAD_SHFT_AMT;
}
break;
case OIN:
case IA:
case IS:
case IM:
case IDENT:
case FN:
case FA:
case FS:
case FM:
case FD:
case BI:
case BO:
case BA:
case IC:
case FC:
case JSR:
case BKT:
case LD:
case STO:
case LDA:
case FLT:
case FIX:
case TRNG:
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(wd, reg, 10);
GetCh();
if (Ch != ',')
{
Warn(MISSING_COMMA);
Saved = true;
}
GetGenAddr(op, wd, wd2, twowds);
if (Error == NO_ERROR)
if (twowds)
{
InsertMem (wd);
InsertMem (wd2);
}
else
InsertMem (wd);
}
break;
case J:
GetGenAddr(op, wd, wd2, twowds);
if (Error == NO_ERROR)
if (twowds)
{
InsertMem (wd);
InsertMem (wd2);
}
else
InsertMem (wd);
break;
case RD:
case WR:
twowds = false;
if (!((0x0400 & wd)&&(0x0100 & wd)))
GetGenAddr(op, wd, wd2, twowds);
if (Error == NO_ERROR)
if (twowds)
{
InsertMem (wd);
InsertMem (wd2);
}
else
InsertMem (wd);
break;
case NOP:
case HALT:
InsertMem(wd);
break;
case INTDIR:
ScanInt(wd);
InsertMem(wd);
break;
case REALDIR:
ScanReal(wd, wd2);
InsertMem(wd);
InsertMem(wd2);
break;
case SKIPDIR:
ScanInt(wd);
i1 = int(wd);
if (i1 < 0)
Warn(BAD_SKIP);
else
{
Lc = Lc + i1;
for (int i = 1; i <= i1; i++)
Mem.push_back(Byte(0));
}
break;
case STRINGDIR:
ScanStr();
break;
case LABELDIR:
GetCh();
if ((Ch >= 'A' && Ch <= 'Q') || (Ch >= 'S' && Ch <= 'Z'))
{
ScanName(id);
idrec = FindName(id);
if (idrec == NULL)
idrec = InName(id);
else
{
if (idrec->loc >= 0)
Warn(NAME_DEFINED);
i1 = idrec->patch;
wd = Word(Lc);
WordToBytes(wd, b1, b2);
while (i1 >= 0)
{
BytesToWord(Mem[i1], Mem[i1+1], wd);
i2 = int(wd);
Mem[i1] = b1;
Mem[i1+1] = b2;
i1 = i2;
}
}
idrec->patch = -1;
idrec->loc = Lc;
}
else
Error = INVALID_NAME;
}
} // if Error = NO_ERROR
}
void InitOpcodes()
//
// Initalize all the opcodes.0
//
{
Inop = 0x0000; // 00000
Iaop = 0x0800; // 00001
Isop = 0x1000; // 00010
Imop = 0x1800; // 00011
Idop = 0x2000; // 00100
Fnop = 0x2800; // 00101
Faop = 0x3000; // 00110
Fsop = 0x3800; // 00111
Fmop = 0x4000; // 01000
Fdop = 0x4800; // 01001
Biop = 0x5000; // 01010
Boop = 0x5800; // 01011
Baop = 0x6000; // 01100
Icop = 0x6800; // 01101
Fcop = 0x7000; // 01110
Jsrop = 0x7800; // 01111
Bktop = 0x8000; // 10000
Ldop = 0x8800; // 10001
Stoop = 0x9000; // 10010
Ldaop = 0x9800; // 10011
Fltop = 0xA000; // 10100
Fixop = 0xA800; // 10101
Jop = 0xB000; // 10110
Srop = 0xB800; // 10111
Slop = 0xC000; // 11000
Rdop = 0xC800; // 11001
Wrop = 0xD000; // 11010
Trngop = 0xD800; // 11011
Haltop = 0xF800; // 11111
}
//---------------------------------------------------------------------
string Date()
{
const string MONTH[] =
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December" };
/*
char theDate[10];
int moNumber;
_strdate_s(theDate);
string strDate(theDate, theDate+8);
moNumber = 10 * (theDate[0] - '0') + theDate[1] - '0' - 1;
return MONTH[moNumber] + ' '
+ ((strDate[3] == '0') ? strDate.substr(4,1)
: strDate.substr(3,2))
+ ", 20" + strDate.substr(6,3);
*/
time_t now = time(0);
tm *ltm = localtime(&now);
return MONTH[ltm->tm_mon] + " " +
static_cast<ostringstream*>(
&(ostringstream() << ltm->tm_mday) )->str()
+ ", " +
static_cast<ostringstream*>(
&(ostringstream() << 1900 + ltm->tm_year) )->str();
}
string Time()
{
const string HOUR[]
= { "12", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "11" };
int hrNumber;
string suffix;
string pad = "";
time_t now = time(0);
tm *ltm = localtime(&now);
hrNumber = ltm->tm_hour;
if (ltm->tm_hour < 12)
suffix = " A.M.";
else
{
suffix = " P.M.";
hrNumber -= 12;
}
if ( ltm->tm_min < 10)
pad = "0";
return HOUR[hrNumber] + ':' + pad +
static_cast<ostringstream*>(
&(ostringstream() << ltm->tm_min) )->str()
+ suffix;
}
int main(int argc, char *argv[])
{
cout << "SAM 2016 ASSEMBLER\n" << endl;
if (argc > 1) {
if (strcmp(argv[1], "help") == 0) {
cout << "Usage: ./sam [sourceFile]\n ./sam help";
} else {
Source = argv[1];
Source = Source.substr(0, Source.find(".asm"));
cout << "SAM source file name: " << Source << ".asm" << endl;
}
} else {
cout << "SAM source file name: ";
getline(cin, Source);
}
InFile.open((Source + ".asm").data());
if(!InFile.is_open())
{
cout << "\nFile \"" << Source + ".asm" << "\" not found!"
<< "\nAssembly aborted.\n" << endl;
cin.get();
exit(1);
}
ListFile.open((Source+".lis").data());
ListFile << endl;
ListFile << " SAM 2016 Assembler Listing\n" << endl;
ListFile << " " + Date() << " at " << Time() << endl;
ListFile << " SOURCE FILE: " + Source + ".asm" << endl;
Symbols = NULL;
InitOpcodes();
Line = 0;
Lc = 0;
Errs = false;
Warning = false;
Saved = false;
InFile.peek();
if (!InFile.eof())
{
ListFile << endl;
ListFile << setw(10) << "LN" << setw(6) << "LC" << endl;
ListFile << setw(10) << Line
<< setw(6) << hex << uppercase << Lc
<< dec << ": ";
}
else
{
InFile.close();
ListFile.close();
cout << "\nFile is empty.\n" << endl;
exit(1);
}
InFile.peek();
while (!InFile.eof())
{
GetCh();
InFile.peek();
while (!InFile.eof() && (Ch == '%'))
{
InFile.ignore(256, '\n');
InFile.peek();
if (!InFile.eof())
{
ListFile << endl << flush;
ListFile << setw(10) << ++Line
<< setw(6) << hex << uppercase << Lc
<< dec << ": ";
GetCh();
}
}
if (Eoln(InFile)){//skip over blank lines in input file
GetCh();
continue;
}
if (!InFile.eof())
{ // instruction processing
Error = NO_ERROR;
Morewarn = false;
ProLine();
GetCh();
if (Ch != '%' && !isspace(Ch))
{ // skip text after instruction
Warn(TEXT_FOLLOWS);
do
{
InFile.get(Ch);
ListFile << Ch;
} while (Ch != '\n');
}
if (Error != NO_ERROR)
{
ListFile << endl;
Errs = true;
ListFile << " ERROR -- ";
switch (Error)
{
case INVALID_NAME:
ListFile <<
"Invalid Name in Label Directive";
break;
case UNKNOWN_OP_NAME:
ListFile <<
"Unknown Operation or Directive Name";
break;
case BAD_STR:
ListFile <<
"Improper String Directive -- Missing \"";
break;
case BAD_GEN_ADDR:
ListFile <<
"Improperly Formed General Address";
break;
case BAD_REG_ADDR:
ListFile <<
"Register Address Out of Range";
break;
case BAD_INTEGER:
ListFile <<
"Improperly Formed Integer Constant";
break;
case BAD_REAL:
ListFile <<
"Improperly Formed Real Constant";
break;
case BAD_STRING:
ListFile <<
"Improperly Formed String Constant";
break;
case BAD_NAME:
ListFile <<
"Improperly Formed Name";
break;
case ILL_REG_ADDR:
ListFile <<
"Direct Register Address not Permitted";
break;
case ILL_MED_ADDR:
ListFile <<
"Immediate Address not Permitted";
break;
case BAD_SHFT_AMT:
ListFile <<
"Shift Amount not in Range";
break;
default:;
}
ListFile << " detected on line " << Line << endl;
}
while (Morewarn)
PrintWarn();
}
}
ListFile << endl << endl;
CheckTab(Symbols);
if (!Errs && !Warning)
{
MemFile.open((Source+".obj").data(), ios_base::binary);
ListFile << "\nMACC Memory Hexadecimal Dump\n" << endl;
ListFile << " ADDR |";
for (int i = 0; i < 16; i++) ListFile << setw(4) << hex << i;
ListFile << endl;
ListFile << "------+";
for (int i = 0; i < 16; i++) ListFile << "----";
for (int i = 0; i < Lc; i++)
{
MemFile.put(Mem[i]);
if (i % 16 == 0) ListFile << endl << setw(5) << i << " |";
ListFile << " ";
if (Mem[i] < 16) ListFile << "0";
ListFile << hex << short(Mem[i]);
}
ListFile << endl << endl;
MemFile.close();
cout << " SUCCESSFUL ASSEMBLY." << endl;
cout << " OBJECT CODE FILE: "+ Source + ".obj" << endl;
}
else
{
cout << " ERRORS/WARNINGS IN ASSEMBLY CODE." << endl;
cout << " NO OBJECT CODE FILE WAS GENERATED." << endl;
ListFile.close();
InFile.close();
exit(1);
}
ListFile.close();
InFile.close();
//cin.ignore(256, '\n');
//cin.get(); // wait for Enter
return 0;
}
| 17.165441
| 79
| 0.504207
|
leandrohga
|
23a16754db0186edec4777a29ab424dbede84267
| 40,226
|
cpp
|
C++
|
multimedia/directx/dmusic/dmscript/dmscript.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
multimedia/directx/dmusic/dmscript/dmscript.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
multimedia/directx/dmusic/dmscript/dmscript.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//
// Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved.
//
// Implementation of CDirectMusicScript.
//
#include "stdinc.h"
#include "dll.h"
#include "dmscript.h"
#include "oleaut.h"
#include "globaldisp.h"
#include "activescript.h"
#include "sourcetext.h"
//////////////////////////////////////////////////////////////////////
// Creation
CDirectMusicScript::CDirectMusicScript()
: m_cRef(0),
m_fZombie(false),
m_fCriticalSectionInitialized(false),
m_pPerformance8(NULL),
m_pLoader8P(NULL),
m_pDispPerformance(NULL),
m_pComposer8(NULL),
m_fUseOleAut(true),
m_pScriptManager(NULL),
m_pContainerDispatch(NULL),
m_pGlobalDispatch(NULL),
m_fInitError(false)
{
LockModule(true);
InitializeCriticalSection(&m_CriticalSection);
// Note: on pre-Blackcomb OS's, this call can raise an exception; if it
// ever pops in stress, we can add an exception handler and retry loop.
m_fCriticalSectionInitialized = TRUE;
m_info.fLoaded = false;
m_vDirectMusicVersion.dwVersionMS = 0;
m_vDirectMusicVersion.dwVersionLS = 0;
Zero(&m_iohead);
ZeroAndSize(&m_InitErrorInfo);
}
void CDirectMusicScript::ReleaseObjects()
{
if (m_pScriptManager)
{
m_pScriptManager->Close();
SafeRelease(m_pScriptManager);
}
SafeRelease(m_pPerformance8);
SafeRelease(m_pDispPerformance);
if (m_pLoader8P)
{
m_pLoader8P->ReleaseP();
m_pLoader8P = NULL;
}
SafeRelease(m_pComposer8);
delete m_pContainerDispatch;
m_pContainerDispatch = NULL;
delete m_pGlobalDispatch;
m_pGlobalDispatch = NULL;
}
HRESULT CDirectMusicScript::CreateInstance(
IUnknown* pUnknownOuter,
const IID& iid,
void** ppv)
{
*ppv = NULL;
if (pUnknownOuter)
return CLASS_E_NOAGGREGATION;
CDirectMusicScript *pInst = new CDirectMusicScript;
if (pInst == NULL)
return E_OUTOFMEMORY;
return pInst->QueryInterface(iid, ppv);
}
//////////////////////////////////////////////////////////////////////
// IUnknown
STDMETHODIMP
CDirectMusicScript::QueryInterface(const IID &iid, void **ppv)
{
V_INAME(CDirectMusicScript::QueryInterface);
V_PTRPTR_WRITE(ppv);
V_REFGUID(iid);
if (iid == IID_IUnknown || iid == IID_IDirectMusicScript)
{
*ppv = static_cast<IDirectMusicScript*>(this);
}
else if (iid == IID_IDirectMusicScriptPrivate)
{
*ppv = static_cast<IDirectMusicScriptPrivate*>(this);
}
else if (iid == IID_IDirectMusicObject)
{
*ppv = static_cast<IDirectMusicObject*>(this);
}
else if (iid == IID_IDirectMusicObjectP)
{
*ppv = static_cast<IDirectMusicObjectP*>(this);
}
else if (iid == IID_IPersistStream)
{
*ppv = static_cast<IPersistStream*>(this);
}
else if (iid == IID_IPersist)
{
*ppv = static_cast<IPersist*>(this);
}
else if (iid == IID_IDispatch)
{
*ppv = static_cast<IDispatch*>(this);
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>(this)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG)
CDirectMusicScript::AddRef()
{
return InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG)
CDirectMusicScript::Release()
{
if (!InterlockedDecrement(&m_cRef))
{
this->Zombie();
DeleteCriticalSection(&m_CriticalSection);
delete this;
LockModule(false);
return 0;
}
return m_cRef;
}
//////////////////////////////////////////////////////////////////////
// IPersistStream
STDMETHODIMP
CDirectMusicScript::Load(IStream* pStream)
{
V_INAME(CDirectMusicScript::Load);
V_INTERFACE(pStream);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::Load after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
HRESULT hr = S_OK;
SmartRef::CritSec CS(&m_CriticalSection);
// Clear any old info
this->ReleaseObjects();
m_info.fLoaded = false;
m_info.oinfo.Clear();
m_vDirectMusicVersion.dwVersionMS = 0;
m_vDirectMusicVersion.dwVersionLS = 0;
m_wstrLanguage = NULL;
m_fInitError = false;
// Get the loader from stream
IDirectMusicGetLoader *pIDMGetLoader = NULL;
SmartRef::ComPtr<IDirectMusicLoader> scomLoader;
hr = pStream->QueryInterface(IID_IDirectMusicGetLoader, reinterpret_cast<void **>(&pIDMGetLoader));
if (FAILED(hr))
{
Trace(1, "Error: unable to load script from a stream because it doesn't support the IDirectMusicGetLoader interface.\n");
return DMUS_E_UNSUPPORTED_STREAM;
}
hr = pIDMGetLoader->GetLoader(&scomLoader);
pIDMGetLoader->Release();
if (FAILED(hr))
return hr;
hr = scomLoader->QueryInterface(IID_IDirectMusicLoader8P, reinterpret_cast<void **>(&m_pLoader8P)); // OK if this fails -- just means the scripts won't be garbage collected
if (SUCCEEDED(hr))
{
// Hold only a private ref on the loader. See IDirectMusicLoader8P::AddRefP for more info.
m_pLoader8P->AddRefP();
m_pLoader8P->Release(); // offset the QI
}
// Read the script's header information
SmartRef::RiffIter riForm(pStream);
if (!riForm)
{
#ifdef DBG
if (SUCCEEDED(riForm.hr()))
{
Trace(1, "Error: Unable to load script: Unexpected end of file.\n");
}
#endif
return SUCCEEDED(riForm.hr()) ? DMUS_E_SCRIPT_INVALID_FILE : riForm.hr();
}
hr = riForm.FindRequired(SmartRef::RiffIter::Riff, DMUS_FOURCC_SCRIPT_FORM, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Form 'DMSC' not found.\n");
}
#endif
return hr;
}
SmartRef::RiffIter ri = riForm.Descend();
if (!ri)
return ri.hr();
hr = ri.FindRequired(SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPT_CHUNK, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Chunk 'schd' not found.\n");
}
#endif
return hr;
}
hr = SmartRef::RiffIterReadChunk(ri, &m_iohead);
if (FAILED(hr))
return hr;
hr = ri.LoadObjectInfo(&m_info.oinfo, SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPTVERSION_CHUNK);
if (FAILED(hr))
return hr;
hr = SmartRef::RiffIterReadChunk(ri, &m_vDirectMusicVersion);
if (FAILED(hr))
return hr;
// Read the script's embedded container
IDirectMusicContainer *pContainer = NULL;
hr = ri.FindAndGetEmbeddedObject(
SmartRef::RiffIter::Riff,
DMUS_FOURCC_CONTAINER_FORM,
DMUS_E_SCRIPT_INVALID_FILE,
scomLoader,
CLSID_DirectMusicContainer,
IID_IDirectMusicContainer,
reinterpret_cast<void**>(&pContainer));
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Form 'DMCN' no found.\n");
}
#endif
return hr;
}
// Build the container object that will represent the items in the container to the script
m_pContainerDispatch = new CContainerDispatch(pContainer, scomLoader, m_iohead.dwFlags, &hr);
pContainer->Release();
if (!m_pContainerDispatch)
return E_OUTOFMEMORY;
if (FAILED(hr))
return hr;
// Create the global dispatch object
m_pGlobalDispatch = new CGlobalDispatch(this);
if (!m_pGlobalDispatch)
return E_OUTOFMEMORY;
// Get the script's language
hr = ri.FindRequired(SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPTLANGUAGE_CHUNK, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Chunk 'scla' no found.\n");
}
#endif
return hr;
}
hr = ri.ReadText(&m_wstrLanguage);
if (FAILED(hr))
{
#ifdef DBG
if (hr == E_FAIL)
{
Trace(1, "Error: Unable to load script: Problem reading 'scla' chunk.\n");
}
#endif
return hr == E_FAIL ? DMUS_E_SCRIPT_INVALID_FILE : hr;
}
// Get the script's source code
SmartRef::WString wstrSource;
for (++ri; ;++ri)
{
if (!ri)
{
Trace(1, "Error: Unable to load script: Expected chunk 'scsr' or list 'DMRF'.\n");
return DMUS_E_SCRIPT_INVALID_FILE;
}
SmartRef::RiffIter::RiffType type = ri.type();
FOURCC id = ri.id();
if (type == SmartRef::RiffIter::Chunk)
{
if (id == DMUS_FOURCC_SCRIPTSOURCE_CHUNK)
{
hr = ri.ReadText(&wstrSource);
if (FAILED(hr))
{
#ifdef DBG
if (hr == E_FAIL)
{
Trace(1, "Error: Unable to load script: Problem reading 'scsr' chunk.\n");
}
#endif
return hr == E_FAIL ? DMUS_E_SCRIPT_INVALID_FILE : hr;
}
}
break;
}
else if (type == SmartRef::RiffIter::List)
{
if (id == DMUS_FOURCC_REF_LIST)
{
DMUS_OBJECTDESC desc;
hr = ri.ReadReference(&desc);
if (FAILED(hr))
return hr;
// The resulting desc shouldn't have a name or GUID (the plain text file can't hold name/GUID info)
// and it should have a clsid should be GUID_NULL, which we'll replace with the clsid of our private
// source helper object.
if (desc.dwValidData & (DMUS_OBJ_NAME | DMUS_OBJ_OBJECT) ||
!(desc.dwValidData & DMUS_OBJ_CLASS) || desc.guidClass != GUID_NULL)
{
#ifdef DBG
if (desc.dwValidData & (DMUS_OBJ_NAME | DMUS_OBJ_OBJECT))
{
Trace(1, "Error: Unable to load script: 'DMRF' list must have dwValidData with DMUS_OBJ_CLASS and guidClassID of GUID_NULL.\n");
}
else
{
Trace(1, "Error: Unable to load script: 'DMRF' list cannot have dwValidData with DMUS_OBJ_NAME or DMUS_OBJ_OBJECT.\n");
}
#endif
return DMUS_E_SCRIPT_INVALID_FILE;
}
desc.guidClass = CLSID_DirectMusicSourceText;
IDirectMusicSourceText *pISource = NULL;
hr = scomLoader->EnableCache(CLSID_DirectMusicSourceText, false); // This is a private object we just use temporarily. Don't want these guys hanging around in the cache.
if (FAILED(hr))
return hr;
hr = scomLoader->GetObject(&desc, IID_IDirectMusicSourceText, reinterpret_cast<void**>(&pISource));
if (FAILED(hr))
return hr;
DWORD cwchSourceBufferSize = 0;
pISource->GetTextLength(&cwchSourceBufferSize);
WCHAR *pwszSource = new WCHAR[cwchSourceBufferSize];
if (!pwszSource)
return E_OUTOFMEMORY;
pISource->GetText(pwszSource);
*&wstrSource = pwszSource;
pISource->Release();
}
break;
}
}
m_info.fLoaded = true;
// Now that we are loaded and initialized, we can start active scripting
// See if we're dealing with a custom DirectMusic scripting engine. Such engines are marked with the key DMScript. They can be
// called on multiple threads and they don't use oleaut32. Ordinary active scripting engines are marked with the key OLEScript.
SmartRef::HKey shkeyLanguage;
SmartRef::HKey shkeyMark;
SmartRef::AString astrLanguage = m_wstrLanguage;
if (ERROR_SUCCESS != ::RegOpenKeyEx(HKEY_CLASSES_ROOT, astrLanguage, 0, KEY_QUERY_VALUE, &shkeyLanguage) || !shkeyLanguage)
{
Trace(1, "Error: Unable to load script: Scripting engine for language %s does not exist or is not registered.\n", astrLanguage);
return DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE;
}
bool fCustomScriptEngine = ERROR_SUCCESS == ::RegOpenKeyEx(shkeyLanguage, "DMScript", 0, KEY_QUERY_VALUE, &shkeyMark) && shkeyMark;
if (!fCustomScriptEngine)
{
if (ERROR_SUCCESS != ::RegOpenKeyEx(shkeyLanguage, "OLEScript", 0, KEY_QUERY_VALUE, &shkeyMark) || !shkeyMark)
{
Trace(1, "Error: Unable to load script: Language %s refers to a COM object that is not registered as a scripting engine (OLEScript key).\n", astrLanguage);
return DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE;
}
}
m_fUseOleAut = !fCustomScriptEngine;
if (fCustomScriptEngine)
{
m_pScriptManager = new CActiveScriptManager(
m_fUseOleAut,
m_wstrLanguage,
wstrSource,
this,
&hr,
&m_InitErrorInfo);
}
else
{
m_pScriptManager = new CSingleThreadedScriptManager(
m_fUseOleAut,
m_wstrLanguage,
wstrSource,
this,
&hr,
&m_InitErrorInfo);
}
if (!m_pScriptManager)
return E_OUTOFMEMORY;
if (FAILED(hr))
{
SafeRelease(m_pScriptManager);
}
if (hr == DMUS_E_SCRIPT_ERROR_IN_SCRIPT)
{
// If we fail here, load would fail and client would never be able to get the
// error information. Instead, return S_OK and save the error to return from Init.
m_fInitError = true;
hr = S_OK;
}
return hr;
}
//////////////////////////////////////////////////////////////////////
// IDirectMusicObject
STDMETHODIMP
CDirectMusicScript::GetDescriptor(LPDMUS_OBJECTDESC pDesc)
{
V_INAME(CDirectMusicScript::GetDescriptor);
V_PTR_WRITE(pDesc, DMUS_OBJECTDESC);
ZeroMemory(pDesc, sizeof(DMUS_OBJECTDESC));
pDesc->dwSize = sizeof(DMUS_OBJECTDESC);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::GetDescriptor after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (wcslen(m_info.oinfo.wszName) > 0)
{
pDesc->dwValidData |= DMUS_OBJ_NAME;
wcsncpy(pDesc->wszName, m_info.oinfo.wszName, DMUS_MAX_NAME);
pDesc->wszName[DMUS_MAX_NAME-1] = L'\0';
}
if (GUID_NULL != m_info.oinfo.guid)
{
pDesc->guidObject = m_info.oinfo.guid;
pDesc->dwValidData |= DMUS_OBJ_OBJECT;
}
pDesc->vVersion = m_info.oinfo.vVersion;
pDesc->dwValidData |= DMUS_OBJ_VERSION;
pDesc->guidClass = CLSID_DirectMusicScript;
pDesc->dwValidData |= DMUS_OBJ_CLASS;
if (m_info.wstrFilename)
{
wcsncpy(pDesc->wszFileName, m_info.wstrFilename, DMUS_MAX_FILENAME);
pDesc->wszFileName[DMUS_MAX_FILENAME-1] = L'\0';
pDesc->dwValidData |= DMUS_OBJ_FILENAME;
}
if (m_info.fLoaded)
{
pDesc->dwValidData |= DMUS_OBJ_LOADED;
}
return S_OK;
}
STDMETHODIMP
CDirectMusicScript::SetDescriptor(LPDMUS_OBJECTDESC pDesc)
{
V_INAME(CDirectMusicScript::SetDescriptor);
V_STRUCTPTR_READ(pDesc, DMUS_OBJECTDESC);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::SetDescriptor after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
DWORD dwTemp = pDesc->dwValidData;
if (pDesc->dwValidData & DMUS_OBJ_OBJECT)
{
m_info.oinfo.guid = pDesc->guidObject;
}
if (pDesc->dwValidData & DMUS_OBJ_CLASS)
{
pDesc->dwValidData &= ~DMUS_OBJ_CLASS;
}
if (pDesc->dwValidData & DMUS_OBJ_NAME)
{
wcsncpy(m_info.oinfo.wszName, pDesc->wszName, DMUS_MAX_NAME);
m_info.oinfo.wszName[DMUS_MAX_NAME-1] = L'\0';
}
if (pDesc->dwValidData & DMUS_OBJ_CATEGORY)
{
pDesc->dwValidData &= ~DMUS_OBJ_CATEGORY;
}
if (pDesc->dwValidData & DMUS_OBJ_FILENAME)
{
m_info.wstrFilename = pDesc->wszFileName;
}
if (pDesc->dwValidData & DMUS_OBJ_FULLPATH)
{
pDesc->dwValidData &= ~DMUS_OBJ_FULLPATH;
}
if (pDesc->dwValidData & DMUS_OBJ_URL)
{
pDesc->dwValidData &= ~DMUS_OBJ_URL;
}
if (pDesc->dwValidData & DMUS_OBJ_VERSION)
{
m_info.oinfo.vVersion = pDesc->vVersion;
}
if (pDesc->dwValidData & DMUS_OBJ_DATE)
{
pDesc->dwValidData &= ~DMUS_OBJ_DATE;
}
if (pDesc->dwValidData & DMUS_OBJ_LOADED)
{
pDesc->dwValidData &= ~DMUS_OBJ_LOADED;
}
return dwTemp == pDesc->dwValidData ? S_OK : S_FALSE;
}
STDMETHODIMP
CDirectMusicScript::ParseDescriptor(LPSTREAM pStream, LPDMUS_OBJECTDESC pDesc)
{
V_INAME(CDirectMusicScript::ParseDescriptor);
V_INTERFACE(pStream);
V_PTR_WRITE(pDesc, DMUS_OBJECTDESC);
ZeroMemory(pDesc, sizeof(DMUS_OBJECTDESC));
pDesc->dwSize = sizeof(DMUS_OBJECTDESC);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::ParseDescriptor after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
// Read the script's header information
SmartRef::RiffIter riForm(pStream);
if (!riForm)
{
#ifdef DBG
if (SUCCEEDED(riForm.hr()))
{
Trace(2, "Error: ParseDescriptor on a script failed: Unexpected end of file. "
"(Note that this may be OK, such as when ScanDirectory is used to parse a set of unknown files, some of which are not scripts.)\n");
}
#endif
return SUCCEEDED(riForm.hr()) ? DMUS_E_SCRIPT_INVALID_FILE : riForm.hr();
}
HRESULT hr = riForm.FindRequired(SmartRef::RiffIter::Riff, DMUS_FOURCC_SCRIPT_FORM, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: ParseDescriptor on a script failed: Form 'DMSC' not found. "
"(Note that this may be OK, such as when ScanDirectory is used to parse a set of unknown files, some of which are not scripts.)\n");
}
#endif
return hr;
}
SmartRef::RiffIter ri = riForm.Descend();
if (!ri)
return ri.hr();
hr = ri.LoadObjectInfo(&m_info.oinfo, SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPTVERSION_CHUNK);
if (FAILED(hr))
return hr;
hr = this->GetDescriptor(pDesc);
return hr;
}
STDMETHODIMP_(void)
CDirectMusicScript::Zombie()
{
m_fZombie = true;
this->ReleaseObjects();
}
//////////////////////////////////////////////////////////////////////
// IDirectMusicScript
STDMETHODIMP
CDirectMusicScript::Init(IDirectMusicPerformance *pPerformance, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::Init);
V_INTERFACE(pPerformance);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::Init after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::ComPtr<IDirectMusicPerformance8> scomPerformance8;
HRESULT hr = pPerformance->QueryInterface(IID_IDirectMusicPerformance8, reinterpret_cast<void **>(&scomPerformance8));
if (FAILED(hr))
return hr;
// Don't take the critical section if the script is already initialized.
// For example, this is necessary in the following situation:
// - The critical section has already been taken by CallRoutine.
// - The routine played a segment with a script track referencing this script.
// - The script track calls Init (from a different thread) to make sure the script
// is initialized.
if (m_pPerformance8)
{
// Additional calls to Init are ignored.
// First call wins. Return S_FALSE if performance doesn't match.
if (m_pPerformance8 == scomPerformance8)
return S_OK;
else
return S_FALSE;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (m_fInitError)
{
if (pErrorInfo)
{
// Syntax errors in a script occur as it is loaded, before SetDescriptor gives a script
// its filename. We'll have it after the load (before init is called) so can add it
// back in here.
if (m_InitErrorInfo.wszSourceFile[0] == L'\0' && m_info.wstrFilename)
wcsTruncatedCopy(m_InitErrorInfo.wszSourceFile, m_info.wstrFilename, DMUS_MAX_FILENAME);
CopySizedStruct(pErrorInfo, &m_InitErrorInfo);
}
return DMUS_E_SCRIPT_ERROR_IN_SCRIPT;
}
if (!m_info.fLoaded)
{
Trace(1, "Error: IDirectMusicScript::Init called before the script has been loaded.\n");
return DMUS_E_NOT_LOADED;
}
// Get the dispatch interface for the performance
SmartRef::ComPtr<IDispatch> scomDispPerformance = NULL;
hr = pPerformance->QueryInterface(IID_IDispatch, reinterpret_cast<void **>(&scomDispPerformance));
if (FAILED(hr))
return hr;
// Get a composer object
hr = CoCreateInstance(CLSID_DirectMusicComposer, NULL, CLSCTX_INPROC_SERVER, IID_IDirectMusicComposer8, reinterpret_cast<void **>(&m_pComposer8));
if (FAILED(hr))
return hr;
m_pDispPerformance = scomDispPerformance.disown();
m_pPerformance8 = scomPerformance8.disown();
hr = m_pScriptManager->Start(pErrorInfo);
if (FAILED(hr))
return hr;
hr = m_pContainerDispatch->OnScriptInit(m_pPerformance8);
return hr;
}
// Returns DMUS_E_SCRIPT_ROUTINE_NOT_FOUND if routine doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::CallRoutine(WCHAR *pwszRoutineName, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::CallRoutine);
V_BUFPTR_READ(pwszRoutineName, 2);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::CallRoutine after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::CallRoutine.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->CallRoutine(pwszRoutineName, pErrorInfo);
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND if variable doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::SetVariableVariant(
WCHAR *pwszVariableName,
VARIANT varValue,
BOOL fSetRef,
DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::SetVariableVariant);
V_BUFPTR_READ(pwszVariableName, 2);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
switch (varValue.vt)
{
case VT_BSTR:
V_BUFPTR_READ_OPT(varValue.bstrVal, sizeof(OLECHAR));
// We could be more thorough and verify each character until we hit the terminator but
// that would be inefficient. We could also use the length preceding a BSTR pointer,
// but that would be cheating COM's functions that encapsulate BSTRs and could lead to
// problems in future versions of windows such as 64 bit if the BSTR format changes.
break;
case VT_UNKNOWN:
V_INTERFACE_OPT(varValue.punkVal);
break;
case VT_DISPATCH:
V_INTERFACE_OPT(varValue.pdispVal);
break;
}
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::SetVariableObject/SetVariableNumber/SetVariableVariant after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::SetVariableVariant.\n");
return DMUS_E_NOT_INIT;
}
HRESULT hr = m_pScriptManager->SetVariable(pwszVariableName, varValue, !!fSetRef, pErrorInfo);
if (hr == DMUS_E_SCRIPT_VARIABLE_NOT_FOUND)
{
// There are also items in the script's container that the m_pScriptManager object isn't available.
// If that's the case, we should return a more specific error message.
IUnknown *punk = NULL;
hr = m_pContainerDispatch->GetVariableObject(pwszVariableName, &punk);
if (SUCCEEDED(hr))
{
// We don't actually need the object--it can't be set. Just needed to find out if it's there
// in order to return a more specific error message.
punk->Release();
return DMUS_E_SCRIPT_CONTENT_READONLY;
}
}
return hr;
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND and empty value if variable doesn't exist in the script.
// Certain varient types such as BSTRs and interface pointers must be freed/released according to the standards for VARIANTS.
// If unsure, use VariantClear (requires oleaut32).
STDMETHODIMP
CDirectMusicScript::GetVariableVariant(WCHAR *pwszVariableName, VARIANT *pvarValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::GetVariableVariant);
V_BUFPTR_READ(pwszVariableName, 2);
V_PTR_WRITE(pvarValue, VARIANT);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
DMS_VariantInit(m_fUseOleAut, pvarValue);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::GetVariableObject/GetVariableNumber/GetVariableVariant after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::GetVariableVariant.\n");
return DMUS_E_NOT_INIT;
}
HRESULT hr = m_pScriptManager->GetVariable(pwszVariableName, pvarValue, pErrorInfo);
if (hr == DMUS_E_SCRIPT_VARIABLE_NOT_FOUND)
{
// There are also items in the script's container that we need to return.
// This is implemented by the container, which returns the IUnknown pointer directly rather than through a variant.
IUnknown *punk = NULL;
hr = m_pContainerDispatch->GetVariableObject(pwszVariableName, &punk);
if (SUCCEEDED(hr))
{
pvarValue->vt = VT_UNKNOWN;
pvarValue->punkVal = punk;
}
}
#ifdef DBG
if (hr == DMUS_E_SCRIPT_VARIABLE_NOT_FOUND)
{
Trace(1, "Error: Attempt to get variable '%S' that is not defined in the script.\n", pwszVariableName);
}
#endif
if (!m_fUseOleAut && pvarValue->vt == VT_BSTR)
{
// m_fUseOleAut is false when we're using our own custom scripting engine that avoids
// depending on oleaut32.dll. But in this case we're returning a BSTR variant to the
// caller. We have to allocate this string with SysAllocString (from oleaut32)
// because the caller is going to free it with SysFreeString--the standard thing to
// do with a variant BSTR.
BSTR bstrOle = DMS_SysAllocString(true, pvarValue->bstrVal); // allocate a copy with oleaut
DMS_SysFreeString(false, pvarValue->bstrVal); // free the previous value (allocated without oleaut)
pvarValue->bstrVal = bstrOle; // return the oleaut string to the user
if (!bstrOle)
hr = E_OUTOFMEMORY;
}
return hr;
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND if variable doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::SetVariableNumber(WCHAR *pwszVariableName, LONG lValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
VARIANT var;
var.vt = VT_I4;
var.lVal = lValue;
return this->SetVariableVariant(pwszVariableName, var, false, pErrorInfo);
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND and 0 if variable doesn't exist in the script.
// Returns DISP_E_TYPEMISMATCH if variable's datatype cannot be converted to LONG.
STDMETHODIMP
CDirectMusicScript::GetVariableNumber(WCHAR *pwszVariableName, LONG *plValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::GetVariableNumber);
V_PTR_WRITE(plValue, LONG);
*plValue = 0;
VARIANT var;
HRESULT hr = this->GetVariableVariant(pwszVariableName, &var, pErrorInfo);
if (FAILED(hr) || hr == S_FALSE || hr == DMUS_S_GARBAGE_COLLECTED)
return hr;
hr = DMS_VariantChangeType(m_fUseOleAut, &var, &var, 0, VT_I4);
if (SUCCEEDED(hr))
*plValue = var.lVal;
// GetVariableVariant forces a BSTR to be allocated with SysAllocString;
// so if we allocated a BSTR there, we need to free it with SysAllocString here.
bool fUseOleAut = m_fUseOleAut;
if (!m_fUseOleAut && var.vt == VT_BSTR)
{
fUseOleAut = true;
}
DMS_VariantClear(fUseOleAut, &var);
return hr;
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND if variable doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::SetVariableObject(WCHAR *pwszVariableName, IUnknown *punkValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
VARIANT var;
var.vt = VT_UNKNOWN;
var.punkVal = punkValue;
return this->SetVariableVariant(pwszVariableName, var, true, pErrorInfo);
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND and NULL if variable doesn't exist in the script.
// Returns DISP_E_TYPEMISMATCH if variable's datatype cannot be converted to IUnknown.
STDMETHODIMP
CDirectMusicScript::GetVariableObject(WCHAR *pwszVariableName, REFIID riid, LPVOID FAR *ppv, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::GetVariableObject);
V_PTR_WRITE(ppv, IUnknown *);
*ppv = NULL;
VARIANT var;
HRESULT hr = this->GetVariableVariant(pwszVariableName, &var, pErrorInfo);
if (FAILED(hr) || hr == DMUS_S_GARBAGE_COLLECTED)
return hr;
hr = DMS_VariantChangeType(m_fUseOleAut, &var, &var, 0, VT_UNKNOWN);
if (SUCCEEDED(hr))
hr = var.punkVal->QueryInterface(riid, ppv);
DMS_VariantClear(m_fUseOleAut, &var);
return hr;
}
STDMETHODIMP
CDirectMusicScript::EnumRoutine(DWORD dwIndex, WCHAR *pwszName)
{
V_INAME(CDirectMusicScript::EnumRoutine);
V_BUFPTR_WRITE(pwszName, MAX_PATH);
*pwszName = L'\0';
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::EnumRoutine after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::EnumRoutine.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->EnumItem(true, dwIndex, pwszName, NULL);
}
STDMETHODIMP
CDirectMusicScript::EnumVariable(DWORD dwIndex, WCHAR *pwszName)
{
V_INAME(CDirectMusicScript::EnumRoutine);
V_BUFPTR_WRITE(pwszName, MAX_PATH);
*pwszName = L'\0';
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::EnumVariable after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::EnumVariable.\n");
return DMUS_E_NOT_INIT;
}
int cScriptItems = 0;
HRESULT hr = m_pScriptManager->EnumItem(false, dwIndex, pwszName, &cScriptItems);
if (FAILED(hr))
return hr;
if (hr == S_FALSE)
{
// There are also items in the script's container that we need to report.
assert(dwIndex >= cScriptItems);
hr = m_pContainerDispatch->EnumItem(dwIndex - cScriptItems, pwszName);
}
return hr;
}
STDMETHODIMP
CDirectMusicScript::ScriptTrackCallRoutine(
WCHAR *pwszRoutineName,
IDirectMusicSegmentState *pSegSt,
DWORD dwVirtualTrackID,
bool fErrorPMsgsEnabled,
__int64 i64IntendedStartTime,
DWORD dwIntendedStartTimeFlags)
{
V_INAME(CDirectMusicScript::CallRoutine);
V_BUFPTR_READ(pwszRoutineName, 2);
V_INTERFACE(pSegSt);
if (m_fZombie)
{
Trace(1, "Error: Script track attempted to call a routine after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: Unitialized Script elements in an attempt to call a Script Routine.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->ScriptTrackCallRoutine(
pwszRoutineName,
pSegSt,
dwVirtualTrackID,
fErrorPMsgsEnabled,
i64IntendedStartTime,
dwIntendedStartTimeFlags);
}
STDMETHODIMP
CDirectMusicScript::GetTypeInfoCount(UINT *pctinfo)
{
V_INAME(CDirectMusicScript::GetTypeInfoCount);
V_PTR_WRITE(pctinfo, UINT);
*pctinfo = 0;
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::GetTypeInfoCount after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
return S_OK;
}
STDMETHODIMP
CDirectMusicScript::GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
*ppTInfo = NULL;
return E_NOTIMPL;
}
STDMETHODIMP
CDirectMusicScript::GetIDsOfNames(
REFIID riid,
LPOLESTR __RPC_FAR *rgszNames,
UINT cNames,
LCID lcid,
DISPID __RPC_FAR *rgDispId)
{
if (m_fZombie)
{
if (rgDispId)
{
for (int i = 0; i < cNames; ++i)
{
rgDispId[i] = DISPID_UNKNOWN;
}
}
Trace(1, "Error: Call of GetIDsOfNames after a script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before GetIDsOfNames.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->DispGetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId);
}
STDMETHODIMP
CDirectMusicScript::Invoke(
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS __RPC_FAR *pDispParams,
VARIANT __RPC_FAR *pVarResult,
EXCEPINFO __RPC_FAR *pExcepInfo,
UINT __RPC_FAR *puArgErr)
{
if (m_fZombie)
{
if (pVarResult)
DMS_VariantInit(m_fUseOleAut, pVarResult);
Trace(1, "Error: Call of Invoke after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before Invoke.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->DispInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
//////////////////////////////////////////////////////////////////////
// Methods that allow CActiveScriptManager access to private script interfaces
IDispatch *CDirectMusicScript::GetGlobalDispatch()
{
assert(m_pGlobalDispatch);
return m_pGlobalDispatch;
}
| 34.6179
| 186
| 0.621861
|
npocmaka
|
23a3eef99bb03be101e5c678edd9f254ac18b11c
| 617
|
cpp
|
C++
|
Coraza.cpp
|
ErickMartinez2/Lab7P3_ErickMartinez
|
b6f045979bd3b09e9b89f2bd97c51d031db0978b
|
[
"MIT"
] | null | null | null |
Coraza.cpp
|
ErickMartinez2/Lab7P3_ErickMartinez
|
b6f045979bd3b09e9b89f2bd97c51d031db0978b
|
[
"MIT"
] | null | null | null |
Coraza.cpp
|
ErickMartinez2/Lab7P3_ErickMartinez
|
b6f045979bd3b09e9b89f2bd97c51d031db0978b
|
[
"MIT"
] | null | null | null |
#include "Coraza.h"
Coraza::Coraza() {
}
Coraza::Coraza(int pdureza, int pcantidad) {
dureza = pdureza;
cantidad = pcantidad;;
}
Coraza::Coraza(string pnombre, string pciudad, int pedad, int pdureza, int pcantidad): Soldado(pnombre, pciudad, pedad) {
dureza = pdureza;
cantidad = pcantidad;
}
int Coraza::getDureza() {
return dureza;
}
void Coraza::setDureza(int pdureza) {
dureza = pdureza;
}
int Coraza::getCantidad() {
return cantidad;
}
void Coraza::setCantidad(int pcantidad) {
cantidad = pcantidad;
}
double Coraza::ataque() {
return cantidad;
}
double Coraza::defensa() {
return dureza;
}
| 15.04878
| 121
| 0.701783
|
ErickMartinez2
|
23a4241af81aa23c0da2f9375699cb1983670347
| 1,153
|
cpp
|
C++
|
src/RuleTimer.cpp
|
d3wy/pool-controller
|
182d8c67638abf56d8e5126103b5995006c06b42
|
[
"MIT"
] | 12
|
2020-03-04T18:43:43.000Z
|
2022-01-30T22:59:27.000Z
|
src/RuleTimer.cpp
|
d3wy/pool-controller
|
182d8c67638abf56d8e5126103b5995006c06b42
|
[
"MIT"
] | 17
|
2019-05-20T20:22:09.000Z
|
2022-01-11T16:55:26.000Z
|
src/RuleTimer.cpp
|
d3wy/pool-controller
|
182d8c67638abf56d8e5126103b5995006c06b42
|
[
"MIT"
] | 6
|
2020-06-05T18:17:13.000Z
|
2022-03-19T20:13:58.000Z
|
#include "RuleTimer.hpp"
/**
*
*/
RuleTimer::RuleTimer(RelayModuleNode* solarRelay, RelayModuleNode* poolRelay) {
_solarRelay = solarRelay;
_poolRelay = poolRelay;
}
/**
*
*/
void RuleTimer::loop() {
Homie.getLogger() << cIndent << F("§ RuleTimer: loop") << endl;
_poolRelay->setSwitch(checkPoolPumpTimer());
if (_solarRelay->getSwitch()) {
_solarRelay->setSwitch(false);
}
}
/**
*
*/
bool RuleTimer::checkPoolPumpTimer() {
Homie.getLogger() << F("↕ checkPoolPumpTimer") << endl;
tm time = getCurrentDateTime();
bool retval;
tm startTime = getStartTime(getTimerSetting());
tm endTime = getEndTime(getTimerSetting());
Homie.getLogger() << cIndent << F("time= ") << asctime(&time);
Homie.getLogger() << cIndent << F("startTime= ") << asctime(&startTime);
Homie.getLogger() << cIndent << F("endTime= ") << asctime(&endTime);
if (difftime(mktime(&time), mktime(&startTime)) >= 0
&& difftime(mktime(&time), mktime(&endTime)) <= 0) {
retval = true;
} else {
retval = false;
}
Homie.getLogger() << cIndent << F("checkPoolPumpTimer = ") << retval << endl;
return retval;
}
| 20.589286
| 79
| 0.626193
|
d3wy
|
23ae7e5ac53ac779985446beb4d8c74dbbeccd09
| 572
|
cpp
|
C++
|
Source/Musa/GameObject/DemoGameObjects/OrbitingObject.cpp
|
frobro98/Musa
|
6e7dcd5d828ca123ce8f43d531948a6486428a3d
|
[
"MIT"
] | null | null | null |
Source/Musa/GameObject/DemoGameObjects/OrbitingObject.cpp
|
frobro98/Musa
|
6e7dcd5d828ca123ce8f43d531948a6486428a3d
|
[
"MIT"
] | null | null | null |
Source/Musa/GameObject/DemoGameObjects/OrbitingObject.cpp
|
frobro98/Musa
|
6e7dcd5d828ca123ce8f43d531948a6486428a3d
|
[
"MIT"
] | null | null | null |
#include "OrbitingObject.hpp"
#include "Math/Matrix4.hpp"
#include "Math/Quat.hpp"
OrbitingObject::OrbitingObject(const Vector4& orbitAxis, const Vector4& orbitPos)
: axis(orbitAxis),
orbitLocation(orbitPos)
{
}
void OrbitingObject::Update(float /*tick*/)
{
// constexpr float angleOffsetDeg = .005f;
// Matrix4 trans(TRANS, orbitLocation);
// Quat rot(ROT_AXIS_ANGLE, axis, angleOffsetDeg * tick);
// Matrix4 negTrans(TRANS, -orbitLocation);
//
// Matrix4 orbitTrans = negTrans * rot * trans;
//
// position *= orbitTrans;
//
// GameObject::Update(tick);
}
| 23.833333
| 81
| 0.713287
|
frobro98
|
23b0372f4e2172c56569014cd64d3ee64537cd34
| 3,343
|
cpp
|
C++
|
Classes/transitScene.cpp
|
alchemz/Campuspedia
|
0d686a346f67e0f54087fc307ef5fc65d334b935
|
[
"MIT"
] | 1
|
2015-03-21T17:55:17.000Z
|
2015-03-21T17:55:17.000Z
|
Classes/transitScene.cpp
|
alchemz/Campuspedia
|
0d686a346f67e0f54087fc307ef5fc65d334b935
|
[
"MIT"
] | null | null | null |
Classes/transitScene.cpp
|
alchemz/Campuspedia
|
0d686a346f67e0f54087fc307ef5fc65d334b935
|
[
"MIT"
] | null | null | null |
#include "TransitScene.h"
using namespace cocos2d::ui;
USING_NS_CC;
Scene* Transit::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = Transit::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool Transit::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
ini=60;
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
stopFrame=false;
scene=UserDefault::getInstance()->getIntegerForKey("Scene");
auto label=Label::createWithTTF("", "fonts/Calibri.ttf", 120);
label->setPosition(Vec2(origin.x+visibleSize.width/2,origin.y+visibleSize.height/2));
this->addChild(label,1);
if (scene==_DORM) {
int dorm=UserDefault::getInstance()->getIntegerForKey("Dorm");
if (dorm==_POLLOCK) {
label->setString("POLLOCK DORM AREA");
}
else if(dorm==_EAST){
label->setString("EAST DORM AREA");
}
else if(dorm==_WEST){
label->setString("WEST DORM AREA");
}
else if(dorm==_SOUTH){
label->setString("SOUTH DORM AREA");
}
else if(dorm==_NORTH){
label->setString("NORTH DORM AREA");
}
}
else if(scene==_HUB){
label->setString("HUB AREA");
}
else if(scene==_OLDMAIN){
label->setString("OLD MAIN AREA");
}
else if(scene==_LIFESC){
label->setString("LIFE SCIENCE AREA");
}
else if(scene==_PATTEE){
label->setString("PATTEE LIBRARY AREA");
}
else if(scene==_IST){
label->setString("IST AREA");
}
else if(scene==_ARENA){
label->setString("ARENA");
auto ist_bg=Sprite::create("transit/ist.png");
ist_bg->setPosition(Vec2(origin.x+visibleSize.width/2,origin.y+visibleSize.height/2));
this->addChild(ist_bg,0);
}
this->scheduleUpdate();
return true;
}
void Transit::update(float dt) {
if (stopFrame==false) {
if (ini!=0) {
ini--;
}
else{
stopFrame=true;
if (scene!=_ARENA) {
auto Scene=Game::createScene();
Director::getInstance()->replaceScene(TransitionFade::create(0.5, Scene, Color3B(0,0,0)));
}
else{
auto arenaScene=Arena::createScene();
Director::getInstance()->replaceScene(TransitionFade::create(0.5, arenaScene, Color3B(0,0,0)));
}
}
}
}
void Transit::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
| 29.069565
| 111
| 0.548908
|
alchemz
|
23b6267156ba30d4212a91e8925ca4c296c927a0
| 5,285
|
hpp
|
C++
|
packages/monte_carlo/estimator/native/src/MonteCarlo_CellPulseHeightEstimator.hpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
packages/monte_carlo/estimator/native/src/MonteCarlo_CellPulseHeightEstimator.hpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
packages/monte_carlo/estimator/native/src/MonteCarlo_CellPulseHeightEstimator.hpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_CellPulseHeightEstimator.hpp
//! \author Alex Robinson
//! \brief Cell pulse height estimator class declaration
//!
//---------------------------------------------------------------------------//
#ifndef FACEMC_CELL_PULSE_HEIGHT_ESTIMATOR_HPP
#define FACEMC_CELL_PULSE_HEIGHT_ESTIMATOR_HPP
// Boost Includes
#include <boost/unordered_set.hpp>
#include <boost/mpl/vector.hpp>
// FRENSIE Includes
#include "MonteCarlo_EntityEstimator.hpp"
#include "MonteCarlo_EstimatorContributionMultiplierPolicy.hpp"
#include "MonteCarlo_ParticleEnteringCellEventObserver.hpp"
#include "MonteCarlo_ParticleLeavingCellEventObserver.hpp"
#include "Geometry_ModuleTraits.hpp"
namespace MonteCarlo{
/*! The pulse height entity estimator class
* \details This class has been set up to get correct results with multiple
* threads. However, the commitHistoryContribution member function call
* should only appear within an omp critical block. Use the enable thread
* support member function to set up an instance of this class for the
* requested number of threads. The classes default initialization is for
* a single thread.
*/
template<typename ContributionMultiplierPolicy = WeightMultiplier>
class CellPulseHeightEstimator : public EntityEstimator<Geometry::ModuleTraits::InternalCellHandle>,
public ParticleEnteringCellEventObserver,
public ParticleLeavingCellEventObserver
{
private:
// Typedef for the serial update tracker
typedef boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,
double>
SerialUpdateTracker;
// Typedef for the parallel update tracker
typedef Teuchos::Array<SerialUpdateTracker>
ParallelUpdateTracker;
public:
//! Typedef for the cell id type
typedef Geometry::ModuleTraits::InternalCellHandle cellIdType;
//! Typedef for event tags used for quick dispatcher registering
typedef boost::mpl::vector<ParticleEnteringCellEventObserver::EventTag,
ParticleLeavingCellEventObserver::EventTag>
EventTags;
//! Constructor
CellPulseHeightEstimator( const Estimator::idType id,
const double multiplier,
const Teuchos::Array<cellIdType>& entity_ids );
//! Destructor
~CellPulseHeightEstimator()
{ /* ... */ }
//! Set the response functions
void setResponseFunctions(
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_functions );
//! Set the particle types that can contribute to the estimator
void setParticleTypes( const Teuchos::Array<ParticleType>& particle_types );
//! Add current history estimator contribution
void updateFromParticleEnteringCellEvent( const ParticleState& particle,
const cellIdType cell_entering );
//! Add current history estimator contribution
void updateFromParticleLeavingCellEvent( const ParticleState& particle,
const cellIdType cell_leaving );
//! Commit the contribution from the current history to the estimator
void commitHistoryContribution();
//! Print the estimator data
void print( std::ostream& os ) const;
//! Enable support for multiple threads
void enableThreadSupport( const unsigned num_threads );
//! Reset the estimator data
void resetData();
//! Export the estimator data
void exportData( EstimatorHDF5FileHandler& hdf5_file,
const bool process_data ) const;
private:
// Assign bin boundaries to an estimator dimension
void assignBinBoundaries(
const Teuchos::RCP<EstimatorDimensionDiscretization>& bin_boundaries );
// Calculate the estimator contribution from the entire history
double calculateHistoryContribution( const double energy_deposition,
WeightMultiplier );
// Calculate the estimator contribution from the entire history
double calculateHistoryContribution( const double energy_deposition,
WeightAndEnergyMultiplier );
// Add info to update tracker
void addInfoToUpdateTracker( const unsigned thread_id,
const cellIdType cell_id,
const double contribution );
// Get the entity iterators from the update tracker
void getCellIteratorFromUpdateTracker(
const unsigned thread_id,
typename SerialUpdateTracker::const_iterator& start_cell,
typename SerialUpdateTracker::const_iterator& end_cell ) const;
// Reset the update tracker
void resetUpdateTracker( const unsigned thread_id );
// The entities that have been updated
ParallelUpdateTracker d_update_tracker;
// The generic particle state map (avoids having to make a new map for cont.)
Teuchos::Array<Estimator::DimensionValueMap> d_dimension_values;
};
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//
#include "MonteCarlo_CellPulseHeightEstimator_def.hpp"
//---------------------------------------------------------------------------//
#endif // end FACEMC_CELL_PULSE_HEIGHT_ESTIMATOR_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_CellPulseHeightEstimator.hpp
//---------------------------------------------------------------------------//
| 35.233333
| 101
| 0.693661
|
lkersting
|
23b6b5a280f6b6b9fc6621a21ebcdf8dd9977483
| 5,206
|
cpp
|
C++
|
src/formats/RareSnesInstr.cpp
|
ValleyBell/vgmtrans
|
fc7ad99857450d3a943d8201a05331837e5db938
|
[
"Zlib"
] | 2
|
2021-01-18T05:47:48.000Z
|
2022-03-15T18:27:41.000Z
|
src/formats/RareSnesInstr.cpp
|
ValleyBell/vgmtrans
|
fc7ad99857450d3a943d8201a05331837e5db938
|
[
"Zlib"
] | null | null | null |
src/formats/RareSnesInstr.cpp
|
ValleyBell/vgmtrans
|
fc7ad99857450d3a943d8201a05331837e5db938
|
[
"Zlib"
] | null | null | null |
#include "stdafx.h"
#include "RareSnesInstr.h"
#include "Format.h"
#include "SNESDSP.h"
#include "RareSnesFormat.h"
// ****************
// RareSnesInstrSet
// ****************
RareSnesInstrSet::RareSnesInstrSet(RawFile* file, uint32_t offset, uint32_t spcDirAddr, const std::wstring & name) :
VGMInstrSet(RareSnesFormat::name, file, offset, 0, name),
spcDirAddr(spcDirAddr),
maxSRCNValue(255)
{
Initialize();
}
RareSnesInstrSet::RareSnesInstrSet(RawFile* file, uint32_t offset, uint32_t spcDirAddr,
const std::map<uint8_t, int8_t> & instrUnityKeyHints, const std::map<uint8_t, int16_t> & instrPitchHints, const std::map<uint8_t, uint16_t> & instrADSRHints,
const std::wstring & name) :
VGMInstrSet(RareSnesFormat::name, file, offset, 0, name),
spcDirAddr(spcDirAddr),
maxSRCNValue(255),
instrUnityKeyHints(instrUnityKeyHints),
instrPitchHints(instrPitchHints),
instrADSRHints(instrADSRHints)
{
Initialize();
}
RareSnesInstrSet::~RareSnesInstrSet()
{
}
void RareSnesInstrSet::Initialize()
{
for (uint32_t srcn = 0; srcn < 256; srcn++)
{
uint32_t offDirEnt = spcDirAddr + (srcn * 4);
if (offDirEnt + 4 > 0x10000)
{
maxSRCNValue = srcn - 1;
break;
}
if (GetShort(offDirEnt) == 0)
{
maxSRCNValue = srcn - 1;
break;
}
}
unLength = 0x100;
if (dwOffset + unLength > GetRawFile()->size())
{
unLength = GetRawFile()->size() - dwOffset;
}
ScanAvailableInstruments();
}
void RareSnesInstrSet::ScanAvailableInstruments()
{
availInstruments.clear();
bool firstZero = true;
for (uint32_t inst = 0; inst < unLength; inst++)
{
uint8_t srcn = GetByte(dwOffset + inst);
if (srcn == 0 && !firstZero)
{
continue;
}
if (srcn == 0)
{
firstZero = false;
}
uint32_t offDirEnt = spcDirAddr + (srcn * 4);
if (offDirEnt + 4 > 0x10000)
{
continue;
}
if (srcn > maxSRCNValue)
{
continue;
}
uint16_t addrSampStart = GetShort(offDirEnt);
uint16_t addrSampLoop = GetShort(offDirEnt + 2);
// valid loop?
if (addrSampStart > addrSampLoop)
{
continue;
}
// not in DIR table
if (addrSampStart < spcDirAddr + (128 * 4))
{
continue;
}
// address 0 is probably legit, but it should not be used
if (addrSampStart == 0)
{
continue;
}
// Rare engine does not break the following rule... perhaps
if (addrSampStart < spcDirAddr)
{
continue;
}
availInstruments.push_back(inst);
}
}
bool RareSnesInstrSet::GetHeaderInfo()
{
return true;
}
bool RareSnesInstrSet::GetInstrPointers()
{
for (std::vector<uint8_t>::iterator itr = availInstruments.begin(); itr != availInstruments.end(); ++itr)
{
uint8_t inst = (*itr);
uint8_t srcn = GetByte(dwOffset + inst);
int8_t transpose = 0;
std::map<uint8_t, int8_t>::iterator itrKey;
itrKey = this->instrUnityKeyHints.find(inst);
if (itrKey != instrUnityKeyHints.end())
{
transpose = itrKey->second;
}
int16_t pitch = 0;
std::map<uint8_t, int16_t>::iterator itrPitch;
itrPitch = this->instrPitchHints.find(inst);
if (itrPitch != instrPitchHints.end())
{
pitch = itrPitch->second;
}
uint16_t adsr = 0x8FE0;
std::map<uint8_t, uint16_t>::iterator itrADSR;
itrADSR = this->instrADSRHints.find(inst);
if (itrADSR != instrADSRHints.end())
{
adsr = itrADSR->second;
}
std::wostringstream instrName;
instrName << L"Instrument " << inst;
RareSnesInstr * newInstr = new RareSnesInstr(this, dwOffset + inst, inst >> 7, inst & 0x7f, spcDirAddr, transpose, pitch, adsr, instrName.str());
aInstrs.push_back(newInstr);
}
return aInstrs.size() != 0;
}
const std::vector<uint8_t>& RareSnesInstrSet::GetAvailableInstruments()
{
return availInstruments;
}
// *************
// RareSnesInstr
// *************
RareSnesInstr::RareSnesInstr(VGMInstrSet* instrSet, uint32_t offset, uint32_t theBank, uint32_t theInstrNum, uint32_t spcDirAddr, int8_t transpose, int16_t pitch, uint16_t adsr, const std::wstring& name) :
VGMInstr(instrSet, offset, 1, theBank, theInstrNum, name),
spcDirAddr(spcDirAddr),
transpose(transpose),
pitch(pitch),
adsr(adsr)
{
}
RareSnesInstr::~RareSnesInstr()
{
}
bool RareSnesInstr::LoadInstr()
{
uint8_t srcn = GetByte(dwOffset);
uint32_t offDirEnt = spcDirAddr + (srcn * 4);
if (offDirEnt + 4 > 0x10000)
{
return false;
}
uint16_t addrSampStart = GetShort(offDirEnt);
RareSnesRgn * rgn = new RareSnesRgn(this, dwOffset, transpose, pitch, adsr);
rgn->sampOffset = addrSampStart - spcDirAddr;
aRgns.push_back(rgn);
return true;
}
// ***********
// RareSnesRgn
// ***********
RareSnesRgn::RareSnesRgn(RareSnesInstr* instr, uint32_t offset, int8_t transpose, int16_t pitch, uint16_t adsr) :
VGMRgn(instr, offset, 1),
transpose(transpose),
pitch(pitch),
adsr(adsr)
{
// normalize (it is needed especially since SF2 pitch correction is signed 8-bit)
int16_t pitchKeyShift = (pitch / 100);
int8_t realTranspose = transpose + pitchKeyShift;
int16_t realPitch = pitch - (pitchKeyShift * 100);
// NOTE_PITCH_TABLE[73] == 0x1000
// 0x80 + (73 - 36) = 0xA5
SetUnityKey(36 + 36 - realTranspose);
SetFineTune(realPitch);
SNESConvADSR<VGMRgn>(this, adsr >> 8, adsr & 0xff, 0);
}
RareSnesRgn::~RareSnesRgn()
{
}
bool RareSnesRgn::LoadRgn()
{
return true;
}
| 22.634783
| 205
| 0.684595
|
ValleyBell
|
23b8430bc6dc45bb0fa1a18df8d033da62315651
| 6,716
|
cpp
|
C++
|
src/model.cpp
|
akitsu-sanae/phylan
|
bf949de7b5a91dfd965c3fcc4868b76b4b577375
|
[
"BSL-1.0"
] | null | null | null |
src/model.cpp
|
akitsu-sanae/phylan
|
bf949de7b5a91dfd965c3fcc4868b76b4b577375
|
[
"BSL-1.0"
] | null | null | null |
src/model.cpp
|
akitsu-sanae/phylan
|
bf949de7b5a91dfd965c3fcc4868b76b4b577375
|
[
"BSL-1.0"
] | null | null | null |
/*============================================================================
Copyright (C) 2016 akitsu sanae
https://github.com/akitsu-sanae/phylan
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
============================================================================*/
#include <GLFW/glfw3.h>
#include "model.hpp"
#include "world.hpp"
#include "ast.hpp"
#include "rope.hpp"
ph::Model::Model(ph::World& world, std::istream& input) :
m_world(world)
{
m_ast = ph::Element::load(input);
m_ast->regist(world);
m_ropes = ph::Rope::set(m_ast.get(), *world.world_info());
m_ropes.push_back(std::make_shared<Rope>(*m_ast, *world.world_info()));
for (auto&& rope : m_ropes)
rope->regist(world);
m_selected_element = m_ast.get();
}
ph::Model::~Model() {
for (auto&& rope : m_ropes)
rope->remove(m_world);
m_ast->remove(m_world);
}
void ph::Model::draw() const {
m_ast->draw(m_selected_element);
for (auto const& rope : m_ropes)
rope->draw();
}
void ph::Model::save() const {
m_ast->save();
}
void ph::Model::move(ph::Model::Move move) {
Element* tmp = nullptr;
switch (move) {
case Move::Next:
tmp = m_selected_element->next();
break;
case Move::Prev:
tmp = m_selected_element->prev();
break;
case Move::Parent:
tmp = m_selected_element->parent();
break;
}
if (tmp)
m_selected_element = tmp;
}
void add_element(
std::unique_ptr<ph::Element>& ast,
ph::Element* selected,
std::unique_ptr<ph::Element>& e) {
if (auto mult = ph::node_cast<ph::NodeType::Mult>(ast.get())) {
if (mult->lhs.get() == selected) {
mult->lhs = std::move(e);
mult->lhs->parent(mult);
} else
add_element(mult->lhs, selected, e);
if (mult->rhs.get() == selected) {
mult->rhs = std::move(e);
mult->rhs->parent(mult);
} else
add_element(mult->rhs, selected, e);
} else if (auto plus = ph::node_cast<ph::NodeType::Plus>(ast.get())) {
if (plus->lhs.get() == selected) {
plus->lhs = std::move(e);
plus->lhs->parent(plus);
} else
add_element(plus->lhs, selected, e);
if (plus->rhs.get() == selected) {
plus->rhs = std::move(e);
plus->rhs->parent(plus);
} else
add_element(plus->rhs, selected, e);
} else if (auto print = ph::node_cast<ph::NodeType::Print>(ast.get())) {
if (print->val.get() == selected) {
print->val = std::move(e);
print->val->parent(print);
} else
add_element(print->val, selected, e);
} else if (auto if_ = ph::node_cast<ph::NodeType::If>(ast.get())) {
if (if_->cond.get() == selected) {
if_->cond = std::move(e);
if_->cond->parent(if_);
} else
add_element(if_->cond, selected, e);
if (if_->true_.get() == selected) {
if_->true_ = std::move(e);
if_->true_->parent(if_);
} else
add_element(if_->true_, selected, e);
if (if_->false_.get() == selected) {
if_->false_ = std::move(e);
if_->false_->parent(if_);
} else
add_element(if_->false_, selected, e);
}
}
std::unique_ptr<ph::Element> make_node(ph::Element const* selected) {
std::string type = "";
while (true) {
std::cout << "what type? (plus, mult, print, number)" << std::endl;
std::cin >> type;
if (type == "plus")
break;
if (type == "mult")
break;
if (type == "print")
break;
if (type == "if")
break;
if (type == "number")
break;
}
std::unique_ptr<ph::Element> element;
if (type == "plus") {
auto pos = ph::Point::from_vec(selected->position());
auto plus = std::make_unique<ph::Node<ph::NodeType::Plus>>(pos);
plus->lhs = std::make_unique<ph::Undefined>(pos);
plus->rhs = std::make_unique<ph::Undefined>(pos);
plus->lhs->parent(plus.get());
plus->rhs->parent(plus.get());
element = std::move(plus);
} else if (type == "mult") {
auto pos = ph::Point::from_vec(selected->position());
auto mult = std::make_unique<ph::Node<ph::NodeType::Mult>>(pos);
mult->lhs = std::make_unique<ph::Undefined>(pos);
mult->rhs = std::make_unique<ph::Undefined>(pos);
mult->lhs->parent(mult.get());
mult->rhs->parent(mult.get());
element = std::move(mult);
} else if (type == "if") {
auto pos = ph::Point::from_vec(selected->position());
auto if_ = std::make_unique<ph::Node<ph::NodeType::If>>(pos);
if_->cond = std::make_unique<ph::Undefined>(pos);
if_->true_ = std::make_unique<ph::Undefined>(pos);
if_->false_ = std::make_unique<ph::Undefined>(pos);
if_->cond->parent(if_.get());
if_->true_->parent(if_.get());
if_->false_->parent(if_.get());
element = std::move(if_);
} else if (type == "print") {
auto pos = ph::Point::from_vec(selected->position());
auto print = std::make_unique<ph::Node<ph::NodeType::Print>>(pos);
print->val = std::make_unique<ph::Undefined>(pos);
print->val->parent(print.get());
element = std::move(print);
} else if (type == "number") {
std::cout << "value: ";
int n;
std::cin >> n;
element = std::make_unique<ph::Literal>(ph::Point::from_vec(selected->position()), n);
}
return element;
}
void ph::Model::edit() {
if (m_selected_element == m_ast.get()) {
std::cerr << "you cen not edit the root node!" << std::endl;
return;
}
std::unique_ptr<Element> element;
if (!dynamic_cast<ph::Undefined*>(m_selected_element))
element = std::make_unique<Undefined>(Point::from_vec(m_selected_element->position()));
else
element = make_node(m_selected_element);
for (auto&& rope : m_ropes)
rope->remove(m_world);
m_ast->remove(m_world);
// swap element and m_selected_element
add_element(m_ast, m_selected_element, element);
m_ropes.clear();
m_ropes = ph::Rope::set(m_ast.get(), *m_world.world_info());
m_ropes.push_back(std::make_shared<Rope>(*m_ast, *m_world.world_info()));
m_ast->regist(m_world);
for (auto&& rope : m_ropes)
rope->regist(m_world);
m_selected_element = m_ast.get();
}
int ph::Model::eval() const {
return m_ast->value();
}
| 33.247525
| 95
| 0.544818
|
akitsu-sanae
|
23bacc4836a2719609c6d5f7e06370e32f250472
| 3,953
|
cpp
|
C++
|
test/fence_counting.cpp
|
mdsudara/percy
|
b593922b98c9c20fe0a3e4726e50401e54b9cb09
|
[
"MIT"
] | 14
|
2018-03-10T21:50:20.000Z
|
2021-11-22T04:09:09.000Z
|
test/fence_counting.cpp
|
mdsudara/percy
|
b593922b98c9c20fe0a3e4726e50401e54b9cb09
|
[
"MIT"
] | 3
|
2018-06-12T15:17:22.000Z
|
2019-06-20T12:00:45.000Z
|
test/fence_counting.cpp
|
mdsudara/percy
|
b593922b98c9c20fe0a3e4726e50401e54b9cb09
|
[
"MIT"
] | 12
|
2018-03-10T17:02:07.000Z
|
2022-01-09T16:04:56.000Z
|
#include <percy/percy.hpp>
#include <cassert>
#include <cstdio>
#include <vector>
using namespace percy;
using std::vector;
/*******************************************************************************
Counts and prints all fences up to and including F_5 and ensures that the
number is correct.
*******************************************************************************/
int main(void)
{
fence f;
auto total_expected_fences = 0u;
for (unsigned k = 1; k <= 5; k++) {
printf("F_%u\n", k);
for (unsigned l = 1; l <= k; l++) {
printf("F(%u, %u)\n", k, l);
partition_generator g(k, l);
auto nfences = 0u;
while (g.next_fence(f)) {
nfences++;
print_fence(f);
printf("\n");
}
const auto expected_fences = binomial_coeff(k-1, l-1);
assert(nfences == expected_fences);
total_expected_fences += nfences;
}
auto nfences = 0u;
family_generator g(k);
auto expected_fences = 0u;
for (auto l = 1u; l <= k; l++) {
expected_fences += binomial_coeff(k-1, l-1);
}
while (g.next_fence(f)) {
nfences++;
}
assert(nfences == (unsigned)expected_fences);
}
unbounded_generator g;
auto nfences = 0u;
while (true) {
g.next_fence(f);
if (g.get_nnodes() >= 6) {
break;
}
nfences++;
}
assert(nfences == total_expected_fences);
rec_fence_generator recgen;
recgen.set_po_filter(false);
for (unsigned k = 1; k <= 5; k++) {
printf("F_%u\n", k);
auto total_nr_fences = 0u;
for (unsigned l = 1; l <= k; l++) {
printf("F(%u, %u)\n", k, l);
recgen.reset(k, l);
vector<fence> fences;
recgen.generate_fences(fences);
const auto nfences = fences.size();
for (auto& f : fences) {
print_fence(f);
printf("\n");
}
const auto expected_fences = binomial_coeff(k-1, l-1);
assert(nfences == expected_fences);
total_nr_fences += nfences;
}
auto fences = generate_fences(k, false);
assert(fences.size() == total_nr_fences);
}
// Count the maximum number of fences needed to synthesize all 5-input
// functions.
auto global_total = 0u;
recgen.set_po_filter(true);
vector<fence> po_fences;
for (unsigned k = 1; k <= 12; k++) {
auto total_nr_fences = 0u;
for (unsigned l = 1; l <= k; l++) {
recgen.reset(k, l);
total_nr_fences += recgen.count_fences();
}
generate_fences(po_fences, k);
global_total += total_nr_fences;
printf("Number of fences in F_%d = %d\n", k, total_nr_fences);
}
assert(po_fences.size() == global_total);
for (unsigned k = 13; k <= 15; k++) {
auto total_nr_fences = 0u;
for (unsigned l = 1; l <= k; l++) {
recgen.reset(k, l);
total_nr_fences += recgen.count_fences();
}
printf("Number of fences in F_%u = %d\n", k, total_nr_fences);
}
printf("Nr. of fences relevant to 5-input single-output synthesis is %d\n",
global_total);
// Count the number of fence relevant to synthesizing single-output chains
// with 3-input operators
global_total = 0;
recgen.set_po_filter(true);
po_fences.clear();
for (unsigned k = 1; k <= 15; k++) {
auto total_nr_fences = 0;
for (unsigned l = 1; l <= k; l++) {
recgen.reset(k, l, 1, 3);
total_nr_fences += recgen.count_fences();
}
generate_fences(po_fences, k);
global_total += total_nr_fences;
printf("Number of fences in F_%u = %u (3-input gates)\n", k, total_nr_fences);
}
return 0;
}
| 31.125984
| 86
| 0.510751
|
mdsudara
|
23bcd21af6406c7041ba801dab6dcc72689b9dd5
| 2,240
|
hpp
|
C++
|
src/base/include/structs.hpp
|
N4G170/generic
|
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
|
[
"MIT"
] | null | null | null |
src/base/include/structs.hpp
|
N4G170/generic
|
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
|
[
"MIT"
] | null | null | null |
src/base/include/structs.hpp
|
N4G170/generic
|
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
|
[
"MIT"
] | null | null | null |
#ifndef STRUCTS_HPP
#define STRUCTS_HPP
#include <type_traits>
#include <string>
#include "vector3.hpp"
#include "enums.hpp"
#include "SDL.h"
template<typename T>
struct Bounds
{
//check if we initialize the vector with the right values
static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "Bounds template can only integrals of floating point types");
T min_x{0}, min_y{0}, min_z{0}, max_x{0}, max_y{0}, max_z{0};
Bounds(): min_x{0}, min_y{0}, min_z{0}, max_x{0}, max_y{0}, max_z{0} {};
Bounds(T minx, T miny, T minz, T maxx, T maxy, T maxz): min_x{minx}, min_y{miny}, min_z{minz}, max_x{maxx}, max_y{maxy}, max_z{maxz} {};
Bounds(const Vector3<T>& position, const Vector3<T>& size): min_x{position.X()}, min_y{position.Y()}, min_z{position.Z()},
max_x{position.X() + size.X()}, max_y{position.Y() + size.Y()}, max_z{position.Z() + size.Z()} {}
Vector3<T> Size(){ return {max_x - min_x, max_y - min_y, max_z - min_z}; }
Vector3<T> PointPosition(BoundsPositions bounds_position = BoundsPositions::Front_Top_Left)
{
switch (bounds_position)
{
case BoundsPositions::Front_Top_Left: return {min_x, min_y, min_z}; break;
case BoundsPositions::Front_Top_Right: return {max_x, min_y, min_z}; break;
case BoundsPositions::Front_Bottom_Left: return {min_x, max_y, min_z}; break;
case BoundsPositions::Front_Bottom_Right: return {max_x, max_y, min_z}; break;
case BoundsPositions::Back_Top_Left: return {min_x, min_y, max_z}; break;
case BoundsPositions::Back_Top_Right: return {max_x, min_y, max_z}; break;
case BoundsPositions::Back_Bottom_Left: return {min_x, max_y, max_z}; break;
case BoundsPositions::Back_Bottom_Right: return {max_x, max_y, max_z}; break;
default: return {min_x, min_y, min_z};
}
}
};
struct BasicFrame
{
std::string image_path{};
bool has_src_rect{false};
SDL_Rect source_rect{0,0,0,0};
BasicFrame(const std::string& path, bool has_rect, const SDL_Rect& src_rect) : image_path{path}, has_src_rect{has_rect}, source_rect{src_rect} {}
};
#endif //STRUCTS_HPP
| 42.264151
| 149
| 0.658036
|
N4G170
|
23bf3d4e2e7fccc5f011f98b95a9fa02783391b3
| 1,604
|
cpp
|
C++
|
src/type.cpp
|
robey/nolove
|
d83e5ba34e5e53dbef066f4da2f22c6cc2d0572c
|
[
"Apache-2.0"
] | 1
|
2015-11-05T12:17:23.000Z
|
2015-11-05T12:17:23.000Z
|
src/type.cpp
|
robey/nolove
|
d83e5ba34e5e53dbef066f4da2f22c6cc2d0572c
|
[
"Apache-2.0"
] | null | null | null |
src/type.cpp
|
robey/nolove
|
d83e5ba34e5e53dbef066f4da2f22c6cc2d0572c
|
[
"Apache-2.0"
] | null | null | null |
#include "llvm/Support/raw_ostream.h"
#include "type.h"
using namespace v8;
// ----- LType
NodeProto<LType> LType::proto("Type");
void LType::init() {
proto.addMethod("isDoubleType", <ype::isDoubleType);
proto.addMethod("isFunctionType", <ype::isFunctionType);
proto.addMethod("toString", <ype::toString);
}
Handle<Value> LType::isDoubleType(const Arguments& args) {
return Boolean::New(type()->isDoubleTy());
}
Handle<Value> LType::isFunctionType(const Arguments& args) {
return Boolean::New(type()->isFunctionTy());
}
Handle<Value> LType::toString(const Arguments& args) {
std::string s("<Type ");
llvm::raw_string_ostream os(s);
type()->print(os);
os << ">";
return String::New(os.str().c_str());
}
// ----- LFunctionType
NodeProto<LFunctionType> LFunctionType::proto("FunctionType");
void LFunctionType::init() {
proto.inherit(LType::proto);
proto.addMethod("isVarArg", &LFunctionType::isVarArg);
proto.addMethod("getNumParams", &LFunctionType::getNumParams);
proto.addMethod("getParamType", &LFunctionType::getParamType);
}
Handle<Value> LFunctionType::isVarArg(const Arguments& args) {
return Boolean::New(functionType()->isVarArg());
}
Handle<Value> LFunctionType::getNumParams(const Arguments& args) {
return Integer::New(functionType()->getNumParams());
}
Handle<Value> LFunctionType::getParamType(const Arguments& args) {
CHECK_ARG_COUNT("getParamType", 1, 1, "index: Number");
CHECK_ARG_NUMBER(0);
unsigned int index = (unsigned int) args[0]->ToNumber()->Value();
return LType::create(functionType()->getParamType(index))->handle_;
}
| 28.140351
| 69
| 0.714464
|
robey
|
23bf978e1a5d09fea9cb909b5ec53ef5d141c86e
| 1,564
|
cpp
|
C++
|
gui/NativeWindow.cpp
|
razaqq/PotatoAlert
|
4dfb54a7841ca71d8dbf58620173f2a9fc1886f2
|
[
"MIT"
] | 20
|
2020-06-16T01:30:29.000Z
|
2022-03-08T14:54:30.000Z
|
gui/NativeWindow.cpp
|
razaqq/PotatoAlert
|
4dfb54a7841ca71d8dbf58620173f2a9fc1886f2
|
[
"MIT"
] | 26
|
2019-07-15T10:49:47.000Z
|
2022-02-16T19:25:48.000Z
|
gui/NativeWindow.cpp
|
razaqq/PotatoAlert
|
4dfb54a7841ca71d8dbf58620173f2a9fc1886f2
|
[
"MIT"
] | 5
|
2020-06-16T01:31:03.000Z
|
2022-01-22T19:43:48.000Z
|
// Copyright 2020 <github.com/razaqq>
#include <QWidget>
#include <QVBoxLayout>
#include <QMainWindow>
#include <QWindow>
#include "NativeWindow.hpp"
#include "TitleBar.hpp"
#include "Config.hpp"
#include "FramelessWindowsManager.hpp"
using PotatoAlert::NativeWindow;
NativeWindow::NativeWindow(QMainWindow* mainWindow) : QWidget()
{
this->mainWindow = mainWindow;
this->mainWindow->setParent(this);
this->init();
}
void NativeWindow::closeEvent(QCloseEvent* event)
{
PotatoConfig().set<int>("window_height", this->height());
PotatoConfig().set<int>("window_width", this->width());
PotatoConfig().set<int>("window_x", this->x());
PotatoConfig().set<int>("window_y", this->y());
QWidget::closeEvent(event);
}
void NativeWindow::init()
{
this->createWinId();
QWindow* w = this->windowHandle();
this->titleBar->setFixedHeight(23);
for (auto& o : this->titleBar->getIgnores())
FramelessWindowsManager::addIgnoreObject(w, o);
FramelessWindowsManager::addWindow(w);
FramelessWindowsManager::setBorderWidth(w, borderWidth);
FramelessWindowsManager::setBorderHeight(w, borderWidth);
FramelessWindowsManager::setTitleBarHeight(w, this->titleBar->height());
auto layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(this->titleBar);
layout->addWidget(this->mainWindow);
this->setLayout(layout);
this->resize(PotatoConfig().get<int>("window_width"), PotatoConfig().get<int>("window_height"));
this->move(PotatoConfig().get<int>("window_x"), PotatoConfig().get<int>("window_y"));
}
| 26.508475
| 97
| 0.734655
|
razaqq
|
23c3004cf0c9368068db9a38c09ea79a4e2a8414
| 1,558
|
cpp
|
C++
|
basic/tree/print_all_ancestors.cpp
|
sanjosh/smallprogs
|
8acf7a357080b9154b55565be7c7667db0d4049b
|
[
"Apache-2.0"
] | 7
|
2017-02-28T06:33:43.000Z
|
2021-12-17T04:58:19.000Z
|
basic/tree/print_all_ancestors.cpp
|
sanjosh/smallprogs
|
8acf7a357080b9154b55565be7c7667db0d4049b
|
[
"Apache-2.0"
] | null | null | null |
basic/tree/print_all_ancestors.cpp
|
sanjosh/smallprogs
|
8acf7a357080b9154b55565be7c7667db0d4049b
|
[
"Apache-2.0"
] | 3
|
2017-02-28T06:33:30.000Z
|
2021-02-25T09:42:31.000Z
|
/*
http://en.wikipedia.org/wiki/Level_ancestor_problem
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.
For example, if the given tree is following Binary Tree and key is 7, then your function should print 4, 2 and 1.
1
/ \
2 3
/ \
4 5
/
7
Thanks to Mike , Sambasiva and wgpshashank for their contribution.
*/
#include <iostream>
#include <stdlib.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
int data;
Node* left = nullptr;
Node* right = nullptr;
Node(int d) : data(d) { }
};
struct Algo
{
int data;
Algo(int d) : data(d) {}
bool predicate(const Node* n)
{
return (n->data == this->data);
}
void postProcess(const Node* p)
{
cout << p->data << endl;
}
};
bool preorder(const Node* current, Algo& a)
{
if (current == nullptr)
{
return false;
}
if (a.predicate(current))
{
return true;
}
auto x = preorder(current->left, a);
auto y = preorder(current->right, a);
if (x || y) {
a.postProcess(current);
}
return x || y;
}
int main()
{
Algo a(4);
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->left->left = new Node(7);
preorder(root, a);
}
| 17.120879
| 114
| 0.560334
|
sanjosh
|
23c9ace5e859445761efa5495bdc621173051908
| 20,355
|
cpp
|
C++
|
src/client/vhsm_admin/vhsm_admin.cpp
|
OSLL/vhsm
|
a06820919438f11be25df05978dcb679615f5b0b
|
[
"MIT"
] | 8
|
2015-09-27T01:31:25.000Z
|
2020-10-29T17:05:12.000Z
|
src/client/vhsm_admin/vhsm_admin.cpp
|
OSLL/vhsm
|
a06820919438f11be25df05978dcb679615f5b0b
|
[
"MIT"
] | null | null | null |
src/client/vhsm_admin/vhsm_admin.cpp
|
OSLL/vhsm
|
a06820919438f11be25df05978dcb679615f5b0b
|
[
"MIT"
] | 2
|
2015-05-20T18:54:14.000Z
|
2021-11-04T19:40:18.000Z
|
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include "vhsm_api_prototype/common.h"
#include "vhsm_api_prototype/key_mgmt.h"
#include "vhsm_api_prototype/mac.h"
#include "vhsm_api_prototype/digest.h"
#define BUF_SIZE 4096
#define BUF_TIME_SIZE 256
#define HELP_BASE 1
#define HELP_GENERATE 2
#define HELP_IMPORT 4
#define HELP_KEYINFO 8
#define HELP_DELETE 16
#define HELP_HMAC 32
#define EXIT_OK 0
#define EXIT_BAD_ARGS 1
#define EXIT_VHSM_ERR 2
#define CMD_UNKNOWN 0
#define CMD_HELP 1
#define CMD_GENERATE 2
#define CMD_IMPORT 3
#define CMD_KEYINFO 4
#define CMD_DELETE 5
#define CMD_HMAC 6
//------------------------------------------------------------------------------
void showHelp(int sections) {
std::cout << "VHSM administration tool" << std::endl;
if(sections & HELP_BASE) {
std::cout << "List of available commands. Use 'vhsm_admin <command> help' for details." << std::endl;
std::cout << "generate - generates key with the given key length and optional key purpose" << std::endl;
std::cout << " and key id; returns the key id" << std::endl;
std::cout << "import - imports key or key-file with the given key length and optional" << std::endl;
std::cout << " key purpose and key id; returns the key id" << std::endl;
std::cout << "delete - deletes key with the given key id" << std::endl;
std::cout << "keyinfo - prints information about user keys" << std::endl;
std::cout << "hmac - computes hmac of the given file with the specified vhsm-key" << std::endl;
}
if(sections & HELP_GENERATE) {
std::cout << "vhsm_admin generate <user> <password> <key length> [--purpose=value] [--keyid=id]" << std::endl;
std::cout << "Generates key with the given key length." << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "purpose - integer key purpose; default value: 0;" << std::endl;
std::cout << "keyid - user-defined id for the new key;" << std::endl;
std::cout << "VHSM generates key id if it's not specified. Returns id of the newly generated key" << std::endl;
}
if(sections & HELP_IMPORT) {
std::cout << "vhsm_admin import <user> <password> <--file=path> [--purpose=value] [--keyid=id]" << std::endl;
std::cout << "vhsm_admin import <user> <password> <--key=key> [--purpose=value] [--keyid=id]" << std::endl;
std::cout << "Imports specified key or key-file." << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "purpose - key purpose; default value: 0;" << std::endl;
std::cout << "keyid - user-defined id for the new key;" << std::endl;
std::cout << "VHSM generates key id if it's not specified. Returns id of the imported key" << std::endl;
}
if(sections & HELP_KEYINFO) {
std::cout << "vhsm_admin keyinfo <user> <password> [ids...]" << std::endl;
std::cout << "Prints information about keys for the specified user." << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "ids - return information only for the specified list of key ids" << std::endl;
}
if(sections & HELP_DELETE) {
std::cout << "vhsm_admin delete <user> <password> <keyid>" << std::endl;
std::cout << "Deletes key with the given key id" << std::endl;;
}
if(sections & HELP_HMAC) {
std::cout << "vhsm_admin hmac <user> <password> <--file=path> <--keyid=id> [--md=sha1] [-b|-h]" << std::endl;
std::cout << "Computes hmac for the specified file using specified key stored in vhsm" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "file - path to the file" << std::endl;
std::cout << "keyid - id of the key to use in hmac" << std::endl;
std::cout << "md - digest algorithm to use in hmac. Only SHA1 is currently supported" << std::endl;
std::cout << "-b - output in binary format" << std::endl;
std::cout << "-h - output in hex format (default)" << std::endl;
std::cout << "Prints hmac digest of the file in hex or binary format" << std::endl;
}
}
//------------------------------------------------------------------------------
/*
void create_user(int argc, char ** argv) {
if (3 != argc) {
show_help();
return;
}
VhsmStorage storage(argv[0]);
if(storage.createUser(argv[1], argv[2])) {
std::cout << "Unable to create user" << std::endl;
}
}
void init_root(int argc, char ** argv) {
if (1 != argc) {
show_help();
return;
}
std::string path = argv[0];
mkdir(path.c_str(), 0777);
std::cout << "Initializing database at: " << path << std::endl;
VhsmStorage storage(path);
if(!storage.initDatabase()) {
std::cout << "Unable to init database" << std::endl;
}
}
*/
//------------------------------------------------------------------------------
static int commandId(const std::string &str) {
if(str == "help" || str == "--help" || str == "-h") return CMD_HELP;
if(str == "generate") return CMD_GENERATE;
if(str == "import") return CMD_IMPORT;
if(str == "keyinfo") return CMD_KEYINFO;
if(str == "delete") return CMD_DELETE;
if(str == "hmac") return CMD_HMAC;
return CMD_UNKNOWN;
}
//------------------------------------------------------------------------------
static bool vhsmEnter(vhsm_session &s, const std::string &username, const std::string &password) {
if(vhsm_start_session(&s) != VHSM_RV_OK) {
std::cout << "Error: unable to start vhsm session" << std::endl;
return false;
}
vhsm_credentials user;
memset(user.username, 0, sizeof(user.username));
memset(user.password, 0, sizeof(user.password));
strncpy(user.username, username.c_str(), std::min(username.size(), sizeof(user.username)));
strncpy(user.password, password.c_str(), std::min(password.size(), sizeof(user.password)));
if(vhsm_login(s, user) != VHSM_RV_OK) {
std::cout << "Error: unable to login user" << std::endl;
vhsm_end_session(s);
return false;
}
return true;
}
static void vhsmExit(vhsm_session &s) {
vhsm_logout(s);
vhsm_end_session(s);
}
static vhsm_key_id vhsmGetKeyID(const std::string &keyID) {
vhsm_key_id id;
memset(id.id, 0, sizeof(id.id));
if(!keyID.empty()) strncpy((char*)id.id, keyID.c_str(), std::min(keyID.size(), sizeof(id.id)));
return id;
}
static std::string vhsmErrorCode(int ec) {
switch(ec) {
case VHSM_RV_OK: return "no error";
case VHSM_RV_KEY_ID_OCCUPIED: return "key id occupied";
case VHSM_RV_KEY_NOT_FOUND: return "key id not found";
case VHSM_RV_BAD_BUFFER_SIZE: return "bad buffer size";
case VHSM_RV_BAD_SESSION: return "bad session";
case VHSM_RV_NOT_AUTHORIZED: return "user is not authorized";
case VHSM_RV_BAD_CREDENTIALS: return "bad username or password";
case VHSM_RV_BAD_DIGEST_METHOD: return "unsupported digest method requested";
case VHSM_RV_MAC_INIT_ERR: return "unable to init mac";
case VHSM_RV_BAD_MAC_METHOD: return "unsupported mac method requested";
case VHSM_RV_MAC_NOT_INITIALIZED: return "mac context is not initialized";
case VHSM_RV_BAD_ARGUMENTS: return "bad arguments";
default: return "unknown error";
}
}
//------------------------------------------------------------------------------
static int generateKey(int argc, char **argv) {
if(argc < 3 || argc > 5) {
showHelp(HELP_GENERATE);
return EXIT_BAD_ARGS;
}
int keyLength = std::strtol(argv[2], NULL, 10);
int keyPurpose = 0;
std::string keyID = "";
for(int i = 3; i < argc; ++i) {
std::string arg(argv[i]);
size_t vpos = arg.find('=');
if(vpos == std::string::npos && arg.at(0) == '-') {
std::cout << "Error: value for option \'" << arg << "\' is not specified" << std::endl;
return EXIT_BAD_ARGS;
} else if(vpos == std::string::npos) {
std::cout << "Error: unknown option: " << argv[i] << std::endl;
return EXIT_BAD_ARGS;
}
if(arg.find("--purpose=") == 0) keyPurpose = std::strtol(argv[i] + vpos + 1, NULL, 10);
else if(arg.find("--keyid=") == 0) keyID = arg.substr(vpos + 1);
else {
std::cout << "Error: unknown option: " << argv[i] << std::endl;
showHelp(HELP_GENERATE);
return EXIT_BAD_ARGS;
}
}
vhsm_key_id kid = vhsmGetKeyID(keyID);
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
int exitCode = EXIT_OK;
int res = vhsm_key_mgmt_generate_key(s, &kid, keyLength, keyPurpose);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to generate key: " << vhsmErrorCode(res) << std::endl;
exitCode = EXIT_VHSM_ERR;
} else {
std::cout << kid.id << std::endl;
}
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static int importKey(int argc, char **argv) {
if(argc < 3 || argc > 5) {
showHelp(HELP_IMPORT);
return EXIT_BAD_ARGS;
}
int keyPurpose = 0;
std::string keyID = "";
std::string realKey = "";
std::string keyPath = "";
for(int i = 2; i < argc; ++i) {
std::string arg(argv[i]);
size_t vpos = arg.find('=');
if(vpos == std::string::npos && arg.at(0) == '-') {
std::cout << "Error: value for option \'" << arg << "\' is not specified" << std::endl;
return EXIT_BAD_ARGS;
} else if(vpos == std::string::npos) {
std::cout << "Error: unknown option: " << argv[i] << std::endl;
return EXIT_BAD_ARGS;
}
if(arg.find("--purpose=") == 0) keyPurpose = std::strtol(argv[i] + vpos + 1, NULL, 10);
else if(arg.find("--keyid=") == 0) keyID = arg.substr(vpos + 1);
else if(arg.find("--key=") == 0) realKey = arg.substr(vpos + 1);
else if(arg.find("--file=") == 0) keyPath = arg.substr(vpos + 1);
else {
std::cout << "Error: unknown argument: " << argv[i] << std::endl;
showHelp(HELP_IMPORT);
return EXIT_BAD_ARGS;
}
}
if((!realKey.empty() && !keyPath.empty()) || (realKey.empty() && keyPath.empty())) {
std::cout << "Error: bad arguments" << std::endl;
showHelp(HELP_IMPORT);
return EXIT_BAD_ARGS;
}
if(!keyPath.empty()) {
std::ifstream keyIn(keyPath.c_str(), std::ifstream::in | std::ifstream::binary);
if(!keyIn.is_open()) {
std::cout << "Error: unable to open key file: " << keyPath.c_str() << std::endl;
return EXIT_BAD_ARGS;
}
char buf[BUF_SIZE];
while(!keyIn.eof()) {
size_t ln = keyIn.readsome(buf, BUF_SIZE);
if(ln == 0) break;
realKey.append(std::string(buf, ln));
}
keyIn.close();
}
if(realKey.size() > VHSM_MAX_DATA_LENGTH) {
std::cout << "Error: unsupported key length; current max key length: " << VHSM_MAX_DATA_LENGTH << " bytes" << std::endl;
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
vhsm_key key;
vhsm_key_id newKeyID;
key.id = vhsmGetKeyID(keyID);
key.key_data = const_cast<char*>(realKey.data());
key.data_size = realKey.size();
int exitCode = EXIT_OK;
int res = vhsm_key_mgmt_create_key(s, key, &newKeyID, keyPurpose);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to generate key: " << vhsmErrorCode(res) << std::endl;
exitCode = EXIT_VHSM_ERR;
} else {
std::cout << newKeyID.id << std::endl;
}
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static std::string timeToString(uint64_t secs) {
tm *rawTime = gmtime((time_t*)&secs);
char timeBuf[BUF_TIME_SIZE];
size_t ln = std::strftime(timeBuf, BUF_TIME_SIZE, "%FT%T%z", rawTime);
return std::string(timeBuf, ln);
}
static int getKeyInfo(int argc, char **argv) {
if(argc < 2) {
showHelp(HELP_KEYINFO);
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
vhsm_key_info *keyInfo = 0;
unsigned int keyCount = 0;
int exitCode = EXIT_VHSM_ERR;
if(argc == 2) {
int res = vhsm_key_mgmt_get_key_info(s, NULL, &keyCount);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to get key count: " << vhsmErrorCode(res) << std::endl;
goto vhsm_exit;
}
if(keyCount == 0) {
std::cout << "No keys found for user: " << argv[0] << std::endl;
goto vhsm_exit;
}
keyInfo = new vhsm_key_info[keyCount];
res = vhsm_key_mgmt_get_key_info(s, keyInfo, &keyCount);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to get key info: " << vhsmErrorCode(res) << std::endl;
keyCount = 0;
} else {
exitCode = EXIT_OK;
}
} else {
keyCount = argc - 2;
keyInfo = new vhsm_key_info[keyCount];
unsigned int realKeyCount = 0;
for(unsigned int i = 0; i < keyCount; ++i) {
vhsm_key_id keyID;
memset(keyID.id, 0, sizeof(keyID.id));
strncpy((char*)keyID.id, argv[i + 2], std::min(strlen(argv[i + 2]), sizeof(keyID.id)));
if(vhsm_key_mgmt_get_key_info(s, keyID, &keyInfo[realKeyCount]) != VHSM_RV_OK) {
std::cout << "Error: key with id \'" << keyID.id << "\' not found" << std::endl;
} else {
realKeyCount++;
}
}
keyCount = realKeyCount;
}
if(keyCount > 0) std::cout << "Key ID\t\t\tLength\tPurpose\tImport date" << std::endl;
for(unsigned int i = 0; i < keyCount; ++i) {
std::cout << keyInfo[i].key_id.id << "\t";
size_t idLength = strlen((char*)keyInfo[i].key_id.id);
if(idLength < 16) std::cout << "\t";
if(idLength < 8) std::cout << "\t";
std::cout << keyInfo[i].length << "\t";
std::cout << keyInfo[i].purpose << "\t";
std::cout << timeToString(keyInfo[i].import_date) << std::endl;
}
delete[] keyInfo;
vhsm_exit:
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static int deleteKey(int argc, char **argv) {
if(argc != 3) {
showHelp(HELP_DELETE);
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
vhsm_key_id keyId = vhsmGetKeyID(argv[2]);
int exitCode = EXIT_OK;
int res = vhsm_key_mgmt_delete_key(s, keyId);
if(res != VHSM_RV_OK) {
std::cout << "Key with id '" << argv[2] << "' not found" << std::endl;
exitCode = EXIT_VHSM_ERR;
} else {
std::cout << "Key with id '" << argv[2] << "' was successfully deleted" << std::endl;
}
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static bool setDigest(vhsm_mac_method &mac, const std::string &digestName) {
if(digestName == "sha1") {
vhsm_digest_method *dm = new vhsm_digest_method;
dm->digest_method = VHSM_DIGEST_SHA1;
dm->method_params = NULL;
mac.method_params = dm;
return true;
}
return false;
}
static void freeDigest(vhsm_mac_method &mac, const std::string &digestName) {
if(digestName == "sha1") {
delete (vhsm_digest_method*)mac.method_params;
}
}
static int computeHMAC(int argc, char **argv) {
if(argc < 4 || argc > 6) {
showHelp(HELP_HMAC);
return EXIT_BAD_ARGS;
}
std::string keyID = "";
std::string filePath = "";
std::string mdAlgName = "sha1";
bool binOutput = false;
for(int i = 2; i < argc; ++i) {
std::string arg(argv[i]);
if(arg == "-b") {
binOutput = true;
continue;
} else if(arg == "-h") {
binOutput = false;
continue;
}
size_t vpos = arg.find('=');
if(vpos == std::string::npos && arg.at(0) == '-') {
std::cout << "Error: value for option \'" << arg << "\' is not specified" << std::endl;
return EXIT_BAD_ARGS;
} else if(vpos == std::string::npos) {
std::cout << "Error: unknown option: " << arg << std::endl;
return EXIT_BAD_ARGS;
}
if(arg.find("--keyid=") == 0) keyID = arg.substr(vpos + 1);
else if(arg.find("--file=") == 0) filePath = arg.substr(vpos + 1);
else if(arg.find("--md=") == 0) mdAlgName = arg.substr(vpos + 1);
else {
std::cout << "Error: unknown argument: " << argv[i] << std::endl;
return EXIT_BAD_ARGS;
}
}
if(filePath.empty() || keyID.empty()) {
std::cout << "Error one of the required arguments is not specified" << std::endl;
return EXIT_BAD_ARGS;
}
vhsm_key_id vkid = vhsmGetKeyID(keyID);
vhsm_mac_method macMethod = {VHSM_MAC_HMAC, 0, vkid};
if(!setDigest(macMethod, mdAlgName)) {
std::cout << "Error: unsupported digest method: " << mdAlgName << std::endl;
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) {
freeDigest(macMethod, mdAlgName);
return EXIT_VHSM_ERR;
}
std::ifstream fileIn;
unsigned int md_size = 0;
unsigned char *md = NULL;
int exitCode = EXIT_VHSM_ERR;
int res = vhsm_mac_init(s, macMethod);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to init mac: " << vhsmErrorCode(res) << std::endl;
goto cleanup;
}
fileIn.open(filePath.c_str(), std::ifstream::in | std::ifstream::binary);
if(!fileIn.is_open()) {
std::cout << "Error: unable to open file: " << filePath << std::endl;
exitCode = EXIT_BAD_ARGS;
goto cleanup;
}
char buf[VHSM_MAX_DATA_LENGTH];
while(!fileIn.eof()) {
size_t ln = fileIn.readsome(buf, VHSM_MAX_DATA_LENGTH);
if(ln == 0) break;
res = vhsm_mac_update(s, (unsigned char*)buf, ln);
if(res != VHSM_RV_OK) {
std::cout << "Error: vhsm_mac_update: " << vhsmErrorCode(res) << std::endl;
fileIn.close();
goto cleanup;
}
}
fileIn.close();
res = vhsm_mac_end(s, NULL, &md_size);
if(res != VHSM_RV_BAD_BUFFER_SIZE) {
std::cout << "Error: failed to obtain mac size" << std::endl;
goto cleanup;
}
md = new unsigned char[md_size];
res = vhsm_mac_end(s, md, &md_size);
if(res != VHSM_RV_OK) {
std::cout << "Error: failed to obtain mac: " << vhsmErrorCode(res) << std::endl;
delete[] md;
goto cleanup;
}
if(binOutput) {
for(unsigned int i = 0; i < md_size; ++i) std::cout << md[i];
} else {
std::cout << "0x" << std::hex;
for(unsigned int i = 0; i < md_size; ++i) std::cout << (int)md[i];
std::cout << std::dec;
}
std::cout << std::endl;
delete[] md;
exitCode = EXIT_OK;
cleanup:
freeDigest(macMethod, mdAlgName);
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
if(argc < 3) {
showHelp(HELP_BASE);
return EXIT_BAD_ARGS;
}
switch(commandId(argv[1])) {
case CMD_HELP:
showHelp(HELP_BASE);
break;
case CMD_GENERATE:
return generateKey(argc - 2, argv + 2);
case CMD_IMPORT:
return importKey(argc - 2, argv + 2);
case CMD_DELETE:
return deleteKey(argc - 2, argv + 2);
case CMD_KEYINFO:
return getKeyInfo(argc - 2, argv + 2);
case CMD_HMAC:
return computeHMAC(argc - 2, argv + 2);
default:
std::cout << "Unknown command: " << argv[1] << std::endl;
showHelp(HELP_BASE);
}
return EXIT_OK;
}
| 34.794872
| 128
| 0.552837
|
OSLL
|
23cb33ca493b6d2d59fc46ba0968a4adb2718e58
| 1,922
|
cpp
|
C++
|
584 Bowling.cpp
|
zihadboss/UVA-Solutions
|
020fdcb09da79dc0a0411b04026ce3617c09cd27
|
[
"Apache-2.0"
] | 86
|
2016-01-20T11:36:50.000Z
|
2022-03-06T19:43:14.000Z
|
584 Bowling.cpp
|
Mehedishihab/UVA-Solutions
|
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
|
[
"Apache-2.0"
] | null | null | null |
584 Bowling.cpp
|
Mehedishihab/UVA-Solutions
|
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
|
[
"Apache-2.0"
] | 113
|
2015-12-04T06:40:57.000Z
|
2022-02-11T02:14:28.000Z
|
#include <cstdio>
int handle(char current, char previous, char twoPrevious, bool addOwnScore)
{
int baseScore(0);
int score = 0;
if (current == 'X')
{
baseScore = 10;
}
else if (current == '/')
{
baseScore = 10 - (previous - '0');
}
else
{
baseScore = current - '0';
}
if (addOwnScore)
score = baseScore;
if (previous == '/' || previous == 'X')
score += baseScore;
if (twoPrevious == 'X')
score += baseScore;
return score;
}
const int countedThrows = 20;
int main()
{
char first;
while (scanf(" %c", &first), first != 'G')
{
char current = first, previous = ' ', twoPrevious = ' ';
int score;
score = handle(current, previous, twoPrevious, true);
previous = current;
int bonusThrows = 0;
for (int i = (current == 'X') ? 2 : 1; i < countedThrows; ++i)
{
scanf(" %c", ¤t);
score += handle(current, previous, twoPrevious, true);
twoPrevious = previous;
previous = current;
if (current == 'X')
{
if (i == 18) // First throw of the last round
bonusThrows = 2;
++i;
}
if (current == '/' && i == 19)
bonusThrows = 1;
}
for (int i = 0; i < bonusThrows; ++i)
{
scanf(" %c", ¤t);
score += handle(current, previous, twoPrevious, false);
twoPrevious = previous;
previous = current; // The just thrown ball does not improve score
if (previous == 'X')
previous = ' ';
}
printf("%d\n", score);
}
}
| 22.091954
| 78
| 0.426639
|
zihadboss
|
23cd22431b7eedfa78296fb3cadd0a30e4363843
| 1,071
|
cpp
|
C++
|
dynamic_progrmmaing/coursera_primitive_calculator.cpp
|
BackAged/100_days_of_problem_solving
|
2e24efad6d46804c4b31f415dbd69d7b80703a4f
|
[
"Apache-2.0"
] | 3
|
2020-06-15T10:39:34.000Z
|
2021-01-17T14:03:37.000Z
|
dynamic_progrmmaing/coursera_primitive_calculator.cpp
|
BackAged/100_days_of_problem_solving
|
2e24efad6d46804c4b31f415dbd69d7b80703a4f
|
[
"Apache-2.0"
] | null | null | null |
dynamic_progrmmaing/coursera_primitive_calculator.cpp
|
BackAged/100_days_of_problem_solving
|
2e24efad6d46804c4b31f415dbd69d7b80703a4f
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int choice[1000000];
int visited[1000000];
int optimal_sequence(int n) {
visited[0] = 0;
visited[1] = 0;
for (int i = 2; i <= n; i++) {
int ans = INT32_MAX;
int t1 = 1 + visited[i - 1];
if (t1 < ans) {
ans = t1;
choice[i] = i - 1;
}
if (i % 2 == 0) {
int t2 = 1 + visited[i/2];
if (t2 < ans) {
ans = t2;
choice[i] = i / 2;
}
}
if (i % 3 == 0) {
int t3 = 1 + visited[i/3];
if (t3 < ans) {
ans = t3;
choice[i] = i / 3;
}
}
visited[i] = min(ans, visited[i]);
}
return visited[n];
}
void printOptimalSolution(int n) {
if (n == 1) {
cout << 1 << " ";
return;
}
printOptimalSolution(choice[n]);
cout << n << " ";
}
int main() {
int n;
cin >> n;
fill_n(visited, 1000005, INT32_MAX);
int sequence = optimal_sequence(n);
cout << sequence << endl;
printOptimalSolution(n);
}
| 18.789474
| 40
| 0.46592
|
BackAged
|
23d0fb391b788e8e2f6eee11162b4c14efde0691
| 4,155
|
cpp
|
C++
|
kernel/system_tree/system_tree_root.cpp
|
martin-hughes/project_azalea
|
28aa0183cde350073cf0167df3f51435ea409c8b
|
[
"MIT"
] | 13
|
2017-12-20T00:02:38.000Z
|
2022-01-07T11:18:36.000Z
|
kernel/system_tree/system_tree_root.cpp
|
martin-hughes/project_azalea
|
28aa0183cde350073cf0167df3f51435ea409c8b
|
[
"MIT"
] | 21
|
2016-09-21T16:50:39.000Z
|
2020-04-12T12:58:19.000Z
|
kernel/system_tree/system_tree_root.cpp
|
martin-hughes/project_azalea
|
28aa0183cde350073cf0167df3f51435ea409c8b
|
[
"MIT"
] | 6
|
2017-12-20T00:02:27.000Z
|
2019-03-21T16:28:24.000Z
|
/// @file
/// @brief Implement `system_tree_root`, which handles the very root of the System Tree.
#include "klib/klib.h"
#include "system_tree/system_tree_root.h"
uint32_t system_tree_root::number_of_instances = 0;
system_tree_root::system_tree_root()
{
KL_TRC_ENTRY;
ASSERT(system_tree_root::number_of_instances == 0);
system_tree_root::number_of_instances++;
root = std::make_shared<system_tree_simple_branch>();
KL_TRC_EXIT;
}
system_tree_root::~system_tree_root()
{
KL_TRC_ENTRY;
// In some ways it'd be better if this destructor simply panic'd - but that'd confuse the test scripts. We need to be
// able to destroy the system tree in order to demonstrate that no memory is leaked.
KL_TRC_TRACE(TRC_LVL::ERROR, "System tree is being destroyed! Shouldn't occur\n");
system_tree_root::number_of_instances--;
KL_TRC_EXIT;
}
ERR_CODE system_tree_root::get_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> &child)
{
ERR_CODE result;
KL_TRC_ENTRY;
KL_TRC_TRACE(TRC_LVL::FLOW, "Look for name: ", name, "\n");
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else if (name == "\\")
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Return root element\n");
result = ERR_CODE::NO_ERROR;
child = root;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Find in rest of tree\n");
std::string remainder = name.substr(1);
result = root->get_child(remainder, child);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::add_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> child)
{
ERR_CODE result;
KL_TRC_ENTRY;
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::INVALID_OP;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Add somewhere in rest of tree\n");
std::string remainder = name.substr(1);
result = root->add_child(remainder, child);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::create_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> &child)
{
ERR_CODE result;
KL_TRC_ENTRY;
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Find in rest of tree\n");
std::string remainder = name.substr(1);
result = root->create_child(remainder, child);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::rename_child(const std::string &old_name, const std::string &new_name)
{
ERR_CODE result;
KL_TRC_ENTRY;
if ((old_name[0] != '\\') || (new_name[0] != '\\'))
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Rename in rest of tree\n");
std::string old_remainder = old_name.substr(1);
std::string new_remainder = new_name.substr(1);
result = root->rename_child(old_remainder, new_remainder);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::delete_child(const std::string &name)
{
ERR_CODE result;
KL_TRC_ENTRY;
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else if (name == "\\")
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Delete root element??\n");
result = ERR_CODE::INVALID_OP;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Find in rest of tree\n");
std::string remainder = name.substr(1);
result = root->delete_child(remainder);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
std::pair<ERR_CODE, uint64_t> system_tree_root::num_children()
{
return root->num_children();
}
std::pair<ERR_CODE, std::vector<std::string>>
system_tree_root::enum_children(std::string start_from, uint64_t max_count)
{
return root->enum_children(start_from, max_count);
}
| 24.156977
| 119
| 0.681829
|
martin-hughes
|
23d20a928719cc1b369db802f3439e83766f11f7
| 608
|
cpp
|
C++
|
cpp_models/libsrc/RLLib/visualization/RLLibViz/Framebuffer.cpp
|
akangasr/sdirl
|
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
|
[
"MIT"
] | null | null | null |
cpp_models/libsrc/RLLib/visualization/RLLibViz/Framebuffer.cpp
|
akangasr/sdirl
|
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
|
[
"MIT"
] | null | null | null |
cpp_models/libsrc/RLLib/visualization/RLLibViz/Framebuffer.cpp
|
akangasr/sdirl
|
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
|
[
"MIT"
] | null | null | null |
/*
* Framebuffer.cpp
*
* Created on: Oct 12, 2013
* Author: sam
*/
#include "Framebuffer.h"
#include <cassert>
using namespace RLLibViz;
Framebuffer::Framebuffer()
{
}
Framebuffer::~Framebuffer()
{
}
void Framebuffer::draw(QPainter& painter)
{
if (points.empty() || points.size() < 1)
return;
QPainterPath path;
for (int i = 1; i < points.size(); i++)
{
path.moveTo(points.at(i-1));
path.lineTo(points.at(i));
}
painter.drawPath(path);
}
void Framebuffer::clear()
{
points.clear();
}
void Framebuffer::add(const Vec& p)
{
points.push_back(QPoint(p.x, p.y));
}
| 13.511111
| 42
| 0.626645
|
akangasr
|
23d438cc7f53933fdb5f6abb578da26c5bf0b5ec
| 10,552
|
cpp
|
C++
|
src/modules/dvb/dvb.cpp
|
ivanmurashko/kalinka
|
58a3f774c414dfc408aa06f560dde455c2271c6b
|
[
"MIT"
] | null | null | null |
src/modules/dvb/dvb.cpp
|
ivanmurashko/kalinka
|
58a3f774c414dfc408aa06f560dde455c2271c6b
|
[
"MIT"
] | null | null | null |
src/modules/dvb/dvb.cpp
|
ivanmurashko/kalinka
|
58a3f774c414dfc408aa06f560dde455c2271c6b
|
[
"MIT"
] | null | null | null |
/**
@file dvb.cpp
@brief This file is part of Kalinka mediaserver.
@author ipp <ivan.murashko@gmail.com>
Copyright (c) 2007-2012 Kalinka Team
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.
CHANGE HISTORY
@date
- 2008/07/26 created by ipp (Ivan Murashko)
- 2009/08/02 header was changed by header.py script
- 2010/01/06 header was changed by header.py script
- 2011/01/01 header was changed by header.py script
- 2012/02/03 header was changed by header.py script
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include "dvb.h"
#include "dvbdev.h"
#include "common.h"
#include "log.h"
#include "defines.h"
#include "infocommand.h"
#include "resourcecommand.h"
#include "traps.h"
#include "utils.h"
#include "exception.h"
#include "messages.h"
#include "snmp/factory.h"
#include "snmp/scalar.h"
#include "snmp/table.h"
using namespace klk;
using namespace klk::dvb;
/**
Module factory function
each module lib should define it
*/
IModulePtr klk_module_get(IFactory *factory)
{
return IModulePtr(new DVB(factory));
}
//
// DVB
//
// Constructor
// @param[in] factory the module factory
DVB::DVB(IFactory *factory) :
ModuleWithDB(factory, MODID),
m_processor(new Processor(factory))
{
BOOST_ASSERT(m_processor);
}
// Destructor
DVB::~DVB()
{
}
// Gets a human readable module name
const std::string DVB::getName() const throw()
{
return MODNAME;
}
// Does pre actions before start main loop
void DVB::preMainLoop()
{
// preparation staff
ModuleWithDB::preMainLoop();
m_processor->clean();
}
// Does post actions after main loop
void DVB::postMainLoop() throw()
{
m_processor->clean();
ModuleWithDB::postMainLoop();
}
// Register all processors
void DVB::registerProcessors()
{
ModuleWithDB::registerProcessors();
// processors
registerSync(
msg::id::DVBSTART,
boost::bind(&Processor::doStart, m_processor, _1, _2));
registerASync(
msg::id::DVBSTOP,
boost::bind(&Processor::doStop, m_processor, _1));
registerCLI(cli::ICommandPtr(new SetSourceCommand()));
registerCLI(cli::ICommandPtr(new InfoCommand()));
// register actions in a separate threads
registerTimer(boost::bind(&DVB::checkDVBDevs, this),
CHECKINTERVAL);
registerSNMP(boost::bind(&DVB::processSNMP, this, _1), MODID);
}
// Process changes at the DB
// @param[in] msg - the input message
void DVB::processDB(const IMessagePtr& msg)
{
BOOST_ASSERT(msg);
// update DVB devs info from DB
IDevList devs =
getFactory()->getResources()->getResourceByType(dev::DVB_ALL);
std::for_each(devs.begin(), devs.end(),
boost::bind(&IDev::update, _1));
}
// Checks DVB devs state
void DVB::checkDVBDevs()
{
IDevList devs =
getFactory()->getResources()->getResourceByType(dev::DVB_ALL);
std::for_each(devs.begin(), devs.end(),
boost::bind(&DVB::checkDVBDev, this, _1));
}
// Checks a DVB dev state
void DVB::checkDVBDev(const IDevPtr& dev)
{
BOOST_ASSERT(dev);
// check last update time
bool old = (static_cast<u_long>(time(NULL)) >
dev->getLastUpdateTime() + CHECKINTERVAL);
// first of all to clear lost lock flag
// to be able to use the dev
// dont update last update time
dev->setParam(dev::LOSTLOCK, 0, true);
if (dev->getState() == dev::IDLE)
{
// just clear lost lock flag
return;
}
// check update time
if (old)
{
getFactory()->getSNMP()->sendTrap(
TRAP_TIMEOUT,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Cannot retrive DVB device state within %d seconds. "
"Device UUID: '%s'", CHECKINTERVAL,
dev->getStringParam(dev::UUID).c_str());
// signal lost
m_processor->doSignalLost(dev);
return;
}
// check has lock
if (dev->getIntParam(dev::HASLOCK) == 0)
{
getFactory()->getSNMP()->sendTrap(
TRAP_NOSIGNAL,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"DVB dev does not get a lock "
"Device name: '%s'",
dev->getStringParam(dev::NAME).c_str());
// signal lost
m_processor->doSignalLost(dev);
return;
}
// check signal
if (dev->getIntParam(dev::SIGNAL) < SIGNAL_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADSIGNAL,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad signal strength: Failed %d < %d. "
"Device name: '%s'",
signal, SIGNAL_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
#if 0 //FIXME!!! sometime can really have signal
if (signal == 0)
{
// signal lost
m_processor->doSignalLost(dev);
}
#endif
}
// check snr
int snr = dev->getIntParam(dev::SNR);
if (snr < SNR_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADSNR,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad SNR: %d < %d. "
"Device name: '%s'",
snr, SNR_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
}
// check ber
int ber = dev->getIntParam(dev::BER);
if (ber > BER_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADBER,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad BER: %d > %d. "
"Device name: '%s'",
ber, BER_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
}
// check unc
int unc = dev->getIntParam(dev::UNC);
if (unc > UNC_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADUNC,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad UNC: %d > %d. "
"Device name: '%s'",
unc, UNC_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
}
}
// Processes SNMP request
const snmp::IDataPtr DVB::processSNMP(const snmp::IDataPtr& req)
{
BOOST_ASSERT(req);
snmp::ScalarPtr reqreal =
boost::dynamic_pointer_cast<snmp::Scalar, snmp::IData>(req);
BOOST_ASSERT(reqreal);
const std::string reqstr = reqreal->getValue().toString();
// support only snmp::GETSTATUSTABLE
if (reqstr != snmp::GETSTATUSTABLE)
{
throw Exception(__FILE__, __LINE__,
"Unknown SNMP request: " + reqstr);
}
// create the response
// table with data
snmp::TablePtr table(new snmp::Table());
IDevList devs =
getFactory()->getResources()->getResourceByType(dev::DVB_ALL);
u_int count = 0;
for (IDevList::iterator dev = devs.begin(); dev != devs.end();
dev++, count++)
{
// klkIndex Counter32
// klkCardName DisplayString,
// klkCardType DisplayString,
// klkAdapter Integer32,
// klkFrontend Integer32,
// klkHasLock TruthValue,
// klkSignal Integer32,
// klkSNR Integer32,
// klkBER Integer32,
// klkUNC Counter32,
// klkRate Counter32
snmp::TableRow row;
try
{
row.push_back(count);
row.push_back((*dev)->getStringParam(dev::NAME));
const std::string type = (*dev)->getStringParam(dev::TYPE);
if (type == dev::DVB_S)
{
row.push_back(DVB_S_NAME);
}
else if (type == dev::DVB_T)
{
row.push_back(DVB_T_NAME);
}
else if (type == dev::DVB_C)
{
row.push_back(DVB_C_NAME);
}
else
{
row.push_back(NOTAVAILABLE);
}
row.push_back((*dev)->getIntParam(dev::ADAPTER));
row.push_back((*dev)->getIntParam(dev::FRONTEND));
if ((*dev)->hasParam(dev::HASLOCK))
{
row.push_back((*dev)->getIntParam(dev::HASLOCK));
row.push_back((*dev)->getIntParam(dev::SIGNAL));
row.push_back((*dev)->getIntParam(dev::SNR));
row.push_back((*dev)->getIntParam(dev::BER));
row.push_back((*dev)->getIntParam(dev::UNC));
}
else
{
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
}
if ((*dev)->hasParam(dev::RATE))
row.push_back((*dev)->getIntParam(dev::RATE));
else
row.push_back(0);
}
catch(...)
{
row.clear();
row.push_back(count);
row.push_back(NOTAVAILABLE);
row.push_back(NOTAVAILABLE);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
}
table->addRow(row);
}
return table;
}
| 27.479167
| 74
| 0.574204
|
ivanmurashko
|
23deb62f8d3ee6616e5b5fe1e3f59b55af069ade
| 2,464
|
cpp
|
C++
|
src/Base/DoubleSpinBox.cpp
|
roto5296/choreonoid
|
ffe12df8db71e32aea18833afb80dffc42c373d0
|
[
"MIT"
] | 66
|
2020-03-11T14:06:01.000Z
|
2022-03-23T23:18:27.000Z
|
src/Base/DoubleSpinBox.cpp
|
roto5296/choreonoid
|
ffe12df8db71e32aea18833afb80dffc42c373d0
|
[
"MIT"
] | 12
|
2020-07-23T06:13:11.000Z
|
2022-01-13T14:25:01.000Z
|
src/Base/DoubleSpinBox.cpp
|
roto5296/choreonoid
|
ffe12df8db71e32aea18833afb80dffc42c373d0
|
[
"MIT"
] | 18
|
2020-07-17T15:57:54.000Z
|
2022-03-29T13:18:59.000Z
|
#include "DoubleSpinBox.h"
#include <QKeyEvent>
using namespace cnoid;
DoubleSpinBox::DoubleSpinBox(QWidget* parent)
: QDoubleSpinBox(parent)
{
setKeyboardTracking(false);
isSettingValueInternally = false;
isUndoRedoKeyInputEnabled_ = false;
valueChangedByLastUserInput = false;
}
void DoubleSpinBox::setUndoRedoKeyInputEnabled(bool on)
{
isUndoRedoKeyInputEnabled_ = on;
if(on){
// Activate signal handlers
sigValueChanged();
sigEditingFinished();
}
}
void DoubleSpinBox::setValue(double val)
{
isSettingValueInternally = true;
QDoubleSpinBox::setValue(val);
isSettingValueInternally = false;
}
SignalProxy<void(double)> DoubleSpinBox::sigValueChanged()
{
if(!sigValueChanged_){
stdx::emplace(sigValueChanged_);
connect(this, (void(QDoubleSpinBox::*)(double)) &QDoubleSpinBox::valueChanged,
[this](double value){ onValueChanged(value); });
}
return *sigValueChanged_;
}
SignalProxy<void()> DoubleSpinBox::sigEditingFinished()
{
if(!sigEditingFinished_){
stdx::emplace(sigEditingFinished_);
connect(this, &QDoubleSpinBox::editingFinished,
[this](){ onEditingFinished(); });
}
return *sigEditingFinished_;
}
SignalProxy<void()> DoubleSpinBox::sigEditingFinishedWithValueChange()
{
if(!sigEditingFinishedWithValueChange_){
stdx::emplace(sigEditingFinishedWithValueChange_);
sigEditingFinished();
}
return *sigEditingFinishedWithValueChange_;
}
void DoubleSpinBox::onValueChanged(double value)
{
if(!isSettingValueInternally){
valueChangedByLastUserInput = true;
}
(*sigValueChanged_)(value);
}
void DoubleSpinBox::onEditingFinished()
{
(*sigEditingFinished_)();
if(sigEditingFinishedWithValueChange_){
if(valueChangedByLastUserInput){
(*sigEditingFinishedWithValueChange_)();
}
}
valueChangedByLastUserInput = false;
}
void DoubleSpinBox::keyPressEvent(QKeyEvent* event)
{
bool isUndoOrRedoKey = false;
if(isUndoRedoKeyInputEnabled_){
if(event->key() == Qt::Key_Z && event->modifiers() & Qt::ControlModifier){
isUndoOrRedoKey = true;
}
}
if(isUndoOrRedoKey){
if(valueChangedByLastUserInput){
onEditingFinished();
}
QWidget::keyPressEvent(event);
} else {
QDoubleSpinBox::keyPressEvent(event);
}
}
| 22.814815
| 86
| 0.676948
|
roto5296
|
23e60ab5fbae97a04f5642bcb8bc617f26084126
| 51
|
cpp
|
C++
|
src/LoginInfo.cpp
|
NoSuchBoyException/QT-PureMVC
|
cc84e68ddc2666941af6970a4fab364ab74f5190
|
[
"Apache-2.0"
] | 40
|
2016-06-20T12:22:42.000Z
|
2022-03-10T03:20:00.000Z
|
src/LoginInfo.cpp
|
NoSuchBoyException/PureMVC_QT
|
cc84e68ddc2666941af6970a4fab364ab74f5190
|
[
"Apache-2.0"
] | null | null | null |
src/LoginInfo.cpp
|
NoSuchBoyException/PureMVC_QT
|
cc84e68ddc2666941af6970a4fab364ab74f5190
|
[
"Apache-2.0"
] | 24
|
2017-01-03T13:18:04.000Z
|
2022-03-20T01:24:41.000Z
|
#include "LoginInfo.h"
LoginInfo::LoginInfo()
{
}
| 8.5
| 22
| 0.686275
|
NoSuchBoyException
|
23ea38bae9e49e20a987deab48c375b42aa64b46
| 7,474
|
cpp
|
C++
|
src/bin/balanceHandler.cpp
|
D7ry/valhallaCombat
|
07929d29a48401c2878a1ed5993b7bba14743c6f
|
[
"MIT"
] | 1
|
2022-01-19T07:13:48.000Z
|
2022-01-19T07:13:48.000Z
|
src/bin/balanceHandler.cpp
|
D7ry/valhallaCombat
|
07929d29a48401c2878a1ed5993b7bba14743c6f
|
[
"MIT"
] | null | null | null |
src/bin/balanceHandler.cpp
|
D7ry/valhallaCombat
|
07929d29a48401c2878a1ed5993b7bba14743c6f
|
[
"MIT"
] | 1
|
2022-01-19T07:13:52.000Z
|
2022-01-19T07:13:52.000Z
|
#include "include/balanceHandler.h"
#include "include/reactionHandler.h"
#include "include/offsets.h"
#include "include/Utils.h"
inline const float balanceRegenTime = 6;//time it takes for balance to regen, in seconds.
void balanceHandler::update() {
//DEBUG("update");
/*if (garbageCollectionQueued) {
collectGarbage();
garbageCollectionQueued = false;
}*/
mtx_balanceBrokenActors.lock();
if (balanceBrokenActors.empty()) {//stop updating when there is 0 actor need to regen balance.
mtx_balanceBrokenActors.unlock();
//DEBUG("no balance broken actors, stop update");
ValhallaCombat::GetSingleton()->deactivateUpdate(ValhallaCombat::HANDLER::balanceHandler);
return;
}
//DEBUG("non-empty balance map");
//regenerate balance for all balance broken actors.
auto it = balanceBrokenActors.begin();
mtx_actorBalanceMap.lock();
while (it != balanceBrokenActors.end()) {
if (!actorBalanceMap.contains(*it)) { //edge case: actor's balance broken but no longer tracked on actor balance map.
//DEBUG("edge case");
it = balanceBrokenActors.erase(it);
continue;
}
//regen a single actor's balance.
auto* balanceData = &actorBalanceMap.find(*it)->second;
float regenVal = balanceData->first * *RE::Offset::g_deltaTime * 1 / balanceRegenTime;
//DEBUG(regenVal);
//DEBUG(a_balanceData.second);
//DEBUG(a_balanceData.first);
if (balanceData->second + regenVal >= balanceData->first) {//this regen exceeds actor's max balance.
//DEBUG("{}'s balance has recovered", (*it)->GetName());
balanceData->second = balanceData->first;//reset balance.
debuffHandler::GetSingleton()->quickStopStaminaDebuff(*it);
it = balanceBrokenActors.erase(it);
continue;
}
else {
//DEBUG("normal regen");
balanceData->second += regenVal;
}
it++;
}
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.unlock();
}
void balanceHandler::queueGarbageCollection() {
garbageCollectionQueued = true;
}
float balanceHandler::calculateMaxBalance(RE::Actor* a_actor) {
return a_actor->GetPermanentActorValue(RE::ActorValue::kHealth);
}
void balanceHandler::trackBalance(RE::Actor* a_actor) {
float maxBalance = calculateMaxBalance(a_actor);
mtx_actorBalanceMap.lock();
actorBalanceMap.emplace(a_actor, std::pair<float, float> {maxBalance, maxBalance});
mtx_actorBalanceMap.unlock();
}
void balanceHandler::untrackBalance(RE::Actor* a_actor) {
mtx_actorBalanceMap.lock();
actorBalanceMap.erase(a_actor);
mtx_actorBalanceMap.unlock();
}
void balanceHandler::collectGarbage() {
INFO("Cleaning up balance map...");
int ct = 0;
mtx_actorBalanceMap.lock();
auto it_balanceMap = actorBalanceMap.begin();
while (it_balanceMap != actorBalanceMap.end()) {
auto a_actor = it_balanceMap->first;
if (!a_actor || !a_actor->currentProcess || !a_actor->currentProcess->InHighProcess()) {
safeErase_BalanceBrokenActors(a_actor);
it_balanceMap = actorBalanceMap.erase(it_balanceMap);
ct++;
continue;
}
it_balanceMap++;
}
mtx_actorBalanceMap.unlock();
INFO("...done; cleaned up {} inactive actors.", ct);
}
void balanceHandler::reset() {
INFO("Reset all balance...");
mtx_actorBalanceMap.lock();
actorBalanceMap.clear();
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.lock();
balanceBrokenActors.clear();
mtx_balanceBrokenActors.unlock();
INFO("..done");
}
bool balanceHandler::isBalanceBroken(RE::Actor* a_actor) {
mtx_balanceBrokenActors.lock();
if (balanceBrokenActors.contains(a_actor)) {
mtx_balanceBrokenActors.unlock();
return true;
}
else {
mtx_balanceBrokenActors.unlock();
return false;
}
}
void balanceHandler::damageBalance(DMGSOURCE dmgSource, RE::Actor* a_aggressor, RE::Actor* a_victim, float damage) {
//DEBUG("damaging balance: aggressor: {}, victim: {}, damage: {}", aggressor->GetName(), victim->GetName(), damage);
mtx_actorBalanceMap.lock();
if (!actorBalanceMap.contains(a_victim)) {
mtx_actorBalanceMap.unlock();
trackBalance(a_victim);
damageBalance(dmgSource, a_aggressor, a_victim, damage);
return;
}
#define a_balanceData actorBalanceMap.find(a_victim)->second
//DEBUG("curr balance: {}", a_balanceData.second);
if (a_balanceData.second - damage <= 0) { //balance broken, ouch!
a_balanceData.second = 0;
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.lock();
if (!balanceBrokenActors.contains(a_victim)) {//if not balance broken already
//DEBUG("{}'s balance has broken", victim->GetName());
balanceBrokenActors.insert(a_victim);
if (dmgSource == DMGSOURCE::parry) {
reactionHandler::triggerStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
ValhallaCombat::GetSingleton()->activateUpdate(ValhallaCombat::HANDLER::balanceHandler);
}
else {//balance already broken, yet broken again, ouch!
//DEBUG("{}'s balance double broken", victim->GetName());
reactionHandler::triggerContinuousStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
mtx_balanceBrokenActors.unlock();
}
else {
//DEBUG("normal balance damage.");
a_balanceData.second -= damage;
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.lock();
if (balanceBrokenActors.contains(a_victim)) {
if (dmgSource == DMGSOURCE::powerAttack) {
reactionHandler::triggerStagger(a_aggressor, a_victim, reactionHandler::reactionType::kKnockBack);
}
else {
reactionHandler::triggerContinuousStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
}//if balance broken, trigger stagger.
else if (dmgSource == DMGSOURCE::powerAttack
&& !debuffHandler::GetSingleton()->isInDebuff(a_aggressor)) //or if is power attack and not in debuff
{
reactionHandler::triggerContinuousStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
mtx_balanceBrokenActors.unlock();
}
}
void balanceHandler::recoverBalance(RE::Actor* a_actor, float recovery) {
mtx_actorBalanceMap.lock();
if (!actorBalanceMap.contains(a_actor)) {
mtx_actorBalanceMap.unlock();
return;
}
float attempedRecovery = actorBalanceMap[a_actor].second + recovery;
if (attempedRecovery >= actorBalanceMap[a_actor].first) {//balance fully recovered.
actorBalanceMap[a_actor].second = actorBalanceMap[a_actor].first;
mtx_actorBalanceMap.unlock();
if (isBalanceBroken(a_actor)) {
safeErase_BalanceBrokenActors(a_actor);
debuffHandler::GetSingleton()->quickStopStaminaDebuff(a_actor);
}
}
else {
actorBalanceMap[a_actor].second = attempedRecovery;
mtx_actorBalanceMap.unlock();
}
}
void balanceHandler::processBalanceDamage(DMGSOURCE dmgSource, RE::TESObjectWEAP* weapon, RE::Actor* aggressor, RE::Actor* victim, float baseDamage) {
if (!settings::bBalanceToggle) {
return;
}
baseDamage *= 2;
if (isBalanceBroken(victim) && dmgSource < DMGSOURCE::bash) {
recoverBalance(victim, baseDamage * 1);
baseDamage = 0;
}
else {
if (debuffHandler::GetSingleton()->isInDebuff(victim)) {
baseDamage *= 1.5;
}
if (dmgSource == DMGSOURCE::parry) {
baseDamage *= 1.5;
}
if (victim->IsRangedAttacking() || ValhallaUtils::isCasting(victim)) {
baseDamage * 2.25;
}
}
damageBalance(dmgSource, aggressor, victim, baseDamage);
}
void balanceHandler::safeErase_ActorBalanceMap(RE::Actor* a_actor) {
mtx_actorBalanceMap.lock();
actorBalanceMap.erase(a_actor);
mtx_actorBalanceMap.unlock();
}
void balanceHandler::safeErase_BalanceBrokenActors(RE::Actor* a_actor) {
mtx_balanceBrokenActors.lock();
balanceBrokenActors.erase(a_actor);
mtx_balanceBrokenActors.unlock();
}
| 32.637555
| 150
| 0.737624
|
D7ry
|
23eae08214ee1ecabf369ec840d1dcb03d36ba1e
| 1,138
|
cpp
|
C++
|
pbr/Mesh.cpp
|
chuxu1793/pbr-1
|
c77d9bcc2c19637ab79382cbef3fc0e2a31b6560
|
[
"MIT"
] | 51
|
2016-04-03T20:37:57.000Z
|
2022-03-31T00:38:11.000Z
|
pbr/Mesh.cpp
|
chuxu1793/pbr-1
|
c77d9bcc2c19637ab79382cbef3fc0e2a31b6560
|
[
"MIT"
] | 2
|
2016-11-14T21:14:10.000Z
|
2016-11-16T15:01:47.000Z
|
pbr/Mesh.cpp
|
chuxu1793/pbr-1
|
c77d9bcc2c19637ab79382cbef3fc0e2a31b6560
|
[
"MIT"
] | 9
|
2016-06-02T03:46:23.000Z
|
2020-10-16T23:30:16.000Z
|
#include "Mesh.h"
#include <glbinding/gl/gl.h>
void Mesh::draw()
{
glBindVertexArray(m_VAO);
glDrawElements(GL_TRIANGLES, m_IndicesCount * 3, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
}
void Mesh::initialize(const std::vector<Vertex>& vertices, const std::vector<Triangle>& indices)
{
m_IndicesCount = indices.size();
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
{
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)(sizeof(glm::vec3)));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)(2 * sizeof(glm::vec3)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glGenBuffers(1, &m_EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(Triangle), indices.data(), GL_STATIC_DRAW);
}
glBindVertexArray(0);
}
| 31.611111
| 107
| 0.748682
|
chuxu1793
|
23eb4c38cc7c876ace8bc06e105f134921e3f8b7
| 1,130
|
cpp
|
C++
|
src/CursATE/Curses/Field/detail/resizePadded.cpp
|
qiagen/LogATE
|
aa43595c89bf3bcaa302d8406e5ad789efc0e035
|
[
"BSD-2-Clause"
] | null | null | null |
src/CursATE/Curses/Field/detail/resizePadded.cpp
|
qiagen/LogATE
|
aa43595c89bf3bcaa302d8406e5ad789efc0e035
|
[
"BSD-2-Clause"
] | null | null | null |
src/CursATE/Curses/Field/detail/resizePadded.cpp
|
qiagen/LogATE
|
aa43595c89bf3bcaa302d8406e5ad789efc0e035
|
[
"BSD-2-Clause"
] | 3
|
2021-01-12T18:52:49.000Z
|
2021-01-19T17:48:50.000Z
|
#include "CursATE/Curses/Field/detail/resizePadded.hpp"
#include <But/assert.hpp>
namespace CursATE::Curses::Field::detail
{
VisibleSize resizePaddedVisibleSize(std::string const& in, size_t maxSize, size_t selectedElement)
{
if( in.size() <= maxSize )
return {0, selectedElement, in.size()};
if( selectedElement > in.size() )
BUT_THROW(SelectionOutOfRange, "requested element " << selectedElement << " in a string of length " << in.size());
const auto half = maxSize / 2;
auto start = 0u;
if( selectedElement > half )
start = selectedElement - half;
if( in.size() - start < maxSize )
start = in.size() - maxSize;
const auto offset = selectedElement - start;
BUT_ASSERT( offset <= maxSize && "offset it outside of display window" );
return {start, offset, maxSize};
}
std::string resizePadded(std::string const& in, const size_t maxSize, const size_t selectedElement)
{
if( in.size() <= maxSize )
{
auto tmp = in;
tmp.resize(maxSize, ' ');
return tmp;
}
const auto vs = resizePaddedVisibleSize(in, maxSize, selectedElement);
return in.substr(vs.start_, vs.count_);
}
}
| 29.736842
| 118
| 0.685841
|
qiagen
|
6710cae5db7291a10684008a748246fc5eeec215
| 1,483
|
cpp
|
C++
|
Pearly/src/Pearly/Math/Math.cpp
|
JumpyLionnn/Pearly
|
2dce5f54144980cecd998a325422e56bff6c4c83
|
[
"Apache-2.0"
] | null | null | null |
Pearly/src/Pearly/Math/Math.cpp
|
JumpyLionnn/Pearly
|
2dce5f54144980cecd998a325422e56bff6c4c83
|
[
"Apache-2.0"
] | null | null | null |
Pearly/src/Pearly/Math/Math.cpp
|
JumpyLionnn/Pearly
|
2dce5f54144980cecd998a325422e56bff6c4c83
|
[
"Apache-2.0"
] | null | null | null |
#include "prpch.h"
#include "Math.h"
namespace Pearly {
bool Math::DecomposeTransform(const glm::mat4& transform, glm::vec3& position, float& rotation, glm::vec2& scale)
{
glm::mat4 localMatrix(transform);
// Normalize the matrix.
if (glm::epsilonEqual(localMatrix[3][3], static_cast<float>(0), glm::epsilon<float>()))
return false;
// First, isolate perspective. floathis is the messiest.
if (
glm::epsilonNotEqual(localMatrix[0][3], static_cast<float>(0), glm::epsilon<float>()) ||
glm::epsilonNotEqual(localMatrix[1][3], static_cast<float>(0), glm::epsilon<float>()) ||
glm::epsilonNotEqual(localMatrix[2][3], static_cast<float>(0), glm::epsilon<float>()))
{
// Clear the perspective partition
localMatrix[0][3] = localMatrix[1][3] = localMatrix[2][3] = static_cast<float>(0);
localMatrix[3][3] = static_cast<float>(1);
}
// Next take care of translation (easy).
position = glm::vec3(localMatrix[3]);
localMatrix[3] = glm::vec4(0, 0, 0, localMatrix[3].w);
glm::vec3 row[3];
// Now get scale and shear.
for (glm::length_t i = 0; i < 3; ++i)
for (glm::length_t j = 0; j < 3; ++j)
row[i][j] = localMatrix[i][j];
// Compute X scale factor and normalize first row.
scale.x = glm::length(row[0]);
row[0] = glm::detail::scale(row[0], static_cast<float>(1));
scale.y = glm::length(row[1]);
row[1] = glm::detail::scale(row[1], static_cast<float>(1));
rotation = atan2(row[0][1], row[0][0]);
return true;
}
}
| 32.23913
| 114
| 0.646662
|
JumpyLionnn
|
6711ec4603bd0025df95902abfec0d44315c7bae
| 2,149
|
cc
|
C++
|
device/device_rom.cc
|
CompaqDisc/zippy
|
e8c3b67ea59adbbdf9881e1bc34f0eab0eab6abe
|
[
"MIT"
] | null | null | null |
device/device_rom.cc
|
CompaqDisc/zippy
|
e8c3b67ea59adbbdf9881e1bc34f0eab0eab6abe
|
[
"MIT"
] | null | null | null |
device/device_rom.cc
|
CompaqDisc/zippy
|
e8c3b67ea59adbbdf9881e1bc34f0eab0eab6abe
|
[
"MIT"
] | null | null | null |
#include "device_rom.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>
DeviceROM::DeviceROM(uint16_t address_start, size_t region_length) {
address_start_ = address_start;
region_length_ = region_length;
buffer_contents_ = (uint8_t*) malloc(region_length_ * sizeof(uint8_t));
}
DeviceROM::DeviceROM(uint16_t address_start, size_t region_length,
std::string file_path
) {
address_start_ = address_start;
region_length_ = region_length;
buffer_contents_ = (uint8_t*) malloc(region_length_ * sizeof(uint8_t));
std::ifstream f(file_path);
// Bail if file wasn't found.
if (!f.good()) {
std::cout
<< "[FATL] [device_rom.cc] Specified file does not exist!"
<< std::endl;
exit(ENOENT);
}
f.seekg(0, f.end);
size_t file_length = f.tellg();
f.seekg(0, f.beg);
/*
Check that file length <= buffer space.
If not, only read until buffer is filled.
*/
if (file_length > region_length_) {
// Warn that we will truncate the read.
std::cout
<< "[WARN] [device_rom.cc] Specified romfile is too long for virtual ROM!"
<< "Truncating read!" << std::endl;
// Warn how large the file was.
printf(
"[WARN] [device_rom.cc] "
"Attempting to load %s (%li bytes), into virtual ROM with size of %li bytes!\n",
file_path.c_str(), file_length, region_length_
);
// Truncate read.
file_length = sizeof(buffer_contents_);
} else {
printf(
"[INFO] [device_rom.cc] "
"Loaded %s (%li bytes), into virtual ROM with size of %li bytes\n",
file_path.c_str(), file_length, region_length_
);
}
// Read the file into our buffer.
f.read((char*) buffer_contents_, file_length);
}
DeviceROM::~DeviceROM() {
free(buffer_contents_);
}
void DeviceROM::Clock() {
if (bus_->MemoryRequestActive()) {
if (bus_->ReadRequestActive()) {
if (bus_->Address() >= address_start_ &&
bus_->Address() < (address_start_ + region_length_))
{
printf("[INFO] [device_rom.cc] /RD request made for 0x%04x\n",
bus_->Address());
bus_->PushData(
buffer_contents_[bus_->Address() - address_start_]);
}
}
}
}
void DeviceROM::BindToBus(Bus* bus) {
bus_ = bus;
}
| 23.615385
| 83
| 0.676128
|
CompaqDisc
|
671579f43f756cf8cdfde950e4ef720c4f5b80c4
| 1,197
|
cpp
|
C++
|
cxx/test/test_binheap.cpp
|
EQt/graphidx
|
9716488cf29f6235072fc920fa1a473bf88e954f
|
[
"MIT"
] | 4
|
2020-04-03T15:18:30.000Z
|
2022-01-06T15:22:48.000Z
|
cxx/test/test_binheap.cpp
|
EQt/graphidx
|
9716488cf29f6235072fc920fa1a473bf88e954f
|
[
"MIT"
] | null | null | null |
cxx/test/test_binheap.cpp
|
EQt/graphidx
|
9716488cf29f6235072fc920fa1a473bf88e954f
|
[
"MIT"
] | null | null | null |
#include <doctest/doctest.h>
#include <graphidx/heap/binheap.hpp>
#include <graphidx/heap/quadheap.hpp>
TEST_CASE_TEMPLATE_DEFINE("heap basic", Heap, test_heap_basics)
{
constexpr size_t N = 6;
Heap h(N);
REQUIRE(h.empty());
REQUIRE_EQ(h.size(), 0);
for (size_t i = 0; i < N; i++) {
REQUIRE(!h.contains(i));
}
h.push(5, 0.2f);
REQUIRE(!h.empty());
REQUIRE(h.contains(5));
REQUIRE(!h.contains(3));
REQUIRE_EQ(h.size(), 1);
REQUIRE_EQ(h[5], 0.2f);
REQUIRE_EQ(h.top(), 5);
h.push(3, -1.0f);
REQUIRE(!h.empty());
REQUIRE_EQ(h.size(), 2);
REQUIRE(h.contains(5));
REQUIRE(h.contains(3));
REQUIRE_EQ(h[5], 0.2f);
REQUIRE_EQ(h[3], -1.0f);
REQUIRE_EQ(h.top(), 3);
h.pop();
REQUIRE(!h.empty());
REQUIRE(h.contains(5));
REQUIRE(!h.contains(3));
REQUIRE_EQ(h.size(), 1);
REQUIRE_EQ(h[5], 0.2f);
h.push(3, 1.0f);
h.push(1, 0.1f);
REQUIRE_EQ(h.size(), 3);
REQUIRE_EQ(h.top(), 1);
h.decrease(5, -2.0f);
REQUIRE(!h.empty());
REQUIRE_EQ(h.top(), 5);
}
TEST_CASE_TEMPLATE_INVOKE(
test_heap_basics, gidx::BinaryHeap<int, float>, gidx::QuadHeap<int, float>);
| 22.166667
| 80
| 0.578112
|
EQt
|
671afcda2345039279bc47492c4f1a66cbd14d83
| 328
|
cpp
|
C++
|
Zerojudge/d111.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 9
|
2017-10-08T16:22:03.000Z
|
2021-08-20T09:32:17.000Z
|
Zerojudge/d111.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | null | null | null |
Zerojudge/d111.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 2
|
2018-01-15T16:35:44.000Z
|
2019-03-21T18:30:04.000Z
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
long long int n;
while(cin >> n)
{
if(n==0)break;
long long int t=sqrt(n);
if(t*t==n)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
| 15.619048
| 33
| 0.45122
|
w181496
|
671b8a4c8d8a666826e1265b4102ce0f9a0e1f3b
| 2,268
|
hpp
|
C++
|
include/P2P.hpp
|
Sygmei/IsenCoin
|
91668cf056704da950a6c1f55e7a5b573b685ca7
|
[
"MIT"
] | 7
|
2018-05-31T14:16:48.000Z
|
2022-02-24T18:54:06.000Z
|
include/P2P.hpp
|
Sygmei/IsenCoin
|
91668cf056704da950a6c1f55e7a5b573b685ca7
|
[
"MIT"
] | null | null | null |
include/P2P.hpp
|
Sygmei/IsenCoin
|
91668cf056704da950a6c1f55e7a5b573b685ca7
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Logger.hpp>
#include <functional>
#include <optional>
#include <msgpack11/msgpack11.hpp>
#include <tacopie/network/tcp_socket.hpp>
#include "base58/base58.hpp"
namespace tacopie
{
int init();
void close();
}
namespace ic::p2p
{
namespace mp = msgpack11;
std::string msgpack_type_to_string(mp::MsgPack::Type type);
using additional_check_t = std::function<bool(const mp::MsgPack&)>;
struct Requirement
{
std::string name;
mp::MsgPack::Type type;
std::optional<additional_check_t> check;
bool has_check() const;
bool check_if_needed(const mp::MsgPack& msg);
Requirement(const std::string& name, mp::MsgPack::Type type);
Requirement(const std::string& name, mp::MsgPack::Type type, additional_check_t check);
};
using Requirements = std::vector<Requirement>;
mp::MsgPack string_to_msgpack(const std::string& msg);
mp::MsgPack bytearray_to_msgpack(const std::vector<char>& msg);
std::vector<char> string_to_bytearray(const std::string& msg);
bool is_msgpack_valid(const mp::MsgPack& msg);
bool is_msgpack_valid_type(const mp::MsgPack& msg, const std::string& type);
using success_callback_t = const std::function<void(const mp::MsgPack&)>;
using failure_callback_t = const std::function<void()>;
bool check_requirement(const std::string& name, const mp::MsgPack& msg, Requirement req);
void use_msg(
const mp::MsgPack& msg,
const std::string& type,
success_callback_t& on_success,
failure_callback_t& on_failure,
Requirements requirements = {}
);
mp::MsgPack build_msg(const std::string& type, mp::MsgPack::object fields = {});
void send_msg(tacopie::tcp_socket& socket, const mp::MsgPack& msg);
mp::MsgPack recv_msg(tacopie::tcp_socket& socket, size_t max_size);
template <size_t N>
void decode_b58(const std::string& message, std::array<unsigned char, N>& tarray);
template <size_t N>
void decode_b58(const std::string& message, std::array<unsigned char, N>& tarray)
{
std::vector<unsigned char> buffer;
base58::decode(message.c_str(), buffer);
std::copy(buffer.begin(), buffer.end(), tarray.begin());
}
}
| 36
| 95
| 0.679894
|
Sygmei
|
671c60ceccc5a70d03b40fce21ce4617c071e989
| 1,420
|
cpp
|
C++
|
compiler/angkor/src/ADT/tensor/LexicalLayout.cpp
|
periannath/ONE
|
61e0bdf2bcd0bc146faef42b85d469440e162886
|
[
"Apache-2.0"
] | 255
|
2020-05-22T07:45:29.000Z
|
2022-03-29T23:58:22.000Z
|
compiler/angkor/src/ADT/tensor/LexicalLayout.cpp
|
periannath/ONE
|
61e0bdf2bcd0bc146faef42b85d469440e162886
|
[
"Apache-2.0"
] | 5,102
|
2020-05-22T07:48:33.000Z
|
2022-03-31T23:43:39.000Z
|
compiler/angkor/src/ADT/tensor/LexicalLayout.cpp
|
periannath/ONE
|
61e0bdf2bcd0bc146faef42b85d469440e162886
|
[
"Apache-2.0"
] | 120
|
2020-05-22T07:51:08.000Z
|
2022-02-16T19:08:05.000Z
|
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. 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 "nncc/core/ADT/tensor/LexicalLayout.h"
#include <cassert>
using nncc::core::ADT::tensor::Shape;
using nncc::core::ADT::tensor::Index;
// NOTE This forward declaration is introduced to minimize code diff
static uint32_t lexical_offset(const Shape &shape, const Index &index)
{
assert(shape.rank() > 0);
assert(shape.rank() == index.rank());
const uint32_t rank = shape.rank();
uint32_t res = index.at(0);
for (uint32_t axis = 1; axis < rank; ++axis)
{
res *= shape.dim(axis);
res += index.at(axis);
}
return res;
}
namespace nncc
{
namespace core
{
namespace ADT
{
namespace tensor
{
LexicalLayout::LexicalLayout() : Layout(lexical_offset)
{
// DO NOTHING
}
} // namespace tensor
} // namespace ADT
} // namespace core
} // namespace nncc
| 23.278689
| 75
| 0.705634
|
periannath
|
671ca6f6fe06b1edc73fc3aaed7937d9f7a7399a
| 543
|
cpp
|
C++
|
TAO/tao/Storable_Factory.cpp
|
cflowe/ACE
|
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
|
[
"DOC"
] | 36
|
2015-01-10T07:27:33.000Z
|
2022-03-07T03:32:08.000Z
|
TAO/tao/Storable_Factory.cpp
|
cflowe/ACE
|
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
|
[
"DOC"
] | 2
|
2018-08-13T07:30:51.000Z
|
2019-02-25T03:04:31.000Z
|
TAO/tao/Storable_Factory.cpp
|
cflowe/ACE
|
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
|
[
"DOC"
] | 38
|
2015-01-08T14:12:06.000Z
|
2022-01-19T08:33:00.000Z
|
// -*- C++ -*-
//=============================================================================
/**
* @file Storable_Factory.cpp
*
* $Id: Storable_Factory.cpp 96760 2013-02-05 21:11:03Z stanleyk $
*
* @author Byron Harris <harrisb@ociweb.com>
*/
//=============================================================================
#include "tao/Storable_Factory.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO::Storable_Factory::Storable_Factory (void)
{
}
TAO::Storable_Factory::~Storable_Factory (void)
{
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 20.884615
| 79
| 0.510129
|
cflowe
|
671fb22bf156d02ccdb16b73138f40f99f753d9b
| 1,042
|
cpp
|
C++
|
course1/laba4/L_pairosochetatie_max_weight/main.cpp
|
flydzen/ITMO_algo
|
ea251dca0fddb0d4d212377c6785cdc3667ece89
|
[
"MIT"
] | null | null | null |
course1/laba4/L_pairosochetatie_max_weight/main.cpp
|
flydzen/ITMO_algo
|
ea251dca0fddb0d4d212377c6785cdc3667ece89
|
[
"MIT"
] | null | null | null |
course1/laba4/L_pairosochetatie_max_weight/main.cpp
|
flydzen/ITMO_algo
|
ea251dca0fddb0d4d212377c6785cdc3667ece89
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
vector<vector<pair<int, int>>> ss;
vector<long long> a;
vector<long long> b;
vector<long long> c;
void discrete_finger_simulation(int i, int from) {
for (pair<int, int> p : ss[i]) {
if (p.first == from)
continue;
discrete_finger_simulation(p.first, i);
a[i] = max(a[i], b[p.first] + p.second - c[p.first]);
b[i] += c[p.first];
}
a[i] += b[i];
c[i] = max(a[i], b[i]);
}
int main() {
ifstream fin("matching.in");
ofstream fout("matching.out");
int n;
fin >> n;
ss = vector<vector<pair<int, int>>>(n, vector<pair<int, int>>());
a = vector<long long>(n);
b = vector<long long>(n);
c = vector<long long>(n);
for (int i = 0; i < n - 1; i++) {
int f, t, w;
fin >> f >> t >> w;
ss[f - 1].push_back(make_pair(t - 1, w));
ss[t - 1].push_back(make_pair(f - 1, w));
}
discrete_finger_simulation(0, -1);
fout << c[0];
return 0;
}
| 24.809524
| 69
| 0.52975
|
flydzen
|
6720bd6af8045487c67d1df89445c5c7e2a4de00
| 819
|
cpp
|
C++
|
elf/strlen/jni/test_strlen.cpp
|
martinkro/doc-2017
|
6c8121b72786b7a2563a00dad78e481186643cd7
|
[
"MIT"
] | null | null | null |
elf/strlen/jni/test_strlen.cpp
|
martinkro/doc-2017
|
6c8121b72786b7a2563a00dad78e481186643cd7
|
[
"MIT"
] | null | null | null |
elf/strlen/jni/test_strlen.cpp
|
martinkro/doc-2017
|
6c8121b72786b7a2563a00dad78e481186643cd7
|
[
"MIT"
] | null | null | null |
#include <jni.h>
#include <string.h>
#include <stdio.h>
typedef int (*strlen_fun)(const char *);
strlen_fun global_strlen1 = (strlen_fun)strlen;
strlen_fun global_strlen2 = (strlen_fun)strlen;
#define SHOW(x) printf("%s is %d", #x, x)
jint Java_com_example_allhookinone_HookUtils_elfhook(JNIEnv* env,jobject thiz){
const char *str = "helloworld";
strlen_fun local_strlen1 = (strlen_fun)strlen;
strlen_fun local_strlen2 = (strlen_fun)strlen;
int len0 = global_strlen1(str);
int len1 = global_strlen2(str);
int len2 = local_strlen1(str);
int len3 = local_strlen2(str);
int len4 = strlen(str);
int len5 = strlen(str);
SHOW(len0);
SHOW(len1);
SHOW(len2);
SHOW(len3);
SHOW(len4);
SHOW(len5);
return 0;
}
| 25.59375
| 79
| 0.637363
|
martinkro
|
67218a76893c678f78f19e84b5a049d78bc74795
| 6,944
|
cc
|
C++
|
physicalrobots/player/examples/libplayerc++/goto.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
physicalrobots/player/examples/libplayerc++/goto.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
physicalrobots/player/examples/libplayerc++/goto.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2005, Brad Kratochvil, Toby Collett, Brian Gerkey, Andrew Howard, ...
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 Player Project 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.
*/
/*
* goto.cc - a simple (and bad) goto program
*
* but, it demonstrates one multi-threaded structure
*
* @todo: this has been ported to libplayerc++, but not tested AT ALL
*/
#include <libplayerc++/playerc++.h>
#include <iostream>
#include <stdlib.h> // for atof()
#if !defined (WIN32)
#include <unistd.h>
#endif
#include <math.h>
#include <string>
#include <boost/signal.hpp>
#include <boost/bind.hpp>
#define USAGE \
"USAGE: goto [-x <x>] [-y <y>] [-h <host>] [-p <port>] [-m]\n" \
" -x <x>: set the X coordinate of the target to <x>\n"\
" -y <y>: set the Y coordinate of the target to <y>\n"\
" -h <host>: connect to Player on this host\n" \
" -p <port>: connect to Player on this TCP port\n" \
" -m : turn on motors (be CAREFUL!)"
PlayerCc::PlayerClient* robot;
PlayerCc::Position2dProxy* pp;
PlayerCc::SonarProxy* sp;
bool gMotorEnable(false);
bool gGotoDone(false);
std::string gHostname(PlayerCc::PLAYER_HOSTNAME);
uint32_t gPort(PlayerCc::PLAYER_PORTNUM);
uint32_t gIndex(0);
uint32_t gDebug(0);
uint32_t gFrequency(10); // Hz
player_pose2d_t gTarget = {0, 0, 0};
void
print_usage(int argc, char** argv)
{
std::cout << USAGE << std::endl;
}
int
parse_args(int argc, char** argv)
{
const char* optflags = "h:p:i:d:u:x:y:m";
int ch;
while(-1 != (ch = getopt(argc, argv, optflags)))
{
switch(ch)
{
/* case values must match long_options */
case 'h':
gHostname = optarg;
break;
case 'p':
gPort = atoi(optarg);
break;
case 'i':
gIndex = atoi(optarg);
break;
case 'd':
gDebug = atoi(optarg);
break;
case 'u':
gFrequency = atoi(optarg);
break;
case 'x':
gTarget.px = atof(optarg);
break;
case 'y':
gTarget.py = atof(optarg);
break;
case 'm':
gMotorEnable = true;
break;
case '?':
case ':':
default:
print_usage(argc, argv);
return (-1);
}
}
return (0);
}
/*
* very bad goto. target is arg (as pos_t*)
*
* sets global 'gGotoDone' when it's done
*/
void
position_goto(player_pose2d_t target)
{
using namespace PlayerCc;
double dist, angle;
dist = sqrt((target.px - pp->GetXPos())*
(target.px - pp->GetXPos()) +
(target.py - pp->GetYPos())*
(target.py - pp->GetYPos()));
angle = atan2(target.py - pp->GetYPos(),
target.px - pp->GetXPos());
double newturnrate = 0;
double newspeed = 0;
if (fabs(rtod(angle)) > 10.0)
{
newturnrate = limit((angle/M_PI) * 40.0, -40.0, 40.0);
newturnrate = dtor(newturnrate);
}
else
newturnrate = 0.0;
if (dist > 0.05)
{
newspeed = limit(dist * 0.200, -0.2, 0.2);
}
else
newspeed = 0.0;
if (fabs(newspeed) < 0.01)
gGotoDone = true;
pp->SetSpeed(newspeed, newturnrate);
}
/*
* sonar avoid.
* policy:
* if(object really close in front)
* backup and turn away;
* else if(object close in front)
* stop and turn away
*/
void
sonar_avoid(void)
{
double min_front_dist = 0.500;
double really_min_front_dist = 0.300;
bool avoid = false;
double newturnrate = 10.0;
double newspeed = 10.0;
if ((sp->GetScan(2) < really_min_front_dist) ||
(sp->GetScan(3) < really_min_front_dist) ||
(sp->GetScan(4) < really_min_front_dist) ||
(sp->GetScan(5) < really_min_front_dist))
{
avoid = true;
std::cerr << "really avoiding" << std::endl;
newspeed = -0.100;
}
else if((sp->GetScan(2) < min_front_dist) ||
(sp->GetScan(3) < min_front_dist) ||
(sp->GetScan(4) < min_front_dist) ||
(sp->GetScan(5) < min_front_dist))
{
avoid = true;
std::cerr << "avoiding" << std::endl;
newspeed = 0;
}
if(avoid)
{
if ((sp->GetScan(0) + sp->GetScan(1)) < (sp->GetScan(6) + sp->GetScan(7)))
newturnrate = PlayerCc::dtor(30);
else
newturnrate = PlayerCc::dtor(-30);
}
if(newspeed < 10.0 && newturnrate < 10.0)
pp->SetSpeed(newspeed, newturnrate);
}
template<typename T>
void
Print(T t)
{
std::cout << *t << std::endl;
}
int
main(int argc, char **argv)
{
try
{
using namespace PlayerCc;
parse_args(argc,argv);
// Connect to Player server
robot = new PlayerClient(gHostname, gPort);
// Request sensor data
pp = new Position2dProxy(robot, gIndex);
sp = new SonarProxy(robot, gIndex);
if(gMotorEnable)
pp->SetMotorEnable(true);
// output the data
pp->ConnectReadSignal(boost::bind(&Print<Position2dProxy*>, pp));
sp->ConnectReadSignal(boost::bind(&Print<SonarProxy*>, sp));
// callback to avoid obstacles whenever we have new sonar data
sp->ConnectReadSignal(&sonar_avoid);
// start the read thread
robot->StartThread();
std::cout << "goto starting, target: " << gTarget.px
<< ", " << gTarget.py << std::endl;
for (;;)
{
position_goto(gTarget);
if (gGotoDone)
robot->StopThread();
timespec sleep = {0, 100000000}; // 100 ms
nanosleep(&sleep, NULL);
}
}
catch (PlayerCc::PlayerError & e)
{
std::cerr << e << std::endl;
return -1;
}
return(0);
}
| 25.068592
| 83
| 0.618952
|
parasol-ppl
|
67230243b18fae2b57fa419b50760d3f68cd775c
| 1,943
|
cpp
|
C++
|
base/crts/crtw32/misc/dbgdel.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
base/crts/crtw32/misc/dbgdel.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
base/crts/crtw32/misc/dbgdel.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/***
*dbgnew.cpp - defines C++ scalar delete routine, debug version
*
* Copyright (c) 1995-2001, Microsoft Corporation. All rights reserved.
*
*Purpose:
* Defines C++ scalar delete() routine.
*
*Revision History:
* 12-28-95 JWM Split from dbgnew.cpp for granularity.
* 05-22-98 JWM Support for KFrei's RTC work, and operator delete[].
* 07-28-98 JWM RTC update.
* 05-26-99 KBF Updated RTC_Allocate_hook params
* 10-21-99 PML Get rid of delete[], use heap\delete2.cpp for both
* debug and release builds (vs7#53440).
* 04-29-02 GB Added try-finally arounds lock-unlock.
*
*******************************************************************************/
#ifdef _DEBUG
#include <cruntime.h>
#include <malloc.h>
#include <mtdll.h>
#include <dbgint.h>
#include <rtcsup.h>
/***
*void operator delete() - delete a block in the debug heap
*
*Purpose:
* Deletes any type of block.
*
*Entry:
* void *pUserData - pointer to a (user portion) of memory block in the
* debug heap
*
*Return:
* <void>
*
*******************************************************************************/
void operator delete(
void *pUserData
)
{
_CrtMemBlockHeader * pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg( pUserData, pHead->nBlockUse );
__FINALLY
_munlock(_HEAP_LOCK); /* release other threads */
__END_TRY_FINALLY
return;
}
#endif /* _DEBUG */
| 26.616438
| 81
| 0.519815
|
npocmaka
|
6725b0780abb7d9c0419b517fcf07d347c0c3a45
| 1,771
|
hpp
|
C++
|
asteria/src/reference.hpp
|
MaskRay/asteria
|
56a9251f5bb80b92e5aff25eac145f8cd2495096
|
[
"BSD-3-Clause"
] | null | null | null |
asteria/src/reference.hpp
|
MaskRay/asteria
|
56a9251f5bb80b92e5aff25eac145f8cd2495096
|
[
"BSD-3-Clause"
] | null | null | null |
asteria/src/reference.hpp
|
MaskRay/asteria
|
56a9251f5bb80b92e5aff25eac145f8cd2495096
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is part of Asteria.
// Copyleft 2018, LH_Mouse. All wrongs reserved.
#ifndef ASTERIA_REFERENCE_HPP_
#define ASTERIA_REFERENCE_HPP_
#include "fwd.hpp"
#include "reference_root.hpp"
#include "reference_modifier.hpp"
namespace Asteria {
class Reference
{
private:
Reference_root m_root;
Vector<Reference_modifier> m_mods;
public:
Reference() noexcept
: m_root(), m_mods()
{
}
// This constructor does not accept lvalues.
template<typename XrootT, typename std::enable_if<(Reference_root::Variant::index_of<XrootT>::value || true)>::type * = nullptr>
Reference(XrootT &&xroot)
: m_root(std::forward<XrootT>(xroot)), m_mods()
{
}
// This assignment operator does not accept lvalues.
template<typename XrootT, typename std::enable_if<(Reference_root::Variant::index_of<XrootT>::value || true)>::type * = nullptr>
Reference & operator=(XrootT &&xroot)
{
this->m_root = std::forward<XrootT>(xroot);
this->m_mods.clear();
return *this;
}
~Reference();
Reference(const Reference &) noexcept;
Reference & operator=(const Reference &) noexcept;
Reference(Reference &&) noexcept;
Reference & operator=(Reference &&) noexcept;
public:
bool is_constant() const noexcept
{
return this->m_root.index() == Reference_root::index_constant;
}
Value read() const;
Value & write(Value value) const;
Value unset() const;
Reference & zoom_in(Reference_modifier mod);
Reference & zoom_out();
Reference & convert_to_temporary();
Reference & convert_to_variable(Global_context &global);
void enumerate_variables(const Abstract_variable_callback &callback) const;
};
}
#endif
| 26.432836
| 132
| 0.671937
|
MaskRay
|
672705ff65970239683ce82be68db76924118ba7
| 1,160
|
cpp
|
C++
|
search_algorithms/coding_problems/search_sorted_rotated.cpp
|
sky-lynx/Algorithms
|
95592a73dcd1dc04be7df3ce3157e63230fac27b
|
[
"MIT"
] | null | null | null |
search_algorithms/coding_problems/search_sorted_rotated.cpp
|
sky-lynx/Algorithms
|
95592a73dcd1dc04be7df3ce3157e63230fac27b
|
[
"MIT"
] | null | null | null |
search_algorithms/coding_problems/search_sorted_rotated.cpp
|
sky-lynx/Algorithms
|
95592a73dcd1dc04be7df3ce3157e63230fac27b
|
[
"MIT"
] | null | null | null |
// searches an element in an array which is sorted and then rotated
#include <iostream>
using namespace std;
int binary_search(int* arr, int l, int r, int key)
{
int m;
while(l != r)
{
m = (l + r) / 2;
if(arr[m] == key)
return m;
else if(arr[m] > key)
r = m - 1;
else
l = m + 1;
}
return -1;
}
int pivot_search(int* arr, int l, int r)
{
if(l < r)
return -1;
if(l == r)
return l;
int m = (l+r)/2;
if(m < r && arr[m] > arr[m+1])
return m;
if(m > l && arr[m] < arr[m-1])
return m-1;
if(arr[l] >= arr[m])
return pivot_search(arr, l, m-1);
return pivot_search(arr, m+1, r);
}
int pivoted_binary(int* arr, int l, int r, int key)
{
int pivot = pivot_search(arr, l, r);
if(pivot == -1)
return binary_search(arr, l, r, key);
if(arr[pivot] == key)
return pivot;
if(arr[0] <= key)
return binary_search(arr, l, pivot-1, key);
return binary_search(arr, pivot+1, r, key);
}
int main(void)
{
int array[] = {4,5,6,7,8,1,2,3};
int left = 0;
int right = (sizeof(array) / sizeof(*array)) - 1;
cout<<pivoted_binary(array, left, right, 7)<<'\n';
return 0;
}
| 17.575758
| 67
| 0.551724
|
sky-lynx
|
672b1c0d09b5b2ffa2f2bddaf4536ef544fc227b
| 2,516
|
cpp
|
C++
|
kernel/main.cpp
|
ethan4984/rock
|
751b9af1009b622bedf384c1f80970b333c436c3
|
[
"BSD-2-Clause"
] | 207
|
2020-05-27T21:57:28.000Z
|
2022-02-26T15:17:27.000Z
|
kernel/main.cpp
|
ethan4984/crepOS
|
751b9af1009b622bedf384c1f80970b333c436c3
|
[
"BSD-2-Clause"
] | 3
|
2020-07-26T18:14:05.000Z
|
2020-12-09T05:32:07.000Z
|
kernel/main.cpp
|
ethan4984/rock
|
751b9af1009b622bedf384c1f80970b333c436c3
|
[
"BSD-2-Clause"
] | 17
|
2020-07-05T19:08:48.000Z
|
2021-10-13T12:30:13.000Z
|
#include <mm/vmm.hpp>
#include <mm/pmm.hpp>
#include <mm/slab.hpp>
#include <int/idt.hpp>
#include <int/gdt.hpp>
#include <int/apic.hpp>
#include <fs/dev.hpp>
#include <fs/vfs.hpp>
#include <fs/fd.hpp>
#include <drivers/hpet.hpp>
#include <drivers/tty.hpp>
#include <drivers/pci.hpp>
#include <sched/smp.hpp>
#include <sched/scheduler.hpp>
#include <debug.hpp>
#include <stivale.hpp>
#include <font.hpp>
static stivale *stivale_virt = NULL;
extern "C" void _init();
extern "C" void __cxa_pure_virtual() { for(;;); }
extern "C" int main(size_t stivale_phys) {
cpuid_state cpu_id = cpuid(7, 0);
if(cpu_id.rcx & (1 << 16)) {
vmm::high_vma = 0xff00000000000000;
}
stivale_virt = reinterpret_cast<stivale*>(stivale_phys + vmm::high_vma);
pmm::init(stivale_virt);
kmm::cache(NULL, 0, 32);
kmm::cache(NULL, 0, 64);
kmm::cache(NULL, 0, 128);
kmm::cache(NULL, 0, 256);
kmm::cache(NULL, 0, 512);
kmm::cache(NULL, 0, 1024);
kmm::cache(NULL, 0, 2048);
kmm::cache(NULL, 0, 4096);
kmm::cache(NULL, 0, 8192);
kmm::cache(NULL, 0, 16384);
kmm::cache(NULL, 0, 32768);
kmm::cache(NULL, 0, 65536);
kmm::cache(NULL, 0, 131072);
kmm::cache(NULL, 0, 262144);
vmm::init();
_init();
x86::gdt_init();
x86::idt_init();
new x86::tss;
acpi::rsdp_ptr = (acpi::rsdp*)(stivale_virt->rsdp + vmm::high_vma);
if(acpi::rsdp_ptr->xsdt_addr) {
acpi::xsdt_ptr = (acpi::xsdt*)(acpi::rsdp_ptr->xsdt_addr + vmm::high_vma);
print("[ACPI] xsdt found at {x}\n", (size_t)(acpi::xsdt_ptr));
} else {
acpi::rsdt_ptr = (acpi::rsdt*)(acpi::rsdp_ptr->rsdt_addr + vmm::high_vma);
print("[ACPI] rsdt found at {x}\n", (size_t)(acpi::rsdt_ptr));
}
lib::vector<vmm::region> region_list;
cpu_init_features();
init_hpet();
apic::init();
smp::boot_aps();
dev::init();
tty::screen screen(stivale_virt);
new tty::tty(screen, (uint8_t*)font_bitmap, 16, 8);
asm ("sti");
pci::init();
apic::timer_calibrate(100);
vfs::mount("sd0-0", "/");
const char *argv[] = { "/usr/bin/bash", NULL };
const char *envp[] = {
"HOME=/",
"PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
"TERM=linux",
NULL
};
sched::arguments args(argv, envp);
sched::task *new_task = new sched::task(-1);
new_task->exec("/usr/bin/bash", 0x23, args, vfs::root_cluster->root_node);
for(;;)
asm ("pause");
}
| 22.666667
| 82
| 0.589825
|
ethan4984
|
6731e47e88a5f57bc5899ec39faf39129f015d54
| 154
|
cpp
|
C++
|
fastbuild-v1.02/Code/Tools/FBuild/FBuildTest/Data/TestObject/SourceMapping/File.cpp
|
jj4jj/TurboBuildUE4
|
497f0944c8d04d70e3656a34c145d21f431366a5
|
[
"MIT"
] | 11
|
2020-08-28T02:11:22.000Z
|
2021-09-11T11:29:53.000Z
|
fastbuild-v1.02/Code/Tools/FBuild/FBuildTest/Data/TestObject/SourceMapping/File.cpp
|
jj4jj/TurboBuildUE4
|
497f0944c8d04d70e3656a34c145d21f431366a5
|
[
"MIT"
] | 1
|
2020-11-23T13:35:00.000Z
|
2020-11-23T13:35:00.000Z
|
fastbuild-v1.02/Code/Tools/FBuild/FBuildTest/Data/TestObject/SourceMapping/File.cpp
|
jj4jj/TurboBuildUE4
|
497f0944c8d04d70e3656a34c145d21f431366a5
|
[
"MIT"
] | 5
|
2020-10-22T11:16:11.000Z
|
2021-04-01T10:20:09.000Z
|
const char * Function()
{
// .obj file will contain filename, surrounded by these tokens
return "FILE_MACRO_START(" __FILE__ ")FILE_MACRO_END";
}
| 25.666667
| 66
| 0.714286
|
jj4jj
|
6734e3cce0853a205bac21e8fbc28cf2dd7466a9
| 4,588
|
hpp
|
C++
|
src/core/NEON/kernels/arm_gemm/gemm_implementation.hpp
|
elenita1221/ComputeLibrary
|
3d2d44ef55ab6b08afda8be48301ce3c55c7bc67
|
[
"MIT"
] | 2
|
2020-07-25T20:27:14.000Z
|
2021-08-22T17:20:59.000Z
|
src/core/NEON/kernels/arm_gemm/gemm_implementation.hpp
|
elenita1221/ComputeLibrary
|
3d2d44ef55ab6b08afda8be48301ce3c55c7bc67
|
[
"MIT"
] | null | null | null |
src/core/NEON/kernels/arm_gemm/gemm_implementation.hpp
|
elenita1221/ComputeLibrary
|
3d2d44ef55ab6b08afda8be48301ce3c55c7bc67
|
[
"MIT"
] | 1
|
2021-08-22T17:09:09.000Z
|
2021-08-22T17:09:09.000Z
|
/*
* Copyright (c) 2018 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "gemv_batched.hpp"
namespace arm_gemm {
template<typename Top, typename Tret>
class GemmImplementation {
public:
/* Is this implementation compatible with the args as provided? */
virtual bool is_supported(const GemmArgs<Tret> &args) { return true; }
/* Is this implementation "recommended" for these args (heuristic)? */
virtual bool is_recommended(const GemmArgs<Tret> &args) { return true; }
/* Instantiate this method please. */
virtual UniqueGemmCommon<Top, Tret> instantiate(const GemmArgs<Tret> &args) = 0;
/* Indicate the "GemmMethod" for use as a selector */
const GemmMethod method;
virtual ~GemmImplementation() { }
GemmImplementation(GemmMethod method) : method(method) { }
};
/* "gemv_batched" implementation is type-agnostic, so template it here. */
template<typename Top, typename Tret>
class GemmImpl_gemv_batched : public GemmImplementation<Top, Tret> {
public:
bool is_supported(const GemmArgs<Tret> &args) override {
return (args._Msize==1 && args._nbatches > 1);
}
UniqueGemmCommon<Top, Tret> instantiate(const GemmArgs<Tret> &args) override {
return UniqueGemmCommon<Top, Tret> (new GemvBatched<Top, Tret>(args));
}
GemmImpl_gemv_batched() : GemmImplementation<Top, Tret>(GemmMethod::GEMV_BATCHED) { }
};
/* "Master" function implemented for each valid combination of types.
* Returns a list of GEMM implementation descriptors for processing by the
* other functions. */
template<typename Top, typename Tret>
std::vector<GemmImplementation<Top, Tret> *> &gemm_implementation_list();
template<typename Top, typename Tret>
GemmImplementation<Top, Tret> *find_implementation(GemmArgs<Tret> &args, GemmConfig *cfg) {
auto gemms = gemm_implementation_list<Top, Tret>();
for(auto &&i : gemms) {
/* Skip if this implementation doesn't support these args. */
if (!i->is_supported(args)) {
continue;
}
/* Skip if a specific method is requested and this is a different one. */
if (cfg && cfg->method != GemmMethod::DEFAULT && i->method != cfg->method) {
continue;
}
/* If no specific method is requested, check that this method recommends itself. */
if ((!cfg || cfg->method == GemmMethod::DEFAULT) && !i->is_recommended(args)) {
continue;
}
return i;
}
return nullptr;
}
template<typename Top, typename Tret>
UniqueGemmCommon<Top, Tret> gemm(GemmArgs<Tret> &args, GemmConfig *cfg) {
auto impl = find_implementation<Top, Tret>(args, cfg);
if (impl) {
return impl->instantiate(args);
}
return UniqueGemmCommon<Top, Tret>(nullptr);
}
template<typename Top, typename Tret>
GemmMethod get_gemm_method(GemmArgs<Tret> &args) {
auto impl = find_implementation<Top, Tret>(args, nullptr);
if (impl) {
return impl->method;
}
/* This shouldn't happen - there should always be at least one valid implementation. */
return GemmMethod::DEFAULT;
}
template<typename Top, typename Tret>
bool method_is_compatible(GemmMethod method, GemmArgs<Tret> &args) {
/* Determine if the method is valid by attempting to obtain an implementation specifying this method. */
GemmConfig cfg(method);
auto impl = find_implementation<Top, Tret>(args, &cfg);
if (impl) {
return true;
}
return false;
}
} // namespace arm_gemm
| 34.757576
| 108
| 0.700523
|
elenita1221
|
6736e6775cf4db401229a62885c84877683c0d0b
| 2,498
|
cpp
|
C++
|
Jan-3/src/ofApp.cpp
|
Lywa/Genuary
|
865ef0515eb986a175c565faa1fa56529a70f599
|
[
"MIT"
] | 1
|
2022-01-06T09:34:03.000Z
|
2022-01-06T09:34:03.000Z
|
Jan-3/src/ofApp.cpp
|
Lywa/Genuary
|
865ef0515eb986a175c565faa1fa56529a70f599
|
[
"MIT"
] | null | null | null |
Jan-3/src/ofApp.cpp
|
Lywa/Genuary
|
865ef0515eb986a175c565faa1fa56529a70f599
|
[
"MIT"
] | 1
|
2022-01-06T09:34:04.000Z
|
2022-01-06T09:34:04.000Z
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
smileys.load("images/face_tiny.png");
smileysIcon.load("images/smileys_q.png");
smileysIcon.setImageType(OF_IMAGE_GRAYSCALE);
}
//--------------------------------------------------------------
void ofApp::update(){
ofBackground(255);
}
//--------------------------------------------------------------
void ofApp::draw(){
//smileys.draw(0, 0);
// Code based on OF example: imageLoaderExample
ofPixels & pixels = smileysIcon.getPixels();
ofSetColor(0, 0, 0);
int w = smileysIcon.getWidth();
int h = smileysIcon.getHeight();
float diameter = 10;
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
int index = y * w + x;
unsigned char cur = pixels[index];
float size = 1 - ((float) cur / 255);
int xPos = 30 + x * diameter;
int yPos = 30 + y * diameter;
int radius = 0.5 + size * diameter /2 ;
ofDrawCircle(xPos, yPos, radius);
//ofDrawRectangle(xPos, yPos, radius, radius);
}
}
//ofSetColor(255);
//smileysIcon.draw(100, 100, 20, 20);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 23.790476
| 64
| 0.367894
|
Lywa
|
6737d72ca34672087a62f5cb6b3721a688c9b01d
| 798
|
cc
|
C++
|
P1945.cc
|
daily-boj/kiwiyou
|
ceca96ddfee95708871af67d1682048e0bed0257
|
[
"Unlicense"
] | 6
|
2020-04-08T09:04:57.000Z
|
2021-11-16T07:30:24.000Z
|
P1945.cc
|
daily-boj/kiwiyou
|
ceca96ddfee95708871af67d1682048e0bed0257
|
[
"Unlicense"
] | null | null | null |
P1945.cc
|
daily-boj/kiwiyou
|
ceca96ddfee95708871af67d1682048e0bed0257
|
[
"Unlicense"
] | 2
|
2020-04-16T05:32:06.000Z
|
2020-05-28T13:40:56.000Z
|
#include <bits/stdc++.h>
using namespace std;
struct Frac {
long long u, d;
bool operator<(const Frac& x) const {
return u * x.d < d * x.u;
}
};
int main() {
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
vector<pair<Frac, bool>> segs;
segs.reserve(n * 2);
for (int i = 0; i < n; ++i) {
int top, left, bottom, right;
cin >> left >> bottom >> right >> top;
segs.emplace_back(Frac { .u = bottom, .d = right }, false);
segs.emplace_back(Frac { .u = top, .d = left }, true);
}
sort(segs.begin(), segs.end());
int max_depth = 0;
int depth = 0;
for (auto& [_, is_close] : segs) {
if (is_close) --depth;
else ++depth;
max_depth = max(max_depth, depth);
}
cout << max_depth;
}
| 26.6
| 67
| 0.518797
|
daily-boj
|
673d4e691c78287353086652ae0a2ba79d09840e
| 2,247
|
cpp
|
C++
|
src/animation_widget.cpp
|
CourrierGui/plotcpp
|
00b5a94e4c9804cbc441a0bcede67f70cef08a0c
|
[
"MIT"
] | null | null | null |
src/animation_widget.cpp
|
CourrierGui/plotcpp
|
00b5a94e4c9804cbc441a0bcede67f70cef08a0c
|
[
"MIT"
] | null | null | null |
src/animation_widget.cpp
|
CourrierGui/plotcpp
|
00b5a94e4c9804cbc441a0bcede67f70cef08a0c
|
[
"MIT"
] | null | null | null |
#include <animation_widget.hpp>
#include <plotwidget.hpp>
#include <iostream>
#include <QElapsedTimer>
#include <QTimer>
namespace pcpp {
AnimationWidget::AnimationWidget(
int rows, int cols,
QWidget* parent)
: _plot{rows, cols, parent}, _actions{},
_continue{true}, _qtime{new QElapsedTimer}
{
}
void AnimationWidget::init(const std::function<void(PlotWrapper&)>& setup) {
setup(_plot);
}
void AnimationWidget::add(int msec, const Action& action) {
auto* timer = new QTimer{_plot.context().get()};
timer->setInterval(msec);
_actions.push_back({timer, action});
}
void AnimationWidget::start() {
if (!_actions.empty()) {
auto action_it = _actions.begin();
while (action_it != _actions.end()) {
auto action = action_it->second;
auto* timer = action_it->first;
if ((action_it+1) != _actions.end()) {
auto* next_timer = (action_it+1)->first;
QObject::connect(
timer, &QTimer::timeout,
[this, action, timer, next_timer]()
{
if (_continue) {
int64_t time = _qtime->elapsed();
_continue = action(time, _plot);
} else {
timer->stop();
_qtime->start();
_continue = true;
next_timer->start();
}
}
);
} else {
QObject::connect(
timer, &QTimer::timeout,
[this, action, timer]()
{
if (_continue) {
int64_t time = _qtime->elapsed();
_continue = action(time, _plot);
} else {
timer->stop();
_continue = true;
}
}
);
}
++action_it;
}
auto* first_timer = new QTimer{_plot.context().get()};
first_timer->setInterval(5);
QObject::connect(
first_timer, &QTimer::timeout,
[first_timer, this]()
{
first_timer->stop();
_actions.front().first->start();
_qtime->start();
}
);
first_timer->start();
}
_plot.show();
}
} /* end of namespace pcpp */
| 25.827586
| 78
| 0.503783
|
CourrierGui
|
673f96702ef633f29305647846c1175b933abcae
| 7,963
|
cpp
|
C++
|
cpp/opendnp3/src/opendnp3/master/Master.cpp
|
tarm/dnp3_orig
|
87c639b3462c980fba255e85793f6ec663abe981
|
[
"Apache-2.0"
] | null | null | null |
cpp/opendnp3/src/opendnp3/master/Master.cpp
|
tarm/dnp3_orig
|
87c639b3462c980fba255e85793f6ec663abe981
|
[
"Apache-2.0"
] | null | null | null |
cpp/opendnp3/src/opendnp3/master/Master.cpp
|
tarm/dnp3_orig
|
87c639b3462c980fba255e85793f6ec663abe981
|
[
"Apache-2.0"
] | 3
|
2016-07-13T18:54:13.000Z
|
2021-04-12T13:30:39.000Z
|
/**
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#include "Master.h"
#include "opendnp3/master/MasterStates.h"
#include "opendnp3/master/MeasurementHandler.h"
#include "opendnp3/master/ConstantCommandProcessor.h"
#include "opendnp3/master/AsyncTaskInterfaces.h"
#include "opendnp3/master/AsyncTaskGroup.h"
#include "opendnp3/master/AsyncTaskBase.h"
#include "opendnp3/master/AsyncTaskPeriodic.h"
#include "opendnp3/master/AsyncTaskNonPeriodic.h"
#include "opendnp3/master/AsyncTaskContinuous.h"
#include "opendnp3/app/APDUParser.h"
#include "opendnp3/app/APDURequest.h"
#include "opendnp3/LogLevels.h"
#include <openpal/IExecutor.h>
#include <openpal/LogMacros.h>
using namespace openpal;
namespace opendnp3
{
Master::Master(LogRoot& root, MasterConfig aCfg, IAppLayer* apAppLayer, ISOEHandler* apSOEHandler, AsyncTaskGroup* apTaskGroup, openpal::IExecutor* apExecutor, IUTCTimeSource* apTimeSrc) :
IAppUser(root),
pExecutor(apExecutor),
mpAppLayer(apAppLayer),
mpSOEHandler(apSOEHandler),
mpTaskGroup(apTaskGroup),
mpTimeSrc(apTimeSrc),
mpState(AMS_Closed::Inst()),
mpTask(nullptr),
mpScheduledTask(nullptr),
mSchedule(apTaskGroup, this, aCfg),
mClassPoll(logger, apSOEHandler),
mClearRestart(logger),
mConfigureUnsol(logger),
mTimeSync(logger, apTimeSrc),
mCommandTask(logger),
mCommandQueue(apExecutor, mSchedule.mpCommandTask)
{
}
void Master::ProcessIIN(const IINField& iin)
{
mLastIIN = iin;
bool check_state = false;
//The clear IIN task only happens in response to detecting an IIN bit.
if(mLastIIN.IsSet(IINBit::NEED_TIME))
{
SIMPLE_LOG_BLOCK(logger, flags::INFO, "Need time detected");
mSchedule.mpTimeTask->SilentEnable();
check_state = true;
}
if (mLastIIN.IsSet(IINBit::DEVICE_TROUBLE))
{
SIMPLE_LOG_BLOCK(logger, flags::WARN, "IIN Device trouble detected");
}
if (mLastIIN.IsSet(IINBit::EVENT_BUFFER_OVERFLOW))
{
SIMPLE_LOG_BLOCK(logger, flags::WARN, "Event buffer overflow detected");
}
// If this is detected, we need to reset the startup tasks
if(mLastIIN.IsSet(IINBit::DEVICE_RESTART))
{
SIMPLE_LOG_BLOCK(logger, flags::WARN, "Device restart detected");
mSchedule.ResetStartupTasks();
mSchedule.mpClearRestartTask->SilentEnable();
check_state = true;
}
if(check_state) mpTaskGroup->CheckState();
}
void Master::ProcessCommand(ITask* apTask)
{
if(mpState == AMS_Closed::Inst()) //we're closed
{
ConstantCommandProcessor ccp(pExecutor, CommandResponse(CommandResult::NO_COMMS));
while(mCommandQueue.Dispatch(&ccp));
apTask->Disable();
}
else
{
if(mCommandQueue.Dispatch(this))
{
mpState->StartTask(this, apTask, &mCommandTask);
}
else apTask->Disable();
}
}
void Master::SelectAndOperate(const ControlRelayOutputBlock& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureSBO(command, index, pCallback);
}
void Master::SelectAndOperate(const AnalogOutputInt32& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureSBO(command, index, pCallback);
}
void Master::SelectAndOperate(const AnalogOutputInt16& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureSBO(command, index, pCallback);
}
void Master::SelectAndOperate(const AnalogOutputFloat32& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureSBO(command, index, pCallback);
}
void Master::SelectAndOperate(const AnalogOutputDouble64& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureSBO(command, index, pCallback);
}
void Master::DirectOperate(const ControlRelayOutputBlock& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureDO(command, index, pCallback);
}
void Master::DirectOperate(const AnalogOutputInt32& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureDO(command, index, pCallback);
}
void Master::DirectOperate(const AnalogOutputInt16& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureDO(command, index, pCallback);
}
void Master::DirectOperate(const AnalogOutputFloat32& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureDO(command, index, pCallback);
}
void Master::DirectOperate(const AnalogOutputDouble64& command, uint16_t index, ICommandCallback* pCallback)
{
this->mCommandTask.ConfigureDO(command, index, pCallback);
}
void Master::StartTask(MasterTaskBase* apMasterTask, bool aInit)
{
if(aInit) apMasterTask->Init();
APDURequest request(this->requestBuffer.GetWriteBuffer());
request.SetControl(AppControlField(true, true, false, false).ToByte());
apMasterTask->ConfigureRequest(request);
mpAppLayer->SendRequest(request);
}
/* Tasks */
void Master::SyncTime(ITask* apTask)
{
if(mLastIIN.IsSet(IINBit::NEED_TIME))
{
mpState->StartTask(this, apTask, &mTimeSync);
}
else apTask->Disable();
}
void Master::WriteIIN(ITask* apTask)
{
if(mLastIIN.IsSet(IINBit::DEVICE_RESTART))
{
mpState->StartTask(this, apTask, &mClearRestart);
}
else apTask->Disable();
}
void Master::IntegrityPoll(ITask* apTask)
{
mClassPoll.Set(CLASS_1 | CLASS_2 | CLASS_3 | CLASS_0);
mpState->StartTask(this, apTask, &mClassPoll);
}
void Master::EventPoll(ITask* apTask, int aClassMask)
{
mClassPoll.Set(aClassMask);
mpState->StartTask(this, apTask, &mClassPoll);
}
void Master::ChangeUnsol(ITask* apTask, bool aEnable, int aClassMask)
{
mConfigureUnsol.Set(aEnable, aClassMask);
mpState->StartTask(this, apTask, &mConfigureUnsol);
}
MasterScan Master::GetIntegrityScan()
{
return MasterScan(pExecutor, mSchedule.mpIntegrityPoll);
}
MasterScan Master::AddClassScan(int aClassMask, openpal::TimeDuration aScanRate, openpal::TimeDuration aRetryRate)
{
auto pTask = mSchedule.AddClassScan(aClassMask, aScanRate, aRetryRate);
return MasterScan(pExecutor, pTask);
}
/* Implement IAppUser */
void Master::OnLowerLayerUp()
{
mpState->OnLowerLayerUp(this);
mSchedule.EnableOnlineTasks();
}
void Master::OnLowerLayerDown()
{
mpState->OnLowerLayerDown(this);
mSchedule.DisableOnlineTasks();
}
void Master::OnSolSendSuccess()
{
mpState->OnSendSuccess(this);
}
void Master::OnSolFailure()
{
mpState->OnFailure(this);
}
void Master::OnUnsolSendSuccess()
{
SIMPLE_LOG_BLOCK(logger, flags::ERR, "Master can't send unsol");
}
void Master::OnUnsolFailure()
{
SIMPLE_LOG_BLOCK(logger, flags::ERR, "Master can't send unsol");
}
void Master::OnPartialResponse(const APDUResponseRecord& aRecord)
{
mpState->OnPartialResponse(this, aRecord);
}
void Master::OnFinalResponse(const APDUResponseRecord& aRecord)
{
mpState->OnFinalResponse(this, aRecord);
}
void Master::OnUnsolResponse(const APDUResponseRecord& aRecord)
{
mpState->OnUnsolResponse(this, aRecord);
}
/* Private functions */
void Master::ProcessDataResponse(const APDUResponseRecord& record)
{
MeasurementHandler handler(logger, this->mpSOEHandler);
APDUParser::ParseTwoPass(record.objects, &handler, &logger);
}
} //end ns
| 27.364261
| 188
| 0.771317
|
tarm
|
67441b108ccb6440a5e7333e0263e018224a5db1
| 6,086
|
cpp
|
C++
|
Sankore-3.1/src/domain/UBGraphicsEllipseItem.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
Sankore-3.1/src/domain/UBGraphicsEllipseItem.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
Sankore-3.1/src/domain/UBGraphicsEllipseItem.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBGraphicsEllipseItem.h"
UB3HEditableGraphicsEllipseItem::UB3HEditableGraphicsEllipseItem(QGraphicsItem* parent):
UB3HEditablesGraphicsBasicShapeItem(parent)
{
// Ellipse has Stroke and Fill capabilities :
initializeStrokeProperty();
initializeFillingProperty();
mRadiusX = 0;
mRadiusY = 0;
}
UB3HEditableGraphicsEllipseItem::~UB3HEditableGraphicsEllipseItem()
{
}
UBItem *UB3HEditableGraphicsEllipseItem::deepCopy() const
{
UB3HEditableGraphicsEllipseItem* copy = new UB3HEditableGraphicsEllipseItem();
copyItemParameters(copy);
return copy;
}
void UB3HEditableGraphicsEllipseItem::copyItemParameters(UBItem *copy) const
{
UB3HEditablesGraphicsBasicShapeItem::copyItemParameters(copy);
UB3HEditableGraphicsEllipseItem *cp = dynamic_cast<UB3HEditableGraphicsEllipseItem*>(copy);
if(cp){
cp->mRadiusX = mRadiusX;
cp->mRadiusY = mRadiusY;
}
}
QPointF UB3HEditableGraphicsEllipseItem::center() const
{
QPointF centre;
centre.setX(pos().x() + mRadiusX);
centre.setY(pos().y() + mRadiusY);
return centre;
}
void UB3HEditableGraphicsEllipseItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
setStyle(painter);
int rx = (mRadiusX < 0 ? -mRadiusX : mRadiusX);
int ry = (mRadiusY < 0 ? -mRadiusY : mRadiusY);
int x = (mRadiusX < 0 ? mRadiusX : 0);
int y = (mRadiusY < 0 ? mRadiusY : 0);
//N/C - NNE - 20140312 : Litle work around for avoid crash under MacOs 10.9
QPainterPath path;
path.addEllipse(QRectF(x*2, y*2, rx*2, ry*2));
painter->drawPath(path);
if(isInEditMode()){
QPen p;
p.setColor(QColor(128, 128, 200));
p.setStyle(Qt::DotLine);
p.setWidth(pen().width());
painter->setPen(p);
painter->setBrush(QBrush());
painter->drawRect(0, 0, mRadiusX*2, mRadiusY*2);
}
}
QRectF UB3HEditableGraphicsEllipseItem::boundingRect() const
{
int x = (mRadiusX < 0 ? mRadiusX : 0);
int y = (mRadiusY < 0 ? mRadiusY : 0);
int rx = (mRadiusX < 0 ? -mRadiusX : mRadiusX);
int ry = (mRadiusY < 0 ? -mRadiusY : mRadiusY);
rx *= 2;
ry *= 2;
x *= 2;
y *= 2;
QRectF rect(x, y, rx, ry);
rect = adjustBoundingRect(rect);
return rect;
}
void UB3HEditableGraphicsEllipseItem::onActivateEditionMode()
{
verticalHandle()->setPos(mRadiusX, mRadiusY*2);
horizontalHandle()->setPos(mRadiusX*2, mRadiusY);
diagonalHandle()->setPos(mRadiusX*2, mRadiusY*2);
}
void UB3HEditableGraphicsEllipseItem::updateHandle(UBAbstractHandle *handle)
{
prepareGeometryChange();
qreal maxSize = handle->radius() * 4;
if(handle->getId() == 1){
//it's the vertical handle
if(handle->pos().y() >= maxSize){
mRadiusY = handle->pos().y() / 2;
}
}else if(handle->getId() == 0){
//it's the horizontal handle
if(handle->pos().x() >= maxSize){
mRadiusX = handle->pos().x() / 2;
}
}else{
//it's the diagonal handle
if(handle->pos().x() >= maxSize && handle->pos().y() >= maxSize){
float ratio = mRadiusY / mRadiusX;
if(mRadiusX > mRadiusY){
mRadiusX = handle->pos().x() / 2;
mRadiusY = ratio * mRadiusX;
}else{
mRadiusY = handle->pos().y() / 2;
mRadiusX = 1/ratio * mRadiusY;
}
}
}
verticalHandle()->setPos(mRadiusX, mRadiusY*2);
horizontalHandle()->setPos(mRadiusX*2, mRadiusY);
diagonalHandle()->setPos(mRadiusX*2, mRadiusY*2);
if(hasGradient()){
QLinearGradient g(QPointF(), QPointF(mRadiusX*2, 0));
g.setColorAt(0, brush().gradient()->stops().at(0).second);
g.setColorAt(1, brush().gradient()->stops().at(1).second);
setBrush(g);
}
}
QPainterPath UB3HEditableGraphicsEllipseItem::shape() const
{
QPainterPath path;
if(isInEditMode()){
path.addRect(boundingRect());
}else{
path.addEllipse(boundingRect());
}
return path;
}
void UB3HEditableGraphicsEllipseItem::setRadiusX(qreal radius)
{
prepareGeometryChange();
mRadiusX = radius;
}
void UB3HEditableGraphicsEllipseItem::setRadiusY(qreal radius)
{
prepareGeometryChange();
mRadiusY = radius;
}
void UB3HEditableGraphicsEllipseItem::setRect(QRectF rect){
prepareGeometryChange();
setPos(rect.topLeft());
mRadiusX = rect.width()/2;
mRadiusY = rect.height()/2;
if(hasGradient()){
QLinearGradient g(QPointF(), QPointF(mRadiusX*2, 0));
g.setColorAt(0, brush().gradient()->stops().at(0).second);
g.setColorAt(1, brush().gradient()->stops().at(1).second);
setBrush(g);
}
}
QRectF UB3HEditableGraphicsEllipseItem::rect() const
{
QRectF r;
r.setTopLeft(pos());
r.setWidth(mRadiusX*2);
r.setHeight(mRadiusY*2);
return r;
}
qreal UB3HEditableGraphicsEllipseItem::radiusX() const
{
return mRadiusX;
}
qreal UB3HEditableGraphicsEllipseItem::radiusY() const
{
return mRadiusY;
}
| 25.464435
| 119
| 0.651002
|
eaglezzb
|
674773b616afc8e7d9f9b0fb29de3211aa0096cc
| 19,627
|
cpp
|
C++
|
TransferLogManager.cpp
|
agomez0207/wdt
|
d85fd11b14ae835e88cfffe970284fcf42866b18
|
[
"BSD-3-Clause"
] | 1
|
2020-07-19T21:21:11.000Z
|
2020-07-19T21:21:11.000Z
|
TransferLogManager.cpp
|
agomez0207/wdt
|
d85fd11b14ae835e88cfffe970284fcf42866b18
|
[
"BSD-3-Clause"
] | null | null | null |
TransferLogManager.cpp
|
agomez0207/wdt
|
d85fd11b14ae835e88cfffe970284fcf42866b18
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "TransferLogManager.h"
#include <wdt/WdtConfig.h>
#include "ErrorCodes.h"
#include "WdtOptions.h"
#include "SerializationUtil.h"
#include "Reporting.h"
#include <folly/Range.h>
#include <folly/ScopeGuard.h>
#include <folly/Bits.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <map>
#include <ctime>
#include <iomanip>
namespace facebook {
namespace wdt {
void TransferLogManager::setRootDir(const std::string &rootDir) {
rootDir_ = rootDir;
}
std::string TransferLogManager::getFullPath(const std::string &relPath) {
WDT_CHECK(!rootDir_.empty()) << "Root directory not set";
std::string fullPath = rootDir_;
if (fullPath.back() != '/') {
fullPath.push_back('/');
}
fullPath.append(relPath);
return fullPath;
}
int TransferLogManager::open() {
WDT_CHECK(!rootDir_.empty()) << "Root directory not set";
auto openFlags = O_CREAT | O_WRONLY | O_APPEND;
int fd = ::open(getFullPath(LOG_NAME).c_str(), openFlags, 0644);
if (fd < 0) {
PLOG(ERROR) << "Could not open wdt log";
}
return fd;
}
bool TransferLogManager::openAndStartWriter() {
WDT_CHECK(fd_ == -1) << "Trying to open wdt log multiple times";
fd_ = open();
if (fd_ < 0) {
return false;
} else {
writerThread_ =
std::move(std::thread(&TransferLogManager::writeEntriesToDisk, this));
LOG(INFO) << "Log writer thread started " << fd_;
return true;
}
}
void TransferLogManager::enableLogging() {
loggingEnabled_ = true;
}
int64_t TransferLogManager::timestampInMicroseconds() const {
auto timestamp = Clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(
timestamp.time_since_epoch()).count();
}
std::string TransferLogManager::getFormattedTimestamp(int64_t timestampMicros) {
// This assumes Clock's epoch is Posix's epoch (1970/1/1)
// to_time_t is unfortunately only on the system_clock and not
// on high_resolution_clock (on MacOS at least it isn't)
time_t seconds = timestampMicros / kMicroToSec;
int microseconds = timestampMicros - seconds * kMicroToSec;
// need 25 bytes to encode date in format mm/dd/yy HH:MM:SS.MMMMMM
char buf[25];
struct tm tm;
localtime_r(&seconds, &tm);
snprintf(buf, sizeof(buf), "%02d/%02d/%02d %02d:%02d:%02d.%06d",
tm.tm_mon + 1, tm.tm_mday, (tm.tm_year % 100), tm.tm_hour, tm.tm_min,
tm.tm_sec, microseconds);
return buf;
}
void TransferLogManager::addLogHeader(const std::string &recoveryId) {
if (!loggingEnabled_ || fd_ < 0) {
return;
}
VLOG(1) << "Adding log header " << LOG_VERSION << " " << recoveryId;
char buf[kMaxEntryLength];
// increment by 2 bytes to later store the total length
char *ptr = buf + sizeof(int16_t);
int64_t size = 0;
ptr[size++] = HEADER;
encodeInt(ptr, size, timestampInMicroseconds());
encodeInt(ptr, size, LOG_VERSION);
encodeString(ptr, size, recoveryId);
folly::storeUnaligned<int16_t>(buf, size);
std::lock_guard<std::mutex> lock(mutex_);
entries_.emplace_back(buf, size + sizeof(int16_t));
}
void TransferLogManager::addFileCreationEntry(const std::string &fileName,
int64_t seqId, int64_t fileSize) {
if (!loggingEnabled_ || fd_ < 0) {
return;
}
VLOG(1) << "Adding file entry to log " << fileName << " " << seqId << " "
<< fileSize;
char buf[kMaxEntryLength];
// increment by 2 bytes to later store the total length
char *ptr = buf + sizeof(int16_t);
int64_t size = 0;
ptr[size++] = FILE_CREATION;
encodeInt(ptr, size, timestampInMicroseconds());
encodeString(ptr, size, fileName);
encodeInt(ptr, size, seqId);
encodeInt(ptr, size, fileSize);
folly::storeUnaligned<int16_t>(buf, size);
std::lock_guard<std::mutex> lock(mutex_);
entries_.emplace_back(buf, size + sizeof(int16_t));
}
void TransferLogManager::addBlockWriteEntry(int64_t seqId, int64_t offset,
int64_t blockSize) {
if (!loggingEnabled_ || fd_ < 0) {
return;
}
VLOG(1) << "Adding block entry to log " << seqId << " " << offset << " "
<< blockSize;
char buf[kMaxEntryLength];
// increment by 2 bytes to later store the total length
char *ptr = buf + sizeof(int16_t);
int64_t size = 0;
ptr[size++] = BLOCK_WRITE;
encodeInt(ptr, size, timestampInMicroseconds());
encodeInt(ptr, size, seqId);
encodeInt(ptr, size, offset);
encodeInt(ptr, size, blockSize);
folly::storeUnaligned<int16_t>(buf, size);
std::lock_guard<std::mutex> lock(mutex_);
entries_.emplace_back(buf, size + sizeof(int16_t));
}
void TransferLogManager::addInvalidationEntry(int64_t seqId) {
if (!loggingEnabled_ || fd_ < 0) {
return;
}
VLOG(1) << "Adding invalidation entry " << seqId;
char buf[kMaxEntryLength];
int64_t size = 0;
encodeInvalidationEntry(buf, size, seqId);
std::lock_guard<std::mutex> lock(mutex_);
entries_.emplace_back(buf, size + sizeof(int16_t));
}
bool TransferLogManager::close() {
if (fd_ < 0) {
return false;
}
if (::close(fd_) != 0) {
PLOG(ERROR) << "Failed to close wdt log " << fd_;
fd_ = -1;
return false;
}
LOG(INFO) << "wdt log closed";
fd_ = -1;
return true;
}
bool TransferLogManager::unlink() {
std::string fullLogName = getFullPath(LOG_NAME);
if (::unlink(fullLogName.c_str()) != 0) {
PLOG(ERROR) << "Could not unlink " << fullLogName;
return false;
}
return true;
}
bool TransferLogManager::closeAndStopWriter() {
if (fd_ < 0) {
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
finished_ = true;
conditionFinished_.notify_all();
}
writerThread_.join();
WDT_CHECK(entries_.empty());
if (!close()) {
return false;
}
return true;
}
void TransferLogManager::writeEntriesToDisk() {
WDT_CHECK(fd_ >= 0) << "Writer thread started before the log is opened";
auto &options = WdtOptions::get();
WDT_CHECK(options.transfer_log_write_interval_ms >= 0);
auto waitingTime =
std::chrono::milliseconds(options.transfer_log_write_interval_ms);
std::vector<std::string> entries;
bool finished = false;
while (!finished) {
{
std::unique_lock<std::mutex> lock(mutex_);
conditionFinished_.wait_for(lock, waitingTime);
finished = finished_;
// make a copy of all the entries so that we do not need to hold lock
// during writing
entries = entries_;
entries_.clear();
}
std::string buffer;
// write entries to disk
for (const auto &entry : entries) {
buffer.append(entry);
}
int toWrite = buffer.size();
int written = ::write(fd_, buffer.c_str(), toWrite);
if (written != toWrite) {
PLOG(ERROR) << "Disk write error while writing transfer log " << written
<< " " << toWrite;
close();
return;
}
}
}
bool TransferLogManager::parseLogHeader(char *buf, int16_t entrySize,
int64_t ×tamp, int &version,
std::string &recoveryId) {
folly::ByteRange br((uint8_t *)buf, entrySize);
try {
timestamp = decodeInt(br);
version = decodeInt(br);
if (!decodeString(br, buf, entrySize, recoveryId)) {
return false;
}
} catch (const std::exception &ex) {
LOG(ERROR) << "got exception " << folly::exceptionStr(ex);
return false;
}
return checkForOverflow(br.start() - (uint8_t *)buf, entrySize);
}
bool TransferLogManager::parseFileCreationEntry(char *buf, int16_t entrySize,
int64_t ×tamp,
std::string &fileName,
int64_t &seqId,
int64_t &fileSize) {
folly::ByteRange br((uint8_t *)buf, entrySize);
try {
timestamp = decodeInt(br);
if (!decodeString(br, buf, entrySize, fileName)) {
return false;
}
seqId = decodeInt(br);
fileSize = decodeInt(br);
} catch (const std::exception &ex) {
LOG(ERROR) << "got exception " << folly::exceptionStr(ex);
return false;
}
return checkForOverflow(br.start() - (uint8_t *)buf, entrySize);
}
bool TransferLogManager::parseBlockWriteEntry(char *buf, int16_t entrySize,
int64_t ×tamp,
int64_t &seqId, int64_t &offset,
int64_t &blockSize) {
folly::ByteRange br((uint8_t *)buf, entrySize);
try {
timestamp = decodeInt(br);
seqId = decodeInt(br);
offset = decodeInt(br);
blockSize = decodeInt(br);
} catch (const std::exception &ex) {
LOG(ERROR) << "got exception " << folly::exceptionStr(ex);
return false;
}
return checkForOverflow(br.start() - (uint8_t *)buf, entrySize);
}
bool TransferLogManager::parseInvalidationEntry(char *buf, int16_t entrySize,
int64_t ×tamp,
int64_t &seqId) {
folly::ByteRange br((uint8_t *)buf, entrySize);
try {
timestamp = decodeInt(br);
seqId = decodeInt(br);
} catch (const std::exception &ex) {
LOG(ERROR) << "got exception " << folly::exceptionStr(ex);
return false;
}
return checkForOverflow(br.start() - (uint8_t *)buf, entrySize);
}
void TransferLogManager::encodeInvalidationEntry(char *dest, int64_t &off,
int64_t seqId) {
int64_t oldOffset = off;
char *ptr = dest + off + sizeof(int16_t);
ptr[off++] = ENTRY_INVALIDATION;
encodeInt(ptr, off, timestampInMicroseconds());
encodeInt(ptr, off, seqId);
folly::storeUnaligned<int16_t>(dest, off - oldOffset);
}
bool TransferLogManager::writeInvalidationEntries(
const std::set<int64_t> &seqIds) {
int fd = open();
if (fd < 0) {
return false;
}
char buf[kMaxEntryLength];
for (auto seqId : seqIds) {
int64_t size = 0;
encodeInvalidationEntry(buf, size, seqId);
int toWrite = size + sizeof(int16_t);
int written = ::write(fd, buf, toWrite);
if (written != toWrite) {
PLOG(ERROR) << "Disk write error while writing transfer log " << written
<< " " << toWrite;
::close(fd);
return false;
}
}
if (::fsync(fd) != 0) {
PLOG(ERROR) << "fsync() failed for fd " << fd;
::close(fd);
return false;
}
if (::close(fd) != 0) {
PLOG(ERROR) << "close() failed for fd " << fd;
}
return true;
}
bool TransferLogManager::truncateExtraBytesAtEnd(int fd, int extraBytes) {
LOG(INFO) << "Removing extra " << extraBytes
<< " bytes from the end of transfer log";
struct stat statBuffer;
if (fstat(fd, &statBuffer) != 0) {
PLOG(ERROR) << "fstat failed on fd " << fd;
return false;
}
off_t fileSize = statBuffer.st_size;
if (::ftruncate(fd, fileSize - extraBytes) != 0) {
PLOG(ERROR) << "ftruncate failed for fd " << fd;
return false;
}
return true;
}
bool TransferLogManager::parseAndPrint() {
std::vector<FileChunksInfo> parsedInfo;
return parseVerifyAndFix("", true, parsedInfo);
}
std::vector<FileChunksInfo> TransferLogManager::parseAndMatch(
const std::string &recoveryId) {
std::vector<FileChunksInfo> parsedInfo;
parseVerifyAndFix(recoveryId, false, parsedInfo);
return parsedInfo;
}
bool TransferLogManager::parseVerifyAndFix(
const std::string &recoveryId, bool parseOnly,
std::vector<FileChunksInfo> &parsedInfo) {
WDT_CHECK(parsedInfo.empty()) << "parsedInfo vector must be empty";
std::string fullLogName = getFullPath(LOG_NAME);
int logFd = ::open(fullLogName.c_str(), O_RDONLY);
if (logFd < 0) {
PLOG(ERROR) << "Unable to open transfer log " << fullLogName;
return false;
}
auto errorGuard = folly::makeGuard([&] {
if (logFd >= 0) {
::close(logFd);
}
if (!parseOnly) {
if (::rename(getFullPath(LOG_NAME).c_str(),
getFullPath(BUGGY_LOG_NAME).c_str()) != 0) {
PLOG(ERROR) << "log rename failed " << LOG_NAME << " "
<< BUGGY_LOG_NAME;
}
}
});
std::map<int64_t, FileChunksInfo> fileInfoMap;
std::map<int64_t, int64_t> seqIdToSizeMap;
std::string fileName, logRecoveryId;
int64_t timestamp, seqId, fileSize, offset, blockSize;
int logVersion;
std::set<int64_t> invalidSeqIds;
char entry[kMaxEntryLength];
while (true) {
int16_t entrySize;
int toRead = sizeof(entrySize);
int numRead = ::read(logFd, &entrySize, toRead);
if (numRead < 0) {
PLOG(ERROR) << "Error while reading transfer log " << numRead << " "
<< toRead;
return false;
}
if (numRead == 0) {
break;
}
if (numRead != toRead) {
// extra bytes at the end, most likely part of the previous write
// succeeded partially
if (parseOnly) {
LOG(INFO) << "Extra " << numRead << " bytes at the end of the log";
} else if (!truncateExtraBytesAtEnd(logFd, numRead)) {
return false;
}
break;
}
if (entrySize < 0 || entrySize > kMaxEntryLength) {
LOG(ERROR) << "Transfer log parse error, invalid entry length "
<< entrySize;
return false;
}
numRead = ::read(logFd, entry, entrySize);
if (numRead < 0) {
PLOG(ERROR) << "Error while reading transfer log " << numRead << " "
<< entrySize;
return false;
}
if (numRead == 0) {
break;
}
if (numRead != entrySize) {
if (parseOnly) {
LOG(INFO) << "Extra " << numRead << " bytes at the end of the log";
} else if (!truncateExtraBytesAtEnd(logFd, numRead)) {
return false;
}
break;
}
EntryType type = (EntryType)entry[0];
switch (type) {
case HEADER: {
if (!parseLogHeader(entry + 1, entrySize - 1, timestamp, logVersion,
logRecoveryId)) {
return false;
}
if (logVersion != LOG_VERSION) {
LOG(ERROR) << "Can not parse log version " << logVersion
<< ", parser version " << LOG_VERSION;
return false;
}
if (!parseOnly && recoveryId != logRecoveryId) {
LOG(ERROR)
<< "Current recovery-id does not match with log recovery-id "
<< recoveryId << " " << logRecoveryId;
return false;
}
if (parseOnly) {
std::cout << getFormattedTimestamp(timestamp)
<< " New transfer started, log-version " << logVersion
<< " recovery-id " << logRecoveryId << std::endl;
}
break;
}
case FILE_CREATION: {
if (!parseFileCreationEntry(entry + 1, entrySize - 1, timestamp,
fileName, seqId, fileSize)) {
return false;
}
if (fileInfoMap.find(seqId) != fileInfoMap.end() ||
invalidSeqIds.find(seqId) != invalidSeqIds.end()) {
LOG(ERROR) << "Multiple FILE_CREATION entry for same sequence-id "
<< fileName << " " << seqId << " " << fileSize;
return false;
}
if (parseOnly) {
std::cout << getFormattedTimestamp(timestamp) << " File created "
<< fileName << " seq-id " << seqId << " file-size "
<< fileSize << std::endl;
fileInfoMap.emplace(seqId, FileChunksInfo(seqId, fileName, fileSize));
break;
}
// verify size
bool sizeVerificationSuccess = false;
struct stat buffer;
if (stat(getFullPath(fileName).c_str(), &buffer) != 0) {
PLOG(ERROR) << "stat failed for " << fileName;
} else {
#ifdef HAS_POSIX_FALLOCATE
sizeVerificationSuccess = (buffer.st_size == fileSize);
#else
sizeVerificationSuccess = (buffer.st_size <= fileSize);
#endif
}
if (sizeVerificationSuccess) {
fileInfoMap.emplace(seqId, FileChunksInfo(seqId, fileName, fileSize));
seqIdToSizeMap.emplace(seqId, buffer.st_size);
} else {
LOG(INFO) << "Sanity check failed for " << fileName << " seq-id "
<< seqId << " file-size " << fileSize;
invalidSeqIds.insert(seqId);
}
break;
}
case BLOCK_WRITE: {
if (!parseBlockWriteEntry(entry + 1, entrySize - 1, timestamp, seqId,
offset, blockSize)) {
return false;
}
if (invalidSeqIds.find(seqId) != invalidSeqIds.end()) {
LOG(INFO) << "Block entry for an invalid sequence-id " << seqId
<< ", ignoring";
continue;
}
auto it = fileInfoMap.find(seqId);
if (it == fileInfoMap.end()) {
LOG(ERROR) << "Block entry for unknown sequence-id " << seqId << " "
<< offset << " " << blockSize;
return false;
}
FileChunksInfo &chunksInfo = it->second;
if (parseOnly) {
std::cout << getFormattedTimestamp(timestamp) << " Block written "
<< chunksInfo.getFileName() << " seq-id " << seqId
<< " offset " << offset << " block-size " << blockSize
<< std::endl;
} else {
auto sizeIt = seqIdToSizeMap.find(seqId);
WDT_CHECK(sizeIt != seqIdToSizeMap.end());
if (offset + blockSize > sizeIt->second) {
LOG(ERROR) << "Block end point is greater than file size in disk "
<< chunksInfo.getFileName() << " seq-id " << seqId
<< " offset " << offset << " block-size " << blockSize
<< " file size in disk " << sizeIt->second;
return false;
}
}
chunksInfo.addChunk(Interval(offset, offset + blockSize));
break;
}
case ENTRY_INVALIDATION: {
if (!parseInvalidationEntry(entry + 1, entrySize - 1, timestamp,
seqId)) {
return false;
}
if (fileInfoMap.find(seqId) == fileInfoMap.end() &&
invalidSeqIds.find(seqId) == invalidSeqIds.end()) {
LOG(ERROR) << "Invalidation entry for an unknown sequence id "
<< seqId;
return false;
}
if (parseOnly) {
std::cout << getFormattedTimestamp(timestamp)
<< " Invalidation entry for seq-id " << seqId << std::endl;
}
fileInfoMap.erase(seqId);
invalidSeqIds.erase(seqId);
break;
}
default: {
LOG(ERROR) << "Invalid entry type found " << type;
return false;
}
}
}
if (parseOnly) {
// no need to add invalidation entries in case of invocation from cmd line
return true;
}
if (::close(logFd) != 0) {
PLOG(ERROR) << "close() failed for fd " << logFd;
}
logFd = -1;
if (!invalidSeqIds.empty()) {
if (!writeInvalidationEntries(invalidSeqIds)) {
return false;
}
}
errorGuard.dismiss();
for (auto &pair : fileInfoMap) {
FileChunksInfo &fileInfo = pair.second;
fileInfo.mergeChunks();
parsedInfo.emplace_back(std::move(fileInfo));
}
return true;
}
}
}
| 32.657238
| 80
| 0.590972
|
agomez0207
|
6747f49a6dc5ecbcf0091a7a9277dedd1823e63a
| 929
|
cpp
|
C++
|
platforms/gfg/0097_diagonal_traversal_of_binary_tree.cpp
|
idfumg/algorithms
|
06f85c5a1d07a965df44219b5a6bf0d43a129256
|
[
"MIT"
] | 2
|
2020-09-17T09:04:00.000Z
|
2020-11-20T19:43:18.000Z
|
platforms/gfg/0097_diagonal_traversal_of_binary_tree.cpp
|
idfumg/algorithms
|
06f85c5a1d07a965df44219b5a6bf0d43a129256
|
[
"MIT"
] | null | null | null |
platforms/gfg/0097_diagonal_traversal_of_binary_tree.cpp
|
idfumg/algorithms
|
06f85c5a1d07a965df44219b5a6bf0d43a129256
|
[
"MIT"
] | null | null | null |
#include "../../template.hpp"
ostream& operator<<(ostream& os, Node* root) { print_inorder(root); return os; }
void preorder(Node* root, map<int, vi>& tab, int diagonal) {
if (not root) return;
tab[diagonal].push_back(root->value);
preorder(root->left, tab, diagonal + 1);
preorder(root->right, tab, diagonal);
}
void DiagonalPrint(Node* root) {
map<int, vi> tab;
preorder(root, tab, 0);
for (const auto& [diagonal, nodes] : tab) {
cout << nodes << endl;
}
}
int main() { TimeMeasure _; __x();
Node* root = new Node(8);
root->left = new Node(3);
root->right = new Node(10);
root->left->left = new Node(1);
root->left->right = new Node(6);
root->right->right = new Node(14);
root->right->right->left = new Node(13);
root->left->right->left = new Node(4);
root->left->right->right = new Node(7);
DiagonalPrint(root);
/*
8 10 14
3 6 7 13
1 4
*/
}
| 24.447368
| 80
| 0.595264
|
idfumg
|
6748cabbd113ed004698fdb04af485f3e4f6acf6
| 2,186
|
cpp
|
C++
|
src/status.cpp
|
Nakeib/RonClient
|
9e816c580ec2a6f1b15fdefd8e15ad62647ca29f
|
[
"MIT"
] | 11
|
2020-11-07T19:35:24.000Z
|
2021-08-19T12:25:27.000Z
|
src/status.cpp
|
Nakeib/RonClient
|
9e816c580ec2a6f1b15fdefd8e15ad62647ca29f
|
[
"MIT"
] | null | null | null |
src/status.cpp
|
Nakeib/RonClient
|
9e816c580ec2a6f1b15fdefd8e15ad62647ca29f
|
[
"MIT"
] | 5
|
2020-11-06T20:52:11.000Z
|
2021-02-25T11:02:31.000Z
|
/* -------------------------------------------------------------------------- */
/* ------------- RonClient --- Oficial client for RonOTS servers ------------ */
/* -------------------------------------------------------------------------- */
#include "status.h"
#include "allocator.h"
#include "icons.h"
#include "window.h"
// ---- Status ---- //
MUTEX Status::lockStatus;
Status::Status() {
icons = 0;
container = NULL;
}
Status::~Status() { }
void Status::SetIcons(unsigned short icons) {
this->icons = icons;
}
unsigned short Status::GetIcons() {
return icons;
}
void Status::SetPeriod(unsigned char id, unsigned int period) {
LOCKCLASS lockClass(lockStatus);
time_lt now = RealTime::getTime();
std::map<unsigned char, StatusTime>::iterator it = times.find(id);
if (it != times.end()) {
StatusTime stime = it->second;
if (abs((long)(stime.first + stime.second) - (long)(now + period)) > 1000)
times[id] = StatusTime(now, period);
}
else
times[id] = StatusTime(now, period);
}
void Status::SetContainer(WindowElementContainer* container) {
LOCKCLASS lockClass(lockStatus);
this->container = container;
}
void Status::UpdateContainer() {
LOCKCLASS lockClass1(Windows::lockWindows);
LOCKCLASS lockClass2(lockStatus);
if (!container)
return;
container->DeleteAllElements();
Window* window = container->GetWindow();
WindowTemplate* wndTemplate = window->GetWindowTemplate();
window->SetActiveElement(NULL);
POINT size_int = window->GetWindowContainer()->GetIntSize();
POINT size_ext = container->GetIntSize();
int num = 0;
for (int i = 0; i < 15; i++) {
if (icons & (1 << i)) {
StatusTime stime(0, 0);
std::map<unsigned char, StatusTime>::iterator it = times.find(i + 1);
if (it != times.end())
stime = it->second;
AD2D_Image* image = Icons::GetStatusIcon(i + 1);
WindowElementCooldown* wstatus = new(M_PLACE) WindowElementCooldown;
wstatus->Create(0, 0, num * 32, 32, 32, wndTemplate);
wstatus->SetCast(stime.first, stime.second);
wstatus->SetIcon(image);
container->AddElement(wstatus);
num++;
}
}
container->SetPosition(0, size_int.y - num * 32);
container->SetSize(32, num * 32);
}
| 23.505376
| 80
| 0.618939
|
Nakeib
|
674a7eb21be0415058f79fdae32ac00ef058376d
| 1,664
|
hpp
|
C++
|
Router/Data/Route_Stop_Data.hpp
|
kravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | 2
|
2018-04-27T11:07:02.000Z
|
2020-04-24T06:53:21.000Z
|
Router/Data/Route_Stop_Data.hpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
Router/Data/Route_Stop_Data.hpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
//*********************************************************
// Route_Stop_Data.hpp - transit route stop data classes
//*********************************************************
#ifndef ROUTE_STOP_DATA_HPP
#define ROUTE_STOP_DATA_HPP
#include "Data_Array.hpp"
//---------------------------------------------------------
// Route_Stop_Data class definition
//---------------------------------------------------------
class Route_Stop_Data
{
public:
Route_Stop_Data (void);
int Route (void) { return (route); }
int Stop (void) { return (stop); }
int List (void) { return (list); }
void Route (int value) { route = (short) value; }
void Stop (int value) { stop = (short) value; }
void List (int value) { list = value; }
private:
short route;
short stop;
int list;
};
//---------------------------------------------------------
// Route_Stop_Array
//---------------------------------------------------------
class Route_Stop_Array : public Data_Array
{
public:
Route_Stop_Array (int max_records = 0);
bool Add (Route_Stop_Data *data) { return (Data_Array::Add ((void *) data)); }
Route_Stop_Data * First (void) { return ((Route_Stop_Data *) Data_Array::First ()); }
Route_Stop_Data * Next (void) { return ((Route_Stop_Data *) Data_Array::Next ()); }
Route_Stop_Data * Last (void) { return ((Route_Stop_Data *) Data_Array::Last ()); }
Route_Stop_Data * Previous (void) { return ((Route_Stop_Data *) Data_Array::Previous ()); }
Route_Stop_Data * operator[] (int index) { return ((Route_Stop_Data *) Record (index)); }
};
#endif
| 30.814815
| 100
| 0.497596
|
kravitz
|
674cc6352b2fd0e6c122e527457aa0a2f14c39da
| 138
|
hpp
|
C++
|
externals/numeric_bindings/libs/numeric/bindings/tools/templates/driver/stev.hpp
|
ljktest/siconos
|
85b60e62beca46e6bf06bfbd65670089e86607c7
|
[
"Apache-2.0"
] | 137
|
2015-06-16T15:55:28.000Z
|
2022-03-26T06:01:59.000Z
|
externals/numeric_bindings/libs/numeric/bindings/tools/templates/driver/stev.hpp
|
ljktest/siconos
|
85b60e62beca46e6bf06bfbd65670089e86607c7
|
[
"Apache-2.0"
] | 381
|
2015-09-22T15:31:08.000Z
|
2022-02-14T09:05:23.000Z
|
externals/numeric_bindings/libs/numeric/bindings/tools/templates/driver/stev.hpp
|
ljktest/siconos
|
85b60e62beca46e6bf06bfbd65670089e86607c7
|
[
"Apache-2.0"
] | 30
|
2015-08-06T22:57:51.000Z
|
2022-03-02T20:30:20.000Z
|
$TEMPLATE[stev.real.min_size_work.args]
N
$TEMPLATE[stev.real.min_size_work]
return std::max< $INTEGER_TYPE >( 1, 2*n-2 );
$TEMPLATE[end]
| 23
| 45
| 0.73913
|
ljktest
|
6750116edd11d113a2610814ba8adbaca4bcf5b5
| 4,518
|
cpp
|
C++
|
src/main.cpp
|
scaryrawr/tofi
|
15b3757c4d492d5bbc7f57aef94f582549d2bef3
|
[
"MIT"
] | 1
|
2020-08-03T18:57:01.000Z
|
2020-08-03T18:57:01.000Z
|
src/main.cpp
|
scaryrawr/tofi
|
15b3757c4d492d5bbc7f57aef94f582549d2bef3
|
[
"MIT"
] | 1
|
2021-03-07T21:32:10.000Z
|
2021-03-08T13:56:10.000Z
|
src/main.cpp
|
scaryrawr/tofi
|
15b3757c4d492d5bbc7f57aef94f582549d2bef3
|
[
"MIT"
] | null | null | null |
#include <TofiConfig.h>
#include "tofi.h"
#include "modes/dmenu.h"
#ifdef GIOMM_FOUND
#include "modes/drun.h"
#endif
#ifdef I3IPC_FOUND
#include "modes/i3wm.h"
#endif
#ifdef GTKMM_FOUND
#include "modes/recent.h"
#endif
#include "modes/run.h"
#include "modes/script.h"
#include <getopt.h>
#include <ftxui/component/screen_interactive.hpp>
#include <mtl/string.hpp>
struct LaunchMode
{
std::string_view mode;
std::optional<std::string_view> script;
};
struct LaunchOptions
{
bool dmenu{};
std::vector<LaunchMode> modes;
};
void help()
{
std::cout << "tofi usage:" << std::endl
<< "\ttofi [--options]" << std::endl
<< "Options:" << std::endl;
std::cout << "\t-d, --dmenu\tRun in dmenu mode" << std::endl;
std::cout << "\t-m, --modes\tStart with modes enabled [drun,run,i3wm]" << std::endl
<< "\t-h, --help \tDisplay this message" << std::endl
<< "Modes:" << std::endl;
#ifdef GIOMM_FOUND
std::cout << "\tdrun\tRun from list of desktop installed applications" << std::endl;
#endif
#ifdef GTKMM_FOUND
std::cout << "\recent\tOpen a recently opened file" << std::endl;
#endif
std::cout << "\trun \tRun from binaries on $PATH" << std::endl;
#ifdef I3IPC_FOUND
std::cout << "\ti3wm\tSwitch between active windows using i3ipc" << std::endl;
#endif
std::cout << "Script:" << std::endl
<< "\tPass a custom command disp:command" << std::endl
<< "\t\t -m list:ls" << std::endl
<< std::endl
<< "\tcommand will be called with selected result" << std::endl
<< "\ttofi will stay open as long as command prints output" << std::endl;
exit(-1);
}
LaunchOptions parse_args(int argc, char **argv)
{
LaunchOptions launch{};
enum class Option
{
modes,
dmenu,
help,
};
static option options[] = {
{"modes", required_argument, nullptr, 0},
{"dmenu", no_argument, nullptr, 0},
{"help", no_argument, nullptr, 0},
};
for (int index{}, code{getopt_long(argc, argv, "m:dh", options, &index)}; code >= 0; code = getopt_long(argc, argv, "m:dh", options, &index))
{
switch (code)
{
case 'd':
index = static_cast<int>(Option::dmenu);
break;
case 'm':
index = static_cast<int>(Option::modes);
break;
case 'h':
index = static_cast<int>(Option::help);
break;
}
switch (static_cast<Option>(index))
{
case Option::dmenu:
{
launch.dmenu = true;
break;
}
case Option::modes:
{
std::vector<std::string_view> modes;
mtl::string::split(optarg, ",", std::back_inserter(modes));
launch.modes.reserve(modes.size());
std::transform(std::begin(modes), std::end(modes), std::back_inserter(launch.modes), [](std::string_view mode) {
std::vector<std::string_view> parts;
parts.reserve(2);
mtl::string::split(mode, ":", std::back_inserter(parts));
return parts.size() == 1 ? LaunchMode{parts[0], std::nullopt} : LaunchMode{parts[0], parts[1]};
});
break;
}
case Option::help:
{
help();
break;
}
}
}
return launch;
}
int main(int argc, char **argv)
{
LaunchOptions options{parse_args(argc, argv)};
tofi::Modes modes;
// If we're in dmenu mode, other modes might break, so... just dmenu
if (options.dmenu)
{
modes.emplace_back(std::make_unique<tofi::modes::dmenu>());
}
else
{
std::transform(std::begin(options.modes), std::end(options.modes), std::back_inserter(modes), [](const LaunchMode &mode) -> std::unique_ptr<tofi::Mode> {
if (mode.script.has_value())
{
return std::make_unique<tofi::modes::script>(mode.mode, mode.script.value());
}
#ifdef I3IPC_FOUND
if ("i3wm" == mode.mode)
{
return std::make_unique<tofi::modes::i3wm>("tofi");
}
#endif
if ("run" == mode.mode)
{
return std::make_unique<tofi::modes::run>();
}
#ifdef GIOMM_FOUND
if ("drun" == mode.mode)
{
return std::make_unique<tofi::modes::drun>();
}
#endif
#ifdef GTKMM_FOUND
if ("recent" == mode.mode)
{
return std::make_unique<tofi::modes::recent>();
}
#endif
return nullptr;
});
}
modes.erase(std::remove(std::begin(modes), std::end(modes), nullptr), std::end(modes));
if (modes.empty())
{
// We don't have any modes, so show user help.
help();
}
// Use active wal theme if available
system("[ -f $HOME/.cache/wal/sequences ] && cat $HOME/.cache/wal/sequences");
tofi::Tofi tofi{std::move(modes)};
int exit{};
auto screen = ftxui::ScreenInteractive::TerminalOutput();
tofi.on_exit = [&exit, &screen](int code) {
exit = code;
screen.ExitLoopClosure()();
};
screen.Loop(&tofi);
return exit;
}
| 22.366337
| 155
| 0.634794
|
scaryrawr
|
67510af1134b5530b703475985ce9f9b695fc754
| 3,147
|
cpp
|
C++
|
SceneServer/SSBattleMgr/SSProfileStatics.cpp
|
tsymiar/----
|
90e21cbfe7b3bc730c998e9f5ef87aa3581e357a
|
[
"Unlicense"
] | 6
|
2019-07-15T23:55:15.000Z
|
2020-09-07T15:07:54.000Z
|
SceneServer/SSBattleMgr/SSProfileStatics.cpp
|
j1527156/BattleServer
|
68c9146bf35e93dfd5a175b46e9761ee3c7c0d04
|
[
"Unlicense"
] | null | null | null |
SceneServer/SSBattleMgr/SSProfileStatics.cpp
|
j1527156/BattleServer
|
68c9146bf35e93dfd5a175b46e9761ee3c7c0d04
|
[
"Unlicense"
] | 7
|
2019-07-15T23:55:24.000Z
|
2021-08-10T07:49:05.000Z
|
#include "StdAfx.h"
#include "SSProfileStatics.h"
#include <iostream>
#include <fstream>
#include "SSWorkThreadMgr.h"
#include <iomanip>
namespace SceneServer{
CSSProfileStatics::CSSProfileStatics(void):m_LastMsgShow(0)
{
}
CSSProfileStatics::~CSSProfileStatics(void)
{
}
void CSSProfileStatics::Begin(StaticsType aType){
auto iter = m_ProfileMap.find(aType);
TIME_MILSEC now = GetWinMiliseconds();
if (iter == m_ProfileMap.end()){
ProfileData lProfileData;
lProfileData.beginTime = now;
switch(aType){
case StaticsType_NPCLookEnemy:
lProfileData.debugString = "NPCLookEnemy";
break;
case StaticsType_Move:
lProfileData.debugString = "Move";
break;
case StaticsType_Sight:
lProfileData.debugString = "Sight";
break;
}
m_ProfileMap.insert(std::make_pair(aType, lProfileData));
}
else{
iter->second.beginTime = now;
}
}
void CSSProfileStatics::End(StaticsType aType){
auto iter = m_ProfileMap.find(aType);
TIME_MILSEC now = GetWinMiliseconds();
if (iter != m_ProfileMap.end()){
iter->second.tottime += now - iter->second.beginTime;
iter->second.beginTime = 0;
}
}
CSSProfileStatics& CSSProfileStatics::GetInstance(){
static CSSProfileStatics lCSSProfileStatics;
return lCSSProfileStatics;
}
void CSSProfileStatics::GetProfileReport(wstringstream &report){
if (!CSSWorkThreadMgr::GetInstance().m_IfStatics){
return;
}
//if (CSSWorkThreadMgr::GetInstance().GetKernel()->GetHeartBeatUTCMilsec() - m_LastMsgShow < CSSWorkThreadMgr::GetInstance().m_MsgStaticsInterval){
// return;
//}
stringstream lTestStream;
//m_LastMsgShow = CSSWorkThreadMgr::GetInstance().GetKernel()->GetHeartBeatUTCMilsec();
//for (auto iter = m_ProfileMap.begin(); iter != m_ProfileMap.end(); ++iter){
// ProfileData& lProfileData = iter->second;
// if (lProfileData.tottime != 0){
// lTestStream << " " << setw(7) << lProfileData.debugString.c_str() << ":" << lProfileData.tottime;
// lProfileData.tottime = 0;
// }
//}
int i = 0;
set<MsgInterval> tempSet;
for (auto iter = m_TotNumForPerMsg.begin(); iter != m_TotNumForPerMsg.end(); ++iter){
MsgInterval lMsgInterval(iter->first, iter->second);
tempSet.insert(lMsgInterval);
}
int max = CSSWorkThreadMgr::GetInstance().m_MaxStatisMsgToShow;
for (auto iter = tempSet.begin(); iter != tempSet.end(); ++iter){
if (i > max){
break;
}
++i;
lTestStream << " " << setw(7) << iter->msgid << "," << iter->msgnum;
}
if (!lTestStream.str().empty()){
ELOG(LOG_SpecialDebug, "%s", lTestStream.str().c_str());
}
}
void CSSProfileStatics::AddMsg(int Msgid){
if (!CSSWorkThreadMgr::GetInstance().m_IfStatics){
return;
}
auto iter = m_TotNumForPerMsg.find(Msgid);
if (iter == m_TotNumForPerMsg.end()){
m_TotNumForPerMsg.insert(std::make_pair(Msgid, 1));
}
else{
++iter->second;
}
}
ProfileInScope::ProfileInScope(StaticsType aType):m_Type(aType){
if (!CSSWorkThreadMgr::GetInstance().m_IfStatics){
return;
}
CSSProfileStatics::GetInstance().Begin(m_Type);
}
ProfileInScope::~ProfileInScope(){
if (!CSSWorkThreadMgr::GetInstance().m_IfStatics){
return;
}
CSSProfileStatics::GetInstance().End(m_Type);
}
}
| 24.779528
| 148
| 0.71306
|
tsymiar
|
675e2a110fefc2b8916753461909761463c1ded6
| 1,108
|
cpp
|
C++
|
Graph/Dijkstra.cpp
|
XitizVerma/Data-Structures-and-Algorithms-Advanced
|
610225eeb7e0b4ade229ec86355901ad1ca38784
|
[
"MIT"
] | 1
|
2020-08-27T06:59:52.000Z
|
2020-08-27T06:59:52.000Z
|
Graph/Dijkstra.cpp
|
XitizVerma/Data-Structures-and-Algorithms-Advanced
|
610225eeb7e0b4ade229ec86355901ad1ca38784
|
[
"MIT"
] | null | null | null |
Graph/Dijkstra.cpp
|
XitizVerma/Data-Structures-and-Algorithms-Advanced
|
610225eeb7e0b4ade229ec86355901ad1ca38784
|
[
"MIT"
] | null | null | null |
//author : Avishkar A. Hande
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxS = 1e5+10;
vector<pair<ll, ll>> adj[maxS]; // represents adjacency list to store weight and destination node as a pair
vector<ll> dist(maxS, 1e9); // distance array initialised assuming 1e9 as infinity
void dijkstra(ll source){
priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>> pq;
pq.push({0, source}); // pair of distance and node
dist[source] = 0; // source node has 0 distance
while(!pq.empty()){
pair<ll, ll> top = pq.top();
pq.pop();
for(pair<ll, ll> child: adj[top.second]){
if(dist[top.second] + child.first < dist[child.second]){
dist[child.second] = dist[top.second] + child.first;
pq.push(child);
}
}
}
}
int main()
{
ll nodes, edges;
cin >> nodes >> edges;
while(edges--){
ll from, to, weight;
cin >> from >> to >> weight;
adj[from].push_back({weight, to});
adj[to].push_back({weight, from});
}
dijkstra(1); // replace 1 with source node.
for(int i = 0; i < nodes; i++){
cout << dist[i] << " ";
}cout << endl;
}
| 25.767442
| 107
| 0.635379
|
XitizVerma
|
67635a72614c96245d14753a30f9db84a551520f
| 2,788
|
cpp
|
C++
|
src/robotican_demos_upgrade/src/depth_to_base_foot.cpp
|
aosbgu/ROSPlan-ExperimentPDDL
|
09de0ba980362606dd1269c6689cb59d6f8776c6
|
[
"MIT"
] | null | null | null |
src/robotican_demos_upgrade/src/depth_to_base_foot.cpp
|
aosbgu/ROSPlan-ExperimentPDDL
|
09de0ba980362606dd1269c6689cb59d6f8776c6
|
[
"MIT"
] | null | null | null |
src/robotican_demos_upgrade/src/depth_to_base_foot.cpp
|
aosbgu/ROSPlan-ExperimentPDDL
|
09de0ba980362606dd1269c6689cb59d6f8776c6
|
[
"MIT"
] | null | null | null |
#include "ros/ros.h"
#include "tf/message_filter.h"
#include "message_filters/subscriber.h"
#include <ar_track_alvar_msgs/AlvarMarkers.h>
tf::TransformListener *listener_ptr;
int object_id = 1;
ros::Publisher object_pub;
ros::Publisher object_pub1;
void obj_msgCallback(const boost::shared_ptr<const geometry_msgs::PoseStamped>& point_ptr)
{
//ROS_INFO_STREAM("Received pose x: " << point_ptr->pose.position.x);
//get object location msg
try
{
geometry_msgs::PoseStamped base_object_pose;
listener_ptr->transformPose("base_footprint", *point_ptr, base_object_pose);
base_object_pose.pose.orientation= tf::createQuaternionMsgFromRollPitchYaw(0.0,0.0,0.0);
//simulate alvar msgs, to get tf
ar_track_alvar_msgs::AlvarMarkers msg;
msg.header.stamp=base_object_pose.header.stamp;
msg.header.frame_id="base_footprint";
ar_track_alvar_msgs::AlvarMarker m;
m.id=object_id;
m.header.stamp=base_object_pose.header.stamp;
m.header.frame_id="base_footprint";
m.pose=base_object_pose;
msg.markers.push_back(m);
m.pose.pose.position.z-=0.1;
m.id=2;
msg.markers.push_back(m);
object_pub.publish(msg);
geometry_msgs::PoseStamped base_object_pose1;
listener_ptr->transformPose("base_footprint", *point_ptr, base_object_pose1);
base_object_pose1.pose.orientation= tf::createQuaternionMsgFromRollPitchYaw(M_PI,0.0,0.0);
//ROS_INFO("Did the transformation");
//printf("X: %lf Y: %lf Z: %lf\n",base_object_pose1.pose.position.x,base_object_pose1.pose.position.y,base_object_pose1.pose.position.z);
object_pub1.publish(base_object_pose1);
}
catch (tf::TransformException &ex)
{
printf ("Failure %s\n", ex.what()); //Print exception which was caught
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "detected_objects");
ros::NodeHandle n;
object_pub=n.advertise<ar_track_alvar_msgs::AlvarMarkers>("detected_objects", 2, true);
object_pub1=n.advertise<geometry_msgs::PoseStamped>("detected_object1", 2, true);
//convert depth cam tf to base foot print tf (moveit work with base foot print tf)
tf::TransformListener listener;
listener_ptr=&listener;
message_filters::Subscriber<geometry_msgs::PoseStamped> point_sub_;
point_sub_.subscribe(n, "my_find_object/object_pose", 10);
//message_filters::Subscriber<geometry_msgs::PoseStamped> point_sub_(n, "object_pose", 10);
tf::MessageFilter<geometry_msgs::PoseStamped> tf_filter(point_sub_, listener, "base_footprint", 10);
tf_filter.registerCallback( boost::bind(obj_msgCallback, _1) );
ros::Rate r(10);
while (ros::ok()) {
ros::spinOnce();
r.sleep();
}
return 0;
}
| 30.637363
| 145
| 0.707317
|
aosbgu
|
676c451ada470463a8f272b17b02d6618daac4cb
| 29,791
|
cpp
|
C++
|
fitp/pan/link_layer/link.cpp
|
BeeeOn/fitplib
|
71f8ab7ca2a35d97a9f56a9c8aac3b25fde0cb9f
|
[
"BSD-3-Clause"
] | null | null | null |
fitp/pan/link_layer/link.cpp
|
BeeeOn/fitplib
|
71f8ab7ca2a35d97a9f56a9c8aac3b25fde0cb9f
|
[
"BSD-3-Clause"
] | null | null | null |
fitp/pan/link_layer/link.cpp
|
BeeeOn/fitplib
|
71f8ab7ca2a35d97a9f56a9c8aac3b25fde0cb9f
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* @file link.cc
*/
#include "common/phy_layer/phy.h"
#include "pan/link_layer/link.h"
#include <stdio.h>
#include "common/log/log.h"
/*! bit mask of data transfer from coordinator to end device */
#define LINK_COORD_TO_ED 0x20
/*! bit mask of data transfer from end device to coordinator */
#define LINK_ED_TO_COORD 0x10
/*! bit mask of device busyness */
#define LINK_BUSY 0x08
/*! RX buffer size */
#define LINK_RX_BUFFER_SIZE 4
/*! TX buffer size */
#define LINK_TX_BUFFER_SIZE 4
/*! maximum number of channels */
#define MAX_CHANNEL 31
/*! broadcast address */
#define LINK_COORD_ALL 0xfc
/** @enum LINK_packet_type
* Packet types.
*/
enum LINK_packet_type_pan {
LINK_DATA_TYPE = 0, /**< DATA. */
LINK_COMMIT_TYPE = 1, /**< COMMIT. */
LINK_ACK_TYPE = 2, /**< ACK. */
LINK_COMMIT_ACK_TYPE = 3 /**< COMMIT ACK. */
};
/**
* Packet states during four-way handshake.
*/
enum LINK_tx_packet_state_pan {
DATA_SENT = 0, /**< DATA were sent. */
COMMIT_SENT = 1 /**< COMMIT was sent. */
};
/**
* Structure for coordinator RX buffer record (used during four-way handshake).
*/
typedef struct {
uint8_t data[MAX_PHY_PAYLOAD_SIZE]; /**< Data. */
uint8_t address_type:1; /**< Address type: 0 - coordinator, 1 - end device. */
uint8_t empty:1; /**< Flag if record is empty. */
uint8_t len:6; /**< Data length. */
uint8_t expiration_time; /**< Packet expiration time. */
uint8_t transfer_type; /**< Transfer type. */
union {
uint8_t coord; /**< Coordinator address. */
uint8_t ed[EDID_LENGTH]; /**< End device address. */
} address;
} LINK_rx_buffer_record_t;
/**
* Structure for coordinator TX buffer record (used during four-way handshake).
*/
typedef struct {
uint8_t data[MAX_PHY_PAYLOAD_SIZE]; /**< Data. */
uint8_t address_type:1; /**< Address type: 0 - coordinator, 1 - end device. */
uint8_t empty:1; /**< Flag if record is empty. */
uint8_t len:6; /**< Data length. */
uint8_t state:1; /**< Packet states: 0 - DATA were sent, 1 - COMMIT was sent. */
uint8_t expiration_time; /**< Packet expiration time. */
uint8_t transmits_to_error; /**< Maximum number of packet retransmissions. */
uint8_t transfer_type; /**< Transfer type. */
union {
uint8_t coord; /**< Coordinator address. */
uint8_t ed[EDID_LENGTH]; /**< End device address. */
} address;
} LINK_tx_buffer_record_t;
/**
* Structure for link layer.
*/
struct LINK_storage_t {
uint8_t tx_max_retries; /**< Maximum number of packet retransmissions. */
uint8_t timer_counter; /**< Timer for packet expiration time setting. */
LINK_rx_buffer_record_t rx_buffer[LINK_RX_BUFFER_SIZE]; /**< Array of RX buffer records for coordinator. */
LINK_tx_buffer_record_t tx_buffer[LINK_TX_BUFFER_SIZE]; /**< Array of TX buffer records for coordinator. */
} LINK_STORAGE;
extern void delay_ms (uint16_t t);
uint8_t LINK_cid_mask (uint8_t address);
/**
* Checks if identifier of end device equals to zeros.
* @param edid Identifier of end device (EDID).
* @return Returns true if EDID equals to zeros, false otherwise.
*/
bool zero_address (uint8_t* edid)
{
for (uint8_t i = 0; i < EDID_LENGTH; i++) {
if (edid[i] != 0)
return false;
}
return true;
}
/**
* Compares two arrays (4 B).
* @param array1 The first array.
* @param array2 The second array.
* @return Returns true if arrays are equal, false otherwise.
*/
bool array_cmp (uint8_t* array1, uint8_t* array2)
{
for (uint8_t i = 0; i < EDID_LENGTH; i++) {
if (array1[i] != array2[i])
return false;
}
return true;
}
/**
* Copies source array to destination array.
* @param src Source array.
* @param dst Destination array.
* @param size Array size.
*/
void array_copy (uint8_t* src, uint8_t* dst, uint8_t size)
{
for (uint8_t i = 0; i < size; i++) {
dst[i] = src[i];
}
}
/**
* Searches a free index in TX buffer.
* @return Returns a free index in TX buffer or invalid index in case of
* full TX buffer.
*/
uint8_t get_free_index_tx ()
{
uint8_t free_index = LINK_TX_BUFFER_SIZE;
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
if (LINK_STORAGE.tx_buffer[i].empty) {
free_index = i;
break;
}
}
return free_index;
}
/**
* Searches a free index in RX buffer.
* @return Returns a free index in RX buffer or invalid index in case of
* full RX buffer.
*/
uint8_t get_free_index_rx ()
{
uint8_t free_index = LINK_RX_BUFFER_SIZE;
for (uint8_t i = 0; i < LINK_RX_BUFFER_SIZE; i++) {
if (LINK_STORAGE.rx_buffer[i].empty) {
free_index = i;
break;
}
}
return free_index;
}
/**
* Generates packet header.
* @param header Array for link packet header.
* @param as_ed True if device sends packet as end device, false otherwise.
* @param to_ed True if device sends packet to end device, false otherwise.
* @param address Destination coordinator ID or end device ID.
* @param packet_type Packet type.
* @param transfer_type Transfer type on link layer.
*/
void gen_header (uint8_t* header, bool as_ed, bool to_ed,
uint8_t* address, uint8_t packet_type,
uint8_t transfer_type)
{
if (as_ed && to_ed) {
// communication between EDs is not allowed
return;
}
uint8_t header_index = 0;
// packet type (2 b), dst (1 b), src (1 b), transfer type (4 b)
header[header_index++] =
packet_type << 6 | (to_ed ? 1 : 0) << 5 | (as_ed ? 1 : 0) << 4 | (transfer_type & 0x0f);
// NID
for (uint8_t i = 0; i < EDID_LENGTH; i++) {
header[header_index++] = GLOBAL_STORAGE.nid[i];
}
// data sending to ED
if (to_ed) {
for (uint8_t i = 0; i < EDID_LENGTH; i++)
// ED address - dst
header[header_index++] = address[i];
// COORD address - src
header[header_index++] = GLOBAL_STORAGE.cid;
}
// data sending to COORD
else {
if (as_ed) {
// COORD address - dst
// ED can send packet to its descendant
header[header_index++] = *address;
// ED adress - src
for (uint8_t i = 0; i < EDID_LENGTH; i++)
header[header_index++] = GLOBAL_STORAGE.edid[i];
}
else {
// COORD address - dst
header[header_index++] = *address;
// COORD address - src
header[header_index++] = GLOBAL_STORAGE.cid;
}
}
}
/**
* Sends DATA.
* @param as_ed True if device sends packet as end device ID, false otherwise.
* @param to_ed True if device sends packet to end device ID, false otherwise.
* @param address Destination coordinator ID or end device ID.
* @param payload Payload.
* @param len Payload length.
* @param transfer_type Transfer type on link layer.
*/
void send_data (bool as_ed, bool to_ed, uint8_t* address, uint8_t* payload,
uint8_t len, uint8_t transfer_type)
{
uint8_t packet[MAX_PHY_PAYLOAD_SIZE];
gen_header (packet, as_ed, to_ed, address, LINK_DATA_TYPE,
transfer_type);
// size of link header
uint8_t packet_index = LINK_HEADER_SIZE;
for (uint8_t i = 0; i < len; i++)
packet[packet_index++] = payload[i];
D_LINK printf ("send_data()\n");
PHY_send_with_cca (packet, packet_index);
}
/**
* Sends ACK.
* @param as_ed True if device sends packet as end device ID, false otherwise.
* @param to_ed True if device sends packet to end device ID, false otherwise.
* @param address Destination coordinator ID or end device ID.
* @param transfer_type Transfer type on link layer.
*/
void send_ack (bool as_ed, bool to_ed, uint8_t* address, uint8_t transfer_type)
{
uint8_t ack_packet[LINK_HEADER_SIZE];
gen_header (ack_packet, as_ed, to_ed, address, LINK_ACK_TYPE,
transfer_type);
D_LINK printf ("send_ack()\n");
PHY_send_with_cca (ack_packet, LINK_HEADER_SIZE);
}
/**
* Sends COMMIT.
* @param as_ed True if device sends packet as end device ID, false otherwise.
* @param to_ed True if device sends packet to end device ID, false otherwise.
* @param address Destination coordinator ID or end device ID.
*/
void send_commit (bool as_ed, bool to_ed, uint8_t* address)
{
uint8_t commit_packet[LINK_HEADER_SIZE];
gen_header (commit_packet, as_ed, to_ed, address, LINK_COMMIT_TYPE,
LINK_DATA_HS4);
D_LINK printf ("send_commit()\n");
PHY_send_with_cca (commit_packet, LINK_HEADER_SIZE);
}
/**
* Sends COMMIT ACK.
* @param as_ed True if device sends packet as end device ID, false otherwise.
* @param to_ed True if device sends packet to end device ID, false otherwise.
* @param address Destination coordinator ID or end device ID.
*/
void send_commit_ack (bool as_ed, bool to_ed, uint8_t* address)
{
uint8_t commit_ack_packet[LINK_HEADER_SIZE];
gen_header (commit_ack_packet, as_ed, to_ed, address, LINK_COMMIT_ACK_TYPE,
LINK_DATA_HS4);
D_LINK printf ("send_commit_ack()\n");
PHY_send_with_cca (commit_ack_packet, LINK_HEADER_SIZE);
}
/**
* Sends BUSY ACK.
* @param as_ed True if device sends packet as end device ID, false otherwise.
* @param to_ed True if device sends packet to end device ID, false otherwise.
* @param address Destination coordinator ID or end device ID.
*/
void send_busy_ack (bool as_ed, bool to_ed, uint8_t* address)
{
uint8_t ack_packet[LINK_HEADER_SIZE];
gen_header (ack_packet, as_ed, to_ed, address, LINK_ACK_TYPE, LINK_BUSY);
D_LINK printf ("send_busy_ack()\n");
PHY_send_with_cca (ack_packet, LINK_HEADER_SIZE);
}
/**
* Processes packet for coordinator and routes it towards destination.
* @param data Data.
* @param len Data length.
* @return Returns false if packet is BUSY ACK,
* if the packet has been already stored in RX buffer
* or if the packet is not successfully sent, true otherwise.
*/
bool router_process_packet (uint8_t* data, uint8_t len)
{
uint8_t packet_type = data[0] >> 6;
uint8_t transfer_type = data[0] & 0x0f;
D_LINK printf("router_process_packet()\n");
// processing of ACK packet
if (packet_type == LINK_ACK_TYPE) {
D_LINK printf ("ACK\n");
if (data[0] & LINK_ED_TO_COORD) {
D_LINK printf ("R: ACK to COORD\n");
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
// if some DATA message for ED is in TX buffer and address is the same,
// COMMIT message can be sent
if (!LINK_STORAGE.tx_buffer[i].empty) {
if (LINK_STORAGE.tx_buffer[i].address_type == 1
&& array_cmp (LINK_STORAGE.tx_buffer[i].address.ed, data + 6)) {
// it is not BUSY ACK packet, switch state and send COMMIT packet
if (transfer_type != LINK_BUSY) {
LINK_STORAGE.tx_buffer[i].state = COMMIT_SENT;
LINK_STORAGE.tx_buffer[i].transmits_to_error = LINK_STORAGE.tx_max_retries;
LINK_STORAGE.tx_buffer[i].expiration_time = LINK_STORAGE.timer_counter + 2;
D_LINK printf ("S: COMMIT to ED\n");
send_commit (false, true, LINK_STORAGE.tx_buffer[i].address.ed);
break;
}
else {
// it is BUSY ACK packet, set retransmission count again and set
// longer timeout (receiving device is busy)
LINK_STORAGE.tx_buffer[i].transmits_to_error = LINK_STORAGE.tx_max_retries;
LINK_STORAGE.tx_buffer[i].expiration_time = LINK_STORAGE.timer_counter + 3;
return false;
}
}
}
}
}
else {
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
// if some DATA message for COORD is in buffer and address is the same,
// COMMIT packet can be sent
if (!LINK_STORAGE.tx_buffer[i].empty) {
if (LINK_STORAGE.tx_buffer[i].address_type == 0
&& LINK_STORAGE.tx_buffer[i].address.coord == data[6]) {
// it is not BUSY ACK packet, switch state and send COMMIT packet
if(transfer_type != LINK_BUSY) {
LINK_STORAGE.tx_buffer[i].state = COMMIT_SENT;;
LINK_STORAGE.tx_buffer[i].transmits_to_error = LINK_STORAGE.tx_max_retries;
LINK_STORAGE.tx_buffer[i].expiration_time = LINK_STORAGE.timer_counter + 2;
if(data[0] & LINK_COORD_TO_ED) {
D_LINK printf ("R: ACK to ED\n");
D_LINK printf ("S: COMMIT to COORD\n");
send_commit (true, false,
&LINK_STORAGE.tx_buffer[i].address.coord);
break;
}
else {
D_LINK printf ("R: ACK to COORD\n");
D_LINK printf ("S: COMMIT to COORD\n");
send_commit (false, false,
&LINK_STORAGE.tx_buffer[i].address.coord);
break;
}
}
else {
// it is BUSY ACK packet, set retransmission count again and set
// longer timeout (receiving device is busy)
LINK_STORAGE.tx_buffer[i].transmits_to_error = LINK_STORAGE.tx_max_retries;
LINK_STORAGE.tx_buffer[i].expiration_time = LINK_STORAGE.timer_counter + 3;
return false;
}
}
}
}
}
}
// processing of COMMIT ACK packet
else if (packet_type == LINK_COMMIT_ACK_TYPE) {
D_LINK printf ("COMMIT ACK\n");
if (data[0] & LINK_ED_TO_COORD) {
D_LINK printf ("R: COMMIT ACK to COORD\n");
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
if (!LINK_STORAGE.tx_buffer[i].empty) {
if (LINK_STORAGE.tx_buffer[i].address_type == 1
&& array_cmp (LINK_STORAGE.tx_buffer[i].address.ed, data + 6)) {
// packet can be accepted
LINK_STORAGE.tx_buffer[i].empty = 1;
break;
}
}
}
}
else {
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
if (!LINK_STORAGE.tx_buffer[i].empty) {
if (LINK_STORAGE.tx_buffer[i].address_type == 0
&& LINK_STORAGE.tx_buffer[i].address.coord == data[6]) {
// packet can be accepted
LINK_STORAGE.tx_buffer[i].empty = 1;
D_LINK printf ("R: COMMIT ACK to ED or COORD\n");
LINK_notify_send_done();
break;
}
}
}
}
}
// processing of DATA packet
else if (packet_type == LINK_DATA_TYPE) {
D_LINK printf ("DATA\n");
if (transfer_type == LINK_DATA_WITHOUT_ACK) {
return LINK_route (data + LINK_HEADER_SIZE, len - LINK_HEADER_SIZE, transfer_type);
}
else if (transfer_type == LINK_DATA_HS4) {
for(uint8_t i = 0; i < LINK_RX_BUFFER_SIZE; i++) {
// some DATA are in RX buffer, verify if received packet has not been
// already stored in RX buffer
if(!LINK_STORAGE.rx_buffer[i].empty) {
if (LINK_STORAGE.rx_buffer[i].address_type == 1) {
if (array_cmp (LINK_STORAGE.tx_buffer[i].address.ed, data + 6)) {
D_LINK printf("ED -> COORD: DATA has been already stored!\n");
send_ack (false, LINK_STORAGE.rx_buffer[i].address_type, data + 6, LINK_STORAGE.rx_buffer[i].transfer_type);
return false;
}
}
else {
if ((LINK_STORAGE.rx_buffer[i].address.coord == data[6])) {
if (data[0] & LINK_COORD_TO_ED) {
D_LINK printf("COORD -> ED: DATA has been already stored!\n");
send_ack (true, LINK_STORAGE.rx_buffer[i].address_type, data + 6, LINK_STORAGE.rx_buffer[i].transfer_type);
return false;
}
else {
D_LINK printf("COORD -> COORD: DATA has been already stored!\n");
send_ack (false, LINK_STORAGE.rx_buffer[i].address_type, data + 6, LINK_STORAGE.rx_buffer[i].transfer_type);
return false;
}
}
}
}
}
uint8_t sender_address_type = (data[0] & LINK_ED_TO_COORD) ? 1 : 0;
uint8_t empty_index = get_free_index_rx ();
if (empty_index < LINK_RX_BUFFER_SIZE) {
// RX buffer is not full, save information about DATA packet
uint8_t data_index = 0;
for (; data_index < len && data_index < MAX_PHY_PAYLOAD_SIZE; data_index++) {
LINK_STORAGE.rx_buffer[empty_index].data[data_index] = data[data_index];
}
LINK_STORAGE.rx_buffer[empty_index].len = data_index;
LINK_STORAGE.rx_buffer[empty_index].transfer_type = transfer_type;
LINK_STORAGE.rx_buffer[empty_index].empty = 0;
LINK_STORAGE.rx_buffer[empty_index].address_type = sender_address_type;
if (sender_address_type) {
for (uint8_t i = 0; i < EDID_LENGTH; i++)
LINK_STORAGE.rx_buffer[empty_index].address.ed[i] = data[6 + i];
} else {
LINK_STORAGE.rx_buffer[empty_index].address.coord = LINK_cid_mask (data[6]);
}
}
else {
// RX buffer is full, send BUSY ACK packet
send_busy_ack (false, sender_address_type, data + 6);
return true;
}
if (sender_address_type) {
D_LINK printf("R: DATA to COORD\n");
for (uint8_t i = 0; i < LINK_RX_BUFFER_SIZE; i++) {
// if some DATA message for COORD from ED is in RX buffer
// and address is the same, ACK packet can be sent
if (!LINK_STORAGE.rx_buffer[i].empty) {
if (LINK_STORAGE.rx_buffer[i].address_type == 1
&& array_cmp (LINK_STORAGE.rx_buffer[i].address.ed, data + 6)) {
D_LINK printf("S: ACK to ED\n");
send_ack (false, sender_address_type, data + 6, LINK_STORAGE.rx_buffer[i].transfer_type);
}
}
}
}
else {
for (uint8_t i = 0; i < LINK_RX_BUFFER_SIZE; i++) {
// if some DATA message for ED or COORD from COORD is in RX buffer
// and address is the same, ACK packet can be sent
if (!LINK_STORAGE.rx_buffer[i].empty) {
if (LINK_STORAGE.rx_buffer[i].address_type == 0
&& LINK_STORAGE.rx_buffer[i].address.coord == data[6]) {
if (data[0] & LINK_COORD_TO_ED) {
D_LINK printf("R: DATA to ED\n");
D_LINK printf("S: ACK to COORD\n");
send_ack (true, sender_address_type, data + 6, LINK_STORAGE.rx_buffer[i].transfer_type);
}
else {
D_LINK printf("R: DATA to COORD\n");
D_LINK printf("S: ACK to COORD\n");
send_ack (false, sender_address_type, data + 6, LINK_STORAGE.rx_buffer[i].transfer_type);
}
}
}
}
}
}
}
// processing of COMMIT packet
else if (packet_type == LINK_COMMIT_TYPE) {
D_LINK printf ("COMMIT\n");
if (data[0] & LINK_ED_TO_COORD) {
D_LINK printf ("R: COMMIT to COORD\n");
uint8_t i = 0;
for (; i < LINK_RX_BUFFER_SIZE; i++) {
// if some DATA message for COORD from ED is in RX buffer
// and address is the same, COMMIT ACK packet can be sent
if (!LINK_STORAGE.rx_buffer[i].empty) {
if (LINK_STORAGE.rx_buffer[i].address_type == 1
&& array_cmp (LINK_STORAGE.rx_buffer[i].address.ed, data + 6)) {
D_LINK printf("S: COMMIT ACK to ED\n");
send_commit_ack (false, data[0] & LINK_ED_TO_COORD, data + 6);
bool result = LINK_route (LINK_STORAGE.rx_buffer[i].data + LINK_HEADER_SIZE,
LINK_STORAGE.rx_buffer[i].len - LINK_HEADER_SIZE, LINK_STORAGE.rx_buffer[i].transfer_type);
LINK_STORAGE.rx_buffer[i].empty = 1;
return result;
}
}
}
// in case of multiple receiving of COMMIT packet send COMMIT ACK
// packet (COMMIT packet was not received by sender)
send_commit_ack (false, data[0] & LINK_ED_TO_COORD, data + 6);
}
else {
uint8_t i = 0;
for (; i < LINK_RX_BUFFER_SIZE; i++) {
if (!LINK_STORAGE.rx_buffer[i].empty) {
// if some DATA message for ED or COORD from COORD is in RX buffer
// and address is the same, COMMIT ACK packet can be sent
if (LINK_STORAGE.rx_buffer[i].address_type == 0
&& LINK_STORAGE.rx_buffer[i].address.coord == LINK_cid_mask (data[6])) {
if(data[0] & LINK_COORD_TO_ED) {
D_LINK printf ("R: COMMIT to ED\n");
D_LINK printf ("S: COMMIT ACK to COORD\n");
send_commit_ack (true, data[0] & LINK_ED_TO_COORD, data + 6);
}
else {
D_LINK printf ("R: COMMIT to COORD\n");
D_LINK printf ("S: COMMIT ACK to COORD\n");
send_commit_ack (false, data[0] & LINK_ED_TO_COORD, data + 6);
}
bool result = LINK_route (LINK_STORAGE.rx_buffer[i].data + LINK_HEADER_SIZE,
LINK_STORAGE.rx_buffer[i].len - LINK_HEADER_SIZE, LINK_STORAGE.rx_buffer[i].transfer_type);
LINK_STORAGE.rx_buffer[i].empty = 1;
return result;
}
}
}
// in case of multiple receiving of COMMIT packet send COMMIT ACK
// packet (COMMIT packet was not received by sender)
if(data[0] & LINK_COORD_TO_ED) {
send_commit_ack (true, data[0] & LINK_ED_TO_COORD, data + 6);
}
else {
send_commit_ack (false, data[0] & LINK_ED_TO_COORD, data + 6);
}
}
}
return true;
}
/*
* Checks TX and RX buffers periodically.
* Ensures packet retransmission during four-way handshake and detects
* unsuccessful four-way handshake.
*/
void check_buffers_state ()
{
// check the COORD buffers
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
if ((!LINK_STORAGE.tx_buffer[i].empty)
&& LINK_STORAGE.tx_buffer[i].expiration_time == LINK_STORAGE.timer_counter) {
if ((LINK_STORAGE.tx_buffer[i].transmits_to_error--) == 0) {
// multiple unsuccessful packet sending, network reinitialization starts
if (LINK_STORAGE.tx_buffer[i].address_type) {
LINK_error_handler_coord ();
// delete all messages for unavailable ED
for (uint8_t j = 0; j < LINK_TX_BUFFER_SIZE; j++) {
if(!LINK_STORAGE.tx_buffer[j].empty && array_cmp(LINK_STORAGE.tx_buffer[i].address.ed, LINK_STORAGE.tx_buffer[j].address.ed)){
LINK_STORAGE.tx_buffer[j].empty = 1;
}
}
}
else {
LINK_error_handler_coord ();
// delete all messages for unavailable COORD
for (uint8_t j = 0; j < LINK_TX_BUFFER_SIZE; j++) {
if(!LINK_STORAGE.tx_buffer[j].empty && LINK_STORAGE.tx_buffer[i].address.coord == LINK_STORAGE.tx_buffer[j].address.coord){
LINK_STORAGE.tx_buffer[j].empty = 1;
}
}
}
}
else {
// try to resend packet
if (LINK_STORAGE.tx_buffer[i].state) {
D_LINK printf("COMMIT again!\n");
if (LINK_STORAGE.tx_buffer[i].address_type) {
send_commit (false, true, LINK_STORAGE.tx_buffer[i].address.ed);
}
else {
send_commit (false, false,
&LINK_STORAGE.tx_buffer[i].address.coord);
}
}
else {
D_LINK printf("DATA again!\n");
if (LINK_STORAGE.tx_buffer[i].address_type) {
send_data (false, true, LINK_STORAGE.tx_buffer[i].address.ed,
LINK_STORAGE.tx_buffer[i].data, LINK_STORAGE.tx_buffer[i].len, LINK_STORAGE.tx_buffer[i].transfer_type);
}
else {
send_data (false, false, &LINK_STORAGE.tx_buffer[i].address.coord,
LINK_STORAGE.tx_buffer[i].data, LINK_STORAGE.tx_buffer[i].len, LINK_STORAGE.tx_buffer[i].transfer_type);
}
}
LINK_STORAGE.tx_buffer[i].expiration_time = LINK_STORAGE.timer_counter + 2;
}
}
}
}
/**
* Processes received packet.
* @param data Data.
* @param len Data length.
*/
void PHY_process_packet (uint8_t* data, uint8_t len)
{
/*printf("RAW: ");
for(uint8_t i = 0; i < len; i++)
printf("%02x ",data[i]);
printf("\n");*/
D_LINK printf ("PHY_process_packet()!\n");
// packet is too short
if (len < LINK_HEADER_SIZE)
return;
uint8_t packet_type = data[0] >> 6;
uint8_t transfer_type = data[0] & 0x0f;
// JOIN packet processing before NID check
if (transfer_type == LINK_DATA_JOIN_REQUEST && packet_type == LINK_DATA_TYPE) {
D_LINK printf("JOIN REQUEST received\n");
// JOIN REQUEST message, send ACK JOIN REQUEST message
if(!NET_is_set_pair_mode()) {
D_LINK printf("Not in a PAIR MODE!\n");
return;
}
LINK_save_msg_info(data + 10, len - 10);
uint8_t ack_packet[LINK_HEADER_SIZE];
gen_header (ack_packet, false, true, data + 6, LINK_ACK_TYPE,
LINK_ACK_JOIN_REQUEST);
D_LINK printf("ACK JOIN REQUEST\n");
PHY_send_with_cca (ack_packet, LINK_HEADER_SIZE);
// send JOIN REQUEST ROUTE message with RSSI
uint8_t RSSI = PHY_get_measured_noise();
LINK_join_request_received (RSSI, data + LINK_HEADER_SIZE, len - LINK_HEADER_SIZE);
return;
}
// packet is not in my network
if (!array_cmp (data + 1, GLOBAL_STORAGE.nid))
return;
LINK_save_msg_info(data + 10, len - 10);
if (transfer_type == LINK_DATA_BROADCAST) {
D_LINK printf("BROADCAST received\n");
LINK_route (data + LINK_HEADER_SIZE, len - LINK_HEADER_SIZE, LINK_DATA_BROADCAST);
return;
}
// packets to PAN are sent only as to COORD, not to ED
if (data[0] & LINK_COORD_TO_ED)
return;
// packet for another COORD
if (LINK_cid_mask (data[5]) != GLOBAL_STORAGE.cid)
return;
// if routing is disabled and four-way handshake is not finished
// do not process next packets
if (!GLOBAL_STORAGE.routing_enabled && ((transfer_type == LINK_DATA_HS4) && packet_type != LINK_COMMIT_ACK_TYPE)) {
D_LINK printf ("Routing disabled\n");
return;
}
// packet is from COORD
if (!(data[0] & LINK_ED_TO_COORD)) {
uint8_t sender_cid = LINK_cid_mask (data[6]);
// packet has to be from my child
if (GLOBAL_STORAGE.routing_tree[sender_cid] != GLOBAL_STORAGE.cid) {
D_LINK printf ("Not my child!\n");
return;
}
}
// packet processing and routing
router_process_packet (data, len);
}
/**
* Checks buffers, increments counter periodically and
* alternatively sends JOIN RESPONSE (ROUTE) and MOVE RESPONSE (ROUTE) messages.
*/
void PHY_timer_interrupt ()
{
LINK_STORAGE.timer_counter++;
LINK_timer_counter();
/*if(GLOBAL_STORAGE.pair_mode)
NET_joining();
NET_moving();*/
check_buffers_state ();
}
/**
* Gets address of coordinator (CID).
* @param byte Byte containing coordinator ID.
* @return Returns coordinator ID (6 bits).
*/
uint8_t LINK_cid_mask (uint8_t address)
{
return address & 0x3f;
}
/**
* Initializes link layer and ensures initialization of physical layer.
* @param phy_params Parameters of physical layer.
* @param link_params Parameters of link layer.
*/
void LINK_init (struct PHY_init_t* phy_params, struct LINK_init_t* link_params)
{
D_LINK printf("LINK_init\n");
PHY_init(phy_params);
LINK_STORAGE.tx_max_retries = link_params->tx_max_retries;
for (uint8_t i = 0; i < LINK_RX_BUFFER_SIZE; i++) {
LINK_STORAGE.rx_buffer[i].empty = 1;
}
for (uint8_t i = 0; i < LINK_TX_BUFFER_SIZE; i++) {
LINK_STORAGE.tx_buffer[i].empty = 1;
}
LINK_STORAGE.timer_counter = 0;
}
void LINK_send_join_response (uint8_t* edid, uint8_t* payload, uint8_t len)
{
// JOIN RESPONSE length is 25 bytes
uint8_t packet[25];
uint8_t packet_index = LINK_HEADER_SIZE;
gen_header (packet, false, true, edid, LINK_DATA_TYPE, LINK_DATA_JOIN_RESPONSE);
for (uint8_t i = 0; i < len && packet_index < MAX_PHY_PAYLOAD_SIZE; i++) {
packet[packet_index++] = payload[i];
}
PHY_send_with_cca (packet, packet_index);
}
/**
* Broadcasts packet.
* @param payload Payload.
* @param len Payload length.
*/
bool LINK_send_broadcast (uint8_t * payload, uint8_t len)
{
uint8_t packet[MAX_PHY_PAYLOAD_SIZE];
uint8_t packet_index = LINK_HEADER_SIZE;
// size of link header
uint8_t address_next_coord = LINK_COORD_ALL;
gen_header (packet, true, false, &address_next_coord, LINK_DATA_TYPE,
LINK_DATA_BROADCAST);
for (uint8_t index = 0; index < len; index++) {
packet[packet_index++] = payload[index];
}
PHY_send_with_cca (packet, packet_index);
return true;
}
/**
* Sends packet.
* @param to_ed True if destination device is ED, false otherwise.
* @param address Destination address.
* @param payload Payload.
* @param len Payload length.
* @param transfer_type Transfer type on link layer.
* @return Returns false if no space is in TX buffer, true otherwise.
*/
bool LINK_send_coord (bool to_ed, uint8_t * address, uint8_t * payload,
uint8_t len, uint8_t transfer_type)
{
D_LINK printf("LINK_send_coord()\n");
if(transfer_type == LINK_DATA_HS4) {
// send data using four-way handshake
uint8_t free_index = get_free_index_tx ();
if (free_index >= LINK_TX_BUFFER_SIZE)
return false;
for (uint8_t i = 0; i < len; i++)
LINK_STORAGE.tx_buffer[free_index].data[i] = payload[i];
LINK_STORAGE.tx_buffer[free_index].len = len;
if (to_ed) {
for (uint8_t i = 0; i < EDID_LENGTH; i++)
LINK_STORAGE.tx_buffer[free_index].address.ed[i] = address[i];
}
else {
LINK_STORAGE.tx_buffer[free_index].address.coord = *address;
}
// 0 - packet is for ED, 1- packet is for COORD
LINK_STORAGE.tx_buffer[free_index].address_type = to_ed ? 1 : 0;
LINK_STORAGE.tx_buffer[free_index].state = DATA_SENT;
LINK_STORAGE.tx_buffer[free_index].transmits_to_error = LINK_STORAGE.tx_max_retries;
LINK_STORAGE.tx_buffer[free_index].expiration_time = LINK_STORAGE.timer_counter + 2;
LINK_STORAGE.tx_buffer[free_index].transfer_type = transfer_type;
LINK_STORAGE.tx_buffer[free_index].empty = 0;
if (LINK_STORAGE.tx_buffer[free_index].address_type)
send_data (false, true, LINK_STORAGE.tx_buffer[free_index].address.ed,
LINK_STORAGE.tx_buffer[free_index].data,
LINK_STORAGE.tx_buffer[free_index].len, transfer_type);
else
send_data (false, false, &LINK_STORAGE.tx_buffer[free_index].address.coord,
LINK_STORAGE.tx_buffer[free_index].data,
LINK_STORAGE.tx_buffer[free_index].len, transfer_type);
}
else if (transfer_type == LINK_DATA_WITHOUT_ACK) {
// send data without waiting for ACK message
uint8_t packet[MAX_PHY_PAYLOAD_SIZE];
//size of link header
uint8_t packet_index = LINK_HEADER_SIZE;
if(to_ed)
gen_header (packet, false, true, address, LINK_DATA_TYPE, LINK_DATA_WITHOUT_ACK);
else
gen_header (packet, false, false, address, LINK_DATA_TYPE, LINK_DATA_WITHOUT_ACK);
for (uint8_t index = 0; index < len; index++) {
packet[packet_index++] = payload[index];
}
PHY_send_with_cca (packet, packet_index);
}
else if (transfer_type == LINK_DATA_BROADCAST) {
// send broadcast message
D_LINK printf("BROADCAST sent!\n");
LINK_send_broadcast(payload, len);
}
return true;
}
/**
* Gets RSSI value.
* @return Returns RSSI value.
*/
uint8_t LINK_get_measured_noise()
{
return PHY_get_measured_noise();
}
void LINK_stop()
{
PHY_stop();
}
| 34.007991
| 132
| 0.669934
|
BeeeOn
|
677683951ea683a30b3a06aa27a6d6031be6b75e
| 77,473
|
cpp
|
C++
|
source/game/gamesys/SysCvar.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | 2
|
2021-05-02T18:37:48.000Z
|
2021-07-18T16:18:14.000Z
|
source/game/gamesys/SysCvar.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | null | null | null |
source/game/gamesys/SysCvar.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "../../framework/BuildVersion.h"
#include "../../framework/BuildDefines.h"
#include "../../framework/Licensee.h"
#include "../rules/GameRules.h"
#if defined( _DEBUG )
#define BUILD_DEBUG "(debug)"
#else
#define BUILD_DEBUG ""
#endif
/*
All game cvars should be defined here.
*/
struct gameVersion_t {
static const int strSize = 256;
gameVersion_t( void ) {
idStr::snPrintf( string, strSize, "%s %d.%d.%d.%d %s %s %s %s", GAME_NAME, ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR, ENGINE_SRC_REVISION, ENGINE_MEDIA_REVISION, BUILD_DEBUG, BUILD_STRING, __DATE__, __TIME__ );
string[ strSize - 1 ] = '\0';
}
char string[strSize];
} gameVersion;
#define MOD_NAME "QWTA"
#define MOD_VERSION_MAJOR 0
#define MOD_VERSION_MINOR 3
#define MOD_VERSION_REVISION 5
struct modVersion_t {
static const int strSize = 256;
modVersion_t( void ) {
idStr::snPrintf( string, strSize, "%s %d.%d.%d", MOD_NAME, MOD_VERSION_MAJOR, MOD_VERSION_MINOR, MOD_VERSION_REVISION );
}
char string[strSize];
} modVersion;
idCVar g_version( "g_version", gameVersion.string, CVAR_GAME | CVAR_ROM, "game version" );
idCVar g_modVersion( "g_modVersion", modVersion.string, CVAR_GAME | CVAR_ROM, "mod version" );
// noset vars
idCVar gamename( "gamename", GAME_VERSION, CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "" );
idCVar gamedate( "gamedate", __DATE__, CVAR_GAME | CVAR_ROM, "" );
// server info
idCVar si_name( "si_name", GAME_NAME " Server", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "name of the server" );
idCVar si_maxPlayers( "si_maxPlayers", "24", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "max number of players allowed on the server", 1, static_cast< float >( MAX_CLIENTS ) );
idCVar si_privateClients( "si_privateClients", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER, "max number of private players allowed on the server", 0, static_cast< float >( MAX_CLIENTS ) );
idCVar si_teamDamage( "si_teamDamage", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "enable team damage" );
idCVar si_needPass( "si_needPass", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "enable client password checking" );
idCVar si_pure( "si_pure", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "server is pure and does not allow modified data" );
idCVar si_spectators( "si_spectators", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "allow spectators or require all clients to play" );
idCVar si_rules( "si_rules", "sdGameRulesCampaign", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_RANKLOCKED, "ruleset for game", sdGameRules::ArgCompletion_RuleTypes );
idCVar si_timeLimit( "si_timelimit", "20", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_RANKLOCKED, "time limit (mins)" );
idCVar si_map( "si_map", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "current active map" );
idCVar si_campaign( "si_campaign", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "current active campaign" );
idCVar si_campaignInfo( "si_campaignInfo", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "current campaign map info" );
idCVar si_tactical( "si_tactical", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "current active tactical" );
idCVar si_tacticalInfo( "si_tacticalInfo", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "current tactical map info" );
idCVar si_teamForceBalance( "si_teamForceBalance", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "Stop players from unbalancing teams" );
idCVar si_website( "si_website", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "website info" );
idCVar si_adminname( "si_adminname", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "admin name(s)" );
idCVar si_email( "si_email", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "contact email address" );
idCVar si_irc( "si_irc", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "IRC channel" );
idCVar si_motd_1( "si_motd_1", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "motd line 1" );
idCVar si_motd_2( "si_motd_2", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "motd line 2" );
idCVar si_motd_3( "si_motd_3", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "motd line 3" );
idCVar si_motd_4( "si_motd_4", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "motd line 4" );
idCVar si_adminStart( "si_adminStart", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_RANKLOCKED, "admin required to start the match" );
idCVar si_disableVoting( "si_disableVoting", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "disable/enable all voting" );
idCVar si_readyPercent( "si_readyPercent", "51", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "percentage of players that need to ready up to start a match" );
idCVar si_minPlayers( "si_minPlayers", "6", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "minimum players before a game can be started" );
idCVar si_allowLateJoin( "si_allowLateJoin", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "Enable/disable players joining a match in progress" );
idCVar si_noProficiency( "si_noProficiency", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "enable/disable XP" );
idCVar si_disableGlobalChat( "si_disableGlobalChat", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "disable global text communication" );
idCVar si_gameReviewReadyWait( "si_gameReviewReadyWait", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "wait for players to ready up before going to the next map" );
idCVar si_serverURL( "si_serverURL", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "server information page" );
idCVar* si_motd_cvars[] = {
&si_motd_1, &si_motd_2, &si_motd_3, &si_motd_4,
};
// user info
idCVar ui_name( "ui_name", "Player", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE, "player name" );
idCVar ui_clanTag( "ui_clanTag", "", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE, "player clan tag" );
idCVar ui_clanTagPosition( "ui_clanTagPosition", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_INTEGER, "positioning of player clan tag. 0 is before their name, 1 is after" );
idCVar ui_showGun( "ui_showGun", "1", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "show gun" );
idCVar ui_autoSwitchEmptyWeapons( "ui_autoSwitchEmptyWeapons", "1", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, will switch to the next usable weapon when the current weapon runs out of ammo" );
idCVar ui_ignoreExplosiveWeapons( "ui_ignoreExplosiveWeapons", "1", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, weapons marked as explosive will be ignored during auto-switches" );
idCVar ui_postArmFindBestWeapon( "ui_postArmFindBestWeapon", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, after arming players' best weapon will be selected" );
idCVar ui_advancedFlightControls( "ui_advancedFlightControls", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, advanced flight controls are activated" );
idCVar ui_rememberCameraMode( "ui_rememberCameraMode", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "use same camera mode as was previously used when re-entering a vehicle" );
idCVar ui_drivingCameraFreelook( "ui_drivingCameraFreelook", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, driving cameras where there is no weapon defaults to freelook" );
idCVar ui_voipReceiveGlobal( "ui_voipReceiveGlobal", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, receive voice chat sent to the global channel" );
idCVar ui_voipReceiveTeam( "ui_voipReceiveTeam", "1", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, receive voice chat sent to the team channel" );
idCVar ui_voipReceiveFireTeam( "ui_voipReceiveFireTeam", "1", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, receive voice chat sent to the fireteam channel" );
idCVar ui_showComplaints( "ui_showComplaints", "1", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, receive complaints popups for team kills" );
idCVar ui_swapFlightYawAndRoll( "ui_swapFlightYawAndRoll", "0", CVAR_GAME | CVAR_PROFILE | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "if true, swaps the yaw & roll controls for flying vehicles - mouse becomes yaw and keys become roll" );
// change anytime vars
idCVar g_decals( "g_decals", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_BOOL, "show decals such as bullet holes" );
idCVar g_knockback( "g_knockback", "1", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_gravity( "g_gravity", DEFAULT_GRAVITY_STRING, CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_disasm( "g_disasm", "0", CVAR_GAME | CVAR_BOOL, "disassemble script into base/script/disasm.txt on the local drive when script is compiled" );
idCVar g_debugBounds( "g_debugBounds", "0", CVAR_GAME | CVAR_BOOL, "checks for models with bounds > 2048" );
idCVar g_debugAnim( "g_debugAnim", "-1", CVAR_GAME | CVAR_INTEGER, "displays information on which animations are playing on the specified entity number. set to -1 to disable." );
idCVar g_debugAnimStance( "g_debugAnimStance", "-1", CVAR_GAME | CVAR_INTEGER, "displays information on which stances are set on the specified entity number. set to -1 to disable." );
idCVar g_debugDamage( "g_debugDamage", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_debugWeapon( "g_debugWeapon", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_debugWeaponSpread( "g_debugWeaponSpread", "0", CVAR_GAME | CVAR_BOOL, "displays the current spread value for the weapon" );
idCVar g_debugScript( "g_debugScript", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_debugCinematic( "g_debugCinematic", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_debugPlayerList( "g_debugPlayerList", "0", CVAR_GAME | CVAR_INTEGER, "fills UI lists with fake players" );
idCVar g_showPVS( "g_showPVS", "0", CVAR_GAME | CVAR_INTEGER, "", 0, 2 );
idCVar g_showTargets( "g_showTargets", "0", CVAR_GAME | CVAR_BOOL, "draws entities and their targets. hidden entities are drawn grey." );
idCVar g_showTriggers( "g_showTriggers", "0", CVAR_GAME | CVAR_BOOL, "draws trigger entities (orange) and their targets (green). disabled triggers are drawn grey." );
idCVar g_showCollisionWorld( "g_showCollisionWorld", "0", CVAR_GAME | CVAR_INTEGER, "" );
idCVar g_showVehiclePathNodes( "g_showVehiclePathNodes", "0", CVAR_GAME | CVAR_INTEGER, "" );
idCVar g_showCollisionModels( "g_showCollisionModels", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_showRenderModelBounds( "g_showRenderModelBounds", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_collisionModelMask( "g_collisionModelMask", "-1", CVAR_GAME | CVAR_INTEGER, "" );
idCVar g_showCollisionTraces( "g_showCollisionTraces", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_showClipSectors( "g_showClipSectors", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_showClipSectorFilter( "g_showClipSectorFilter", "0", CVAR_GAME, "" );
idCVar g_showAreaClipSectors( "g_showAreaClipSectors", "0", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_maxShowDistance( "g_maxShowDistance", "128", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_showEntityInfo( "g_showEntityInfo", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_showcamerainfo( "g_showcamerainfo", "0", CVAR_GAME, "displays the current frame # for the camera when playing cinematics" );
idCVar g_showTestModelFrame( "g_showTestModelFrame", "0", CVAR_GAME | CVAR_BOOL, "displays the current animation and frame # for testmodels" );
idCVar g_showActiveEntities( "g_showActiveEntities", "0", CVAR_GAME | CVAR_BOOL, "draws boxes around thinking entities. " );
idCVar g_debugMask( "g_debugMask", "", CVAR_GAME, "debugs a deployment mask" );
idCVar g_debugLocations( "g_debugLocations", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_showActiveDeployZones( "g_showActiveDeployZones", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_disableVehicleSpawns( "g_disableVehicleSpawns", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT | CVAR_RANKLOCKED, "disables vehicles spawning from construction pads" );
idCVar g_frametime( "g_frametime", "0", CVAR_GAME | CVAR_BOOL, "displays timing information for each game frame" );
//idCVar g_timeentities( "g_timeEntities", "0", CVAR_GAME | CVAR_FLOAT, "when non-zero, shows entities whose think functions exceeded the # of milliseconds specified" );
//idCVar g_timetypeentities( "g_timeTypeEntities", "", CVAR_GAME, "" );
idCVar ai_debugScript( "ai_debugScript", "-1", CVAR_GAME | CVAR_INTEGER, "displays script calls for the specified monster entity number" );
idCVar ai_debugAnimState( "ai_debugAnimState", "-1", CVAR_GAME | CVAR_INTEGER, "displays animState changes for the specified monster entity number" );
idCVar ai_debugMove( "ai_debugMove", "0", CVAR_GAME | CVAR_BOOL, "draws movement information for monsters" );
idCVar ai_debugTrajectory( "ai_debugTrajectory", "0", CVAR_GAME | CVAR_BOOL, "draws trajectory tests for monsters" );
idCVar g_kickTime( "g_kickTime", "1", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_kickAmplitude( "g_kickAmplitude", "0.0001", CVAR_GAME | CVAR_FLOAT, "" );
//idCVar g_blobTime( "g_blobTime", "1", CVAR_GAME | CVAR_FLOAT, "" );
//idCVar g_blobSize( "g_blobSize", "1", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_editEntityMode( "g_editEntityMode", "0", CVAR_GAME | CVAR_INTEGER, "0 = off\n"
"1 = lights\n"
"2 = sounds\n"
"3 = articulated figures\n"
"4 = particle systems\n"
"5 = monsters\n"
"6 = entity names\n"
"7 = entity models", 0, 7, idCmdSystem::ArgCompletion_Integer<0,7> );
idCVar g_dragEntity( "g_dragEntity", "0", CVAR_GAME | CVAR_BOOL, "allows dragging physics objects around by placing the crosshair over them and holding the fire button" );
idCVar g_dragDamping( "g_dragDamping", "0.5", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_dragMaxforce( "g_dragMaxforce", "5000000", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_dragShowSelection( "g_dragShowSelection", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_vehicleVelocity( "g_vehicleVelocity", "1000", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_vehicleForce( "g_vehicleForce", "50000", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_vehicleSuspensionUp( "g_vehicleSuspensionUp", "32", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_vehicleSuspensionDown( "g_vehicleSuspensionDown", "20", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_vehicleSuspensionKCompress("g_vehicleSuspensionKCompress","200", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_vehicleSuspensionDamping( "g_vehicleSuspensionDamping","400", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_vehicleTireFriction( "g_vehicleTireFriction", "0.8", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_commandMapZoomStep( "g_commandMapZoomStep", "0.125", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "percent to increase/decrease command map zoom by" );
idCVar g_commandMapZoom( "g_commandMapZoom", "0.25", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "command map zoom level", 0.125f, 0.75f );
idCVar g_showPlayerSpeed( "g_showPlayerSpeed", "0", CVAR_GAME | CVAR_BOOL, "displays player movement speed" );
idCVar m_helicopterPitch( "m_helicopterPitch", "-0.022", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "helicopter mouse pitch scale" );
idCVar m_helicopterYaw( "m_helicopterYaw", "0.022", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "helicopter mouse yaw scale" );
idCVar m_helicopterPitchScale( "m_helicopterPitchScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Anansi/Tormentor pitch" );
idCVar m_helicopterYawScale( "m_helicopterYawScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Anansi/Tormentor yaw" );
idCVar m_bumblebeePitchScale( "m_bumblebeePitchScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Bumblebee pitch" );
idCVar m_bumblebeeYawScale( "m_bumblebeeYawScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Bumblebee yaw" );
idCVar m_lightVehiclePitchScale( "m_lightVehiclePitchScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Husky/Armadillo/Hog/Trojan pitch" );
idCVar m_lightVehicleYawScale( "m_lightVehicleYawScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Husky/Armadillo/Hog/Trojan yaw" );
idCVar m_heavyVehiclePitchScale( "m_heavyVehiclePitchScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Titan/Cyclops pitch" );
idCVar m_heavyVehicleYawScale( "m_heavyVehicleYawScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for Titan/Cyclops yaw" );
idCVar m_playerPitchScale( "m_playerPitchScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for player pitch" );
idCVar m_playerYawScale( "m_playerYawScale", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_NOCHEAT, "sensitivity scale (over base) for player yaw" );
idCVar ik_enable( "ik_enable", "1", CVAR_GAME | CVAR_BOOL, "enable IK" );
idCVar ik_debug( "ik_debug", "0", CVAR_GAME | CVAR_BOOL, "show IK debug lines" );
idCVar af_useLinearTime( "af_useLinearTime", "1", CVAR_GAME | CVAR_BOOL, "use linear time algorithm for tree-like structures" );
idCVar af_useImpulseFriction( "af_useImpulseFriction", "0", CVAR_GAME | CVAR_BOOL, "use impulse based contact friction" );
idCVar af_useJointImpulseFriction( "af_useJointImpulseFriction","0", CVAR_GAME | CVAR_BOOL, "use impulse based joint friction" );
idCVar af_useSymmetry( "af_useSymmetry", "1", CVAR_GAME | CVAR_BOOL, "use constraint matrix symmetry" );
idCVar af_skipSelfCollision( "af_skipSelfCollision", "0", CVAR_GAME | CVAR_BOOL, "skip self collision detection" );
idCVar af_skipLimits( "af_skipLimits", "0", CVAR_GAME | CVAR_BOOL, "skip joint limits" );
idCVar af_skipFriction( "af_skipFriction", "0", CVAR_GAME | CVAR_BOOL, "skip friction" );
idCVar af_forceFriction( "af_forceFriction", "-1", CVAR_GAME | CVAR_FLOAT, "force the given friction value" );
idCVar af_maxLinearVelocity( "af_maxLinearVelocity", "128", CVAR_GAME | CVAR_FLOAT, "maximum linear velocity" );
idCVar af_maxAngularVelocity( "af_maxAngularVelocity", "1.57", CVAR_GAME | CVAR_FLOAT, "maximum angular velocity" );
idCVar af_timeScale( "af_timeScale", "1", CVAR_GAME | CVAR_FLOAT, "scales the time" );
idCVar af_jointFrictionScale( "af_jointFrictionScale", "0", CVAR_GAME | CVAR_FLOAT, "scales the joint friction" );
idCVar af_contactFrictionScale( "af_contactFrictionScale", "0", CVAR_GAME | CVAR_FLOAT, "scales the contact friction" );
idCVar af_highlightBody( "af_highlightBody", "", CVAR_GAME, "name of the body to highlight" );
idCVar af_highlightConstraint( "af_highlightConstraint", "", CVAR_GAME, "name of the constraint to highlight" );
idCVar af_showTimings( "af_showTimings", "0", CVAR_GAME | CVAR_BOOL, "show articulated figure cpu usage" );
idCVar af_showConstraints( "af_showConstraints", "0", CVAR_GAME | CVAR_BOOL, "show constraints" );
idCVar af_showConstraintNames( "af_showConstraintNames", "0", CVAR_GAME | CVAR_BOOL, "show constraint names" );
idCVar af_showConstrainedBodies( "af_showConstrainedBodies", "0", CVAR_GAME | CVAR_BOOL, "show the two bodies contrained by the highlighted constraint" );
idCVar af_showPrimaryOnly( "af_showPrimaryOnly", "0", CVAR_GAME | CVAR_BOOL, "show primary constraints only" );
idCVar af_showTrees( "af_showTrees", "0", CVAR_GAME | CVAR_BOOL, "show tree-like structures" );
idCVar af_showLimits( "af_showLimits", "0", CVAR_GAME | CVAR_BOOL, "show joint limits" );
idCVar af_showBodies( "af_showBodies", "0", CVAR_GAME | CVAR_BOOL, "show bodies" );
idCVar af_showBodyNames( "af_showBodyNames", "0", CVAR_GAME | CVAR_BOOL, "show body names" );
idCVar af_showMass( "af_showMass", "0", CVAR_GAME | CVAR_BOOL, "show the mass of each body" );
idCVar af_showTotalMass( "af_showTotalMass", "0", CVAR_GAME | CVAR_BOOL, "show the total mass of each articulated figure" );
idCVar af_showInertia( "af_showInertia", "0", CVAR_GAME | CVAR_BOOL, "show the inertia tensor of each body" );
idCVar af_showVelocity( "af_showVelocity", "0", CVAR_GAME | CVAR_BOOL, "show the velocity of each body" );
idCVar af_showActive( "af_showActive", "0", CVAR_GAME | CVAR_BOOL, "show tree-like structures of articulated figures not at rest" );
idCVar af_testSolid( "af_testSolid", "1", CVAR_GAME | CVAR_BOOL, "test for bodies initially stuck in solid" );
idCVar rb_showTimings( "rb_showTimings", "0", CVAR_GAME | CVAR_INTEGER, "show rigid body cpu usage" );
idCVar rb_showBodies( "rb_showBodies", "0", CVAR_GAME | CVAR_BOOL, "show rigid bodies" );
idCVar rb_showMass( "rb_showMass", "0", CVAR_GAME | CVAR_BOOL, "show the mass of each rigid body" );
idCVar rb_showInertia( "rb_showInertia", "0", CVAR_GAME | CVAR_BOOL, "show the inertia tensor of each rigid body" );
idCVar rb_showVelocity( "rb_showVelocity", "0", CVAR_GAME | CVAR_BOOL, "show the velocity of each rigid body" );
idCVar rb_showActive( "rb_showActive", "0", CVAR_GAME | CVAR_BOOL, "show rigid bodies that are not at rest" );
idCVar rb_showContacts( "rb_showContacts", "0", CVAR_GAME | CVAR_BOOL, "show contact points on rigid bodies" );
idCVar pm_friction( "pm_friction", "4", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "friction applied to player on the ground" );
idCVar pm_jumpheight( "pm_jumpheight", "68", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "approximate height the player can jump" );
idCVar pm_stepsize( "pm_stepsize", "16", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "maximum height the player can step up without jumping" );
idCVar pm_pronespeed( "pm_pronespeed", "60", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move while prone" );
idCVar pm_crouchspeed( "pm_crouchspeed", "80", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move while crouched" );
idCVar pm_walkspeed( "pm_walkspeed", "128", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move while walking" );
idCVar pm_runspeedforward( "pm_runspeedforward", "256", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move forwards while running" );
idCVar pm_runspeedback( "pm_runspeedback", "160", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move backwards while running" );
idCVar pm_runspeedstrafe( "pm_runspeedstrafe", "212", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move sideways while running" );
idCVar pm_sprintspeedforward( "pm_sprintspeedforward", "352", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move forwards while sprinting" );
idCVar pm_sprintspeedstrafe( "pm_sprintspeedstrafe", "176", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "speed the player can move sideways while sprinting" );
idCVar pm_noclipspeed( "pm_noclipspeed", "480", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while in noclip" );
idCVar pm_noclipspeedsprint( "pm_noclipspeedsprint", "960", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while in noclip and sprinting" );
idCVar pm_noclipspeedwalk( "pm_noclipspeedwalk", "256", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while in noclip and walking" );
idCVar pm_democamspeed( "pm_democamspeed", "200", CVAR_GAME | CVAR_FLOAT | CVAR_NOCHEAT, "speed the player can move while flying around in a demo" );
idCVar pm_spectatespeed( "pm_spectatespeed", "450", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while spectating" );
idCVar pm_spectatespeedsprint( "pm_spectatespeedsprint", "1024", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while spectating and sprinting" );
idCVar pm_spectatespeedwalk( "pm_spectatespeedwalk", "256", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while spectating and walking" );
idCVar pm_spectatebbox( "pm_spectatebbox", "16", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "size of the spectator bounding box" );
idCVar pm_minviewpitch( "pm_minviewpitch", "-89", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "amount player's view can look up (negative values are up)" );
idCVar pm_maxviewpitch( "pm_maxviewpitch", "88", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "amount player's view can look down" );
idCVar pm_minproneviewpitch( "pm_minproneviewpitch", "-45", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "amount player's view can look up when prone(negative values are up)" );
idCVar pm_maxproneviewpitch( "pm_maxproneviewpitch", "89", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "amount player's view can look down when prone" );
idCVar pm_proneheight( "pm_proneheight", "20", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's bounding box while prone" );
idCVar pm_proneviewheight( "pm_proneviewheight", "16", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's view while prone" );
idCVar pm_proneviewdistance( "pm_proneviewdistance", "10", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "distance in front of the player's view while prone" );
idCVar pm_crouchheight( "pm_crouchheight", "56", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's bounding box while crouched" );
idCVar pm_crouchviewheight( "pm_crouchviewheight", "48", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's view while crouched" );
idCVar pm_normalheight( "pm_normalheight", "79", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's bounding box while standing" );
idCVar pm_normalviewheight( "pm_normalviewheight", "72", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's view while standing" );
idCVar pm_deadheight( "pm_deadheight", "20", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's bounding box while dead" );
idCVar pm_deadviewheight( "pm_deadviewheight", "10", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "height of player's view while dead" );
idCVar pm_crouchrate( "pm_crouchrate", "180", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "time it takes for player's view to change from standing to crouching" );
idCVar pm_bboxwidth( "pm_bboxwidth", "32", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT | CVAR_RANKLOCKED, "x/y size of player's bounding box" );
idCVar pm_crouchbob( "pm_crouchbob", "0.23", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "bob much faster when crouched" );
idCVar pm_walkbob( "pm_walkbob", "0.3", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "bob slowly when walking" );
idCVar pm_runbob( "pm_runbob", "0.4", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "bob faster when running" );
idCVar pm_runpitch( "pm_runpitch", "0.002", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "" );
idCVar pm_runroll( "pm_runroll", "0.005", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "" );
idCVar pm_bobup( "pm_bobup", "0.005", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "" );
idCVar pm_bobpitch( "pm_bobpitch", "0.002", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "" );
idCVar pm_bobroll( "pm_bobroll", "0.002", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "" );
idCVar pm_skipBob( "pm_skipBob", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "Disable all bobbing" );
idCVar pm_thirdPersonRange( "pm_thirdPersonRange", "80", CVAR_GAME | CVAR_FLOAT, "camera distance from player in 3rd person" );
idCVar pm_thirdPersonHeight( "pm_thirdPersonHeight", "0", CVAR_GAME | CVAR_FLOAT, "height of camera from normal view height in 3rd person" );
idCVar pm_thirdPersonAngle( "pm_thirdPersonAngle", "0", CVAR_GAME | CVAR_FLOAT, "direction of camera from player in 3rd person in degrees (0 = behind player, 180 = in front)" );
idCVar pm_thirdPersonOrbit( "pm_thirdPersonOrbit", "0", CVAR_GAME | CVAR_FLOAT, "if set, will automatically increment pm_thirdPersonAngle every frame" );
idCVar pm_thirdPersonNoPitch( "pm_thirdPersonNoPitch", "0", CVAR_GAME | CVAR_BOOL, "ignore camera pitch when in third person mode" );
idCVar pm_thirdPersonClip( "pm_thirdPersonClip", "1", CVAR_GAME | CVAR_BOOL, "clip third person view into world space" );
idCVar pm_thirdPerson( "pm_thirdPerson", "0", CVAR_GAME | CVAR_BOOL, "enables third person view" );
idCVar pm_pausePhysics( "pm_pausePhysics", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL | CVAR_RANKLOCKED, "pauses physics" );
idCVar pm_deployThirdPersonRange( "pm_deployThirdPersonRange","200", CVAR_GAME | CVAR_FLOAT, "camera distance from player in 3rd person" );
idCVar pm_deployThirdPersonHeight( "pm_deployThirdPersonHeight","100", CVAR_GAME | CVAR_FLOAT, "height of camera from normal view height in 3rd person" );
idCVar pm_deployThirdPersonAngle( "pm_deployThirdPersonAngle","0", CVAR_GAME | CVAR_FLOAT, "direction of camera from player in 3rd person in degrees (0 = behind player, 180 = in front)" );
idCVar pm_deathThirdPersonRange( "pm_deathThirdPersonRange", "100", CVAR_GAME | CVAR_FLOAT, "camera distance from player in 3rd person" );
idCVar pm_deathThirdPersonHeight( "pm_deathThirdPersonHeight","20", CVAR_GAME | CVAR_FLOAT, "height of camera from normal view height in 3rd person" );
idCVar pm_deathThirdPersonAngle( "pm_deathThirdPersonAngle", "0", CVAR_GAME | CVAR_FLOAT, "direction of camera from player in 3rd person in degrees (0 = behind player, 180 = in front)" );
idCVar pm_slidevelocity( "pm_slidevelocity", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC | CVAR_RANKLOCKED, "what to do with velocity when hitting a surface at an angle. 0: use horizontal speed, 1: keep some of the impact speed to push along the slide" );
idCVar pm_powerslide( "pm_powerslide", "0.09", CVAR_GAME | CVAR_FLOAT | CVAR_NETWORKSYNC, "adjust the push when pm_slidevelocity == 1, set power < 1 -> more speed, > 1 -> closer to pm_slidevelocity 0", 0, 4 );
idCVar g_showPlayerArrows( "g_showPlayerArrows", "2", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC, "enable/disable arrows above the heads of players (0=off,1=all,2=friendly only)" );
idCVar g_showPlayerClassIcon( "g_showPlayerClassIcon", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "Force drawing of player class icon above players in the fireteam." );
idCVar g_showPlayerShadow( "g_showPlayerShadow", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_BOOL, "enables shadow of player model" );
idCVar g_showHud( "g_showHud", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "draw the hud gui" );
idCVar g_advancedHud( "g_advancedHud", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "Draw advanced HUD" );
idCVar g_skipPostProcess( "g_skipPostProcess", "0", CVAR_GAME | CVAR_BOOL, "draw the post process gui" );
idCVar g_gun_x( "g_gunX", "0", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_gun_y( "g_gunY", "0", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_gun_z( "g_gunZ", "0", CVAR_GAME | CVAR_FLOAT, "" );
idCVar g_fov( "g_fov", "90", CVAR_GAME | CVAR_INTEGER | CVAR_NOCHEAT, "", 1.0f, 179.0f );
idCVar g_skipViewEffects( "g_skipViewEffects", "0", CVAR_GAME | CVAR_BOOL, "skip damage and other view effects" );
idCVar g_forceClear( "g_forceClear", "1", CVAR_GAME | CVAR_BOOL, "forces clearing of color buffer on main game draw (faster)" );
idCVar g_testParticle( "g_testParticle", "0", CVAR_GAME | CVAR_INTEGER, "test particle visualization, set by the particle editor" );
idCVar g_testParticleName( "g_testParticleName", "", CVAR_GAME, "name of the particle being tested by the particle editor" );
idCVar g_testModelRotate( "g_testModelRotate", "0", CVAR_GAME, "test model rotation speed" );
idCVar g_testPostProcess( "g_testPostProcess", "", CVAR_GAME, "name of material to draw over screen" );
idCVar g_testViewSkin( "g_testViewSkin", "", CVAR_GAME, "name of skin to use for the view" );
idCVar g_testModelAnimate( "g_testModelAnimate", "0", CVAR_GAME | CVAR_INTEGER, "test model animation,\n"
"0 = cycle anim with origin reset\n"
"1 = cycle anim with fixed origin\n"
"2 = cycle anim with continuous origin\n"
"3 = frame by frame with continuous origin\n"
"4 = play anim once", 0, 4, idCmdSystem::ArgCompletion_Integer<0,4> );
idCVar g_disableGlobalAudio( "g_disableGlobalAudio", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "disable global VOIP communication" );
idCVar g_maxPlayerWarnings( "g_maxPlayerWarnings", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "maximum warnings before player is kicked" );
idCVar g_testModelBlend( "g_testModelBlend", "0", CVAR_GAME | CVAR_INTEGER, "number of frames to blend" );
idCVar g_exportMask( "g_exportMask", "", CVAR_GAME, "" );
idCVar password( "password", "", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_RANKLOCKED, "client password used when connecting" );
idCVar net_useAOR( "net_useAOR", "1", CVAR_GAME | CVAR_BOOL, "Enable/Disable Area of Relevance" );
idCVar net_aorPVSScale( "net_aorPVSScale", "4", CVAR_GAME | CVAR_FLOAT, "AoR scale for outside of PVS" );
idCVar pm_vehicleSoundLerpScale( "pm_vehicleSoundLerpScale", "10", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT, "" );
idCVar pm_waterSpeed( "pm_waterSpeed", "400", CVAR_GAME | CVAR_FLOAT | CVAR_RANKLOCKED, "speed player will be pushed up in water when totally under water" );
idCVar pm_realisticMovement( "pm_realisticMovement", "2", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_INTEGER, "Which player movement physics to use: 0=Quake-style, 1=Realistic-style 2=Realistic for players, Quake-style for bots" );
idCVar g_ignorePersistentRanks( "g_ignorePersistentRanks", "0", CVAR_GAME | CVAR_BOOL | CVAR_INIT, "Whether or not persistent ranks are ignored for use in game purposes. 0=Use persistent ranks, 1=Ignore persistent ranks" );
idCVar g_debugNetworkWrite( "g_debugNetworkWrite", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_debugProficiency( "g_debugProficiency", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_weaponSwitchTimeout( "g_weaponSwitchTimeout", "1.5", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_FLOAT, "" );
idCVar g_hitBeep( "g_hitBeep", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_INTEGER, "play hit beep sound when you inflict damage.\n 0 = do nothing\n 1 = beep/flash cross-hair\n 2 = beep\n 3 = flash cross-hair" );
idCVar g_allowHitBeep( "g_allowHitBeep", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Allow or disallow players' use of hitbeep damage feedbck." );
idCVar fs_debug( "fs_debug", "0", CVAR_SYSTEM | CVAR_INTEGER, "", 0, 2, idCmdSystem::ArgCompletion_Integer<0,2> );
#if !defined( _XENON ) && !defined( MONOLITHIC )
idCVar r_aspectRatio( "r_aspectRatio", "0", CVAR_RENDERER | CVAR_INTEGER | CVAR_ARCHIVE, "aspect ratio. 0 is 4:3, 1 is 16:9, 2 is 16:10, 3 is 5:4. -1 uses r_customAspectRatioH and r_customAspectRatioV" );
idCVar r_customAspectRatioH( "r_customAspectRatioH", "16", CVAR_RENDERER | CVAR_FLOAT | CVAR_ARCHIVE, "horizontal custom aspect ratio" );
idCVar r_customAspectRatioV( "r_customAspectRatioV", "10", CVAR_RENDERER | CVAR_FLOAT | CVAR_ARCHIVE, "vertical custom aspect ratio" );
#endif
idCVar anim_showMissingAnims( "anim_showMissingAnims", "0", CVAR_BOOL, "Show warnings for missing animations" );
const char *aas_types[] = {
"aas_player",
"aas_vehicle",
NULL
};
idCVar aas_test( "aas_test", "0", CVAR_GAME, "select which AAS to test", aas_types, idCmdSystem::ArgCompletion_String<aas_types> );
idCVar aas_showEdgeNums( "aas_showEdgeNums", "0", CVAR_GAME | CVAR_BOOL, "show edge nums" );
idCVar aas_showAreas( "aas_showAreas", "0", CVAR_GAME | CVAR_INTEGER, "show the areas in the selected aas", 0, 2, idCmdSystem::ArgCompletion_Integer<0,2> );
idCVar aas_showAreaNumber( "aas_showAreaNumber", "0", CVAR_GAME | CVAR_INTEGER, "show the specific area number set" );
idCVar aas_showPath( "aas_showPath", "0", CVAR_GAME, "show the path to the walk specified area" );
idCVar aas_showHopPath( "aas_showHopPath", "0", CVAR_GAME, "show hop path to specified area" );
idCVar aas_showWallEdges( "aas_showWallEdges", "0", CVAR_GAME | CVAR_INTEGER, "show the edges of walls, 2 = project all to same height, 3 = project onscreen", 0, 3, idCmdSystem::ArgCompletion_Integer<0,3> );
idCVar aas_showWallEdgeNums( "aas_showWallEdgeNums", "0", CVAR_GAME | CVAR_BOOL, "show the number of the edges of walls" );
idCVar aas_showNearestCoverArea( "aas_showNearestCoverArea", "0", CVAR_GAME | CVAR_INTEGER, "show the nearest area with cover from the selected area (aas_showHideArea 4 will show the nearest area in cover from area 4)" );
idCVar aas_showNearestInsideArea( "aas_showNearestInsideArea", "0", CVAR_GAME | CVAR_BOOL, "show the nearest area that is inside" );
idCVar aas_showTravelTime( "aas_showTravelTime", "0", CVAR_GAME | CVAR_INTEGER, "print the travel time to the specified goal area (only when aas_showAreas is set)" );
idCVar aas_showPushIntoArea( "aas_showPushIntoArea", "0", CVAR_GAME | CVAR_BOOL, "show an arrow going to the closest area" );
idCVar aas_showFloorTrace( "aas_showFloorTrace", "0", CVAR_GAME | CVAR_BOOL, "show floor trace" );
idCVar aas_showObstaclePVS( "aas_showObstaclePVS", "0", CVAR_GAME | CVAR_INTEGER, "show obstacle PVS for the given area" );
idCVar aas_showManualReachabilities("aas_showManualReachabilities", "0", CVAR_GAME | CVAR_BOOL, "show manually placed reachabilities" );
idCVar aas_showFuncObstacles( "aas_showFuncObstacles", "0", CVAR_GAME | CVAR_BOOL, "show the AAS func_obstacles on the map" );
idCVar aas_showBadAreas( "aas_showBadAreas", "0", CVAR_GAME | CVAR_INTEGER, "show bad AAS areas", 0, 3, idCmdSystem::ArgCompletion_Integer<0,3> );
idCVar aas_locationMemory( "aas_locationMemory", "0", CVAR_GAME, "used to remember a particular location, set to 'current' to store the current x,y,z location" );
idCVar aas_pullPlayer( "aas_pullPlayer", "0", CVAR_GAME, "pull the player to the specified area" );
idCVar aas_randomPullPlayer( "aas_randomPullPlayer", "0", CVAR_GAME | CVAR_INTEGER, "pull the player to a random area" );
idCVar bot_threading( "bot_threading", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "enable running the bot AI in a separate thread" );
idCVar bot_threadMinFrameDelay( "bot_threadMinFrameDelay", "1", CVAR_GAME | CVAR_INTEGER | CVAR_NOCHEAT, "minimum number of game frames the bot AI trails behind", 0, 4, idCmdSystem::ArgCompletion_Integer<0,4> );
idCVar bot_threadMaxFrameDelay( "bot_threadMaxFrameDelay", "4", CVAR_GAME | CVAR_INTEGER | CVAR_NOCHEAT, "maximum number of game frames the bot AI can trail behind", 0, 4, idCmdSystem::ArgCompletion_Integer<0,4> );
idCVar bot_pause( "bot_pause", "0", CVAR_GAME | CVAR_BOOL, "Pause the bot's thinking - useful for screenshots/debugging/etc" );
idCVar bot_drawClientNumbers( "bot_drawClientNumbers", "0", CVAR_GAME | CVAR_BOOL, "Draw every clients number above their head" );
idCVar bot_drawActions( "bot_drawActions", "0", CVAR_GAME | CVAR_BOOL, "Draw the bot's actions." );
idCVar bot_drawBadIcarusActions( "bot_drawBadIcarusActions", "0", CVAR_GAME | CVAR_BOOL, "Draw actions with an icarus flag, that aren't in a valid vehicle AAS area." );
idCVar bot_drawIcarusActions( "bot_drawIcarusActions", "0", CVAR_GAME | CVAR_BOOL, "Draw actions with an icarus flag, that appear valid to the AAS." );
idCVar bot_drawActionRoutesOnly( "bot_drawActionRoutesOnly", "-1", CVAR_GAME | CVAR_INTEGER, "Draw only the bot actions that have the defined route." );
idCVar bot_drawNodes( "bot_drawNodes", "0", CVAR_BOOL | CVAR_GAME, "draw vehicle path nodes" );
idCVar bot_drawNodeNumber( "bot_drawNodeNumber", "-1", CVAR_INTEGER | CVAR_GAME, "draw a specific vehicle path node" );
idCVar bot_drawDefuseHints( "bot_drawDefuseHints", "0", CVAR_BOOL | CVAR_GAME, "draw the bot's defuse hints." );
idCVar bot_drawActionNumber( "bot_drawActionNumber", "-1", CVAR_GAME | CVAR_INTEGER, "Draw a specific bot action only. -1 = disable" );
idCVar bot_drawActionVehicleType( "bot_drawActionVehicleType", "-1", CVAR_GAME | CVAR_INTEGER, "Draw only the actions that have this vehicleType set. -1 = disable" );
idCVar bot_drawActiveActionsOnly( "bot_drawActiveActionsOnly", "0", CVAR_GAME | CVAR_INTEGER, "Draw only active bot actions. 1 = all active actions. 2 = only GDF active actions. 3 = only Strogg active actions. Combo actions, that have both GDF and strogg goals, will still show up." );
idCVar bot_drawActionWithClasses( "bot_drawActionWithClasses", "0", CVAR_GAME | CVAR_BOOL, "Draw only actions that have a validClass set to anything other then 0 ( 0 = any class )." );
idCVar bot_drawActionTypeOnly( "bot_drawActionTypeOnly", "-1", CVAR_GAME | CVAR_INTEGER, "Draw only actions that have a gdf/strogg goal number matching the cvar value. Check the bot manual for goal numbers. -1 = disabled." );
idCVar bot_drawRoutes( "bot_drawRoutes", "0", CVAR_GAME | CVAR_BOOL, "Draw the routes on the map." );
idCVar bot_drawActiveRoutesOnly( "bot_drawActiveRoutesOnly", "0", CVAR_GAME | CVAR_BOOL, "Only draw the active routes on the map." );
idCVar bot_drawRouteGroupOnly( "bot_drawRouteGroupOnly", "-1", CVAR_GAME | CVAR_INTEGER, "Only draw routes that have the groupID specified." );
idCVar bot_drawActionSize( "bot_drawActionSize", "0.2", CVAR_GAME | CVAR_FLOAT, "How big to draw the bot action info. Default is 0.2" );
idCVar bot_drawActionGroupNum( "bot_drawActionGroupNum", "-1", CVAR_GAME | CVAR_INTEGER, "Filter what action groups to draw with the bot_drawAction cmd. -1 = disabled." );
idCVar bot_drawActionDist( "bot_drawActionDist", "4092", CVAR_GAME | CVAR_FLOAT, "How far away to draw the bot action info. Default is 2048" );
idCVar bot_drawObstacles( "bot_drawObstacles", "0", CVAR_GAME | CVAR_BOOL, "Draw the bot's dynamic obstacles in the world" );
idCVar bot_drawRearSpawnLocations( "bot_drawRearSpawnLocations", "0", CVAR_GAME | CVAR_BOOL, "Draw the rear spawn locations for each team" );
idCVar bot_enable( "bot_enable", "1", CVAR_GAME | CVAR_BOOL | CVAR_SERVERINFO, "0 = bots will not be loaded in the game. 1 = bots are loaded." );
idCVar bot_doObjectives( "bot_doObjectives", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "0 = bots let the player play the hero, with the bots filling a supporting role, 1 = bots do all the major objectives along with the player" );
idCVar bot_ignoreGoals( "bot_ignoreGoals", "0", CVAR_GAME | CVAR_INTEGER | CVAR_CHEAT, "If set to 1, bots will ignore all map objectives. Useful for debugging bot behavior" );
idCVar bot_useVehicles( "bot_useVehicles", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots dont use vehicles, 1 = bots do use vehicles" );
idCVar bot_useVehicleDrops( "bot_useVehicleDrops", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots don't use vehicle drops, 1 = bots do use vehicle drops" );
idCVar bot_stayInVehicles( "bot_stayInVehicles", "0", CVAR_GAME | CVAR_BOOL, "1 = bots will never leave their vehicle. Only useful for debugging. Default is 0" );
idCVar bot_useStrafeJump( "bot_useStrafeJump", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots can't strafe jump, 1 = bots CAN strafe jump to goal locations that are far away" );
idCVar bot_useSuicideWhenStuck( "bot_useSuicideWhenStuck", "1", CVAR_GAME | CVAR_BOOL, "0 = bots never suicide when stuck. 1 = bots suicide if they detect that they're stuck" );
idCVar bot_useDeployables( "bot_useDeployables", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots dont drop deployables of any kind, 1 = bots can drop all deployables" );
idCVar bot_useMines( "bot_useMines", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots dont use mines, 1 = bots can use mines. Default = 1" );
idCVar bot_sillyWarmup( "bot_sillyWarmup", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots play the game like normal, 1 = bots shoot each other and act silly during warmup" );
idCVar bot_useSpawnHosts( "bot_useSpawnHosts", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = strogg bots can't use spawn host bodies, 1 = bots can use spawnhosts" );
idCVar bot_useUniforms( "bot_useUniforms", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots won't steal uniforms, 1 = bots take uniforms" );
idCVar bot_noChat( "bot_noChat", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots chat, 1 = bots never chat" );
idCVar bot_noTaunt( "bot_noTaunt", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots taunt, 1 = bots never taunt" );
idCVar bot_aimSkill( "bot_aimSkill", "1", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "Sets the bot's default aiming skill. 0 = EASY, 1 = MEDIUM, 2 = EXPERT, 3 = MASTER", 0, 3, idCmdSystem::ArgCompletion_Integer<0,3> );
idCVar bot_skill( "bot_skill", "3", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "Sets the bot's default AI skill. 0 = EASY, 1 = NORMAL, 2 = EXPERT, 3 = TRAINING MODE - this mode is useful for learning about the game", 0, 3, idCmdSystem::ArgCompletion_Integer<0,3> );
idCVar bot_knifeOnly( "bot_knifeOnly", "0", CVAR_GAME | CVAR_BOOL, "goofy mode where the bots only use their knifes in combat." );
idCVar bot_ignoreEnemies( "bot_ignoreEnemies", "0", CVAR_GAME | CVAR_INTEGER, "If set to 1, bots will ignore all enemies. 2 = Ignore Strogg. 3 = Ignore GDF. Useful for debugging bot behavior" );
idCVar bot_debug( "bot_debug", "0", CVAR_GAME | CVAR_BOOL, "Debug various bot subsystems. Many bot debugging features are disabled if this is not set to 1" );
idCVar bot_debugActionGoalNumber( "bot_debugActionGoalNumber", "-1", CVAR_GAME | CVAR_INTEGER, "Set to any action number on the map to have the bot ALWAYS do that action, for debugging. -1 = disabled. NOTE: The bot will treat the goal as a camp goal. This is useful for path testing." );
idCVar bot_debugSpeed( "bot_debugSpeed", "-1", CVAR_GAME | CVAR_INTEGER, "Debug bot's move speed. -1 = disable" );
idCVar bot_debugGroundVehicles( "bot_debugGroundVehicles", "-1", CVAR_GAME | CVAR_INTEGER, "Debug bot ground vehicle usage. -1 = disable" );
idCVar bot_debugAirVehicles( "bot_debugAirVehicles", "-1", CVAR_GAME | CVAR_INTEGER, "Debug bot air vehicle usage. -1 = disable" );
idCVar bot_debugObstacles( "bot_debugObstacles", "0", CVAR_GAME | CVAR_BOOL, "Debug bot obstacles in the world" );
idCVar bot_spectateDebug( "bot_spectateDebug", "0", CVAR_GAME | CVAR_BOOL, "If enabled, automatically sets the debug hud to the bot being spectated" );
idCVar bot_followMe( "bot_followMe", "0", CVAR_GAME | CVAR_INTEGER, "Have the bots follow you in debug mode" );
idCVar bot_breakPoint( "bot_breakPoint", "0", CVAR_GAME | CVAR_BOOL, "Cause a program break to occur inside the bot's AI" );
idCVar bot_useShotguns( "bot_useShotguns", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots wont use shotguns/nailguns. 1 = bots will use shotguns/nailguns." );
idCVar bot_useSniperWeapons( "bot_useSniperWeapons", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots wont use sniper rifles. 1 = bots will use sniper rifles." );
idCVar bot_minClients( "bot_minClients", "-1", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "Keep a minimum number of clients on the server with bots and humans. -1 to disable", -1, MAX_CLIENTS );
idCVar bot_minClientsMax( "bot_minClientsMax", "16", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_INIT, "Maximum allowed value of bot_minClients. Only affects the in-game UI.", -1, MAX_CLIENTS );
idCVar bot_debugPersonalVehicles( "bot_debugPersonalVehicles", "0", CVAR_GAME | CVAR_BOOL, "Only used for debugging the use of the husky/icarus." );
idCVar bot_debugWeapons( "bot_debugWeapons", "0", CVAR_GAME | CVAR_BOOL, "Only used for debugging bots weapons." );
idCVar bot_uiNumStrogg( "bot_uiNumStrogg", "-1", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "The number of strogg bots to add to the server. -1 to disable" );
idCVar bot_uiNumGDF( "bot_uiNumGDF", "-1", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "The number of gdf bots to add to the server. -1 to disable" );
idCVar bot_uiSkill( "bot_uiSkill", "5", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC | CVAR_NOCHEAT, "The overall skill the bots should play at in the game. 0 = EASY, 1 = MEDIUM, 2 = EXPERT, 3 = MASTER, 4 = CUSTOM, 5 = TRAINING" );
idCVar bot_showPath( "bot_showPath", "-1", CVAR_GAME | CVAR_INTEGER, "Show the path for the bot's client number. -1 = disable." );
idCVar bot_skipThinkClient( "bot_skipThinkClient", "-1", CVAR_GAME | CVAR_INTEGER, "A debug only cvar that skips thinking for a particular bot with the client number entered. -1 = disabled." );
idCVar bot_debugMapScript( "bot_debugMapScript", "0", CVAR_GAME | CVAR_BOOL, "Allows you to debug the bot script." );
idCVar bot_useTKRevive( "bot_useTKRevive", "1", CVAR_GAME | CVAR_BOOL, "Allows the bots to use the advanced tactic of TK reviving if their teammate is weak. 0 = disabled. Default is 1" );
idCVar bot_debugObstacleAvoidance( "bot_debugObstacleAvoidance", "0", CVAR_GAME | CVAR_BOOL, "Debug obstacle avoidance" );
idCVar bot_testObstacleQuery( "bot_testObstacleQuery", "", CVAR_GAME, "test a previously recorded obstacle avoidance query" );
idCVar bot_balanceCriticalClass( "bot_balanceCriticalClass", "1", CVAR_GAME | CVAR_BOOL, "Have the bots try to keep someone playing the critical class at all times. 0 = keep the class they spawn in as. Default = 1." );
idCVar bot_useAltRoutes( "bot_useAltRoutes", "1", CVAR_GAME | CVAR_BOOL, "Debug the bot's alternate path use." );
idCVar bot_godMode( "bot_godMode", "-1", CVAR_GAME | CVAR_INTEGER, "Set to the bot client you want to enter god mode. -1 = disable." );
idCVar bot_useRearSpawn( "bot_useRearSpawn", "1", CVAR_BOOL | CVAR_GAME, "debug bots using rear spawn points" );
idCVar bot_sleepWhenServerEmpty( "bot_sleepWhenServerEmpty", "1", CVAR_BOOL | CVAR_GAME | CVAR_NOCHEAT, "has the bots stop thinking when the server is idle and there are no humans playing, to conserve CPU." );
idCVar bot_allowObstacleDecay( "bot_allowObstacleDecay", "1", CVAR_BOOL | CVAR_GAME, "0 = dont allow obstacle decay. 1 = allow obstacle decay." );
idCVar bot_allowClassChanges( "bot_allowClassChanges", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots won't ever change their class. 1 = Bots can change their class thru script/code." );
idCVar bot_testPathToBotAction( "bot_testPathToBotAction", "-1", CVAR_GAME | CVAR_INTEGER, "based on which aas type aas_test is set to, will test to see if a path is available from the players current origin, to the bot action in question. You need to join a team for this to work properly! -1 = disabled." );
idCVar bot_pauseInVehicleTime( "bot_pauseInVehicleTime", "7", CVAR_GAME | CVAR_INTEGER, "Time the bots will pause when first enter a vehicle ( in seconds ) to allow others to jump in. Default is 7 seconds." );
idCVar bot_doObjsInTrainingMode( "bot_doObjsInTrainingMode", "1", CVAR_GAME | CVAR_BOOL, "Controls whether or not bots will do objectives in training mode, if the human isn't the correct class to do the objective. 0 = bots won't do primary or secondary objecitives in training mode. 1 = bots will do objectives. Default = 1. " );
idCVar bot_doObjsDelayTimeInMins( "bot_doObjsDelayTimeInMins", "3", CVAR_GAME | CVAR_INTEGER, "How long of a delay in time the bots will have before they start considering objectives while in Training mode. Default is 3 minutes. " );
idCVar bot_useAirVehicles( "bot_useAirVehicles", "1", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "0 = bots dont use air vehicles, 1 = bots do use air vehicles. Useful for debugging ground vehicles only." );
idCVar g_showCrosshairInfo( "g_showCrosshairInfo", "1", CVAR_INTEGER | CVAR_GAME, "shows information about the entity under your crosshair" );
idCVar g_banner_1( "g_banner_1", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 1" );
idCVar g_banner_2( "g_banner_2", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 2" );
idCVar g_banner_3( "g_banner_3", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 3" );
idCVar g_banner_4( "g_banner_4", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 4" );
idCVar g_banner_5( "g_banner_5", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 5" );
idCVar g_banner_6( "g_banner_6", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 6" );
idCVar g_banner_7( "g_banner_7", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 7" );
idCVar g_banner_8( "g_banner_8", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 8" );
idCVar g_banner_9( "g_banner_9", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 9" );
idCVar g_banner_10( "g_banner_10", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 10" );
idCVar g_banner_11( "g_banner_11", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 11" );
idCVar g_banner_12( "g_banner_12", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 12" );
idCVar g_banner_13( "g_banner_13", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 13" );
idCVar g_banner_14( "g_banner_14", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 14" );
idCVar g_banner_15( "g_banner_15", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 15" );
idCVar g_banner_16( "g_banner_16", "", CVAR_GAME | CVAR_NOCHEAT, "banner message 16" );
idCVar g_bannerDelay( "g_banner_delay", "1", CVAR_GAME | CVAR_NOCHEAT | CVAR_INTEGER, "delay in seconds between banner messages" );
idCVar g_bannerLoopDelay( "g_banner_loopdelay", "0", CVAR_GAME | CVAR_NOCHEAT | CVAR_INTEGER, "delay in seconds before banner messages repeat, 0 = off" );
idCVar* g_bannerCvars[ NUM_BANNER_MESSAGES ] = {
&g_banner_1, &g_banner_2, &g_banner_3, &g_banner_4, &g_banner_5, &g_banner_6, &g_banner_7, &g_banner_8,
&g_banner_9, &g_banner_10, &g_banner_11, &g_banner_12, &g_banner_13, &g_banner_14, &g_banner_15, &g_banner_16,
};
idCVar g_allowComplaintFiresupport( "g_allowComplaint_firesupport", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Allow complaints for teamkills with fire support" );
idCVar g_allowComplaintCharge( "g_allowComplaint_charge", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Allow complaints for teamkills with charges" );
idCVar g_allowComplaintExplosives( "g_allowComplaint_explosives", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Allow complaints for teamkills with explosive weapons and items" );
idCVar g_allowComplaintVehicles( "g_allowComplaint_vehicles", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Allow complaints for teamkills with vehicle" );
idCVar g_complaintLimit( "g_complaintLimit", "6", CVAR_GAME | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "Total complaints at which a player will be kicked" );
idCVar g_complaintGUIDLimit( "g_complaintGUIDLimit", "4", CVAR_GAME | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "Total unique complaints at which a player will be kicked" );
idCVar g_execMapConfigs( "g_execMapConfigs", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Execute map cfg with same name" );
idCVar g_teamSwitchDelay( "g_teamSwitchDelay", "5", CVAR_GAME | CVAR_ARCHIVE | CVAR_INTEGER | CVAR_RANKLOCKED, "Delay (in seconds) before player can change teams again" );
idCVar g_warmupDamage( "g_warmupDamage", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Enable/disable players taking damage during warmup" );
idCVar g_muteSpecs( "g_muteSpecs", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "Send all spectator global chat to team chat" );
idCVar g_warmup( "g_warmup", "0.5", CVAR_GAME | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_RANKLOCKED, "Length (in minutes) of warmup period" );
idCVar g_gameReviewPause( "g_gameReviewPause", "0.5", CVAR_GAME | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_RANKLOCKED, "Time (in minutes) for scores review time" );
idCVar g_password( "g_password", "", CVAR_GAME | CVAR_ARCHIVE | CVAR_RANKLOCKED, "game password" );
idCVar g_privatePassword( "g_privatePassword", "", CVAR_GAME | CVAR_ARCHIVE, "game password for private slots" );
idCVar g_xpSave( "g_xpSave", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL | CVAR_RANKLOCKED, "stores xp for disconnected players which will be given back if they reconnect" );
idCVar g_kickBanLength( "g_kickBanLength", "2", CVAR_GAME | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_RANKLOCKED, "length of time a kicked player will be banned for" );
idCVar g_maxSpectateTime( "g_maxSpectateTime", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_RANKLOCKED, "maximum length of time a player may spectate for" );
idCVar g_unlock_updateAngles( "g_unlock_updateAngles", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_BOOL, "update view angles in fps unlock mode" );
idCVar g_unlock_updateViewpos( "g_unlock_updateViewpos", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_BOOL, "update view origin in fps unlock mode" );
idCVar g_unlock_interpolateMoving( "g_unlock_interpolateMoving", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_BOOL, "interpolate moving objects in fps unlock mode" );
idCVar g_unlock_viewStyle( "g_unlock_viewStyle", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_INTEGER, "0: extrapolate view origin, 1: interpolate view origin" );
idCVar g_voteWait( "g_voteWait", "2.5", CVAR_GAME | CVAR_ARCHIVE | CVAR_FLOAT | CVAR_RANKLOCKED, "Delay (in minutes) before player may perform a callvote again" );
idCVar g_useTraceCollection( "g_useTraceCollection", "1", CVAR_GAME | CVAR_BOOL, "Use optimized trace collections" );
idCVar g_removeStaticEntities( "g_removeStaticEntities", "1", CVAR_GAME | CVAR_BOOL, "Remove non-dynamic entities on map spawn when they aren't needed" );
idCVar g_maxVoiceChats( "g_maxVoiceChats", "4", CVAR_GAME | CVAR_ARCHIVE | CVAR_INTEGER, "maximum number of voice chats a player may do in a period of time" );
idCVar g_maxVoiceChatsOver( "g_maxVoiceChatsOver", "30", CVAR_GAME | CVAR_ARCHIVE | CVAR_INTEGER, "time over which the maximum number of voice chat limit is applied" );
idCVar g_profileEntityThink( "g_profileEntityThink", "0", CVAR_GAME | CVAR_BOOL, "Enable entity think profiling" );
idCVar g_timeoutToSpec( "g_timeoutToSpec", "0", CVAR_GAME | CVAR_FLOAT | CVAR_NOCHEAT, "Timeout in minutes for players who are AFK to go into spectator mode (0=disabled)" );
idCVar g_autoReadyPercent( "g_autoReadyPercent", "50", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE, "Percentage of a full server that must be in game for auto ready to start" );
idCVar g_autoReadyWait( "g_autoReadyWait", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE, "Length of time in minutes auto ready will wait before starting the countdown" );
idCVar g_useBotsInPlayerTotal( "g_useBotsInPlayerTotal", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "Should bots count towards the number of players required to start the game?" );
idCVar g_playTooltipSound( "g_playTooltipSound", "2", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE | CVAR_PROFILE, "0: no sound 1: play tooltip sound in single player only 2: Always play tooltip sound" );
idCVar g_tooltipTimeScale( "g_tooltipTimeScale", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Scale the amount of time that a tooltip is visible. 0 will disable all tooltips." );
idCVar g_tooltipVolumeScale( "g_tooltipVolumeScale", "-20", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Change the game volume while playing a tooltip with VO." );
idCVar g_allowSpecPauseFreeFly( "g_allowSpecPauseFreeFly", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Allow spectators to free fly when the game is paused" );
idCVar g_smartTeamBalance( "g_smartTeamBalance", "1", CVAR_GAME | CVAR_BOOL | CVAR_RANKLOCKED, "Encourages players to balance teams themselves by giving rewards." );
idCVar g_smartTeamBalanceReward( "g_smartTeamBalanceReward", "10", CVAR_GAME | CVAR_INTEGER | CVAR_RANKLOCKED, "The amount of XP to give people who switch teams when asked to." );
idCVar g_keepFireTeamList( "g_keepFireTeamList", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "Always show the fireteam list on the HUD." );
idCVar net_serverDownload( "net_serverDownload", "0", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "enable server download redirects. 0: off 1: client exits and opens si_serverURL in web browser 2: client downloads pak files from an URL and connects again. See net_serverDl* cvars for configuration" );
idCVar net_serverDlBaseURL( "net_serverDlBaseURL", "", CVAR_GAME | CVAR_ARCHIVE, "base URL for the download redirection" );
idCVar net_serverDlTable( "net_serverDlTable", "", CVAR_GAME | CVAR_ARCHIVE, "pak names for which download is provided, seperated by ; - use a * to mark all paks" );
idCVar g_drawMineIcons( "g_drawMineIcons", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "Draw icons on the HUD for mines." );
idCVar g_allowMineIcons( "g_allowMineIcons", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC | CVAR_RANKLOCKED, "Allow clients to draw icons on the HUD for mines." );
idCVar g_mineIconSize( "g_mineIconSize", "10", CVAR_FLOAT | CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "Size of the screen space mine icons. NOTE: Will only take effect for new mines, not those already existing.", 0, 20 );
idCVar g_mineIconAlphaScale( "g_mineIconAlphaScale", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Alpha scale to apply to mine icons. NOTE: Will only take effect for new mines, not those already existing." );
idCVar g_drawVehicleIcons( "g_drawVehicleIcons", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "Draw icons on the HUD for vehicles (eg spawn invulnerability)." );
#ifdef SD_SUPPORT_REPEATER
idCVar ri_useViewerPass( "ri_useViewerPass", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_REPEATERINFO | CVAR_BOOL, "use g_viewerPassword for viewers/repeaters" );
idCVar g_viewerPassword( "g_viewerPassword", "", CVAR_GAME | CVAR_ARCHIVE, "password for viewers" );
idCVar g_repeaterPassword( "g_repeaterPassword", "", CVAR_GAME | CVAR_ARCHIVE, "password for repeaters" );
idCVar ri_privateViewers( "ri_privateViewers", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_REPEATERINFO | CVAR_INTEGER, "number of private viewer slots" );
idCVar g_privateViewerPassword( "g_privateViewerPassword", "", CVAR_GAME | CVAR_ARCHIVE, "privatePassword for private viewer slots" );
idCVar ri_name( "ri_name", "", CVAR_GAME | CVAR_ARCHIVE | CVAR_REPEATERINFO, "override the server's si_name with this for relays" );
idCVar g_noTVChat( "g_noTVChat", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "Server enable/disable flag for viewer chat on ETQW:TV" );
#endif // SD_SUPPORT_REPEATER
idCVar g_drawHudMessages( "g_drawHudMessages", "1", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE | CVAR_PROFILE, "Draw task, task success and objective text on HUD." );
idCVar g_allowMineTriggerWarning( "g_allowMineTriggerWarning", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC | CVAR_RANKLOCKED, "Allow clients to draw warning text on the HUD for mine triggering." );
idCVar g_mineTriggerWarning( "g_mineTriggerWarning", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "Show warning message on HUD when triggering a proximity mine." );
idCVar g_allowAPTWarning( "g_allowAPTWarning", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC | CVAR_RANKLOCKED, "Allow clients to draw warning text on the HUD for APT lock ons." );
idCVar g_aptWarning( "g_aptWarning", "3", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE | CVAR_PROFILE, "Show warning message on HUD when APT is locking on. 0: Off 1: Visual warning only 2: Beep only 3: Visual and beep" );
idCVar g_useBaseETQW12Shotguns( "g_useBaseETQW12Shotguns", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use BaseETQW v1.2 behaviour for shotgun and nailgun." );
idCVar g_useQuake4DarkMatter( "g_useQuake4DarkMatter", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use Quake 4-style Dark Matter weaponry." );
idCVar g_artilleryWarning( "g_artilleryWarning", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "Notify players of the launch of Hammer or DMC artillery." );
idCVar g_useDeathFading( "g_useDeathFading", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use screen fading effects when dead or unconscious?" );
idCVar g_useReverseAirstrikes( "g_useReverseAirstrikes", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use reversed airstrikes on the altfire of the Vampire and Violator?" );
idCVar g_useShieldAbsorber( "g_useShieldAbsorber", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use the shield absorber as the altfire of the Tactical Shield?" );
idCVar g_useNuclearHammer( "g_useNuclearHammer", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Make the Hammer and SSM missiles behave more like tactical nukes?" );
idCVar g_useQuake4Hyperblaster( "g_useQuake4Hyperblaster", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use Quake 4-style Hyperblaster weaponry?" );
idCVar g_useQuake4Railgun( "g_useQuake4Railgun", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use Quake 4-style Railgun weaponry?" );
idCVar g_useClassLimits( "g_useClassLimits", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Enables or disables class number limitations." );
idCVar g_useGibKills( "g_useGibKills", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "Enables or disables certain attacks that don't normally gib, to do so." );
idCVar g_useAwardJackOfAllTrades( "g_useAwardJackOfAllTrades", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Enables or disables the new Jack of All Trades after-mission award." );
idCVar g_advancedVehicleDrops( "g_advancedVehicleDrops", "-1", CVAR_GAME | CVAR_INTEGER | CVAR_NETWORKSYNC, "Bitfield that specifies which vehicles may be dropped in via quickchat commands." );
idCVar g_useSpecificRadar( "g_useSpecificRadar", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should players(but not vehicles) be invisible to radar? (3rd eye and MCP exempt.)" );
idCVar g_vehicleDropsUseFE( "g_vehicleDropsUseFE", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should vehicle drops have Force Escalation requirements for their use?" );
idCVar g_vehicleDropsUseLP( "g_vehicleDropsUseLP", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should vehicle drops have Logistics Points requirements for their use?" );
idCVar g_huskyIcarusDropsIgnoreFE( "g_huskyIcarusDropsIgnoreFE", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should the Husky and Icarus ignore FE requirements? (Treat them as costing 0 FE.)" );
idCVar g_huskyIcarusDropsIgnoreLP( "g_huskyIcarusDropsIgnoreLP", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should the Husky and Icarus ignore LP requirements? (Treat them as costing 0 LP.)" );
idCVar g_useBaseETQWVehicleCredits("g_useBaseETQWVehicleCredits", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should the Icarus and Husky use BaseETQW vehicle credit costs?" );
idCVar g_useBaseETQWProficiencies( "g_useBaseETQWProficiencies", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should BaseETQW proficiencies be used? (QWTA gives free Vehicle Drops otherwise.)" );
idCVar g_useBaseETQWVehicleCharge( "g_useBaseETQWVehicleCharge", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should the BaseETQW vehicle credit charge timer duration be used?" );
idCVar g_vehicleSpawnsUseFE( "g_vehicleSpawnsUseFE", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Do vehicle spawns have Force Escalation requirements?" );
idCVar g_disableVehicleRespawns( "g_disableVehicleRespawns", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Are vehicles permitted to respawn after being destroyed?" );
idCVar g_disablePlayerRespawns( "g_disablePlayerRespawns", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Are players permitted to respawn after being killed?" );
idCVar g_allowCrosshairs( "g_allowCrosshairs", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Allow or disallow player's crosshairs." );
//idCVar g_allowTimerCircles( "g_allowTimerCircles", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Allow or disallow the timer circles that normally surround the crosshairs." );
//idCVar g_useStraightRockets( "g_useStraightRockets", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use Rocket Launcher projectiles that fly straight, or keep the flight arc of the BaseETQW Rocket Launcher?" );
idCVar g_useBaseETQW12SniperTrail( "g_useBaseETQW12SniperTrail", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Use the BaseETQW 1.2 sniper rifle's trail-tracer effect?" );
//idCVar g_hideHud( "g_hideHud", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Disables most aspects of the HUD, revealing them only when they're accessed in some way." );
idCVar g_useRealisticWeapons( "g_useRealisticWeapons", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should weapons behave in a realistic manner, or more game-oriented?" );
idCVar g_useVehicleAmmo( "g_useVehicleAmmo", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should vehicle weapons consume ammunition or not?" );
idCVar g_useVehicleDecoyAmmo( "g_useVehicleDecoyAmmo", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Should vehicle decoys consume ammunition or not?" );
idCVar g_allowEMPFriendlyFire( "g_allowEMPFriendlyFire", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Allow or disallow EMP effects from affecting friendly units." );
idCVar g_allowRadFriendlyFire( "g_allowRadFriendlyFire", "1", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Allow or disallow radiation effects from affecting friendly units." );
idCVar g_forgivingBotMatch( "g_forgivingBotMatch", "0", CVAR_GAME | CVAR_BOOL | CVAR_NETWORKSYNC, "Make BotMatches be more forgiving for a player." );
idCVar g_blood( "g_blood", "1", CVAR_GAME | CVAR_PROFILE | CVAR_ARCHIVE | CVAR_BOOL, "Show blood" );
idCVar g_trainingMode( "g_trainingMode", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT, "whether the game is in training mode or not" );
idCVar g_objectiveDecayTime( "g_objectiveDecayTime", "5", CVAR_GAME | CVAR_FLOAT | CVAR_RANKLOCKED, "Length of time in seconds that it takes a construct/hack objective to decay once after the initial timeout is complete" );
idCVar g_noQuickChats( "g_noQuickChats", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "disables sound and text of quickchats" );
idCVar g_maxProficiency( "g_maxProficiency", "0", CVAR_GAME | CVAR_BOOL | CVAR_RANKLOCKED, "" );
idCVar g_vehicleSpawnMinPlayersHusky( "g_vehicleSpawnMinPlayersHusky", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersPlatypus( "g_vehicleSpawnMinPlayersPlatypus", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersArmadillo( "g_vehicleSpawnMinPlayersArmadillo", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersTrojan( "g_vehicleSpawnMinPlayersTrojan", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersBumblebee( "g_vehicleSpawnMinPlayersBumblebee", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersTitan( "g_vehicleSpawnMinPlayersTitan", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersAnansi( "g_vehicleSpawnMinPlayersAnansi", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersIcarus( "g_vehicleSpawnMinPlayersIcarus", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersHog( "g_vehicleSpawnMinPlayersHog", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersDesecrator( "g_vehicleSpawnMinPlayersDesecrator", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersCyclops( "g_vehicleSpawnMinPlayersCyclops", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersTormentor( "g_vehicleSpawnMinPlayersTormentor", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersJupiter( "g_vehicleSpawnMinPlayersJupiter", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
idCVar g_vehicleSpawnMinPlayersAbaddon( "g_vehicleSpawnMinPlayersAbaddon", "0", CVAR_GAME | CVAR_NETWORKSYNC, "The minimum players that have to be on server before this vehicle will spawn.");
| 116.325826
| 337
| 0.722832
|
JasonHutton
|
677f46fc06e7d13606731f6f380c3030e3e2c04e
| 4,986
|
cpp
|
C++
|
Server/GameServer/SealHandler.cpp
|
APistole/KnightOnline
|
80268e2fa971389a3e94c430966a7943c2631dbf
|
[
"MIT"
] | 191
|
2016-03-05T16:44:15.000Z
|
2022-03-09T00:52:31.000Z
|
Server/GameServer/SealHandler.cpp
|
APistole/KnightOnline
|
80268e2fa971389a3e94c430966a7943c2631dbf
|
[
"MIT"
] | 128
|
2016-08-31T04:09:06.000Z
|
2022-01-14T13:42:56.000Z
|
Server/GameServer/SealHandler.cpp
|
APistole/KnightOnline
|
80268e2fa971389a3e94c430966a7943c2631dbf
|
[
"MIT"
] | 165
|
2016-03-05T16:43:59.000Z
|
2022-01-22T00:52:25.000Z
|
#include "stdafx.h"
using std::string;
#define ITEM_SEAL_PRICE 1000000
enum
{
SEAL_TYPE_SEAL = 1,
SEAL_TYPE_UNSEAL = 2,
SEAL_TYPE_KROWAZ = 3
};
enum SealErrorCodes
{
SealErrorNone = 0, // no error, success!
SealErrorFailed = 2, // "Seal Failed."
SealErrorNeedCoins = 3, // "Not enough coins."
SealErrorInvalidCode = 4, // "Invalid Citizen Registry Number" (i.e. invalid code/password)
SealErrorPremiumOnly = 5, // "Only available to premium users"
SealErrorFailed2 = 6, // "Seal Failed."
SealErrorTooSoon = 7, // "Please try again. You may not repeat this function instantly."
};
/**
* @brief Packet handler for the item sealing system.
*
* @param pkt The packet.
*/
void CUser::ItemSealProcess(Packet & pkt)
{
// Seal type
uint8_t opcode = pkt.read<uint8_t>();
Packet result(WIZ_ITEM_UPGRADE);
result << uint8_t(ITEM_SEAL) << opcode;
switch (opcode)
{
// Used when sealing an item.
case SEAL_TYPE_SEAL:
{
string strPasswd;
uint32_t nItemID;
int16_t unk0; // set to -1 in this case
uint8_t bSrcPos, bResponse = SealErrorNone;
pkt >> unk0 >> nItemID >> bSrcPos >> strPasswd;
/*
Most of these checks are handled client-side, so we shouldn't need to provide error messages.
Also, item sealing requires certain premium types (gold, platinum, etc) - need to double-check
these before implementing this check.
*/
// is this a valid position? (need to check if it can be taken from new slots)
if (bSrcPos >= HAVE_MAX
// does the item exist where the client says it does?
|| GetItem(SLOT_MAX + bSrcPos)->nNum != nItemID
// i ain't be allowin' no stealth items to be sealed!
|| GetItem(SLOT_MAX + bSrcPos)->nSerialNum == 0)
bResponse = SealErrorFailed;
// is the password valid by client limits?
else if (strPasswd.empty() || strPasswd.length() > 8)
bResponse = SealErrorInvalidCode;
// do we have enough coins?
else if (!hasCoins(ITEM_SEAL_PRICE))
bResponse = SealErrorNeedCoins;
_ITEM_TABLE* pItem = g_pMain->m_ItemtableArray.GetData(nItemID);
if(pItem == nullptr)
return;
#if 0 // this doesn't look right
// If the item's not equippable we not be lettin' you seal no moar!
if (pItem->m_bSlot >= SLOT_MAX)
bResponse = SealErrorFailed;
#endif
// If no error, pass it along to the database.
if (bResponse == SealErrorNone)
{
result << nItemID << bSrcPos << strPasswd << bResponse;
g_pMain->AddDatabaseRequest(result, this);
}
// If there's an error, tell the client.
// From memory though, there was no need -- it handled all of these conditions itself
// so there was no need to differentiate (just ignore the packet). Need to check this.
else
{
result << bResponse;
Send(&result);
}
} break;
// Used when unsealing an item.
case SEAL_TYPE_UNSEAL:
{
string strPasswd;
uint32_t nItemID;
int16_t unk0; // set to -1 in this case
uint8_t bSrcPos, bResponse = SealErrorNone;
pkt >> unk0 >> nItemID >> bSrcPos >> strPasswd;
if (bSrcPos >= HAVE_MAX
|| GetItem(SLOT_MAX+bSrcPos)->bFlag != ITEM_FLAG_SEALED
|| GetItem(SLOT_MAX+bSrcPos)->nNum != nItemID)
bResponse = SealErrorFailed;
else if (strPasswd.empty() || strPasswd.length() > 8)
bResponse = SealErrorInvalidCode;
// If no error, pass it along to the database.
if (bResponse == SealErrorNone)
{
result << nItemID << bSrcPos << strPasswd << bResponse;
g_pMain->AddDatabaseRequest(result, this);
}
// If there's an error, tell the client.
// From memory though, there was no need -- it handled all of these conditions itself
// so there was no need to differentiate (just ignore the packet). Need to check this.
else
{
result << bResponse;
Send(&result);
}
} break;
// Used when binding a Krowaz item (used to take it from not bound -> bound)
case SEAL_TYPE_KROWAZ:
{
string strPasswd = "0"; //Dummy, not actually used.
uint32_t nItemID;
uint8_t bSrcPos = 0 , unk3, bResponse = SealErrorNone;
uint16_t unk1, unk2;
pkt >> unk1 >> nItemID >> bSrcPos >> unk3 >> unk2;
if (bSrcPos >= HAVE_MAX
|| GetItem(SLOT_MAX+bSrcPos)->bFlag != ITEM_FLAG_NONE
|| GetItem(SLOT_MAX+bSrcPos)->nNum != nItemID)
bResponse = SealErrorFailed;
if (bResponse == SealErrorNone)
{
result << nItemID << bSrcPos << strPasswd << bResponse;
g_pMain->AddDatabaseRequest(result, this);
}
} break;
}
}
void CUser::SealItem(uint8_t bSealType, uint8_t bSrcPos)
{
_ITEM_DATA * pItem = GetItem(SLOT_MAX + bSrcPos);
if (pItem == nullptr)
return;
switch (bSealType)
{
case SEAL_TYPE_SEAL:
pItem->bFlag = ITEM_FLAG_SEALED;
GoldLose(ITEM_SEAL_PRICE);
break;
case SEAL_TYPE_UNSEAL:
pItem->bFlag = 0;
break;
case SEAL_TYPE_KROWAZ:
pItem->bFlag = ITEM_FLAG_BOUND;
break;
}
}
/**
* @brief Packet handler for the character sealing system.
*
* @param pkt The packet.
*/
void CUser::CharacterSealProcess(Packet & pkt)
{
}
| 27.546961
| 98
| 0.676093
|
APistole
|
677f4c58a0957dd00800731a89c97b4a7d44ce20
| 13,771
|
cpp
|
C++
|
vs2017/screenshot/GeneratedFiles/moc_FullScreenWidget.cpp
|
cheechang/cppcc
|
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
|
[
"MIT"
] | null | null | null |
vs2017/screenshot/GeneratedFiles/moc_FullScreenWidget.cpp
|
cheechang/cppcc
|
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
|
[
"MIT"
] | null | null | null |
vs2017/screenshot/GeneratedFiles/moc_FullScreenWidget.cpp
|
cheechang/cppcc
|
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
|
[
"MIT"
] | null | null | null |
/****************************************************************************
** Meta object code from reading C++ file 'FullScreenWidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../FullScreenWidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'FullScreenWidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_fullScreenWidget_t {
QByteArrayData data[37];
char stringdata0[541];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_fullScreenWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_fullScreenWidget_t qt_meta_stringdata_fullScreenWidget = {
{
QT_MOC_LITERAL(0, 0, 16), // "fullScreenWidget"
QT_MOC_LITERAL(1, 17, 12), // "finishPixmap"
QT_MOC_LITERAL(2, 30, 0), // ""
QT_MOC_LITERAL(3, 31, 10), // "exitPixmap"
QT_MOC_LITERAL(4, 42, 12), // "finishedshot"
QT_MOC_LITERAL(5, 55, 3), // "cmd"
QT_MOC_LITERAL(6, 59, 24), // "signalChangeCurrentShape"
QT_MOC_LITERAL(7, 84, 11), // "Shape::Code"
QT_MOC_LITERAL(8, 96, 3), // "pen"
QT_MOC_LITERAL(9, 100, 20), // "signalDeleteLastDraw"
QT_MOC_LITERAL(10, 121, 22), // "signalSelectPenChanged"
QT_MOC_LITERAL(11, 144, 23), // "signalSelectFontChanged"
QT_MOC_LITERAL(12, 168, 19), // "signalAddTextToView"
QT_MOC_LITERAL(13, 188, 20), // "loadBackgroundPixmap"
QT_MOC_LITERAL(14, 209, 8), // "bgPixmap"
QT_MOC_LITERAL(15, 218, 1), // "x"
QT_MOC_LITERAL(16, 220, 1), // "y"
QT_MOC_LITERAL(17, 222, 5), // "width"
QT_MOC_LITERAL(18, 228, 6), // "height"
QT_MOC_LITERAL(19, 235, 14), // "exitShotScreen"
QT_MOC_LITERAL(20, 250, 8), // "iscancel"
QT_MOC_LITERAL(21, 259, 10), // "savePixmap"
QT_MOC_LITERAL(22, 270, 16), // "finishScreenShot"
QT_MOC_LITERAL(23, 287, 19), // "slotDrawRectClicked"
QT_MOC_LITERAL(24, 307, 22), // "slotDrawEllipseClicked"
QT_MOC_LITERAL(25, 330, 20), // "slotDrawArrowClicked"
QT_MOC_LITERAL(26, 351, 19), // "slotDrawTextClicked"
QT_MOC_LITERAL(27, 371, 19), // "slotDrawPathClicked"
QT_MOC_LITERAL(28, 391, 17), // "slotRevokeClicked"
QT_MOC_LITERAL(29, 409, 20), // "slotSelectPenChanged"
QT_MOC_LITERAL(30, 430, 21), // "slotSelectFontChanged"
QT_MOC_LITERAL(31, 452, 4), // "font"
QT_MOC_LITERAL(32, 457, 27), // "slotSceneTextLeftBtnPressed"
QT_MOC_LITERAL(33, 485, 3), // "pos"
QT_MOC_LITERAL(34, 489, 10), // "bIsPressed"
QT_MOC_LITERAL(35, 500, 19), // "slotEditTextChanged"
QT_MOC_LITERAL(36, 520, 20) // "slotBtnCancelClicked"
},
"fullScreenWidget\0finishPixmap\0\0"
"exitPixmap\0finishedshot\0cmd\0"
"signalChangeCurrentShape\0Shape::Code\0"
"pen\0signalDeleteLastDraw\0"
"signalSelectPenChanged\0signalSelectFontChanged\0"
"signalAddTextToView\0loadBackgroundPixmap\0"
"bgPixmap\0x\0y\0width\0height\0exitShotScreen\0"
"iscancel\0savePixmap\0finishScreenShot\0"
"slotDrawRectClicked\0slotDrawEllipseClicked\0"
"slotDrawArrowClicked\0slotDrawTextClicked\0"
"slotDrawPathClicked\0slotRevokeClicked\0"
"slotSelectPenChanged\0slotSelectFontChanged\0"
"font\0slotSceneTextLeftBtnPressed\0pos\0"
"bIsPressed\0slotEditTextChanged\0"
"slotBtnCancelClicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_fullScreenWidget[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
25, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
8, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 139, 2, 0x06 /* Public */,
3, 0, 142, 2, 0x06 /* Public */,
4, 1, 143, 2, 0x06 /* Public */,
6, 2, 146, 2, 0x06 /* Public */,
9, 0, 151, 2, 0x06 /* Public */,
10, 1, 152, 2, 0x06 /* Public */,
11, 2, 155, 2, 0x06 /* Public */,
12, 1, 160, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
13, 1, 163, 2, 0x0a /* Public */,
13, 5, 166, 2, 0x0a /* Public */,
19, 1, 177, 2, 0x0a /* Public */,
19, 0, 180, 2, 0x2a /* Public | MethodCloned */,
21, 0, 181, 2, 0x0a /* Public */,
22, 0, 182, 2, 0x0a /* Public */,
23, 0, 183, 2, 0x0a /* Public */,
24, 0, 184, 2, 0x0a /* Public */,
25, 0, 185, 2, 0x0a /* Public */,
26, 0, 186, 2, 0x0a /* Public */,
27, 0, 187, 2, 0x0a /* Public */,
28, 0, 188, 2, 0x0a /* Public */,
29, 1, 189, 2, 0x0a /* Public */,
30, 2, 192, 2, 0x0a /* Public */,
32, 2, 197, 2, 0x0a /* Public */,
35, 0, 202, 2, 0x0a /* Public */,
36, 0, 203, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::QPixmap, 1,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 5,
QMetaType::Void, 0x80000000 | 7, QMetaType::QPen, 2, 8,
QMetaType::Void,
QMetaType::Void, QMetaType::QPen, 2,
QMetaType::Void, QMetaType::QPen, QMetaType::QFont, 2, 2,
QMetaType::Void, QMetaType::QString, 2,
// slots: parameters
QMetaType::Void, QMetaType::QPixmap, 14,
QMetaType::Void, QMetaType::QPixmap, QMetaType::Int, QMetaType::Int, QMetaType::Int, QMetaType::Int, 14, 15, 16, 17, 18,
QMetaType::Void, QMetaType::Bool, 20,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QPen, 8,
QMetaType::Void, QMetaType::QPen, QMetaType::QFont, 8, 31,
QMetaType::Void, QMetaType::QPointF, QMetaType::Bool, 33, 34,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void fullScreenWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<fullScreenWidget *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->finishPixmap((*reinterpret_cast< const QPixmap(*)>(_a[1]))); break;
case 1: _t->exitPixmap(); break;
case 2: _t->finishedshot((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 3: _t->signalChangeCurrentShape((*reinterpret_cast< Shape::Code(*)>(_a[1])),(*reinterpret_cast< QPen(*)>(_a[2]))); break;
case 4: _t->signalDeleteLastDraw(); break;
case 5: _t->signalSelectPenChanged((*reinterpret_cast< QPen(*)>(_a[1]))); break;
case 6: _t->signalSelectFontChanged((*reinterpret_cast< QPen(*)>(_a[1])),(*reinterpret_cast< QFont(*)>(_a[2]))); break;
case 7: _t->signalAddTextToView((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 8: _t->loadBackgroundPixmap((*reinterpret_cast< const QPixmap(*)>(_a[1]))); break;
case 9: _t->loadBackgroundPixmap((*reinterpret_cast< const QPixmap(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4])),(*reinterpret_cast< int(*)>(_a[5]))); break;
case 10: _t->exitShotScreen((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 11: _t->exitShotScreen(); break;
case 12: _t->savePixmap(); break;
case 13: _t->finishScreenShot(); break;
case 14: _t->slotDrawRectClicked(); break;
case 15: _t->slotDrawEllipseClicked(); break;
case 16: _t->slotDrawArrowClicked(); break;
case 17: _t->slotDrawTextClicked(); break;
case 18: _t->slotDrawPathClicked(); break;
case 19: _t->slotRevokeClicked(); break;
case 20: _t->slotSelectPenChanged((*reinterpret_cast< QPen(*)>(_a[1]))); break;
case 21: _t->slotSelectFontChanged((*reinterpret_cast< QPen(*)>(_a[1])),(*reinterpret_cast< QFont(*)>(_a[2]))); break;
case 22: _t->slotSceneTextLeftBtnPressed((*reinterpret_cast< QPointF(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
case 23: _t->slotEditTextChanged(); break;
case 24: _t->slotBtnCancelClicked(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (fullScreenWidget::*)(const QPixmap );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::finishPixmap)) {
*result = 0;
return;
}
}
{
using _t = void (fullScreenWidget::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::exitPixmap)) {
*result = 1;
return;
}
}
{
using _t = void (fullScreenWidget::*)(QString );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::finishedshot)) {
*result = 2;
return;
}
}
{
using _t = void (fullScreenWidget::*)(Shape::Code , QPen );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::signalChangeCurrentShape)) {
*result = 3;
return;
}
}
{
using _t = void (fullScreenWidget::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::signalDeleteLastDraw)) {
*result = 4;
return;
}
}
{
using _t = void (fullScreenWidget::*)(QPen );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::signalSelectPenChanged)) {
*result = 5;
return;
}
}
{
using _t = void (fullScreenWidget::*)(QPen , QFont );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::signalSelectFontChanged)) {
*result = 6;
return;
}
}
{
using _t = void (fullScreenWidget::*)(QString );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&fullScreenWidget::signalAddTextToView)) {
*result = 7;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject fullScreenWidget::staticMetaObject = { {
&QWidget::staticMetaObject,
qt_meta_stringdata_fullScreenWidget.data,
qt_meta_data_fullScreenWidget,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *fullScreenWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *fullScreenWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_fullScreenWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int fullScreenWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 25)
qt_static_metacall(this, _c, _id, _a);
_id -= 25;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 25)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 25;
}
return _id;
}
// SIGNAL 0
void fullScreenWidget::finishPixmap(const QPixmap _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void fullScreenWidget::exitPixmap()
{
QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}
// SIGNAL 2
void fullScreenWidget::finishedshot(QString _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
// SIGNAL 3
void fullScreenWidget::signalChangeCurrentShape(Shape::Code _t1, QPen _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
// SIGNAL 4
void fullScreenWidget::signalDeleteLastDraw()
{
QMetaObject::activate(this, &staticMetaObject, 4, nullptr);
}
// SIGNAL 5
void fullScreenWidget::signalSelectPenChanged(QPen _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 5, _a);
}
// SIGNAL 6
void fullScreenWidget::signalSelectFontChanged(QPen _t1, QFont _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 6, _a);
}
// SIGNAL 7
void fullScreenWidget::signalAddTextToView(QString _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 7, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 38.90113
| 239
| 0.609469
|
cheechang
|
67800f90ec79ad1afddbd9c4cf721fc8a405b323
| 752
|
hpp
|
C++
|
src/math/mat2.hpp
|
simonfxr/gl
|
11705f718d27657fc76243d59a251f49c0a41486
|
[
"MIT"
] | null | null | null |
src/math/mat2.hpp
|
simonfxr/gl
|
11705f718d27657fc76243d59a251f49c0a41486
|
[
"MIT"
] | null | null | null |
src/math/mat2.hpp
|
simonfxr/gl
|
11705f718d27657fc76243d59a251f49c0a41486
|
[
"MIT"
] | null | null | null |
#ifndef MATH_MAT2_HPP
#define MATH_MAT2_HPP
#include "math/genmat.hpp"
namespace math {
using mat2_t = genmat<real, 2>;
constexpr mat2_t
mat2()
{
return mat2_t::identity();
}
constexpr mat2_t
mat2(real x)
{
return mat2_t::fill(x);
}
template<typename T>
constexpr mat2_t
mat2(const genmat<T, 2> &A)
{
return mat2_t::convert(A);
}
constexpr mat2_t
mat2(mat2_t::buffer b)
{
return mat2_t::load(b);
}
constexpr mat2_t
mat2(const genvec<real, 2> &c1, const genvec<real, 2> &c2)
{
return mat2_t::make(c1, c2);
}
constexpr mat2_t
mat2(const genmat<real, 3> &A)
{
mat2_t B{};
for (size_t i = 0; i < 2; ++i)
for (size_t j = 0; j < 2; ++j)
B[i][j] = A[i][j];
return B;
}
} // namespace math
#endif
| 13.925926
| 58
| 0.62367
|
simonfxr
|
6783defb9c837966b097ecad6ae9876a83d5ce20
| 43,237
|
hpp
|
C++
|
task-movement/Koala/container/assoctab.hpp
|
miloszc/task-movement
|
26b40595b590b0fcc3c226fbe8576faa3b5c1244
|
[
"MIT"
] | null | null | null |
task-movement/Koala/container/assoctab.hpp
|
miloszc/task-movement
|
26b40595b590b0fcc3c226fbe8576faa3b5c1244
|
[
"MIT"
] | 19
|
2019-02-15T09:04:22.000Z
|
2020-06-23T21:42:29.000Z
|
task-movement/Koala/container/assoctab.hpp
|
miloszc/task-movement
|
26b40595b590b0fcc3c226fbe8576faa3b5c1244
|
[
"MIT"
] | 1
|
2019-05-04T16:12:25.000Z
|
2019-05-04T16:12:25.000Z
|
// AssocTabConstInterface
template< class K, class V > V AssocTabConstInterface< std::map< K,V > >::operator[]( K arg ) const
{
koalaAssert( !Privates::ZeroAssocKey<K>::isZero(arg),ContExcOutpass );
typename std::map< K,V >::const_iterator i;
i = cont.find( arg );
if (i == cont.end()) return V();
else return i->second;
}
template< class K, class V > V &AssocTabConstInterface< std::map< K,V > >::get( K arg )
{
koalaAssert( !Privates::ZeroAssocKey<K>::isZero(arg),ContExcOutpass );
return (_cont())[arg];
}
template< class K, class V > typename AssocTabConstInterface< std::map< K,V > >::ValType
*AssocTabConstInterface< std::map< K,V > >::valPtr( K arg )
{
koalaAssert( !Privates::ZeroAssocKey<K>::isZero(arg),ContExcOutpass );
typename std::map< K,V >::iterator i = _cont().find( arg );
if (i == _cont().end()) return NULL;
else return &(_cont())[arg];
}
template< class K, class V > bool AssocTabConstInterface< std::map< K,V > >::delKey( K arg )
{
typename std::map< K,V >::iterator pos = _cont().find( arg );
if (pos == _cont().end()) return false;
_cont().erase( pos );
return true;
}
template< class K, class V > K AssocTabConstInterface<std::map< K,V > >::firstKey() const
{
if (cont.begin() == cont.end()) return Privates::ZeroAssocKey<K>::zero();
return cont.begin()->first;
}
template< class K, class V > K AssocTabConstInterface<std::map< K,V > >::lastKey() const
{
typename std::map< K,V >::const_iterator pos;
if (cont.begin() == (pos = cont.end())) return Privates::ZeroAssocKey<K>::zero();
pos--;
return pos->first;
}
template< class K, class V > K AssocTabConstInterface<std::map< K,V > >::prevKey( K arg ) const
{
if (Privates::ZeroAssocKey<K>::isZero(arg)) return lastKey();
typename std::map< K,V >::const_iterator pos = cont.find( arg );
koalaAssert( pos != cont.end(),ContExcOutpass );
if (pos == cont.begin()) return Privates::ZeroAssocKey<K>::zero();
pos--;
return pos->first;
}
template< class K, class V > K AssocTabConstInterface<std::map< K,V > >::nextKey( K arg ) const
{
if (Privates::ZeroAssocKey<K>::isZero(arg)) return firstKey();
typename std::map< K,V >::const_iterator pos = cont.find( arg );
koalaAssert( pos != cont.end(),ContExcOutpass );
pos++;
if (pos == cont.end()) return Privates::ZeroAssocKey<K>::zero();
return pos->first;
}
template< class K, class V > template< class Iterator >
int AssocTabConstInterface< std::map< K,V > >::getKeys( Iterator iter ) const
{
for( K key = firstKey(); !Privates::ZeroAssocKey<K>::isZero(key); key = nextKey( key ) )
{
*iter = key;
iter++;
}
return size();
}
// AssocTabInterface
template< class T > AssocTabInterface< T > &AssocTabInterface< T >::operator=( const AssocTabInterface< T > &arg )
{
if (&arg.cont == &cont) return *this;
clear();
for( KeyType k = arg.firstKey(); !Privates::ZeroAssocKey<KeyType>::isZero(k); k = arg.nextKey( k ) ) operator[]( k ) = arg[k];
return *this;
}
template< class T > AssocTabInterface< T > &AssocTabInterface< T >::operator=( const AssocTabConstInterface< T > &arg )
{
if (&arg.cont == &cont) return *this;
clear();
for( KeyType k = arg.firstKey(); !Privates::ZeroAssocKey<KeyType>::isZero(k); k = arg.nextKey( k ) ) operator[]( k )=arg[k];
return *this;
}
template< class T > template< class AssocCont >
AssocTabInterface< T > &AssocTabInterface< T >::operator=( const AssocCont &arg )
{
Privates::AssocTabTag< KeyType >::operator=( arg );
clear();
for( KeyType k = arg.firstKey(); !Privates::ZeroAssocKey<KeyType>::isZero(k); k = arg.nextKey( k ) ) operator[]( k )=arg[k];
return *this;
}
// AssocTable
template< class T > AssocTable< T > &AssocTable< T >::operator=( const AssocTable< T > &X )
{
if (this == &X) return *this;
cont = X.cont;
return *this;
}
template< class T > AssocTable< T > &AssocTable< T >::operator=( const T &X )
{
if (&cont == &X) return *this;
cont = X;
return *this;
}
template< class T > template< class AssocCont >
AssocTable< T > &AssocTable< T >::operator=( const AssocCont &arg )
{
Privates::AssocTabTag< typename AssocTabInterface< T >::KeyType >::operator=( arg );
if (Privates::asssocTabInterfTest( arg ) == &cont) return *this;
clear();
for( typename AssocTabInterface< T >::KeyType k = arg.firstKey(); !Privates::ZeroAssocKey<KeyType>::isZero(k); k = arg.nextKey( k ) )
operator[]( k ) = arg[k];
return *this;
}
// AssocContReg
AssocKeyContReg &AssocKeyContReg::operator=( const AssocKeyContReg &X )
{
if (&X != this) next = 0;
return *this;
}
AssocContReg *AssocKeyContReg::find( AssocContBase *cont )
{
AssocContReg *res;
for( res = this; res->next; res= &(res->next->getReg( res->nextPos )) )
if (res->next == cont) return res;
return NULL;
}
void AssocKeyContReg::deregister()
{
std::pair< AssocContBase *,int > a = std::pair< AssocContBase *,int >( next,nextPos ), n;
next = 0;
while (a.first)
{
AssocContReg *p = &a.first->getReg( a.second );
n = std::pair< AssocContBase *,int >( p->next,p->nextPos );
a.first->DelPosCommand( a.second );
a = n;
}
}
// AssocArray
template< class Klucz, class Elem, class Container > template< class AssocCont >
AssocArray< Klucz,Elem,Container > &AssocArray< Klucz,Elem,Container >::operator=( const AssocCont &arg )
{
Privates::AssocTabTag< Klucz >::operator=( arg );
clear();
for( Klucz k = arg.firstKey(); k; k = arg.nextKey( k ) ) operator[]( k ) = arg[k];
return *this;
}
template< class Klucz, class Elem, class Container > Elem *AssocArray< Klucz,Elem,Container >::valPtr( Klucz v )
{
int x = keyPos( v );
if (x == -1) return NULL;
else return &tab[x].val;
}
template< class Klucz, class Elem, class Container >
AssocArray< Klucz,Elem,Container >::AssocArray( const AssocArray< Klucz,Elem,Container > &X ):
tab(X.tab)
{
for( int i = tab.firstPos(); i != -1; i = tab.nextPos( i ) )
{
tab[i].assocReg = tab[i].key->assocReg;
tab[i].key->assocReg.next = this;
tab[i].key->assocReg.nextPos = i;
}
}
template< class Klucz, class Elem, class Container > AssocArray< Klucz,Elem,Container >
&AssocArray< Klucz,Elem,Container >::operator=( const AssocArray< Klucz,Elem,Container > &X )
{
if (&X == this) return *this;
clear();
tab = X.tab;
for( int i = tab.firstPos(); i != -1; i = tab.nextPos( i ) )
{
tab[i].assocReg = tab[i].key->assocReg;
tab[i].key->assocReg.next = this;
tab[i].key->assocReg.nextPos = i;
}
return *this;
}
template< class Klucz, class Elem, class Container > int AssocArray< Klucz,Elem,Container >::keyPos( Klucz v ) const
{
if (!v) return -1;
AssocContReg *preg = v->assocReg.find( const_cast<AssocArray< Klucz,Elem,Container > * > (this) );
if (preg) return preg->nextPos;
else return -1;
}
template< class Klucz, class Elem, class Container > bool AssocArray< Klucz,Elem,Container >::delKey( Klucz v )
{
int x;
if (!v) return false;
AssocContReg *preg = v->assocReg.find( this );
if (!preg) return false;
x = preg->nextPos;
*preg = tab[x].assocReg;
tab.delPos( x );
return true;
}
template< class Klucz, class Elem, class Container > Klucz AssocArray< Klucz,Elem,Container >::firstKey() const
{
if (tab.empty()) return 0;
else return tab[tab.firstPos()].key;
}
template< class Klucz, class Elem, class Container > Klucz AssocArray< Klucz,Elem,Container >::lastKey() const
{
if (tab.empty()) return 0;
else return tab[tab.lastPos()].key;
}
template< class Klucz, class Elem, class Container > Klucz AssocArray< Klucz,Elem,Container >::nextKey( Klucz v ) const
{
if (!v) return firstKey();
int x= keyPos( v );
koalaAssert( x != -1,ContExcOutpass );
if ((x = tab.nextPos( x )) == -1) return 0;
return tab[x].key;
}
template< class Klucz, class Elem, class Container > Klucz AssocArray< Klucz,Elem,Container >::prevKey( Klucz v ) const
{
if (!v) return lastKey();
int x = keyPos( v );
koalaAssert( x != -1,ContExcOutpass );
if ((x = tab.prevPos( x )) == -1) return 0;
return tab[x].key;
}
template< class Klucz, class Elem, class Container > Elem &AssocArray< Klucz,Elem,Container >::operator[]( Klucz v )
{
koalaAssert( v,ContExcWrongArg );
int x = keyPos( v );
if (x == -1)
{
x = tab.newPos();
tab[x].key = v;
tab[x].assocReg = v->assocReg;
v->assocReg.next = this;
v->assocReg.nextPos = x;
}
return tab[x].val;
}
template< class Klucz, class Elem, class Container > Elem AssocArray< Klucz,Elem,Container >::operator[]( Klucz v ) const
{
koalaAssert( v,ContExcWrongArg );
int x = keyPos( v );
if (x == -1) return Elem();
return tab[x].val;
}
template< class Klucz, class Elem, class Container > void AssocArray< Klucz,Elem,Container >::defrag()
{
tab.defrag();
for( int i = 0; i < tab.size(); i++ )
tab[i].key->assocReg.find( this )->nextPos = i;
}
template< class Klucz, class Elem, class Container > void AssocArray< Klucz,Elem,Container >::clear()
{
for( Klucz v = firstKey(); v; v = firstKey() ) delKey( v );
}
template< class Klucz, class Elem, class Container > template< class Iterator >
int AssocArray< Klucz,Elem,Container >::getKeys( Iterator iter ) const
{
for( Klucz key = firstKey(); key; key = nextKey( key ) )
{
*iter = key;
iter++;
}
return size();
}
namespace Privates {
// PseudoAssocArray
template< class Klucz, class Elem, class AssocCont, class Container > template< class AssocCont2 >
PseudoAssocArray< Klucz,Elem,AssocCont,Container >
&PseudoAssocArray< Klucz,Elem,AssocCont,Container >::operator=( const AssocCont2 &arg )
{
Privates::AssocTabTag< Klucz >::operator=( arg );
clear();
for( Klucz k = arg.firstKey(); k; k = arg.nextKey( k ) ) operator[]( k ) = arg[k];
return *this;
}
template< class Klucz, class Elem, class AssocCont, class Container >
int PseudoAssocArray< Klucz,Elem,AssocCont,Container >::keyPos( Klucz v ) const
{
if (!v) return -1;
if (!assocTab.hasKey( v )) return -1;
return assocTab[v];
}
template< class Klucz, class Elem, class AssocCont, class Container >
bool PseudoAssocArray< Klucz,Elem,AssocCont,Container >::delKey( Klucz v )
{
if (!v) return false;
if (!assocTab.hasKey( v )) return false;
tab.delPos( assocTab[v] );
assocTab.delKey( v );
return true;
}
template< class Klucz, class Elem, class AssocCont, class Container >
Klucz PseudoAssocArray< Klucz,Elem,AssocCont,Container >::firstKey() const
{
if (tab.empty()) return 0;
else return tab[tab.firstPos()].key;
}
template< class Klucz, class Elem, class AssocCont, class Container >
Klucz PseudoAssocArray< Klucz,Elem,AssocCont,Container >::lastKey() const
{
if (tab.empty()) return 0;
else return tab[tab.lastPos()].key;
}
template< class Klucz, class Elem, class AssocCont, class Container >
Klucz PseudoAssocArray< Klucz,Elem,AssocCont,Container >::nextKey( Klucz v ) const
{
if (!v) return firstKey();
int x = keyPos( v );
koalaAssert( x != -1,ContExcOutpass );
if ((x = tab.nextPos( x )) == -1) return 0;
return tab[x].key;
}
template< class Klucz, class Elem, class AssocCont, class Container >
Klucz PseudoAssocArray< Klucz,Elem,AssocCont,Container >::prevKey( Klucz v ) const
{
if (!v) return lastKey();
int x = keyPos( v );
koalaAssert( x != -1,ContExcOutpass );
if ((x = tab.prevPos( x )) == -1) return 0;
return tab[x].key;
}
template< class Klucz, class Elem, class AssocCont, class Container >
Elem &PseudoAssocArray< Klucz,Elem,AssocCont,Container >::operator[]( Klucz v )
{
koalaAssert( v,ContExcWrongArg );
int x = keyPos( v );
if (x == -1)
{
tab[x = tab.newPos()].key = v;
assocTab[v] = x;
}
return tab[x].val;
}
template< class Klucz, class Elem, class AssocCont, class Container >
Elem PseudoAssocArray< Klucz,Elem,AssocCont,Container >::operator[]( Klucz v ) const
{
koalaAssert( v,ContExcOutpass );
int x = keyPos( v );
if (x == -1) return Elem();
return tab[x].val;
}
template< class Klucz, class Elem, class AssocCont, class Container >
void PseudoAssocArray< Klucz,Elem,AssocCont,Container >::defrag()
{
tab.defrag();
for( int i = 0; i < tab.size(); i++ ) assocTab[tab[i].key] = i;
}
template< class Klucz, class Elem, class AssocCont, class Container > template< class Iterator >
int PseudoAssocArray< Klucz,Elem,AssocCont,Container >::getKeys( Iterator iter ) const
{
for( Klucz key = firstKey(); key; key = nextKey( key ) )
{
*iter = key;
iter++;
}
return size();
}
template< class Klucz, class Elem, class AssocCont, class Container >
void PseudoAssocArray< Klucz,Elem,AssocCont,Container >::reserve( int arg )
{
tab.reserve( arg );
assocTab.reserve( arg );
}
template< class Klucz, class Elem, class AssocCont, class Container >
Elem *PseudoAssocArray< Klucz,Elem,AssocCont,Container >::valPtr( Klucz v )
{
int x = keyPos( v );
if (x == -1) return NULL;
else return &tab[x].val;
}
template< class Klucz, class Elem, class AssocCont, class Container >
void PseudoAssocArray< Klucz,Elem,AssocCont,Container >::clear()
{
tab.clear();
assocTab.clear();
}
}
// Assoc2DimTabAddr
inline int Assoc2DimTabAddr< AMatrFull >::wsp2pos( std::pair< int,int > w ) const
{
int mfs = std::max( w.first,w.second );
return mfs * mfs + mfs + w.second - w.first;
}
inline std::pair< int,int > Assoc2DimTabAddr< AMatrFull >::pos2wsp( int pos ) const
{
int x = (int)sqrt( (double)pos );
if (x * x + x - pos > 0) return std::pair< int,int >( x,pos - x * x );
else return std::pair< int,int >( x * x + 2 * x - pos,x );
}
inline int Assoc2DimTabAddr< AMatrNoDiag >::wsp2pos( std::pair< int,int > w ) const
{
int mfs = std::max( w.first,w.second );
return mfs * mfs + w.second - w.first - ((w.first > w.second) ? 0 : 1);
}
inline std::pair< int,int > Assoc2DimTabAddr< AMatrNoDiag >::pos2wsp( int pos ) const
{
int x = (int)sqrt( (double)pos );
if (pos - x * x - x >= 0) return std::pair< int,int >( x + 1,pos - x * x - x );
else return std::pair< int,int >( x * x + x - 1 - pos,x );
}
inline int Assoc2DimTabAddr< AMatrClTriangle >::wsp2pos( std::pair< int,int > w ) const
{
if (w.first < w.second)
{
int z = w.first;
w.first = w.second;
w.second = z;
}
return w.first * (w.first + 1) / 2 + w.second;
}
inline std::pair< int,int > Assoc2DimTabAddr< AMatrClTriangle >::pos2wsp( int pos ) const
{
int x = (int)sqrt( (double)2 * pos ), xx = pos - x * (x + 1) / 2;
if (xx >= 0) return std::pair< int,int >( x,xx );
else return std::pair< int,int >( x - 1,xx + x );
}
inline int Assoc2DimTabAddr< AMatrTriangle >::wsp2pos( std::pair< int,int > w ) const
{
if (w.first < w.second)
{
int z = w.first;
w.first = w.second;
w.second = z;
}
return w.first * (w.first - 1) / 2 + w.second;
}
inline std::pair< int,int > Assoc2DimTabAddr< AMatrTriangle >::pos2wsp( int pos ) const
{
int x = (int)sqrt( (double)2 * pos ), xx = pos - x * (x + 1) / 2;
if (xx >= 0) return std::pair< int,int >( x + 1,xx );
else return std::pair< int,int >( x,xx + x );
}
// AssocMatrix
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Klucz AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::AssocIndex::pos2klucz( int arg )
{
if (arg == -1) return 0;
return IndexContainer::tab[arg].key;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::AssocIndex::DelPosCommand( int pos )
{
int LOCALARRAY( tabpos,IndexContainer::size() );
int l = 0;
int i = IndexContainer::tab.firstPos();
for( ; i != -1; i = IndexContainer::tab.nextPos( i ) )
tabpos[l++] = i;
for( l--; l >= 0; l-- )
{
owner->delPos( std::pair< int,int >( pos,tabpos[l] ) );
if ((aType == AMatrNoDiag || aType == AMatrFull) && (pos != tabpos[l]))
owner->delPos( std::pair< int,int >( tabpos[l],pos ) );
}
IndexContainer::tab.delPos( pos );
Klucz LOCALARRAY(keytab,IndexContainer::size() );
int res=this->getKeys(keytab);
for( int j=0;j<res;j++)
if (!this->operator[]( keytab[j] )) IndexContainer::delKey( keytab[j] );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::delPos( std::pair< int,int > wsp )
{
if (!Assoc2DimTabAddr< aType >::correctPos( wsp.first,wsp.second )) return;
int x;
if (!bufor[x = Assoc2DimTabAddr< aType >::wsp2pos( wsp )].present()) return;
if (bufor[x].next != -1) bufor[bufor[x].next].prev = bufor[x].prev;
else last = bufor[x].prev;
if (bufor[x].prev != -1) bufor[bufor[x].prev].next = bufor[x].next;
else first = bufor[x].next;
bufor[x] = Privates::BlockOfAssocMatrix< Elem >();
siz--;
--index.tab[wsp.first].val;
--index.tab[wsp.second].val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::AssocMatrix( int asize):
index( asize ), siz( 0 ), first( -1 ), last( -1 )
{
bufor.clear();
bufor.reserve( Assoc2DimTabAddr< aType >::bufLen( asize ) );
index.owner = this;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >
&AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::operator=(
const AssocMatrix< Klucz,Elem,aType,Container,IndexContainer > &X )
{
if (&X == this) return *this;
index = X.index;
bufor = X.bufor;
siz = X.siz;
first = X.first;
last = X.last;
index.owner = this;
return *this;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
bool AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::delInd( Klucz v )
{
if (!hasInd( v )) return false;
Klucz LOCALARRAY( tab,index.size() );
int i = 0;
for( Klucz x = index.firstKey(); x; x = index.nextKey( x ) ) tab[i++] = x;
for( i--; i >= 0; i-- )
{
delKey( v,tab[i] );
if ((aType == AMatrNoDiag || aType == AMatrFull) && (v != tab[i]))
delKey( tab[i],v );
}
index.delKey( v );
return true;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template <class ExtCont>
int AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::slice1( Klucz v, ExtCont &tab ) const
{
if (!index.hasKey( v )) return 0;
int licz = 0;
for( Klucz x = index.firstKey(); x; x = index.nextKey( x ) )
if (hasKey( v,x ))
{
tab[x] = this->operator()( v,x );
licz++;
}
return licz;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template<class ExtCont >
int AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::slice2( Klucz v, ExtCont &tab ) const
{
if (!index.hasKey( v )) return 0;
int licz = 0;
for( Klucz x = index.firstKey(); x; x = index.nextKey( x ) )
if (hasKey( x,v ))
{
tab[x] = this->operator()( x,v );
licz++;
}
return licz;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
bool AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::hasKey( Klucz u, Klucz v ) const
{
if (!u || !v) return false;
if (!Assoc2DimTabAddr< aType >::correctPos( u,v )) return false;
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return false;
return bufor[Assoc2DimTabAddr< aType >::wsp2pos( wsp )].present();
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
bool AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::delKey( Klucz u, Klucz v )
{
if (!u || !v) return false;
if (!Assoc2DimTabAddr< aType >::correctPos( u,v )) return false;
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return false;
int x;
if (bufor[x = Assoc2DimTabAddr< aType >::wsp2pos( wsp )].present())
{
if (bufor[x].next != -1) bufor[bufor[x].next].prev = bufor[x].prev;
else last = bufor[x].prev;
if (bufor[x].prev != -1) bufor[bufor[x].prev].next = bufor[x].next;
else first = bufor[x].next;
bufor[x] = Privates::BlockOfAssocMatrix< Elem >();
siz--;
if (--index[u] == 0) index.delKey( u );
if (--index[v] == 0) index.delKey( v );
return true;
}
return false;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Elem &AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::operator()( Klucz u, Klucz v )
{
koalaAssert( u && v && Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1)
{
index[u] = 0;
wsp.first = index.klucz2pos( u );
}
if (wsp.second == -1)
{
index[v] = 0;
wsp.second = index.klucz2pos( v );
}
bufor.resize( std::max( (int)bufor.size(),Assoc2DimTabAddr< aType >::bufLen( index.size() ) ) );
int x = Assoc2DimTabAddr< aType >::wsp2pos( wsp );
if (!bufor[x].present())
{
if ((bufor[x].prev = last) == -1) first = x;
else bufor[bufor[x].prev].next = x;
bufor[x].next = -1;
last = x;
index[u]++;
index[v]++;
siz++;
}
return bufor[x].val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Elem AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::operator()( Klucz u, Klucz v ) const
{
koalaAssert( u && v && Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return Elem();
int x = Assoc2DimTabAddr< aType >::wsp2pos( wsp );
if (!bufor[x].present()) return Elem();
return bufor[x].val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Elem* AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::valPtr( Klucz u, Klucz v )
{
koalaAssert( u && v && Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return NULL;
int pos;
if (!bufor[pos = Assoc2DimTabAddr< aType >::wsp2pos( wsp )].present()) return NULL;
return &bufor[pos].val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
std::pair< Klucz,Klucz > AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::firstKey() const
{
if (!siz) return std::pair< Klucz,Klucz >( (Klucz)0,(Klucz)0 );
std::pair< int,int > wsp = Assoc2DimTabAddr< aType >::pos2wsp( first );
return Assoc2DimTabAddr< aType >::key( std::pair< Klucz,Klucz >( index.pos2klucz( wsp.first ),
index.pos2klucz( wsp.second ) ) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
std::pair< Klucz,Klucz > AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::lastKey() const
{
if (!siz) return std::pair< Klucz,Klucz >( (Klucz)0,(Klucz)0 );
std::pair< int,int > wsp = Assoc2DimTabAddr< aType >::pos2wsp( last );
return Assoc2DimTabAddr< aType >::key( std::pair< Klucz,Klucz >( index.pos2klucz( wsp.first ),
index.pos2klucz( wsp.second ) ) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
std::pair< Klucz,Klucz > AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::nextKey( Klucz u, Klucz v ) const
{
if (!u || !v) return firstKey();
koalaAssert( Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
koalaAssert( wsp.first != -1 && wsp.second != -1,ContExcOutpass );
int x = Assoc2DimTabAddr< aType >::wsp2pos( wsp );
koalaAssert( bufor[x].present(),ContExcOutpass );
x = bufor[x].next;
if (x == -1) return std::pair< Klucz,Klucz >( (Klucz)0,(Klucz)0 );
wsp = Assoc2DimTabAddr< aType >::pos2wsp( x );
return Assoc2DimTabAddr< aType >::key( std::pair< Klucz,Klucz >( index.pos2klucz( wsp.first ),
index.pos2klucz( wsp.second ) ) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template< class MatrixContainer > AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >
&AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::operator=( const MatrixContainer &X )
{
Privates::Assoc2DimTabTag< Klucz,aType >::operator=( X );
this->clear();
int rozm;
std::pair<Klucz,Klucz> LOCALARRAY(tab,rozm=X.size());
X.getKeys(tab);
for( int i=0;i<rozm;i++ )
this->operator()( tab[i] )=X( tab[i] );
return *this;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
std::pair< Klucz,Klucz > AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::prevKey( Klucz u, Klucz v ) const
{
if (!u || !v) return lastKey();
koalaAssert( Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
koalaAssert( wsp.first != -1 && wsp.second != -1,ContExcOutpass );
int x = Assoc2DimTabAddr< aType >::wsp2pos( wsp );
koalaAssert( bufor[x].present(),ContExcOutpass );
x = bufor[x].prev;
if (x == -1) return std::pair< Klucz,Klucz >( (Klucz)0,(Klucz)0 );
wsp = Assoc2DimTabAddr< aType >::pos2wsp( x );
return Assoc2DimTabAddr< aType >::key( std::pair< Klucz,Klucz >(index.pos2klucz( wsp.first ),
index.pos2klucz( wsp.second ) ) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::clear()
{
index.clear();
int in;
for( int i = first; i != -1; i = in )
{
in = bufor[i].next;
bufor[i] = Privates::BlockOfAssocMatrix< Elem >();
}
siz = 0;
first = last = -1;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::reserve( int arg )
{
index.reserve( arg );
bufor.reserve( Assoc2DimTabAddr< aType >::bufLen( arg ) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::defrag()
{
DefragMatrixPom LOCALARRAY( tab,siz );
int i=0;
for( int pos = first; pos != -1; pos = bufor[pos].next )
{
tab[i].val = bufor[pos].val;
std::pair< int,int > wsp = Assoc2DimTabAddr< aType >::pos2wsp( pos );
tab[i].u = index.pos2klucz( wsp.first );
tab[i].v = index.pos2klucz( wsp.second );
i++;
}
bufor.clear();
index.clear();
index.defrag();
{
Container tmp;
bufor.swap(tmp);
}
siz = 0;
first = last = -1;
for( int ii = 0; ii < i ; ii++ ) this->operator()( tab[ii].u,tab[ii].v ) = tab[ii].val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer > template< class Iterator >
int AssocMatrix< Klucz,Elem,aType,Container,IndexContainer >::getKeys( Iterator iter ) const
{
for( std::pair< Klucz,Klucz > key = firstKey(); key.first; key = nextKey( key ) )
{
*iter = key;
iter++;
}
return size();
}
//template<class Klucz, class Elem, AssocMatrixType aType, class C, class IC >
// std::ostream &operator<<( std::ostream &out, const AssocMatrix< Klucz,Elem,aType,C,IC > &cont )
//{
// out << '{';
// int siz = cont.size();
// std::pair< typename AssocMatrix< Klucz,Elem,aType,C,IC >::KeyType,typename AssocMatrix< Klucz,Elem,aType,C,IC >::KeyType >
// key = cont.firstKey();
// for( ; siz; siz-- )
// {
// out << '(' << key.first << ',' << key.second << ':'<< cont(key) << ')';
// if (siz>1)
// {
// key = cont.nextKey( key );
// out << ',';
// }
// }
// out << '}';
// return out;
//}
// AssocInserter
template< class T > template< class K, class V >
AssocInserter< T > &AssocInserter< T >::operator=( const std::pair< K,V > &pair )
{
(*container)[(typename T::KeyType)pair.first] = (typename T::ValType)pair.second;
return *this;
}
template< class T, class Fun > template< class K >
AssocFunctorInserter< T,Fun > &AssocFunctorInserter< T,Fun >::operator=( const K &arg )
{
(*container)[(typename T::KeyType)arg] = (typename T::ValType)functor( arg );
return *this;
}
template< class Cont,class K > std::ostream &Privates::printAssoc( std::ostream &out, const Cont &cont,Privates::AssocTabTag< K > )
{
out << '{';
int siz = cont.size();
typename Cont::KeyType key = cont.firstKey();
for( ; siz; siz-- )
{
out << '(' << key << ',' << cont[key] << ')';
if (key != cont.lastKey())
{
key = cont.nextKey( key );
out << ',';
}
}
out << '}';
return out;
}
template< class Cont,class K,AssocMatrixType aType > std::ostream &Privates::printAssoc( std::ostream &out, const Cont &cont, Privates::Assoc2DimTabTag< K,aType > )
{
out << '{';
int siz = cont.size();
std::pair< typename Cont::KeyType,typename Cont::KeyType >
key = cont.firstKey();
for( ; siz; siz-- )
{
out << '(' << key.first << ',' << key.second << ':'<< cont(key) << ')';
if (siz>1)
{
key = cont.nextKey( key );
out << ',';
}
}
out << '}';
return out;
}
template< AssocMatrixType aType, class Container>
Assoc2DimTable< aType,Container > &Assoc2DimTable< aType,Container >::operator=(const Assoc2DimTable< aType,Container > &X)
{
if (this==&X) return *this;
acont=X.acont;
return *this;
}
template< AssocMatrixType aType, class Container> template< class MatrixContainer >
Assoc2DimTable< aType,Container > &Assoc2DimTable< aType,Container >::operator=( const MatrixContainer &X )
{
Privates::Assoc2DimTabTag< KeyType,aType >::operator=( X );
this->clear();
int rozm;
std::pair<KeyType,KeyType> LOCALARRAY(tab,rozm=X.size());
X.getKeys(tab);
for( int i=0;i<rozm;i++ )
this->operator()( tab[i] )=X( tab[i] );
return *this;
}
template< AssocMatrixType aType, class Container>
bool Assoc2DimTable< aType,Container >::hasKey( typename Assoc2DimTable< aType,Container >::KeyType u,
typename Assoc2DimTable< aType,Container >::KeyType v ) const
{
if (!u || !v) return false;
if (!Assoc2DimTabAddr< aType >::correctPos( u,v )) return false;
return interf.hasKey(Assoc2DimTabAddr< aType >::key(u,v));
}
template< AssocMatrixType aType, class Container>
bool Assoc2DimTable< aType,Container >::delKey( typename Assoc2DimTable< aType,Container >::KeyType u,
typename Assoc2DimTable< aType,Container >::KeyType v)
{
if (!u || !v) return false;
if (!Assoc2DimTabAddr< aType >::correctPos( u,v )) return false;
return interf.delKey(Assoc2DimTabAddr< aType >::key(u,v));
}
template< AssocMatrixType aType, class Container>
std::pair< typename Assoc2DimTable< aType,Container >::KeyType,typename Assoc2DimTable< aType,Container >::KeyType >
Assoc2DimTable< aType,Container >::nextKey( typename Assoc2DimTable< aType,Container >::KeyType u,
typename Assoc2DimTable< aType,Container >::KeyType v) const
{
if (!u || !v) return firstKey();
koalaAssert( Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
return interf.nextKey(Assoc2DimTabAddr< aType >::key(u,v));
}
template< AssocMatrixType aType, class Container>
std::pair< typename Assoc2DimTable< aType,Container >::KeyType,typename Assoc2DimTable< aType,Container >::KeyType >
Assoc2DimTable< aType,Container >::prevKey( typename Assoc2DimTable< aType,Container >::KeyType u,
typename Assoc2DimTable< aType,Container >::KeyType v) const
{
if (!u || !v) return lastKey();
koalaAssert( Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
return interf.prevKey(Assoc2DimTabAddr< aType >::key(u,v));
}
template< AssocMatrixType aType, class Container>
bool Assoc2DimTable< aType,Container >::hasInd( typename Assoc2DimTable< aType,Container >::KeyType v ) const
{
for(std::pair< KeyType,KeyType> key=this->firstKey();
!Privates::ZeroAssocKey<std::pair< KeyType,KeyType> >::isZero(key);
key=this->nextKey(key)) if (key.first==v || key.second==v) return true;
return false;
}
template< AssocMatrixType aType, class Container>
bool Assoc2DimTable< aType,Container >::delInd( typename Assoc2DimTable< aType,Container >::KeyType v )
{
bool flag=false;
std::pair< KeyType,KeyType> key,key2;
for(std::pair< KeyType,KeyType> key=this->firstKey();
!Privates::ZeroAssocKey<std::pair< KeyType,KeyType> >::isZero(key);key=key2)
{
key2=this->nextKey(key);
if (key.first==v || key.second==v)
{
flag=true;
this->delKey(key);
}
}
return flag;
}
template< AssocMatrixType aType, class Container> template<class DefaultStructs, class Iterator >
int Assoc2DimTable< aType,Container >::getInds( Iterator iter ) const
{ typename DefaultStructs:: template AssocCont< KeyType, char >::Type inds(2*this->size());
for(std::pair< KeyType,KeyType> key=this->firstKey();
!Privates::ZeroAssocKey<std::pair< KeyType,KeyType> >::isZero(key);
key=this->nextKey(key))
inds[key.first]=inds[key.second]='A';
return inds.getKeys(iter);
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
inline void SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::AssocIndex::DelPosCommand( int pos )
{
int LOCALARRAY( tabpos,IndexContainer::size() );
int l = 0;
int i = IndexContainer::tab.firstPos();
for( ; i != -1; i = IndexContainer::tab.nextPos( i ) )
tabpos[l++] = i;
for( l--; l >= 0; l-- )
{
owner->delPos( std::pair< int,int >( pos,tabpos[l] ) );
if ((aType == AMatrNoDiag || aType == AMatrFull) && (pos != tabpos[l]))
owner->delPos( std::pair< int,int >( tabpos[l],pos ) );
}
IndexContainer::tab.delPos( pos );
Klucz LOCALARRAY(keytab,IndexContainer::size() );
int res=this->getKeys(keytab);
for( int j=0;j<res;j++)
if (!this->operator[]( keytab[j] )) IndexContainer::delKey( keytab[j] );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::delPos( std::pair< int,int > wsp )
{
if (!Assoc2DimTabAddr< aType >::correctPos( wsp.first,wsp.second )) return;
std::pair< int,int > x=Assoc2DimTabAddr< aType >::wsp2pos2( wsp );
if (!bufor.operator[](x.first).operator[](x.second).present) return;
bufor.operator[](x.first).operator[](x.second) = Privates::BlockOfSimpleAssocMatrix< Elem >();
siz--;
--index.tab[wsp.first].val;
--index.tab[wsp.second].val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::resizeBuf( int asize )
{
asize=std::max((int)bufor.size(),asize );
bufor.resize(asize);
for(int i=0;i<asize;i++) bufor.operator[](i).resize
( std::max(Assoc2DimTabAddr< aType >::colSize( i,asize ),(int)bufor.operator[](i).size()) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
SimpleAssocMatrix< Klucz,Elem,aType,Container,IndexContainer >
&SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::operator=( const SimpleAssocMatrix< Klucz,Elem,aType,Container,IndexContainer > & X)
{
if (&X == this) return *this;
index = X.index;
bufor = X.bufor;
siz = X.siz;
index.owner = this;
return *this;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template< class MatrixContainer > SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>
&SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::operator=( const MatrixContainer &X )
{
Privates::Assoc2DimTabTag< Klucz,aType >::operator=( X );
this->clear();
int rozm;
std::pair<Klucz,Klucz> LOCALARRAY(tab,rozm=X.size());
X.getKeys(tab);
for( int i=0;i<rozm;i++ )
this->operator()( tab[i] )=X( tab[i] );
return *this;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::reserve( int asize )
{
index.reserve( asize );
bufor.resize( asize=std::max((int)bufor.size(),asize ));
for(int i=0;i<asize;i++) bufor.operator[](i).reserve( Assoc2DimTabAddr< aType >::colSize( i,asize ) );
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::clear()
{
index.clear();
int bufsize=bufor.size();
bufor.clear();
this->resizeBuf(bufsize);
siz = 0;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template <class ExtCont> int SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::slice1( Klucz v, ExtCont &tab ) const
{
if (!index.hasKey( v )) return 0;
int licz = 0;
for( Klucz x = index.firstKey(); x; x = index.nextKey( x ) )
if (hasKey( v,x ))
{
tab[x] = this->operator()( v,x );
licz++;
}
return licz;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template <class ExtCont> int SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::slice2( Klucz v, ExtCont &tab ) const
{
if (!index.hasKey( v )) return 0;
int licz = 0;
for( Klucz x = index.firstKey(); x; x = index.nextKey( x ) )
if (hasKey( x,v ))
{
tab[x] = this->operator()( x,v );
licz++;
}
return licz;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
bool SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::delInd( Klucz v )
{
if (!hasInd( v )) return false;
Klucz LOCALARRAY( tab,index.size() );
int i = 0;
for( Klucz x = index.firstKey(); x; x = index.nextKey( x ) ) tab[i++] = x;
for( i--; i >= 0; i-- )
{
delKey( v,tab[i] );
if ((aType == AMatrNoDiag || aType == AMatrFull) && (v != tab[i]))
delKey( tab[i],v );
}
index.delKey( v );
return true;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
bool SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::hasKey( Klucz u, Klucz v ) const
{
if (!u || !v) return false;
if (!Assoc2DimTabAddr< aType >::correctPos( u,v )) return false;
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return false;
wsp=Assoc2DimTabAddr< aType >::wsp2pos2( wsp );
return bufor.operator[](wsp.first).operator[](wsp.second).present;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
bool SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::delKey( Klucz u, Klucz v)
{
if (!u || !v) return false;
if (!Assoc2DimTabAddr< aType >::correctPos( u,v )) return false;
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return false;
std::pair< int,int > x=Assoc2DimTabAddr< aType >::wsp2pos2( wsp );
if (bufor.operator[](x.first).operator[](x.second).present)
{
bufor.operator[](x.first).operator[](x.second) = Privates::BlockOfSimpleAssocMatrix< Elem >();
siz--;
if (--index[u] == 0) index.delKey( u );
if (--index[v] == 0) index.delKey( v );
return true;
}
return false;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Elem &SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::operator()( Klucz u, Klucz v )
{
koalaAssert( u && v && Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1)
{
index[u] = 0;
wsp.first = index.klucz2pos( u );
}
if (wsp.second == -1)
{
index[v] = 0;
wsp.second = index.klucz2pos( v );
}
int q,qq;
this->resizeBuf( q=std::max( qq=(int)bufor.size(), index.size() ) );
std::pair< int,int > x = Assoc2DimTabAddr< aType >::wsp2pos2( wsp );
if (!bufor.operator[](x.first).operator[](x.second).present)
{
bufor.operator[](x.first).operator[](x.second).present=true;
index[u]++;
index[v]++;
siz++;
}
return bufor.operator[](x.first).operator[](x.second).val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Elem SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::operator()( Klucz u, Klucz v) const
{
koalaAssert( u && v && Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return Elem();
std::pair< int,int > x = Assoc2DimTabAddr< aType >::wsp2pos2( wsp );
if (!bufor.operator[](x.first).operator[](x.second).present) return Elem();
return bufor.operator[](x.first).operator[](x.second).val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
Elem *SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::valPtr(Klucz u, Klucz v)
{
koalaAssert( u && v && Assoc2DimTabAddr< aType >::correctPos( u,v ),ContExcWrongArg );
std::pair< int,int > wsp = std::pair< int,int >( index.klucz2pos( u ),index.klucz2pos( v ) );
if (wsp.first == -1 || wsp.second == -1) return NULL;
std::pair< int,int > pos=Assoc2DimTabAddr< aType >::wsp2pos2( wsp );
if (!bufor.operator[](pos.first).operator[](pos.second).present) return NULL;
return &bufor.operator[](pos.first).operator[](pos.second).val;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
template< class Iterator > int SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::getKeys( Iterator iter ) const
{
for(Klucz x=this->firstInd();x;x=this->nextInd(x))
for(Klucz y=(aType==AMatrFull || aType==AMatrNoDiag) ? this->firstInd() : x;
y;y=this->nextInd(y))
if (this->hasKey(x,y))
{
*iter=Assoc2DimTabAddr<aType>::key(std::pair<Klucz,Klucz>(x,y));
++iter;
}
return siz;
}
template< class Klucz, class Elem, AssocMatrixType aType, class Container, class IndexContainer >
void SimpleAssocMatrix<Klucz,Elem,aType,Container,IndexContainer>::defrag()
{
int n;
std::pair<Klucz,Klucz> LOCALARRAY(keys,n=this->size());
ValType LOCALARRAY(vals,n);
this->getKeys(keys);
for(int i=0;i<n;i++) vals[i]=this->operator()(keys[i].first,keys[i].second);
index.clear();
index.defrag();
siz=0;
{
Container tmp;
bufor.swap(tmp);
}
for(int i=0;i<n;i++) this->operator()(keys[i].first,keys[i].second)=vals[i];
}
| 35.009717
| 164
| 0.660568
|
miloszc
|
6787d8c779a3ba6a702a7af7db4f78c9d5b97891
| 8,821
|
cxx
|
C++
|
Hybrid/Testing/Cxx/TestKWEGPUArrayCalculator.cxx
|
wuzhuobin/vtkEdge
|
ed13af68a72cec79e3645f7e842d6074592abfa2
|
[
"BSD-3-Clause"
] | 1
|
2021-01-09T16:06:14.000Z
|
2021-01-09T16:06:14.000Z
|
Hybrid/Testing/Cxx/TestKWEGPUArrayCalculator.cxx
|
wuzhuobin/vtkEdge
|
ed13af68a72cec79e3645f7e842d6074592abfa2
|
[
"BSD-3-Clause"
] | null | null | null |
Hybrid/Testing/Cxx/TestKWEGPUArrayCalculator.cxx
|
wuzhuobin/vtkEdge
|
ed13af68a72cec79e3645f7e842d6074592abfa2
|
[
"BSD-3-Clause"
] | null | null | null |
//=============================================================================
// This file is part of VTKEdge. See vtkedge.org for more information.
//
// Copyright (c) 2010 Kitware, Inc.
//
// VTKEdge may be used under the terms of the BSD License
// Please see the file Copyright.txt in the root directory of
// VTKEdge for further information.
//
// Alternatively, you may see:
//
// http://www.vtkedge.org/vtkedge/project/license.html
//
//
// For custom extensions, consulting services, or training for
// this or any other Kitware supported open source project, please
// contact Kitware at sales@kitware.com.
//
//
//=============================================================================
// This test covers vtkKWEGPUArrayCalulator, compare to vtkArrayCalculator.
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
// An image data is first created with a raw array.
// Some computation on the data array is performed
// IF THIS TEST TIMEOUT, IT IS PROBABLY ON VISTA WITH A NOT-FAST-ENOUGH
// GRAPHICS CARD:
// Depending on how fast/slow is the graphics card, the computation on the GPU
// can take more than 2 seconds. On Vista, after a 2 seconds timeout, the
// Windows Vista's Timeout Detection and Recovery (TDR) kills all the graphics
// contexts, resets the graphics chip and recovers the graphics driver, in
// order to keep the operating system responsive.
// ref: http://www.opengl.org/pipeline/article/vol003_7/
// This reset actually freezes the test. And it really times out this time...
// Example of pathological case: dash1vista32.kitware/Win32Vista-vs80
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkArrayCalculator.h"
#include "vtkKWEGPUArrayCalculator.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkOutlineFilter.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkImageImport.h"
#include <assert.h>
#include "vtkTimerLog.h"
#include "vtkDoubleArray.h"
#include "vtkXYPlotWidget.h"
#include "vtkXYPlotActor.h"
// On a nVidia Quadro FX 3600M (~GeForce8),
// GL_MAX_TEXTURE_SIZE = 8192, GL_MAX_3D_TEXTURE_SIZE = 2048
// GL_MAX_VIEWPORT_DIMS = 8192, 8192
// The following size matches two complete full 2D textures, one 2D texture
// with one complete row and one 2D texture with just one pixel.
//const vtkIdType TestNumberOfPoints=2*(8192*8192)+8192+1;
const vtkIdType TestNumberOfPoints=(2*(8192*8192)+8192+1)/10; // 2*(8192*8192)+8192+1; //4096*4096;
const int TestNumberOfComponents=1; // 1 or 3
void ComputeAndDisplayMeanErrorAndStandardDeviation(vtkDoubleArray *c,
vtkDoubleArray *g)
{
assert("pre: c_exists" && c!=0);
assert("pre: g_exists" && g!=0);
assert("pre: same_size" && c->GetNumberOfTuples()==g->GetNumberOfTuples());
assert("pre: same_components" && c->GetNumberOfComponents()==g->GetNumberOfComponents());
assert("pre: not_empty" && c->GetNumberOfTuples()>0);
vtkIdType n=c->GetNumberOfTuples()*c->GetNumberOfComponents();
double *a=static_cast<double *>(c->GetVoidPointer(0));
double *b=static_cast<double *>(g->GetVoidPointer(0));
vtkIdType i;
// mean error
double meanError=0.0;
double maxError=0.0;
i=0;
while(i<n)
{
double delta=fabs(a[i]-b[i]);
if(delta>maxError)
{
maxError=delta;
}
meanError+=delta;
++i;
}
meanError/=static_cast<double>(n);
// std deviation
double stdDeviation=0.0;
i=0;
while(i<n)
{
double delta=fabs(a[i]-b[i])-meanError;
stdDeviation+=delta*delta;
++i;
}
stdDeviation=sqrt(stdDeviation/static_cast<double>(n));
cout<<" number of values="<<n<<endl;
cout<<" mean error="<<meanError<<endl;
cout<<" standard deviation="<<stdDeviation<<endl;
cout<<" maxError="<<maxError<<endl;
}
vtkImageImport *CreateSource(vtkIdType numberOfPoints,
int numberOfComponents)
{
assert("pre: valid_number_of_points" && numberOfPoints>0);
vtkImageImport *im=vtkImageImport::New();
float *ptr=new float[numberOfPoints*numberOfComponents];
vtkIdType i=0;
while(i<numberOfPoints*numberOfComponents)
{
ptr[i]=static_cast<float>(i); // 2.0
++i;
}
im->SetDataScalarTypeToFloat();
im->SetImportVoidPointer(ptr,0); // let the importer delete it.
im->SetNumberOfScalarComponents(numberOfComponents);
im->SetDataExtent(0,static_cast<int>(numberOfPoints-1),0,0,0,0);
im->SetWholeExtent(0,static_cast<int>(numberOfPoints-1),0,0,0,0);
im->SetScalarArrayName("values");
return im;
}
int TestKWEGPUArrayCalculator(int vtkNotUsed(argc),
char *vtkNotUsed(argv)[])
{
vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->SetSize(101,99);
renWin->SetAlphaBitPlanes(1);
renWin->SetReportGraphicErrors(1);
iren->SetRenderWindow(renWin);
renWin->Delete();
// Useful when looking at the test output in CDash:
cout << "IF THIS TEST TIMEOUT, IT IS PROBABLY ON VISTA WITH"
<< " A NOT-FAST-ENOUGH GRAPHICS CARD."<<endl;
cout<<"numPoints="<<TestNumberOfPoints<<endl;
vtkImageImport *im=CreateSource(TestNumberOfPoints,TestNumberOfComponents);
im->Update();
double range[2];
vtkImageData *image=vtkImageData::SafeDownCast(im->GetOutputDataObject(0));
image->GetPointData()->GetScalars()->GetRange(range);
cout<<"range[2]="<<range[0]<<" "<<range[1]<<endl;
vtkArrayCalculator *calc=vtkArrayCalculator::New();
calc->SetInputConnection(0,im->GetOutputPort(0)); // reader or source
calc->AddScalarArrayName("values");
calc->SetResultArrayName("Result");
calc->SetFunction("values+10.0");
// calc->SetFunction("sin(norm(values))+cos(norm(values))+10.0");
// calc->SetFunction("sin(values)*cos(values)+10.0");
// calc->SetFunction("exp(sqrt(sin(values)*cos(values)+10.0))");
vtkTimerLog *timer=vtkTimerLog::New();
timer->StartTimer();
calc->Update();
timer->StopTimer();
cout<<"Elapsed time with CPU version:"<<timer->GetElapsedTime()<<" seconds."<<endl;
image=vtkImageData::SafeDownCast(calc->GetOutputDataObject(0));
image->GetPointData()->GetScalars()->GetRange(range);
cout<<"range2[2]="<<range[0]<<" "<<range[1]<<endl;
vtkKWEGPUArrayCalculator *calc2=vtkKWEGPUArrayCalculator::New();
calc2->SetContext(renWin);
calc2->SetInputConnection(0,im->GetOutputPort(0)); // reader or source
calc2->AddScalarArrayName("values");
calc2->SetResultArrayName("Result");
calc2->SetFunction("values+10");
// calc2->SetFunction("sin(norm(values))+cos(norm(values))+10.0");
// calc2->SetFunction("sin(values)*cos(values)+10.0");
// calc2->SetFunction("exp(sqrt(sin(values)*cos(values)+10.0))");
// my nVidia Quadro FX 3600M has 512MB
// esimatation of 28MB already taken for screen+current context
// at 1600*1200: 512-28=484
// calc2->SetMaxGPUMemorySizeInBytes(512*1024*1024);
calc2->SetMaxGPUMemorySizeInBytes(128*1024*1024);
timer->StartTimer();
calc2->Update();
timer->StopTimer();
cout<<"Elapsed time with GPU version:"<<timer->GetElapsedTime()<<" seconds."<<endl;
vtkImageData *image2;
image2=vtkImageData::SafeDownCast(calc2->GetOutputDataObject(0));
image2->GetPointData()->GetScalars()->GetRange(range);
cout<<"range3[2]="<<range[0]<<" "<<range[1]<<endl;
ComputeAndDisplayMeanErrorAndStandardDeviation(
vtkDoubleArray::SafeDownCast(image->GetPointData()->GetScalars()),
vtkDoubleArray::SafeDownCast(image2->GetPointData()->GetScalars()));
timer->Delete();
calc2->Calibrate();
cout<<"Calibrated size threshold="<<calc2->GetCalibratedSizeThreshold()<<endl;
#if 0
vtkRenderer *renderer=vtkRenderer::New();
renderer->SetBackground(0.0,0.0,0.3);
renWin->AddRenderer(renderer);
renderer->Delete();
vtkXYPlotActor *actor=vtkXYPlotActor::New();
renderer->AddViewProp(actor);
actor->Delete();
actor->AddInput(image,"Result",0);
actor->SetPlotColor(0,1.0,0.0,0.0);
actor->AddInput(image2,"Result",0);
actor->SetPlotColor(1,0.0,1.0,0.0);
renWin->Render();
vtkXYPlotWidget *w=vtkXYPlotWidget::New();
w->SetInteractor(iren);
w->SetXYPlotActor(actor);
w->SetEnabled(1);
int retVal = vtkRegressionTestImage(renWin);
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
w->Delete();
#endif
calc2->Delete(); // need context
iren->Delete();
im->Delete();
calc->Delete();
return 0; // !retVal; 0: passed, 1: failed
}
| 33.796935
| 117
| 0.677247
|
wuzhuobin
|
6787f8c55a86572359a8d1c112817aa47613cec8
| 4,365
|
hpp
|
C++
|
src/items/SpatialItem.hpp
|
maltewi/envire-envire_core
|
549b64ed30ba8afc4d91ae67b216a78b40cee016
|
[
"BSD-2-Clause"
] | 9
|
2017-05-13T12:33:46.000Z
|
2021-01-27T18:50:40.000Z
|
src/items/SpatialItem.hpp
|
maltewi/envire-envire_core
|
549b64ed30ba8afc4d91ae67b216a78b40cee016
|
[
"BSD-2-Clause"
] | 37
|
2016-02-11T17:34:41.000Z
|
2021-10-04T10:14:18.000Z
|
src/items/SpatialItem.hpp
|
maltewi/envire-envire_core
|
549b64ed30ba8afc4d91ae67b216a78b40cee016
|
[
"BSD-2-Clause"
] | 11
|
2016-07-11T14:49:34.000Z
|
2021-06-04T08:23:39.000Z
|
//
// Copyright (c) 2015, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.
// 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.
//
// 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 __ENVIRE_CORE_SPATIAL_ITEM__
#define __ENVIRE_CORE_SPATIAL_ITEM__
#include <envire_core/items/Item.hpp>
#include <envire_core/items/BoundingVolume.hpp>
#include <boost/shared_ptr.hpp>
#include <Eigen/Geometry>
namespace envire { namespace core
{
/**@class SpatialItem
*
* SpatialItem class
*/
template<class _ItemData>
class SpatialItem : public Item<_ItemData>
{
public:
typedef boost::shared_ptr< SpatialItem<_ItemData> > Ptr;
protected:
boost::shared_ptr<BoundingVolume> boundary;
public:
SpatialItem() : Item<_ItemData>()
{
};
virtual ~SpatialItem() {}
void setBoundary(const boost::shared_ptr<BoundingVolume>& boundary) {this->boundary = boundary;}
boost::shared_ptr<BoundingVolume> getBoundary() {return boundary;}
const boost::shared_ptr<BoundingVolume>& getBoundary() const {return boundary;}
void extendBoundary(const Eigen::Vector3d& point)
{
checkBoundingVolume();
boundary->extend(point);
}
template<typename _Data>
void extendBoundary(const SpatialItem<_Data>& spatial_item)
{
checkBoundingVolume();
boundary->extend(spatial_item.getBoundary());
}
template<typename _Data>
bool intersects(const SpatialItem<_Data>& spatial_item) const
{
checkBoundingVolume();
return boundary->intersects(spatial_item.getBoundary());
}
template<typename _Data>
boost::shared_ptr<BoundingVolume> intersection(const SpatialItem<_Data>& spatial_item) const
{
checkBoundingVolume();
return boundary->intersection(spatial_item.getBoundary());
}
bool contains(const Eigen::Vector3d& point) const
{
checkBoundingVolume();
return boundary->contains(point);
}
template<typename _Data>
bool contains(const SpatialItem<_Data>& spatial_item) const
{
checkBoundingVolume();
return boundary->contains(spatial_item.getBoundary());
}
double exteriorDistance(const Eigen::Vector3d& point) const
{
checkBoundingVolume();
return boundary->exteriorDistance(point);
}
template<typename _Data>
double exteriorDistance(const SpatialItem<_Data>& spatial_item) const
{
checkBoundingVolume();
return boundary->exteriorDistance(spatial_item.getBoundary());
}
Eigen::Vector3d centerOfBoundary() const
{
checkBoundingVolume();
return boundary->center();
}
protected:
void checkBoundingVolume() const
{
if(boundary.get() == NULL)
throw std::runtime_error("BoundingVolume is not available!");
}
};
}}
#endif
| 31.630435
| 104
| 0.666208
|
maltewi
|
678bb6abe6ce6d9516ab5d5f4f07267b9aa57239
| 3,817
|
cpp
|
C++
|
released_plugins/v3d_plugins/hierachical_labeling/hier_label_func.cpp
|
zzhmark/vaa3d_tools
|
3ca418add85a59ac7e805d55a600b78330d7e53d
|
[
"MIT"
] | 1
|
2021-12-27T19:14:03.000Z
|
2021-12-27T19:14:03.000Z
|
released_plugins/v3d_plugins/hierachical_labeling/hier_label_func.cpp
|
zzhmark/vaa3d_tools
|
3ca418add85a59ac7e805d55a600b78330d7e53d
|
[
"MIT"
] | 1
|
2016-12-03T05:33:13.000Z
|
2016-12-03T05:33:13.000Z
|
released_plugins/v3d_plugins/hierachical_labeling/hier_label_func.cpp
|
zzhmark/vaa3d_tools
|
3ca418add85a59ac7e805d55a600b78330d7e53d
|
[
"MIT"
] | null | null | null |
/* hier_label_func.cpp
* This plugin heirachically segments the input neuron tree and label the nodes as features in eswc file.
* 2012-05-04 : by Yinan Wan
*/
#include <v3d_interface.h>
#include "v3d_message.h"
#include "hier_label_func.h"
#include "hierachical_labeling.h"
#include "customary_structs/vaa3d_neurontoolbox_para.h"
#include <vector>
#include <iostream>
using namespace std;
const QString title = QObject::tr("Hierachical Labeling");
int hierachical_labeling_io(V3DPluginCallback2 &callback, QWidget *parent)
{
QString fileOpenName;
fileOpenName = QFileDialog::getOpenFileName(0, QObject::tr("Open File"),
"",
QObject::tr("Supported file (*.swc)"
";;Neuron structure (*.swc)"
));
if(fileOpenName.isEmpty())
return -1;
NeuronTree nt = readSWC_file(fileOpenName);
if (!hierachical_labeling(nt))
{
v3d_msg("Error in consensus skeleton!");
return -1;
}
QString fileSaveName;
QString defaultSaveName = fileOpenName + "_hier.eswc";
fileSaveName = QFileDialog::getSaveFileName(0, QObject::tr("Save merged neuron to file:"),
defaultSaveName,
QObject::tr("Supported file (*.eswc)"
";;Neuron structure (*.eswc)"
));
if (!writeESWC_file(fileSaveName, nt))
{
v3d_msg("Unable to save file");
return -1;
}
return 1;
}
bool hierachical_labeling_io(const V3DPluginArgList & input, V3DPluginArgList & output)
{
cout<<"Welcome to hierachical_labeling"<<endl;
if(input.size() != 1)
{
cerr<<"please specify only 1 input neuron without parameter"<<endl;
return true;
}
vector<char*> * inlist = (vector<char*> *)(input.at(0).p);
if (inlist->size()!=1)
{
cerr<<"please specify only 1 input neuron"<<endl;
return false;
}
QString fileOpenName(inlist->at(0));
if (output.size()!=1) return false;
QString fileSaveName;
vector<char*> * outlist = (vector<char*> *)(output.at(0).p);
if (outlist->size()==0)
fileSaveName = fileOpenName + "_hier.eswc";
else if (outlist->size()==1)
fileSaveName = QString(outlist->at(0));
else
{
cerr<<"please specify only 1 input neuron"<<endl;
return false;
}
NeuronTree nt = readSWC_file(fileOpenName);
if (!hierachical_labeling(nt))
{
cerr<<"Error in consensus skeleton!"<<endl;;
return false;
}
if (!writeESWC_file(fileSaveName, nt))
{
cerr<<"Unable to save file"<<endl;
return false;
}
return true;
}
bool hierachical_labeling_toolbox(const V3DPluginArgList & input)
{
vaa3d_neurontoolbox_paras * paras = (vaa3d_neurontoolbox_paras *)(input.at(0).p);
NeuronTree neuron = paras->nt;
QString fileOpenName = neuron.file;
if (!hierachical_labeling(neuron))
{
v3d_msg("Error in consensus skeleton!");
return -1;
}
QString fileSaveName;
QString defaultSaveName = fileOpenName + "_hier.eswc";
fileSaveName = QFileDialog::getSaveFileName(0, QObject::tr("Save merged neuron to file:"),
defaultSaveName,
QObject::tr("Supported file (*.eswc)"
";;Neuron structure (*.eswc)"
));
if (!writeESWC_file(fileSaveName, neuron))
{
v3d_msg("Unable to save file");
return -1;
}
return 1;
}
void printHelp()
{
cout<<"\nHierachical Labeling: a plugin that hierachically segments the neuron structure and save it as eswc (Enhanced SWC) format. 12-05-04 by Yinan Wan"<<endl;
cout<<"Usage: v3d -x hier_label -f hierachical_labeling -i <input_neuron> -o <output_eswc>"<<endl;
cout<<"Parameters"<<endl;
cout<<"\t-i <input_neuron>: input neuron structure, in .swc or .eswc format"<<endl;
cout<<"\t[-o] <output_eswc> : output eswc file, with hierachy stored in the fea_val row"<<endl;
cout<<"\t not required. DEFAULT file should be generated under the same folder with input neuron with a name of inputFileName_hier.eswc"<<endl;
cout<<"Example: v3d-x hier_label -f hierachical_labeling -i input.swc -o input_labeled.swc\n"<<endl;
}
| 27.861314
| 165
| 0.703432
|
zzhmark
|
678cf958b2fa6c02ad42f430b91df752c6f7a2c8
| 1,061
|
cpp
|
C++
|
tau/TauEngine/src/dx/dxgi/DXGI11GraphicsDisplay.cpp
|
hyfloac/TauEngine
|
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
|
[
"MIT"
] | 1
|
2020-04-22T04:07:01.000Z
|
2020-04-22T04:07:01.000Z
|
tau/TauEngine/src/dx/dxgi/DXGI11GraphicsDisplay.cpp
|
hyfloac/TauEngine
|
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
|
[
"MIT"
] | null | null | null |
tau/TauEngine/src/dx/dxgi/DXGI11GraphicsDisplay.cpp
|
hyfloac/TauEngine
|
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
|
[
"MIT"
] | null | null | null |
#include "dx/dxgi/DXGI11GraphicsDisplay.hpp"
#ifdef _WIN32
NullableRef<DXGI11GraphicsDisplay> DXGI11GraphicsDisplay::build(IDXGIOutput* const dxgiOutput) noexcept
{
UINT numDisplayModes;
HRESULT res = dxgiOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numDisplayModes, nullptr);
if(FAILED(res))
{ return null; }
DynArray<DXGI_MODE_DESC> dxgiDisplayModes(numDisplayModes);
res = dxgiOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numDisplayModes, dxgiDisplayModes);
RefDynArray<IGraphicsDisplay::GraphicsDisplayMode> displayModes(numDisplayModes);
if(FAILED(res))
{ return null; }
for(uSys i = 0; i < numDisplayModes; ++i)
{
const auto& mode = dxgiDisplayModes[i];
displayModes[i] = { mode.Width, mode.Height, mode.RefreshRate.Numerator, mode.RefreshRate.Denominator };
}
return NullableRef<DXGI11GraphicsDisplay>(DefaultTauAllocator::Instance(), dxgiOutput, displayModes);
}
#endif
| 35.366667
| 134
| 0.737983
|
hyfloac
|
6790d2017a223d244fde06f4fd43c86abecc4182
| 1,419
|
hpp
|
C++
|
deeplab/code/include/caffe/layers/graphcut_layer.hpp
|
dmitrii-marin/adm-seg
|
e730b79bcd2b30cee66efac0ce961090c2cd4e62
|
[
"MIT"
] | 10
|
2019-05-28T22:00:08.000Z
|
2021-11-27T04:00:11.000Z
|
deeplab/code/include/caffe/layers/graphcut_layer.hpp
|
dmitrii-marin/adm-seg
|
e730b79bcd2b30cee66efac0ce961090c2cd4e62
|
[
"MIT"
] | 2
|
2019-09-10T09:47:13.000Z
|
2019-10-26T02:58:03.000Z
|
deeplab/code/include/caffe/layers/graphcut_layer.hpp
|
dmitrii-marin/adm-seg
|
e730b79bcd2b30cee66efac0ce961090c2cd4e62
|
[
"MIT"
] | 2
|
2019-12-26T01:58:20.000Z
|
2020-03-11T02:22:08.000Z
|
#ifndef CAFFE_GRAPHCUT_LAYER_HPP_
#define CAFFE_GRAPHCUT_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/filterrgbxy.hpp"
#include "gco-v3.0/GCoptimization.h"
#include <cstddef>
namespace caffe{
template <typename Dtype>
class GraphCutLayer : public Layer<Dtype>{
public:
virtual ~GraphCutLayer();
explicit GraphCutLayer(const LayerParameter & param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*> & bottom,
const vector<Blob<Dtype>*> & top);
virtual inline const char* type() const { return "GraphCut";}
virtual inline int ExactNumBottomBlobs() const {return 2;}
virtual inline int ExactNumTopBlobs() const {return 2;}
protected:
void runGraphCut(const Dtype * image, const Dtype * unary, Dtype * gc_segmentation, bool * ROI);
virtual void Forward_cpu(const vector<Blob<Dtype>*> & bottom,
const vector<Blob<Dtype>*> & top);
virtual void Backward_cpu(const vector<Blob<Dtype>*> & top,
const vector<bool> & propagate_down, const vector<Blob<Dtype>*> & bottom);
int N, C, H, W;
float sigma;
int max_iter;
float potts_weight;
Blob<Dtype> * unaries;
bool * ROI_allimages;
};
} // namespace caffe
#endif // CAFFE_GRAPHCUT_LAYER_HPP_
| 26.277778
| 98
| 0.711769
|
dmitrii-marin
|
09649f973e8094042707dd1d686a901ca1295560
| 6,729
|
cpp
|
C++
|
Cores/FCEU/FCEU/drivers/win/keyboard.cpp
|
werminghoff/Provenance
|
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
|
[
"BSD-3-Clause"
] | 3,459
|
2015-01-07T14:07:09.000Z
|
2022-03-25T03:51:10.000Z
|
Cores/FCEU/FCEU/drivers/win/keyboard.cpp
|
werminghoff/Provenance
|
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
|
[
"BSD-3-Clause"
] | 1,046
|
2018-03-24T17:56:16.000Z
|
2022-03-23T08:13:09.000Z
|
Cores/FCEU/FCEU/drivers/win/keyboard.cpp
|
werminghoff/Provenance
|
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
|
[
"BSD-3-Clause"
] | 549
|
2015-01-07T14:07:15.000Z
|
2022-01-07T16:13:05.000Z
|
/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002 Xodnizel
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "common.h"
#include "dinput.h"
#include "input.h"
#include "keyboard.h"
static HRESULT ddrval; //mbg merge 7/17/06 made static
static int background = 0;
static LPDIRECTINPUTDEVICE7 lpdid=0;
void KeyboardClose(void)
{
if(lpdid) IDirectInputDevice7_Unacquire(lpdid);
lpdid=0;
}
static unsigned int keys[256] = {0,}; // with repeat
static unsigned int keys_nr[256] = {0,}; // non-repeating
static unsigned int keys_jd[256] = {0,}; // just-down
static unsigned int keys_jd_lock[256] = {0,}; // just-down released lock
int autoHoldKey = 0, autoHoldClearKey = 0;
int ctr=0;
void KeyboardUpdateState(void)
{
unsigned char tk[256];
ddrval=IDirectInputDevice7_GetDeviceState(lpdid,256,tk);
if (tk[0]) tk[0] = 0; //adelikat: HACK. If a keyboard key is recognized as this, the effect is that all non assigned hotkeys are run. This prevents the key from being used, but also prevent "hotkey explosion". Also, they essentially couldn't use it anyway since FCEUX doesn't know it is a shift key, and it can't be assigned in the hotkeys
// HACK because DirectInput is totally wacky about recognizing the PAUSE/BREAK key
if(GetAsyncKeyState(VK_PAUSE)) // normally this should have & 0x8000, but apparently this key is too special for that to work
tk[0xC5] = 0x80;
switch(ddrval)
{
case DI_OK: //memcpy(keys,tk,256);break;
break;
//mbg 10/8/2008
//previously only these two cases were handled. this made dwedit's laptop volume keys freak out.
//we're trying this instead
default:
//case DIERR_INPUTLOST:
//case DIERR_NOTACQUIRED:
memset(tk,0,256);
IDirectInputDevice7_Acquire(lpdid);
break;
}
//process keys
extern int soundoptions;
#define SO_OLDUP 32
extern int soundo;
extern int32 fps_scale;
int notAlternateThrottle = !(soundoptions&SO_OLDUP) && soundo && ((NoWaiting&1)?(256*16):fps_scale) >= 64;
#define KEY_REPEAT_INITIAL_DELAY ((!notAlternateThrottle) ? (16) : (64)) // must be >= 0 and <= 255
#define KEY_REPEAT_REPEATING_DELAY (6) // must be >= 1 and <= 255
#define KEY_JUST_DOWN_DURATION (1) // must be >= 1 and <= 255 // AnS: changed to 1 to disallow unwanted hits of e.g. F1 after pressing Shift+F1 and quickly releasing Shift
for(int i = 0 ; i < 256 ; i++)
if(tk[i])
if(keys_nr[i] < 255)
keys_nr[i]++; // activate key, and count up for repeat
else
keys_nr[i] = 255 - KEY_REPEAT_REPEATING_DELAY; // oscillate for repeat
else
keys_nr[i] = 0; // deactivate key
memcpy(keys,keys_nr,sizeof(keys));
// key-down detection
for(int i = 0 ; i < 256 ; i++)
if(!keys_nr[i])
{
keys_jd[i] = 0;
keys_jd_lock[i] = 0;
}
else if(keys_jd_lock[i])
{}
else if(keys_jd[i]
/*&& (i != 0x2A && i != 0x36 && i != 0x1D && i != 0x38)*/)
{
if(++keys_jd[i] > KEY_JUST_DOWN_DURATION)
{
keys_jd[i] = 0;
keys_jd_lock[i] = 1;
}
}
else
keys_jd[i] = 1;
// key repeat
for(int i = 0 ; i < 256 ; i++)
if((int)keys[i] >= KEY_REPEAT_INITIAL_DELAY && !(keys[i]%KEY_REPEAT_REPEATING_DELAY))
keys[i] = 0;
extern uint8 autoHoldOn, autoHoldReset;
autoHoldOn = autoHoldKey && keys[autoHoldKey] != 0;
autoHoldReset = autoHoldClearKey && keys[autoHoldClearKey] != 0;
}
unsigned int *GetKeyboard(void)
{
return(keys);
}
unsigned int *GetKeyboard_nr(void)
{
return(keys_nr);
}
unsigned int *GetKeyboard_jd(void)
{
return(keys_jd);
}
int KeyboardInitialize(void)
{
if(lpdid)
return(1);
//mbg merge 7/17/06 changed:
ddrval=IDirectInput7_CreateDeviceEx(lpDI, GUID_SysKeyboard,IID_IDirectInputDevice7, (LPVOID *)&lpdid,0);
//ddrval=IDirectInput7_CreateDeviceEx(lpDI, &GUID_SysKeyboard,&IID_IDirectInputDevice7, (LPVOID *)&lpdid,0);
if(ddrval != DI_OK)
{
FCEUD_PrintError("DirectInput: Error creating keyboard device.");
return 0;
}
ddrval=IDirectInputDevice7_SetCooperativeLevel(lpdid, hAppWnd,(background?DISCL_BACKGROUND:DISCL_FOREGROUND)|DISCL_NONEXCLUSIVE);
if(ddrval != DI_OK)
{
FCEUD_PrintError("DirectInput: Error setting keyboard cooperative level.");
return 0;
}
ddrval=IDirectInputDevice7_SetDataFormat(lpdid,&c_dfDIKeyboard);
if(ddrval != DI_OK)
{
FCEUD_PrintError("DirectInput: Error setting keyboard data format.");
return 0;
}
////--set to buffered mode
//DIPROPDWORD dipdw;
//dipdw.diph.dwSize = sizeof(DIPROPDWORD);
//dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
//dipdw.diph.dwObj = 0;
//dipdw.diph.dwHow = DIPH_DEVICE;
//dipdw.dwData = 64;
//ddrval = IDirectInputDevice7_SetProperty(lpdid,DIPROP_BUFFERSIZE, &dipdw.diph);
////--------
ddrval=IDirectInputDevice7_Acquire(lpdid);
/* Not really a fatal error. */
//if(ddrval != DI_OK)
//{
// FCEUD_PrintError("DirectInput: Error acquiring keyboard.");
// return 0;
//}
return 1;
}
static bool curr = false;
static void UpdateBackgroundAccess(bool on)
{
if(curr == on) return;
curr = on;
if(!lpdid)
return;
ddrval=IDirectInputDevice7_Unacquire(lpdid);
if(on)
ddrval=IDirectInputDevice7_SetCooperativeLevel(lpdid, hAppWnd,DISCL_BACKGROUND|DISCL_NONEXCLUSIVE);
else
ddrval=IDirectInputDevice7_SetCooperativeLevel(lpdid, hAppWnd,DISCL_FOREGROUND|DISCL_NONEXCLUSIVE);
if(ddrval != DI_OK)
{
FCEUD_PrintError("DirectInput: Error setting keyboard cooperative level.");
return;
}
ddrval=IDirectInputDevice7_Acquire(lpdid);
return;
}
void KeyboardSetBackgroundAccessBit(int bit)
{
background |= (1<<bit);
UpdateBackgroundAccess(background != 0);
}
void KeyboardClearBackgroundAccessBit(int bit)
{
background &= ~(1<<bit);
UpdateBackgroundAccess(background != 0);
}
void KeyboardSetBackgroundAccess(bool on)
{
if(on)
KeyboardSetBackgroundAccessBit(KEYBACKACCESS_OLDSTYLE);
else
KeyboardClearBackgroundAccessBit(KEYBACKACCESS_OLDSTYLE);
}
| 29.384279
| 344
| 0.696983
|
werminghoff
|
0965c5446ac766b60de9408cc4e71f3c7dc6ced4
| 8,639
|
cc
|
C++
|
instrument.cc
|
eryjus/instrumentation
|
82c6e211b4b263c0beece904b615a8817681f6ac
|
[
"Beerware"
] | null | null | null |
instrument.cc
|
eryjus/instrumentation
|
82c6e211b4b263c0beece904b615a8817681f6ac
|
[
"Beerware"
] | null | null | null |
instrument.cc
|
eryjus/instrumentation
|
82c6e211b4b263c0beece904b615a8817681f6ac
|
[
"Beerware"
] | null | null | null |
//===================================================================================================================
//
// instrument.cc -- Bochs instrumentation for CenuryOS
//
/////////////////////////////////////////////////////////////////////////
// $Id: instrument.cc 12655 2015-02-19 20:23:08Z sshwarts $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2015 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// -----------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2020-Jan-11 Initial v0.0.1 ADCL Initial version -- copied from bochs-2.6.11/instrument/example1
//
//===================================================================================================================
#include <stdint.h>
#include <assert.h>
#include "bochs.h"
#include "cpu/cpu.h"
#include "disasm/disasm.h"
bxInstrumentation *icpu = NULL;
static disassembler bx_disassembler;
static logfunctions *instrument_log = new logfunctions ();
#define LOG_THIS instrument_log->
void bx_instr_init_env(void) {}
void bx_instr_exit_env(void) {}
void bx_instr_initialize(unsigned cpu)
{
assert(cpu < BX_SMP_PROCESSORS);
if (icpu == NULL)
icpu = new bxInstrumentation[BX_SMP_PROCESSORS];
icpu[cpu].set_cpu_id(cpu);
BX_INFO(("Initialize cpu %u", cpu));
}
void bxInstrumentation::bx_instr_reset(unsigned type)
{
ready = is_branch = 0;
num_data_accesses = 0;
active = 0;
}
void bxInstrumentation::bx_print_instruction(void)
{
char disasm_tbuf[512]; // buffer for instruction disassembly
char opcode_hex[100] = {0}; // buffer for the instruction hex
char buf[5]; // buffer for sprintf
bx_disassembler.disasm(is32, is64, 0, 0, opcode, disasm_tbuf);
if(opcode_length != 0)
{
unsigned n;
BX_INFO(("----------------------------------------------------------"));
BX_INFO(("CPU %d at %p: %s (reg results):",
cpu_id, eipSave, disasm_tbuf));
for(n=0;n < opcode_length;n++) {
sprintf(buf, "%02x", opcode[n]);
strcat(opcode_hex, buf);
}
BX_INFO(("LEN %d\tBYTES: %s", opcode_length, opcode_hex));
BX_INFO((" EAX: 0x%08.8x; EBX: 0x%08.8x; ECX 0x%08.8x; EDX: 0x%08.8x",
BX_CPU(cpu_id)->gen_reg[0].dword.erx,
BX_CPU(cpu_id)->gen_reg[3].dword.erx,
BX_CPU(cpu_id)->gen_reg[1].dword.erx,
BX_CPU(cpu_id)->gen_reg[2].dword.erx));
BX_INFO((" ESP: 0x%08.8x; EBP: 0x%08.8x; ESI 0x%08.8x; EDI: 0x%08.8x",
BX_CPU(cpu_id)->gen_reg[4].dword.erx,
BX_CPU(cpu_id)->gen_reg[5].dword.erx,
BX_CPU(cpu_id)->gen_reg[6].dword.erx,
BX_CPU(cpu_id)->gen_reg[7].dword.erx));
BX_INFO((" CS: 0x%04.4x; DS: 0x%04.4x; ES: 0x%04.4x; FS: 0x%04.4x; GS: 0x%04.4x; SS: 0x%04.4x; ",
BX_CPU(cpu_id)->sregs[BX_SEG_REG_CS].selector.value,
BX_CPU(cpu_id)->sregs[BX_SEG_REG_DS].selector.value,
BX_CPU(cpu_id)->sregs[BX_SEG_REG_ES].selector.value,
BX_CPU(cpu_id)->sregs[BX_SEG_REG_FS].selector.value,
BX_CPU(cpu_id)->sregs[BX_SEG_REG_GS].selector.value,
BX_CPU(cpu_id)->sregs[BX_SEG_REG_SS].selector.value));
uint32_t flags = BX_CPU(cpu_id)->eflags;
BX_INFO((" EFLAGS: %08.8p (%s %s %s %s %s %s %s IOPL=%d %s %s %s %s %s %s %s %s %s)", flags,
(flags&(1<<21)?"ID":"id"),
(flags&(1<<20)?"VIP":"vip"),
(flags&(1<<19)?"VIF":"vif"),
(flags&(1<<18)?"AC":"ac"),
(flags&(1<<17)?"VM":"vm"),
(flags&(1<<16)?"RF":"rf"),
(flags&(1<<14)?"NT":"nt"),
(flags>>12) & 3,
(flags&(1<<11)?"OF":"of"),
(flags&(1<<10)?"DF":"df"),
(flags&(1<< 9)?"IF":"if"),
(flags&(1<< 8)?"TF":"tf"),
(flags&(1<< 7)?"SF":"sf"),
(flags&(1<< 6)?"ZF":"zf"),
(flags&(1<< 4)?"AF":"af"),
(flags&(1<< 2)?"PF":"pf"),
(flags&(1<< 0)?"CF":"cf")
));
if(is_branch)
{
if(is_taken)
BX_INFO(("\tBRANCH TARGET " FMT_ADDRX " (TAKEN)", target_linear));
else
BX_INFO(("\tBRANCH (NOT TAKEN)"));
}
for(n=0;n < num_data_accesses;n++)
{
BX_INFO(("MEM ACCESS[%u]: 0x" FMT_ADDRX " (linear) 0x" FMT_PHY_ADDRX " (physical) %s SIZE: %d", n,
data_access[n].laddr,
data_access[n].paddr,
data_access[n].rw == BX_READ ? "RD":"WR",
data_access[n].size));
}
}
}
void bxInstrumentation::bx_instr_before_execution(bxInstruction_c *i)
{
eipSave = BX_CPU(cpu_id)->gen_reg[BX_32BIT_REG_EIP].dword.erx;
//
// -- check if we have `xchg edx,edx` and if so we will toggle the active flag
// ------------------------------------------------------------------------
if (i->get_opcode_bytes()[0] == 0x87 && i->get_opcode_bytes()[1] == 0xd2) {
toggle_active();
if (is_active()) {
BX_INFO(("Instrumentation is now ON"));
} else {
BX_INFO(("Instrumentation is now off"));
}
}
if (!active) return;
if (ready) bx_print_instruction();
// prepare instruction_t structure for new instruction
ready = 1;
num_data_accesses = 0;
is_branch = 0;
is32 = BX_CPU(cpu_id)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b;
is64 = BX_CPU(cpu_id)->long64_mode();
opcode_length = i->ilen();
memcpy(opcode, i->get_opcode_bytes(), opcode_length);
}
void bxInstrumentation::bx_instr_after_execution(bxInstruction_c *i)
{
if (!active) return;
if (ready) {
bx_print_instruction();
ready = 0;
}
}
void bxInstrumentation::branch_taken(bx_address new_eip)
{
if (!active || !ready) return;
is_branch = 1;
is_taken = 1;
// find linear address
target_linear = BX_CPU(cpu_id)->get_laddr(BX_SEG_REG_CS, new_eip);
}
void bxInstrumentation::bx_instr_cnear_branch_taken(bx_address branch_eip, bx_address new_eip)
{
branch_taken(new_eip);
}
void bxInstrumentation::bx_instr_cnear_branch_not_taken(bx_address branch_eip)
{
if (!active || !ready) return;
is_branch = 1;
is_taken = 0;
}
void bxInstrumentation::bx_instr_ucnear_branch(unsigned what, bx_address branch_eip, bx_address new_eip)
{
branch_taken(new_eip);
}
void bxInstrumentation::bx_instr_far_branch(unsigned what, Bit16u prev_cs, bx_address prev_eip, Bit16u new_cs, bx_address new_eip)
{
branch_taken(new_eip);
}
void bxInstrumentation::bx_instr_interrupt(unsigned vector)
{
if(active)
{
BX_INFO(("CPU %u: interrupt %02xh", cpu_id, vector));
}
}
void bxInstrumentation::bx_instr_exception(unsigned vector, unsigned error_code)
{
if(active)
{
BX_INFO(("CPU %u: exception %02xh error_code=%x", cpu_id, vector, error_code));
BX_CPU_C *cpu;
#if BX_SUPPORT_SMP
cpu = bx_cpu_array[cpu_id];
#else
cpu = &bx_cpu;
#endif
cpu->debug(0);
}
}
void bxInstrumentation::bx_instr_hwinterrupt(unsigned vector, Bit16u cs, bx_address eip)
{
if(active)
{
BX_INFO(("CPU %u: hardware interrupt %02xh", cpu_id, vector));
}
}
void bxInstrumentation::bx_instr_lin_access(bx_address lin, bx_phy_address phy, unsigned len, unsigned memtype, unsigned rw)
{
if(!active || !ready) return;
if (num_data_accesses < MAX_DATA_ACCESSES) {
data_access[num_data_accesses].laddr = lin;
data_access[num_data_accesses].paddr = phy;
data_access[num_data_accesses].rw = rw;
data_access[num_data_accesses].size = len;
data_access[num_data_accesses].memtype = memtype;
num_data_accesses++;
}
}
| 31.878229
| 130
| 0.573793
|
eryjus
|
09661d776586905743293e00b25c523c21f0b200
| 3,792
|
cpp
|
C++
|
RTIDPRR/Source/Graphics/Core/Buffer.cpp
|
brunosegiu/RTIDPRR
|
d7daef7611899db4e23ba6a2b5a91135c57e0871
|
[
"MIT"
] | 3
|
2020-12-06T02:22:48.000Z
|
2021-06-24T13:52:10.000Z
|
RTIDPRR/Source/Graphics/Core/Buffer.cpp
|
brunosegiu/RTIDPRR
|
d7daef7611899db4e23ba6a2b5a91135c57e0871
|
[
"MIT"
] | null | null | null |
RTIDPRR/Source/Graphics/Core/Buffer.cpp
|
brunosegiu/RTIDPRR
|
d7daef7611899db4e23ba6a2b5a91135c57e0871
|
[
"MIT"
] | 1
|
2021-10-13T10:36:36.000Z
|
2021-10-13T10:36:36.000Z
|
#include "Buffer.h"
#include "Command.h"
#include "Context.h"
#include "DeviceMemory.h"
using namespace RTIDPRR::Graphics;
Buffer::Buffer(const vk::DeviceSize& size, const vk::BufferUsageFlags& usage,
const vk::MemoryPropertyFlags& memoryProperties)
: mSize(size) {
const Device& device = Context::get().getDevice();
vk::BufferCreateInfo bufferCreateInfo =
vk::BufferCreateInfo().setSize(size).setUsage(usage).setSharingMode(
vk::SharingMode::eExclusive);
mBuffer = RTIDPRR_ASSERT_VK(
device.getLogicalDeviceHandle().createBuffer(bufferCreateInfo));
vk::MemoryRequirements memRequirements =
device.getLogicalDeviceHandle().getBufferMemoryRequirements(mBuffer);
vk::MemoryAllocateInfo memAllocInfo =
vk::MemoryAllocateInfo()
.setAllocationSize(memRequirements.size)
.setMemoryTypeIndex(DeviceMemory::findMemoryIndex(
memRequirements.memoryTypeBits, memoryProperties));
mMemory = RTIDPRR_ASSERT_VK(
device.getLogicalDeviceHandle().allocateMemory(memAllocInfo));
RTIDPRR_ASSERT_VK(
device.getLogicalDeviceHandle().bindBufferMemory(mBuffer, mMemory, 0));
mPMapped = nullptr;
}
Buffer::Buffer(Buffer&& other)
: mBuffer(std::move(other.mBuffer)),
mMemory(std::move(other.mMemory)),
mSize(std::move(other.mSize)) {
other.mBuffer = nullptr;
other.mMemory = nullptr;
}
const vk::DeviceSize Buffer::sInvalidSize = static_cast<vk::DeviceSize>(-1);
void Buffer::update(const void* value, const vk::DeviceSize& offset,
const vk::DeviceSize& size) {
const Device& device = Context::get().getDevice();
vk::DeviceSize effectiveSize = size == Buffer::sInvalidSize ? mSize : size;
void* data = RTIDPRR_ASSERT_VK(device.getLogicalDeviceHandle().mapMemory(
mMemory, offset, effectiveSize, vk::MemoryMapFlags{}));
memcpy(data, value, effectiveSize);
device.getLogicalDeviceHandle().unmapMemory(mMemory);
}
void* Buffer::map() {
if (!mPMapped) {
const Device& device = Context::get().getDevice();
mPMapped = RTIDPRR_ASSERT_VK(device.getLogicalDeviceHandle().mapMemory(
mMemory, 0, mSize, vk::MemoryMapFlags{}));
}
return mPMapped;
}
void Buffer::unmap() {
const Device& device = Context::get().getDevice();
device.getLogicalDeviceHandle().unmapMemory(mMemory);
mPMapped = nullptr;
}
void Buffer::copyInto(Buffer& other) {
const Device& device = Context::get().getDevice();
const Queue& graphicsQueue = device.getGraphicsQueue();
Command* command = Context::get().getCommandPool().allocateGraphicsCommand();
// Copy
vk::CommandBufferBeginInfo commandBeginInfo =
vk::CommandBufferBeginInfo().setFlags(
vk::CommandBufferUsageFlagBits::eOneTimeSubmit);
RTIDPRR_ASSERT_VK(command->begin(commandBeginInfo));
vk::BufferCopy copyRegion =
vk::BufferCopy().setSrcOffset(0).setDstOffset(0).setSize(mSize);
command->copyBuffer(mBuffer, other.mBuffer, copyRegion);
RTIDPRR_ASSERT_VK(command->end());
vk::SubmitInfo submitInfo = vk::SubmitInfo().setCommandBuffers(
*static_cast<vk::CommandBuffer*>(command));
vk::FenceCreateInfo fenceCreateInfo = vk::FenceCreateInfo();
vk::Fence waitFence = RTIDPRR_ASSERT_VK(
device.getLogicalDeviceHandle().createFence(fenceCreateInfo));
graphicsQueue.submit(submitInfo, waitFence);
vk::Result copyRes = device.getLogicalDeviceHandle().waitForFences(
waitFence, true, std::numeric_limits<uint64_t>::max());
RTIDPRR_ASSERT(copyRes == vk::Result::eSuccess);
device.getLogicalDeviceHandle().destroyFence(waitFence);
}
Buffer::~Buffer() {
const Device& device = Context::get().getDevice();
device.getLogicalDeviceHandle().destroyBuffer(mBuffer);
device.getLogicalDeviceHandle().freeMemory(mMemory);
}
| 36.461538
| 79
| 0.726002
|
brunosegiu
|
096a3969d7f748663f63ee71124263026f3bfee6
| 513
|
cpp
|
C++
|
codeshef/CIN011.cpp
|
sonuKumar03/data-structure-and-algorithm
|
d1fd3cad494cbcc91ce7ff37ec611752369b50b6
|
[
"MIT"
] | null | null | null |
codeshef/CIN011.cpp
|
sonuKumar03/data-structure-and-algorithm
|
d1fd3cad494cbcc91ce7ff37ec611752369b50b6
|
[
"MIT"
] | null | null | null |
codeshef/CIN011.cpp
|
sonuKumar03/data-structure-and-algorithm
|
d1fd3cad494cbcc91ce7ff37ec611752369b50b6
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<fstream>
#include<climits>
#include<math.h>
using namespace std;
typedef long long ll ;
void solve(){
ll n ;
cin>>n;
ll *roses = new ll[n];
for(int i =0;i<n;i++){
cin>>roses[i];
}
ll happiness = -1;
for(int i =0;i<n;i++){
int t = roses[i] + happiness;
if(t>happiness){
happiness = t;
}
}
cout<<happiness<<endl;
}
int main() {
ll t;
cin>>t;
while(t--){
solve();
}
return 0;
}
| 14.25
| 33
| 0.569201
|
sonuKumar03
|
096f6455e70034e7bad0407873ba591b77351925
| 18,237
|
cpp
|
C++
|
PersistentStore/SqliteStore.cpp
|
MFransen69/rdkservices
|
ce13efeb95779bc04c20e69be5fe86fd8565a6c6
|
[
"BSD-2-Clause"
] | null | null | null |
PersistentStore/SqliteStore.cpp
|
MFransen69/rdkservices
|
ce13efeb95779bc04c20e69be5fe86fd8565a6c6
|
[
"BSD-2-Clause"
] | null | null | null |
PersistentStore/SqliteStore.cpp
|
MFransen69/rdkservices
|
ce13efeb95779bc04c20e69be5fe86fd8565a6c6
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2022 RDK Management
*
* 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 "SqliteStore.h"
#include "UtilsLogging.h"
#include <sqlite3.h>
#if defined(USE_PLABELS)
#include "pbnj_utils.hpp"
#include <glib.h>
#endif
#ifndef SQLITE_FILE_HEADER
#define SQLITE_FILE_HEADER "SQLite format 3"
#endif
#define SQLITE *(sqlite3**)&_data
#define SQLITE_IS_ERROR_DBWRITE(rc) (rc == SQLITE_READONLY || rc == SQLITE_CORRUPT)
namespace {
#if defined(USE_PLABELS)
bool GenerateKey(const char *key, std::vector<uint8_t> &pKey)
{
// NOTE: pbnj_utils stores the nonce under XDG_DATA_HOME/data.
// If the dir doesn't exist it will fail
auto path = g_build_filename(g_get_user_data_dir(), "data", nullptr);
if (!Core::File(string(path)).Exists())
g_mkdir_with_parents(path, 0755);
g_free(path);
return pbnj_utils::prepareBufferForOrigin(key, [&pKey](const std::vector<uint8_t> &buffer)
{
pKey = buffer;
});
}
#endif
}
namespace WPEFramework {
namespace Plugin {
SqliteStore::SqliteStore()
: _data(nullptr),
_path(),
_key(),
_maxSize(0),
_maxValue(0),
_clients(),
_clientLock(),
_lock()
{
}
uint32_t SqliteStore::Register(Exchange::IStore::INotification *notification)
{
Core::SafeSyncType<Core::CriticalSection> lock(_clientLock);
ASSERT(std::find(_clients.begin(), _clients.end(), notification) == _clients.end());
notification->AddRef();
_clients.push_back(notification);
return Core::ERROR_NONE;
}
uint32_t SqliteStore::Unregister(Exchange::IStore::INotification *notification)
{
Core::SafeSyncType<Core::CriticalSection> lock(_clientLock);
std::list<Exchange::IStore::INotification *>::iterator
index(std::find(_clients.begin(), _clients.end(), notification));
ASSERT(index != _clients.end());
if (index != _clients.end()) {
notification->Release();
_clients.erase(index);
}
return Core::ERROR_NONE;
}
uint32_t SqliteStore::Open(const string &path, const string &key, uint32_t maxSize, uint32_t maxValue)
{
CountingLockSync lock(_lock, 0);
if (IsOpen()) {
// Seems open!
return Core::ERROR_ILLEGAL_STATE;
}
Close();
_path = path;
_key = key;
_maxSize = maxSize;
_maxValue = maxValue;
#if defined(SQLITE_HAS_CODEC)
bool shouldEncrypt = !key.empty();
bool shouldReKey = shouldEncrypt && IsValid() && !IsEncrypted();
std::vector<uint8_t> pKey;
if (shouldEncrypt) {
#if defined(USE_PLABELS)
if (!GenerateKey(key.c_str(), pKey)) {
LOGERR("pbnj_utils fail");
Close();
return Core::ERROR_GENERAL;
}
#else
LOGWARN("Key is not secure");
pKey = std::vector<uint8_t>(key.begin(), key.end());
#endif
}
#endif
sqlite3* &db = SQLITE;
int rc = sqlite3_open(path.c_str(), &db);
if (rc != SQLITE_OK) {
LOGERR("%d : %s", rc, sqlite3_errstr(rc));
Close();
return Core::ERROR_OPENING_FAILED;
}
#if defined(SQLITE_HAS_CODEC)
if (shouldEncrypt) {
rc = Encrypt(pKey);
if (rc != SQLITE_OK) {
LOGERR("Failed to attach key - %s", sqlite3_errstr(rc));
Close();
return Core::ERROR_GENERAL;
}
}
#endif
rc = CreateTables();
#if defined(SQLITE_HAS_CODEC)
if (rc == SQLITE_NOTADB
&& shouldEncrypt
&& !shouldReKey // re-key should never fail
) {
LOGWARN("The key doesn't work");
Close();
if (!Core::File(path).Destroy() || IsValid()) {
LOGERR("Can't remove file");
return Core::ERROR_DESTRUCTION_FAILED;
}
sqlite3* &db = SQLITE;
rc = sqlite3_open(path.c_str(), &db);
if (rc != SQLITE_OK) {
LOGERR("Can't create file");
return Core::ERROR_OPENING_FAILED;
}
LOGWARN("SQLite database has been reset, trying re-key");
rc = Encrypt(pKey);
if (rc != SQLITE_OK) {
LOGERR("Failed to attach key - %s", sqlite3_errstr(rc));
Close();
return Core::ERROR_GENERAL;
}
rc = CreateTables();
}
#endif
return Core::ERROR_NONE;
}
uint32_t SqliteStore::SetValue(const string &ns, const string &key, const string &value)
{
if (ns.size() > _maxValue ||
key.size() > _maxValue ||
value.size() > _maxValue) {
return Core::ERROR_INVALID_INPUT_LENGTH;
}
uint32_t result = Core::ERROR_GENERAL;
int retry = 0;
int rc;
do {
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
if (!db)
break;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "SELECT sum(s) FROM ("
" SELECT sum(length(key)+length(value)) s FROM item"
" UNION ALL"
" SELECT sum(length(name)) s FROM namespace"
");", -1, &stmt, nullptr);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
int64_t size = sqlite3_column_int64(stmt, 0);
if (size > _maxSize) {
LOGWARN("max size exceeded: %ld", size);
result = Core::ERROR_WRITE_ERROR;
} else {
result = Core::ERROR_NONE;
}
}
else
LOGERR("ERROR getting size: %s", sqlite3_errstr(rc));
sqlite3_finalize(stmt);
if (result == Core::ERROR_NONE) {
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "INSERT OR IGNORE INTO namespace (name) values (?);", -1, &stmt, nullptr);
sqlite3_bind_text(stmt, 1, ns.c_str(), -1, SQLITE_TRANSIENT);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
LOGERR("ERROR inserting data: %s", sqlite3_errstr(rc));
result = Core::ERROR_GENERAL;
}
sqlite3_finalize(stmt);
}
if (result == Core::ERROR_NONE) {
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "INSERT INTO item (ns,key,value)"
" SELECT id, ?, ?"
" FROM namespace"
" WHERE name = ?"
";", -1, &stmt, nullptr);
sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, value.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 3, ns.c_str(), -1, SQLITE_TRANSIENT);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
LOGERR("ERROR inserting data: %s", sqlite3_errstr(rc));
result = Core::ERROR_GENERAL;
}
else {
ValueChanged(ns, key, value);
}
sqlite3_finalize(stmt);
}
}
while ((result != Core::ERROR_NONE) &&
SQLITE_IS_ERROR_DBWRITE(rc) &&
(++retry < 2) &&
(Open(_path, _key, _maxSize, _maxValue) == Core::ERROR_NONE));
if (result == Core::ERROR_NONE) {
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "SELECT sum(s) FROM ("
" SELECT sum(length(key)+length(value)) s FROM item"
" UNION ALL"
" SELECT sum(length(name)) s FROM namespace"
");", -1, &stmt, nullptr);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
int64_t size = sqlite3_column_int64(stmt, 0);
if (size > _maxSize) {
LOGWARN("max size exceeded: %ld", size);
StorageExceeded();
}
}
else
LOGERR("ERROR getting size: %s", sqlite3_errstr(rc));
sqlite3_finalize(stmt);
}
return result;
}
uint32_t SqliteStore::GetValue(const string &ns, const string &key, string &value)
{
uint32_t result = Core::ERROR_GENERAL;
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
if (db) {
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "SELECT value"
" FROM item"
" INNER JOIN namespace ON namespace.id = item.ns"
" where name = ? and key = ?"
";", -1, &stmt, nullptr);
sqlite3_bind_text(stmt, 1, ns.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, key.c_str(), -1, SQLITE_TRANSIENT);
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
value = (const char *) sqlite3_column_text(stmt, 0);
result = Core::ERROR_NONE;
}
else
LOGWARN("not found: %d", rc);
sqlite3_finalize(stmt);
}
return result;
}
uint32_t SqliteStore::DeleteKey(const string &ns, const string &key)
{
uint32_t result = Core::ERROR_GENERAL;
int retry = 0;
int rc;
do {
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
if (!db)
break;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "DELETE FROM item"
" where ns in (select id from namespace where name = ?)"
" and key = ?"
";", -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, ns.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, key.c_str(), -1, SQLITE_TRANSIENT);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
LOGERR("ERROR removing data: %s", sqlite3_errstr(rc));
else
result = Core::ERROR_NONE;
sqlite3_finalize(stmt);
}
while ((result != Core::ERROR_NONE) &&
SQLITE_IS_ERROR_DBWRITE(rc) &&
(++retry < 2) &&
(Open(_path, _key, _maxSize, _maxValue) == Core::ERROR_NONE));
return result;
}
uint32_t SqliteStore::DeleteNamespace(const string &ns)
{
uint32_t result = Core::ERROR_GENERAL;
int retry = 0;
int rc;
do {
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
if (!db)
break;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "DELETE FROM namespace where name = ?;", -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, ns.c_str(), -1, SQLITE_TRANSIENT);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
LOGERR("ERROR removing data: %s", sqlite3_errstr(rc));
else
result = Core::ERROR_NONE;
sqlite3_finalize(stmt);
}
while ((result != Core::ERROR_NONE) &&
SQLITE_IS_ERROR_DBWRITE(rc) &&
(++retry < 2) &&
(Open(_path, _key, _maxSize, _maxValue) == Core::ERROR_NONE));
return result;
}
uint32_t SqliteStore::GetKeys(const string &ns, std::vector<string> &keys)
{
uint32_t result = Core::ERROR_GENERAL;
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
keys.clear();
if (db) {
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "SELECT key"
" FROM item"
" where ns in (select id from namespace where name = ?)"
";", -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, ns.c_str(), -1, SQLITE_TRANSIENT);
while (sqlite3_step(stmt) == SQLITE_ROW)
keys.push_back((const char *) sqlite3_column_text(stmt, 0));
sqlite3_finalize(stmt);
result = Core::ERROR_NONE;
}
return result;
}
uint32_t SqliteStore::GetNamespaces(std::vector<string> &namespaces)
{
uint32_t result = Core::ERROR_GENERAL;
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
namespaces.clear();
if (db) {
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "SELECT name FROM namespace;", -1, &stmt, NULL);
while (sqlite3_step(stmt) == SQLITE_ROW)
namespaces.push_back((const char *) sqlite3_column_text(stmt, 0));
sqlite3_finalize(stmt);
result = Core::ERROR_NONE;
}
return result;
}
uint32_t SqliteStore::GetStorageSize(std::map<string, uint64_t> &namespaceSizes)
{
uint32_t result = Core::ERROR_GENERAL;
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
namespaceSizes.clear();
if (db) {
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "SELECT name, sum(length(key)+length(value))"
" FROM item"
" INNER JOIN namespace ON namespace.id = item.ns"
" GROUP BY name"
";", -1, &stmt, NULL);
while (sqlite3_step(stmt) == SQLITE_ROW)
namespaceSizes[(const char *) sqlite3_column_text(stmt, 0)] = sqlite3_column_int(stmt, 1);
sqlite3_finalize(stmt);
result = Core::ERROR_NONE;
}
return result;
}
uint32_t SqliteStore::FlushCache()
{
uint32_t result = Core::ERROR_GENERAL;
CountingLockSync lock(_lock);
sqlite3* &db = SQLITE;
if (db) {
int rc = sqlite3_db_cacheflush(db);
if (rc != SQLITE_OK) {
LOGERR("Error while flushing sqlite database cache: %d", rc);
}
else {
result = Core::ERROR_NONE;
}
}
sync();
return result;
}
uint32_t SqliteStore::Term()
{
CountingLockSync lock(_lock, 0);
Close();
return Core::ERROR_NONE;
}
void SqliteStore::ValueChanged(const string &ns, const string &key, const string &value)
{
Core::SafeSyncType<Core::CriticalSection> lock(_clientLock);
std::list<Exchange::IStore::INotification *>::iterator
index(_clients.begin());
while (index != _clients.end()) {
(*index)->ValueChanged(ns, key, value);
index++;
}
}
void SqliteStore::StorageExceeded()
{
Core::SafeSyncType<Core::CriticalSection> lock(_clientLock);
std::list<Exchange::IStore::INotification *>::iterator
index(_clients.begin());
while (index != _clients.end()) {
(*index)->StorageExceeded();
index++;
}
}
int SqliteStore::Encrypt(const std::vector<uint8_t> &key)
{
int rc = SQLITE_OK;
#if defined(SQLITE_HAS_CODEC)
sqlite3* &db = SQLITE;
bool shouldReKey = !IsEncrypted();
if (!shouldReKey) {
rc = sqlite3_key_v2(db, nullptr, key.data(), key.size());
} else {
rc = sqlite3_rekey_v2(db, nullptr, key.data(), key.size());
if (rc == SQLITE_OK)
Vacuum();
}
if (shouldReKey && !IsEncrypted()) {
LOGERR("SQLite database file is clear after re-key");
}
#endif
return rc;
}
int SqliteStore::CreateTables()
{
sqlite3* &db = SQLITE;
char *errmsg;
int rc = sqlite3_exec(db, "CREATE TABLE if not exists namespace ("
"id INTEGER PRIMARY KEY,"
"name TEXT UNIQUE"
");", 0, 0, &errmsg);
if (rc != SQLITE_OK || errmsg) {
if (errmsg) {
LOGERR("%d : %s", rc, errmsg);
sqlite3_free(errmsg);
}
else
LOGERR("%d", rc);
return rc;
}
rc = sqlite3_exec(db, "CREATE TABLE if not exists item ("
"ns INTEGER,"
"key TEXT,"
"value TEXT,"
"FOREIGN KEY(ns) REFERENCES namespace(id) ON DELETE CASCADE ON UPDATE NO ACTION,"
"UNIQUE(ns,key) ON CONFLICT REPLACE"
");", 0, 0, &errmsg);
if (rc != SQLITE_OK || errmsg) {
if (errmsg) {
LOGERR("%d : %s", rc, errmsg);
sqlite3_free(errmsg);
}
else
LOGERR("%d", rc);
return rc;
}
rc = sqlite3_exec(db, "PRAGMA foreign_keys = ON;", 0, 0, &errmsg);
if (rc != SQLITE_OK || errmsg) {
if (errmsg) {
LOGERR("%d : %s", rc, errmsg);
sqlite3_free(errmsg);
}
else
LOGERR("%d", rc);
return rc;
}
return SQLITE_OK;
}
int SqliteStore::Vacuum()
{
sqlite3* &db = SQLITE;
char *errmsg;
int rc = sqlite3_exec(db, "VACUUM", 0, 0, &errmsg);
if (rc != SQLITE_OK || errmsg) {
if (errmsg) {
LOGERR("%s", errmsg);
sqlite3_free(errmsg);
}
else {
LOGERR("%d", rc);
}
return rc;
}
return SQLITE_OK;
}
int SqliteStore::Close()
{
sqlite3* &db = SQLITE;
if (db) {
int rc = sqlite3_db_cacheflush(db);
if (rc != SQLITE_OK) {
LOGERR("Error while flushing sqlite database cache: %d", rc);
}
sqlite3_close_v2(db);
}
db = nullptr;
return SQLITE_OK;
}
bool SqliteStore::IsOpen() const
{
sqlite3* &db = SQLITE;
return (db && IsValid());
}
bool SqliteStore::IsValid() const
{
return (Core::File(_path).Exists());
}
bool SqliteStore::IsEncrypted() const
{
bool result = false;
Core::File file(_path);
if (file.Exists() && file.Open(true)) {
const uint32_t bufLen = strlen(SQLITE_FILE_HEADER);
char buffer[bufLen];
result =
(file.Read(reinterpret_cast<uint8_t *>(buffer), bufLen) != bufLen) ||
(::memcmp(buffer, SQLITE_FILE_HEADER, bufLen) != 0);
}
return result;
}
} // namespace Plugin
} // namespace WPEFramework
| 25.119835
| 109
| 0.551132
|
MFransen69
|
09705a8a905f583738cbc53fc70fa2e3c0205846
| 136
|
cpp
|
C++
|
test/llvm_test_code/linear_constant/call_10.cpp
|
janniclas/phasar
|
324302ae96795e6f0a065c14d4f7756b1addc2a4
|
[
"MIT"
] | 1
|
2022-02-15T07:56:29.000Z
|
2022-02-15T07:56:29.000Z
|
test/llvm_test_code/linear_constant/call_10.cpp
|
fabianbs96/phasar
|
5b8acd046d8676f72ce0eb85ca20fdb0724de444
|
[
"MIT"
] | null | null | null |
test/llvm_test_code/linear_constant/call_10.cpp
|
fabianbs96/phasar
|
5b8acd046d8676f72ce0eb85ca20fdb0724de444
|
[
"MIT"
] | null | null | null |
void bar(int b) {}
void foo(int a) { // clang-format off
bar(a);
} // clang-format on
int main() {
int i;
foo(2);
return 0;
}
| 11.333333
| 37
| 0.551471
|
janniclas
|
097198218d7ba6feaff553a04757aefc9ada1651
| 5,030
|
cc
|
C++
|
topside/qgc/src/AutoPilotPlugins/AutoPilotPluginManager.cc
|
slicht-uri/Sandshark-Beta-Lab-
|
6cff36b227b49b776d13187c307e648d2a52bdae
|
[
"MIT"
] | null | null | null |
topside/qgc/src/AutoPilotPlugins/AutoPilotPluginManager.cc
|
slicht-uri/Sandshark-Beta-Lab-
|
6cff36b227b49b776d13187c307e648d2a52bdae
|
[
"MIT"
] | null | null | null |
topside/qgc/src/AutoPilotPlugins/AutoPilotPluginManager.cc
|
slicht-uri/Sandshark-Beta-Lab-
|
6cff36b227b49b776d13187c307e648d2a52bdae
|
[
"MIT"
] | 1
|
2019-10-18T06:25:14.000Z
|
2019-10-18T06:25:14.000Z
|
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "AutoPilotPluginManager.h"
#include "PX4/PX4AutoPilotPlugin.h"
#include "Generic/GenericAutoPilotPlugin.h"
#include "QGCApplication.h"
#include "UASManager.h"
IMPLEMENT_QGC_SINGLETON(AutoPilotPluginManager, AutoPilotPluginManager)
AutoPilotPluginManager::AutoPilotPluginManager(QObject* parent) :
QGCSingleton(parent)
{
UASManagerInterface* uasMgr = UASManager::instance();
Q_ASSERT(uasMgr);
// We need to track uas coming and going so that we can instantiate plugins for each uas
connect(uasMgr, &UASManagerInterface::UASCreated, this, &AutoPilotPluginManager::_uasCreated);
connect(uasMgr, &UASManagerInterface::UASDeleted, this, &AutoPilotPluginManager::_uasDeleted);
}
AutoPilotPluginManager::~AutoPilotPluginManager()
{
#ifdef QT_DEBUG
foreach(MAV_AUTOPILOT mavType, _pluginMap.keys()) {
Q_ASSERT_X(_pluginMap[mavType].count() == 0, "AutoPilotPluginManager", "LinkManager::_shutdown should have already closed all uas");
}
#endif
_pluginMap.clear();
PX4AutoPilotPlugin::clearStaticData();
GenericAutoPilotPlugin::clearStaticData();
}
/// Create the plugin for this uas
void AutoPilotPluginManager::_uasCreated(UASInterface* uas)
{
Q_ASSERT(uas);
MAV_AUTOPILOT autopilotType = static_cast<MAV_AUTOPILOT>(uas->getAutopilotType());
int uasId = uas->getUASID();
Q_ASSERT(uasId != 0);
if (_pluginMap.contains(autopilotType)) {
Q_ASSERT_X(!_pluginMap[autopilotType].contains(uasId), "AutoPilotPluginManager", "Either we have duplicate UAS ids, or a UAS was not removed correctly.");
}
AutoPilotPlugin* plugin;
switch (autopilotType) {
case MAV_AUTOPILOT_PX4:
plugin = new PX4AutoPilotPlugin(uas, this);
Q_CHECK_PTR(plugin);
_pluginMap[MAV_AUTOPILOT_PX4][uasId] = plugin;
break;
case MAV_AUTOPILOT_GENERIC:
default:
plugin = new GenericAutoPilotPlugin(uas, this);
Q_CHECK_PTR(plugin);
_pluginMap[MAV_AUTOPILOT_GENERIC][uasId] = plugin;
}
}
/// Destroy the plugin associated with this uas
void AutoPilotPluginManager::_uasDeleted(UASInterface* uas)
{
Q_ASSERT(uas);
MAV_AUTOPILOT autopilotType = _installedAutopilotType(static_cast<MAV_AUTOPILOT>(uas->getAutopilotType()));
int uasId = uas->getUASID();
Q_ASSERT(uasId != 0);
Q_ASSERT(_pluginMap.contains(autopilotType));
Q_ASSERT(_pluginMap[autopilotType].contains(uasId));
delete _pluginMap[autopilotType][uasId];
_pluginMap[autopilotType].remove(uasId);
}
AutoPilotPlugin* AutoPilotPluginManager::getInstanceForAutoPilotPlugin(UASInterface* uas)
{
Q_ASSERT(uas);
MAV_AUTOPILOT autopilotType = _installedAutopilotType(static_cast<MAV_AUTOPILOT>(uas->getAutopilotType()));
int uasId = uas->getUASID();
Q_ASSERT(uasId != 0);
Q_ASSERT(_pluginMap.contains(autopilotType));
Q_ASSERT(_pluginMap[autopilotType].contains(uasId));
return _pluginMap[autopilotType][uasId];
}
QList<AutoPilotPluginManager::FullMode_t> AutoPilotPluginManager::getModes(int autopilotType) const
{
switch (autopilotType) {
case MAV_AUTOPILOT_PX4:
return PX4AutoPilotPlugin::getModes();
case MAV_AUTOPILOT_GENERIC:
default:
return GenericAutoPilotPlugin::getModes();
}
}
QString AutoPilotPluginManager::getShortModeText(uint8_t baseMode, uint32_t customMode, int autopilotType) const
{
switch (autopilotType) {
case MAV_AUTOPILOT_PX4:
return PX4AutoPilotPlugin::getShortModeText(baseMode, customMode);
case MAV_AUTOPILOT_GENERIC:
default:
return GenericAutoPilotPlugin::getShortModeText(baseMode, customMode);
}
}
/// If autopilot is not an installed plugin, returns MAV_AUTOPILOT_GENERIC
MAV_AUTOPILOT AutoPilotPluginManager::_installedAutopilotType(MAV_AUTOPILOT autopilot)
{
return _pluginMap.contains(autopilot) ? autopilot : MAV_AUTOPILOT_GENERIC;
}
| 35.174825
| 162
| 0.712326
|
slicht-uri
|
0973942ad6b4dc43319155d9cb62b01f3c1675d2
| 4,551
|
cpp
|
C++
|
Source/BlackWolf.Lupus.Core/Cookie.cpp
|
chronos38/lupus-core
|
ea5196b1b8663999f0a6fcfb5ee3dc5c01d48f32
|
[
"MIT"
] | null | null | null |
Source/BlackWolf.Lupus.Core/Cookie.cpp
|
chronos38/lupus-core
|
ea5196b1b8663999f0a6fcfb5ee3dc5c01d48f32
|
[
"MIT"
] | null | null | null |
Source/BlackWolf.Lupus.Core/Cookie.cpp
|
chronos38/lupus-core
|
ea5196b1b8663999f0a6fcfb5ee3dc5c01d48f32
|
[
"MIT"
] | 1
|
2020-10-03T05:05:03.000Z
|
2020-10-03T05:05:03.000Z
|
/**
* Copyright (C) 2014 David Wolf <d.wolf@live.at>
*
* This file is part of Lupus.
* 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 "Cookie.h"
#include "Version.h"
#include <iomanip>
#include <sstream>
using namespace std;
using namespace std::chrono;
namespace Lupus {
namespace Net {
Cookie::Cookie(String name, String value) :
mName(name), mValue(value)
{
}
Cookie::Cookie(String name, String value, String path) :
mName(name), mValue(value), mPath(path)
{
}
Cookie::Cookie(String name, String value, String path, String domain) :
mName(name), mValue(value), mPath(path), mDomain(domain)
{
}
String Cookie::Name() const
{
return mName;
}
void Cookie::Name(String value)
{
mName = value;
}
String Cookie::Value() const
{
return mValue;
}
void Cookie::Value(String value)
{
mValue = value;
}
String Cookie::Path() const
{
return mPath;
}
void Cookie::Path(String value)
{
mPath = value;
}
String Cookie::Domain() const
{
return mDomain;
}
void Cookie::Domain(String value)
{
mDomain = value;
}
bool Cookie::Expired() const
{
return mExpired;
}
void Cookie::Expired(bool value)
{
mExpired = value;
}
bool Cookie::HttpOnly() const
{
return mHttpOnly;
}
void Cookie::HttpOnly(bool value)
{
mHttpOnly = value;
}
bool Cookie::Secure() const
{
return mSecure;
}
void Cookie::Secure(bool value)
{
mSecure = value;
}
TimePoint Cookie::Expires() const
{
return mExpires;
}
void Cookie::Expires(const TimePoint& value)
{
mExpires = value;
}
String Cookie::ToString() const
{
String expires;
if (mExpired) {
stringstream ss;
time_t time = Clock::to_time_t(Clock::now());
tm timetm;
memset(&timetm, 0, sizeof(timetm));
localtime_s(&timetm, &time);
ss << put_time(&timetm, "%a, %Y-%b-%d %T GMT");
expires += ss.str();
} else if (mExpires != TimePoint::min()) {
stringstream ss;
time_t time = Clock::to_time_t(mExpires);
tm timetm;
memset(&timetm, 0, sizeof(timetm));
localtime_s(&timetm, &time);
ss << put_time(&timetm, "%a, %Y-%b-%d %T GMT");
expires += ss.str();
}
String result = mName + "=" + mValue;
result += (expires.IsEmpty() ? "" : ("; expires=" + expires));
result += (mDomain.IsEmpty() ? "" : ("; domain=" + mDomain));
result += (mPath.IsEmpty() ? "" : ("; path=" + mPath));
result += (mSecure ? "; secure" : "");
result += (mHttpOnly ? "; httponly" : "");
return result;
}
}
}
| 28.267081
| 80
| 0.513733
|
chronos38
|
0973f6e50c45617b6a11bd2d0a2cf3d767047959
| 2,811
|
cpp
|
C++
|
Actions/AddCircAction.cpp
|
OmarKimo/PaintForKids
|
21e41401e40d64880679f53efa4bf92fec06e783
|
[
"MIT"
] | 2
|
2022-01-19T20:39:14.000Z
|
2022-01-20T08:41:45.000Z
|
Actions/AddCircAction.cpp
|
OmarKimo/PaintForKids
|
21e41401e40d64880679f53efa4bf92fec06e783
|
[
"MIT"
] | null | null | null |
Actions/AddCircAction.cpp
|
OmarKimo/PaintForKids
|
21e41401e40d64880679f53efa4bf92fec06e783
|
[
"MIT"
] | null | null | null |
#include "AddCircAction.h"
#include "..\Figures\CCircle.h"
#include "..\ApplicationManager.h"
#include "..\GUI\input.h"
#include "..\GUI\Output.h"
AddCircAction::AddCircAction(ApplicationManager * pApp):Action(pApp)
{}
void AddCircAction::ReadActionParameters()
{
//Get a Pointer to the Input / Output Interfaces
Output* pOut = pManager->GetOutput();
Input* pIn = pManager->GetInput();
pOut->PrintMessage("New Circle: Click at Center");
//Read center and store in point Center
pIn->GetPointClicked(Center.x, Center.y);
pOut->PrintMessage("New Circle: Click at a point on the circle");
//Read a point on the circle and store in point P
pIn->GetPointClicked(P.x, P.y);
//////////////////
Center.x = (int)((Center.x - pOut->getZoomPoint().x) / pow(2, pOut->getZoomScale()) + pOut->getZoomPoint().x);
Center.y = (int)((Center.y - pOut->getZoomPoint().y) / pow(2, pOut->getZoomScale()) + pOut->getZoomPoint().y);
P.x = (int)((P.x - pOut->getZoomPoint().x) / pow(2, pOut->getZoomScale()) + pOut->getZoomPoint().x);
P.y = (int)((P.y - pOut->getZoomPoint().y) / pow(2, pOut->getZoomScale()) + pOut->getZoomPoint().y);
CircGfxInfo.isFilled = pManager->getDefaultFillStatus(); //default is not filled
//get drawing, filling colors and pen width from the interface
CircGfxInfo.DrawClr = pOut->getCrntDrawColor();
CircGfxInfo.FillClr = pOut->getCrntFillColor();
CircGfxInfo.BorderWdth = pOut->getCrntPenWidth();
pOut->ClearStatusBar();
}
//Execute the action
void AddCircAction::Execute()
{
//This action needs to read some parameters first
ReadActionParameters();
const int radius = sqrt(pow((P.x-Center.x),2) + pow((P.y-Center.y),2));
//Create a circle with the parameters read from the user
CCircle *C = new CCircle(Center, radius, CircGfxInfo);
if(!(C->checkLimits()))
pManager->GetOutput()->PrintMessage("Error!! You exceeded the limits of drawing area!");
else{
id = pManager->getNextID();
C->setID(id);
if(!pManager->AddFigure(C)) pManager->GetOutput()->PrintMessage("Error! You exceeded the number of MAX Figures (200)!"); //Add the circle to the list of figures
}
}
//bool AddCircAction::CanUndo() const
//{
// return true;
//}
//
//void AddCircAction::Undo()
//{
// pManager->DeleteFigureByID(id);
//}
//
//void AddCircAction::Redo()
//{
// //ReadActionParameters();
//
// const int radius = sqrt(pow((P.x-Center.x),2) + pow((P.y-Center.y),2));
//
// //Create a circle with the parameters read from the user
// CCircle *C = new CCircle(Center, radius, CircGfxInfo);
//
// if(!(C->checkLimits())){
// Output* pOut = pManager->GetOutput();
// pOut->PrintMessage("Error!! You exceeded the limits of drawing area!");
// }
// else{
// id = pManager->getNextID();
// C->setID(id);
// pManager->AddFigure(C); //Add the circle to the list of figures
// }
//}
| 30.225806
| 162
| 0.67556
|
OmarKimo
|
0975c8e52cf2a7a3ea23ce38e36b92ffcf6843b4
| 517
|
cc
|
C++
|
gearbox/t/core/config_file.t.cc
|
coryb/gearbox
|
88027f2f101c2d1fab16093928963052b9d3294d
|
[
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | 3
|
2015-06-26T15:37:40.000Z
|
2016-05-22T07:42:39.000Z
|
gearbox/t/core/config_file.t.cc
|
coryb/gearbox
|
88027f2f101c2d1fab16093928963052b9d3294d
|
[
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | null | null | null |
gearbox/t/core/config_file.t.cc
|
coryb/gearbox
|
88027f2f101c2d1fab16093928963052b9d3294d
|
[
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012, Yahoo! Inc. All rights reserved.
// Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
#include <tap/trivial.h>
#include <gearbox/core/ConfigFile.h>
using namespace Gearbox;
int main() {
chdir(TESTDIR);
TEST_START(5);
ConfigFile cfg("cfg/2.cfg");
Json a;
NOTHROW( a = cfg.get_json( "json" ) );
IS( a.empty(), true );
IS( a.length(), 0 );
IS( a.typeName(), "array" );
IS( a.serialize(), "[]" );
TEST_END;
}
| 21.541667
| 94
| 0.617021
|
coryb
|
097678ae1ef604a6f07542e23a230b58a61679e4
| 3,944
|
cpp
|
C++
|
Drivers/GranularJet/dec13_A254_Hi0075_RC06_MU05.cpp
|
gustavo-castillo-bautista/Mercury
|
eeb402ccec8e487652229d4595c46ec84f6aefbb
|
[
"BSD-3-Clause"
] | null | null | null |
Drivers/GranularJet/dec13_A254_Hi0075_RC06_MU05.cpp
|
gustavo-castillo-bautista/Mercury
|
eeb402ccec8e487652229d4595c46ec84f6aefbb
|
[
"BSD-3-Clause"
] | null | null | null |
Drivers/GranularJet/dec13_A254_Hi0075_RC06_MU05.cpp
|
gustavo-castillo-bautista/Mercury
|
eeb402ccec8e487652229d4595c46ec84f6aefbb
|
[
"BSD-3-Clause"
] | null | null | null |
//Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved.
//For the list of developers, see <http://www.MercuryDPM.org/Team>.
//
//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 MercuryDPM 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 MERCURYDPM DEVELOPERS TEAM 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 <sstream>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <Species/LinearViscoelasticSlidingFrictionSpecies.h>
#include "Funnel.h"
int main(int argc UNUSED, char *argv[] UNUSED)
{
Funnel problem;
// Problem parameters
problem.setName("dec13_A254_Hi0075_RC06_MU05");
auto species = problem.speciesHandler.copyAndAddObject(LinearViscoelasticSlidingFrictionSpecies());
species->setSlidingFrictionCoefficient(0.5);
species->setDensity(1442.0);
//problem.set_HGRID_max_levels(2);
//problem.set_HGRID_num_buckets(1e6);
// Particle properties
problem.setFixedParticleRadius(300e-6);
problem.setInflowParticleRadius(300e-6);
species->setCollisionTimeAndRestitutionCoefficient(4e-4, 0.6, species->getMassFromRadius(problem.getFixedParticleRadius()));
//problem.setStiffness(1e5*4/3*pi*problem.getInflowParticleRadius()*9.81*problem.getDensity());
//problem.set_disp(50*sqrt(9.81/(2*problem.getInflowParticleRadius());
std::cout << "Setting k to " << species->getStiffness() << " and disp to " << species->getDissipation() << std::endl;
species->setSlidingStiffness(species->getStiffness()*2.0/7.0);
species->setSlidingDissipation(species->getDissipation()*2.0/7.0);
double mass = species->getMassFromRadius(0.5 * (problem.getMinInflowParticleRadius() + problem.getMaxInflowParticleRadius()));
problem.setTimeStep(0.02 * species->getCollisionTime(mass));
problem.setTimeMax(3);
problem.setSaveCount(100);
problem.setChuteLength(0.6);
problem.setChuteWidth(0.25);
problem.setChuteAngle(25.4);
problem.setRoughBottomType(MONOLAYER_DISORDERED);
double funx = problem.getXMin()+0.5*(problem.getXMax()-problem.getXMin());
problem.set_funa(60.0);
problem.set_funD(0.015);
problem.set_funHf(0.075+(problem.getXMax()-funx)*sin(problem.getChuteAngle()));
problem.set_funnz(50.0);
problem.set_funO(-funx, 0.5*(problem.getYMax()-problem.getYMin()));
problem.set_funfr(0.3);
problem.setInflowVelocity(0);
problem.setInflowVelocityVariance(0.01);
problem.setMaxFailed(1);
//solve
//cout << "Maximum allowed speed of particles: " << problem.getMaximumVelocity() << endl; // speed allowed before particles move through each other!
std::cout << "dt=" << problem.getTimeStep() << std::endl;
problem.solve();
problem.writeRestartFile();
}
| 40.659794
| 149
| 0.761663
|
gustavo-castillo-bautista
|
097d29910f58bf15984a871e201ddf64e159f4b3
| 3,105
|
cpp
|
C++
|
tests/mapping/Map2DTest.cpp
|
jonahbardos/PY2020
|
af4f61b86ae5013e58faf4842bf20863b3de3957
|
[
"Apache-2.0"
] | 11
|
2019-10-03T01:17:16.000Z
|
2020-10-25T02:38:32.000Z
|
tests/mapping/Map2DTest.cpp
|
jonahbardos/PY2020
|
af4f61b86ae5013e58faf4842bf20863b3de3957
|
[
"Apache-2.0"
] | 53
|
2019-10-03T02:11:04.000Z
|
2021-06-05T03:11:55.000Z
|
tests/mapping/Map2DTest.cpp
|
jonahbardos/PY2020
|
af4f61b86ae5013e58faf4842bf20863b3de3957
|
[
"Apache-2.0"
] | 3
|
2019-09-20T04:09:29.000Z
|
2020-08-18T22:25:20.000Z
|
#define CATCH_CONFIG_MAIN
#include "mapping/Map2D.h"
#include <iostream>
#include <cmath>
#include <chrono>
#include <ctime>
#include <thread>
constexpr int test_iterations = 100;
constexpr int vertex_count = 1000;
constexpr int sparsity_factor = 2;
#include <catch2/catch.hpp>
namespace Mapping
{
// creates a map with given number of vertices
// when connecting neighbors, the probability that any node will be connected to any other node
// is 1 / sparse_factor
// thus if sparse_factor is 1, each node is connected to each other node
std::shared_ptr<Map2D> CreateRandMap(int vertices, int sparse_factor)
{
Map2D map;
for (int i = 0; i < vertices; i++)
{
Point2D p;
p.id = i;
p.x = (float)(rand() % vertices);
p.y = (float)(rand() % vertices);
std::shared_ptr<Point2D> p_ptr = std::make_shared<Point2D>(p);
for (int j = 0; j < map.vertices.size(); j++)
{
if (rand() % sparse_factor == 0)
{
Connect(p_ptr, map.vertices.at(j));
}
}
map.vertices.push_back(p_ptr);
}
return std::make_shared<Map2D>(map);
}
// randomly picks a start and end vertex, making sure they are different nodes
// returns average time of shortest path computation, in seconds
double TimeShortestPath(std::shared_ptr<Map2D> map, int num_iterations)
{
double avg = 0;
for (int i = 0; i < num_iterations; i++)
{
int start_ind = rand() % map->vertices.size();
int target_ind = rand() % map->vertices.size();
while (target_ind == start_ind)
{
target_ind = rand() % map->vertices.size();
}
auto start = std::chrono::system_clock::now();
ComputePath(map, map->vertices[start_ind], map->vertices[target_ind]);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
avg += elapsed_seconds.count() / num_iterations;
}
return avg;
}
bool verifyCorrectPath()
{
Map2D map;
float x_pts[10] = {0, -1, 2, -3, 4, -5, 6, -7, 8, -9};
float y_pts[10] = {0, -1, 2, -3, 4, -5, 6, -7, 8, -9};
for (int i = 0; i < 10; i++)
{
Point2D p;
p.id = i;
p.x = x_pts[i];
p.y = y_pts[i];
map.vertices.push_back(std::make_shared<Point2D>(p));
if (i > 0)
{
Connect(map.vertices[i], map.vertices[i - 1]);
}
}
Connect(map.vertices[9], map.vertices[2]);
std::vector<std::shared_ptr<Point2D>> actual = ComputePath(std::make_shared<Map2D>(map),
map.vertices[9], map.vertices[0]);
int expected[3] = {0, 1, 2};
for (int i = 0; i < actual.size(); i++)
{
if (expected[i] != actual[i]->id)
{
return false;
}
}
return true;
}
} // namespace Mapping
TEST_CASE("computes correct path")
{
REQUIRE(Mapping::verifyCorrectPath());
}
| 29.571429
| 98
| 0.554267
|
jonahbardos
|
09807f83c5fd4e83dddd8cef01b63649a688bc23
| 1,520
|
cpp
|
C++
|
attacker/SSL/sslPublic.cpp
|
satadriver/attacker
|
24e4434d8a836e040e48df195f2ca8919ab52609
|
[
"Apache-2.0"
] | null | null | null |
attacker/SSL/sslPublic.cpp
|
satadriver/attacker
|
24e4434d8a836e040e48df195f2ca8919ab52609
|
[
"Apache-2.0"
] | null | null | null |
attacker/SSL/sslPublic.cpp
|
satadriver/attacker
|
24e4434d8a836e040e48df195f2ca8919ab52609
|
[
"Apache-2.0"
] | 1
|
2022-03-20T03:21:00.000Z
|
2022-03-20T03:21:00.000Z
|
#include "sslPublic.h"
#include "../attacker.h"
#include "../FileOper.h"
#include <vector>
#include <iostream>
#include <string>
using namespace std;
WORKERCONTROL gWorkControl;
vector <string> gHostAttackList;
char G_USERNAME[64];
SSLPublic::SSLPublic(vector<string>list) {
if (mInstance)
{
return;
}
mInstance = this;
gHostAttackList = list;
}
SSLPublic::~SSLPublic() {
}
int SSLPublic::isTargetHost(string host) {
unsigned int targetlen = gHostAttackList.size();
for (unsigned int i = 0; i < targetlen; i++) {
if (strstr(host.c_str(), gHostAttackList[i].c_str())) {
return TRUE;
}
}
return FALSE;
}
int SSLPublic::prepareCertChain(string certname) {
int ret = 0;
string curpath = gLocalPath + CA_CERT_PATH +"\\";
string crtname = curpath + certname + ".crt";
string midcrtname = curpath+ certname + ".mid.crt";
string crtchainname = curpath+ certname + ".chain.crt";
string cafn = curpath + DIGICERTCA;
if (FileOper::isFileExist(crtchainname))
{
DeleteFileA(crtchainname.c_str());
}
string cmd = "cmd /c type " + crtname + " >> " + crtchainname;
ret = system(cmd.c_str());
cmd = "cmd /c echo.>> " + crtchainname;
ret = system(cmd.c_str());
cmd = "cmd /c type " + midcrtname + " >> " + crtchainname;
ret = system(cmd.c_str());
cmd = "cmd /c echo.>> " + crtchainname;
ret = system(cmd.c_str());
cmd = "cmd /c type " + cafn + " >> " + crtchainname;
ret = system(cmd.c_str());
cmd = "cmd /c echo.>> " + crtchainname;
ret = system(cmd.c_str());
return 0;
}
| 19.74026
| 63
| 0.651316
|
satadriver
|
09817f55dee6853da4cc8fcc42feaf934082197f
| 119
|
cpp
|
C++
|
src/IModel.cpp
|
soraphis/Boids-MPI
|
87ce64b6bfa5f8f9dba94a641046979621e7a71c
|
[
"MIT"
] | null | null | null |
src/IModel.cpp
|
soraphis/Boids-MPI
|
87ce64b6bfa5f8f9dba94a641046979621e7a71c
|
[
"MIT"
] | 1
|
2017-05-30T14:59:29.000Z
|
2017-05-30T14:59:29.000Z
|
src/IModel.cpp
|
soraphis/Boids-MPI
|
87ce64b6bfa5f8f9dba94a641046979621e7a71c
|
[
"MIT"
] | null | null | null |
/*
* IModel.cpp
*
* Created on: 29.06.2014
* Author: oliver
*/
#include "IModel.h"
IModel::~IModel(){
}
| 8.5
| 26
| 0.537815
|
soraphis
|
098189c807f15834fdc770132fb6df986d492496
| 203,441
|
cpp
|
C++
|
ds/ds/src/util/ldp/ldpdoc.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
ds/ds/src/util/ldp/ldpdoc.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
ds/ds/src/util/ldp/ldpdoc.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1996 - 1999
//
// File: ldpdoc.cpp
//
//--------------------------------------------------------------------------
/*******************************************************************
*
* File : ldpdoc.cpp
* Author : Eyal Schwartz
* Copyrights : Microsoft Corp (C) 1996
* Date : 10/21/1996
* Description : implementation of class CldpDoc
*
* Revisions : <date> <name> <description>
*******************************************************************/
// includes
#include "stdafx.h"
#include "Ldp.h"
#include "LdpDoc.h"
#include "LdpView.h"
#include "CnctDlg.h"
#include "MainFrm.h"
#include "string.h"
#include <rpc.h> // for SEC_WINNT_AUTH_IDENTITY
#include <drs.h>
#include <mdglobal.h>
#include <ntldap.h>
#include <sddl.h>
#include <schnlsp.h>
extern "C" {
#include <dsutil.h>
#include <x_list.h>
// BAS_TODO
// These are some silly.
typedef DWORD ULONG ;
SEC_WINNT_AUTH_IDENTITY_W gCreds = { 0 };
SEC_WINNT_AUTH_IDENTITY_W * gpCreds = NULL;
}
#if(_WIN32_WINNT < 0x0500)
// Currently due to some MFC issues, even on a 5.0 system this is left as a 4.0
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x500
#endif
#include <aclapi.h> // for Security Stuff
#include <aclapip.h> // for Security Stuff
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//
// Server stat info
//
#define PARSE_THREADCOUNT 1
#define PARSE_CALLTIME 3
#define PARSE_RETURNED 5
#define PARSE_VISITED 6
#define PARSE_FILTER 7
#define PARSE_INDEXES 8
#define MAXSVRSTAT 32
/////////////////////////////////////////////////////////////////////////////
// CLdpDoc
// Message maps
IMPLEMENT_DYNCREATE(CLdpDoc, CDocument)
BEGIN_MESSAGE_MAP(CLdpDoc, CDocument)
//{{AFX_MSG_MAP(CLdpDoc)
ON_COMMAND(ID_CONNECTION_BIND, OnConnectionBind)
ON_COMMAND(ID_CONNECTION_CONNECT, OnConnectionConnect)
ON_COMMAND(ID_CONNECTION_DISCONNECT, OnConnectionDisconnect)
ON_COMMAND(ID_BROWSE_SEARCH, OnBrowseSearch)
ON_UPDATE_COMMAND_UI(ID_BROWSE_SEARCH, OnUpdateBrowseSearch)
ON_COMMAND(ID_BROWSE_ADD, OnBrowseAdd)
ON_UPDATE_COMMAND_UI(ID_BROWSE_ADD, OnUpdateBrowseAdd)
ON_COMMAND(ID_BROWSE_DELETE, OnBrowseDelete)
ON_UPDATE_COMMAND_UI(ID_BROWSE_DELETE, OnUpdateBrowseDelete)
ON_COMMAND(ID_BROWSE_MODIFYRDN, OnBrowseModifyrdn)
ON_UPDATE_COMMAND_UI(ID_BROWSE_MODIFYRDN, OnUpdateBrowseModifyrdn)
ON_COMMAND(ID_BROWSE_MODIFY, OnBrowseModify)
ON_UPDATE_COMMAND_UI(ID_BROWSE_MODIFY, OnUpdateBrowseModify)
ON_COMMAND(ID_OPTIONS_SEARCH, OnOptionsSearch)
ON_COMMAND(ID_BROWSE_PENDING, OnBrowsePending)
ON_UPDATE_COMMAND_UI(ID_BROWSE_PENDING, OnUpdateBrowsePending)
ON_COMMAND(ID_OPTIONS_PEND, OnOptionsPend)
ON_UPDATE_COMMAND_UI(ID_CONNECTION_CONNECT, OnUpdateConnectionConnect)
ON_UPDATE_COMMAND_UI(ID_CONNECTION_DISCONNECT, OnUpdateConnectionDisconnect)
ON_COMMAND(ID_VIEW_SOURCE, OnViewSource)
ON_UPDATE_COMMAND_UI(ID_VIEW_SOURCE, OnUpdateViewSource)
ON_COMMAND(ID_OPTIONS_BIND, OnOptionsBind)
ON_COMMAND(ID_OPTIONS_PROTECTIONS, OnOptionsProtections)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_PROTECTIONS, OnUpdateOptionsProtections)
ON_COMMAND(ID_OPTIONS_GENERAL, OnOptionsGeneral)
ON_COMMAND(ID_BROWSE_COMPARE, OnBrowseCompare)
ON_UPDATE_COMMAND_UI(ID_BROWSE_COMPARE, OnUpdateBrowseCompare)
ON_COMMAND(ID_OPTIONS_DEBUG, OnOptionsDebug)
ON_COMMAND(ID_VIEW_TREE, OnViewTree)
ON_UPDATE_COMMAND_UI(ID_VIEW_TREE, OnUpdateViewTree)
ON_COMMAND(ID_OPTIONS_SERVEROPTIONS, OnOptionsServeroptions)
ON_COMMAND(ID_OPTIONS_CONTROLS, OnOptionsControls)
ON_COMMAND(ID_OPTIONS_SORTKEYS, OnOptionsSortkeys)
ON_COMMAND(ID_OPTIONS_SETFONT, OnOptionsSetFont)
ON_COMMAND(ID_BROWSE_SECURITY_SD, OnBrowseSecuritySd)
ON_COMMAND(ID_BROWSE_SECURITY_EFFECTIVE, OnBrowseSecurityEffective)
ON_UPDATE_COMMAND_UI(ID_BROWSE_SECURITY_SD, OnUpdateBrowseSecuritySd)
ON_UPDATE_COMMAND_UI(ID_BROWSE_SECURITY_EFFECTIVE, OnUpdateBrowseSecurityEffective)
ON_COMMAND(ID_BROWSE_REPLICATION_VIEWMETADATA, OnBrowseReplicationViewmetadata)
ON_UPDATE_COMMAND_UI(ID_BROWSE_REPLICATION_VIEWMETADATA, OnUpdateBrowseReplicationViewmetadata)
ON_COMMAND(ID_BROWSE_EXTENDEDOP, OnBrowseExtendedop)
ON_UPDATE_COMMAND_UI(ID_BROWSE_EXTENDEDOP, OnUpdateBrowseExtendedop)
ON_COMMAND(ID_VIEW_LIVEENTERPRISE, OnViewLiveEnterprise)
ON_UPDATE_COMMAND_UI(ID_VIEW_LIVEENTERPRISE, OnUpdateViewLiveEnterprise)
ON_COMMAND(ID_BROWSE_VLVSEARCH, OnBrowseVlvsearch)
ON_UPDATE_COMMAND_UI(ID_BROWSE_VLVSEARCH, OnUpdateBrowseVlvsearch)
ON_COMMAND(ID_EDIT_COPYDN, OnEditCopy)
ON_COMMAND(ID_OPTIONS_START_TLS, OnOptionsStartTls)
ON_COMMAND(ID_OPTIONS_STOP_TLS, OnOptionsStopTls)
ON_COMMAND(ID_BROWSE_GetError, OnGetLastError)
//}}AFX_MSG_MAP
ON_COMMAND(ID_SRCHEND, OnSrchEnd)
ON_COMMAND(ID_SRCHGO, OnSrchGo)
ON_COMMAND(ID_ADDGO, OnAddGo)
ON_COMMAND(ID_ADDEND, OnAddEnd)
ON_COMMAND(ID_MODGO, OnModGo)
ON_COMMAND(ID_MODEND, OnModEnd)
ON_COMMAND(ID_MODRDNGO, OnModRdnGo)
ON_COMMAND(ID_MODRDNEND, OnModRdnEnd)
ON_COMMAND(ID_PENDEND, OnPendEnd)
ON_COMMAND(ID_PROCPEND, OnProcPend)
ON_COMMAND(ID_PENDANY, OnPendAny)
ON_COMMAND(ID_PENDABANDON, OnPendAbandon)
ON_COMMAND(ID_COMPGO, OnCompGo)
ON_COMMAND(ID_COMPEND, OnCompEnd)
ON_COMMAND(ID_BIND_OPT_OK, OnBindOptOK)
ON_COMMAND(ID_SSPI_DOMAIN_SHORTCUT, OnSSPIDomainShortcut)
ON_COMMAND(ID_EXTOPGO, OnExtOpGo)
ON_COMMAND(ID_EXTOPEND, OnExtOpEnd)
ON_COMMAND(ID_ENT_TREE_END, OnLiveEntTreeEnd)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLdpDoc construction/destruction
/*+++
Function : CLdpDoc
Description: Constructor
Parameters :
Return :
Remarks : none.
---*/
CLdpDoc::CLdpDoc()
{
CLdpApp *app = (CLdpApp*)AfxGetApp();
SetSecurityPrivilege();
//
// registry
//
HKEY hUserRegKey = NULL;
char szAppDataPath[MAX_PATH];
char szAppDataIni[MAX_PATH];
DWORD dwBufLen;
RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_QUERY_VALUE, &hUserRegKey);
dwBufLen = sizeof(szAppDataPath);
RegQueryValueEx( hUserRegKey, "AppData", NULL, NULL,
(LPBYTE) szAppDataPath, &dwBufLen);
RegCloseKey( hUserRegKey);
strcat( szAppDataPath, "\\Microsoft\\ldp");
CreateDirectory( szAppDataPath, NULL);
//First free the string allocated by MFC at CWinApp startup.
//The string is allocated before InitInstance is called.
free((void*)app->m_pszProfileName);
//Change the name of the .INI file.
//The CWinApp destructor will free the memory.
strcpy( szAppDataIni, szAppDataPath);
strcat( szAppDataIni, "\\ldp.ini");
app->m_pszProfileName=_tcsdup(_T(szAppDataIni));
Svr = app->GetProfileString("Connection", "Server");
BindDn = app->GetProfileString("Connection", "BindDn");
BindPwd.Empty();
// BindPwd = app->GetProfileString("Connection", "BindPwd");
BindDomain = app->GetProfileString("Connection", "BindDomain");
//
// init flags dialogs & params
//
hLdap = NULL;
m_SrcMode = FALSE;
m_bCnctless = FALSE;
m_bProtect = TRUE; // disabled in the UI. Forced TRUE forever.
bConnected = FALSE;
bSrch = FALSE;
bAdd = FALSE;
bLiveEnterprise = FALSE;
bExtOp = FALSE;
bMod = FALSE;
bModRdn = FALSE;
bPndDlg = FALSE;
bCompDlg = FALSE;
SearchDlg = new SrchDlg(this);
m_EntTreeDlg = new CEntTree;
m_AddDlg = new AddDlg;
m_ModDlg = new ModDlg;
m_ModRdnDlg = new ModRDNDlg;
m_PndDlg = new PndDlg(&m_PendList);
m_GenOptDlg = new CGenOpt;
m_CompDlg = new CCompDlg;
m_BndOpt = new CBndOpt;
m_TreeViewDlg = new TreeVwDlg(this);
m_CtrlDlg = new ctrldlg;
m_SKDlg = new SortKDlg;
m_ExtOpDlg = new ExtOpDlg;
m_vlvDlg = NULL;
#ifdef WINLDAP
ldap_set_dbg_flags(m_DbgDlg.ulDbgFlags);
#endif
//
// Initial search info struct
//
for(int i=0; i<MAXLIST; i++)
SrchInfo.attrList[i] = NULL;
//
// setup default attributes to retrieve
//
const TCHAR pszDefaultAttrList[] = "objectClass;name;cn;ou;dc;distinguishedName;description;canonicalName";
SrchInfo.lTlimit = 0;
SrchInfo.lSlimit = 0;
SrchInfo.lToutSec = 0;
SrchInfo.lToutMs = 0;
SrchInfo.bChaseReferrals = FALSE;
SrchInfo.bAttrOnly = FALSE;
SrchInfo.fCall = CALL_SYNC;
SrchInfo.lPageSize = 16;
SrchInfo.fCall = app->GetProfileInt("Search_Operations", "SearchSync", SrchInfo.fCall);
SrchInfo.bAttrOnly = app->GetProfileInt("Search_Operations", "SearchAttrOnly", SrchInfo.bAttrOnly );
SrchInfo.bChaseReferrals = app->GetProfileInt("Search_Operations", "ChaseReferrals", SrchInfo.bChaseReferrals);
SrchInfo.lToutMs = app->GetProfileInt("Search_Operations", "SearchToutMs", SrchInfo.lToutMs );
SrchInfo.lToutSec = app->GetProfileInt("Search_Operations", "SearchToutSec", SrchInfo.lToutSec );
SrchInfo.lTlimit = app->GetProfileInt("Search_Operations", "SearchTlimit", SrchInfo.lTlimit );
SrchInfo.lSlimit = app->GetProfileInt("Search_Operations", "SearchSlimit", SrchInfo.lSlimit );
SrchInfo.lPageSize = app->GetProfileInt("Search_Operations", "SearchPageSize", SrchInfo.lPageSize );
LPTSTR pAttrList = _strdup(app->GetProfileString("Search_Operations", "SearchAttrList", pszDefaultAttrList));
for(i=0, SrchInfo.attrList[i] = strtok(pAttrList, ";");
SrchInfo.attrList[i] != NULL;
SrchInfo.attrList[++i] = strtok(NULL, ";"));
SrchOptDlg.UpdateSrchInfo(SrchInfo, FALSE);
hPage = NULL;
bPagedMode = FALSE;
bServerVLVcapable = FALSE;
m_ServerSupportedControls = NULL;
//
// init pending info struct
//
PndInfo.All = TRUE;
PndInfo.bBlock = TRUE;
PndInfo.tv.tv_sec = 0;
PndInfo.tv.tv_usec = 0;
DefaultContext.Empty();
cNCList = 0;
NCList = NULL;
//
// more registry update (passed default settings)
//
m_bProtect = app->GetProfileInt("Environment", "Protections", m_bProtect);
}
/*+++
Function : ~CLdapDoc
Description: Destructor
Parameters :
Return :
Remarks : none.
---*/
CLdpDoc::~CLdpDoc()
{
CLdpApp *app = (CLdpApp*)AfxGetApp();
INT i=0;
SetSecurityPrivilege(FALSE);
//
// register
//
app->WriteProfileString("Connection", "Server", Svr);
app->WriteProfileString("Connection", "BindDn", BindDn);
// app->WriteProfileString("Connection", "BindPwd", BindPwd);
app->WriteProfileString("Connection", "BindDomain", BindDomain);
m_bProtect = app->WriteProfileInt("Environment", "Protections", m_bProtect);
app->WriteProfileInt("Search_Operations", "SearchSync", SrchInfo.fCall);
app->WriteProfileInt("Search_Operations", "SearchAttrOnly", SrchInfo.bAttrOnly );
app->WriteProfileInt("Search_Operations", "SearchToutMs", SrchInfo.lToutMs );
app->WriteProfileInt("Search_Operations", "SearchToutSec", SrchInfo.lToutSec );
app->WriteProfileInt("Search_Operations", "SearchTlimit", SrchInfo.lTlimit );
app->WriteProfileInt("Search_Operations", "SearchSlimit", SrchInfo.lSlimit );
app->WriteProfileInt("Search_Operations", "ChaseReferrals", SrchInfo.bChaseReferrals);
app->WriteProfileInt("Search_Operations", "SearchPageSize", SrchInfo.lPageSize);
//
// extract attribute list to write to ini file
//
INT cbAttrList=0;
LPTSTR pAttrList = NULL;
for(i=0; SrchInfo.attrList != NULL && SrchInfo.attrList[i] != NULL; i++){
cbAttrList+= strlen(SrchInfo.attrList[i]) + 1;
}
if(cbAttrList != 0){
pAttrList = new TCHAR[cbAttrList+1];
strcpy(pAttrList, SrchInfo.attrList[0]);
for(i=1; SrchInfo.attrList[i] != NULL; i++){
pAttrList = strcat(pAttrList, ";");
pAttrList = strcat(pAttrList, SrchInfo.attrList[i]);
}
}
app->WriteProfileString("Search_Operations", "SearchAttrList", !pAttrList?"":pAttrList);
delete pAttrList;
if(NULL != hLdap)
ldap_unbind(hLdap);
//
// cleanup mem
//
delete SearchDlg;
delete m_AddDlg;
delete m_EntTreeDlg;
delete m_ModDlg;
delete m_ModRdnDlg;
delete m_PndDlg;
delete m_GenOptDlg;
delete m_BndOpt;
delete m_CompDlg;
delete m_TreeViewDlg;
delete m_CtrlDlg;
delete m_SKDlg;
delete m_ExtOpDlg;
if (m_vlvDlg)
delete m_vlvDlg;
if(SrchInfo.attrList[0] != NULL)
free(SrchInfo.attrList[0]);
}
BOOL CLdpDoc::SetSecurityPrivilege(BOOL bOn){
HANDLE hToken;
LUID seSecVal;
TOKEN_PRIVILEGES tkp;
BOOL bRet = FALSE;
/* Retrieve a handle of the access token. */
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken)) {
if (LookupPrivilegeValue((LPSTR)NULL,
SE_SECURITY_NAME,
&seSecVal)) {
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = seSecVal;
tkp.Privileges[0].Attributes = bOn? SE_PRIVILEGE_ENABLED: 0L;
AdjustTokenPrivileges(hToken,
FALSE,
&tkp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL);
}
if (GetLastError() == ERROR_SUCCESS) {
bRet = TRUE;
}
}
return bRet;
}
/*+++
Function : OnNewDocument
Description: Automatic MFC code
Parameters :
Return :
Remarks : none.
---*/
BOOL CLdpDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
//
// set a clean buffer
//
((CEditView*)m_viewList.GetHead())->SetWindowText(NULL);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CLdpDoc serialization
/*+++
Function : Serialize
Description: Automatic MFC code
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::Serialize(CArchive& ar)
{
// CEditView contains an edit control which handles all serialization
((CEditView*)m_viewList.GetHead())->SerializeRaw(ar);
}
/////////////////////////////////////////////////////////////////////////////
// CLdpDoc diagnostics
/*+++
Functionis : Diagnostics
Description: Automatic MFC Code
Parameters :
Return :
Remarks : none.
---*/
#ifdef _DEBUG
void CLdpDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CLdpDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
//////////////////////////////////////////////////////
// Utilty functions
/*+++
Function : Print
Description: Interface for text pane output
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::Print(CString str){
POSITION pos;
CView *pTmpVw;
INT iLineSize=m_GenOptDlg->MaxLineSize();
pos = GetFirstViewPosition();
while(pos != NULL){
pTmpVw = GetNextView(pos);
if((CString)(pTmpVw->GetRuntimeClass()->m_lpszClassName) == _T("CLdpView")){
CLdpView* pView = (CLdpView* )pTmpVw;
if(str.GetLength() > iLineSize){
CString tmp;
tmp = str.GetBufferSetLength(iLineSize);
tmp += "...";
pView->Print(tmp);
}
else
pView->Print(str);
break;
}
}
}
/*+++
Function : CodePrint
Description: Used for code generation
Parameters :
Return :
Remarks : unsupported anymore.
---*/
void CLdpDoc::CodePrint(CString str, int type){
type &= ~CP_ONLY;
switch (type){
case CP_SRC:
Print(str);
break;
case CP_CMT:
Print(CString("// ") + str);
break;
case CP_PRN:
Print(CString("\tprintf(\"") + str + _T("\");"));
break;
case CP_NON:
break;
default:
AfxMessageBox("Unknown switch in CLdpDoc::CodePrint()");
}
}
/*+++
Function : Out
Description: Used for interfacing w/ text pane
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::Out(CString str, int type){
if(m_SrcMode)
CodePrint(str, type);
else if(!(type & CP_ONLY))
Print(str);
}
/////////////////////////////////////////////////////////////////////////////
// CLdpDoc commands
/*+++
Function : Cldp::OnConnectionBind
Description: response to UI bind request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnConnectionBind() {
int res;
CString str;
LPTSTR dn, pwd, domain;
ULONG ulMethod;
SEC_WINNT_AUTH_IDENTITY AuthI;
//
// init dialog props
//
m_BindDlg.m_BindDn = BindDn;
// Storing the password is a security violation.
//m_BindDlg.m_Pwd = BindPwd;
m_BindDlg.m_Domain = BindDomain;
//
// execute dialog request
//
// sync SSPI domain checkbox w/ bind options
OnBindOptOK();
// Execute bind dialog
if (IDOK == m_BindDlg.DoModal()) {
//
// sync dialog info
//
BindDn = m_BindDlg.m_BindDn;
BindPwd = m_BindDlg.m_Pwd;
BindDomain = m_BindDlg.m_Domain;
ulMethod = m_BndOpt->GetAuthMethod();
//
// automatically connect if we're not connected & we're in auto mode.
//
if (NULL == hLdap && m_GenOptDlg->m_initTree) {
Connect(Svr);
}
//
// If we have a connection
//
BeginWaitCursor();
if (NULL != hLdap || !m_bProtect) {
//
// map bind dlg info into local:
// user, pwd, domain
dn = BindDn.IsEmpty()? NULL: (LPTSTR)LPCTSTR(BindDn);
//
// Password rules:
// - non-empty-- use what we have
// - empty pwd:
// - if user's name is NULL -->
// treat as currently logged on user (pwd == NULL)
// - otherwise
// treat as empty pwd for user.
//
//
if ( !BindPwd.IsEmpty() ) {
// non-empty password
pwd = (LPTSTR)LPCTSTR(BindPwd);
}
else if ( !dn ) {
// pwd is empty & user dn is empty
// --> treat as currently logged on
pwd = NULL;
}
else {
// pwd is empty but user isn't NULL (treat as NULL pwd)
pwd = _T("");
}
/* old pwd way. rm later
// special case empty string ""
if(!BindPwd.IsEmpty() && BindPwd == _T("\"\""))
pwd = _T("");
else
pwd = BindPwd.IsEmpty()? NULL: (LPTSTR)LPCTSTR(BindPwd);
*/
domain = m_BindDlg.m_Domain.IsEmpty()? NULL: (LPTSTR)LPCTSTR(m_BindDlg.m_Domain);
if (m_BndOpt->m_API == CBndOpt::BND_SIMPLE_API) {
//
// Do a simple bind
//
if (!m_BndOpt->m_bSync) {
//
// Async simple bind
//
str.Format(_T("res = ldap_simple_bind(ld, '%s', <unavailable>); // v.%d"),
dn == NULL?_T("NULL"): dn,
m_GenOptDlg->GetLdapVer());
Out(str);
res = ldap_simple_bind(hLdap, dn, pwd);
if (res == -1) {
str.Format(_T("Error <%ld>: ldap_simple_bind() failed: %s"),
res, ldap_err2string(res));
Out(str, CP_CMT);
ShowErrorInfo(res);
}
else {
//
// append to pending list
//
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_BIND;
pnd.ld = hLdap;
str.Format(_T("%4d: ldap_simple_bind: dn=\"%s\"."),
res,
dn == NULL ? _T("NULL") : dn);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
}
}
else {
//
// Sync simple
//
str.Format(_T("res = ldap_simple_bind_s(ld, '%s', <unavailable>); // v.%d"),
dn == NULL?_T("NULL"): dn,
m_GenOptDlg->GetLdapVer());
Out(str);
res = ldap_simple_bind_s(hLdap, dn, pwd);
if (res != LDAP_SUCCESS) {
str.Format(_T("Error <%ld>: ldap_simple_bind_s() failed: %s"),
res, ldap_err2string(res));
Out(str, CP_CMT);
ShowErrorInfo(res);
}
else {
str.Format(_T("Authenticated as dn:'%s'."),
dn == NULL ? _T("NULL") : dn);
Out(str, CP_CMT);
}
}
}
else if (m_BndOpt->m_API == CBndOpt::BND_GENERIC_API) {
//
// generic bind
//
//
// Fill in NT_Authority_Identity struct in case we use it
//
if (m_BndOpt->UseAuthI()) {
AuthI.User = (PUCHAR) dn;
AuthI.UserLength = dn == NULL ? 0 : strlen(dn);
AuthI.Domain = (PUCHAR) domain;
AuthI.DomainLength = domain == NULL ? 0 : strlen(domain);
AuthI.Password = (PUCHAR) pwd;
AuthI.PasswordLength = pwd == NULL ? 0 : strlen(pwd);
AuthI.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
}
if (m_BndOpt->m_bSync) {
//
// generic sync
//
if (m_BndOpt->UseAuthI()) {
str.Format(_T("res = ldap_bind_s(ld, NULL, &NtAuthIdentity, %d); // v.%d"),
ulMethod,
m_GenOptDlg->GetLdapVer());
Out(str);
str.Format(_T("\t{NtAuthIdentity: User='%s'; Pwd= <unavailable>; domain = '%s'.}"),
dn == NULL ? _T("NULL") : dn,
domain == NULL ? _T("NULL"): domain);
Out(str);
res = ldap_bind_s(hLdap, NULL, (char*)(&AuthI), ulMethod);
}
else {
str.Format(_T("res = ldap_bind_s(ld, '%s', <unavailable>, %d); // v.%d"),
dn == NULL?_T("NULL"): dn,
ulMethod,
m_GenOptDlg->GetLdapVer());
Out(str);
res = ldap_bind_s(hLdap, dn, pwd, ulMethod);
}
if (res != LDAP_SUCCESS) {
str.Format(_T("Error <%ld>: ldap_bind_s() failed: %s."),
res, ldap_err2string(res));
Out(str, CP_CMT);
ShowErrorInfo(res);
}
else {
str.Format(_T("Authenticated as dn:'%s'."),
dn == NULL ? _T("NULL") : dn);
Out(str, CP_CMT);
}
}
else {
//
// Async generic
//
if (m_BndOpt->UseAuthI()) {
str.Format(_T("res = ldap_bind(ld, NULL, &NtAuthIdentity, %d); // v.%d"),
ulMethod,
m_GenOptDlg->GetLdapVer());
Out(str);
str.Format(_T("\t{NtAuthIdentity: User='%s'; Pwd= <unavailable>; domain = '%s'}"),
dn == NULL ? _T("NULL") : dn,
domain == NULL ? _T("NULL"): domain);
Out(str);
res = ldap_bind(hLdap, NULL, (char*)(&AuthI), ulMethod);
}
else {
str.Format("res = ldap_bind(ld, '%s', <unavailable, %d); // v.%d",
dn == NULL?"NULL": dn,
ulMethod,
m_GenOptDlg->GetLdapVer());
Out(str);
res = ldap_bind(hLdap, dn, pwd, ulMethod);
}
res = ldap_bind(hLdap, dn, pwd, ulMethod);
if (res == -1) {
str.Format(_T("Error <%ld>: ldap_bind() failed: %s"),
res, ldap_err2string(res));
Out(str, CP_CMT);
ShowErrorInfo(res);
}
else {
//
// append to pending list
//
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_BIND;
pnd.ld = hLdap;
str.Format(_T("%4d: ldap_bind: dn=\"%s\",method=%d"), res,
dn == NULL ? _T("NULL") : dn,
ulMethod);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
}
}
}
else if (m_BndOpt->m_API == CBndOpt::BND_EXTENDED_API) {
/***************** Extensions not implemented yet in wldap32.dll ***********************
**** Add new NT_AUTH_IDENTITY format to extensions when implemented ****
//
// extended api bind
//
if(m_BndOpt->m_bSync){
//
// generic sync
//
str.Format("res = ldap_bind_extended_s(ld, \"%s\", \"%s\", %d, \"%s\");",
dn == NULL?"NULL": dn,
pwd == NULL ?"NULL": pwd,
ulMethod,
m_BndOpt->GetExtendedString());
Out(str);
res = ldap_bind_extended_s(hLdap, dn, pwd, ulMethod,
(LPTSTR)m_BndOpt->GetExtendedString());
if(res != LDAP_SUCCESS){
str.Format("Error <%ld>: ldap_bind_extended_s() failed: %s",
res, ldap_err2string(res));
Out(str, CP_CMT);
}
else{
str.Format("Authenticated as dn:'%s', pwd:'%s'.",
dn == NULL ? "NULL" : dn,
pwd == NULL ? "NULL" : pwd);
Out(str, CP_CMT);
}
}
else{
//
// Async extended
//
str.Format("res = ldap_bind_extended(ld, \"%s\", \"%s\", %d, \"%s\");",
dn == NULL?"NULL": dn,
pwd == NULL ?"NULL": pwd,
ulMethod,
m_BndOpt->GetExtendedString());
Out(str);
res = ldap_bind_extended(hLdap, dn, pwd,
ulMethod, (LPTSTR)m_BndOpt->GetExtendedString());
if(res == -1){
str.Format("Error <%ld>: ldap_extended_bind() failed: %s",
res, ldap_err2string(res));
Out(str, CP_CMT);
}
else{
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_BIND;
pnd.ld = hLdap;
str.Format("%4d: ldap_bind_ext: dn=\"%s\",pwd=\"%s\",method=%d", res,
dn == NULL ? "NULL" : dn,
pwd == NULL ? "NULL" : pwd,
ulMethod);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
}
}
*****************************************************************************/
AfxMessageBox("Ldap_bind extensions are not implemented yet. Sorry");
}
}
EndWaitCursor();
//
// Overwrite the memory that is storing the password, then set it to 0 length.
//
if ( !BindPwd.IsEmpty() ) {
RtlSecureZeroMemory( pwd, strlen(pwd));
}
BindPwd.Empty();
}
}
void CLdpDoc::AutoConnect(CString srv) {
SEC_WINNT_AUTH_IDENTITY AuthI;
CString str;
ULONG ulMethod = LDAP_AUTH_SSPI;
int res;
int port = -1;
PCHAR srvName, pColon;
BOOL fIsSsl = FALSE;
BOOL fIsGc = FALSE;
BeginWaitCursor();
// parse srv string
srvName = (LPTSTR)LPCTSTR(srv);
// does it start with ldap:// ssl:// gc:// or gcssl:// ?
if (_strnicmp(srvName, "ldap://", 7) == 0) {
fIsSsl = FALSE;
fIsGc = FALSE;
srvName += 7;
}
else if (_strnicmp(srvName, "gc://", 5) == 0) {
fIsSsl = FALSE;
fIsGc = TRUE;
srvName += 5;
}
else if (_strnicmp(srvName, "ssl://", 6) == 0) {
fIsSsl = TRUE;
fIsGc = FALSE;
srvName += 6;
}
else if (_strnicmp(srvName, "gcssl://", 8) == 0) {
fIsSsl = TRUE;
fIsGc = TRUE;
srvName += 8;
}
pColon = strchr(srvName, ':');
if (pColon) {
*pColon = L'\0';
port = atoi(pColon+1);
if (port == 0) port = -1;
}
if (port == -1) {
// set default port
if (fIsSsl) {
port = fIsGc ? LDAP_SSL_GC_PORT : LDAP_SSL_PORT;
}
else {
port = fIsGc ? LDAP_GC_PORT : LDAP_PORT;
}
}
Connect(CString(srvName), port, fIsSsl);
if (!hLdap) {
goto finish;
}
AuthI.User = NULL;
AuthI.UserLength = 0;
AuthI.Domain = NULL;
AuthI.DomainLength = 0;
AuthI.Password = NULL;
AuthI.PasswordLength = 0;
AuthI.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
str.Format(_T("res = ldap_bind_s(ld, NULL, &NtAuthIdentity, %d); // v.%d"),
ulMethod,
m_GenOptDlg->GetLdapVer());
Out(str);
str.Format(_T("\t{NtAuthIdentity: User='NULL'; Pwd=<unavailable>; domain = 'NULL'.}"));
Out(str);
res = ldap_bind_s(hLdap, NULL, (char*)(&AuthI), ulMethod);
if (res != LDAP_SUCCESS) {
str.Format(_T("Error <%ld>: ldap_bind_s() failed: %s."), res, ldap_err2string(res));
Out(str, CP_CMT);
ShowErrorInfo(res);
}
else {
str.Format(_T("Authenticated as dn:'NULL'."));
Out(str, CP_CMT);
}
finish:
EndWaitCursor();
}
void CLdpDoc::Connect(CString Svr, INT port, BOOL ssl){
CString str;
#ifndef WINLDAP
if(m_bCnctless){
AfxMessageBox("Connectionless protocol is not "
"implemented for U. of Michigan API."
"Continuing with ldap_open().");
m_bCnctless = FALSE;
}
#endif
BeginWaitCursor();
//
// Unsupported automatic code generation
//
PrintHeader();
if(m_bCnctless){
//
// connectionless
//
#ifdef WINLDAP
str.Format(_T("ld = cldap_open(\"%s\", %d);"), LPCTSTR(Svr), port);
Out(str);
hLdap = cldap_open(Svr.IsEmpty() ? NULL : (LPTSTR)LPCTSTR(Svr), port);
#endif
}
else if (ssl) {
ULONG version = LDAP_VERSION3;
LONG lv = 0;
SecPkgContext_ConnectionInfo sslInfo;
int res;
// Open SSL connection
str.Format(_T("ld = ldap_sslinit(\"%s\", %d, 1);"), LPCTSTR(Svr), port);
Out(str);
hLdap = ldap_sslinit(Svr.IsEmpty() ? NULL : (LPTSTR)LPCTSTR(Svr), port, 1);
if (hLdap == NULL) {
goto NoConnection;
}
res = ldap_set_option(hLdap, LDAP_OPT_PROTOCOL_VERSION, (void*)&version);
str.Format(_T("Error <0x%X> = ldap_set_option(hLdap, LDAP_OPT_PROTOCOL_VERSION, LDAP_VERSION3);"), LdapGetLastError());
Out(str);
if (res != LDAP_SUCCESS) {
ShowErrorInfo(res);
goto NoConnection;
}
res = ldap_connect(hLdap, NULL);
str.Format(_T("Error <0x%X> = ldap_connect(hLdap, NULL);"), LdapGetLastError());
Out(str);
if (res != LDAP_SUCCESS) {
ShowErrorInfo(res);
goto NoConnection;
}
// Check for SSL support (returns LDAP_OPT_ON/_OFF)
res = ldap_get_option(hLdap,LDAP_OPT_SSL,(void*)&lv);
str.Format(_T("Error <0x%X> = ldap_get_option(hLdap,LDAP_OPT_SSL,(void*)&lv);"), LdapGetLastError());
Out(str);
if (res != LDAP_SUCCESS) {
ShowErrorInfo(res);
goto NoConnection;
}
if (lv) {
// Retrieve the SSL cipher strength
res = ldap_get_option(hLdap, LDAP_OPT_SSL_INFO, &sslInfo);
if (res != LDAP_SUCCESS) {
str.Format(_T("Error <0x%X> = ldap_get_option(hLdap, LDAP_OPT_SSL_INFO, &sslInfo);"), LdapGetLastError());
Out(str, CP_PRN);
str.Format(_T("Host supports SSL, SSL cipher strength = ? bits"));
}
else {
str.Format(_T("Host supports SSL, SSL cipher strength = %d bits"), sslInfo.dwCipherStrength);
}
}
else {
str.Format(_T("SSL not enabled on host"));
}
Out(str);
NoConnection:
if (res != LDAP_SUCCESS && hLdap != NULL) {
ldap_unbind_s(hLdap);
hLdap = NULL;
}
// fall through
}
else{
//
// Tcp std connection
//
str.Format(_T("ld = ldap_open(\"%s\", %d);"), LPCTSTR(Svr), port);
Out(str);
hLdap = ldap_open(Svr.IsEmpty() ? NULL : (LPTSTR)LPCTSTR(Svr), port);
}
EndWaitCursor();
//
// If connected init flags & show base
//
if(hLdap != NULL){
int err;
str.Format(_T("Established connection to %s."), Svr);
Out(str, CP_PRN);
bConnected = TRUE;
//
// Now that we have a valid handle we can set version
// to whatever specified in general options dialog.
//
hLdap->ld_version = m_GenOptDlg->GetLdapVer();
m_GenOptDlg->DisableVersionUI();
//
// Attempt to show base DSA info & get default context
//
if(m_GenOptDlg->m_initTree){
Out(_T("Retrieving base DSA information..."), CP_PRN);
LDAPMessage *res = NULL;
BeginWaitCursor();
err = ldap_search_s(hLdap,
NULL,
LDAP_SCOPE_BASE,
_T("objectClass=*"),
NULL,
FALSE,
&res);
ShowErrorInfo(err);
//
// Get default context
//
if(1 == ldap_count_entries(hLdap, res)){
char **val;
LDAPMessage *baseEntry;
//
// Get entry
//
baseEntry = ldap_first_entry(hLdap, res);
//
// Get default naming context
//
val = ldap_get_values(hLdap, baseEntry, LDAP_OPATT_DEFAULT_NAMING_CONTEXT);
if(0 < ldap_count_values(val))
DefaultContext = (CString)val[0];
ldap_value_free(val);
// get the schema naming context
//
val = ldap_get_values(hLdap, baseEntry, LDAP_OPATT_SCHEMA_NAMING_CONTEXT);
if(0 < ldap_count_values(val))
SchemaNC = (CString)val[0];
ldap_value_free(val);
// get the config naming context
//
val = ldap_get_values(hLdap, baseEntry, LDAP_OPATT_CONFIG_NAMING_CONTEXT);
if(0 < ldap_count_values(val))
ConfigNC = (CString)val[0];
ldap_value_free(val);
// get the all naming contexts
//
val = ldap_get_values(hLdap, baseEntry, LDAP_OPATT_NAMING_CONTEXTS);
cNCList = ldap_count_values(val);
if (cNCList > 0) {
NCList = new CString[cNCList];
}
for (DWORD i = 0; i < cNCList; i++) {
NCList[i] = (CString)val[i];
}
ldap_value_free(val);
// get server name
val = ldap_get_values(hLdap, baseEntry, LDAP_OPATT_DNS_HOST_NAME);
if(0 < ldap_count_values(val)){
//
// Try to extract server name: could be full DN format or just a name
// so try both.
//
CString TitleString;
if(val[0] == NULL){
Out("Error: ldap internal error: val[0] == NULL");
}
else{
//
// Prepare window title from dns string
//
char* connectionType;
switch(port) {
case 636:
connectionType = "ssl";
break;
case 3268:
connectionType = "gc";
break;
case 3269:
connectionType = "gcssl";
break;
default:
connectionType = ssl ? "ssl" : "ldap";
break;
}
TitleString.Format("%s://%s/%s", connectionType, val[0], DefaultContext);
AfxGetMainWnd()->SetWindowText(TitleString);
ldap_value_free(val);
}
}
// try to read supporteControls
int cnt;
val = ldap_get_values(hLdap, baseEntry, LDAP_OPATT_SUPPORTED_CONTROL);
if(0 < (cnt = ldap_count_values(val)) ) {
SetSupportedServerControls (cnt, val);
}
else {
SetSupportedServerControls (0, NULL);
}
ldap_value_free(val);
}
//
// Display search results
//
DisplaySearchResults(res);
EndWaitCursor();
}
else{
CString TitleString;
TitleString.Format("%s - connected", AfxGetAppName());
AfxGetMainWnd()->SetWindowText(TitleString);
}
}
else{
str.Format(_T("Error <0x%X>: Fail to connect to %s."), LdapGetLastError(), Svr);
Out(str, CP_PRN);
AfxMessageBox(_T("Cannot open connection."));
}
}
void CLdpDoc::SetSupportedServerControls (int cnt, char **val)
{
int i;
// free existing controls
if (m_ServerSupportedControls) {
for (i=0; m_ServerSupportedControls[i]; i++) {
free (m_ServerSupportedControls[i]);
}
free (m_ServerSupportedControls);
m_ServerSupportedControls = NULL;
}
bServerVLVcapable = FALSE;
if (cnt && val) {
m_ServerSupportedControls = (char **)malloc (sizeof (char *) * (cnt + 1));
if (m_ServerSupportedControls) {
for (i=0; i < cnt; i++) {
char *pCtrl = m_ServerSupportedControls[i] = _strdup (val[i]);
if (pCtrl && (strcmp (pCtrl, LDAP_CONTROL_VLVREQUEST) == 0)) {
bServerVLVcapable = TRUE;
}
}
m_ServerSupportedControls[cnt]=NULL;
}
}
}
void CLdpDoc::ShowVLVDialog (const char *strDN, BOOL runQuery)
{
if (!m_vlvDlg) {
m_vlvDlg = new CVLVDialog;
if (!m_vlvDlg) {
return;
}
m_vlvDlg->pldpdoc = this;
m_vlvDlg->Create(IDD_VLV_DLG);
}
else {
m_vlvDlg->ShowWindow(SW_SHOW);
}
if (strDN) {
m_vlvDlg->m_BaseDN = strDN;
}
m_vlvDlg->UpdateData(FALSE);
if (runQuery) {
m_vlvDlg->RunQuery();
}
}
/*+++
Function : CLdp::OnConnectionConnect
Description: response to UI connect request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnConnectionConnect()
{
CnctDlg dlg;
CString str;
int port;
BOOL ssl;
dlg.m_Svr = Svr;
if(IDOK == dlg.DoModal()){
Svr = dlg.m_Svr;
m_bCnctless = dlg.m_bCnctless;
port = dlg.m_Port;
ssl = dlg.m_bSsl;
Connect(Svr, port, ssl);
}
}
/*+++
Function : OnConnectionDisconnect
Description: response to UI disconnect request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnConnectionDisconnect()
{
CString str;
//
// Close connection/less session
//
ldap_unbind(hLdap);
str.Format(_T("0x%x = ldap_unbind(ld);"), LdapGetLastError());
Out(str);
//
// reset connection handle
//
hLdap = NULL;
Out(_T("Disconnected."), CP_PRN | CP_ONLY);
Out(_T("}"), CP_SRC | CP_ONLY);
bConnected = FALSE;
DefaultContext.Empty();
cNCList = 0;
if (NCList != NULL) {
delete[] NCList;
NCList = NULL;
}
m_TreeViewDlg->m_BaseDn.Empty();
m_GenOptDlg->EnableVersionUI();
CString TitleString;
TitleString.Format("%s - disconnected", AfxGetAppName());
AfxGetMainWnd()->SetWindowText(TitleString);
}
/*+++
Function : OnBrowseSearch
Description: Create modeless search diag
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnBrowseSearch()
{
bSrch = TRUE;
if(GetContextActivation()){
SearchDlg->m_BaseDN = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
SearchDlg->m_BaseDN = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
SearchDlg->Create(IDD_SRCH);
}
/*+++
Function :
Description: a few UI utils
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnUpdateConnectionConnect(CCmdUI* pCmdUI)
{
pCmdUI->Enable(!bConnected || !m_bProtect);
}
void CLdpDoc::OnUpdateConnectionDisconnect(CCmdUI* pCmdUI)
{
pCmdUI->Enable(bConnected || !m_bProtect);
}
void CLdpDoc::OnUpdateBrowseSearch(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bSrch && bConnected) || !m_bProtect);
}
void CLdpDoc::OnEditCopy()
{
CString copyStr;
if(GetContextActivation()){
copyStr = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
copyStr = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
else {
return;
}
if ( !OpenClipboard(HWND (AfxGetApp()->m_pActiveWnd)) ) {
AfxMessageBox( "Cannot open the Clipboard" );
return;
}
EmptyClipboard();
HANDLE hData = GlobalAlloc (GMEM_MOVEABLE, copyStr.GetLength()+2);
if (hData) {
char *pStr = (char *)GlobalLock (hData);
strcpy (pStr, LPCTSTR (copyStr));
GlobalUnlock (hData);
if ( ::SetClipboardData( CF_TEXT, hData ) == NULL ) {
AfxMessageBox( "Unable to set Clipboard data" );
CloseClipboard();
return;
}
}
else {
AfxMessageBox( "Out of memory" );
}
CloseClipboard();
}
void CLdpDoc::OnBrowseVlvsearch()
{
const char *baseDN = NULL;
if(GetContextActivation()){
baseDN = LPCTSTR (TreeView()->GetDn());
TreeView()->SetContextActivation(FALSE);
}
ShowVLVDialog (baseDN);
}
void CLdpDoc::OnUpdateBrowseVlvsearch(CCmdUI* pCmdUI)
{
pCmdUI->Enable( (( !m_vlvDlg || (m_vlvDlg && !m_vlvDlg->GetState())) && bConnected && bServerVLVcapable) || !m_bProtect);
}
void CLdpDoc::OnSrchEnd(){
bSrch = FALSE; // dialog is closed.
CString str;
//
// if in paged mode, mark end of page session
//
if(bPagedMode){
str.Format("ldap_search_abandon_page(ld, hPage)");
Out(str);
ldap_search_abandon_page(hLdap, hPage);
bPagedMode = FALSE;
}
}
/*+++
Function : OnSrchGo
Description: Response to UI search request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnSrchGo(){
CString str;
LPTSTR dn;
LPTSTR filter;
LDAP_TIMEVAL tm;
int i;
static LDAPMessage *msg;
ULONG err, MsgId;
ULONG ulEntryCount=0;
PLDAPSortKey *SortKeys = m_SKDlg->KList;
PLDAPControl *SvrCtrls;
PLDAPControl *ClntCtrls;
LDAPControl SortCtrl;
// PLDAPControl SortCtrl=NULL;
PLDAPControl *CombinedCtrl = NULL;
INT cbCombined;
if(!bConnected && m_bProtect)
{
AfxMessageBox("Please re-connect session first");
return;
}
//
// init local time struct
//
tm.tv_sec = SrchInfo.lToutSec;
tm.tv_usec = SrchInfo.lToutMs;
//
// If we're in paged mode, then run means next page, & close is abandon (see onsrchEnd)
//
if(bPagedMode)
{
ulEntryCount=0;
BeginWaitCursor();
err = ldap_get_next_page_s(hLdap, hPage, &tm, SrchInfo.lPageSize, &ulEntryCount, &msg);
EndWaitCursor();
str.Format("0x%X = ldap_get_next_page_s(ld, hPage, %ld, &timeout, %ld, 0x%X);",
err, SrchInfo.lPageSize,ulEntryCount, msg);
Out(str);
if(err != LDAP_SUCCESS)
{
ShowErrorInfo(err);
str.Format("ldap_search_abandon_page(ld, hPage)");
Out(str);
ldap_search_abandon_page(hLdap, hPage);
bPagedMode = FALSE;
}
else
{
bPagedMode = TRUE;
}
DisplaySearchResults(msg);
if(err == LDAP_SUCCESS)
{
Out(" -=>> 'Run' for more, 'Close' to abandon <<=-");
}
return;
}
Out("***Searching...", CP_PRN);
//
// set scope
//
int scope = SearchDlg->m_Scope == 0 ? LDAP_SCOPE_BASE :
SearchDlg->m_Scope == 1 ? LDAP_SCOPE_ONELEVEL :
LDAP_SCOPE_SUBTREE;
//
// Set time/size limits only if connected & hLdap is valid
//
if(bConnected)
{
hLdap->ld_timelimit = SrchInfo.lTlimit;
hLdap->ld_sizelimit = SrchInfo.lSlimit;
ULONG ulVal = SrchInfo.bChaseReferrals ? 1 : 0;
ldap_set_option(hLdap,
LDAP_OPT_REFERRALS,
(LPVOID)&ulVal);
}
//
// set base DN
//
dn = SearchDlg->m_BaseDN.IsEmpty()? NULL : (LPTSTR)LPCTSTR(SearchDlg->m_BaseDN);
if(SearchDlg->m_Filter.IsEmpty() && m_bProtect)
{
AfxMessageBox("Please enter a valid filter string (such as objectclass=*). Empty string is invalid.");
return;
}
//
// & filter
//
filter = (LPTSTR)LPCTSTR(SearchDlg->m_Filter);
// controls
SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
//
// execute search call
//
switch(SrchInfo.fCall)
{
case CALL_ASYNC:
str.Format("ldap_search_ext(ld, \"%s\", %d, \"%s\", %s, %d ...)",
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? "attrList" : "NULL",
SrchInfo.bAttrOnly);
Out(str);
//
// Combine sort & server controls
//
if(SortKeys != NULL)
{
err = ldap_encode_sort_controlA(hLdap,
SortKeys,
&SortCtrl,
TRUE);
if(err != LDAP_SUCCESS)
{
// str.Format("Error <0x%X>: ldap_create_create_control returned: %s", err, ldap_err2string(err));
str.Format("Error <0x%X>: ldap_create_encode_control returned: %s", err, ldap_err2string(err));
SortKeys = NULL;
}
}
CombinedCtrl = NULL;
//
// count total controls
//
for(i=0, cbCombined=0; SvrCtrls != NULL && SvrCtrls[i] != NULL; i++)
cbCombined++;
CombinedCtrl = new PLDAPControl[cbCombined+2];
//
// set combined
//
for(i=0; SvrCtrls != NULL && SvrCtrls[i] != NULL; i++)
CombinedCtrl[i] = SvrCtrls[i];
if(SortKeys != NULL)
CombinedCtrl[i++] = &SortCtrl;
CombinedCtrl[i] = NULL;
BeginWaitCursor();
err = ldap_search_ext(hLdap,
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? SrchInfo.attrList : NULL,
SrchInfo.bAttrOnly,
CombinedCtrl,
ClntCtrls,
SrchInfo.lToutSec,
SrchInfo.lSlimit,
&MsgId);
EndWaitCursor();
//
// cleanup
//
if(SortKeys != NULL)
{
ldap_memfree(SortCtrl.ldctl_value.bv_val);
ldap_memfree(SortCtrl.ldctl_oid);
}
delete CombinedCtrl;
if(err != LDAP_SUCCESS || (DWORD)MsgId <= 0)
{
str.Format("Error<%lu>: %s. (msg = %lu).", err, ldap_err2string(err), MsgId);
Out(str, CP_PRN);
ShowErrorInfo(err);
}
else
{
//
// add to pending requests
//
CPend pnd;
pnd.mID = MsgId;
pnd.OpType = CPend::P_SRCH;
pnd.ld = hLdap;
str.Format("%4d: ldap_search: base=\"%s\",filter=\"%s\"", MsgId,
dn,
filter);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
}
break;
case CALL_SYNC:
str.Format("ldap_search_s(ld, \"%s\", %d, \"%s\", %s, %d, &msg)",
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? "attrList" : "NULL",
SrchInfo.bAttrOnly);
Print(str);
BeginWaitCursor();
err = ldap_search_s(hLdap,
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? SrchInfo.attrList : NULL,
SrchInfo.bAttrOnly,
&msg);
EndWaitCursor();
if(err != LDAP_SUCCESS)
{
str.Format("Error: Search: %s. <%ld>", ldap_err2string(err), err);
Out(str, CP_PRN);
ShowErrorInfo(err);
}
//
// display results even if res is unsuccessfull (specs)
//
DisplaySearchResults(msg);
break;
case CALL_EXTS:
str.Format("ldap_search_ext_s(ld, \"%s\", %d, \"%s\", %s, %d, svrCtrls, ClntCtrls, %ld, %ld ,&msg)",
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? "attrList" : "NULL",
SrchInfo.bAttrOnly,
SrchInfo.lToutSec,
SrchInfo.lSlimit);
Out(str);
//
// Combine sort & server controls
//
if(SortKeys != NULL)
{
err = ldap_encode_sort_controlA(hLdap,
SortKeys,
&SortCtrl,
TRUE);
if(err != LDAP_SUCCESS)
{
str.Format("Error <0x%X>: ldap_create_encode_control returned: %s", err, ldap_err2string(err));
Out(str, CP_PRN);
SortKeys = NULL;
}
}
CombinedCtrl = NULL;
//
// count total controls
//
for(i=0, cbCombined=0; SvrCtrls != NULL && SvrCtrls[i] != NULL; i++)
cbCombined++;
CombinedCtrl = new PLDAPControl[cbCombined+2];
//
// set combined
//
for(i=0; SvrCtrls != NULL && SvrCtrls[i] != NULL; i++)
CombinedCtrl[i] = SvrCtrls[i];
if(SortKeys != NULL)
CombinedCtrl[i++] = &SortCtrl;
CombinedCtrl[i] = NULL;
//
// call search
//
BeginWaitCursor();
err = ldap_search_ext_s(hLdap,
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? SrchInfo.attrList : NULL,
SrchInfo.bAttrOnly,
CombinedCtrl,
ClntCtrls,
&tm,
SrchInfo.lSlimit,
&msg);
EndWaitCursor();
//
// cleanup
//
if(SortKeys != NULL)
{
ldap_memfree(SortCtrl.ldctl_value.bv_val);
ldap_memfree(SortCtrl.ldctl_oid);
}
delete CombinedCtrl;
if(err != LDAP_SUCCESS)
{
str.Format("Error: Search: %s. <%ld>", ldap_err2string(err), err);
Out(str, CP_PRN);
ShowErrorInfo(err);
}
//
// display results even if res is unsuccessfull (specs)
//
DisplaySearchResults(msg);
break;
case CALL_PAGED:
str.Format("ldap_search_init_page(ld, \"%s\", %d, \"%s\", %s, %d, svrCtrls, ClntCtrls, %ld, %ld ,SortKeys)",
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? "attrList" : "NULL",
SrchInfo.bAttrOnly,
SrchInfo.lTlimit,
SrchInfo.lSlimit);
Print(str);
BeginWaitCursor();
hPage = ldap_search_init_page(hLdap,
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? SrchInfo.attrList : NULL,
SrchInfo.bAttrOnly,
SvrCtrls,
ClntCtrls,
SrchInfo.lTlimit,
SrchInfo.lSlimit,
SortKeys);
EndWaitCursor();
if(hPage == NULL)
{
err = LdapGetLastError();
str.Format("Error: Search: %s. <%ld>", ldap_err2string(err), err);
Out(str, CP_PRN);
ShowErrorInfo(err);
}
//
// display results even if res is unsuccessfull (specs)
//
ulEntryCount=0;
BeginWaitCursor();
err = ldap_get_next_page_s(hLdap, hPage, &tm, SrchInfo.lPageSize, &ulEntryCount, &msg);
EndWaitCursor();
str.Format("0x%X = ldap_get_next_page_s(ld, hPage, %lu, &timeout, %ld, 0x%X);",
err, SrchInfo.lPageSize,ulEntryCount, msg);
Out(str);
if(err != LDAP_SUCCESS)
{
ShowErrorInfo(err);
str.Format("ldap_search_abandon_page(ld, hPage)");
Out(str);
ldap_search_abandon_page(hLdap, hPage);
bPagedMode = FALSE;
}
else
{
bPagedMode = TRUE;
}
DisplaySearchResults(msg);
if(err == LDAP_SUCCESS)
{
Out(" -=>> 'Run' for more, 'Close' to abandon <<=-");
}
break;
case CALL_TSYNC:
str.Format("ldap_search_st(ld, \"%s\", %d, \"%s\", %s,%d, &tm, &msg)",
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? "attrList" : "NULL",
SrchInfo.bAttrOnly);
Out(str);
tm.tv_sec = SrchInfo.lToutSec;
tm.tv_usec = SrchInfo.lToutMs;
BeginWaitCursor();
err = ldap_search_st(hLdap,
dn,
scope,
filter,
SrchInfo.attrList[0] != NULL ? SrchInfo.attrList : NULL,
SrchInfo.bAttrOnly,
&tm,
&msg);
EndWaitCursor();
if(err != LDAP_SUCCESS)
{
str.Format("Error: Search: %s. <%ld>", ldap_err2string(err), err);
Out(str, CP_PRN);
ShowErrorInfo(err);
}
//
// display search even if res is unsuccessfull (specs)
//
DisplaySearchResults(msg);
break;
}
//
// Cleanup
//
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
}
/*+++
Function : DisplaySearchResults
Description: Display results
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::DisplaySearchResults(LDAPMessage *msg){
//
// Parse results
//
CString str, strDN;
char *dn;
void *ptr;
char *attr;
LDAPMessage *nxt;
ULONG nEntries;
CLdpView *pView;
pView = (CLdpView*)GetOwnView(_T("CLdpView"));
ParseResults(msg);
Out("", CP_ONLY|CP_SRC);
str.Format("Getting %lu entries:", ldap_count_entries(hLdap, msg));
Out(str, CP_PRN);
if(!SrchOptDlg.m_bDispResults)
Out(_T("<Skipping search results display (search options)...>"));
//
// disable redraw
//
pView->SetRedraw(FALSE);
pView->CacheStart();
//
// traverse entries
//
for(nxt = ldap_first_entry(hLdap, msg)/*,
Out("nxt = ldap_first_entry(ld, msg);", CP_ONLY|CP_SRC)*/,
nEntries = 0;
nxt != NULL;
nxt = ldap_next_entry(hLdap, nxt)/*,
Out("nxt = ldap_next_entry(ld,nxt);", CP_ONLY|CP_SRC)*/,
nEntries++){
//
// get dn text & process
//
// Out("dn = ldap_get_dn(ld,nxt);", CP_ONLY|CP_SRC);
dn = ldap_get_dn(hLdap, nxt);
strDN = DNProcess(dn);
if(m_SrcMode){
str = "\tprintf(\"Dn: %%s\\n\", dn);";
}
else{
str = CString(">> Dn: ") + strDN;
}
if(SrchOptDlg.m_bDispResults)
Out(str);
//
// traverse attributes
//
for(attr = ldap_first_attribute(hLdap, nxt, (BERPTRTYPE)&ptr)/*,
Out("attr = ldap_first_attribute(ld, nxt, (BERPTRTYPE)&ptr);", CP_ONLY|CP_SRC)*/;
attr != NULL;
attr = ldap_next_attribute(hLdap, nxt, (struct berelement*)ptr)/*,
Out("attr = ldap_next_attribute(ld, nxt, (struct berelement*)ptr);", CP_ONLY|CP_SRC) */){
// Out("\tprintf(\"\\t%%s: \", attr);", CP_ONLY|CP_SRC);
//
// display values
//
if(m_GenOptDlg->m_ValProc == STRING_VAL_PROC){
DisplayValues(nxt, attr);
}
else{
DisplayBERValues(nxt, attr);
}
}
// Out("", CP_ONLY|CP_SRC);
}
//
// verify consistency
//
if(nEntries != ldap_count_entries(hLdap, msg)){
str.Format("Error: ldap_count_entries reports %lu entries. Parsed %lu.",
ldap_count_entries(hLdap, msg), nEntries);
Out(str, CP_PRN);
}
Out("ldap_msgfree(msg);", CP_ONLY|CP_SRC);
ldap_msgfree(msg);
Out("-----------", CP_PRN);
Out("", CP_ONLY|CP_SRC);
//
// now allow refresh
//
pView->CacheEnd();
pView->SetRedraw();
}
DWORD
AsciiStrToWideStr(
const char * szIn,
WCHAR ** pwszOut
)
/*++
Routine Description:
Converts an ASCI or UTF-8 string into a wide char string.
Arguments:
szIn - null terminated ASCII string in.
pwszOut - malloc'd (and null terminated) string out.
Return Value:
Win32 Error code
--*/
{
DWORD dwRet = ERROR_SUCCESS;
LPWSTR lpWStr = NULL;
if (szIn == NULL || pwszOut == NULL) {
ASSERT(!"Invalid parameter");
return(ERROR_INVALID_PARAMETER);
}
*pwszOut = NULL;
//
// Get UNICODE str size
//
int cblpWStr = MultiByteToWideChar(CP_ACP, // code page
MB_ERR_INVALID_CHARS, // return err
(LPCSTR)szIn, // input
-1, // null terminated
lpWStr, // converted
0); // calc size
if(cblpWStr == 0){
dwRet = GetLastError();
ASSERT(dwRet);
dwRet = dwRet ? dwRet : ERROR_INVALID_PARAMETER;
return(dwRet);
} else {
//
// Get UNICODE str
//
lpWStr = (LPWSTR)malloc(sizeof(WCHAR)*cblpWStr);
cblpWStr = MultiByteToWideChar(CP_ACP, // code page
MB_ERR_INVALID_CHARS, // return err
(LPCSTR)szIn, // input
-1, // null terminated
lpWStr, // converted
cblpWStr); // size
if(cblpWStr == 0){
free(lpWStr);
dwRet = GetLastError();
ASSERT(dwRet);
dwRet = dwRet ? dwRet : ERROR_INVALID_PARAMETER;
return(dwRet);
}
}
*pwszOut = lpWStr;
return(dwRet);
}
//
// Global ObjDump options for ldp.
//
OBJ_DUMP_OPTIONS ObjDumpOptions = {
OBJ_DUMP_VAL_FRIENDLY_KNOWN_BLOBS,
NULL, NULL, NULL, NULL
};
// FUTURE-2002/08/18-BrettSh - In the future it would be nice to improve
// this so ldp could set these dump options, and furthure integrate the
// xlist\obj_dump.c routines with ldp such that ldp could have the option
// of dumping say all values if it wanted to.
/*+++
Function : FormatValue
Description: generates a string from a berval value
this provides a tiny substitute to loading the schema dynamically & provide
some minimal value parsing for most important/requested attributes
Parameters :
pbval: a ptr to berval value
str: result
Return :
Remarks : none.
---*/
VOID
CLdpDoc::FormatValue(
IN CString attr,
IN PLDAP_BERVAL pbval,
IN PWCHAR* objClassVal,
IN CString& str){
DWORD err;
CString tstr;
BOOL bValid;
WCHAR * szAttrTemp = NULL;
WCHAR * szValTemp = NULL;
// BAS_TODO ... add comment about not adding new clauses here ...
// BAS_TODO assert's aren't firing in ldp ... should make them fire.
ASSERT(!"BAS_TODO We're in here");
if (!pbval)
{
tstr = "<value format error>";
}
else
{
//
// New string formating routine ...
//
err = AsciiStrToWideStr(attr, &szAttrTemp);
if (err == 0) {
ASSERT(szAttrTemp);
err = ValueToString(szAttrTemp, objClassVal,
(PBYTE) pbval->bv_val, pbval->bv_len,
&ObjDumpOptions, &szValTemp);
if (err == 0) {
// AaronN basically ... I have this function ValueToString() that takes some params and gives a nice
// Unicode/wide char string representation of those params ... then I need to merge this string
// into the resulting string in such a way as if instead attr = "objectGuid" (follow this path) to
// then end to get an idea of how it's handled ...
// So is the right thing going to happen here? because szValTemp is a WCHAR *, and below
// w/ pszGuid it's a CHAR * ... is this going to be a cool C++ constructor thing?
tstr = szValTemp;
str += tstr;
LocalFree(szValTemp); // can I free this?
free(szAttrTemp);
return;
} else {
xListClearErrors(); // BAS_TODO
}
free(szAttrTemp);
}
if ( 0 == _stricmp(attr, "objectGuid") ||
0 == _stricmp(attr, "invocationId") ||
0 == _stricmp(attr, "attributeSecurityGUID") ||
0 == _stricmp(attr, "schemaIDGUID") ||
0 == _stricmp(attr, "serviceClassID") )
{
//
// format as a guid
//
PUCHAR pszGuid = NULL;
ASSERT(!"Why wasn't this handled in ValueToString()?");
err = UuidToString((GUID*)pbval->bv_val, &pszGuid);
if(err != RPC_S_OK){
tstr.Format("<ldp error %lu: UuidFromString failure>", err);
}
if ( pszGuid )
{
tstr = pszGuid;
RpcStringFree(&pszGuid);
}
else
{
tstr = "<invalid Guid>";
}
}
else if ( 0 == _stricmp(attr, "objectSid") ||
0 == _stricmp(attr, "sidHistory") )
{
//
// format as object sid
//
PSID psid = pbval->bv_val;
LPSTR pszTmp = NULL;
ASSERT(!"Why wasn't this handled in ValueToString()?");
if ( ConvertSidToStringSidA(psid, &pszTmp) &&
pszTmp )
{
tstr = pszTmp;
LocalFree(pszTmp);
}
else {
tstr = "<ldp error: invalid sid>";
}
}
else if (( 0 == _stricmp(attr, "whenChanged") ||
0 == _stricmp(attr, "whenCreated") ||
0 == _stricmp(attr, "dSCorePropagationData") ||
0 == _stricmp(attr, "msDS-Entry-Time-To-Die") ||
0 == _stricmp(attr, "schemaUpdate") ||
0 == _stricmp(attr, "modifyTimeStamp") ||
0 == _stricmp(attr, "createTimeStamp") ||
0 == _stricmp(attr, "currentTime")) && (atoi (pbval->bv_val) != 0))
{
//
// print in time format
//
SYSTEMTIME sysTime, localTime;
ASSERT(!"Why wasn't this handled in ValueToString()?");
err = GeneralizedTimeToSystemTime(pbval->bv_val,
&sysTime);
if( ERROR_SUCCESS == err)
{
TIME_ZONE_INFORMATION tz;
BOOL bstatus;
err = GetTimeZoneInformation(&tz);
if ( err == TIME_ZONE_ID_INVALID ) {
tstr.Format("<ldp error <%lu>: cannot format time field>",
GetLastError());
}
else {
bstatus = SystemTimeToTzSpecificLocalTime(
(err == TIME_ZONE_ID_UNKNOWN) ? NULL : &tz,
&sysTime,
&localTime );
if ( bstatus )
{
tstr.Format("%d/%d/%d %d:%d:%d %S %S",
localTime.wMonth,
localTime.wDay,
localTime.wYear,
localTime.wHour,
localTime.wMinute,
localTime.wSecond,
tz.StandardName,
tz.DaylightName);
}
else
{
tstr.Format("%d/%d/%d %d:%d:%d UNC",
localTime.wMonth,
localTime.wDay,
localTime.wYear,
localTime.wHour,
localTime.wMinute,
localTime.wSecond);
}
}
}
else
{
tstr.Format("<ldp error <0x%x>: Time processing failed in GeneralizedTimeToSystemTime>", err);
}
}
else if ((0 == _stricmp(attr, "accountExpires") ||
0 == _stricmp(attr, "badPasswordTime") ||
0 == _stricmp(attr, "creationTime") ||
0 == _stricmp(attr, "lastLogon") ||
0 == _stricmp(attr, "lastLogoff") ||
0 == _stricmp(attr, "lastLogonTimestamp") ||
0 == _stricmp(attr, "pwdLastSet") ||
0 == _stricmp(attr, "msDS-Cached-Membership-Time-Stamp")) &&
(atoi (pbval->bv_val) != 0)) {
//
// print in time format
//
SYSTEMTIME sysTime, localTime;
ASSERT(!"Why wasn't this handled in ValueToString()?");
err = DSTimeToSystemTime(pbval->bv_val, &sysTime);
if( ERROR_SUCCESS == err)
{
TIME_ZONE_INFORMATION tz;
BOOL bstatus;
err = GetTimeZoneInformation(&tz);
if ( err != TIME_ZONE_ID_INVALID &&
err != TIME_ZONE_ID_UNKNOWN )
{
bstatus = SystemTimeToTzSpecificLocalTime(&tz,
&sysTime,
&localTime);
if ( bstatus )
{
tstr.Format("%d/%d/%d %d:%d:%d %S %S",
localTime.wMonth,
localTime.wDay,
localTime.wYear,
localTime.wHour,
localTime.wMinute,
localTime.wSecond,
tz.StandardName,
tz.DaylightName);
}
else
{
tstr.Format("%d/%d/%d %d:%d:%d UNC",
localTime.wMonth,
localTime.wDay,
localTime.wYear,
localTime.wHour,
localTime.wMinute,
localTime.wSecond);
}
}
else
{
tstr.Format("<ldp error <0x%x>: cannot format time field", err);
}
}
else
{
tstr.Format("<ldp error <0x%x>: cannot format time field", err);
}
}
else if (0 == _stricmp(attr, "lockoutDuration") ||
0 == _stricmp(attr, "lockoutObservationWindow") ||
0 == _stricmp(attr, "forceLogoff") ||
0 == _stricmp(attr, "minPwdAge") ||
0 == _stricmp(attr, "maxPwdAge")) {
//
// Caculate the duration for this value
// it's stored as a negitive value in nanoseconds.
// a value of -9223372036854775808 is never
__int64 lTemp;
ASSERT(!"Why wasn't this handled in ValueToString()?");
lTemp = _atoi64 (pbval->bv_val);
if (lTemp > 0x8000000000000000){
lTemp = lTemp * -1;
lTemp = lTemp / 10000000;
tstr.Format("%ld", lTemp);
}
else
tstr.Format("%s (none)", pbval->bv_val);
}
else if (0 == _stricmp(attr, "userAccountControl") ||
0 == _stricmp(attr, "groupType") ||
0 == _stricmp(attr, "systemFlags") ) {
ASSERT(!"Why wasn't this handled in ValueToString()?");
tstr.Format("0x%x", atoi (pbval->bv_val));
}
else if ( 0 == _stricmp(attr, "dnsRecord") )
{
// Taken from \nt\private\net\sockets\dns\server\server\record.h
//
// DS Record
//
typedef struct _DsRecord
{
WORD wDataLength;
WORD wType;
//DWORD dwFlags;
BYTE Version;
BYTE Rank;
WORD wFlags;
DWORD dwSerial;
DWORD dwTtlSeconds;
DWORD dwTimeout;
DWORD dwStartRefreshHr;
union _DataUnion
{
struct
{
LONGLONG EntombedTime;
}
Tombstone;
}
Data;
}
DS_RECORD, *PDS_RECORD;
//
// foramt as a dns record
//
PDS_RECORD pDnsRecord = (PDS_RECORD)pbval->bv_val;
DWORD cbDnsRecord = pbval->bv_len;
bValid=TRUE;
if ( cbDnsRecord < sizeof(DS_RECORD) )
{
tstr.Format("<ldp error: cannot format DS_DNSRECORD field");
//
// Weird way to store info...but this is still valid
//
bValid = cbDnsRecord == sizeof(DS_RECORD)-4 ? TRUE : FALSE;
}
//
// ready to print
//
if ( bValid )
{
PBYTE pData = ((PBYTE)pDnsRecord+sizeof(DS_RECORD)-sizeof(LONGLONG));
DWORD cbData = pDnsRecord->wDataLength;
CString sData;
tstr.Format("wDataLength: %d "
"wType: %d; "
"Version: %d "
"Rank: %d "
"wFlags: %d "
"dwSerial: %lu "
"dwTtlSeconds: %lu "
"dwTimeout: %lu "
"dwStartRefreshHr: %lu "
"Data: ",
pDnsRecord->wDataLength,
pDnsRecord->wType,
pDnsRecord->Version,
pDnsRecord->Rank,
pDnsRecord->wFlags,
pDnsRecord->dwSerial,
pDnsRecord->dwTtlSeconds,
pDnsRecord->dwTimeout,
pDnsRecord->dwStartRefreshHr);
DumpBuffer(pData, cbData, sData);
tstr += sData;
}
}
else if ( 0 == _stricmp(attr, "replUpToDateVector") )
{
//
// foramt as Uptodatevector
/*
typedef struct _UPTODATE_VECTOR {
DWORD dwVersion;
DWORD dwReserved1;
SWITCH_IS(dwVersion) union {
CASE(1) UPTODATE_VECTOR_V1 V1;
};
} UPTODATE_VECTOR;
typedef struct _UPTODATE_VECTOR_V1 {
DWORD cNumCursors;
DWORD dwReserved2;
#ifdef MIDL_PASS
[size_is(cNumCursors)]
UPTODATE_CURSOR rgCursors[];
#else
UPTODATE_CURSOR rgCursors[1];
#endif
} UPTODATE_VECTOR_V1;
etc...
*/
//
UPTODATE_VECTOR *pUtdVec = (UPTODATE_VECTOR *)pbval->bv_val;
DWORD cbUtdVec = pbval->bv_len;
if ( pUtdVec->dwVersion != 1 )
{
tstr.Format("<ldp error: cannot process UPDATE_VECTOR v.%lu>", pUtdVec->dwVersion );
}
else
{
tstr.Format("dwVersion: %lu, dwReserved1: %lu, V1.cNumCursors: %lu, V1.dwReserved2: %lu,rgCursors: ",
pUtdVec->dwVersion, pUtdVec->dwReserved1,
pUtdVec->V1.cNumCursors, pUtdVec->V1.dwReserved2 );
bValid = TRUE;
for (INT i=0;
bValid && i < pUtdVec->V1.cNumCursors;
i++)
{
PUCHAR pszGuid = NULL;
err = UuidToString(&(pUtdVec->V1.rgCursors[i].uuidDsa), &pszGuid);
if(err != RPC_S_OK || !pszGuid){
tstr.Format("<ldp error %lu: UuidFromString failure>", err);
bValid = FALSE;
}
else
{
CString strCursor;
strCursor.Format("{uuidDsa: %s, usnHighPropUpdate: %I64d}, ",
pszGuid, pUtdVec->V1.rgCursors[i].usnHighPropUpdate);
RpcStringFree(&pszGuid);
tstr += strCursor;
}
}
}
}
else if ( 0 == _stricmp(attr, "repsFrom") ||
0 == _stricmp(attr, "repsTo") )
{
//
// format as REPLICA_LINK
/*
typedef struct _ReplicaLink_V1 {
ULONG cb; // total size of this structure
ULONG cConsecutiveFailures; // * number of consecutive call failures along
// this link; used by the KCC to route around
// servers that are temporarily down
DSTIME timeLastSuccess; // (Reps-From) time of last successful replication or
// (Reps-To) time at which Reps-To was added or updated
DSTIME timeLastAttempt; // * time of last replication attempt
ULONG ulResultLastAttempt; // * result of last replication attempt (DRSERR_*)
ULONG cbOtherDraOffset; // offset (from struct *) of other-dra MTX_ADDR
ULONG cbOtherDra; // size of other-dra MTX_ADDR
ULONG ulReplicaFlags; // zero or more DRS_* flags
REPLTIMES rtSchedule; // * periodic replication schedule
// (valid only if ulReplicaFlags & DRS_PER_SYNC)
USN_VECTOR usnvec; // * propagation state
UUID uuidDsaObj; // objectGUID of other-dra's ntdsDSA object
UUID uuidInvocId; // * invocation id of other-dra
UUID uuidTransportObj; // * objectGUID of interSiteTransport object
// corresponding to the transport by which we
// communicate with the source DSA
DWORD dwReserved1; // * unused
// and it assumes max size of DWORD rather then the extensible
// DRS_EXTENSIONS. We would filter only those props we're interested in
// storing in RepsFrom so it should last for a while (32 exts)
ULONG cbPASDataOffset; // * offset from beginning of struct to PAS_DATA section
BYTE rgb[]; // storage for the rest of the structure
// * indicates valid only on Reps-From
} REPLICA_LINK_V1;
typedef struct _ReplicaLink {
DWORD dwVersion;
union
{
REPLICA_LINK_V1 V1;
};
} REPLICA_LINK;
etc...
*/
//
REPLICA_LINK *pReplink = (REPLICA_LINK *)pbval->bv_val;
DWORD cbReplink = pbval->bv_len;
// See what generation did we read
BOOL fShowExtended = pReplink->V1.cbOtherDraOffset == offsetof(REPLICA_LINK, V1.rgb);
BOOL fUsePasData = fShowExtended && pReplink->V1.cbPASDataOffset;
PPAS_DATA pPasData = fUsePasData ? RL_PPAS_DATA(pReplink) : NULL;
if ( pReplink->dwVersion != 1 )
{
tstr.Format("<ldp error: cannot process REPLICA_LINK v.%lu>", pReplink->dwVersion );
}
else
{
PUCHAR pszUuidDsaObj=NULL, pszUuidInvocId=NULL, pszUuidTransportObj=NULL;
// Workaround CString inability to convert several longlong in a sequence (eyals)
CString strLastSuccess, strLastAttempt, strUsnHighObj, strUsnHighProp;
strLastSuccess.Format("%I64d", pReplink->V1.timeLastSuccess);
strLastAttempt.Format("%I64d", pReplink->V1.timeLastAttempt);
strUsnHighObj.Format("%I64d", pReplink->V1.usnvec.usnHighObjUpdate);
strUsnHighProp.Format("%I64d", pReplink->V1.usnvec.usnHighPropUpdate);
(VOID)UuidToString(&(pReplink->V1.uuidDsaObj), &pszUuidDsaObj);
(VOID)UuidToString(&(pReplink->V1.uuidInvocId), &pszUuidInvocId);
(VOID)UuidToString(&(pReplink->V1.uuidTransportObj), &pszUuidTransportObj);
tstr.Format("dwVersion = 1, " \
"V1.cb: %lu, " \
"V1.cConsecutiveFailures: %lu " \
"V1.timeLastSuccess: %s " \
"V1.timeLastAttempt: %s " \
"V1.ulResultLastAttempt: 0x%X " \
"V1.cbOtherDraOffset: %lu " \
"V1.cbOtherDra: %lu " \
"V1.ulReplicaFlags: 0x%x " \
"V1.rtSchedule: <ldp:skipped> " \
"V1.usnvec.usnHighObjUpdate: %s " \
"V1.usnvec.usnHighPropUpdate: %s " \
"V1.uuidDsaObj: %s " \
"V1.uuidInvocId: %s " \
"V1.uuidTransportObj: %s " \
"V1~mtx_address: %s " \
"V1.cbPASDataOffset: %lu " \
"V1~PasData: version = %d, size = %d, flag = %d ",
pReplink->V1.cb,
pReplink->V1.cConsecutiveFailures,
strLastSuccess,
strLastAttempt,
pReplink->V1.ulResultLastAttempt,
pReplink->V1.cbOtherDraOffset,
pReplink->V1.cbOtherDra,
pReplink->V1.ulReplicaFlags,
strUsnHighObj,
strUsnHighProp,
pszUuidDsaObj ? (PCHAR)pszUuidDsaObj : "<Invalid Uuid>",
pszUuidInvocId ? (PCHAR)pszUuidInvocId : "<Invalid Uuid>",
pszUuidTransportObj ? (PCHAR)pszUuidTransportObj : "<Invalid Uuid>",
RL_POTHERDRA(pReplink)->mtx_name,
fUsePasData ? pReplink->V1.cbPASDataOffset : 0,
pPasData ? pPasData->version : -1,
pPasData ? pPasData->size : -1,
pPasData ? pPasData->flag : -1);
if (pszUuidDsaObj)
{
RpcStringFree(&pszUuidDsaObj);
}
if (pszUuidInvocId)
{
RpcStringFree(&pszUuidInvocId);
}
if (pszUuidTransportObj)
{
RpcStringFree(&pszUuidTransportObj);
}
}
}
else if ( 0 == _stricmp(attr, "schedule") )
{
//
// foramt as Schedule
/*
typedef struct _repltimes {
UCHAR rgTimes[84];
} REPLTIMES;
*/
//
//
// Hack:
// Note that we're reding rgtimes[168] (see SCHEDULE_DATA_ENTRIES) but storing
// in rgtimes[84]. We're ok here but this is ugly & not maintainable & for sure will
// break sometimes soon.
// The problem is due to inconsistency due to storing the schedule in 1 byte == 1 hour
// whereas the internal format is using 1 byte == 2 hours. (hence 84 to 168).
//
CString strSched;
PBYTE pTimes;
PSCHEDULE pSched = (PSCHEDULE)pbval->bv_val;;
DWORD cbSched = pbval->bv_len;
if ( cbSched != sizeof(SCHEDULE)+SCHEDULE_DATA_ENTRIES )
{
tstr.Format("<ldp: cannot format schedule. sizeof(REPLTIMES) = %d>", cbSched );
}
else
{
INT bitCount=0;
tstr.Format("Size: %lu, Bandwidth: %lu, NumberOfSchedules: %lu, Schedules[0].Type: %lu, " \
"Schedules[0].Offset: %lu ",
pSched->Size,
pSched->Bandwidth,
pSched->NumberOfSchedules,
pSched->Schedules[0].Type,
pSched->Schedules[0].Offset );
pTimes = (BYTE*)((PBYTE)pSched + pSched->Schedules[0].Offset);
// traverse schedule blob
strSched = " ";
for ( INT i=0; i<168;i++ )
{
BYTE byte = *(pTimes+i);
for ( INT j=0; j<=3;j++ )
{
// traverse bits & mark on/off
strSched += (byte & (1 << j))? "1" : "0";
if( (++bitCount % 4) == 0 )
{
// hour boundary
strSched += ".";
}
if ( (bitCount % 96) == 0)
{
// a day boundary
strSched += " ";
}
}
}
tstr += strSched;
}
}
else if ( 0 == _stricmp(attr, "partialAttributeSet") )
{
//
// foramt as PARTIAL_ATTR_VECTOR
/*
// PARTIAL_ATTR_VECTOR - represents the partial attribute set. This is an array of
// sorted attids that make the partial set.
typedef struct _PARTIAL_ATTR_VECTOR_V1 {
DWORD cAttrs; // count of partial attributes in the array
#ifdef MIDL_PASS
[size_is(cAttrs)] ATTRTYP rgPartialAttr[];
#else
ATTRTYP rgPartialAttr[1];
#endif
} PARTIAL_ATTR_VECTOR_V1;
// We need to make sure the start of the union is aligned at an 8 byte
// boundary so that we can freely cast between internal and external
// formats.
typedef struct _PARTIAL_ATTR_VECTOR_INTERNAL {
DWORD dwVersion;
DWORD dwFlag;
SWITCH_IS(dwVersion) union {
CASE(1) PARTIAL_ATTR_VECTOR_V1 V1;
};
} PARTIAL_ATTR_VECTOR_INTERNAL;
typedef PARTIAL_ATTR_VECTOR_INTERNAL PARTIAL_ATTR_VECTOR;
*/
//
CString strPAS;
PARTIAL_ATTR_VECTOR *pPAS = (PARTIAL_ATTR_VECTOR*)pbval->bv_val;;
DWORD cbPAS = pbval->bv_len;
if ( cbPAS < sizeof(PARTIAL_ATTR_VECTOR))
{
tstr.Format("<ldp: cannot format partialAttributeSet. sizeof(PARTIAL_ATTR_VECTOR) = %d>", cbPAS );
}
else
{
tstr.Format("dwVersion: %lu, dwFlag: %lu, V1.cAttrs: %lu, V1.rgPartialAttr: ",
pPAS->dwVersion, pPAS->dwReserved1, pPAS->V1.cAttrs);
// traverse partial attr list
for ( INT i=0; i<pPAS->V1.cAttrs; i++ )
{
strPAS.Format("%X ", pPAS->V1.rgPartialAttr[i]);
tstr += strPAS;
}
}
}
else
{
//
// unknown attribute.
// try to find if it's printable
//
BOOL bPrintable=TRUE;
for (INT i=0; i<pbval->bv_len; i++)
{
if (!isalpha(pbval->bv_val[i]) &&
!isspace(pbval->bv_val[i]) &&
!isdigit(pbval->bv_val[i]) &&
!isgraph(pbval->bv_val[i]) &&
pbval->bv_val[i] != 0 // accept Null terminated strings
)
{
bPrintable = FALSE;
break;
}
}
if (bPrintable)
{
tstr = pbval->bv_val;
}
else
{
tstr = "<ldp: Binary blob>";
}
}
}
str += tstr;
}
/*+++
Function : DisplayValues
Description: printout the values of a dn
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::DisplayValues(LDAPMessage *entry, char *attr){
LDAP_BERVAL **bval;
unsigned long i;
CString str;
PWCHAR* objClassVal = NULL;
// do we have an objectClass in among the values?
objClassVal = ldap_get_valuesW(hLdap, entry, L"objectClass");
//
// get & traverse values
//
bval = ldap_get_values_len(hLdap, entry, attr);
// Out("val = ldap_get_values(ld, nxt, attr);", CP_ONLY|CP_SRC);
str.Format("\t%lu> %s: ", ldap_count_values_len(bval), attr);
for(i=0/*,
Out("i=0;", CP_ONLY|CP_SRC)*/;
bval != NULL && bval[i] != NULL;
i++/*, Out("i++;", CP_ONLY|CP_SRC)*/){
FormatValue(attr, bval[i], objClassVal, str);
str += "; ";
// Out("\tprintf(\"\\t\\t%%s; \",val[i]);", CP_ONLY|CP_SRC);
}
// Out("\\n", CP_ONLY|CP_PRN);
if(SrchOptDlg.m_bDispResults)
Out(str, CP_CMT);
// Out("", CP_ONLY|CP_SRC);
if(i != ldap_count_values_len(bval)){
str.Format("Error: ldap_count_values_len reports %lu values. Parsed %lu",
ldap_count_values_len(bval), i);
Out(str, CP_PRN);
}
//
// free up mem
//
if(bval != NULL){
ldap_value_free_len(bval);
// Out("ldap_value_free(val);", CP_ONLY|CP_SRC);
}
if (objClassVal != NULL) {
ldap_value_freeW(objClassVal);
}
}
/*+++
Function : DisplayBERValues
Description: Display values using BER interface
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::DisplayBERValues(LDAPMessage *entry, char *attr){
struct berval **val;
unsigned long i;
CString str, tmpStr;
//
// get & traverse values
//
val = ldap_get_values_len(hLdap, entry, attr);
// Out("val = ldap_get_values_len(ld, nxt, attr);", CP_ONLY|CP_SRC);
str.Format("\t%lu> %s: ", ldap_count_values_len(val), attr);
for(i=0/*,
Out("i=0;", CP_ONLY|CP_SRC)*/;
val != NULL && val[i] != NULL;
i++/*, Out("i++;", CP_ONLY|CP_SRC)*/){
DumpBuffer(val[i]->bv_val, val[i]->bv_len, tmpStr);
str += tmpStr;
// Out("\tprintf(\"\\t\\t%%s; \",val[i]);", CP_ONLY|CP_SRC);
}
// Out("\\n", CP_ONLY|CP_PRN);
if(SrchOptDlg.m_bDispResults)
Out(str, CP_CMT);
// Out("", CP_ONLY|CP_SRC);
//
// verify consistency
//
if(i != ldap_count_values_len(val)){
str.Format("Error: ldap_count_values reports %lu values. Parsed %lu",
ldap_count_values_len(val), i);
Out(str, CP_PRN);
}
//
// free up
//
if(val != NULL){
ldap_value_free_len(val);
// Out("ldap_value_free(val);", CP_ONLY|CP_SRC);
}
}
/*+++
Function : DNProcess
Description: process DN format for display (types etc)
Parameters :
Return :
Remarks : none.
---*/
CString CLdpDoc::DNProcess(PCHAR dn){
CString strDN;
PCHAR *DNs;
int i;
//
// pre-process dn before displaying
//
switch(m_GenOptDlg->m_DnProc){
case CGenOpt::GEN_DN_NONE:
strDN = dn;
break;
case CGenOpt::GEN_DN_EXPLD:
DNs = ldap_explode_dn(dn, FALSE);
strDN.Empty();
for(i=0; DNs!= NULL && DNs[i] != NULL; i++){
strDN += CString(DNs[i]) + "; ";
}
ldap_value_free(DNs);
break;
case CGenOpt::GEN_DN_NOTYPE:
DNs = ldap_explode_dn(dn, TRUE);
strDN.Empty();
for(i=0; DNs!= NULL && DNs[i] != NULL; i++){
strDN += CString(DNs[i]) + "; ";
}
ldap_value_free(DNs);
break;
case CGenOpt::GEN_DN_UFN:
strDN = ldap_dn2ufn(dn);
break;
default:
strDN.Empty();
}
return strDN;
}
/*+++
Function :
Description: UI handlers
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnBrowseAdd()
{
bAdd = TRUE;
if(GetContextActivation()){
m_AddDlg->m_Dn = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
m_AddDlg->m_Dn = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
m_AddDlg->Create(IDD_ADD);
}
void CLdpDoc::OnUpdateBrowseAdd(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bAdd && bConnected) || !m_bProtect);
}
void CLdpDoc::OnAddEnd(){
bAdd = FALSE;
}
/*+++
Function : OnAddGo
Description: Response to ADd request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnAddGo(){
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
Out("***Calling Add...", CP_PRN);
int nMaxEnt = m_AddDlg->GetEntryCount();
int res;
LDAPMod *attr[MAXLIST];
char *p[MAXLIST], *pTok;
int i, j;
CString str;
LPTSTR dn, lpBERVals;
//
// traverse & setup attributes
//
for(i = 0,
Out("i=0;", CP_ONLY|CP_SRC);
i<nMaxEnt;
i++,
Out("i++;", CP_ONLY | CP_SRC)){
attr[i] = (LDAPMod *)malloc(sizeof(LDAPMod));
ASSERT(attr[i] != NULL);
Out("mods[i] = (struct ldapmod*)malloc(sizeof(LDAPMod));", CP_ONLY|CP_SRC);
//
// add a std value
//
if(NULL == (lpBERVals = strstr(LPCTSTR(m_AddDlg->GetEntry(i)), "\\BER(")) &&
NULL == (lpBERVals = strstr(LPCTSTR(m_AddDlg->GetEntry(i)), "\\SDDL:")) &&
NULL == (lpBERVals = strstr(LPCTSTR(m_AddDlg->GetEntry(i)), "\\UNI"))){
attr[i]->mod_values = (char**)malloc(sizeof(char*)*MAXLIST);
ASSERT(attr[i]->mod_values != NULL);
Out("mods[i]->mod_values = (char**)malloc(sizeof(char*)*MAXLIST);", CP_ONLY|CP_SRC);
attr[i]->mod_op = 0;
Out("mods[i]->mod_op = 0;", CP_ONLY|CP_SRC);
p[i] = _strdup(LPCTSTR(m_AddDlg->GetEntry(i)));
ASSERT(p[i] != NULL);
attr[i]->mod_type = strtok(p[i], ":\n");
str.Format("mods[i]->mod_type = _strdup(\"%s\");", attr[i]->mod_type);
Out(str, CP_ONLY|CP_SRC);
for(j=0, pTok = strtok(NULL, ";\n");
pTok;
pTok= strtok(NULL, ";\n"), j++){
attr[i]->mod_values[j] = pTok;
str.Format("mods[i]->mod_values[%d] = _strdup(\"%s\");",
j, pTok);
Out(str, CP_ONLY|CP_SRC);
}
attr[i]->mod_values[j] = NULL;
str.Format("mods[i]->mod_values[%d] = NULL", j);
Out(str, CP_ONLY|CP_SRC);
}
else{
//
// Add BER values
//
//
// allocate value array buffer
//
attr[i]->mod_bvalues = (struct berval**)malloc(sizeof(struct berval*)*MAXLIST);
//
// prefast bug 653640, check that malloc did not retun null
//
if(NULL == attr[i]->mod_bvalues){
AfxMessageBox("Error: Out of memory", MB_ICONHAND);
ASSERT( attr[i]->mod_bvalues != NULL);
return;
}
//
// initialize operand
//
attr[i]->mod_op = LDAP_MOD_BVALUES;
Out("mods[i]->mod_op = LDAP_MOD_BVALUES;", CP_ONLY|CP_SRC);
//
// set entry attribute
//
p[i] = _strdup(LPCTSTR(m_AddDlg->GetEntry(i)));
ASSERT(p[i] != NULL);
attr[i]->mod_type = strtok(p[i], ":\n");
str.Format("mods[i]->mod_type = _strdup(\"%s\");", attr[i]->mod_type);
Out(str, CP_ONLY|CP_SRC);
// point to the beginning of the value
pTok = p[i] + strlen(attr[i]->mod_type) + 1;
if (_strnicmp(pTok, "\\SDDL:", 6) == 0) {
// special case: value is in SDDL format (most likely, a security descriptor)
// we can not use ';' as a separator because it is used in SDDL. So, assume
// there's just one value (which is always the case for NTSD)
PSECURITY_DESCRIPTOR pSD;
DWORD cbSD;
pTok += 6;
j = 0;
if (ConvertStringSecurityDescriptorToSecurityDescriptor(
pTok,
SDDL_REVISION_1,
&pSD,
&cbSD))
{
// value is good. Copy it.
attr[i]->mod_bvalues[j] = (struct berval*)malloc(sizeof(struct berval));
//
// prefast bug 653638, check that malloc did not retun null
//
if(NULL == attr[i]->mod_bvalues[j]){
AfxMessageBox("Error: Out of memory", MB_ICONHAND);
ASSERT( attr[i]->mod_bvalues[j] != NULL);
return;
}
attr[i]->mod_bvalues[j]->bv_len = cbSD;
attr[i]->mod_bvalues[j]->bv_val = (PCHAR)malloc(cbSD);
ASSERT(attr[i]->mod_bvalues[j]->bv_val);
memcpy(attr[i]->mod_bvalues[j]->bv_val, pSD, cbSD);
LocalFree(pSD);
j++;
}
else {
str.Format(_T("Invalid SDDL value: %lu"), GetLastError());
Out(str, CP_CMT);
}
}
else {
//
// parse values
//
for(j=0, pTok = strtok(NULL, ";\n");
pTok;
pTok= strtok(NULL, ";\n"), j++){
char fName[MAXSTR];
char szVal[MAXSTR];
attr[i]->mod_bvalues[j] = (struct berval*)malloc(sizeof(struct berval));
ASSERT(attr[i]->mod_bvalues[j] != NULL);
if(1 == sscanf(pTok, "\\UNI:%s", szVal)){
//
// UNICODE
//
LPWSTR lpWStr=NULL;
//
// Get UNICODE str size
//
int cblpWStr = MultiByteToWideChar(CP_ACP, // code page
MB_ERR_INVALID_CHARS, // return err
(LPCSTR)szVal, // input
-1, // null terminated
lpWStr, // converted
0); // calc size
if(cblpWStr == 0){
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
Out("Internal Error: MultiByteToWideChar(1): %lu", GetLastError());
}
else{
//
// Get UNICODE str
//
lpWStr = (LPWSTR)malloc(sizeof(WCHAR)*cblpWStr);
cblpWStr = MultiByteToWideChar(CP_ACP, // code page
MB_ERR_INVALID_CHARS, // return err
(LPCSTR)szVal, // input
-1, // null terminated
lpWStr, // converted
cblpWStr); // size
if(cblpWStr == 0){
free(lpWStr);
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
Out("Internal Error: MultiByteToWideChar(2): %lu", GetLastError());
}
else{
//
// assign unicode to mods.
//
attr[i]->mod_bvalues[j]->bv_len = (cblpWStr-1)*2;
attr[i]->mod_bvalues[j]->bv_val = (LPTSTR)lpWStr;
}
}
}
//
// if improper format, just get the string value
//
else if(1 != sscanf(pTok, "\\BER(%*lu): %s", fName)){
attr[i]->mod_bvalues[j]->bv_len = strlen(pTok);
attr[i]->mod_bvalues[j]->bv_val = _strdup(pTok);
}
else{
//
// Get contents from file
//
HANDLE hFile;
DWORD dwLength, dwRead;
LPVOID ptr;
hFile = CreateFile(fName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if(hFile == INVALID_HANDLE_VALUE){
str.Format("Error <%lu>: Cannot open %s value file. "
"BER Value %s set to zero.",
GetLastError(),
fName,
attr[i]->mod_type);
AfxMessageBox(str);
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
}
else{
//
// Read file in
//
dwLength = GetFileSize(hFile, NULL);
ptr = malloc(dwLength * sizeof(BYTE));
ASSERT(p != NULL);
if(!ReadFile(hFile, ptr, dwLength, &dwRead, NULL)){
str.Format("Error <%lu>: Cannot read %s value file. "
"BER Value %s set to zero.",
GetLastError(),
fName,
attr[i]->mod_type);
AfxMessageBox(str);
free(ptr);
ptr = NULL;
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
}
else{
attr[i]->mod_bvalues[j]->bv_len = dwRead;
attr[i]->mod_bvalues[j]->bv_val = (PCHAR)ptr;
}
CloseHandle(hFile);
}
str.Format("mods[i]->mod_bvalues.bv_len = %lu",
attr[i]->mod_bvalues[j]->bv_len);
Out(str, CP_ONLY|CP_CMT);
}
}
}
//
// finalize values array
//
attr[i]->mod_bvalues[j] = NULL;
str.Format("mods[i]->mod_bvalues[%d] = NULL", j);
Out(str, CP_ONLY|CP_SRC);
}
}
//
// Finalize attribute array
//
attr[i] = NULL;
str.Format("mods[%d] = NULL", i);
Out(str, CP_ONLY|CP_SRC);
//
// prepare dn
//
dn = m_AddDlg->m_Dn.IsEmpty() ? NULL : (char*)LPCTSTR(m_AddDlg->m_Dn);
if(dn != NULL){
str.Format("dn = _strdup(\"%s\");", dn);
}
else
str = "dn = NULL;";
Out(str, CP_ONLY|CP_SRC);
//
// Execute ldap_add & friends
//
if(m_AddDlg->m_Sync){
//
// Sync add
//
BeginWaitCursor();
if(m_AddDlg->m_bExtended){
PLDAPControl *SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
PLDAPControl *ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
str.Format("ldap_add_ext_s(ld, '%s',[%d] attrs, SvrCtrls, ClntCtrls);", dn, i);
Out(str);
res = ldap_add_ext_s(hLdap, dn, attr, SvrCtrls, ClntCtrls);
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
}
else{
str.Format("ldap_add_s(ld, \"%s\", [%d] attrs)", dn, i);
Out(str);
res = ldap_add_s(hLdap, dn, attr);
}
EndWaitCursor();
if(res != LDAP_SUCCESS){
str.Format("Error: Add: %s. <%ld>", ldap_err2string(res), res);
Out(str, CP_CMT);
ShowErrorInfo(res);
Out(CString("Expected: ") + str, CP_PRN|CP_ONLY);
}
else{
str.Format("Added {%s}.", dn);
Out(str, CP_PRN);
}
}
else{
//
// Async add
//
res = ldap_add(hLdap,
dn,
attr);
Out("ldap_add(ld, dn, mods);", CP_ONLY|CP_SRC);
if(res == -1){
str.Format("Error: ldap_add(\"%s\"): %s. <%d>",
dn,
ldap_err2string(res), res);
Out(str, CP_CMT);
Out(CString("Expected: ") + str, CP_PRN|CP_ONLY);
ShowErrorInfo(res);
}
else{
//
// add to pending list
//
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_ADD;
pnd.ld = hLdap;
str.Format("%4d: ldap_add: dn={%s}",
res,
dn);
Out(str, CP_PRN|CP_ONLY);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
Out("\tPending.", CP_PRN);
}
}
//
// restore memory
//
for(i=0; i<nMaxEnt; i++){
int k;
free(p[i]);
if(attr[i]->mod_op & LDAP_MOD_BVALUES){
for(k=0; attr[i]->mod_bvalues[k] != NULL; k++){
if(attr[i]->mod_bvalues[k]->bv_len != 0L)
free(&(attr[i]->mod_bvalues[k]->bv_val[0]));
free(attr[i]->mod_bvalues[k]);
str.Format("free(mods[%d]->mod_bvalues[%d]);", i,k);
Out(str, CP_ONLY|CP_SRC);
}
}
else{
for(k=0; attr[i]->mod_values[k] != NULL; k++){
str.Format("free(mods[%d]->mod_values[%d]);", i,k);
Out(str, CP_ONLY|CP_SRC);
}
}
if(attr[i]->mod_op & LDAP_MOD_BVALUES){
free(attr[i]->mod_bvalues);
}
else{
free(attr[i]->mod_values);
str.Format("free(mods[%d]->mod_values);", i);
Out(str, CP_ONLY|CP_SRC);
}
free(attr[i]);
str.Format("free(mods[%d]);", i);
Out(str, CP_ONLY|CP_SRC);
}
Out("-----------", CP_PRN);
}
/*+++
Function : OnBrowseDelete
Description: response to delete request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnBrowseDelete()
{
DelDlg dlg;
char *dn;
CString str;
int res;
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
if(GetContextActivation()){
dlg.m_Dn = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
dlg.m_Dn = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
if(IDOK == dlg.DoModal()){
// Try to delete entry
dn = dlg.m_Dn.IsEmpty() ? NULL : (char*)LPCTSTR(dlg.m_Dn);
//
// RM: remove for invalid validation
//
if(dn == NULL && m_bProtect){
AfxMessageBox("Cannot execute ldap_delete() on a NULL dn."
"Please specify a valid dn.");
return;
}
if(dlg.m_Recursive){
str.Format("deleting \"%s\"...", dn);
Out(str);
m_ulDeleted = 0;
BeginWaitCursor();
RecursiveDelete(hLdap, dn);
EndWaitCursor();
str.Format("\tdeleted %lu entries", m_ulDeleted);
Out(str);
}
else if(dlg.m_Sync){
//
// sync delete
//
BeginWaitCursor();
if(dlg.m_bExtended){
//
// get controls
//
PLDAPControl *SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
PLDAPControl *ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
str.Format("ldap_delete_ext_s(ld, '%s', SvrCtrls, ClntCtrls);", dn);
Out(str);
// do ext delete
res = ldap_delete_ext_s(hLdap, dn, SvrCtrls, ClntCtrls);
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
}
else{
str.Format("ldap_delete_s(ld, \"%s\");", dn);
Out(str);
// do delete
res = ldap_delete_s(hLdap, dn);
}
EndWaitCursor();
if(res != LDAP_SUCCESS){
str.Format("Error: Delete: %s. <%ld>", ldap_err2string(res), res);
Out(str, CP_CMT);
Out(CString("Expected: ") + str, CP_PRN|CP_ONLY);
ShowErrorInfo(res);
}
else{
str.Format("Deleted \"%s\"", dn);
Print(str);
}
}
else{
//
// async delete
//
res = ldap_delete(hLdap, dn);
str.Format("ldap_delete(ld, \"%s\");", dn);
Out(str, CP_SRC);
if(res == -1){
str.Format("Error: ldap_delete(\"%s\"): %s. <%d>",
dn,
ldap_err2string(res), res);
Out(str, CP_CMT);
Out(CString("Expected: ") + str, CP_PRN|CP_ONLY);
ShowErrorInfo(res);
}
else{
//
// add to pending
//
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_DEL;
pnd.ld = hLdap;
str.Format("%4d: ldap_delete: dn= {%s}", res, dn);
Out(str, CP_PRN|CP_ONLY);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
Out("\tPending.", CP_PRN);
}
}
}
Out("-----------", CP_PRN);
}
void CLdpDoc::OnUpdateBrowseDelete(CCmdUI* pCmdUI)
{
pCmdUI->Enable(bConnected || !m_bProtect);
}
/*+++
Function : RecursiveDelete
Description: delete a subtree based on lpszDN
Parameters : ld: a bound ldap handle, lpszDN: base from which to start deletion
Return :
Remarks : none.
---*/
BOOL CLdpDoc::RecursiveDelete(LDAP* ld, LPTSTR lpszDN){
ULONG err;
PCHAR attrs[] = { "Arbitrary Invalid Attribute", NULL };
PLDAPMessage result;
PLDAPMessage entry;
CString str;
BOOL bRet = TRUE;
//
// get entry's immediate children
//
err = ldap_search_s(ld,
lpszDN,
LDAP_SCOPE_ONELEVEL,
"objectClass=*",
attrs,
FALSE,
&result);
if(LDAP_SUCCESS != err){
//
// report failure
//
str.Format("Error <%lu>: failed to search '%s'. {%s}.\n", err, lpszDN, ldap_err2string(err));
Out(str);
ShowErrorInfo(err);
return FALSE;
}
//
// recursion end point and actual deletion
//
if(0 == ldap_count_entries(ld, result)){
//
// delete entry
//
err = ldap_delete_s(ld, lpszDN);
if(err != LDAP_SUCCESS){
//
// report failure
//
str.Format("Error <%lu>: failed to delete '%s'. {%s}.", err, lpszDN, ldap_err2string(err));
Out(str);
ShowErrorInfo(err);
}
else{
m_ulDeleted++;
if((m_ulDeleted % 10) == 0 && m_ulDeleted != 0){
str.Format("\t>> %lu...", m_ulDeleted);
Out(str);
}
}
//
// done
//
ldap_msgfree(result);
return TRUE;
}
//
// proceeding down the subtree recursively
// traverse children
//
for(entry = ldap_first_entry(ld, result);
entry != NULL;
entry = ldap_next_entry(ld, entry)){
if(!RecursiveDelete(ld, ldap_get_dn(ld, entry))){
ldap_msgfree(result);
return FALSE;
}
}
//
// now delete current node
//
err = ldap_delete_s(ld, lpszDN);
if(err != LDAP_SUCCESS){
//
// report failure
//
str.Format("Error <%lu>: failed to delete '%s'. {%s}.\n", err, lpszDN, ldap_err2string(err));
Out(str);
ShowErrorInfo(err);
}
else{
m_ulDeleted++;
if((m_ulDeleted % 10) == 0 && m_ulDeleted != 0){
str.Format("\t>> %lu...", m_ulDeleted);
Out(str);
}
}
ldap_msgfree(result);
return TRUE;
}
/*+++
Function : OnModRdnEnd
Description: UI response
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnModRdnEnd(){
bModRdn = FALSE;
}
/*+++
Function : OnModRdnGo
Description: response to modRDN request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnModRdnGo(){
if((m_ModRdnDlg->m_Old.IsEmpty() ||
m_ModRdnDlg->m_Old.IsEmpty()) &&
!m_bProtect){
AfxMessageBox("Please enter a valid dn for both fields. Empty strings are invalid");
return;
}
//
// get DNs to process
//
char *oldDn = (char*)LPCTSTR(m_ModRdnDlg->m_Old);
char * newDn = (char*)LPCTSTR(m_ModRdnDlg->m_New);
BOOL bRename = m_ModRdnDlg->m_rename;
int res;
CString str;
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
if(m_ModRdnDlg->m_Sync){
//
// do sync
//
BeginWaitCursor();
if(bRename){
//
// parse new DN & break into RDN & new parent
//
LPTSTR szParentDn = strchr(newDn, ',');
for (;;) {
if (NULL == szParentDn) {
// There are no comma's
break;
}
if (szParentDn == newDn) {
// The first character is a comma.
// This shouldn't happen.
break;
}
if ('\\' != *(szParentDn - 1)) {
//
// Found it! And it's not escaped either.
//
break;
}
//
// Must have been an escaped comma, continue
// looking.
//
szParentDn = strchr(szParentDn + 1, ',');
}
if(szParentDn != NULL){
LPTSTR p = szParentDn;
if(&(szParentDn[1]) != NULL && szParentDn[1] != '\0')
szParentDn++;
*p = '\0';
}
LPTSTR szRdn = newDn;
//
// get controls
//
PLDAPControl *SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
PLDAPControl *ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
// execute
res = ldap_rename_ext_s(hLdap,
oldDn,
szRdn,
szParentDn,
m_ModRdnDlg->m_bDelOld,
SvrCtrls,
ClntCtrls);
str.Format("0x%x = ldap_rename_ext_s(ld, %s, %s, %s, %s, svrCtrls, ClntCtrls)",
res, oldDn, szRdn, szParentDn,
m_ModRdnDlg->m_bDelOld?"TRUE":FALSE);
Out(str);
ShowErrorInfo(res);
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
}
else{
res = ldap_modrdn2_s(hLdap,
oldDn,
newDn,
m_ModRdnDlg->m_bDelOld);
str.Format("0x%x = ldap_modrdn2_s(ld, %s, %s, %s)",
res, oldDn, newDn,
m_ModRdnDlg->m_bDelOld?"TRUE":FALSE);
Out(str);
}
EndWaitCursor();
if(res != LDAP_SUCCESS){
str.Format("Error: ModifyRDN: %s. <%ld>", ldap_err2string(res), res);
Print(str);\
ShowErrorInfo(res);
}
else{
str.Format("Rdn \"%s\" modified to \"%s\"", oldDn, newDn);
Print(str);
}
}
else{
//
// do async
//
if(bRename){
//
// parse new DN & break into RDN & new parent
//
LPTSTR szParentDn = strchr(newDn, ',');
for (;;) {
if (NULL == szParentDn) {
// There are no comma's
break;
}
if (szParentDn == newDn) {
// The first character is a comma.
// This shouldn't happen.
break;
}
if ('\\' != *(szParentDn - 1)) {
//
// Found it! And it's not escaped either.
//
break;
}
//
// Must have been an escaped comma, continue
// looking.
//
szParentDn = strchr(szParentDn + 1, ',');
}
if(szParentDn != NULL){
LPTSTR p = szParentDn;
if(&(szParentDn[1]) != NULL && szParentDn[1] != '\0')
szParentDn++;
*p = '\0';
}
LPTSTR szRdn = newDn;
//
// get controls
//
PLDAPControl *SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
PLDAPControl *ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
ULONG ulMsgId=0;
// execute
res = ldap_rename_ext(hLdap,
oldDn,
szRdn,
szParentDn,
m_ModRdnDlg->m_bDelOld,
SvrCtrls,
ClntCtrls,
&ulMsgId);
str.Format("0x%x = ldap_rename_ext(ld, %s, %s, %s, %s, svrCtrls, ClntCtrls, 0x%x)",
res, oldDn, szRdn, szParentDn,
m_ModRdnDlg->m_bDelOld?"TRUE":FALSE, ulMsgId);
Out(str);
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
if(res == -1){
ULONG err = LdapGetLastError();
str.Format("Error: ldap_rename_ext(\"%s\", \"%s\", %d): %s. <%d>",
oldDn, newDn, m_ModRdnDlg->m_bDelOld,
ldap_err2string(err), err);
Print(str);
ShowErrorInfo(res);
}
else
res = (int)ulMsgId;
}
else{
res = ldap_modrdn2(hLdap,
oldDn,
newDn,
m_ModRdnDlg->m_bDelOld);
str.Format("0x%x = ldap_modrdn2(ld, %s, %s, )",
res, oldDn, newDn, m_ModRdnDlg->m_bDelOld?"TRUE":FALSE);
Out(str);
if(res == -1){
ULONG err = LdapGetLastError();
str.Format("Error: ldap_modrdn2(\"%s\", \"%s\", %d): %s. <%d>",
oldDn, newDn, m_ModRdnDlg->m_bDelOld,
ldap_err2string(err), err);
Print(str);
ShowErrorInfo(res);
}
}
//
// insert into pending list
//
if(res != -1){
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_MODRDN;
pnd.ld = hLdap;
str.Format("%4d: ldap_modrdn: dn=\"%s\"", res, oldDn);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
Print("\tPending.");
}
}
Print("-----------");
}
/*+++
Function : UI handlers
Description:
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnBrowseModifyrdn()
{
bModRdn = TRUE;
if(GetContextActivation()){
m_ModRdnDlg->m_Old = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
m_ModRdnDlg->m_Old = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
m_ModRdnDlg->Create(IDD_MODRDN);
}
void CLdpDoc::OnUpdateBrowseModifyrdn(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bModRdn && bConnected) || !m_bProtect);
}
void CLdpDoc::OnModEnd(){
bMod = FALSE;
}
/*+++
Function : OnModGo
Description: Handle Modify request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnModGo(){
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
Print("***Call Modify...");
int nMaxEnt = m_ModDlg->GetEntryCount();
LDAPMod *attr[MAXLIST];
char *p[MAXLIST], *pTok;
int i, j, k;
CString str;
CString sAttr, sVals;
int Op, res;
LPTSTR dn;
//
// traverse entries
//
for(i = 0; i<nMaxEnt; i++){
//
// fix to fit document format (as opposed to dialog format)
//
m_ModDlg->FormatListString(i, sAttr, sVals, Op);
//
// alloc mem
//
attr[i] = (LDAPMod *)malloc(sizeof(LDAPMod));
if(NULL == attr[i]){
AfxMessageBox("Error: Out of memory", MB_ICONHAND);
ASSERT(attr[i] != NULL);
return;
}
//
// add string values
//
if(NULL == strstr(LPCTSTR(m_ModDlg->GetEntry(i)), "\\BER(") &&
NULL == strstr(LPCTSTR(m_ModDlg->GetEntry(i)), "\\SDDL:") &&
NULL == strstr(LPCTSTR(m_ModDlg->GetEntry(i)), "\\UNI")){
attr[i]->mod_values = (char**)malloc(sizeof(char*)*MAXLIST);
ASSERT(attr[i]->mod_values != NULL);
attr[i]->mod_op = Op == MOD_OP_ADD ? LDAP_MOD_ADD :
Op == MOD_OP_DELETE ? LDAP_MOD_DELETE :
LDAP_MOD_REPLACE;
attr[i]->mod_type = _strdup(LPCTSTR(sAttr));
if(sVals.IsEmpty())
p[i] = NULL;
else{
p[i] = _strdup(LPCTSTR(sVals));
ASSERT(p[i] != NULL);
}
if(p[i] == NULL){
free(attr[i]->mod_values);
attr[i]->mod_values = NULL;
}
else{
int len = strlen(p[i]);
if (len >= 2 && p[i][0] == '"' && p[i][len-1] == '"') {
// quoted value
p[i][len-1] = '\0';
attr[i]->mod_values[0] = p[i]+1;
j = 1;
}
else {
for(j=0, pTok = strtok(p[i], ";\n");
pTok;
pTok= strtok(NULL, ";\n"), j++){
attr[i]->mod_values[j] = pTok;
}
}
attr[i]->mod_values[j] = NULL;
}
}
else{
//
// BER values
//
//
// allocate value array buffer
//
attr[i]->mod_bvalues = (struct berval**)malloc(sizeof(struct berval*)*MAXLIST);
//
// prefast bug 653621, Check that malloc did not return NULL.
//
if(NULL == attr[i]->mod_bvalues){
AfxMessageBox("Error: Out of memory", MB_ICONHAND);
ASSERT( attr[i]->mod_bvalues != NULL);
return;
}
//
// initialize operand
//
attr[i]->mod_op = Op == MOD_OP_ADD ? LDAP_MOD_ADD :
Op == MOD_OP_DELETE ? LDAP_MOD_DELETE :
LDAP_MOD_REPLACE;
attr[i]->mod_op |= LDAP_MOD_BVALUES;
str.Format("mods[i]->mod_op = %d;", attr[i]->mod_op);
Out(str, CP_ONLY|CP_SRC);
//
// Fill attribute type
//
attr[i]->mod_type = _strdup(LPCTSTR(sAttr));
//
// Null out values if empty
//
if(sVals.IsEmpty())
p[i] = NULL;
else{
p[i] = _strdup(LPCTSTR(sVals));
ASSERT(p[i] != NULL);
}
if(p[i] == NULL){
free(attr[i]->mod_bvalues);
attr[i]->mod_bvalues = NULL;
}
else{
if (_strnicmp(p[i], "\\SDDL:", 6) == 0) {
// special case: value is in SDDL format (most likely, a security descriptor)
// we can not use ';' as a separator because it is used in SDDL. So, assume
// there's just one value (which is always the case for NTSD)
PSECURITY_DESCRIPTOR pSD;
DWORD cbSD;
pTok = p[i] + 6;
j = 0;
if (ConvertStringSecurityDescriptorToSecurityDescriptor(
pTok,
SDDL_REVISION_1,
&pSD,
&cbSD))
{
// value is good. Copy it.
attr[i]->mod_bvalues[j] = (struct berval*)malloc(sizeof(struct berval));
ASSERT(attr[i]->mod_bvalues[j] != NULL);
attr[i]->mod_bvalues[j]->bv_len = cbSD;
attr[i]->mod_bvalues[j]->bv_val = (PCHAR)malloc(cbSD);
ASSERT(attr[i]->mod_bvalues[j]->bv_val);
memcpy(attr[i]->mod_bvalues[j]->bv_val, pSD, cbSD);
LocalFree(pSD);
j++;
}
else {
str.Format(_T("Invalid SDDL value: %lu"), GetLastError());
Out(str, CP_CMT);
}
}
else {
for(j=0, pTok = strtok(p[i], ";\n");
pTok;
pTok= strtok(NULL, ";\n"), j++){
attr[i]->mod_values[j] = pTok;
char fName[MAXSTR];
char szVal[MAXSTR];
attr[i]->mod_bvalues[j] = (struct berval*)malloc(sizeof(struct berval));
//
// prefast bug 653622, check that malloc did not retun null
//
if(NULL == attr[i]->mod_bvalues[j]){
AfxMessageBox("Error: Out of memory", MB_ICONHAND);
ASSERT( attr[i]->mod_bvalues[j] != NULL);
return;
}
if(1 == sscanf(pTok, "\\UNI:%s", szVal)){
//
// UNICODE?
//
LPWSTR lpWStr=NULL;
//
// Get UNICODE str size
//
int cblpWStr = MultiByteToWideChar(CP_ACP, // code page
MB_ERR_INVALID_CHARS, // return err
(LPCSTR)szVal, // input
-1, // null terminated
lpWStr, // converted
0); // calc size
if(cblpWStr == 0){
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
Out("Internal Error: MultiByteToWideChar(1): %lu", GetLastError());
}
else{
//
// Get UNICODE str
//
lpWStr = (LPWSTR)malloc(sizeof(WCHAR)*cblpWStr);
cblpWStr = MultiByteToWideChar(CP_ACP, // code page
MB_ERR_INVALID_CHARS, // return err
(LPCSTR)szVal, // input
-1, // null terminated
lpWStr, // converted
cblpWStr); // size
if(cblpWStr == 0){
free(lpWStr);
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
Out("Internal Error: MultiByteToWideChar(2): %lu", GetLastError());
}
else{
//
// assign unicode to mods.
//
attr[i]->mod_bvalues[j]->bv_len = (cblpWStr-1)*2;
attr[i]->mod_bvalues[j]->bv_val = (LPTSTR)lpWStr;
}
}
}
//
// if improper format get string equiv
//
else if(1 != sscanf(pTok, "\\BER(%*lu): %s", fName)){
attr[i]->mod_bvalues[j]->bv_len = strlen(pTok);
attr[i]->mod_bvalues[j]->bv_val = _strdup(pTok);
}
else{
//
// open file
//
HANDLE hFile;
DWORD dwLength, dwRead;
LPVOID ptr;
hFile = CreateFile(fName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if(hFile == INVALID_HANDLE_VALUE){
str.Format("Error <%lu>: Cannot open %s value file. "
"BER Value %s set to zero.",
GetLastError(),
fName,
attr[i]->mod_type);
AfxMessageBox(str);
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
}
else{
//
// read file
//
dwLength = GetFileSize(hFile, NULL);
ptr = malloc(dwLength * sizeof(BYTE));
ASSERT(p != NULL);
if(!ReadFile(hFile, ptr, dwLength, &dwRead, NULL)){
str.Format("Error <%lu>: Cannot read %s value file. "
"BER Value %s set to zero.",
GetLastError(),
fName,
attr[i]->mod_type);
AfxMessageBox(str);
free(ptr);
ptr = NULL;
attr[i]->mod_bvalues[j]->bv_len = 0;
attr[i]->mod_bvalues[j]->bv_val = NULL;
}
else{
attr[i]->mod_bvalues[j]->bv_len = dwRead;
attr[i]->mod_bvalues[j]->bv_val = (PCHAR)ptr;
}
CloseHandle(hFile);
}
str.Format("mods[i]->mod_bvalues.bv_len = %lu",
attr[i]->mod_bvalues[j]->bv_len);
Out(str, CP_ONLY|CP_CMT);
}
} // for all values loop
}
//
// finalize values array
//
attr[i]->mod_bvalues[j] = NULL;
str.Format("mods[i]->mod_bvalues[%d] = NULL", j);
Out(str, CP_ONLY|CP_SRC);
} // else of empty attr spec
} // BER values
} // for all attributes
//
// finalize attribute array
//
attr[i] = NULL;
//
// Execute modify calls
//
dn = m_ModDlg->m_Dn.IsEmpty() ? NULL : (char*)LPCTSTR(m_ModDlg->m_Dn);
if(m_ModDlg->m_Sync){
BeginWaitCursor();
if(m_ModDlg->m_bExtended){
//
// get controls
//
PLDAPControl *SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
PLDAPControl *ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
str.Format("ldap_modify_ext_s(ld, '%s',[%d] attrs, SvrCtrls, ClntCtrls);", dn, i);
Out(str);
res = ldap_modify_ext_s(hLdap, dn, attr, SvrCtrls, ClntCtrls);
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
}
else{
str.Format("ldap_modify_s(ld, '%s',[%d] attrs);", dn, i);
Print(str);
res = ldap_modify_s(hLdap,dn,attr);
}
EndWaitCursor();
if(res != LDAP_SUCCESS){
str.Format("Error: Modify: %s. <%ld>", ldap_err2string(res), res);
Print(str);
ShowErrorInfo(res);
}
else{
str.Format("Modified \"%s\".", m_ModDlg->m_Dn);
Print(str);
}
}
else{
//
// async call
//
res = ldap_modify(hLdap,
dn,
attr);
if(res == -1){
str.Format("Error: ldap_modify(\"%s\"): %s. <%d>",
dn,
ldap_err2string(res), res);
Print(str);
ShowErrorInfo(res);
}
else{
//
// add to pending
//
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_MOD;
pnd.ld = hLdap;
str.Format("%4d: ldap_modify: dn=\"%s\"", res, dn);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
Print("\tPending.");
}
}
//
// restore memory
//
for(i=0; i<nMaxEnt; i++){
if(p[i] != NULL)
free(p[i]);
if(attr[i]->mod_type != NULL)
free(attr[i]->mod_type );
if(attr[i]->mod_op & LDAP_MOD_BVALUES){
for(k=0; attr[i]->mod_bvalues[k] != NULL; k++){
if(attr[i]->mod_bvalues[k]->bv_len != 0L)
free(&(attr[i]->mod_bvalues[k]->bv_val[0]));
free(attr[i]->mod_bvalues[k]);
str.Format("free(mods[%d]->mod_bvalues[%d]);", i,k);
Out(str, CP_ONLY|CP_SRC);
}
free(attr[i]->mod_bvalues);
}
else{
if(attr[i]->mod_values != NULL)
free(attr[i]->mod_values);
}
free(attr[i]);
}
Print("-----------");
}
/*+++
Function :
Description: UI handlers
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnBrowseModify()
{
bMod = TRUE;
if(GetContextActivation()){
m_ModDlg->m_Dn = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
m_ModDlg->m_Dn = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
m_ModDlg->Create(IDD_MODIFY);
}
void CLdpDoc::OnUpdateBrowseModify(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bMod && bConnected) || !m_bProtect);
}
void CLdpDoc::OnOptionsSearch()
{
if(IDOK == SrchOptDlg.DoModal())
SrchOptDlg.UpdateSrchInfo(SrchInfo, TRUE);
}
void CLdpDoc::OnBrowsePending()
{
bPndDlg = TRUE;
m_PndDlg->Create(IDD_PEND);
}
void CLdpDoc::OnUpdateBrowsePending(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bPndDlg && (bConnected || !m_BndOpt->m_bSync)) || !m_bProtect);
}
void CLdpDoc::OnPendEnd(){
bPndDlg = FALSE;
}
void CLdpDoc::OnOptionsPend()
{
PndOpt dlg;
if(IDOK == dlg.DoModal()){
PndInfo.All = dlg.m_bAllSearch;
PndInfo.bBlock = dlg.m_bBlock;
PndInfo.tv.tv_sec = dlg.m_Tlimit_sec;
PndInfo.tv.tv_usec = dlg.m_Tlimit_usec;
}
}
/*+++
Function : OnProcPend
Description: Process pending requests
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnProcPend(){
Out("*** Processing Pending...", CP_CMT);
if(m_PndDlg->posPending != NULL){
//
// Get current pending from dialog storage
//
CPend pnd = m_PendList.GetAt(m_PndDlg->posPending);
CString str;
int res;
LDAPMessage *msg;
str.Format("ldap_result(ld, %d, %d, &tv, &msg)", pnd.mID, PndInfo.All);
Out(str, CP_SRC);
//
// execute ldap result
//
BeginWaitCursor();
res = ldap_result(hLdap,
pnd.mID,
PndInfo.All,
&PndInfo.tv,
&msg);
EndWaitCursor();
//
// process result
//
HandleProcResult(res, msg, &pnd);
}
else{
AfxMessageBox("Error: Tried to process an invalid pending request");
}
}
/*+++
Function : OnPendAny
Description: Process any pending result
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnPendAny()
{
CString str;
int res;
LDAPMessage *msg;
Out("*** Processing Pending...", CP_CMT);
str.Format("ldap_result(ld, %d, %d, &tv, &msg)", LDAP_RES_ANY, PndInfo.All);
Out(str, CP_SRC);
BeginWaitCursor();
res = ldap_result(hLdap,
(ULONG)LDAP_RES_ANY,
PndInfo.All,
&PndInfo.tv,
&msg);
EndWaitCursor();
HandleProcResult(res, msg);
}
/*+++
Function : OnPendAbandon
Description: execute abandon request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnPendAbandon(){
Out("*** Abandon pending", CP_CMT);
CPend pnd;
CString str;
int mId;
int res;
if(m_PndDlg->posPending == NULL)
mId = 0;
else{
pnd = m_PendList.GetAt(m_PndDlg->posPending);
mId = pnd.mID;
}
str.Format("ldap_abandon(ld, %d)", mId);
Out(str);
res = ldap_abandon(hLdap, mId);
if (LDAP_SUCCESS != res) {
ShowErrorInfo(res);
AfxMessageBox("ldap_abandon() failed!");
}
}
/*+++
Function : HandleProcResults
Description: Process executed pending request
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::HandleProcResult(int res, LDAPMessage *msg, CPend *pnd){
CString str;
ParseResults(msg);
switch(res){
case 0:
Out(">Timeout", CP_PRN);
ldap_msgfree(msg);
break;
case -1:
res = ldap_result2error(hLdap, msg, TRUE);
str.Format("Error: ldap_result: %s <%X>", ldap_err2string(res), res);
Out(str);
ShowErrorInfo(res);
break;
default:
str.Format("result code: %s <%X>",
res == LDAP_RES_BIND ? "LDAP_RES_BIND" :
res == LDAP_RES_SEARCH_ENTRY ? "LDAP_RES_SEARCH_ENTRY" :
res == LDAP_RES_SEARCH_RESULT ? "LDAP_RES_SEARCH_RESULT" :
res == LDAP_RES_MODIFY ? "LDAP_RES_MODIFY" :
res == LDAP_RES_ADD ? "LDAP_RES_ADD" :
res == LDAP_RES_DELETE ? "LDAP_RES_DELETE" :
res == LDAP_RES_MODRDN ? "LDAP_RES_MODRDN" :
res == LDAP_RES_COMPARE ? "LDAP_RES_COMPARE": "UNKNOWN!",
res);
Out(str, CP_PRN);
switch(res){
case LDAP_RES_BIND:
res = ldap_result2error(hLdap, msg, TRUE);
if(res != LDAP_SUCCESS){
str.Format("Error: %s <%d>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
else{
str.Format("Authenticated bind request #%lu.", pnd != NULL ? pnd->mID : LDAP_RES_ANY);
Out(str, CP_PRN);
// AfxMessageBox("Connection established.");
}
break;
case LDAP_RES_SEARCH_ENTRY:
case LDAP_RES_SEARCH_RESULT:
DisplaySearchResults(msg);
break;
case LDAP_RES_ADD:
res = ldap_result2error(hLdap, msg, TRUE);
if(res != LDAP_SUCCESS){
str.Format("Error: %s <%d>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
str.Format(">completed: %s", pnd != NULL ? pnd->strMsg : "ANY");
Print(str);
break;
case LDAP_RES_DELETE:
res = ldap_result2error(hLdap, msg, TRUE);
if(res != LDAP_SUCCESS){
str.Format("Error: %s <%d>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
str.Format(">completed: %s", pnd != NULL ? pnd->strMsg : "ANY");
Out(str, CP_PRN);
break;
case LDAP_RES_MODIFY:
res = ldap_result2error(hLdap, msg, TRUE);
if(res != LDAP_SUCCESS){
str.Format("Error: %s <%d>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
str.Format(">completed: %s", pnd != NULL ? pnd->strMsg : "ANY");
Out(str, CP_PRN);
break;
case LDAP_RES_MODRDN:
res = ldap_result2error(hLdap, msg, TRUE);
if(res != LDAP_SUCCESS){
str.Format("Error: %s <%d>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
str.Format(">completed: %s", pnd != NULL ? pnd->strMsg : "ANY");
Out(str, CP_PRN);
break;
case LDAP_RES_COMPARE:
res = ldap_result2error(hLdap, msg, TRUE);
if(res == LDAP_COMPARE_TRUE){
str.Format("Results: TRUE. <%lu>", res);
Out(str, CP_PRN);
}
else if(res == LDAP_COMPARE_FALSE){
str.Format("Results: FALSE. <%lu>", res);
Out(str, CP_PRN);
}
else{
str.Format("Error: ldap_compare(): %s. <%lu>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
break;
}
}
}
/*+++
Function : PrintHeader
Description: Print C header for source view
Parameters :
Return :
Remarks : Source view is unsupported anymore
---*/
void CLdpDoc::PrintHeader(void){
if(m_SrcMode){
Out("/**********************************************/");
Out("/* Ldap Automated Scenario Recording */");
Out("/**********************************************/");
Out("");
Out("includes", CP_CMT);
Out("#include <stdio.h>");
Out("#include \"lber.h\"");
Out("#include \"ldap.h\"");
Out("");
Out("definitions", CP_CMT);
Out("#define MAXSTR\t\t512");
Out("");
Out("Global Variables", CP_CMT);
Out("LDAP *ld;\t\t//ldap connection handle");
Out("int res;\t\t//generic return variable");
Out("char *attrList[MAXSTR];\t//generic attributes list (search)");
Out("LDAPMessage *msg;\t//generic ldap message place holder");
Out("struct timeval tm;\t//for time limit on search");
Out("char *dn;\t//generic 'dn' place holder");
Out("void *ptr;\t//generic pointer");
Out("char *attr, **val;\t//a pointer to list of attributes, & values traversal helper");
Out("LDAPMessage *nxt;\t//result traversal helper");
Out("int i;\t//generic index traversal");
Out("LDAPMod *mods[MAXLIST];\t//global LDAPMod space");
Out("");
Out("");
Out("int main(void){");
Out("");
}
}
/*+++
Function : UI handlers
Description:
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnViewSource()
{
m_SrcMode = ~m_SrcMode;
}
void CLdpDoc::OnUpdateViewSource(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_SrcMode ? 1 : 0);
}
void CLdpDoc::OnOptionsBind()
{
m_BndOpt->DoModal();
}
void CLdpDoc::OnOptionsProtections()
{
m_bProtect = !m_bProtect;
}
void CLdpDoc::OnUpdateOptionsProtections(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_bProtect ? 1 : 0);
}
void CLdpDoc::OnOptionsGeneral()
{
m_GenOptDlg->DoModal();
}
void CLdpDoc::OnCompEnd(){
bCompDlg = FALSE;
}
/*+++
Function : OnCompGo
Description: ldap_compare execution
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnCompGo(){
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
PCHAR dn, attr, val;
ULONG res;
CString str;
//
// get properties from dialog
//
dn = m_CompDlg->m_dn.IsEmpty() ? NULL : (char*)LPCTSTR(m_CompDlg->m_dn);
attr = m_CompDlg->m_attr.IsEmpty() ? NULL : (char*)LPCTSTR(m_CompDlg->m_attr);
val = m_CompDlg->m_val.IsEmpty() ? NULL : (char*)LPCTSTR(m_CompDlg->m_val);
if(m_CompDlg->m_sync){
//
// do sync
//
str.Format("ldap_compare_s(0x%x, \"%s\", \"%s\", \"%s\")", hLdap, dn, attr, val);
Print(str);
BeginWaitCursor();
res = ldap_compare_s(hLdap, dn, attr, val);
EndWaitCursor();
if(res == LDAP_COMPARE_TRUE){
str.Format("Results: TRUE. <%lu>", res);
Out(str, CP_PRN);
}
else if(res == LDAP_COMPARE_FALSE){
str.Format("Results: FALSE. <%lu>", res);
Out(str, CP_PRN);
}
else{
str.Format("Error: ldap_compare(): %s. <%lu>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
}
else{
//
// async call
//
str.Format("ldap_compare(0x%x, \"%s\", \"%s\", \"%s\")", hLdap, dn, attr, val);
Print(str);
res = ldap_compare(hLdap, dn, attr, val);
if(res == -1){
str.Format("Error: ldap_compare(): %s. <%lu>", ldap_err2string(res), res);
Out(str, CP_PRN);
ShowErrorInfo(res);
}
else{
//
// add to pending
//
CPend pnd;
pnd.mID = res;
pnd.OpType = CPend::P_COMP;
pnd.ld = hLdap;
str.Format("%4d: ldap_comp: dn=\"%s\"", res, dn);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
Out("\tCompare Pending...", CP_PRN);
}
}
Out("-----------", CP_PRN);
}
void CLdpDoc::OnBrowseCompare()
{
bCompDlg = TRUE;
if(GetContextActivation()){
m_CompDlg->m_dn = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
m_CompDlg->m_dn = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
m_CompDlg->Create(IDD_COMPARE);
}
void CLdpDoc::OnUpdateBrowseCompare(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bCompDlg && bConnected) || !m_bProtect);
}
void CLdpDoc::OnOptionsDebug()
{
CString str;
if(IDOK == m_DbgDlg.DoModal()){
#ifdef WINLDAP
ldap_set_dbg_flags(m_DbgDlg.ulDbgFlags);
str.Format("ldap_set_dbg_flags(0x%x);", m_DbgDlg.ulDbgFlags);
Out(str);
#endif
}
}
void CLdpDoc::OnViewTree()
{
if(IDOK == m_TreeViewDlg->DoModal()){
UpdateAllViews(NULL);
}
}
void CLdpDoc::OnUpdateViewTree(CCmdUI* pCmdUI)
{
pCmdUI->Enable(bConnected);
}
void CLdpDoc::OnViewLiveEnterprise()
{
bLiveEnterprise = TRUE;
m_EntTreeDlg->SetLd(hLdap);
Out(_T("* Use the Refresh button to load currently live enterprise configuration"));
Out(_T("* Attention: This may take several minutes!"));
m_EntTreeDlg->Create(IDD_ENTERPRISE_TREE);
}
void CLdpDoc::OnUpdateViewLiveEnterprise(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bLiveEnterprise && bConnected) || !m_bProtect);
}
void CLdpDoc::OnLiveEntTreeEnd(){
bLiveEnterprise = FALSE;
}
/*+++
Function : GetOwnView
Description: get requested pane
Parameters :
Return :
Remarks : none.
---*/
CView* CLdpDoc::GetOwnView(LPCTSTR rtszName)
{
POSITION pos;
CView *pTmpVw = NULL;
pos = GetFirstViewPosition();
while(pos != NULL){
pTmpVw = GetNextView(pos);
if((CString)pTmpVw->GetRuntimeClass()->m_lpszClassName == rtszName)
break;
}
// ASSERT(pTmpVw != NULL);
return pTmpVw;
}
/*+++
Function : GetTreeView
Description: Get a pointer to the DSTree view pane
Parameters :
Return :
Remarks : none.
---*/
CDSTree *CLdpDoc::TreeView(void){
return (CDSTree*)GetOwnView(_T("CDSTree"));
}
BOOL CLdpDoc::GetContextActivation(void){
CDSTree* tv = TreeView();
if (tv) {
return tv->GetContextActivation();
}
else{
// see bug 447444
ASSERT(tv);
AfxMessageBox("Internal Error in CLdpDoc::GetContextActivation", MB_ICONHAND);
return FALSE;
}
}
void CLdpDoc::SetContextActivation(BOOL bFlag){
CDSTree* tv = TreeView();
ASSERT(tv);
if ( tv ) {
// prefix is happier with this check.
tv->SetContextActivation(bFlag);
}
}
/*+++
Function : OnBindOptOK
Description: UI response to closing bind options
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnBindOptOK(){
if((m_BndOpt->GetAuthMethod() == LDAP_AUTH_SSPI ||
m_BndOpt->GetAuthMethod() == LDAP_AUTH_NTLM ||
m_BndOpt->GetAuthMethod() == LDAP_AUTH_DIGEST) &&
m_BndOpt->m_API == CBndOpt::BND_GENERIC_API)
m_BindDlg.m_bSSPIdomain = TRUE;
else
m_BindDlg.m_bSSPIdomain = FALSE;
if(NULL != m_BindDlg.m_hWnd &&
::IsWindow(m_BindDlg.m_hWnd))
m_BindDlg.UpdateData(FALSE);
}
/*+++
Function : OnSSPIDomainShortcut
Description: response to novice user shortcut UI checkbox
Parameters :
Return :
Remarks : none.
---*/
void CLdpDoc::OnSSPIDomainShortcut(){
//
// sync bind & bind options dialog info such that advanced options
// map to novice user usage. Triggered by Bind dlg shortcut checkbox
//
if(m_BindDlg.m_bSSPIdomain){
m_BndOpt->m_Auth = BIND_OPT_AUTH_SSPI;
m_BndOpt->m_API = CBndOpt::BND_GENERIC_API;
m_BndOpt->m_bAuthIdentity = TRUE;
m_BndOpt->m_bSync = TRUE;
}
else{
m_BndOpt->m_Auth = BIND_OPT_AUTH_SIMPLE;
m_BndOpt->m_API = CBndOpt::BND_SIMPLE_API;
m_BndOpt->m_bAuthIdentity = FALSE;
m_BndOpt->m_bSync = TRUE;
}
}
/*+++
Function : ParseResults
Description: shells ldap_parse_result
Parameters : LDAPMessage to pass on to ldap call
Return : nothing. output to screen
---*/
void CLdpDoc::ParseResults(LDAPMessage *msg){
PLDAPControl *pResultControls = NULL;
BOOL bstatus;
CString str;
DWORD TimeCore=0, TimeCall=0, Threads=0;
PSVRSTATENTRY pStats=NULL;
if(hLdap->ld_version == LDAP_VERSION3){
ULONG ulRetCode=0;
PCHAR pMatchedDNs=NULL;
PCHAR pErrMsg=NULL;
ULONG err = ldap_parse_result(hLdap,
msg,
&ulRetCode,
&pMatchedDNs,
&pErrMsg,
NULL,
&pResultControls,
FALSE);
if(err != LDAP_SUCCESS){
str.Format("Error<%lu>: ldap_parse_result failed: %s", err, ldap_err2string(err));
Out(str);
}
else{
str.Format("Result <%lu>: %s", ulRetCode, pErrMsg);
Out(str);
str.Format("Matched DNs: %s", pMatchedDNs);
Out(str);
if (pResultControls &&
pResultControls[0])
{
//
// If we requested stats, get it
//
pStats = GetServerStatsFromControl ( pResultControls[0] );
if ( pStats)
{
Out("Stats:");
for (INT i=0; i < MAXSVRSTAT; i++)
{
switch (pStats[i].index)
{
case 0:
break;
case PARSE_THREADCOUNT:
#ifdef DBG
str.Format("\tThread Count:\t%lu", pStats[i].val);
Out(str);
#endif
break;
case PARSE_CALLTIME:
str.Format("\tCall Time:\t%lu (ms)", pStats[i].val);
Out(str);
break;
case PARSE_RETURNED:
str.Format("\tEntries Returned:\t%lu", pStats[i].val);
Out(str);
break;
case PARSE_VISITED:
str.Format("\tEntries Visited:\t%lu", pStats[i].val);
Out(str);
break;
case PARSE_FILTER:
str.Format("\tUsed Filter:\t%s", pStats[i].val_str);
free (pStats[i].val_str);
pStats[i].val_str = 0;
Out(str);
break;
case PARSE_INDEXES:
str.Format("\tUsed Indexes:\t%s", pStats[i].val_str);
free (pStats[i].val_str);
pStats[i].val_str = 0;
Out(str);
break;
default:
break;
}
}
}
ldap_controls_free(pResultControls);
}
ldap_memfree(pErrMsg);
ldap_memfree(pMatchedDNs);
}
}
}
CLdpDoc::PSVRSTATENTRY CLdpDoc::GetServerStatsFromControl( PLDAPControl pControl )
{
BYTE *pVal, Tag;
DWORD len, tmp;
DWORD val;
BOOL bstatus=TRUE;
INT i;
static SVRSTATENTRY pStats[MAXSVRSTAT];
char *pszFilter = NULL;
char *pszIndexes = NULL;
PDWORD pdwRet=NULL;
BYTE *pVal_str;
DWORD val_str_len;
//
// init stats
//
for (i=0;i<MAXSVRSTAT;i++)
{
pStats[i].index = 0;
pStats[i].val = 0;
pStats[i].val_str = NULL;
}
pVal = (PBYTE)pControl->ldctl_value.bv_val;
len = pControl->ldctl_value.bv_len;
// Parse out the ber value
if(strcmp(pControl->ldctl_oid, "1.2.840.113556.1.4.970")) {
return NULL;
}
if (!GetBerTagLen (&pVal,&len,&Tag,&tmp)) {
return NULL;
}
if (Tag != 0x30) {
return NULL;
}
for (i=0; i<MAXSVRSTAT && len; i++)
{
//
// get stat index
//
if ( !GetBerDword(&pVal,&len,&val) )
return NULL;
//
// get stat value
//
if (val == PARSE_FILTER || val == PARSE_INDEXES) {
bstatus = GetBerOctetString ( &pVal, &len, &pVal_str, &val_str_len);
if (!bstatus)
{
return NULL;
}
pStats[i].val_str = (LPSTR) malloc (val_str_len + 1);
if (pStats[i].val_str) {
memcpy (pStats[i].val_str, pVal_str, val_str_len);
pStats[i].val_str[val_str_len] = '\0';
}
}
else {
bstatus = GetBerDword(&pVal, &len, &(pStats[i].val));
if (!bstatus)
{
return NULL;
}
}
pStats[i].index = val;
}
return (PSVRSTATENTRY)pStats;
}
BOOL
CLdpDoc::GetBerTagLen (
BYTE **ppVal,
DWORD *pLen,
BYTE *Tag,
DWORD *pObjLen)
{
BYTE *pVal = *ppVal;
DWORD Len = *pLen;
BYTE sizeLen;
DWORD i;
if (!Len) {
return FALSE;
}
// Get the tag.
*Tag = *pVal++;
Len--;
if (!Len) {
return FALSE;
}
// Get the Length.
if (*pVal < 0x7f) {
*pObjLen = *pVal++;
Len--;
} else {
if (*pVal > 0x84) {
// We don't handle lengths bigger than a DWORD.
return FALSE;
}
sizeLen = *pVal & 0xf;
*pVal++; Len--;
if (Len < sizeLen) {
return FALSE;
}
*pObjLen = *pVal++;
Len--;
for (i = 1; i < sizeLen; i++) {
*pObjLen = (*pObjLen << 8) | *pVal++;
Len--;
}
}
*ppVal = pVal;
*pLen = Len;
return TRUE;
}
BOOL
CLdpDoc::GetBerOctetString (
BYTE **ppVal,
DWORD *pLen,
BYTE **ppOctetString,
DWORD *cbOctetString)
{
BYTE *pVal = *ppVal;
BYTE Tag;
DWORD Len = *pLen;
if (!GetBerTagLen(&pVal, &Len, &Tag, cbOctetString)) {
return FALSE;
}
if (Len < *cbOctetString || Tag != 0x04) {
return FALSE;
}
*ppOctetString = pVal;
pVal += *cbOctetString;
Len -= *cbOctetString;
*ppVal = pVal;
*pLen = Len;
return TRUE;
}
BOOL
CLdpDoc::GetBerDword (
BYTE **ppVal,
DWORD *pLen,
DWORD *pRetVal)
{
BYTE *pVal = *ppVal;
DWORD i, num;
*pRetVal = 0;
if(! (*pLen)) {
return FALSE;
}
// We are expecting to parse a number. Next byte is magic byte saying this
// is a number.
if(*pVal != 2) {
return FALSE;
}
pVal++;
*pLen = *pLen - 1;
if(! (*pLen)) {
return FALSE;
}
// Next is the number of bytes the number contains.
i=*pVal;
pVal++;
if((*pLen) < (i + 1)) {
return FALSE;
}
*pLen = *pLen - i - 1;
num = 0;
while(i) {
num = (num << 8) | *pVal;
pVal++;
i--;
}
*pRetVal = num;
*ppVal = pVal;
return TRUE;
}
/*++
Routine Description: Dumps the buffer content on to the debugger output.
Arguments:
Buffer: buffer pointer.
BufferSize: size of the buffer.
Return Value: none
Author: borrowed from MikeSw
--*/
VOID CLdpDoc::DumpBuffer(PVOID Buffer, DWORD BufferSize, CString &outStr){
#define NUM_CHARS 16
DWORD i, limit;
CHAR TextBuffer[NUM_CHARS + 1];
LPBYTE BufferPtr = (LPBYTE)Buffer;
CString tmp;
outStr.FormatMessage("%n%t%t");
//
// Hex dump of the bytes
//
limit = ((BufferSize - 1) / NUM_CHARS + 1) * NUM_CHARS;
for (i = 0; i < limit; i++) {
if (i < BufferSize) {
tmp.Format("%02x ", BufferPtr[i]);
outStr += tmp;
if (BufferPtr[i] < 31 ) {
TextBuffer[i % NUM_CHARS] = '.';
} else if (BufferPtr[i] == '\0') {
TextBuffer[i % NUM_CHARS] = ' ';
} else {
TextBuffer[i % NUM_CHARS] = (CHAR) BufferPtr[i];
}
} else {
tmp.Format(" ");
outStr += tmp;
TextBuffer[i % NUM_CHARS] = ' ';
}
if ((i + 1) % NUM_CHARS == 0) {
TextBuffer[NUM_CHARS] = 0;
tmp.FormatMessage(" %1!s!%n%t%t", TextBuffer);
outStr += tmp;
}
}
tmp.FormatMessage("------------------------------------%n");
outStr += tmp;
}
void CLdpDoc::OnOptionsServeroptions()
{
SvrOpt dlg(this);
dlg.DoModal();
}
void CLdpDoc::OnOptionsControls()
{
if(IDOK == m_CtrlDlg->DoModal()){
}
}
void CLdpDoc::FreeControls(PLDAPControl *ctrl){
if(ctrl == NULL)
return;
for(INT i=0; ctrl[i] != NULL; i++){
PLDAPControl c = ctrl[i]; // for convinience
delete c->ldctl_oid;
delete c->ldctl_value.bv_val;
delete c;
}
delete ctrl;
}
void CLdpDoc::OnOptionsSortkeys()
{
if(IDOK == m_SKDlg->DoModal()){
}
}
void CLdpDoc::OnOptionsSetFont()
{
POSITION pos;
CView *pTmpVw;
pos = GetFirstViewPosition();
while(pos != NULL){
pTmpVw = GetNextView(pos);
if((CString)(pTmpVw->GetRuntimeClass()->m_lpszClassName) == _T("CLdpView")){
CLdpView* pView = (CLdpView* )pTmpVw;
pView->SelectFont();
}
}
}
void CLdpDoc::OnBrowseExtendedop()
{
bExtOp = TRUE;
m_ExtOpDlg->Create( IDD_EXT_OPT );
}
void CLdpDoc::OnUpdateBrowseExtendedop(CCmdUI* pCmdUI)
{
pCmdUI->Enable((!bExtOp && bConnected) || !m_bProtect);
}
void CLdpDoc::OnExtOpEnd(){
bExtOp = FALSE;
}
void CLdpDoc::OnExtOpGo(){
ULONG ulMid=0, ulErr;
struct berval data;
DWORD dwVal=0;
CString str= m_ExtOpDlg->m_strData;
PCHAR pOid = (PCHAR) LPCTSTR(m_ExtOpDlg->m_strOid);
PLDAPControl *SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
PLDAPControl *ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
// data.bv_len = pStr == NULL ? 0 : (strlen(pStr) * sizeof(TCHAR));
// data.bv_val = pStr;
if(0 != (dwVal = atol(str)) ||
(!str.IsEmpty() && str[0] == '0')){
data.bv_val = (PCHAR)&dwVal;
data.bv_len = sizeof(DWORD);
}
else if(str.IsEmpty()){
data.bv_val = NULL;
data.bv_len = 0;
}
else{
data.bv_val = (PCHAR) LPCTSTR(str);
data.bv_len = str.GetLength()+1;
}
BeginWaitCursor();
ulErr = ldap_extended_operation(hLdap, pOid, &data, NULL, NULL, &ulMid);
EndWaitCursor();
str.Format("0x%X = ldap_extended_operation(ld, '%s', &data, svrCtrl, clntCtrl, %lu);",
ulErr, pOid, ulMid);
Out(str);
if(LDAP_SUCCESS == ulErr){
//
// add to pending
//
CPend pnd;
pnd.mID = ulMid;
pnd.OpType = CPend::P_EXTOP;
pnd.ld = hLdap;
str.Format("%4d: ldap_extended_op: Oid=\"%s\"", ulMid, pOid);
pnd.strMsg = str;
m_PendList.AddTail(pnd);
m_PndDlg->Refresh(&m_PendList);
Print("\tPending.");
}
else{
str.Format("Error <0x%X>: %s", ulErr, ldap_err2string(ulErr));
Out(str);
}
FreeControls(SvrCtrls);
FreeControls(ClntCtrls);
}
/////////////////////// SECURITY EXTENSIONS HANDLER & FRIENDS //////////////////////////
void CLdpDoc::OnBrowseSecuritySd()
{
SecDlg dlg;
char *dn;
CString str;
int res;
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
if(GetContextActivation()){
dlg.m_Dn = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
dlg.m_Dn = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
Out("***Calling Security...", CP_PRN);
if (IDOK == dlg.DoModal())
{
// Try to query security for entry
dn = dlg.m_Dn.IsEmpty() ? NULL : (char*)LPCTSTR(dlg.m_Dn);
//
// RM: remove for invalid validation
//
if (dn == NULL && m_bProtect){
AfxMessageBox("Cannot query security on a NULL dn."
"Please specify a valid dn.");
return;
}
/* & we execute only in synchronous mode */
BeginWaitCursor();
res = SecDlgGetSecurityData(
dn,
dlg.m_Sacl,
NULL, // No account, we just want a security descriptor dump
str
);
EndWaitCursor();
// str.Format("ldap_delete_s(ld, \"%s\");", dn);
// Out(str, CP_SRC);
if (res != LDAP_SUCCESS)
{
str.Format("Error: Security: %s. <%ld>", ldap_err2string(res), res);
Out(str, CP_CMT);
Out(CString("Expected: ") + str, CP_PRN|CP_ONLY);
ShowErrorInfo(res);
}
else
{
str.Format("Security for \"%s\"", dn);
Print(str);
}
}
Out("-----------", CP_PRN);
}
void CLdpDoc::OnBrowseSecurityEffective()
{
RightDlg dlg;
char *dn, *account;
CString str;
int res;
TRUSTEE t;
TRUSTEE_ACCESS ta = { 0 }; // ENOUGH for our use
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
AfxMessageBox("Not implemented yet");
return;
Out("***Calling EffectiveRights...", CP_PRN);
if (IDOK == dlg.DoModal())
{
// Try to find the effective rights for an entry
dn = dlg.m_Dn.IsEmpty() ? NULL : (char*)LPCTSTR(dlg.m_Dn);
//
// RM: remove for invalid validation
//
if (dn == NULL && m_bProtect){
AfxMessageBox("Cannot query security on a NULL dn."
"Please specify a valid dn.");
return;
}
account = dlg.m_Account.IsEmpty() ? NULL : (char*)LPCTSTR(dlg.m_Account);
//
// RM: remove for invalid validation
//
if (account == NULL && m_bProtect){
AfxMessageBox("Cannot query security for a NULL account."
"Please specify a valid account.");
return;
}
/* & we execute only in synchronous mode */
// BeginWaitCursor();
#if 0
res = SecDlgGetSecurityData(
dn,
FALSE, // Dont bother about SACL
account,
str
);
#endif
t.pMultipleTrustee = NULL;
t.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
t.TrusteeForm = TRUSTEE_IS_NAME;
t.TrusteeType = TRUSTEE_IS_UNKNOWN; // could be a group, alias, user etc.
t.ptstrName = account;
ta.fAccessFlags = TRUSTEE_ACCESS_ALLOWED;
res = TrusteeAccessToObject(
dn,
SE_DS_OBJECT_ALL,
NULL, // Provider
&t,
1,
& ta
);
if (res)
{
str.Format("TrusteeAccessToObject Failed %d", res);
}
else
{
str.Format("Access Rights %s has to %s are:", account, dn);
Print(str);
DebugBreak();
}
// EndWaitCursor();
}
Out("-----------", CP_PRN);
}
void CLdpDoc::OnUpdateBrowseSecuritySd(CCmdUI* pCmdUI)
{
pCmdUI->Enable(bConnected);
}
void CLdpDoc::OnUpdateBrowseSecurityEffective(CCmdUI* pCmdUI)
{
pCmdUI->Enable(bConnected);
}
/////////////////////// REPLICATION METADATA HANDLER & FRIENDS //////////////////////////
void CLdpDoc::OnUpdateBrowseReplicationViewmetadata(CCmdUI* pCmdUI)
{
pCmdUI->Enable(bConnected);
}
void CLdpDoc::OnBrowseReplicationViewmetadata()
{
CString str;
metadlg dlg;
CLdpView *pView;
pView = (CLdpView*)GetOwnView(_T("CLdpView"));
if(!bConnected && m_bProtect){
AfxMessageBox("Please re-connect session first");
return;
}
if(GetContextActivation()){
dlg.m_ObjectDn = TreeView()->GetDn();
TreeView()->SetContextActivation(FALSE);
}
else if (m_vlvDlg && m_vlvDlg->GetContextActivation()) {
dlg.m_ObjectDn = m_vlvDlg->GetDN();
m_vlvDlg->SetContextActivation(FALSE);
}
if (IDOK == dlg.DoModal())
{
LPTSTR dn = dlg.m_ObjectDn.IsEmpty() ? NULL : (LPTSTR)LPCTSTR(dlg.m_ObjectDn);
if(!dn){
AfxMessageBox("Please enter a valid object DN string");
return;
}
str.Format("Getting '%s' metadata...", dn);
Out(str);
BeginWaitCursor();
int ldStatus;
LDAPMessage * pldmResults;
LDAPMessage * pldmEntry;
LPSTR rgpszRootAttrsToRead[] = { "replPropertyMetaData", NULL };
LDAPControl ctrlShowDeleted = { LDAP_SERVER_SHOW_DELETED_OID };
LDAPControl * rgpctrlServerCtrls[] = { &ctrlShowDeleted, NULL };
ldStatus = ldap_search_ext_s(
hLdap,
dn,
LDAP_SCOPE_BASE,
"(objectClass=*)",
rgpszRootAttrsToRead,
0,
rgpctrlServerCtrls,
NULL,
NULL,
0,
&pldmResults
);
if ( LDAP_SUCCESS == ldStatus )
{
pldmEntry = ldap_first_entry( hLdap, pldmResults );
//
// disable redraw
//
pView->SetRedraw(FALSE);
pView->CacheStart();
if ( NULL == pldmEntry )
{
ldStatus = hLdap->ld_errno;
}
else
{
struct berval ** ppberval;
int cVals;
ppberval = ldap_get_values_len( hLdap, pldmEntry, "replPropertyMetaData" );
cVals = ldap_count_values_len( ppberval );
if ( 1 != cVals )
{
str.Format( "%d values returned for replPropertyMetaData attribute; 1 expected.\n", cVals );
Out( str );
ldStatus = LDAP_OTHER;
}
else
{
DWORD iprop;
PROPERTY_META_DATA_VECTOR * pmetavec = (PROPERTY_META_DATA_VECTOR *) ppberval[ 0 ]->bv_val;
if (VERSION_V1 != pmetavec->dwVersion)
{
str.Format("Meta Data Version is not %d!! Format unrecognizable!", VERSION_V1);
Out(str);
}
else
{
str.Format( "%d entries.", pmetavec->V1.cNumProps );
Out( str );
str.Format(
"%6s\t%6s\t%8s\t%33s\t\t\t%8s\t%18s",
"AttID",
"Ver",
"Loc.USN",
"Originating DSA",
"Org.USN",
"Org.Time/Date"
);
Out( str );
str.Format(
"%6s\t%6s\t%8s\t%33s\t\t%8s\t%18s",
"=====",
"===",
"=======",
"===============",
"=======",
"============="
);
Out( str );
for ( iprop = 0; iprop < pmetavec->V1.cNumProps; iprop++ )
{
CHAR szTime[ SZDSTIME_LEN ];
struct tm * ptm;
UCHAR * pszUUID = NULL;
UuidToString(&pmetavec->V1.rgMetaData[ iprop ].uuidDsaOriginating,
&pszUUID);
str.Format(
"%6x\t%6x\t%8I64d\t%33s\t%8I64d\t%18s",
pmetavec->V1.rgMetaData[ iprop ].attrType,
pmetavec->V1.rgMetaData[ iprop ].dwVersion,
pmetavec->V1.rgMetaData[ iprop ].usnProperty,
pszUUID ? pszUUID : (UCHAR *) "<conv err>",
pmetavec->V1.rgMetaData[ iprop ].usnOriginating,
DSTimeToDisplayString(pmetavec->V1.rgMetaData[iprop].timeChanged, szTime)
);
Out( str );
if (NULL != pszUUID) {
RpcStringFree(&pszUUID);
}
}
}
}
ldap_value_free_len( ppberval );
}
ldap_msgfree( pldmResults );
//
// now allow refresh
//
pView->CacheEnd();
pView->SetRedraw();
}
EndWaitCursor();
if ( LDAP_SUCCESS != ldStatus )
{
str.Format( "Error: %s. <%ld>", ldap_err2string( ldStatus ), ldStatus );
Out( str );
ShowErrorInfo(ldStatus);
}
Out("-----------", CP_PRN);
}
}
//
// Functions to process GeneralizedTime for DS time values (whenChanged kinda strings)
// Mostly taken & sometimes modified from \nt\private\ds\src\dsamain\src\dsatools.c
//
//
// MemAtoi - takes a pointer to a non null terminated string representing
// an ascii number and a character count and returns an integer
//
int CLdpDoc::MemAtoi(BYTE *pb, ULONG cb)
{
#if (1)
int res = 0;
int fNeg = FALSE;
if (*pb == '-') {
fNeg = TRUE;
pb++;
}
while (cb--) {
res *= 10;
res += *pb - '0';
pb++;
}
return (fNeg ? -res : res);
#else
char ach[20];
if (cb >= 20)
return(INT_MAX);
memcpy(ach, pb, cb);
ach[cb] = 0;
return atoi(ach);
#endif
}
DWORD
CLdpDoc::GeneralizedTimeStringToValue(LPSTR IN szTime,
PLONGLONG OUT pllTime)
/*++
Function : GeneralizedTimeStringToValue
Description: converts Generalized time string to equiv DWORD value
Parameters : szTime: G time string
pdwTime: returned value
Return : Success or failure
Remarks : none.
--*/
{
DWORD status = ERROR_SUCCESS;
SYSTEMTIME tmConvert;
FILETIME fileTime;
LONGLONG tempTime;
ULONG cb;
int sign = 1;
DWORD timeDifference = 0;
char *pLastChar;
int len=0;
//
// param sanity
//
if (!szTime || !pllTime)
{
return STATUS_INVALID_PARAMETER;
}
// Intialize pLastChar to point to last character in the string
// We will use this to keep track so that we don't reference
// beyond the string
len = strlen(szTime);
pLastChar = szTime + len - 1;
if( len < 15 || szTime[14] != '.')
{
return STATUS_INVALID_PARAMETER;
}
// initialize
memset(&tmConvert, 0, sizeof(SYSTEMTIME));
*pllTime = 0;
// Set up and convert all time fields
// year field
cb=4;
tmConvert.wYear = (USHORT)MemAtoi((LPBYTE)szTime, cb) ;
szTime += cb;
// month field
tmConvert.wMonth = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// day of month field
tmConvert.wDay = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// hours
tmConvert.wHour = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// minutes
tmConvert.wMinute = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// seconds
tmConvert.wSecond = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// Ignore the 1/10 seconds part of GENERALISED_TIME_STRING
szTime += 2;
// Treat the possible deferential, if any
if (szTime <= pLastChar) {
switch (*szTime++) {
case '-': // negative differential - fall through
sign = -1;
case '+': // positive differential
// Must have at least 4 more chars in string
// starting at pb
if ( (szTime+3) > pLastChar) {
// not enough characters in string
return STATUS_INVALID_PARAMETER;
}
// hours (convert to seconds)
timeDifference = (MemAtoi((LPBYTE)szTime, (cb=2))* 3600);
szTime += cb;
// minutes (convert to seconds)
timeDifference += (MemAtoi((LPBYTE)szTime, (cb=2)) * 60);
szTime += cb;
break;
case 'Z': // no differential
default:
break;
}
}
if (SystemTimeToFileTime(&tmConvert, &fileTime)) {
*pllTime = (LONGLONG) fileTime.dwLowDateTime;
tempTime = (LONGLONG) fileTime.dwHighDateTime;
*pllTime |= (tempTime << 32);
// this is 100ns blocks since 1601. Now convert to
// seconds
*pllTime = *pllTime/(10*1000*1000L);
}
else {
return GetLastError();
}
if(timeDifference) {
// add/subtract the time difference
switch (sign) {
case 1:
// We assume that adding in a timeDifference will never overflow
// (since generalised time strings allow for only 4 year digits, our
// maximum date is December 31, 9999 at 23:59. Our maximum
// difference is 99 hours and 99 minutes. So, it won't wrap)
*pllTime += timeDifference;
break;
case -1:
if(*pllTime < timeDifference) {
// differential took us back before the beginning of the world.
status = STATUS_INVALID_PARAMETER;
}
else {
*pllTime -= timeDifference;
}
break;
default:
status = STATUS_INVALID_PARAMETER;
}
}
return status;
}
DWORD
CLdpDoc::GeneralizedTimeToSystemTime(LPSTR IN szTime,
PSYSTEMTIME OUT psysTime)
/*++
Function : GeneralizedTimeStringToValue
Description: converts Generalized time string to equiv DWORD value
Parameters : szTime: G time string
pdwTime: returned value
Return : Success or failure
Remarks : none.
--*/
{
DWORD status = ERROR_SUCCESS;
ULONG cb;
ULONG len;
//
// param sanity
//
if (!szTime || !psysTime)
{
return STATUS_INVALID_PARAMETER;
}
// Intialize pLastChar to point to last character in the string
// We will use this to keep track so that we don't reference
// beyond the string
len = strlen(szTime);
if( len < 15 || szTime[14] != '.')
{
return STATUS_INVALID_PARAMETER;
}
// initialize
memset(psysTime, 0, sizeof(SYSTEMTIME));
// Set up and convert all time fields
// year field
cb=4;
psysTime->wYear = (USHORT)MemAtoi((LPBYTE)szTime, cb) ;
szTime += cb;
// month field
psysTime->wMonth = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// day of month field
psysTime->wDay = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// hours
psysTime->wHour = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// minutes
psysTime->wMinute = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
szTime += cb;
// seconds
psysTime->wSecond = (USHORT)MemAtoi((LPBYTE)szTime, (cb=2));
return status;
}
DWORD
CLdpDoc::DSTimeToSystemTime(LPSTR IN szTime,
PSYSTEMTIME OUT psysTime)
/*++
Function : DSTimeStringToValue
Description: converts UTC time string to equiv DWORD value
Parameters : szTime: G time string
pdwTime: returned value
Return : Success or failure
Remarks : none.
--*/
{
ULONGLONG ull;
FILETIME filetime;
BOOL ok;
ull = _atoi64 (szTime);
filetime.dwLowDateTime = (DWORD) (ull & 0xFFFFFFFF);
filetime.dwHighDateTime = (DWORD) (ull >> 32);
// Convert FILETIME to SYSTEMTIME,
if (!FileTimeToSystemTime(&filetime, psysTime)) {
return !ERROR_SUCCESS;
}
return ERROR_SUCCESS;
}
/*++
Function : OnOptionsStartTLS
Description: initiate Transport Level Security on an LDAP connection.
Parameters : none
Return : none
Remarks : none.
--*/
void CLdpDoc::OnOptionsStartTls()
{
ULONG retValue, err;
CString str;
PLDAPControl *SvrCtrls;
PLDAPControl *ClntCtrls;
PLDAPMessage result = NULL;
str.Format("ldap_start_tls_s(ld, &retValue, result, SvrCtrls, ClntCtrls)");
Out(str);
// controls
SvrCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_SVR);
ClntCtrls = m_CtrlDlg->AllocCtrlList(ctrldlg::CT_CLNT);
err = ldap_start_tls_s(hLdap, &retValue, &result, SvrCtrls, ClntCtrls);
if(err == 0){
str.Format("result <0>");
Out(str);
}
else{
str.Format("Error <0x%X>:ldap_start_tls_s() failed: %s", err, ldap_err2string(err));
Out(str);
str.Format("Server Returned: 0x%X: %s", retValue, ldap_err2string(retValue));
Out(str);
ShowErrorInfo(err);
// If the server returned a referal, check the returned message and print.
if(result != NULL){
str.Format("Checking return message for referal...");
Out(str);
// if there was a referal then the referal will be in the message.
DisplaySearchResults(result);
}
}
ldap_msgfree(result);
}
/*++
Function : OnOptionsStopTLS
Description: Terminate Transport Level Security on an LDAP connection.
Parameters : none
Return : none
Remarks : none.
--*/
void CLdpDoc::OnOptionsStopTls()
{
ULONG retValue, err;
CString str;
str.Format("ldap_stop_tls_s( ld )");
Out(str);
err = ldap_stop_tls_s( hLdap );
if(err == 0){
str.Format("result <0>");
Out(str);
}
else{
str.Format("Error <0x%X>:ldap_stop_tls_s() failed:%s", err, ldap_err2string(err));
Out(str);
ShowErrorInfo(err);
}
}
/*
*/
void CLdpDoc::OnGetLastError()
{
CString str;
str.Format(_T("0x%X=LdapGetLastError() %s"), LdapGetLastError(), ldap_err2string(LdapGetLastError()) );
Out(str, CP_CMT);
}
void CLdpDoc::ShowErrorInfo(int res)
{
int err;
LPTSTR pStr = NULL;
CString str;
if (hLdap == NULL || res == 0 || !m_GenOptDlg->m_extErrorInfo) {
return;
}
err = ldap_get_option(hLdap, LDAP_OPT_SERVER_ERROR, (LPVOID)&pStr);
if (err == 0) {
// success
str.Format("Server error: %s", pStr?pStr:"<empty>");
}
else {
str.Format("Error <0x%X>:ldap_get_option(hLdap, LDAP_OPT_SERVER_ERROR, &pStr) failed:%s", err, ldap_err2string(err));
}
Out(str);
}
| 30.68029
| 145
| 0.435571
|
npocmaka
|
098225952388ba074e560ffa576c15afc2ebe0c4
| 2,258
|
cpp
|
C++
|
TestApps/Rosetta/BNN/Sources/utils/DataIO.cpp
|
stephenneuendorffer/hls_tuner
|
fa7de78f0e2bb4b8f9f2e0a0368ed071b379c875
|
[
"MIT"
] | 1
|
2021-02-21T12:13:09.000Z
|
2021-02-21T12:13:09.000Z
|
TestApps/Rosetta/BNN/Sources/utils/DataIO.cpp
|
stephenneuendorffer/hls_tuner
|
fa7de78f0e2bb4b8f9f2e0a0368ed071b379c875
|
[
"MIT"
] | null | null | null |
TestApps/Rosetta/BNN/Sources/utils/DataIO.cpp
|
stephenneuendorffer/hls_tuner
|
fa7de78f0e2bb4b8f9f2e0a0368ed071b379c875
|
[
"MIT"
] | 1
|
2019-09-10T16:45:27.000Z
|
2019-09-10T16:45:27.000Z
|
#include "DataIO.h"
#ifdef RUN_STANDALONE
#include <ff.h>
#endif
Cifar10TestInputs::Cifar10TestInputs(const std::string & filename, unsigned n)
: m_size(n*CHANNELS*ROWS*COLS)
{
#ifdef RUN_STANDALONE
data = new float[m_size];
DB_PRINT(2, "Opening data file %s\n", filename.c_str());
FIL File;
if (f_open(&File, filename.c_str(), FA_READ) != FR_OK)
{
printf("Cannot open file %s\n", filename.c_str());
exit(1);
}
unsigned Size;
if (f_read(&File, data, m_size * 4, &Size) != FR_OK || Size != m_size * 4)
{
printf("Cannot read file %s\n", filename.c_str());
exit(1);
}
if (f_close(&File) != FR_OK)
{
printf("Cannot close file %s\n", filename.c_str());
exit(1);
}
#else
data = new float[m_size];
DB_PRINT(2, "Opening data archive %s\n", filename.c_str());
unzFile ar = open_unzip(filename.c_str());
unsigned nfiles = get_nfiles_in_unzip(ar);
assert(nfiles == 1);
// We read m_size*4 bytes from the archive
unsigned fsize = get_current_file_size(ar);
assert(m_size*4 <= fsize);
DB_PRINT(2, "Reading %u bytes\n", m_size*4);
read_current_file(ar, (void*)data, m_size*4);
unzClose(ar);
#endif
}
Cifar10TestLabels::Cifar10TestLabels(const std::string & filename, unsigned n)
: m_size(n)
{
#ifdef RUN_STANDALONE
data = new float[m_size];
DB_PRINT(2, "Opening data file %s\n", filename.c_str());
FIL File;
if (f_open(&File, filename.c_str(), FA_READ) != FR_OK)
{
printf("Cannot open file %s\n", filename.c_str());
exit(1);
}
unsigned Size;
if (f_read(&File, data, m_size * 4, &Size) != FR_OK || Size != m_size * 4)
{
printf("Cannot read file %s\n", filename.c_str());
exit(1);
}
if (f_close(&File) != FR_OK)
{
printf("Cannot close file %s\n", filename.c_str());
exit(1);
}
#else
data = new float[m_size];
DB_PRINT(2, "Opening data archive %s\n", filename.c_str());
unzFile ar = open_unzip(filename.c_str());
unsigned nfiles = get_nfiles_in_unzip(ar);
assert(nfiles == 1);
// We read n*4 bytes from the archive
unsigned fsize = get_current_file_size(ar);
assert(m_size*4 <= fsize);
DB_PRINT(2, "Reading %u bytes\n", m_size*4);
read_current_file(ar, (void*)data, m_size*4);
unzClose(ar);
#endif
}
| 23.520833
| 78
| 0.641718
|
stephenneuendorffer
|
0982fc2f50f944be4581a3e21cd40ce1d769102d
| 1,273
|
cpp
|
C++
|
src/trade_book/TradeBook.cpp
|
karelhala-cz/BitstampTax
|
361b94a8acf233082badc21da256b4089aad2188
|
[
"MIT"
] | null | null | null |
src/trade_book/TradeBook.cpp
|
karelhala-cz/BitstampTax
|
361b94a8acf233082badc21da256b4089aad2188
|
[
"MIT"
] | null | null | null |
src/trade_book/TradeBook.cpp
|
karelhala-cz/BitstampTax
|
361b94a8acf233082badc21da256b4089aad2188
|
[
"MIT"
] | null | null | null |
//*********************************************************************************************************************
// Author: Karel Hala, hala.karel@gmail.com
// Copyright: (c) 2021-2022 Karel Hala
// License: MIT
//*********************************************************************************************************************
#include "TradeBook.h"
#include "TradeItem.h"
#include "TradeItemMarket.h"
C_TradeBook::C_TradeBook()
{
}
void C_TradeBook::Reserve(size_t const count)
{
m_TradeItems.reserve(count);
}
void C_TradeBook::AddItem(std::unique_ptr<C_TradeItem> && item)
{
m_TradeItems.emplace_back(std::move(item));
}
void C_TradeBook::SetTradeItems(T_TradeItems && items)
{
m_TradeItems = std::move(items);
}
T_CurrencyType C_TradeBook::AssessUserCurrency() const
{
T_CurrencyType userCurrency;
for (T_TradeItemUniquePtr const & item : m_TradeItems)
{
C_TradeItemMarket const * const itemMarket (dynamic_cast<C_TradeItemMarket const *>(item.get()));
if (itemMarket != nullptr)
{
userCurrency = itemMarket->GetValue().GetType();
break;
}
}
return userCurrency;
}
void C_TradeBook::PrintData(std::ostringstream & str)
{
for (T_TradeItemUniquePtr & item : m_TradeItems)
{
item->PrintData(str);
str << std::endl;
}
}
| 23.574074
| 119
| 0.586803
|
karelhala-cz
|
09839fb928a67e869b7b8cf5c6a1129430fd171f
| 796
|
cpp
|
C++
|
src/gamelib/utils/LifetimeTracker.cpp
|
mall0c/GameLib
|
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
|
[
"MIT"
] | 1
|
2020-02-17T09:53:36.000Z
|
2020-02-17T09:53:36.000Z
|
src/gamelib/utils/LifetimeTracker.cpp
|
mall0c/GameLib
|
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
|
[
"MIT"
] | null | null | null |
src/gamelib/utils/LifetimeTracker.cpp
|
mall0c/GameLib
|
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
|
[
"MIT"
] | null | null | null |
#include "gamelib/utils/LifetimeTracker.hpp"
namespace gamelib
{
SlotMapShort<void*> LifetimeTrackerManager::_data;
LifetimeTrackerManager::LifetimeTrackerManager()
{ }
auto LifetimeTrackerManager::add(void* ptr) -> LifetimeHandle
{
auto h = _data.acquire();
_data[h] = ptr;
return h;
}
auto LifetimeTrackerManager::del(LifetimeHandle handle) -> void
{
_data.destroy(handle);
}
auto LifetimeTrackerManager::get(LifetimeHandle handle) -> void*
{
if (_data.isValid(handle))
return _data[handle];
return nullptr;
}
auto LifetimeTrackerManager::update(LifetimeHandle handle, void* newptr) -> void
{
if (_data.isValid(handle))
_data[handle] = newptr;
}
}
| 22.742857
| 84
| 0.628141
|
mall0c
|
0988cb9ad208ef6d58ccf6001e8cd49c540a41e6
| 2,410
|
cpp
|
C++
|
VoDTCPServer/VoDTCPServerView.cpp
|
ckaraca/VoD
|
415590649053eb560ef094768bec210c4c0fe19f
|
[
"MIT"
] | 3
|
2021-11-26T21:26:32.000Z
|
2022-01-09T20:54:49.000Z
|
VoDTCPServer/VoDTCPServerView.cpp
|
ckaraca/VoD
|
415590649053eb560ef094768bec210c4c0fe19f
|
[
"MIT"
] | null | null | null |
VoDTCPServer/VoDTCPServerView.cpp
|
ckaraca/VoD
|
415590649053eb560ef094768bec210c4c0fe19f
|
[
"MIT"
] | null | null | null |
// VoDTCPServerView.cpp : implementation of the CVoDTCPServerView class
//
#include "stdafx.h"
#include "VoDTCPServer.h"
#include "VoDTCPServerDoc.h"
#include "VoDTCPServerView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define WSA_VERSION MAKEWORD(2,0)
extern TCHAR ServerPathName[];
extern TCHAR ServerPath[];
// CVoDTCPServerView
IMPLEMENT_DYNCREATE(CVoDTCPServerView, CListView)
BEGIN_MESSAGE_MAP(CVoDTCPServerView, CListView)
ON_MESSAGE(WM_SETLIST,SetListEx)
ON_MESSAGE(WM_SETLISTS,SetListSuccessEx)
END_MESSAGE_MAP()
// CVoDTCPServerView construction/destruction
extern HWND hWnd;
CVoDTCPServerView::CVoDTCPServerView()
{
index = 0;
}
CVoDTCPServerView::~CVoDTCPServerView()
{
}
BOOL CVoDTCPServerView::PreCreateWindow(CREATESTRUCT& cs)
{
cs.style &= ~LVS_TYPEMASK;
cs.style |= LVS_REPORT;
return CListView::PreCreateWindow(cs);
}
void CVoDTCPServerView::OnInitialUpdate()
{
CListView::OnInitialUpdate();
RECT rc;
GetClientRect(&rc);
GetListCtrl ().InsertColumn (0, _T ("Status ID"), LVCFMT_LEFT, 100);
GetListCtrl ().InsertColumn (1, _T ("Event"), LVCFMT_LEFT, 300);
GetListCtrl ().InsertColumn (2, _T ("Success"), LVCFMT_LEFT,rc.right-400);
// begin adding here
SetList("002","Starting Windows sockets");
SetListSuccess("OK!");
SetList("003","Starting TCP Listener thread");
//Listen = new CTCPListener;
hWnd = this->m_hWnd;
AfxBeginThread(TCPListener,(LPVOID)0);
SetListSuccess("OK!");
}
void CVoDTCPServerView::SetList(TCHAR *Code,TCHAR *Event)
{
GetListCtrl ().InsertItem (index,Code);
GetListCtrl ().SetItemText (index, 1, Event);
}
void CVoDTCPServerView::SetListSuccess(TCHAR *Success)
{
GetListCtrl ().SetItemText (index++, 2, Success);
}
LONG CVoDTCPServerView::SetListEx(WPARAM wParam,LPARAM lParam)
{
SetList((TCHAR *)wParam,(TCHAR *)lParam);
return 0;
}
LONG CVoDTCPServerView::SetListSuccessEx(WPARAM wParam,LPARAM /*lParam*/)
{
SetListSuccess((TCHAR *)wParam);
return 0;
}
// CVoDTCPServerView diagnostics
#ifdef _DEBUG
void CVoDTCPServerView::AssertValid() const
{
CListView::AssertValid();
}
void CVoDTCPServerView::Dump(CDumpContext& dc) const
{
CListView::Dump(dc);
}
CVoDTCPServerDoc* CVoDTCPServerView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CVoDTCPServerDoc)));
return (CVoDTCPServerDoc*)m_pDocument;
}
#endif //_DEBUG
// CVoDTCPServerView message handlers
| 21.327434
| 87
| 0.755602
|
ckaraca
|
09899356e00cbb258e99c61dd65dd32b225df382
| 2,492
|
cpp
|
C++
|
plugins/builtin.cpp
|
iotbzh/DEPRECATED_afb-signal-composer
|
ee50d58c38e4a8f2dafd40b6cdf3aa6c7612e866
|
[
"Apache-2.0"
] | null | null | null |
plugins/builtin.cpp
|
iotbzh/DEPRECATED_afb-signal-composer
|
ee50d58c38e4a8f2dafd40b6cdf3aa6c7612e866
|
[
"Apache-2.0"
] | null | null | null |
plugins/builtin.cpp
|
iotbzh/DEPRECATED_afb-signal-composer
|
ee50d58c38e4a8f2dafd40b6cdf3aa6c7612e866
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2016 "IoT.bzh"
* Author Romain Forlot <romain.forlot@iot.bzh>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define AFB_BINDING_VERSION 2
#include <afb/afb-binding.h>
#include <systemd/sd-event.h>
#include <json-c/json_object.h>
#include <stdbool.h>
#include <string.h>
#include "signal-composer.hpp"
#include "ctl-config.h"
#include "wrap-json.h"
extern "C"
{
CTLP_LUA_REGISTER("builtin");
static struct signalCBT* pluginCtx = NULL;
// Call at initialisation time
/*CTLP_ONLOAD(plugin, handle) {
pluginCtx = (struct signalCBT*)calloc (1, sizeof(struct signalCBT));
pluginCtx = (struct signalCBT*)handle;
AFB_NOTICE ("Signal Composer builtin plugin: label='%s' info='%s'",
plugin->uid,
plugin->info);
return (void*)pluginCtx;
}*/
CTLP_CAPI (defaultOnReceived, source, argsJ, eventJ)
{
struct signalCBT* ctx = (struct signalCBT*)source->context;
AFB_NOTICE("source: %s argj: %s, eventJ %s", source->uid,
json_object_to_json_string(argsJ),
json_object_to_json_string(eventJ));
void* sig = ctx->aSignal;
json_object* valueJ = nullptr;
json_object* timestampJ = nullptr;
double value = 0;
uint64_t timestamp = 0;
if(json_object_object_get_ex(eventJ, "value", &valueJ))
{value = json_object_get_double(valueJ);}
if(json_object_object_get_ex(eventJ, "timestamp", ×tampJ))
{timestamp = json_object_get_int64(timestampJ);}
struct signalValue v = value;
ctx->setSignalValue(sig, timestamp, v);
return 0;
}
CTLP_LUA2C (setSignalValueWrap, source, argsJ, responseJ)
{
const char* name = nullptr;
double resultNum;
uint64_t timestamp;
if(! wrap_json_unpack(argsJ, "{ss, sF, sI? !}",
"name", &name,
"value", &resultNum,
"timestamp", ×tamp))
{
AFB_ERROR("Fail to set value for uid: %s, argsJ: %s", source->uid, json_object_to_json_string(argsJ));
return -1;
}
struct signalValue result = resultNum;
pluginCtx->searchNsetSignalValue(name, timestamp*MICRO, result);
return 0;
}
// extern "C" closure
}
| 27.688889
| 104
| 0.725522
|
iotbzh
|
0995a4bfc97cf2bc46e173bd52b113ce0b119b86
| 2,190
|
cpp
|
C++
|
src/libs/utilities/testharness/play.cpp
|
suggitpe/RPMS
|
7a12da0128f79b8b0339fd7146105ba955079b8c
|
[
"Apache-2.0"
] | null | null | null |
src/libs/utilities/testharness/play.cpp
|
suggitpe/RPMS
|
7a12da0128f79b8b0339fd7146105ba955079b8c
|
[
"Apache-2.0"
] | null | null | null |
src/libs/utilities/testharness/play.cpp
|
suggitpe/RPMS
|
7a12da0128f79b8b0339fd7146105ba955079b8c
|
[
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <iostream>
void print_cpu_time()
{
struct rusage usage;
getrusage (RUSAGE_SELF, &usage);
printf ("CPU time: %ld.%06ld sec user, %ld.%06ld sec system\n",
usage.ru_utime.tv_sec, usage.ru_utime.tv_usec,
usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
std::cout << "user (" << usage.ru_utime.tv_sec << ") secs, (" << usage.ru_utime.tv_usec << ")" << std::endl;
}
void debug() // just somewhere safe to keep the info
{
/*cout << "Description ...............................................: " << setw(20) << "Latest" << setw(20) << "Baseline" << setw(20) << "Diff" << endl;
cout << "-----------------------------------------------------------: " << setw(20) << "------" << setw(20) << "--------" << setw(20) << "----" << endl;
cout << "Total amount of user time used (secs) .....................: " << setw(20) << mLatestData.ru_utime.tv_sec << setw(20) << mBaselineData.ru_utime.tv_sec << setw(20) << (mLatestData.ru_utime.tv_sec - mBaselineData.ru_utime.tv_sec) << endl;
cout << "Total amount of user time used (u_secs) ...................: " << setw(20) << mLatestData.ru_utime.tv_usec << setw(20) << mBaselineData.ru_utime.tv_usec << setw(20) << (mLatestData.ru_utime.tv_usec - mBaselineData.ru_utime.tv_usec) << endl;
cout << "Total amount of system time used (secs) ...................: " << setw(20) << mLatestData.ru_stime.tv_sec << setw(20) << mBaselineData.ru_stime.tv_sec << setw(20) << (mLatestData.ru_stime.tv_sec - mBaselineData.ru_stime.tv_sec) << endl;
cout << "Total amount of system time used (usecs) ..................: " << setw(20) << mLatestData.ru_stime.tv_usec << setw(20) << mBaselineData.ru_stime.tv_usec << setw(20) << (mLatestData.ru_stime.tv_usec - mBaselineData.ru_stime.tv_usec) << endl;
cout << "Maximum resident set size (in kilobytes) ..................: " << setw(20) << mLatestData.ru_maxrss << setw(20) << mBaselineData.ru_maxrss << setw(20) << (mLatestData.ru_maxrss - mBaselineData.ru_maxrss) << endl;*/
}
int main()
{
print_cpu_time();
return 0;
}
| 66.363636
| 256
| 0.574886
|
suggitpe
|
0998a6a1c67e59ff7263fff32514f9b73af3fa9b
| 1,583
|
cpp
|
C++
|
modules/cudaimgproc/samples/connected_components.cpp
|
pccvlab/opencv_contrib
|
f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93
|
[
"Apache-2.0"
] | null | null | null |
modules/cudaimgproc/samples/connected_components.cpp
|
pccvlab/opencv_contrib
|
f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93
|
[
"Apache-2.0"
] | null | null | null |
modules/cudaimgproc/samples/connected_components.cpp
|
pccvlab/opencv_contrib
|
f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaimgproc.hpp"
using namespace cv;
using namespace std;
using namespace cv::cuda;
void colorLabels(const Mat1i& labels, Mat3b& colors) {
colors.create(labels.size());
for (int r = 0; r < labels.rows; ++r) {
int const* labels_row = labels.ptr<int>(r);
Vec3b* colors_row = colors.ptr<Vec3b>(r);
for (int c = 0; c < labels.cols; ++c) {
colors_row[c] = Vec3b(labels_row[c] * 131 % 255, labels_row[c] * 241 % 255, labels_row[c] * 251 % 255);
}
}
}
int main(int argc, const char** argv)
{
CommandLineParser parser(argc, argv, "{@image|stuff.jpg|image for converting to a grayscale}");
parser.about("This program finds connected components in a binary image and assign each of them a different color.\n"
"The connected components labeling is performed in GPU.\n");
parser.printMessage();
String inputImage = parser.get<string>(0);
Mat1b img = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
Mat1i labels;
if (img.empty())
{
cout << "Could not read input image file: " << inputImage << endl;
return EXIT_FAILURE;
}
GpuMat d_img, d_labels;
d_img.upload(img);
cuda::connectedComponents(d_img, d_labels, 8, CV_32S);
d_labels.download(labels);
Mat3b colors;
colorLabels(labels, colors);
imshow("Labels", colors);
waitKey(0);
return EXIT_SUCCESS;
}
| 26.830508
| 121
| 0.655085
|
pccvlab
|
099a548581f12d5b5a3a2a36c45dd14ccf4a8336
| 176
|
cpp
|
C++
|
src/world/health.cpp
|
louiz/batajelo
|
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
|
[
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7
|
2015-01-28T09:17:08.000Z
|
2020-04-21T13:51:16.000Z
|
src/world/health.cpp
|
louiz/batajelo
|
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
|
[
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null |
src/world/health.cpp
|
louiz/batajelo
|
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
|
[
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1
|
2020-07-11T09:20:25.000Z
|
2020-07-11T09:20:25.000Z
|
#include <world/health.hpp>
const ComponentType Health::component_type;
Health::Health(const Quantity::type max):
Quantity(max)
{
}
void Health::tick(Entity*, World*)
{
}
| 13.538462
| 43
| 0.721591
|
louiz
|
099a85de008229877140cca914f025843039871f
| 372
|
cpp
|
C++
|
05_bits/digits_demo.cpp
|
anton0xf/stepik_cpp
|
fe87fff8523bc62c92b13dc8c0908b6d984aec43
|
[
"MIT"
] | null | null | null |
05_bits/digits_demo.cpp
|
anton0xf/stepik_cpp
|
fe87fff8523bc62c92b13dc8c0908b6d984aec43
|
[
"MIT"
] | null | null | null |
05_bits/digits_demo.cpp
|
anton0xf/stepik_cpp
|
fe87fff8523bc62c92b13dc8c0908b6d984aec43
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include "digits.hpp"
int main() {
init_digits();
printf("values: \n");
for (int i=0; i < VALUES_COUNT; i++) {
if (values[i] == UNUSED) continue;
printf("%c -> %lld\n", (char)i, values[i]);
}
printf("digits: ");
for (int i=0; i < DIGITS_COUNT; i++) {
printf("%c, ", digits[i]);
}
printf("\n");
}
| 21.882353
| 51
| 0.491935
|
anton0xf
|
099fbb7c121449c95fb9f56489000d921c612477
| 814
|
hpp
|
C++
|
Kuplung/kuplung/utilities/consumption/WindowsCPUUsage.hpp
|
supudo/Kuplung
|
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
|
[
"Unlicense"
] | 14
|
2017-02-17T17:12:40.000Z
|
2021-12-22T01:55:06.000Z
|
Kuplung/kuplung/utilities/consumption/WindowsCPUUsage.hpp
|
supudo/Kuplung
|
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
|
[
"Unlicense"
] | null | null | null |
Kuplung/kuplung/utilities/consumption/WindowsCPUUsage.hpp
|
supudo/Kuplung
|
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
|
[
"Unlicense"
] | 1
|
2019-10-15T08:10:10.000Z
|
2019-10-15T08:10:10.000Z
|
//
// WindowsCPUUsage.hpp
// Kuplung
//
// Created by Sergey Petrov on 12/16/15.
// Copyright © 2015 supudo.net. All rights reserved.
//
#ifndef WindowsCPUUsage_hpp
#define WindowsCPUUsage_hpp
namespace KuplungApp { namespace Utilities { namespace Consumption {
#include <windows.h>
class WindowsCPUUsage {
public:
WindowsCPUUsage();
short GetUsage();
private:
ULONGLONG SubtractTimes(const FILETIME& ftA, const FILETIME& ftB);
bool EnoughTimePassed();
inline bool IsFirstRun() const { return (m_dwLastRun == 0); }
//system total times
FILETIME m_ftPrevSysKernel;
FILETIME m_ftPrevSysUser;
//process times
FILETIME m_ftPrevProcKernel;
FILETIME m_ftPrevProcUser;
short m_nCpuUsage;
ULONGLONG m_dwLastRun;
volatile LONG m_lRunCount;
};
}}}
#endif /* WindowsCPUUsage_hpp */
| 18.930233
| 68
| 0.739558
|
supudo
|
09a0d8fbc646e7ed4bca93c50809b96655e90b06
| 787
|
cpp
|
C++
|
assingment/32.cpp
|
aditya1k2/CPP-SEM-2-KIIT
|
1afceeb39458201b6dafe33422d7de8e613d96de
|
[
"MIT"
] | null | null | null |
assingment/32.cpp
|
aditya1k2/CPP-SEM-2-KIIT
|
1afceeb39458201b6dafe33422d7de8e613d96de
|
[
"MIT"
] | null | null | null |
assingment/32.cpp
|
aditya1k2/CPP-SEM-2-KIIT
|
1afceeb39458201b6dafe33422d7de8e613d96de
|
[
"MIT"
] | null | null | null |
/* Name:- Aditya Kumar Gupta
Roll No.:- 1706291
Sec:- B-19
Ques No.:-32 */
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
char str[100],pat[20],new_str[100],rep_pat[50];
int i=0,j=0,k,n=0,copy_loop=0, rep_index=0;
cout<<"Enter the string:\n";
gets(str);
cout<<"\nEnter the pattern: ";
gets(pat);
cout<<"\nEnter the replace pattern:";
gets(rep_pat);
while(str[i]!='\0')
{ j=0,k=i;
while(str[k]==pat[j] && pat[j]!='\0')
{ k++;
j++;
}
if(pat[j]=='\0')
{ copy_loop=k;
while(rep_pat[rep_index]!='\0')
{ new_str[n]=rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n]=str[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
cout<<"\nThe new string is: ";
puts(new_str);
return 0;
}
| 18.738095
| 48
| 0.556544
|
aditya1k2
|
09a191ad3902e2287e28eccae3b07851957fe736
| 2,035
|
cpp
|
C++
|
cpp/HeapStack/HeapStack_v1/main.cpp
|
ArboreusSystems/arboreus_examples
|
17d39e18f4b2511c19f97d4e6c07ec9d7087fae8
|
[
"BSD-3-Clause"
] | 17
|
2019-02-19T21:29:22.000Z
|
2022-01-29T11:03:45.000Z
|
cpp/HeapStack/HeapStack_v1/main.cpp
|
MbohBless/arboreus_examples
|
97f0e25182bbc4b5ffab37c6157514332002aeee
|
[
"BSD-3-Clause"
] | null | null | null |
cpp/HeapStack/HeapStack_v1/main.cpp
|
MbohBless/arboreus_examples
|
97f0e25182bbc4b5ffab37c6157514332002aeee
|
[
"BSD-3-Clause"
] | 9
|
2021-02-21T05:32:23.000Z
|
2022-02-26T07:51:52.000Z
|
/* -------------------------------------------------------------------
* @doc
* @notice Template file wizards/projects/plaincpp/main.cpp
*
* @copyright Arboreus (http://arboreus.systems)
* @author Alexandr Kirilov (http://alexandr.kirilov.me)
* @created 19/07/2020 at 13:12:12
* */// --------------------------------------------------------------
// System includes
#include <iostream>
// Application includes
#include "maindatamodels.h"
#include "alogger.h"
// Constants
#define A_MAX_LOOP_COUNT 10000000
// Namespace
using namespace std;
// Application
int main(int inCounter, char *inArguments[]) {
int oStackInteger = 10;
int oStackArray[10];
oStackArray[0] = 0; oStackArray[1] = 1;
oStackArray[2] = 2; oStackArray[3] = 3;
oStackArray[4] = 4; oStackArray[5] = 5;
oStackArray[6] = 6; oStackArray[7] = 7;
oStackArray[8] = 8; oStackArray[9] = 9;
ACordinates oStackCordinates;
oStackCordinates.pX = 100;
oStackCordinates.pY = 100;
int* oHeapInteger = new int; *oHeapInteger = 5;
int* oHeapArray = new int[10];
oHeapArray[0] = 0; oHeapArray[1] = 1;
oHeapArray[2] = 2; oHeapArray[3] = 3;
oHeapArray[4] = 4; oHeapArray[5] = 5;
oHeapArray[6] = 6; oHeapArray[7] = 7;
oHeapArray[8] = 8; oHeapArray[9] = 9;
ACordinates* oHeapCordinates = new ACordinates();
oHeapCordinates->pX = 20;
oHeapCordinates->pY = 20;
delete oHeapInteger;
delete[] oHeapArray;
delete oHeapCordinates;
clock_t oStackAllocStart = clock();
for (int i = 0; i < A_MAX_LOOP_COUNT; ++i) {
ACordinates iStackCordinates1 = ACordinates();
}
clock_t oStackAllocDuartion = clock() - oStackAllocStart;
ALOG << "Stack allocation duration: " << oStackAllocDuartion << endl;
clock_t oHeapAllocStart = clock();
for (int i = 0; i < A_MAX_LOOP_COUNT; ++i) {
ACordinates* iHeapCordinates1 = new ACordinates();
// delete iHeapCordinates1;
}
clock_t oHeapAllocDuartion = clock() - oHeapAllocStart;
ALOG << "Heap allocation duration: " << oHeapAllocDuartion << endl;
ALOG << "Heap and stack demo OK" << endl;
return 0;
}
| 26.776316
| 70
| 0.648649
|
ArboreusSystems
|