hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
addeda634cac9ac0482948c3cf8a791516bab8a1 | 22,545 | cpp | C++ | src/qt/qtbase/src/plugins/platforms/mirclient/qmirclientinput.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/src/plugins/platforms/mirclient/qmirclientinput.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/plugins/platforms/mirclient/qmirclientinput.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2014-2015 Canonical, Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
// Local
#include "qmirclientinput.h"
#include "qmirclientintegration.h"
#include "qmirclientnativeinterface.h"
#include "qmirclientscreen.h"
#include "qmirclientwindow.h"
#include "qmirclientlogging.h"
#include "qmirclientorientationchangeevent_p.h"
// Qt
#if !defined(QT_NO_DEBUG)
#include <QtCore/QThread>
#endif
#include <QtCore/qglobal.h>
#include <QtCore/QCoreApplication>
#include <private/qguiapplication_p.h>
#include <qpa/qplatforminputcontext.h>
#include <qpa/qwindowsysteminterface.h>
#include <xkbcommon/xkbcommon.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <mir_toolkit/mir_client_library.h>
#define LOG_EVENTS 0
// XKB Keysyms which do not map directly to Qt types (i.e. Unicode points)
static const uint32_t KeyTable[] = {
XKB_KEY_Escape, Qt::Key_Escape,
XKB_KEY_Tab, Qt::Key_Tab,
XKB_KEY_ISO_Left_Tab, Qt::Key_Backtab,
XKB_KEY_BackSpace, Qt::Key_Backspace,
XKB_KEY_Return, Qt::Key_Return,
XKB_KEY_Insert, Qt::Key_Insert,
XKB_KEY_Delete, Qt::Key_Delete,
XKB_KEY_Clear, Qt::Key_Delete,
XKB_KEY_Pause, Qt::Key_Pause,
XKB_KEY_Print, Qt::Key_Print,
XKB_KEY_Home, Qt::Key_Home,
XKB_KEY_End, Qt::Key_End,
XKB_KEY_Left, Qt::Key_Left,
XKB_KEY_Up, Qt::Key_Up,
XKB_KEY_Right, Qt::Key_Right,
XKB_KEY_Down, Qt::Key_Down,
XKB_KEY_Prior, Qt::Key_PageUp,
XKB_KEY_Next, Qt::Key_PageDown,
XKB_KEY_Shift_L, Qt::Key_Shift,
XKB_KEY_Shift_R, Qt::Key_Shift,
XKB_KEY_Shift_Lock, Qt::Key_Shift,
XKB_KEY_Control_L, Qt::Key_Control,
XKB_KEY_Control_R, Qt::Key_Control,
XKB_KEY_Meta_L, Qt::Key_Meta,
XKB_KEY_Meta_R, Qt::Key_Meta,
XKB_KEY_Alt_L, Qt::Key_Alt,
XKB_KEY_Alt_R, Qt::Key_Alt,
XKB_KEY_Caps_Lock, Qt::Key_CapsLock,
XKB_KEY_Num_Lock, Qt::Key_NumLock,
XKB_KEY_Scroll_Lock, Qt::Key_ScrollLock,
XKB_KEY_Super_L, Qt::Key_Super_L,
XKB_KEY_Super_R, Qt::Key_Super_R,
XKB_KEY_Menu, Qt::Key_Menu,
XKB_KEY_Hyper_L, Qt::Key_Hyper_L,
XKB_KEY_Hyper_R, Qt::Key_Hyper_R,
XKB_KEY_Help, Qt::Key_Help,
XKB_KEY_KP_Space, Qt::Key_Space,
XKB_KEY_KP_Tab, Qt::Key_Tab,
XKB_KEY_KP_Enter, Qt::Key_Enter,
XKB_KEY_KP_Home, Qt::Key_Home,
XKB_KEY_KP_Left, Qt::Key_Left,
XKB_KEY_KP_Up, Qt::Key_Up,
XKB_KEY_KP_Right, Qt::Key_Right,
XKB_KEY_KP_Down, Qt::Key_Down,
XKB_KEY_KP_Prior, Qt::Key_PageUp,
XKB_KEY_KP_Next, Qt::Key_PageDown,
XKB_KEY_KP_End, Qt::Key_End,
XKB_KEY_KP_Begin, Qt::Key_Clear,
XKB_KEY_KP_Insert, Qt::Key_Insert,
XKB_KEY_KP_Delete, Qt::Key_Delete,
XKB_KEY_KP_Equal, Qt::Key_Equal,
XKB_KEY_KP_Multiply, Qt::Key_Asterisk,
XKB_KEY_KP_Add, Qt::Key_Plus,
XKB_KEY_KP_Separator, Qt::Key_Comma,
XKB_KEY_KP_Subtract, Qt::Key_Minus,
XKB_KEY_KP_Decimal, Qt::Key_Period,
XKB_KEY_KP_Divide, Qt::Key_Slash,
XKB_KEY_ISO_Level3_Shift, Qt::Key_AltGr,
XKB_KEY_Multi_key, Qt::Key_Multi_key,
XKB_KEY_Codeinput, Qt::Key_Codeinput,
XKB_KEY_SingleCandidate, Qt::Key_SingleCandidate,
XKB_KEY_MultipleCandidate, Qt::Key_MultipleCandidate,
XKB_KEY_PreviousCandidate, Qt::Key_PreviousCandidate,
XKB_KEY_Mode_switch, Qt::Key_Mode_switch,
XKB_KEY_script_switch, Qt::Key_Mode_switch,
XKB_KEY_XF86AudioRaiseVolume, Qt::Key_VolumeUp,
XKB_KEY_XF86AudioLowerVolume, Qt::Key_VolumeDown,
XKB_KEY_XF86PowerOff, Qt::Key_PowerOff,
XKB_KEY_XF86PowerDown, Qt::Key_PowerDown,
0, 0
};
class QMirClientEvent : public QEvent
{
public:
QMirClientEvent(QMirClientWindow* window, const MirEvent *event, QEvent::Type type)
: QEvent(type), window(window) {
nativeEvent = mir_event_ref(event);
}
~QMirClientEvent()
{
mir_event_unref(nativeEvent);
}
QPointer<QMirClientWindow> window;
const MirEvent *nativeEvent;
};
QMirClientInput::QMirClientInput(QMirClientClientIntegration* integration)
: QObject(nullptr)
, mIntegration(integration)
, mEventFilterType(static_cast<QMirClientNativeInterface*>(
integration->nativeInterface())->genericEventFilterType())
, mEventType(static_cast<QEvent::Type>(QEvent::registerEventType()))
, mLastFocusedWindow(nullptr)
{
// Initialize touch device.
mTouchDevice = new QTouchDevice;
mTouchDevice->setType(QTouchDevice::TouchScreen);
mTouchDevice->setCapabilities(
QTouchDevice::Position | QTouchDevice::Area | QTouchDevice::Pressure |
QTouchDevice::NormalizedPosition);
QWindowSystemInterface::registerTouchDevice(mTouchDevice);
}
QMirClientInput::~QMirClientInput()
{
// Qt will take care of deleting mTouchDevice.
}
#if (LOG_EVENTS != 0)
static const char* nativeEventTypeToStr(MirEventType t)
{
switch (t)
{
case mir_event_type_key:
return "mir_event_type_key";
case mir_event_type_motion:
return "mir_event_type_motion";
case mir_event_type_surface:
return "mir_event_type_surface";
case mir_event_type_resize:
return "mir_event_type_resize";
case mir_event_type_prompt_session_state_change:
return "mir_event_type_prompt_session_state_change";
case mir_event_type_orientation:
return "mir_event_type_orientation";
case mir_event_type_close_surface:
return "mir_event_type_close_surface";
case mir_event_type_input:
return "mir_event_type_input";
default:
DLOG("Invalid event type %d", t);
return "invalid";
}
}
#endif // LOG_EVENTS != 0
void QMirClientInput::customEvent(QEvent* event)
{
DASSERT(QThread::currentThread() == thread());
QMirClientEvent* ubuntuEvent = static_cast<QMirClientEvent*>(event);
const MirEvent *nativeEvent = ubuntuEvent->nativeEvent;
if ((ubuntuEvent->window == nullptr) || (ubuntuEvent->window->window() == nullptr)) {
qWarning() << "Attempted to deliver an event to a non-existent window, ignoring.";
return;
}
// Event filtering.
long result;
if (QWindowSystemInterface::handleNativeEvent(
ubuntuEvent->window->window(), mEventFilterType,
const_cast<void *>(static_cast<const void *>(nativeEvent)), &result) == true) {
DLOG("event filtered out by native interface");
return;
}
#if (LOG_EVENTS != 0)
LOG("QMirClientInput::customEvent(type=%s)", nativeEventTypeToStr(mir_event_get_type(nativeEvent)));
#endif
// Event dispatching.
switch (mir_event_get_type(nativeEvent))
{
case mir_event_type_input:
dispatchInputEvent(ubuntuEvent->window, mir_event_get_input_event(nativeEvent));
break;
case mir_event_type_resize:
{
Q_ASSERT(ubuntuEvent->window->screen() == mIntegration->screen());
auto resizeEvent = mir_event_get_resize_event(nativeEvent);
mIntegration->screen()->handleWindowSurfaceResize(
mir_resize_event_get_width(resizeEvent),
mir_resize_event_get_height(resizeEvent));
ubuntuEvent->window->handleSurfaceResized(mir_resize_event_get_width(resizeEvent),
mir_resize_event_get_height(resizeEvent));
break;
}
case mir_event_type_surface:
{
auto surfaceEvent = mir_event_get_surface_event(nativeEvent);
if (mir_surface_event_get_attribute(surfaceEvent) == mir_surface_attrib_focus) {
const bool focused = mir_surface_event_get_attribute_value(surfaceEvent) == mir_surface_focused;
// Mir may have sent a pair of focus lost/gained events, so we need to "peek" into the queue
// so that we don't deactivate windows prematurely.
if (focused) {
mPendingFocusGainedEvents--;
ubuntuEvent->window->handleSurfaceFocused();
QWindowSystemInterface::handleWindowActivated(ubuntuEvent->window->window(), Qt::ActiveWindowFocusReason);
// NB: Since processing of system events is queued, never check qGuiApp->applicationState()
// as it might be outdated. Always call handleApplicationStateChanged() with the latest
// state regardless.
QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive);
} else if (!mPendingFocusGainedEvents) {
DLOG("[ubuntumirclient QPA] No windows have focus");
QWindowSystemInterface::handleWindowActivated(nullptr, Qt::ActiveWindowFocusReason);
QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive);
}
}
break;
}
case mir_event_type_orientation:
dispatchOrientationEvent(ubuntuEvent->window->window(), mir_event_get_orientation_event(nativeEvent));
break;
case mir_event_type_close_surface:
QWindowSystemInterface::handleCloseEvent(ubuntuEvent->window->window());
break;
default:
DLOG("unhandled event type: %d", static_cast<int>(mir_event_get_type(nativeEvent)));
}
}
void QMirClientInput::postEvent(QMirClientWindow *platformWindow, const MirEvent *event)
{
QWindow *window = platformWindow->window();
const auto eventType = mir_event_get_type(event);
if (mir_event_type_surface == eventType) {
auto surfaceEvent = mir_event_get_surface_event(event);
if (mir_surface_attrib_focus == mir_surface_event_get_attribute(surfaceEvent)) {
const bool focused = mir_surface_event_get_attribute_value(surfaceEvent) == mir_surface_focused;
if (focused) {
mPendingFocusGainedEvents++;
}
}
}
QCoreApplication::postEvent(this, new QMirClientEvent(
platformWindow, event, mEventType));
if ((window->flags().testFlag(Qt::WindowTransparentForInput)) && window->parent()) {
QCoreApplication::postEvent(this, new QMirClientEvent(
static_cast<QMirClientWindow*>(platformWindow->QPlatformWindow::parent()),
event, mEventType));
}
}
void QMirClientInput::dispatchInputEvent(QMirClientWindow *window, const MirInputEvent *ev)
{
switch (mir_input_event_get_type(ev))
{
case mir_input_event_type_key:
dispatchKeyEvent(window, ev);
break;
case mir_input_event_type_touch:
dispatchTouchEvent(window, ev);
break;
case mir_input_event_type_pointer:
dispatchPointerEvent(window, ev);
break;
default:
break;
}
}
void QMirClientInput::dispatchTouchEvent(QMirClientWindow *window, const MirInputEvent *ev)
{
const MirTouchEvent *tev = mir_input_event_get_touch_event(ev);
// FIXME(loicm) Max pressure is device specific. That one is for the Samsung Galaxy Nexus. That
// needs to be fixed as soon as the compat input lib adds query support.
const float kMaxPressure = 1.28;
const QRect kWindowGeometry = window->geometry();
QList<QWindowSystemInterface::TouchPoint> touchPoints;
// TODO: Is it worth setting the Qt::TouchPointStationary ones? Currently they are left
// as Qt::TouchPointMoved
const unsigned int kPointerCount = mir_touch_event_point_count(tev);
for (unsigned int i = 0; i < kPointerCount; ++i) {
QWindowSystemInterface::TouchPoint touchPoint;
const float kX = mir_touch_event_axis_value(tev, i, mir_touch_axis_x) + kWindowGeometry.x();
const float kY = mir_touch_event_axis_value(tev, i, mir_touch_axis_y) + kWindowGeometry.y(); // see bug lp:1346633 workaround comments elsewhere
const float kW = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_major);
const float kH = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_minor);
const float kP = mir_touch_event_axis_value(tev, i, mir_touch_axis_pressure);
touchPoint.id = mir_touch_event_id(tev, i);
touchPoint.normalPosition = QPointF(kX / kWindowGeometry.width(), kY / kWindowGeometry.height());
touchPoint.area = QRectF(kX - (kW / 2.0), kY - (kH / 2.0), kW, kH);
touchPoint.pressure = kP / kMaxPressure;
MirTouchAction touch_action = mir_touch_event_action(tev, i);
switch (touch_action)
{
case mir_touch_action_down:
mLastFocusedWindow = window;
touchPoint.state = Qt::TouchPointPressed;
break;
case mir_touch_action_up:
touchPoint.state = Qt::TouchPointReleased;
break;
case mir_touch_action_change:
default:
touchPoint.state = Qt::TouchPointMoved;
}
touchPoints.append(touchPoint);
}
ulong timestamp = mir_input_event_get_event_time(ev) / 1000000;
QWindowSystemInterface::handleTouchEvent(window->window(), timestamp,
mTouchDevice, touchPoints);
}
static uint32_t translateKeysym(uint32_t sym, char *string, size_t size)
{
Q_UNUSED(size);
string[0] = '\0';
if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F35)
return Qt::Key_F1 + (int(sym) - XKB_KEY_F1);
for (int i = 0; KeyTable[i]; i += 2) {
if (sym == KeyTable[i])
return KeyTable[i + 1];
}
string[0] = sym;
string[1] = '\0';
return toupper(sym);
}
namespace
{
Qt::KeyboardModifiers qt_modifiers_from_mir(MirInputEventModifiers modifiers)
{
Qt::KeyboardModifiers q_modifiers = Qt::NoModifier;
if (modifiers & mir_input_event_modifier_shift) {
q_modifiers |= Qt::ShiftModifier;
}
if (modifiers & mir_input_event_modifier_ctrl) {
q_modifiers |= Qt::ControlModifier;
}
if (modifiers & mir_input_event_modifier_alt) {
q_modifiers |= Qt::AltModifier;
}
if (modifiers & mir_input_event_modifier_meta) {
q_modifiers |= Qt::MetaModifier;
}
return q_modifiers;
}
}
void QMirClientInput::dispatchKeyEvent(QMirClientWindow *window, const MirInputEvent *event)
{
const MirKeyboardEvent *key_event = mir_input_event_get_keyboard_event(event);
ulong timestamp = mir_input_event_get_event_time(event) / 1000000;
xkb_keysym_t xk_sym = mir_keyboard_event_key_code(key_event);
// Key modifier and unicode index mapping.
auto modifiers = qt_modifiers_from_mir(mir_keyboard_event_modifiers(key_event));
MirKeyboardAction action = mir_keyboard_event_action(key_event);
QEvent::Type keyType = action == mir_keyboard_action_up
? QEvent::KeyRelease : QEvent::KeyPress;
if (action == mir_keyboard_action_down)
mLastFocusedWindow = window;
char s[2];
int sym = translateKeysym(xk_sym, s, sizeof(s));
QString text = QString::fromLatin1(s);
bool is_auto_rep = action == mir_keyboard_action_repeat;
QPlatformInputContext *context = QGuiApplicationPrivate::platformIntegration()->inputContext();
if (context) {
QKeyEvent qKeyEvent(keyType, sym, modifiers, text, is_auto_rep);
qKeyEvent.setTimestamp(timestamp);
if (context->filterEvent(&qKeyEvent)) {
DLOG("key event filtered out by input context");
return;
}
}
QWindowSystemInterface::handleKeyEvent(window->window(), timestamp, keyType, sym, modifiers, text, is_auto_rep);
}
namespace
{
Qt::MouseButtons extract_buttons(const MirPointerEvent *pev)
{
Qt::MouseButtons buttons = Qt::NoButton;
if (mir_pointer_event_button_state(pev, mir_pointer_button_primary))
buttons |= Qt::LeftButton;
if (mir_pointer_event_button_state(pev, mir_pointer_button_secondary))
buttons |= Qt::RightButton;
if (mir_pointer_event_button_state(pev, mir_pointer_button_tertiary))
buttons |= Qt::MiddleButton;
if (mir_pointer_event_button_state(pev, mir_pointer_button_back))
buttons |= Qt::BackButton;
if (mir_pointer_event_button_state(pev, mir_pointer_button_forward))
buttons |= Qt::ForwardButton;
return buttons;
}
}
void QMirClientInput::dispatchPointerEvent(QMirClientWindow *platformWindow, const MirInputEvent *ev)
{
auto window = platformWindow->window();
auto timestamp = mir_input_event_get_event_time(ev) / 1000000;
auto pev = mir_input_event_get_pointer_event(ev);
auto action = mir_pointer_event_action(pev);
auto localPoint = QPointF(mir_pointer_event_axis_value(pev, mir_pointer_axis_x),
mir_pointer_event_axis_value(pev, mir_pointer_axis_y));
auto modifiers = qt_modifiers_from_mir(mir_pointer_event_modifiers(pev));
switch (action) {
case mir_pointer_action_button_up:
case mir_pointer_action_button_down:
case mir_pointer_action_motion:
{
const float hDelta = mir_pointer_event_axis_value(pev, mir_pointer_axis_hscroll);
const float vDelta = mir_pointer_event_axis_value(pev, mir_pointer_axis_vscroll);
if (hDelta != 0 || vDelta != 0) {
const QPoint angleDelta = QPoint(hDelta * 15, vDelta * 15);
QWindowSystemInterface::handleWheelEvent(window, timestamp, localPoint, window->position() + localPoint,
QPoint(), angleDelta, modifiers, Qt::ScrollUpdate);
}
auto buttons = extract_buttons(pev);
QWindowSystemInterface::handleMouseEvent(window, timestamp, localPoint, window->position() + localPoint /* Should we omit global point instead? */,
buttons, modifiers);
break;
}
case mir_pointer_action_enter:
QWindowSystemInterface::handleEnterEvent(window, localPoint, window->position() + localPoint);
break;
case mir_pointer_action_leave:
QWindowSystemInterface::handleLeaveEvent(window);
break;
default:
DLOG("Unrecognized pointer event");
}
}
#if (LOG_EVENTS != 0)
static const char* nativeOrientationDirectionToStr(MirOrientation orientation)
{
switch (orientation) {
case mir_orientation_normal:
return "Normal";
break;
case mir_orientation_left:
return "Left";
break;
case mir_orientation_inverted:
return "Inverted";
break;
case mir_orientation_right:
return "Right";
break;
default:
return "INVALID!";
}
}
#endif
void QMirClientInput::dispatchOrientationEvent(QWindow *window, const MirOrientationEvent *event)
{
MirOrientation mir_orientation = mir_orientation_event_get_direction(event);
#if (LOG_EVENTS != 0)
// Orientation event logging.
LOG("ORIENTATION direction: %s", nativeOrientationDirectionToStr(mir_orientation));
#endif
if (!window->screen()) {
DLOG("Window has no associated screen, dropping orientation event");
return;
}
OrientationChangeEvent::Orientation orientation;
switch (mir_orientation) {
case mir_orientation_normal:
orientation = OrientationChangeEvent::TopUp;
break;
case mir_orientation_left:
orientation = OrientationChangeEvent::LeftUp;
break;
case mir_orientation_inverted:
orientation = OrientationChangeEvent::TopDown;
break;
case mir_orientation_right:
orientation = OrientationChangeEvent::RightUp;
break;
default:
DLOG("No such orientation %d", mir_orientation);
return;
}
// Dispatch orientation event to [Platform]Screen, as that is where Qt reads it. Screen will handle
// notifying Qt of the actual orientation change - done to prevent multiple Windows each creating
// an identical orientation change event and passing it directly to Qt.
// [Platform]Screen can also factor in the native orientation.
QCoreApplication::postEvent(static_cast<QMirClientScreen*>(window->screen()->handle()),
new OrientationChangeEvent(OrientationChangeEvent::mType, orientation));
}
| 38.87069 | 155 | 0.664937 | [
"geometry"
] |
ade0be264fcad933025807fa30f6b772dc6a3b80 | 4,937 | hpp | C++ | third-party/casadi/casadi/interfaces/hsl/ma27_interface.hpp | dbdxnuliba/mit-biomimetics_Cheetah | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 8 | 2020-02-18T09:07:48.000Z | 2021-12-25T05:40:02.000Z | third-party/casadi/casadi/interfaces/hsl/ma27_interface.hpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | null | null | null | third-party/casadi/casadi/interfaces/hsl/ma27_interface.hpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 13 | 2019-08-25T12:32:06.000Z | 2022-03-31T02:38:12.000Z | /*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi 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 3 of the License, or (at your option) any later version.
*
* CasADi 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 CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CASADI_MA27_INTERFACE_HPP
#define CASADI_MA27_INTERFACE_HPP
#include "casadi/core/linsol_internal.hpp"
#include <casadi/interfaces/hsl/casadi_linsol_ma27_export.h>
extern "C" {
void ma27id_(int* ICNTL, double* CNTL);
void ma27ad_(int *N, int *NZ, const int *IRN, const int* ICN,
int *IW, int* LIW, int* IKEEP, int *IW1,
int* NSTEPS, int* IFLAG, int* ICNTL,
double* CNTL, int *INFO, double* OPS);
void ma27bd_(int *N, int *NZ, const int *IRN, const int* ICN,
double* A, int* LA, int* IW, int* LIW,
int* IKEEP, int* NSTEPS, int* MAXFRT,
int* IW1, int* ICNTL, double* CNTL,
int* INFO);
void ma27cd_(int *N, double* A, int* LA, int* IW,
int* LIW, double* W, int* MAXFRT,
double* RHS, int* IW1, int* NSTEPS,
int* ICNTL, double* CNTL);
}
/** \defgroup plugin_Linsol_ma27
* Interface to the sparse direct linear solver MA27
* Works for symmetric indefinite systems
* Partly adopted from qpOASES 3.2
* \author Joel Andersson
* \date 2016
*/
/** \pluginsection{Linsol,ma27} */
/// \cond INTERNAL
namespace casadi {
struct CASADI_LINSOL_MA27_EXPORT Ma27Memory : public LinsolMemory {
// Constructor
Ma27Memory();
// Destructor
~Ma27Memory();
/* Work vector for MA27AD */
std::vector<int> iw1;
/* Number of nonzeros in the current linear system. */
int nnz;
/* matrix/factor for MA27 (A in MA27) */
std::vector<double> nz;
/* Row entries of matrix (IRN in MA27) */
std::vector<int> irn;
/* Column entries of matrix (JCN in MA27) */
std::vector<int> jcn;
/* integer control values (ICNRL in MA27) */
int icntl[30];
/* real control values (CNRL in MA27) */
double cntl[5];
/* integer work space (IW in MA27) */
std::vector<int> iw;
/* Real work space (W in MA27CD) */
std::vector<double> w;
/* IKEEP in MA27 */
std::vector<int> ikeep;
/* NSTEPS in MA27 */
int nsteps;
/* MAXFRT in MA27 */
int maxfrt;
/* number of negative eigenvalues */
int neig;
// Rank of matrix
int rank;
};
/** \brief \pluginbrief{Linsol,ma27}
* @copydoc Linsol_doc
* @copydoc plugin_Linsol_ma27
*/
class CASADI_LINSOL_MA27_EXPORT Ma27Interface : public LinsolInternal {
public:
// Create a linear solver given a sparsity pattern and a number of right hand sides
Ma27Interface(const std::string& name, const Sparsity& sp);
/** \brief Create a new Linsol */
static LinsolInternal* creator(const std::string& name, const Sparsity& sp) {
return new Ma27Interface(name, sp);
}
// Destructor
~Ma27Interface() override;
// Initialize the solver
void init(const Dict& opts) override;
/** \brief Create memory block */
void* alloc_mem() const override { return new Ma27Memory();}
/** \brief Initalize memory block */
int init_mem(void* mem) const override;
/** \brief Free memory block */
void free_mem(void *mem) const override { delete static_cast<Ma27Memory*>(mem);}
// Factorize the linear system
int nfact(void* mem, const double* A) const override;
/// Number of negative eigenvalues
casadi_int neig(void* mem, const double* A) const override;
/// Matrix rank
casadi_int rank(void* mem, const double* A) const override;
// Solve the linear system
int solve(void* mem, const double* A, double* x, casadi_int nrhs, bool tr) const override;
/// A documentation string
static const std::string meta_doc;
// Get name of the plugin
const char* plugin_name() const override { return "ma27";}
// Get name of the class
std::string class_name() const override { return "Ma27Interface";}
};
} // namespace casadi
/// \endcond
#endif // CASADI_MA27_INTERFACE_HPP
| 29.562874 | 94 | 0.644724 | [
"vector"
] |
adfdc494c17181c5c9eb3f2adce2c82bb2481cfd | 68,902 | cpp | C++ | src/WorkloadThread.cpp | Hitachi-Data-Systems/ivy | 07a77c271cad7f682d7fbff497bf74a76ecd5378 | [
"Apache-2.0"
] | 6 | 2016-09-12T16:23:53.000Z | 2021-12-16T23:08:34.000Z | src/WorkloadThread.cpp | Hitachi-Data-Systems/ivy | 07a77c271cad7f682d7fbff497bf74a76ecd5378 | [
"Apache-2.0"
] | null | null | null | src/WorkloadThread.cpp | Hitachi-Data-Systems/ivy | 07a77c271cad7f682d7fbff497bf74a76ecd5378 | [
"Apache-2.0"
] | null | null | null | //Copyright (c) 2016, 2017, 2018 Hitachi Vantara Corporation
//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.
//
//Authors: Allart Ian Vogelesang <ian.vogelesang@hitachivantara.com>
//
//Support: "ivy" is not officially supported by Hitachi Vantara.
// Contact one of the authors by email and as time permits, we'll help on a best efforts basis.
#include "ivytypes.h"
#include "ivyhelpers.h"
#include "ivytime.h"
#include "ivydriver.h"
#include "RunningStat.h"
extern bool routine_logging;
pid_t get_subthread_pid()
{
return syscall(SYS_gettid);
}
std::ostream& operator<< (std::ostream& o, const ThreadState& s)
{
switch (s)
{
case ThreadState::undefined:
o << "ThreadState::undefined";
break;
case ThreadState::initial:
o << "ThreadState::initial";
break;
case ThreadState::waiting_for_command:
o << "ThreadState::waiting_for_command";
break;
case ThreadState::running:
o << "ThreadState::running";
break;
case ThreadState::died:
o << "ThreadState::died";
break;
case ThreadState::exited_normally:
o << "ThreadState::exited_normally";
break;
default:
o << "<internal programming error - unknown ThreadState value cast to int as " << ((int) s) << ">";
}
return o;
}
std::ostream& operator<< (std::ostream& o, const cqe_type& ct)
{
switch (ct)
{
case cqe_type::eyeo:
o << "cqe_type::eyeo";
break;
case cqe_type::timeout:
o << "cqe_type::timeout";
break;
default:
o << "<internal programming error - unknown cqe_type value cast to int as " << ((int) ct) << ">";
}
return o;
}
std::ostream& operator<<(std::ostream& o, const struct cqe_shim& s)
{
o << "{ \"struct cqe_shim\" : { ";
o << "\"this\" : \"" << &s << "\"";
o << "\", type\" : \"" << s.type << "\"";
struct timespec ts;
switch (s.type)
{
case cqe_type::timeout:
o << ", \"wait_until_this_time\" : \"" << s.wait_until_this_time.format_as_datetime_with_ns() << "\"";
ts.tv_sec = s.kts.tv_sec;
ts.tv_nsec = s.kts.tv_nsec;
o << ", \"duration\" : \"" << ivytime(ts).format_as_duration_HMMSSns() << "\"";
o << ", \"when_inserted\" : \"" << s.when_inserted.format_as_datetime_with_ns() << "\"";
break;
default: ;
}
o << " } }";
return o;
}
struct cqe_shim* timeout_shims::insert_timeout(const ivytime& then, const ivytime& now)
{
if (then.isZero() || now.isZero() || then <= now)
{
std::ostringstream o;
o << "<Error> timeout_shims::insert_timeout(const ivytime& then = " << then.format_as_datetime_with_ns()
<< ", const ivytime& now = " << now.format_as_datetime_with_ns() << ")"
<< " - Neither \"then\" nor \"now\" may be zero, and \"then\" must be after \"now\".";
throw std::runtime_error(o.str());
}
struct cqe_shim* p_shim = new struct cqe_shim;
if (p_shim == nullptr) {throw std::runtime_error("<Error> internal programming error - timeout_shims::insert_timeout() - failed getting memory for cqe_shim.");}
p_shim->type = cqe_type::timeout;
p_shim->wait_until_this_time = then;
p_shim->when_inserted = now;
unexpired_shims.insert(p_shim);
return p_shim;
}
ivytime timeout_shims::earliest_timeout()
{
ivytime earliest {0};
for ( cqe_shim* p_shim : unexpired_shims )
{
if (earliest.isZero() || p_shim->wait_until_this_time < earliest) { earliest = p_shim->wait_until_this_time; }
}
if ( (!unsubmitted_timeout.isZero()) && (earliest.isZero() || unsubmitted_timeout < earliest)) { earliest = unsubmitted_timeout; }
return earliest;
}
void timeout_shims::delete_shim(struct cqe_shim* p_shim)
{
auto it = unexpired_shims.find(p_shim);
if (it == unexpired_shims.end()) throw std::runtime_error ("failed in timeout_shims::delete_shim() - shim not found in unexpired_time_shims.");
unexpired_shims.erase(it);
delete p_shim;
return;
}
WorkloadThread::WorkloadThread(std::mutex* p_imm, unsigned int pc, unsigned int h)
: p_ivydriver_main_mutex(p_imm), physical_core(pc), hyperthread(h) {}
std::string threadStateToString (const ThreadState ts)
{
std::ostringstream o;
o << ts;
return o.str();
}
std::string mainThreadCommandToString(MainThreadCommand mtc)
{
switch (mtc)
{
case MainThreadCommand::start: return "MainThreadCommand::start";
case MainThreadCommand::keep_going: return "MainThreadCommand::keep_going";
case MainThreadCommand::stop: return "MainThreadCommand::stop";
case MainThreadCommand::die: return "MainThreadCommand::die";
default:
{
std::ostringstream o;
o << "mainThreadCommandToString (MainThreadCommand = (decimal) " << ((int) mtc) << ") - internal programming error - invalid MainThreadCommand value." ;
return o.str();
}
}
}
void WorkloadThread::WorkloadThreadRun()
{
if (routine_logging)
{
std::ostringstream o;
o<< "WorkloadThreadRun() fireup for physical core " << physical_core << " hyperthread " << hyperthread << "." << std::endl;
log(slavethreadlogfile,o.str());
}
my_pid = getpid();
my_tid = get_subthread_pid();
my_pgid = getpgid(my_tid);
if (routine_logging)
{
std::ostringstream o;
o << "getpid() = " << my_pid << ", gettid() = " << my_tid << ", getpgid(my_tid=" << my_tid << ") = " << my_pgid << std::endl;
log(slavethreadlogfile,o.str());
}
// The workload thread is initially in "waiting for command" state.
//
// In the outer "waiting for command" loop we wait indefinitely for
// ivydriver to set "ivydriver_main_posted_command" to the value true.
//
// Before turning on the "ivydriver_main_posted_command" flag and notifying,
// ivydriver sets the actual command value into a MainThreadCommand enum class
// variable called "ivydriver_main_says".
//
// The MainThreadCommand enum class has four values, "start", "keep_going", "stop", and "die".
//
// When the workload thread wakes up and sees that ivydriver_main_posted_command == true, we first turn it off for next time.
//
// In this outer loop, there are only two commands that are recognized
// "die" (nicely), and "start" the first subinterval running.
//
// When we get the "start" command, first we (re) initialize stuff
// and then we start the first subinterval running.
//
// At the end of every running subinterval, we need to switch over to the
// next one pretty much instantly.
//
// When a running subinterval ends, we look for up to 15 ms
// to see either the command "keep_running", "stop", or "die".
//
// "stop" means :
// You just finished the last subinterval.
// Don't run another subinterval.
// Do wrap up activities, possibly write log records,
// and then loop back to the top of the outer "waiting for command" loop.
//
// "keep_running" means :
// Mark this subinterval as "ready to send"
// Switch over to the other subinterval, which must already be marked "ready_to_run".
// Loop back to the top of the inner running subinterval loop.
wait_for_command: // the "stop" command finishes by "goto wait_for_command". This to make the code easy to read compared to break statements in nested loops.
state = ThreadState::waiting_for_command;
slaveThreadConditionVariable.notify_all(); // ivydriver waits for the thread to be in waiting for command state.
while (true) // loop that waits for "run" commands
{
// indent level in loop waiting for run commands
{
// runs with lock held
std::unique_lock<std::mutex> wkld_lk(slaveThreadMutex);
while (!ivydriver_main_posted_command) slaveThreadConditionVariable.wait(wkld_lk);
if (routine_logging) log(slavethreadlogfile,std::string("Received command from host - ") + mainThreadCommandToString(ivydriver_main_says));
ivydriver_main_posted_command=false;
if (reported_error && ivydriver_main_says != MainThreadCommand::die)
{
std::ostringstream o;
o << "ignoring command \"" << mainThreadCommandToString(ivydriver_main_says) << "\" from ivydriver main thread "
<< "because I prevously reported an error. Exiting instead.";
post_error(o.str());
state=ThreadState::died;
wkld_lk.unlock();
slaveThreadConditionVariable.notify_all();
return;
}
switch (ivydriver_main_says)
{
case MainThreadCommand::die :
{
if (routine_logging) log (slavethreadlogfile,std::string("WorkloadThread dutifully dying upon command.\n"));
if (reported_error) { state=ThreadState::died; }
else { state=ThreadState::exited_normally; }
wkld_lk.unlock();
slaveThreadConditionVariable.notify_all();
return;
}
case MainThreadCommand::start :
{
break;
}
default:
{
post_error("in main loop waiting for commands but didn\'t get \"start\" or \"die\" when expected."s
+ " Instead got "s + mainThreadCommandToString(ivydriver_main_says) + " WorkloadThread exiting."s);
state=ThreadState::died;
wkld_lk.unlock();
slaveThreadConditionVariable.notify_all();
return;
}
}
} // lock released
// "start" command received.
number_of_concurrent_timeouts.clear();
slaveThreadConditionVariable.notify_all();
thread_view_subinterval_number = -1;
//*debug*/ { std::ostringstream o; o << "b4 build uring" << std::endl; log(slavethreadlogfile,o.str());}
build_uring_and_allocate_and_mmap_Eyeo_buffers_and_build_Eyeos();
//*debug*/ { std::ostringstream o; o << "after build uring" << std::endl; log(slavethreadlogfile,o.str());}
step_run_time_seconds = 0.0;
for (auto& pTestLUN : pTestLUNs)
{
try
{
pTestLUN->testLUN_furthest_behind_weighted_IOPS_max_skew_progress = 0.0;
for (auto& pear: pTestLUN->workloads)
{
//*debug*/pear.second.io_return_code_counts.clear();
pear.second.iops_max_io_count = 0;
pear.second.currentSubintervalIndex=0;
pear.second.otherSubintervalIndex=1;
pear.second.subinterval_number=0;
pear.second.prepare_to_run();
//pear.second.build_Eyeos();
pear.second.workload_cumulative_launch_count = 0;
pear.second.workload_weighted_IOPS_max_skew_progress = 0.0;
if (pear.second.dedupe_target_spread_regulator != nullptr) { delete pear.second.dedupe_target_spread_regulator; }
if (pear.second.p_current_IosequencerInput->dedupe > 1.0 && pear.second.p_current_IosequencerInput->fractionRead != 1.0 && pear.second.p_current_IosequencerInput->dedupe_type == dedupe_method::target_spread)
{
pear.second.dedupe_target_spread_regulator = new DedupeTargetSpreadRegulator(pear.second.subinterval_array[0].input.dedupe, pear.second.pattern_seed);
if (pear.second.p_my_iosequencer->isRandom())
{
if (pear.second.dedupe_target_spread_regulator->decide_reuse())
{
std::pair<uint64_t, uint64_t> align_pattern;
align_pattern = pear.second.dedupe_target_spread_regulator->reuse_seed();
pear.second.pattern_seed = align_pattern.first;
pear.second.pattern_alignment = align_pattern.second;
pear.second.pattern_number = pear.second.pattern_alignment;
} else
{
pear.second.pattern_seed = pear.second.dedupe_target_spread_regulator->random_seed();
}
}
}
//log(slavethreadlogfile, pear.second.dedupe_regulator->logmsg());
if (pear.second.dedupe_constant_ratio_regulator != nullptr) { delete pear.second.dedupe_constant_ratio_regulator; pear.second.dedupe_constant_ratio_regulator = nullptr;}
if (pear.second.p_current_IosequencerInput->dedupe > 1.0 && pear.second.p_current_IosequencerInput->fractionRead != 1.0 &&
pear.second.p_current_IosequencerInput->dedupe_type == dedupe_method::constant_ratio)
{
pear.second.dedupe_constant_ratio_regulator = new DedupeConstantRatioRegulator(pear.second.p_current_IosequencerInput->dedupe,
pear.second.p_current_IosequencerInput->blocksize_bytes,
pear.second.p_current_IosequencerInput->fraction_zero_pattern,
pear.second.uint64_t_hash_of_host_plus_LUN);
}
if (pear.second.dedupe_round_robin_regulator != nullptr) { delete pear.second.dedupe_round_robin_regulator; pear.second.dedupe_round_robin_regulator = nullptr;}
if (pear.second.p_current_IosequencerInput->dedupe > 1.0 && pear.second.p_current_IosequencerInput->fractionRead != 1.0 &&
pear.second.p_current_IosequencerInput->dedupe_type == dedupe_method::round_robin)
{
pear.second.dedupe_round_robin_regulator = new DedupeRoundRobinRegulator(
pear.second, // Workload
pear.second.p_my_iosequencer->numberOfCoverageBlocks,
pear.second.p_current_IosequencerInput->blocksize_bytes,
pear.second.p_current_IosequencerInput->dedupe,
pear.second.p_current_IosequencerInput->dedupe_unit_bytes,
pear.second.p_my_iosequencer->pLUN);
}
}
}
catch (std::exception& e)
{
std::ostringstream o;
o << "failed preparing TestLUNs and Workloads to start running - "
<< e.what() << "." << std::endl;
log(slavethreadlogfile, o.str());
post_error(o.str());
goto wait_for_command;
}
}
//*debug*/ { std::ostringstream o; o << "aye" << std::endl; log(slavethreadlogfile,o.str());}
dispatching_latency_seconds.clear();
lock_aquisition_latency_seconds.clear();
switchover_completion_latency_seconds.clear();
set_all_queue_depths_to_zero();
number_of_IO_errors = 0;
// prefill precompute queues
for (TestLUN* pTestLUN : pTestLUNs)
{
for (auto& pear : pTestLUN->workloads)
{
{
Workload& w = pear.second;
unsigned int number_generated;
do { number_generated = w.generate_IOs(); }
while (number_generated > 0);
}
}
}
if (routine_logging)
{
std::ostringstream o;
o << "Thread for physical core " << physical_core << " hyperthread " << hyperthread << std::endl;
log(slavethreadlogfile,o.str());
}
//*debug*/ { std::ostringstream o; o << "eye" << std::endl; log(slavethreadlogfile,o.str());}
for (auto& pTestLUN : pTestLUNs)
{
try { pTestLUN->prepare_linux_AIO_driver_to_start(); }
catch (std::exception& e)
{
std::ostringstream o;
o << "failed running prepare_linux_AIO_driver_to_start() for " << pTestLUN->host_plus_lun << " - "
<< e.what() << "." << std::endl;
post_error(o.str());
goto wait_for_command;
}
}
state=ThreadState::running;
//*debug*/ { std::ostringstream o; o << "bye" << std::endl; log(slavethreadlogfile,o.str());}
if (routine_logging) { log(slavethreadlogfile,"Finished initialization and now about to start running subintervals."); }
// indent level in loop waiting for run commands
while (true) // inner loop running subintervals, until we are told "stop" or "die"
{
// indent level in loop running subintervals
thread_view_subinterval_number++;
if (thread_view_subinterval_number == 0)
{
thread_view_subinterval_start = ivydriver.test_start_time;
}
else
{
thread_view_subinterval_start = thread_view_subinterval_end;
}
thread_view_subinterval_end = thread_view_subinterval_start + ivydriver.subinterval_duration;
if (routine_logging){
std::ostringstream o;
o << "Physical core " << physical_core << " hyperthread " << hyperthread << ": Top of subinterval " << thread_view_subinterval_number
<< " " << thread_view_subinterval_start.format_as_datetime_with_ns()
<< " to " << thread_view_subinterval_end.format_as_datetime_with_ns()
<< " with subinterval_duration = " << ivydriver.subinterval_duration.format_as_duration_HMMSSns()
<< std::endl;
log(slavethreadlogfile,o.str());
}
// // This nested loop to set hot zone parameters.
// for (auto& pTestLUN : pTestLUNs)
// {
// for (auto& peach : pTestLUN->workloads)
// {
// {
// Workload& wrkld = peach.second;
//
// if (wrkld.p_current_IosequencerInput->hot_zone_size_bytes > 0)
// {
// if (wrkld.p_my_iosequencer->instanceType() == "random_steady"
// || wrkld.p_my_iosequencer->instanceType() == "random_independent")
// {
// IosequencerRandom* p = (IosequencerRandom*) wrkld.p_my_iosequencer;
// if (!p->set_hot_zone_parameters(wrkld.p_current_IosequencerInput))
// {
// std::ostringstream o;
// o << " - working on WorkloadID " << wrkld.workloadID.workloadID
// << " - call to IosequencerRandom::set_hot_zone_parameters(() failed.\n";
// post_error(o.str());
// goto wait_for_command;
// }
// }
// }
// }
// }
// }
try
{
run_subinterval();
}
catch (std::exception& e)
{
std::ostringstream o;
o << "failed running run_subinterval() - "
<< e.what() << "." << std::endl;
post_error(o.str());
goto wait_for_command;
}
// end of subinterval, flip over to other subinterval or stop
// First record the dispatching latency,
// the time from when the clock clicked over to a new subinterval
// to the time that the WorkloadThread code starts running.
//*debug*/ { std::ostringstream o; o << "back in WorkloadThreadRun() after running subinterval." << std::endl; log(slavethreadlogfile,o.str());}
ivytime before_getting_lock, dispatch_time;
before_getting_lock.setToNow();
if ( pTestLUNs.size() == 0)
{
dispatching_latency_seconds.push(0.0);
}
else
{
switchover_begin = ivydriver.ivydriver_view_subinterval_end;
dispatch_time = before_getting_lock - ivydriver.ivydriver_view_subinterval_end;
dispatching_latency_seconds.push(dispatch_time.getlongdoubleseconds());
}
if (routine_logging)
{
std::ostringstream o;
o << "Physical core " << physical_core << " hyperthread " << hyperthread << ": Bottom of subinterval " << thread_view_subinterval_number
<< " " << thread_view_subinterval_start.format_as_datetime_with_ns()
<< " to " << thread_view_subinterval_end.format_as_datetime_with_ns() << std::endl;
//*debug*/for (auto& pTestLUN:pTestLUNs){for (auto& pear : pTestLUN->workloads) {Workload& w = pear.second; for (auto& q : w.io_return_code_counts ){ o << w.workloadID << "I/O return code " << q.first << " occurred " << q.second.c << " times."<< std::endl;}}}
log(slavethreadlogfile,o.str());
}
// indent level in loop waiting for run commands
// indent level in loop running subintervals
{
// start of locked section at subinterval switchover
std::unique_lock<std::mutex> wkld_lk(slaveThreadMutex);
//*debug*/ { std::ostringstream o; o << "Got lock to look at command which is " << mainThreadCommandToString(ivydriver_main_says) << "." << std::endl; log(slavethreadlogfile,o.str()); }
ivytime got_lock_time; got_lock_time.setToNow();
ivytime lock_aquire_time = got_lock_time - before_getting_lock;
lock_aquisition_latency_seconds.push(lock_aquire_time.getlongdoubleseconds());
ivydriver_main_posted_command=false; // for next time
if (ivydriver.track_long_running_IOs) { check_for_long_running_IOs(); }
// we still have the lock
if (MainThreadCommand::die == ivydriver_main_says)
{
if (routine_logging) log(slavethreadlogfile,"WorkloadThread dutifully dying upon command.\n");
state=ThreadState::exited_normally;
wkld_lk.unlock();
slaveThreadConditionVariable.notify_all();
return;
}
// we still have the lock during subinterval switchover
for (auto& pTestLUN : pTestLUNs)
{
for (auto& peach : pTestLUN->workloads)
{
try
{
peach.second.switchover();
}
catch (std::exception& e)
{
std::ostringstream o;
o << "failed switcover to next subinterval for " << pTestLUN->host_plus_lun <<" - "
<< e.what() << "." << std::endl;
post_error(o.str());
goto wait_for_command;
}
}
}
// indent level in loop waiting for run commands
// indent level in loop running subintervals
// indent level in locked section at subinterval switchover
if (routine_logging)
{
std::ostringstream o;
o << std::endl;
for (auto& pTestLUN : pTestLUNs)
{
for (auto& peach : pTestLUN->workloads)
{
{
const Workload& w = peach.second;
unsigned min_required_IOs = w.precomputedepth() + w.subinterval_array[0].input.maxTags;
unsigned max_used_Eyeos = w.eyeo_build_qty() - w.min_freeStack_level;
o << w.workloadID
<< " min_required_IOs = ( precomputedepth() + maxTags ) = " << min_required_IOs
<< ", max_used_Eyeos = " << max_used_Eyeos
<< ", max_design_spare_Eyeos_used = "; if (max_used_Eyeos > min_required_IOs) { o << (max_used_Eyeos > min_required_IOs); } else { o << "<none>"; }
o << ", min_freeStack_level = " << w.min_freeStack_level
<< ", eyeo_build_qty() = " << w.eyeo_build_qty()
<< ", precompute_depth() = " << w.precomputedepth()
<< ", maxTags = " << w.subinterval_array[0].input.maxTags
<< "." << std::endl;
}
}
}
log(slavethreadlogfile, o.str());
}
if (MainThreadCommand::stop == ivydriver_main_says)
{
if (routine_logging) log(slavethreadlogfile,std::string("WorkloadThread stopping at end of subinterval.\n"));
catch_in_flight_IOs_after_last_subinterval();
if (routine_logging)
{
{
std::ostringstream o;
o << "Subinterval count = " << dispatching_latency_seconds.count() << std::endl
<< "OS dispatching latency after subinterval end, seconds: "
<< " avg = " << dispatching_latency_seconds.avg()
<< " / min = " << dispatching_latency_seconds.min()
<< " / max = " << dispatching_latency_seconds.max()
<< std::endl
<< "lock acquisition latency: "
<< " avg = " << lock_aquisition_latency_seconds.avg()
<< " / min = " << lock_aquisition_latency_seconds.min()
<< " / max = " << lock_aquisition_latency_seconds.max()
<< std::endl
<< "complete switchover latency: "
<< " avg = " << switchover_completion_latency_seconds.avg()
<< " / min = " << switchover_completion_latency_seconds.min()
<< " / max = " << switchover_completion_latency_seconds.max()
<< std::endl;
log(slavethreadlogfile,o.str());
}
{
std::ostringstream o;
o << "workload_thread_max_queue_depth = " << workload_thread_max_queue_depth << std::endl;
for (auto& pTestLUN : pTestLUNs)
{
o << "For TestLUN" << pTestLUN->host_plus_lun << " : " << std::endl;
for (auto& pear : pTestLUN->workloads)
{
o << "For Workload" << pear.first << " : "
<< "workload_max_queue_depth = " << pear.second.workload_max_queue_depth << std::endl;
}
}
log(slavethreadlogfile,o.str());
}
log_io_uring_engine_stats();
}
if (routine_logging && !ivydriver.spinloop)
{
std::ostringstream o;
o << "number_of_concurrent_timeouts: "
<< "count() = " << number_of_concurrent_timeouts.count()
<< ", avg() = " << number_of_concurrent_timeouts.avg()
<< ", max() = " << number_of_concurrent_timeouts.max()
<< ".";
log(slavethreadlogfile,o.str());
}
//*debug*/{std::ostringstream o; o << "about to shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos()."; log(slavethreadlogfile,o.str());}
shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos();
//*debug*/{std::ostringstream o; o << "about to turn off ivydriver_main_posted_command, go into waiting_for_command state, unlock, notify all ..."; log(slavethreadlogfile,o.str());}
ivydriver_main_posted_command = false;
state=ThreadState::waiting_for_command;
wkld_lk.unlock();
slaveThreadConditionVariable.notify_all();
goto wait_for_command;
// end of processing "stop" command
}
// indent level in loop waiting for run commands
// indent level in loop running subintervals
// indent level in locked section at subinterval switchover
if (MainThreadCommand::keep_going != ivydriver_main_says)
{
std::ostringstream o; o << " WorkloadThread only expects \"stop\" or \"keep_going\" commands at end of subinterval. Received "
<< mainThreadCommandToString(ivydriver_main_says) << ".\n";
wkld_lk.unlock();
post_error(o.str());
goto wait_for_command;
}
//*debug*/{std::ostringstream o; o << "processing keep_going command."; log(slavethreadlogfile,o.str());}
// MainThreadCommand::keep_going
for (auto& pTestLUN : pTestLUNs)
{
for (auto& pear : pTestLUN->workloads)
{
Workload* pWorkload = & pear.second;
if ( pWorkload->subinterval_array[pWorkload->currentSubintervalIndex].subinterval_status != subinterval_state::ready_to_run )
{
std::ostringstream o; o << "WorkloadThread told to keep going, but next subinterval not marked READY_TO_RUN"
<< " for workload " << pWorkload->workloadID.workloadID
<< " Master host late to post command, or has stopped. Try increasing subinterval_seconds." << std::endl;
wkld_lk.unlock();
post_error(o.str());
goto wait_for_command;
}
pWorkload->p_current_subinterval->subinterval_status = subinterval_state::running;
// end of locked section
}
}
}
// indent level in loop waiting for run commands
// indent level in loop running subintervals
// indent level in locked section at subinterval switchover
ivytime switchover_complete;
switchover_complete.setToNow();
switchover_completion_latency_seconds.push(ivytime(switchover_complete-switchover_begin).getlongdoubleseconds());
slaveThreadConditionVariable.notify_all();
//*debug*/{std::ostringstream o; o << "switchover complete."; log(slavethreadlogfile,o.str());}
}
}
}
void WorkloadThread::run_subinterval()
{
//*debug*/short_submit_counter_map.clear(); dropped_ocurrences_map.clear();
ivytime now; now.setToNow();
if (routine_logging)
{
std::ostringstream o;
now = now - thread_view_subinterval_end;
o << "WorkloadThread::run_subinterval() running subinterval which will end at "
<< thread_view_subinterval_end.format_as_datetime_with_ns()
<< " - " << (thread_view_subinterval_end-now).format_as_duration_HMMSSns() << " from now " << std::endl;
log(slavethreadlogfile,o.str());
}
try_generating_IOs = true;
// The idea here is that if there's no new information since last time
// and last time there wasn't anything to do, and more than 1/2 second
// has passed, well then there's still nothing to do.
// The one half second is in case there is room in the precompute queue,
// but the most recently generated was for a time too far into the future.
// Called PRECOMPUTE_HORIZON_SECONDS, set at time of writing this to 0.5 seconds
ivytime too_far_in_the_future (PRECOMPUTE_HORIZON_SECONDS/2.0);
// that were coming for very low I/O rate workloads.
consecutive_fruitless_passes = 0;
//*debug*/unsigned torque = 0;
while (true)
{
cumulative_loop_passes ++;
//*debug*/if (++torque == 100) { std::ostringstream o; o << " %%%%%%%%%%%%%% 100th pass %%%%%%%%%%%%%%%%%%"; log(slavethreadlogfile,o.str()); }
//*debug*/if (cumulative_loop_passes % 10000 == 0) { std::ostringstream o; o << " ||||||||||||||============== cumulative_loop_passes = " << cumulative_loop_passes << "."; log(slavethreadlogfile,o.str()); }
did_something_this_pass = false;
have_failed_to_get_an_sqe = false;
now.setToNow();
// first we harvest any pending completion events - doesn't use any system calls.
struct io_uring_cqe* p_cqe {nullptr};
unsigned total_cqes_reaped_this_pass = 0;
unsigned cqe_harvest_count = 0;
do
{
cqe_harvest_count = io_uring_peek_batch_cqe(&struct_io_uring, cqe_pointer_array, cqes_with_one_peek_limit);
total_cqes_reaped_this_pass += cqe_harvest_count;
cumulative_cqes += cqe_harvest_count;
workload_thread_queue_depth -= cqe_harvest_count;
if (cqe_harvest_count > 0)
{
if (cqe_harvest_count > max_cqes_reaped_at_once) { max_cqes_reaped_at_once = cqe_harvest_count; }
for (size_t i = 0; i < cqe_harvest_count; i++)
{
p_cqe = cqe_pointer_array[i];
process_cqe(p_cqe, now);
}
io_uring_cq_advance(&struct_io_uring,cqe_harvest_count);
}
} while (cqe_harvest_count == cqes_with_one_peek_limit);
if ( total_cqes_reaped_this_pass > 0 ) { did_something_this_pass = true; }
if ( now >= thread_view_subinterval_end ) { break; }
if ( (!ivydriver.spinloop)
&& (!unexpired_timeouts.unsubmitted_timeout.isZero()) ) { did_something_this_pass = true; try_to_submit_unsubmitted_timeout(now); }
if ( !have_failed_to_get_an_sqe ) { populate_sqes(); }
if ( !did_something_this_pass ) { generate_IOs(); }
if ( (!ivydriver.spinloop) && (!did_something_this_pass) ) { possibly_insert_timeout(now); }
bool fruitless_pass = (!did_something_this_pass) && (!ivydriver.spinloop) && sqes_queued_for_submit == 0;
if (fruitless_pass) { consecutive_fruitless_passes++; cumulative_fruitless_passes++; }
else { consecutive_fruitless_passes = 0; }
int submitted = 0;
if ( sqes_queued_for_submit > 0 )
{
// we already knew it wasn't a fruitless pass, but now we know there are sqes to submit
if ( max_sqes_tried_to_submit_at_once < sqes_queued_for_submit ) { max_sqes_tried_to_submit_at_once = sqes_queued_for_submit; }
submitted = io_uring_submit(&struct_io_uring); cumulative_submits++;
if (submitted < 0)
{
std::ostringstream o;
o << "io_uring_submit(&struct_io_uring) with sqes_queued_for_submit = " << sqes_queued_for_submit
<< " failed return code " << submitted << " (" << std::strerror(-submitted) << ")." << std::endl;
post_error(o.str());
}
if ( ((unsigned int) submitted) > max_sqes_submitted_at_once ) { max_sqes_submitted_at_once = ((unsigned int) submitted); }
///*debug*/ int short_submit = ((int) sqes_queued_for_submit) - submitted;
///*debug*/
///*debug*/ short_submit_counter_map[short_submit].c++;
///*debug*/
///*debug*/ unsigned dropped = *(struct_io_uring.sq.kdropped);
///*debug*/
///*debug*/ dropped_ocurrences_map[dropped].c++;
sqes_queued_for_submit -= (unsigned) submitted;
}
else // There are no sqes queued for submit
{
if (consecutive_fruitless_passes > ivydriver.fruitless_passes_before_wait)
{
/*debug*/if (workload_thread_queue_depth == 0) {throw std::runtime_error("Wait with zero queue depth.");}
submitted = io_uring_submit_and_wait(&struct_io_uring,1); cumulative_waits++;
if (submitted < 0)
{
std::ostringstream o;
o << "io_uring_submit_and_wait(&struct_io_uring,1) with sqes_queued_for_submit = " << sqes_queued_for_submit
<< " failed return code " << submitted << " (" << std::strerror(-submitted) << ")." << std::endl;
post_error(o.str());
}
else
{
// /*debug*/ int short_submit = ((int) sqes_queued_for_submit) - submitted;
// /*debug*/
// /*debug*/ short_submit_counter_map[short_submit].c++;
// /*debug*/
// /*debug*/ unsigned dropped = *(struct_io_uring.sq.kdropped);
// /*debug*/
// /*debug*/ dropped_ocurrences_map[dropped].c++;
if ( submitted != 0 )
{
std::ostringstream o;
o << "io_uring_submit_and_wait(&struct_io_uring,1) was supposed to be a pure wait, but it submitted "
<< submitted << " sqes. \'sqes_queued_for_submit\", which is supposed to be zero was in fact " << sqes_queued_for_submit
<< "." << std::endl;
post_error(o.str());
}
}
}
}
}
number_of_IOs_running_at_end_of_subinterval = 0;
if (ivydriver.track_long_running_IOs)
{
for (TestLUN* pTestLUN : pTestLUNs)
{
for (const auto& pear : pTestLUN->workloads)
{
number_of_IOs_running_at_end_of_subinterval += pear.second.running_IOs.size();
}
}
}
if (routine_logging)
{
{
std::ostringstream o;
o << "For step number " << ivydriver.step_number << " subinterval number " << thread_view_subinterval_number << " LUNs = " << pTestLUNs.size() << ".";
log(slavethreadlogfile,o.str());
}
log_io_uring_engine_stats();
}
step_run_time_seconds += ivydriver.subinterval_duration.getlongdoubleseconds();
return;
}
void WorkloadThread::examine_timer_pop(struct cqe_shim* p_shim,const ivytime& now)
{
double scheduled_seconds = (p_shim->scheduled_duration()).getlongdoubleseconds();
double actual_seconds = (p_shim->since_insertion(now)).getlongdoubleseconds();
if (scheduled_seconds <= 0.0 || actual_seconds <= 0.0)
{
std::ostringstream o;
o << "<Error> internal programming error - WorkloadThread::examine_timer_pop()"
<< " - one or both of scheduled duration in seconds (" << scheduled_seconds
<< ") or actual duration seconds (" << actual_seconds << ") is less than or equal to zero.";
throw std::runtime_error(o.str());
}
if ( scheduled_seconds >= .001 && actual_seconds < (0.2 * scheduled_seconds) )
{
std::ostringstream o;
o << "<Error> internal programming error - WorkloadThread::examine_timer_pop()"
<< " - actual duration seconds (" << actual_seconds
<< ") less than 1/5th of scheduled duration in seconds (" << scheduled_seconds << ")";
throw std::runtime_error(o.str());
}
// if ( actual_seconds > 0.1 && actual_seconds > (10 * scheduled_seconds) )
// {
// std::ostringstream o;
// o << "<Error> internal programming error - WorkloadThread::examine_timer_pop()"
// << " - actual duration seconds (" << actual_seconds
// << ") greater than 10x scheduled duration in seconds (" << scheduled_seconds << ")";
// throw std::runtime_error(o.str());
// }
return;
}
void WorkloadThread::process_cqe(struct io_uring_cqe* p_cqe, const ivytime& now)
{
if (p_cqe == nullptr) { post_error("WorkloadThread::process_cqe() called with null pointer to struct io_uring_cqe pointer."); }
struct cqe_shim* p_shim = (struct cqe_shim*) p_cqe->user_data;
std::ostringstream o;
Eyeo* pEyeo;
switch (p_shim->type)
{
case cqe_type::timeout:
cumulative_timer_pop_cqes++;
if ( abs(p_cqe->res) != ETIME && p_cqe->res != 0 )
{
std::lock_guard<std::mutex> lk_guard(*p_ivydriver_main_mutex);
if (!ivydriver.spinloop)
{
ivydriver.spinloop = true;
o << "<Warning> internal programming issue - an IORING_OP_TIMEOUT failed return code ";
print_in_dec_and_hex(o, p_cqe->res);
o << " - " << std::strerror(abs(p_cqe->res));
o << " - setting spinloop to \"on\" to disable use of timeouts / waiting." << std::endl;
ivydriver.workload_thread_warning_messages.push_back(o.str());
}
}
examine_timer_pop(p_shim, now);
unexpired_timeouts.delete_shim(p_shim);
break;
case cqe_type::eyeo:
pEyeo = (Eyeo*) p_cqe->user_data;
pEyeo->pWorkload->post_Eyeo_result(p_cqe, pEyeo, now);
cumulative_eyeo_cqes++;
break;
default:
o << "when harvesting a completion queue event, user_data pointed to a cqe_shim of an unexpected type " << p_shim->type;
post_error(o.str());
}
return;
}
unsigned int WorkloadThread::populate_sqes()
{
if (pTestLUNs.size() == 0) return 0;
std::vector<TestLUN*>::iterator it = pTestLUN_populate_sqes_bookmark;
unsigned int total = 0;
while (true)
{
TestLUN* pTestLUN = *it;
total += pTestLUN->populate_sqes();
it++; if (it == pTestLUNs.end()) { it = pTestLUNs.begin(); }
if ( it == pTestLUN_populate_sqes_bookmark
|| have_failed_to_get_an_sqe ) { break; }
}
pTestLUN_populate_sqes_bookmark ++;
if (pTestLUN_populate_sqes_bookmark == pTestLUNs.end())
{
pTestLUN_populate_sqes_bookmark = pTestLUNs.begin();
}
return total;
}
unsigned int WorkloadThread::generate_IOs()
{
if (pTestLUNs.size() == 0) return 0;
auto it = pTestLUN_generate_bookmark;
unsigned int n {0};
while (true)
{
TestLUN* pTestLUN = (*it);
n += pTestLUN->generate_IOs();
if ( n > 0 ) break;
it++; if (it == pTestLUNs.end()) it = pTestLUNs.begin();
if (it == pTestLUN_generate_bookmark) break;
}
pTestLUN_generate_bookmark++;
if (pTestLUN_generate_bookmark == pTestLUNs.end())
{
pTestLUN_generate_bookmark = pTestLUNs.begin();
}
return n;
}
void WorkloadThread::set_all_queue_depths_to_zero()
{
workload_thread_queue_depth = 0;
workload_thread_max_queue_depth = 0;
for (auto& pTestLUN : pTestLUNs)
{
for (auto& pear : pTestLUN->workloads)
{
pear.second.workload_queue_depth = 0;
pear.second.workload_max_queue_depth = 0;
}
}
return;
}
void WorkloadThread::post_error(const std::string& msg)
{
std::string s;
{
std::ostringstream o;
o << "<Error> internal programming error - "s << ivydriver.ivyscript_hostname
<< " WorkloadThread physical core "s << physical_core << " hyperthread " << hyperthread
<< " - " << msg;
s = o.str();
}
if (s[s.size()-1] != '\n') { s += "\n"; }
log(slavethreadlogfile,s);
log(ivydriver.slavelogfile,"posted by WorkloadThread: "s + s);
reported_error = true;
if (!ivydriver.reported_error) {ivydriver.time_error_reported.setToNow();}
ivydriver.reported_error = true;
std::cout << s << std::flush; // The reason we both queue it and say it is that it's possible that when I say() it here, this may come out in the middle of a line being spoken by ivydriver.
{
std::lock_guard<std::mutex> lk_guard(*p_ivydriver_main_mutex);
ivydriver.workload_thread_error_messages.push_back(s);
}
// ?????? should we sleep here a bit? - gnaw.
return;
}
void WorkloadThread::post_warning(const std::string& msg)
{
std::string s;
{
std::ostringstream o;
o << "<Warning> "s << ivydriver.ivyscript_hostname
<< " WorkloadThread physical core "s << physical_core << " hyperthread " << hyperthread
<< " - " << msg;
s = render_string_harmless(o.str());
}
s.push_back('\n');
log(slavethreadlogfile,s);
log(ivydriver.slavelogfile,"posted by WorkloadThread: "s + s);
{
std::lock_guard<std::mutex> lk_guard(*p_ivydriver_main_mutex);
ivydriver.workload_thread_warning_messages.push_back(s);
}
return;
}
void WorkloadThread::check_for_long_running_IOs()
{
// runs with the lock held at subinterval switchover
// when I/O events are not being harvested.
ivytime now; now.setToNow();
for (TestLUN*& pTestLUN : pTestLUNs)
{
{
RunningStat<ivy_float,ivy_int> long_running_IOs;
for (auto& pear : pTestLUN->workloads)
{
for (Eyeo* pEyeo : pear.second.running_IOs)
{
long double run_time_so_far = 0.0 - pEyeo->start_time.seconds_from(now);
if (run_time_so_far > 1.0)
{
long_running_IOs.push(run_time_so_far);
}
}
}
if (long_running_IOs.count() > 0)
{
std::ostringstream o;
o << "LUN " << pTestLUN->host_plus_lun << " has " << long_running_IOs.count()
<< " I/Os that have been running for more than one second, the longest of which for "
<< std::fixed << std::setprecision(0) << long_running_IOs.max() << ".x seconds." << std::endl;
post_warning(o.str());
}
}
}
ivytime ending; ending.setToNow();
ivytime run_time = ending-now;
if (routine_logging)
{
std::ostringstream o;
o << "WorkloadThread::check_for_long_running_IOs() held the lock and ran for " << run_time.getAsNanoseconds() << " nanoseconds." << std::endl;
log(slavethreadlogfile,o.str());
}
return;
}
void WorkloadThread::build_uring_and_allocate_and_mmap_Eyeo_buffers_and_build_Eyeos()
{
if (io_uring_fd != -1)
{
std::ostringstream o;
o << "WorkloadThread::build_uring_and_allocate_and_mmap_Eyeo_buffers_and_build_Eyeos()"
<< " - upon entry, io_uring_fd was not -1, instead it was " << io_uring_fd << std::endl;
post_error(o.str());
}
if (p_buffer_pool != nullptr)
{
std::ostringstream o;
o << "WorkloadThread::build_uring_and_allocate_and_mmap_Eyeo_buffers_and_build_Eyeos()"
<< " - upon entry, p_buffer_pool was not nullptr, instead it was " << p_buffer_pool << std::endl;
post_error(o.str());
}
cumulative_sqes = 0;
cumulative_submits = 0;
cumulative_waits = 0;
cumulative_loop_passes = 0;
cumulative_fruitless_passes = 0;
cumulative_cqes = 0; // all set in process_cqe
cumulative_timer_pop_cqes = 0;
cumulative_eyeo_cqes = 0;
max_sqes_submitted_at_once = 0;
max_cqes_reaped_at_once = 0;
max_sqes_tried_to_submit_at_once = 0;
total_buffer_size = 0;
total_maxTags = 0;
//*debug*/ { std::ostringstream o; o << "WorkloadThread::build_uring_and_allocate_and_mmap_Eyeo_buffers_and_build_Eyeos() - b4 computing buffer pool size." << std::endl;log(slavethreadlogfile, o.str()); }
unsigned total_Eyeos {0};
for (TestLUN* pTestLUN : pTestLUNs)
{
for (auto& wkld_pear : pTestLUN->workloads)
{
{
Workload& w = wkld_pear.second;
Subinterval& s = w.subinterval_array[0];
IosequencerInput& ii = s.input;
total_maxTags += ii.maxTags;
total_buffer_size += w.io_buffer_space();
total_Eyeos += w.eyeo_build_qty();
if (routine_logging)
{
std::ostringstream o; o << w.workloadID << " - "
<< "ii.blocksize_bytes = " << put_on_KiB_etc_suffix( ii.blocksize_bytes )
<< ", ii.maxTags = " << w.eyeo_build_qty()
<< ", w.precomputedepth() = " << w.precomputedepth()
<< ", w.eyeo_build_qty() = " << w.eyeo_build_qty()
<< ", w.flex_Eyeos() = " << w.flex_Eyeos()
<< ", blocksize rounded-up to 4 kIB multiple = " << put_on_KiB_etc_suffix( round_up_to_4096_multiple(ii.blocksize_bytes) )
<< ", w.io_buffer_space() = " << put_on_KiB_etc_suffix( w.io_buffer_space() )
<< ", running total_Eyeos = " << total_Eyeos
<< ", running total_buffer_size = " << put_on_KiB_etc_suffix( total_buffer_size )
;
log(slavethreadlogfile,o.str());
}
}
}
}
if (routine_logging)
{
std::ostringstream o;
o << "I/O buffer pool total_buffer_size = " << put_on_KiB_etc_suffix(total_buffer_size)
<< " for " << total_Eyeos << " Eyeos"
<< " or an average of " << (total_buffer_size / total_Eyeos) << " buffer pool bytes per Eyeo.";
o << " Total maxTags = " << total_maxTags << std::endl;
log(slavethreadlogfile, o.str());
}
int rc = posix_memalign(&p_buffer_pool, 4096, total_buffer_size);
if (rc != 0)
{
p_buffer_pool = nullptr;
std::ostringstream o;
o << "<Error> internal programming error - WorkloadThread for physical core " << physical_core << " hyperthread " << hyperthread
<< " - posix_memalign(&p_buffer_pool, 4096, total_buffer_size = " << total_buffer_size
<< " failed with return code " << rc << " (" << std::strerror(-rc) << ") when allocating memory for Eyeo buffer pool." << std::endl;
throw std::runtime_error(o.str());
}
requested_uring_entries = 1;
while (requested_uring_entries < 4096 && (2*requested_uring_entries) < (total_maxTags+4)) // This formulation OK for unsigned - no subtracting
{
requested_uring_entries *= 2;
}
rc = io_uring_queue_init(requested_uring_entries,&struct_io_uring,0);
if ( rc != 0)
{
std::ostringstream o;
o << "<Error> internal programming error - WorkloadThread for physical core " << physical_core << " hyperthread " << hyperthread
<< " - failed trying to initialize io_uring with return code " << rc << " (" << std::strerror(-rc) << ")." << std::endl;
throw std::runtime_error(o.str());
}
io_uring_fd = struct_io_uring.ring_fd;
if (routine_logging)
{
std::ostringstream o;
o << "io_uring_queue_init requested entries = " << requested_uring_entries
<< ", assigned submit queue entries = " << *(struct_io_uring.sq.kring_entries)
<< ", assigned completion queue entries = " << *(struct_io_uring.cq.kring_entries)
<< ". struct io_uring.ring_fd = " << struct_io_uring.ring_fd << "." << std::endl;
log(slavethreadlogfile,o.str());
}
workload_thread_queue_depth_limit = (*(struct_io_uring.cq.kring_entries)) - 1;;
struct iovec struct_iovec;
struct_iovec.iov_base = p_buffer_pool;
struct_iovec.iov_len = total_buffer_size;
rc = io_uring_register_buffers(&struct_io_uring, &struct_iovec, 1);
if ( rc != 0)
{
std::ostringstream o;
o << "<Error> internal programming error - WorkloadThread for physical core " << physical_core << " hyperthread " << hyperthread
<< " - failed trying to register buffer pool with return code " << rc << " (" << std::strerror(errno) << ")." << std::endl;
throw std::runtime_error(o.str());
}
if (routine_logging)
{
std::ostringstream o;
o << "io_uring_register_buffers() performed for struct_iovec.iov_base = " << struct_iovec.iov_base
<< ", struct_iovec.iov_len = " << put_on_KiB_etc_suffix(struct_iovec.iov_len) << ".";
log(slavethreadlogfile, o.str());
}
{
size_t testluns {pTestLUNs.size()};
int arrayof_fds[testluns];
size_t i = 0;
for (auto pTestLUN : pTestLUNs)
{
pTestLUN->open_fd();
arrayof_fds[i] = pTestLUN->fd;
pTestLUN->fd_index = i;
i++;
}
rc = io_uring_register_files(&struct_io_uring, arrayof_fds, pTestLUNs.size());
if ( rc != 0)
{
std::ostringstream o;
o << "<Error> internal programming error - WorkloadThread for physical core " << physical_core << " hyperthread " << hyperthread
<< " - failed trying to register array of TestLUN file descriptors with return code " << rc << " (" << std::strerror(errno) << ")." << std::endl;
throw std::runtime_error(o.str());
}
if (routine_logging)
{
std::ostringstream o;
o << "io_uring_register_files() performed for " << testluns << " fds:";
for (size_t i = 0; i < pTestLUNs.size();i ++)
{
o << " " << arrayof_fds[i];
}
o << ".";
log(slavethreadlogfile, o.str());
}
}
uint64_t p_buffer = (uint64_t) p_buffer_pool;
for (auto& pTestLUN : pTestLUNs)
{
for (auto& pear : pTestLUN->workloads)
{
pear.second.build_Eyeos(p_buffer);
}
}
uint64_t io_buffer_pointer_advance = p_buffer - ( (uint64_t) p_buffer_pool );
if ( io_buffer_pointer_advance != total_buffer_size)
{
std::ostringstream o;
o << "In WorkloadThread::build_uring_and_allocate_and_mmap_Eyeo_buffers_and_build_Eyeos(), "
<< "the amount by which the Eyeo I/O buffer pointer moved forward in build_Eyeos() "
<< " io_buffer_pointer_advance = ";
print_in_dec_and_hex(o, io_buffer_pointer_advance);
o << ", was different from the size of the buffer pool as it was allocated "
<< " based on an original pre-scan to add up the amount of memory needed ";
print_in_dec_and_hex(o, total_buffer_size);
o << "." << std::endl;
post_error(o.str());
}
sqes_queued_for_submit = 0;
return;
}
void WorkloadThread::shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos()
{
//*debug*/ { std::ostringstream o; o << "WorkloadThread::shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - entry." << std::endl;log(slavethreadlogfile, o.str()); }
int rc_ub, rc_uf;
rc_ub = io_uring_unregister_buffers(&struct_io_uring);
rc_uf = io_uring_unregister_files (&struct_io_uring);
io_uring_queue_exit (&struct_io_uring);
io_uring_fd = -1;
if (rc_ub != 0 || rc_uf != 0)
{
std::ostringstream o;
o << "shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - ";
o << "io_uring_unregister_buffers() return code = " << rc_ub; if (rc_ub != 0) { o << " (" << std::strerror(abs(rc_ub)) << ")"; }
o << "io_uring_unregister_files() return code = " << rc_uf; if (rc_uf != 0) { o << " (" << std::strerror(abs(rc_uf)) << ")"; }
post_error(o.str());
}
//*debug*/ { std::ostringstream o; o << "WorkloadThread::shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - after io_uring_queue_exit()." << std::endl;log(slavethreadlogfile, o.str()); }
for (auto& pTestLUN : pTestLUNs)
{
int rc = close(pTestLUN->fd);
if (rc != 0)
{
std::ostringstream o;
o << "shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - ";
o << "return code " << rc << " (" << std::strerror(abs(rc)) << ") from close(" << pTestLUN->fd << ") for " << pTestLUN->host_plus_lun;
post_error(o.str());
}
pTestLUN->fd = -1;
for (auto& pear : pTestLUN->workloads)
{
{
Workload& w = pear.second;
for (auto& pEyeo : w.allEyeosThatExist) delete pEyeo;
w.allEyeosThatExist.clear();
while (0 < w.freeStack.size()) w.freeStack.pop(); // stacks curiously don't hve a clear() method.
w.precomputeQ.clear();
w.running_IOs.clear();
}
}
}
//*debug*/ { std::ostringstream o; o << "WorkloadThread::shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - after closing LUN fds." << std::endl;log(slavethreadlogfile, o.str()); }
if (p_buffer_pool == nullptr)
{
std::ostringstream o;
o << "shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - ";
o << "p_buffer_pool is nullptr.";
post_error(o.str());
}
free(p_buffer_pool);
p_buffer_pool = nullptr;
//*debug*/ { std::ostringstream o; o << "WorkloadThread::shutdown_uring_and_unmap_Eyeo_buffers_and_delete_Eyeos() - returning." << std::endl;log(slavethreadlogfile, o.str()); }
return;
}
void WorkloadThread::possibly_insert_timeout(const ivytime& now)
{
ivytime timer_expiry = now + ivydriver.max_wait;
if (now > thread_view_subinterval_end) { did_something_this_pass = true; return; }
if (timer_expiry > thread_view_subinterval_end) { timer_expiry = thread_view_subinterval_end; }
for (TestLUN* pTestLUN : pTestLUNs)
{
for (auto& pear : pTestLUN->workloads)
{
{
Workload& w = pear.second;
if (w.workload_queue_depth >= w.p_current_IosequencerInput->maxTags) continue;
if (w.is_IOPS_max_with_positive_skew() && w.hold_back_this_time()) continue;
if (w.precomputeQ.size() == 0) continue;
Eyeo* pEyeo = w.precomputeQ.front();
if (pEyeo->scheduled_time.isZero()) continue;
if (timer_expiry.isZero() || pEyeo->scheduled_time < timer_expiry)
{
timer_expiry = pEyeo->scheduled_time;
}
}
}
}
//*debug*/if (timer_expiry.isZero()) {throw std::runtime_error("<Error> internal programming error - WorkloadThread::possibly_insert_timeout(const ivytime& now) - Borked!");}
ivytime earliest_unexpired = unexpired_timeouts.earliest_timeout(); // including a possibly queued timeout
if ( earliest_unexpired.isZero() || timer_expiry < earliest_unexpired )
{
// need to submit new timeout
did_something_this_pass = true;
if (timer_expiry <= now) return;
if ( unexpired_timeouts.unsubmitted_timeout.isZero() )
{
struct io_uring_sqe* p_sqe = get_sqe();
if (p_sqe)
{
fill_in_timeout_sqe(p_sqe, timer_expiry, now);
unexpired_timeouts.unsubmitted_timeout.setToZero();
}
else
{
unexpired_timeouts.unsubmitted_timeout = timer_expiry;
}
}
else
{
unexpired_timeouts.unsubmitted_timeout = timer_expiry;
try_to_submit_unsubmitted_timeout(now);
}
}
return;
}
void WorkloadThread::fill_in_timeout_sqe(struct io_uring_sqe* p_sqe, const ivytime& timestamp, const ivytime& now)
{
if ( timestamp.isZero() || now.isZero() || now > timestamp )
{
std::ostringstream o;
o << "<Error> WorkloadThread::fill_in_timeout_sqe(struct io_uring_sqe* p_sqe, const ivytime& timestamp = "
<< timestamp.format_as_datetime_with_ns() << ", const ivytime& now = " << now.format_as_datetime_with_ns() << ")"
<< " - both \"timestamp\" and \"now\" must be non-zero, and \"timestamp\" must be after \"now\"." << std::endl;
throw std::runtime_error(o.str());
}
cqe_shim* p_shim = unexpired_timeouts.insert_timeout(timestamp, now);
number_of_concurrent_timeouts.push ((ivy_float) unexpired_timeouts.unexpired_shims.size());
ivytime delta_to_timestamp = timestamp - now;
p_shim->kts.tv_sec = delta_to_timestamp.t.tv_sec;
p_shim->kts.tv_nsec = delta_to_timestamp.t.tv_nsec;
// memset(p_sqe,0,sizeof(struct io_uring_sqe));
// p_sqe->opcode = IORING_OP_TIMEOUT;
// p_sqe->fd = -1;
// p_sqe->addr = (uint64_t) &(p_shim->kts);
io_uring_prep_timeout(p_sqe, &(p_shim->kts), 0 /* count*/, 0 /* flags */);
p_sqe->user_data = (uint64_t) p_shim;
return;
}
struct io_uring_sqe* WorkloadThread::get_sqe()
{
if (workload_thread_queue_depth >= workload_thread_queue_depth_limit) { have_failed_to_get_an_sqe = true; return nullptr; }
struct io_uring_sqe* p_sqe = io_uring_get_sqe(&struct_io_uring);
if (p_sqe == nullptr) { have_failed_to_get_an_sqe = true; return nullptr; }
workload_thread_queue_depth++;
cumulative_sqes++;
if ( workload_thread_max_queue_depth < workload_thread_queue_depth )
{ workload_thread_max_queue_depth = workload_thread_queue_depth;}
sqes_queued_for_submit++;
did_something_this_pass = true;
if ( workload_thread_queue_depth /* includes wt.sqes_queued_for_submit) */ >= workload_thread_queue_depth_limit )
{
if (!have_warned_hitting_cqe_entry_limit)
{
have_warned_hitting_cqe_entry_limit = true;
std::ostringstream o;
o << "have reached the workload_thread_queue_depth_limit value being " << workload_thread_queue_depth_limit
<< " : workload_thread_cqe_entrie.";
post_warning(o.str());
}
}
return p_sqe;
}
void WorkloadThread::try_to_submit_unsubmitted_timeout(const ivytime& now)
{
if ( unexpired_timeouts.unsubmitted_timeout.isZero() ) { return; }
did_something_this_pass = true;
if (now >= unexpired_timeouts.unsubmitted_timeout)
{
unexpired_timeouts.unsubmitted_timeout.setToZero();
return;
}
struct io_uring_sqe* p_sqe = get_sqe();
if (p_sqe == nullptr)
{
have_failed_to_get_an_sqe = true;
}
else
{
fill_in_timeout_sqe(p_sqe, unexpired_timeouts.unsubmitted_timeout, now);
// this also creates & inserts a cqe_shim for the timeout.
unexpired_timeouts.unsubmitted_timeout.setToZero();
}
return;
}
void WorkloadThread::log_io_uring_engine_stats()
{
std::ostringstream o;
o << "max_cqes_reaped_at_once = " << max_cqes_reaped_at_once;
o << ", max_sqes_tried_to_submit_at_once = " << max_sqes_tried_to_submit_at_once;
o << ", max_sqes_submitted_at_once = " << max_sqes_submitted_at_once;
o << ", sqes_per_submit_limit = " << ivydriver.sqes_per_submit_limit;
o << ", cqes_with_one_peek_limit = " << cqes_with_one_peek_limit;
o << ", generate_at_a_time_multiplier = " << ivydriver.generate_at_a_time_multiplier;
o << ", loop_passes_per_IO() = " << loop_passes_per_IO();
o << ", timer_pops_per_second() = " << timer_pops_per_second();
o << ", timer_pops_per_IO() = " << timer_pops_per_IO();
o << ", submits_per_IO() = " << submits_per_IO();
o << ", fruitless_passes_per_IO() = " << fruitless_passes_per_IO();
o << ", cqes_per_loop_pass() = " << cqes_per_loop_pass();
o << ", sqes_per_submit() = " << sqes_per_submit();
o << ", IOs_per_system_call() = " << IOs_per_system_call();
//*debug*/{ unsigned total {0}; o << std::endl; for (auto& pear : short_submit_counter_map) { total += pear.second.c; o << "For short submit value " << pear.first << " the number of occurrences was " << pear.second.c << "."<< std::endl;} o << "Total " << total << " occurrences." << std::endl; }
//*debug*/{ unsigned total {0}; o << std::endl; for (auto& pear : dropped_ocurrences_map ) { total += pear.second.c; o << "For dropped value " << pear.first << " the number of occurrences was " << pear.second.c << "."<< std::endl;} o << "Total " << total << " occurrences." << std::endl; }
o << ", track_long_running_IOs = " << (ivydriver.track_long_running_IOs ? "on" : "off");
o << ", spinloop = " << (ivydriver.spinloop ? "on" : "off");
o << ", sqes_per_submit_limit = " << ivydriver.sqes_per_submit_limit;
log(slavethreadlogfile,o.str());
return;
}
void WorkloadThread::catch_in_flight_IOs_after_last_subinterval()
{
ivytime upon_entry; upon_entry.setToNow();
ivytime limit; limit = upon_entry + ivytime(1.0);
unsigned timeouts {0}, eyeos {0};
ivytime now;
while (workload_thread_queue_depth > 0)
{
now.setToNow();
if (now > limit)
{
std::ostringstream o;
o << "In WorkloadThread::catch_in_flight_IOs_after_last_subinterval() after harvesting "
<< eyeos << " I/Os, " << timeouts << " timer pops"
<< " over a period of " << ivytime( now - upon_entry ).format_as_duration_HMMSSns()
<< ", there were still " << workload_thread_queue_depth << " pending completion queue events.";
log(slavethreadlogfile,o.str());
return;
}
unsigned cqe_harvest_count = io_uring_peek_batch_cqe(&struct_io_uring, cqe_pointer_array, cqes_with_one_peek_limit);
if (cqe_harvest_count > 0)
{
workload_thread_queue_depth -= cqe_harvest_count;
for (size_t i = 0; i < cqe_harvest_count; i++)
{
struct io_uring_cqe* p_cqe = cqe_pointer_array[i];
struct cqe_shim* p_shim = (struct cqe_shim*) p_cqe->user_data;
switch (p_shim->type)
{
case cqe_type::eyeo: eyeos++; break;
case cqe_type::timeout: timeouts++; break;
default: ;
}
}
io_uring_cq_advance(&struct_io_uring,cqe_harvest_count);
}
}
now.setToNow();
if (routine_logging)
{
std::ostringstream o;
o << "WorkloadThread::catch_in_flight_IOs_after_last_subinterval() harvested "
<< eyeos << " I/Os and " << timeouts << " timer pops"
<< " over a period of " << ivytime( now - upon_entry ).format_as_duration_HMMSSns() << "." << std::endl;
log(slavethreadlogfile,o.str());
}
return;
}
| 37.304819 | 295 | 0.567342 | [
"vector"
] |
bc031549eb882ef06075407de64a85a53cbb10d2 | 4,503 | hpp | C++ | libs/GeomLib/AbstractNeuralDynamics.hpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 13 | 2015-09-15T17:28:25.000Z | 2022-03-22T20:26:47.000Z | libs/GeomLib/AbstractNeuralDynamics.hpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 41 | 2015-08-25T07:50:55.000Z | 2022-03-21T16:20:37.000Z | libs/GeomLib/AbstractNeuralDynamics.hpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 9 | 2015-09-14T20:52:07.000Z | 2022-03-08T12:18:18.000Z | // Copyright (c) 2005 - 2014 Marc de Kamps
// 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// If you use this software in work leading to a scientific publication, you should include a reference there to
// the 'currently valid reference', which can be found at http://miind.sourceforge.net
#ifndef _CODE_LIBS_GEOMLIB_ABSTRACTNEURALDYNAMICS_H_
#define _CODE_LIBS_GEOMLIB_ABSTRACTNEURALDYNAMICS_H_
#include <vector>
#include <MPILib/include/BasicDefinitions.hpp>
#include "CurrentCompensationParameter.hpp"
#include "OdeParameter.hpp"
namespace GeomLib {
//! The configuration of a GeomAlgorithm requires that the neural dynamics is defined somewhere. The dynamics is used to define an OdeSystem.
//! There are predefined derived classes for leaky-integrate-and-fire and quadratic-integrate-and-fire
//! dynamics. The dynamics is usually defined on a grid, whose dimensions are specified in the OdeParameter. OdeParameter
//! also contains a NeuronParameter that determines the dynamics.Anyone who wants to use their own model of neural dynamics.
//! To define dynamics on this grid, the EvolvePotential must be overloaded. Derived classes exist for
//! LIF and QIF neurons, and more generally for spiking neurons (SpikingNeuralDynamics).
class AbstractNeuralDynamics {
public:
//! Constructor
AbstractNeuralDynamics
(
const OdeParameter&, //! Neuron parameter values, and other information relevant to binning structure
const CurrentCompensationParameter& = CurrentCompensationParameter(0.,0.) //! By default, no current compensation, but if it's chosen, it directly affects the neural dynamics and hence the binning
);
//! Virtual destructor
virtual ~AbstractNeuralDynamics() = 0;
//! Given a potential, specify how it evolves over a given time step
//! The range of validity of this function is determined by the overloaded function
virtual Potential
EvolvePotential
(
Potential,
MPILib::Time
) const = 0;
//! virtual construction mechanism
virtual AbstractNeuralDynamics* Clone() const = 0;
//! Provide efficient access. For use in time critical code
const OdeParameter& Par() const {return _par; }
//! Fundamental time step by which mass is shifted through the geometric bins. Consult
//! the '1D document' for details.
virtual MPILib::Time TStep() const = 0;
//! Period for the dynamic model. Consult the '1D document'.
virtual MPILib::Time TPeriod() const = 0;
//! Generate the bin boundaries for geometric binning based on the dyn
virtual std::vector<Potential> InterpretationArray() const = 0;
//! Return the current compensation object; can be used to test whether current compensation is applied.
const CurrentCompensationParameter& ParCur() const { return _par_current; }
protected:
//! Time critical access for derived classes
const OdeParameter _par;
//! For use in the concrete dynamics instantiation
const CurrentCompensationParameter _par_current;
};
}
#endif /* ABSTRACTNEURALDYNAMICS_H_ */
| 48.945652 | 199 | 0.766378 | [
"object",
"vector",
"model"
] |
bc0fd6fce9cfd5a26195db0207b84e1fbb0dde95 | 3,789 | hpp | C++ | inference-engine/src/inference_engine/cpp_interfaces/base/ie_inference_plugin_api.hpp | giulio1979/dldt | e7061922066ccefc54c8dae6e3215308ce9559e1 | [
"Apache-2.0"
] | 1 | 2021-07-30T17:03:50.000Z | 2021-07-30T17:03:50.000Z | inference-engine/src/inference_engine/cpp_interfaces/base/ie_inference_plugin_api.hpp | Dipet/dldt | b2140c083a068a63591e8c2e9b5f6b240790519d | [
"Apache-2.0"
] | null | null | null | inference-engine/src/inference_engine/cpp_interfaces/base/ie_inference_plugin_api.hpp | Dipet/dldt | b2140c083a068a63591e8c2e9b5f6b240790519d | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* \brief Inference Engine extended plugin API
* \file ie_inference_plugin_api.hpp
*/
#pragma once
#include <ie_api.h>
#include <cpp/ie_executable_network.hpp>
#include <ie_parameter.hpp>
#include <ie_remote_context.hpp>
#include <map>
#include <string>
#include <vector>
namespace InferenceEngine {
/**
* @brief Forward declaration of ICorePrivate interface
*/
class ICore;
/**
* @brief Extended plugin API to add new method to plugins but without changing public interface IInferencePlugin.
* It should be used together with base IInferencePlugin which provides common interface, while this one just extends
* API.
*/
class INFERENCE_ENGINE_API_CLASS(IInferencePluginAPI) {
public:
/**
* @brief Sets plugin name
* @param pluginName Plugin name to set
*/
virtual void SetName(const std::string& pluginName) noexcept = 0;
/**
* @brief Returns plugin name
* @return Plugin name
*/
virtual std::string GetName() const noexcept = 0;
/**
* @brief Sets pointer to ICore interface
* @param core Pointer to Core interface
*/
virtual void SetCore(ICore* core) noexcept = 0;
/**
* @brief Gets refernce to ICore interface
* @return Reference to core interface
*/
virtual const ICore& GetCore() const = 0;
/**
* @brief Gets configuration dedicated to plugin behaviour
* @param name - value of config corresponding to config key
* @param options - configuration details for config
* @return Value of config corresponding to config key
*/
virtual Parameter GetConfig(const std::string& name, const std::map<std::string, Parameter>& options) const = 0;
/**
* @brief Gets general runtime metric for dedicated hardware
* @param name - metric name to request
* @param options - configuration details for metric
* @return Metric value corresponding to metric key
*/
virtual Parameter GetMetric(const std::string& name, const std::map<std::string, Parameter>& options) const = 0;
virtual RemoteContext::Ptr CreateContext(const ParamMap& params) = 0;
virtual RemoteContext::Ptr GetDefaultContext() = 0;
/**
* @brief Wraps original method
* IInferencePlugin::ImportNetwork
* @param network - a network object acquired from CNNNetReader
* @param config string-string map of config parameters relevant only for this load operation
* @param context - a pointer to plugin context derived from RemoteContext class used to
* execute the network
* @return Created Executable Network object
*/
virtual ExecutableNetwork LoadNetwork(ICNNNetwork& network, const std::map<std::string, std::string>& config,
RemoteContext::Ptr context) = 0;
/**
* @brief Wraps original method
* IInferencePlugin::ImportNetwork
* @param networkModel Network model input stream
* @param config A configuration map
* @return Created Executable Network object
*/
virtual ExecutableNetwork ImportNetwork(std::istream& networkModel,
const std::map<std::string, std::string>& config) = 0;
virtual ~IInferencePluginAPI();
};
class INFERENCE_ENGINE_API_CLASS(DeviceIDParser) {
std::string deviceName;
std::string deviceID;
public:
explicit DeviceIDParser(const std::string& deviceNameWithID);
std::string getDeviceID() const;
std::string getDeviceName() const;
static std::vector<std::string> getHeteroDevices(std::string fallbackDevice);
static std::vector<std::string> getMultiDevices(std::string devicesList);
};
} // namespace InferenceEngine
| 31.840336 | 117 | 0.686989 | [
"object",
"vector",
"model"
] |
bc23c394d266833cb7157f04e276b4ba1afe9c3b | 3,323 | cpp | C++ | BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/pla/eRungeKutta/extra/eRungeKutta_FG_sbPL.cpp | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | 53 | 2015-03-15T20:33:36.000Z | 2022-02-25T12:07:26.000Z | BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/pla/eRungeKutta/extra/eRungeKutta_FG_sbPL.cpp | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | 85 | 2015-03-19T19:58:19.000Z | 2022-02-28T20:38:17.000Z | BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/pla/eRungeKutta/extra/eRungeKutta_FG_sbPL.cpp | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | 34 | 2015-05-02T23:46:57.000Z | 2021-12-22T19:35:58.000Z | /*
* eRungeKutta_FG_sbPL.cpp
*
* Created on: Apr 26, 2011
* Author: Leonard Harris
*/
#include "eRungeKutta_EXTRA.hh"
#include "../../../util/util.hh"
/*
eRungeKuttaSB_FG_PL::eRungeKuttaSB_FG_PL() : sp(){
if (MoMMA::debug)
cout << "eRungeKuttaSB_FG_PL constructor called." << endl;
}
*/
eRungeKutta_FG_sbPL::eRungeKutta_FG_sbPL(ButcherTableau bt, double eps, double p, vector<SimpleSpecies*>& sp,
vector<Reaction*>& rxn) : eRungeKutta_FG(bt,sp,rxn), sp(sp){
if (debug)
cout << "eRungeKutta_FG_sbPL constructor called." << endl;
this->ch = new SBChecker(eps,this->sp);
this->bc = new BinomialCorrector_RK(p,rxn);
this->gGet = new g_Getter(this->sp,rxn);
// Add species
for (unsigned int j=0;j < this->sp.size();j++){
this->addSpecies();
}
}
eRungeKutta_FG_sbPL::eRungeKutta_FG_sbPL(ButcherTableau bt, double eps, double p, vector<SimpleSpecies*>& sp,
vector<Reaction*>& rxn, bool round) : eRungeKutta_FG(bt,sp,rxn,round), sp(sp){
if (debug)
cout << "eRungeKutta_FG_sbPL constructor called." << endl;
this->ch = new SBChecker(eps,this->sp);
this->bc = new BinomialCorrector_RK(p,rxn);
this->gGet = new g_Getter(this->sp,rxn);
// Add species
for (unsigned int j=0;j < this->sp.size();j++){
this->addSpecies();
}
}
eRungeKutta_FG_sbPL::eRungeKutta_FG_sbPL(const eRungeKutta_FG_sbPL& fg_pl) : eRungeKutta_FG(fg_pl), oldPop(fg_pl.oldPop),
old_g(fg_pl.old_g), sp(fg_pl.sp){
if (debug)
cout << "eRungeKutta_FG_sbPL copy constructor called." << endl;
this->ch = new SBChecker(*fg_pl.ch);
this->bc = new BinomialCorrector_RK(*fg_pl.bc);
this->gGet = new g_Getter(*fg_pl.gGet);
}
eRungeKutta_FG_sbPL::~eRungeKutta_FG_sbPL(){
if (debug)
cout << "eRungeKutta_FG_sbPL destructor called." << endl;
delete this->ch;
delete this->bc;
delete this->gGet;
}
bool eRungeKutta_FG_sbPL::check(){
// Check for new species
while (this->oldPop.size() != this->sp.size() && this->old_g.size() != this->sp.size()){
this->addSpecies();
}
// X_eff[] elements have already been calculated in fireRxns()
return this->ch->check(1.0,this->aCalc->X_eff,this->oldPop,this->old_g,true);
}
void eRungeKutta_FG_sbPL::update(){
// Update oldPop[] and old_g[]
for (unsigned int j=0;j < this->oldPop.size();j++){
this->oldPop[j] = this->sp[j]->population;
this->old_g[j] = this->gGet->get_g(j);
}
// Just in case
if (this->oldPop.size() != this->sp.size()){
cout << "Error in eRungeKutta_FG_sbPL::update(): Sizes of 'oldPop' and 'sp' vectors not equal. "
<< "Shouldn't happen. Exiting." << endl;
exit(1);
}
if (this->old_g.size() != this->sp.size()){
cout << "Error in eRungeKutta_FG_sbPL::update(): Sizes of 'old_g' and 'sp' vectors not equal. "
<< "Shouldn't happen. Exiting." << endl;
exit(1);
}
}
void eRungeKutta_FG_sbPL::addSpecies(){
if (this->oldPop.size() < this->sp.size() && this->old_g.size() < this->sp.size()
&& this->oldPop.size() == this->old_g.size()){
unsigned int i = this->oldPop.size();
this->oldPop.push_back(this->sp[i]->population);
this->old_g.push_back(this->gGet->get_g(i));;
}
else{
cout << "Error in eRungeKutta_FG_sbPL::addSpecies(): No species to add (oldPop.size = " << this->oldPop.size()
<< ", old_g.size = " << old_g.size() << ", sp.size = " << this->sp.size() << "). Shouldn't happen. Exiting.\n";
exit(1);
}
}
| 33.23 | 121 | 0.665062 | [
"vector"
] |
bc24d18f4094c20b37891791b8b75f8fece38112 | 16,397 | cpp | C++ | C++/Programming Assignments/Program5/Program5.cpp | RamziJabali/CSC240-AB-intro-to-different-languages | f9e0a031924f2c3c657b620f75be872f8f5fe5cc | [
"MIT"
] | null | null | null | C++/Programming Assignments/Program5/Program5.cpp | RamziJabali/CSC240-AB-intro-to-different-languages | f9e0a031924f2c3c657b620f75be872f8f5fe5cc | [
"MIT"
] | null | null | null | C++/Programming Assignments/Program5/Program5.cpp | RamziJabali/CSC240-AB-intro-to-different-languages | f9e0a031924f2c3c657b620f75be872f8f5fe5cc | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
//Parts of Phase 1
void optionTwoRepresentative();
void optionThreeRepresentative();
//UserInput/output
void optionOnePhaseTwoMenu();
void optionOneInputOutput();
void optionTwoInputAndOutput();
void optionThreeInputOutput();
//Engineers for the computations
void optionOneEngineer(double x1, double x2, double y1, double y2,
double *distance, double *horizontalAngle);
double optionTwoEngineer(double elevationAngle, double velocity);
void optionThreeEngineer(double x1, double y1, double &x2, double &y2,
double horizontalAngle, double distance);
//Phase 2 extra required function
int getRandomNumber();
void optionThreeCheatMode(double x1, double x2, double y1, double y2);
//My Functions
char doesUserWantToQuit();
int targetPracticeCalculations(double x1, double x2, double y1, double y2,
double horizontalAngle, double verticalAngle,
double velocity, int radius);
void getXAndYCoordinates(double &xCoordinate, double &yCoordinate);
double getElevationAngle();
double getVelocity();
double getHorizontalAngle();
double getDistance();
double getUserVerticalAngleIncrement();
double getUserVelocityIncrement();
double getHorizontalAnglePhaseTwo();
double getVerticalAngle();
int doesUserWantOptionThreeInEasyMediumOrHardMode();
int getRadiusFromGameMode(int gameMode);
int doesUserWantCheatMode();
int doesUserWantToIncrementVelocityOrVerticalAngle();
void createAndDisplayArtilleryTable(double incrementAmount, double verticalAngle,
double velocity, int velocityOrAngle);
double PI();
double gravitationalVelocity();
int getUserMenuChoice();
int getUserMenuChoicePhase1();
int feetPerMile();
int secondsPerHour();
int two();
void printIntroductionDialogue();
void printPhase1MenuDialogue();
void mainMenu();
void quit();
int main() {
mainMenu();
return 0;
}
void mainMenu() {
int userChoice;
do {
userChoice = getUserMenuChoice();
switch (userChoice) {
case 1:
optionOnePhaseTwoMenu();
break;
case 2:
optionTwoInputAndOutput();//
break;
case 3:
optionThreeInputOutput();
break;
case 4:
quit();
break;
}
} while (userChoice != 4);
}
void optionOnePhaseTwoMenu() {
int userChoice;
do {
userChoice = getUserMenuChoicePhase1();
switch (userChoice) {
case 1:
optionOneInputOutput();
break;
case 2:
optionTwoRepresentative();
break;
case 3:
optionThreeRepresentative();
break;
}
} while (userChoice != 4);
}
void optionOneInputOutput() {
cout << "OPTION 1:" << endl;
double x1, y1, x2, y2;
double distance = 0;
double horizontalAngle = 0;
getXAndYCoordinates(x1, y1);//first point
getXAndYCoordinates(x2, y2);//second point
optionOneEngineer(x1, x2, y1, y2, &distance, &horizontalAngle);
cout << "Distance between point (" << x1 << "," << y1 << ") and " <<
"point (" << x2 << "," << y2 << "): " << distance << " Feet" << endl;
cout << "Horizontal Angle in Degrees from point (" << x1 << "," << y1 << ") to " <<
"point (" << x2 << "," << y2 << "): " << horizontalAngle << "°" << endl << endl;
}
void optionTwoRepresentative() {
cout << "OPTION 2:" <<
endl;
double angleOfElevation = getElevationAngle();
double velocity = getVelocity();
cout << "Your horizontal distance is " <<
optionTwoEngineer(angleOfElevation, velocity)
<< "Feet" << endl << endl;
}
void optionThreeRepresentative() {
cout << "OPTION 3:" << endl;
double x1, y1, x2, y2;
double horizontalAngle = getHorizontalAngle();
double distance = getDistance();
getXAndYCoordinates(x1, y1);
optionThreeEngineer(x1, y1, x2, y2, horizontalAngle, distance);
cout << "Given starting point (" << x1 << "," << y1 << ")" << endl;
cout << "and given horizontal angle " << horizontalAngle << "° " << endl
<< "and given distance " << distance << " feet" << endl
<< "we get destination point (" << x2 << "," << y2 << ")"
<< endl << endl;
}
void optionOneEngineer(double x1, double x2, double y1, double y2,
double *distance, double *horizontalAngle) {
double dx = (x2 - x1); //Difference between X coordinates
double dy = (y2 - y1); //Difference between Y coordinates
double angleInRadians;
*distance = sqrt(pow(dx, two()) + pow(dy, two()));
if (dx > 0) {
angleInRadians = atan(dy / dx);
} else if (dx < 0) {
angleInRadians = atan(dy / dx) + PI();
} else if (dx == 0 && dy >= 0) {
angleInRadians = PI() / 2;
} else {
angleInRadians = -PI() / 2;
}
*horizontalAngle = angleInRadians * (180 / PI());
}
void optionTwoInputAndOutput() {
cout << "OPTION 2: Artillery Table" << endl;
double angleOfElevation = getElevationAngle();
double velocity = getVelocity();
int velocityOrVerticalAngle = doesUserWantToIncrementVelocityOrVerticalAngle();
if (velocityOrVerticalAngle == 1) {
createAndDisplayArtilleryTable(getUserVelocityIncrement(),
angleOfElevation, velocity, velocityOrVerticalAngle);
} else {
createAndDisplayArtilleryTable(getUserVerticalAngleIncrement(),
angleOfElevation, velocity, velocityOrVerticalAngle);
}
}
double optionTwoEngineer(double elevationAngle, double velocity) {
double elevationAngleInRads = elevationAngle * (PI() / 180);
double initialVelocity = velocity * feetPerMile() / secondsPerHour();
return pow(initialVelocity, two()) * sin(two() *
elevationAngleInRads) /
gravitationalVelocity();
}
void optionThreeInputOutput() {
cout << "OPTION 3: TARGET PRACTICE" << endl;
double x1, y1, x2, y2;
double horizontalAngle, verticalAngle, velocity, distance;
double tempHorizontalAngle, destinationX, destinationY;
x1 = 2500;
y1 = 0;
int numOfShots = 0, numOfHits = 0;
do {
x2 = getRandomNumber();
y2 = getRandomNumber();
int radius = getRadiusFromGameMode
(doesUserWantOptionThreeInEasyMediumOrHardMode());
if (doesUserWantCheatMode() == 1) {
optionThreeCheatMode(x1, x2, y1, y2);
}
cout << "You are at coordinate (" << x1 << "," << y1 << ")\n";
cout << "Your target is at coordinate (" << x2 << "," << y2 << ")\n\n";
horizontalAngle = getHorizontalAnglePhaseTwo();
verticalAngle = getVerticalAngle();
velocity = getVelocity();
int didUserHitTarget = targetPracticeCalculations(x1, x2, y1, y2,
horizontalAngle,
verticalAngle,
velocity, radius);
if (didUserHitTarget == 1) {
cout << "BOOM! you hit the target\n" << endl;
numOfShots++;
numOfHits++;
} else {
optionThreeEngineer(x1, y1, destinationX, destinationY, horizontalAngle,
distance);
optionOneEngineer(destinationX, x2, destinationY, y2,
&distance, &tempHorizontalAngle);
cout << "You missed your shot\n"
"You were " << distance << " Feet away from target\n" << endl;
numOfShots++;
}
} while (doesUserWantToQuit() != 'q');
cout << "You shot " << numOfShots << " and hit " <<
numOfHits << " of them!\n" << endl;
}
int targetPracticeCalculations(double x1, double x2, double y1, double y2,
double horizontalAngle, double verticalAngle,
double velocity, int radius) {
double tempHorizontalAngle;
double distance;
optionThreeEngineer(x1, y1, x2, y2, horizontalAngle,
optionTwoEngineer(verticalAngle, velocity));
optionOneEngineer(x2, x1, y2, y1, &distance, &tempHorizontalAngle);
if (distance <= radius) {
return 1;
}
return 0;
}
double getHorizontalAnglePhaseTwo() {
double horizontalAngle;
do {
cout << "Enter the direction of the barrel (horizontal angle: " <<
"0 to 180 degrees) inclusive" << endl;
cin >> horizontalAngle;
} while (horizontalAngle <= -1 || horizontalAngle >= 181);
return horizontalAngle;
}
char doesUserWantToQuit() {
char wantToQuit;
cout << "Would you like to take another shot or\n"
"would you like to go back to the MAINMENU\n"
"Enter 'q' to quit or any other character to play again\n" << endl;
cin >> wantToQuit;
return wantToQuit;
}
double getVerticalAngle() {
double verticalAngle;
do {
cout << "enter the elevation of the barrel (vertical angle: "
"0 to 90 degrees)" << endl;
cin >> verticalAngle;
} while (verticalAngle < 0 || verticalAngle > 90);
return verticalAngle;
}
void optionThreeEngineer(double x1, double y1, double &x2, double &y2,
double horizontalAngle, double distance) {
double horizontalAngleInRads = horizontalAngle * PI() / 180;
double dx = distance * cos(horizontalAngleInRads);
double dy = distance * sin(horizontalAngleInRads);
x2 = x1 + dx;
y2 = y1 + dy;
}
int getRadiusFromGameMode(int gameMode) {
if (gameMode == 1) {
return 100;
} else if (gameMode == 2) {
return 25;
}
return 5;
}
int doesUserWantCheatMode() {
int userChoice;
do {
cout << "Do you want to play in cheat mode?\n"
"(1) Yes\n"
"(2) No" << endl;
cin >> userChoice;
} while (userChoice != 1 && userChoice != 2);
return userChoice;
}
int doesUserWantOptionThreeInEasyMediumOrHardMode() {
int mode;
do {
cout << "Enter:\n"
"(1) for EASY mode RADIUS 100 Feet\n"
"(2) for MEDIUM mode RADIUS 25 Feet\n"
"(3) for HARD mode RADIUS 5 Feet" << endl;
cin >> mode;
} while (mode != 1 && mode != 2 && mode != 3);
return mode;
}
void optionThreeCheatMode(double x1, double x2, double y1, double y2) {
double distance, horizontalAngle;
optionOneEngineer(x1, x2, y1, y2, &distance, &horizontalAngle);
cout << "Distance between the cannon and the target is: " << distance <<
"Feet" << endl;
cout << "Horizontal angle between the cannon and the target: " <<
horizontalAngle << "°" << endl;
}
int getRandomNumber() {
return rand() % 5001;
}
void getXAndYCoordinates(double &xCoordinate, double &yCoordinate) {
cout << "Enter X Coordinates in Feet " << endl;
cin >> xCoordinate;
cout << "Enter Y Coordinates in Feet " << endl;
cin >> yCoordinate;
}
int doesUserWantToIncrementVelocityOrVerticalAngle() {
int userInput;
do {
cout << "Would you like to increment \n"
"(1) For the Velocity \n"
"(2) For the Vertical angle \n" << endl;
cin >> userInput;
} while (userInput != 1 && userInput != 2);
return userInput;
}
double getUserVerticalAngleIncrement() {
double incrementAmount;
do {
cout << "Please Enter a number in degrees you want to increment the\n"
"vertical angle by:" << endl;
cin >> incrementAmount;
} while (incrementAmount <= 0);
return incrementAmount;
}
double getUserVelocityIncrement() {
double incrementAmount;
do {
cout << "Please Enter a number in FEET you want to increment the\n"
"velocity by:" << endl;
cin >> incrementAmount;
} while (incrementAmount <= 0);
return incrementAmount;
}
void createAndDisplayArtilleryTable(double incrementAmount, double verticalAngle,
double velocity, int velocityOrAngle) {
int rowAmount;
do {
cout << "How many rows would you like to see\n"
"If you want only 1 row, type \"1\"\n"
"For more, type your desired number of rows" << endl;
cin >> rowAmount;
} while (rowAmount < 0);
if (velocityOrAngle == 1) {
cout << "Velocity Distance" << endl;
cout << "(feet) (feet)" << endl;
if (rowAmount == 0) {
}
} else {
cout << "Angle Distance" << endl;
cout << "(degs) (feet)" << endl;
}
for (int i = 0; i < rowAmount; ++i) {
if (velocityOrAngle == 1) {
cout << velocity << " " <<
optionTwoEngineer(verticalAngle, velocity) << endl;
velocity += incrementAmount;
} else {
cout << verticalAngle << " " <<
optionTwoEngineer(verticalAngle, velocity) << endl;
verticalAngle += incrementAmount;
}
}
cout << "\n" << endl;
}
double getDistance() {
double distance;
do {
cout << "Enter a distance in FEET GREATER than 0 NOT INCLUSIVE:" << endl;
cin >> distance;
} while (distance <= 0);
return distance;
}
double getHorizontalAngle() {
double horizontalAngle;
do {
cout << "Enter a horizontal angle IN DEGREES(°) "
"\nbetween 0° to 180° INCLUSIVE:" << endl;
cin >> horizontalAngle;
} while (horizontalAngle < 0 || horizontalAngle > 360);
return horizontalAngle;
}
double getVelocity() {
double velocity;
do {
cout << "Enter a velocity in MPH GREATER than 0 NOT INCLUSIVE:" << endl;
cin >> velocity;
} while (velocity <= 0);
return velocity;
}
double getElevationAngle() {
double angleOfElevation;
do {
cout << "Enter an elevation angle IN DEGREES(°) "
"\nbetween 0° to 90° NOT inclusive:" << endl;
cin >> angleOfElevation;
} while (angleOfElevation <= 0 || angleOfElevation >= 90);
return angleOfElevation;
}
double gravitationalVelocity() {
return 32.172;
}
double PI() {
return 3.14159265359;
}
int getUserMenuChoice() {
int userMenuChoice;
do {
printIntroductionDialogue();
cin >> userMenuChoice;
} while (userMenuChoice < 1 || userMenuChoice > 4);
return userMenuChoice;
}
int getUserMenuChoicePhase1() {
int userMenuChoice;
do {
printPhase1MenuDialogue();
cin >> userMenuChoice;
} while (userMenuChoice < 1 || userMenuChoice > 4);
return userMenuChoice;
}
int feetPerMile() {
return 5280;
}
int secondsPerHour() {
return 3600;
}
int two() {
return 2;
}
void printIntroductionDialogue() {
cout << "Pick One of the four options:\n"
"(1) Gives you a menu with 3 options that run basic calculations.\n"
"(2) Generates a table of distances that a shot will travel\n"
"when fired from a cannon.\n"
"(3) Target practice: Lets you fire shots at a randomly assigned\n"
"target location. With three different modes:\n"
"EASY, MEDIUM, and HARD\n"
"And a special cheat mode\n"
"(4) quit\n"
"Enter a number 1 -> 4 inclusive\n";
}
void printPhase1MenuDialogue() {
cout << "Pick One of the four options:\n"
"(1) Given two points, we'll compute the distance between the two points,\n"
"and the horizontal angle from the first point to the second.\n"
"(2) Given the elevation angle and velocity,\n"
"we'll compute the (horizontal) distance an object travels.\n"
"(3) Given a starting point, a distance, and a horizontal angle,\n"
"we'll compute the destination point.\n"
"(4) Go back to the main Application\n"
"Enter a number 1 -> 4 inclusive\n";
}
void quit() {
cout << "\nThank you for using the Application";
} | 30.141544 | 92 | 0.58529 | [
"object"
] |
bc2d584be8473f3017e1cf436f194aa0617cfad4 | 2,414 | cpp | C++ | UVa 10039 - Railroads/sample/10039 - Railroads.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 10039 - Railroads/sample/10039 - Railroads.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 10039 - Railroads/sample/10039 - Railroads.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <iostream>
#include <string.h>
#include <map>
#include <queue>
using namespace std;
struct edge {
int to;
short startTime, endTime;
edge(int a, short b, short c):
to(a),startTime(b),endTime(c) {}
};
vector<edge> g[105];
short dist[2400][105];
void solve(char *name1, char *name2, int st, int ed, int st_time, int n) {
int i, j, k;
memset(dist, -1, sizeof(dist));
for(i = 0; i < g[st].size(); i++) {
if(g[st][i].startTime >= st_time) {
dist[g[st][i].endTime][g[st][i].to] =
max(dist[g[st][i].endTime][g[st][i].to], g[st][i].startTime);
}
}
for(i = st_time; i < 2400; i++) {
for(j = 0; j < n; j++) {
if(dist[i][j] == -1) continue;
for(k = 0; k < g[j].size(); k++) {
if(g[j][k].startTime >= i) {
dist[g[j][k].endTime][g[j][k].to] =
max(dist[g[j][k].endTime][g[j][k].to], dist[i][j]);
}
}
}
if(dist[i][ed] != -1) {
printf("Departure %04d %s\n", dist[i][ed], name1);
printf("Arrival %04d %s\n", i, name2);
return;
}
}
puts("No connection");
}
int main() {
int testcase, cases = 0;
int N, T, M;
int i, j, k;
scanf("%d", &testcase);
char cityName[1024], start[1024], end[1024];
while(testcase--) {
scanf("%d", &N);
map<string, int> R;
for(i = 0; i < N; i++) {
scanf("%s", &cityName);
R[cityName] = i;
g[i].clear();
}
scanf("%d", &T);
int x, y, ptime, time, startTime;
while(T--) {
scanf("%d", &M);
for(i = 0; i < M; i++) {
scanf("%d %s", &time, cityName);
y = R[cityName];
if(i && time >= ptime) {
g[x].push_back(edge(y, ptime, time));
}
x = y, ptime = time;
}
}
scanf("%d %s %s", &startTime, start, end);
x = R[start];
y = R[end];
printf("Scenario %d\n", ++cases);
solve(start, end, x, y, startTime, N);
puts("");
}
return 0;
}
/*
why use dp not short path algorithm?
for example. A-> B ->C
|----------------||---------------|
|-------------------||--------|
|------------------||---------|
*/
| 28.4 | 77 | 0.407208 | [
"vector"
] |
bc2fd17bc12112b5474041e1ecfdff8019e75b28 | 9,017 | cpp | C++ | Engine/Source/ThirdParty/Oculus/LibOVRMobile/LibOVRMobile_050/VRLib/jni/LibOVR/Src/Capture/src/OVR_Capture_Socket.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2019-05-28T06:58:19.000Z | 2019-05-28T07:55:01.000Z | vRLib/src/main/jni/LibOVR/Src/Capture/src/OVR_Capture_Socket.cpp | wilbown/freedomvr-gear | 5c49002c355f27264901fa2408a02c36e71b7299 | [
"MIT"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/ThirdParty/Oculus/LibOVRMobile/LibOVRMobile_050/VRLib/jni/LibOVR/Src/Capture/src/OVR_Capture_Socket.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | /************************************************************************************
PublicHeader: OVR.h
Filename : OVR_Capture_Socket.cpp
Content : Misc network communication functionality.
Created : January, 2015
Notes :
Copyright : Copyright 2015 Oculus VR, LLC. All Rights reserved.
************************************************************************************/
#include "OVR_Capture_Socket.h"
#include <string.h> // memset
namespace OVR
{
namespace Capture
{
SocketAddress SocketAddress::Any(UInt16 port)
{
SocketAddress addr;
addr.m_addr.sin_family = AF_INET;
addr.m_addr.sin_addr.s_addr = INADDR_ANY;
addr.m_addr.sin_port = htons(port);
return addr;
}
SocketAddress SocketAddress::Broadcast(UInt16 port)
{
SocketAddress addr;
addr.m_addr.sin_family = AF_INET;
addr.m_addr.sin_addr.s_addr = INADDR_BROADCAST;
addr.m_addr.sin_port = htons(port);
return addr;
}
SocketAddress::SocketAddress(void)
{
memset(&m_addr, 0, sizeof(m_addr));
}
Socket *Socket::Create(Type type)
{
Socket *newSocket = NULL;
#if defined(OVR_CAPTURE_POSIX)
int sdomain = 0;
int stype = 0;
int sprotocol = 0;
switch(type)
{
case Type_Stream:
sdomain = AF_INET;
stype = SOCK_STREAM;
sprotocol = IPPROTO_TCP;
break;
case Type_Datagram:
sdomain = AF_INET;
stype = SOCK_DGRAM;
sprotocol = 0;
break;
}
const int s = ::socket(sdomain, stype, sprotocol);
OVR_CAPTURE_ASSERT(s != s_invalidSocket);
if(s != s_invalidSocket)
{
#if defined(SO_NOSIGPIPE)
// Disable SIGPIPE on close...
const UInt32 value = 1;
::setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
#endif
// Create the Socket object...
newSocket = new Socket();
newSocket->m_socket = s;
}
#else
#error Unknown Platform!
#endif
return newSocket;
}
void Socket::Release(void)
{
delete this;
}
bool Socket::SetBroadcast(void)
{
#if defined(OVR_CAPTURE_POSIX)
const UInt32 broadcast = 1;
return ::setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) == 0;
#else
#error Unknown Platform!
#endif
}
bool Socket::Bind(const SocketAddress &addr)
{
#if defined(OVR_CAPTURE_POSIX)
return ::bind(m_socket, (const sockaddr*)&addr.m_addr, sizeof(addr.m_addr)) == 0;
#else
#error Unknown Platform!
#endif
}
bool Socket::Listen(UInt32 maxConnections)
{
#if defined(OVR_CAPTURE_POSIX)
return ::listen(m_socket, maxConnections) == 0;
#else
#error Unknown Platform!
#endif
}
Socket *Socket::Accept(SocketAddress &addr)
{
#if defined(OVR_CAPTURE_POSIX)
socklen_t addrlen = sizeof(addr.m_addr);
// Wait for connection... or socket shutdown...
fd_set readfd;
FD_ZERO(&readfd);
FD_SET(m_socket, &readfd);
FD_SET(m_recvPipe, &readfd);
const int sret = ::select((m_socket>m_recvPipe?m_socket:m_recvPipe)+1, &readfd, NULL, NULL, NULL);
// On error or timeout, abort!
if(sret <= 0)
return NULL;
// If we have been signaled to abort... then don't even try to accept...
if(FD_ISSET(m_recvPipe, &readfd))
return NULL;
// If the signal wasn't from the socket (WTF?)... then don't even try to accept...
if(!FD_ISSET(m_socket, &readfd))
return NULL;
// Finally... accept the pending socket that we know for a fact is pending...
Socket *newSocket = NULL;
int s = ::accept(m_socket, (sockaddr*)&addr.m_addr, &addrlen);
if(s != s_invalidSocket)
{
#if defined(SO_NOSIGPIPE)
// Disable SIGPIPE on close...
const UInt32 value = 1;
::setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
#endif
// Create the Socket object...
newSocket = new Socket();
newSocket->m_socket = s;
}
#else
#error Unknown Platform!
#endif
return newSocket;
}
void Socket::Shutdown(void)
{
#if defined(OVR_CAPTURE_POSIX)
::shutdown(m_socket, SHUT_RDWR);
// By writing into m_sendPipe and never reading from m_recvPipe, we are forcing all blocking select()
// calls to return that m_recvPipe is ready for reading...
if(m_sendPipe != -1)
{
const unsigned int dummy = 0;
::write(m_sendPipe, &dummy, sizeof(dummy));
}
#else
#error Unknown Platform!
#endif
}
bool Socket::Send(const void *buffer, UInt32 bufferSize)
{
OVR_CAPTURE_CPU_ZONE(Socket_Send);
#if defined(OVR_CAPTURE_POSIX)
const char *bytesToSend = (const char*)buffer;
int numBytesToSend = (int)bufferSize;
while(numBytesToSend > 0)
{
int flags = 0;
#if defined(MSG_NOSIGNAL)
flags = MSG_NOSIGNAL;
#endif
const int numBytesSent = ::send(m_socket, bytesToSend, numBytesToSend, flags);
if(numBytesSent >= 0)
{
bytesToSend += numBytesSent;
numBytesToSend -= numBytesSent;
}
else
{
// An error occured... just shutdown the socket because after this we are in an invalid state...
Shutdown();
return false;
}
}
return true;
#else
#error Unknown Platform!
#endif
}
bool Socket::SendTo(const void *buffer, UInt32 size, const SocketAddress &addr)
{
#if defined(OVR_CAPTURE_POSIX)
return ::sendto(m_socket, buffer, size, 0, (const sockaddr*)&addr.m_addr, sizeof(addr.m_addr)) != -1;
#else
#error Unknown Platform!
#endif
}
UInt32 Socket::Receive(void *buffer, UInt32 size)
{
#if defined(OVR_CAPTURE_POSIX)
const ssize_t r = ::recv(m_socket, buffer, (size_t)size, 0);
return r>0 ? (UInt32)r : 0;
#else
#error Unknown Platform!
#endif
}
Socket::Socket(void)
{
#if defined(OVR_CAPTURE_POSIX)
m_socket = s_invalidSocket;
m_sendPipe = -1;
m_recvPipe = -1;
int p[2];
if(::pipe(p) == 0)
{
m_recvPipe = p[0];
m_sendPipe = p[1];
}
#else
#error Unknown Platform!
#endif
}
Socket::~Socket(void)
{
#if defined(OVR_CAPTURE_POSIX)
if(m_socket != s_invalidSocket)
{
Shutdown();
::close(m_socket);
}
if(m_recvPipe != -1) ::close(m_recvPipe);
if(m_sendPipe != -1) ::close(m_sendPipe);
#else
#error Unknown Platform!
#endif
}
ZeroConfigHost *ZeroConfigHost::Create(UInt16 udpPort, UInt16 tcpPort, const char *packageName)
{
OVR_CAPTURE_ASSERT(udpPort > 0);
OVR_CAPTURE_ASSERT(tcpPort > 0);
OVR_CAPTURE_ASSERT(udpPort != tcpPort);
OVR_CAPTURE_ASSERT(packageName);
Socket *broadcastSocket = Socket::Create(Socket::Type_Datagram);
if(broadcastSocket && !broadcastSocket->SetBroadcast())
{
broadcastSocket->Release();
broadcastSocket = NULL;
}
if(broadcastSocket)
{
return new ZeroConfigHost(broadcastSocket, udpPort, tcpPort, packageName);
}
return NULL;
}
void ZeroConfigHost::Release(void)
{
delete this;
}
ZeroConfigHost::ZeroConfigHost(Socket *broadcastSocket, UInt16 udpPort, UInt16 tcpPort, const char *packageName)
{
m_socket = broadcastSocket;
m_udpPort = udpPort;
m_packet.magicNumber = m_packet.s_magicNumber;
m_packet.tcpPort = tcpPort;
strcpy(m_packet.packageName, packageName);
}
ZeroConfigHost::~ZeroConfigHost(void)
{
QuitAndWait();
if(m_socket)
m_socket->Release();
}
void ZeroConfigHost::OnThreadExecute(void)
{
const SocketAddress addr = SocketAddress::Broadcast(m_udpPort);
while(!QuitSignaled())
{
if(!m_socket->SendTo(&m_packet, sizeof(m_packet), addr))
{
// If an error occurs, just abort the broadcast...
break;
}
sleep(1); // sleep for 1 second before the next broadcast...
}
m_socket->Shutdown();
}
} // namespace Capture
} // namespace OVR
| 28.266458 | 116 | 0.550183 | [
"object"
] |
bc3680b26c437cc7167d0cc99f1ede04295608b9 | 3,345 | cpp | C++ | 2020/13day/cpp/task2.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | 2 | 2018-12-09T16:00:09.000Z | 2018-12-09T17:56:15.000Z | 2020/13day/cpp/task2.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | null | null | null | 2020/13day/cpp/task2.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: task2.cpp
*
* Description: Advent of Code 2020 - Day 13
*
* Version: 0.1.0
* Created: 13.12.2020
*
* Author: Michał Zagórski (zagura), <zagura6@gmail.com>
*
* =====================================================================================
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <array>
#include <map>
#include <vector>
#include <cstdint>
using std::string;
using std::vector;
using std::array;
using std::map;
using std::stringstream;
using std::pair;
using ull = unsigned long long int;
bool check_contest(const vector<pair<int, int>>& buses,
ull current_time) {
for (const auto& [offset, id]: buses) {
if ((current_time + offset) % id != 0) {
return false;
}
}
return true;
}
/// Buses: vector<pair<int, int>> of elements [offset, id]
ull get_time(const vector<pair<int, int>>& buses) {
/// Stage 1: Prepare modulo values from vector
vector<ull> modulos {};
modulos.reserve(buses.size());
for (const auto&[offset, id]: buses) {
modulos.push_back(((buses.size() * id) - offset) % id);
}
/// Stage 2
ull base = buses[0].second;
ull rest = 0;
for (size_t i = 1; i < modulos.size(); i++) {
ull tmp_base = buses[i].second;
::printf("Modulos: [%zu] = %llu, buses[i] = { %d, %d }\n", i, modulos[i],
buses[i].first, buses[i].second);
for (ull j = 0; j < tmp_base; j++) {
ull mod = (base * j) + rest;
if (mod % tmp_base == modulos[i]) {
rest = mod;
base *= tmp_base;
break;
}
}
::printf("Base: %llu, rest: %llu\n", base, rest);
}
return rest;
}
int main(int argc, char* argv[]) {
std::ifstream input { "input.in" };
if (argc == 2) {
input = std::ifstream { argv[1] };
}
if (!input.good()) {
::fprintf(stderr, "Cannot open input file\n");
return 2;
}
int result = 0;
string line {};
getline(input, line);
int my_arrival = std::stoi(line);
vector<int> bus_times {};
vector<std::pair<int, int>> contest_buses {};
int bus_order_no = 0;
for(string t; getline(input, t, ','); bus_order_no++) {
if ((not t.empty()) and t.front() != 'x') {
bus_times.push_back(std::stoi(t));
contest_buses.emplace_back(bus_order_no, std::stoi(t));
}
}
std::sort(bus_times.begin(), bus_times.end());
int minimum_departure_time = my_arrival + 2 * bus_times.back();
int choosen_bus = 0;
// Part 1
for (auto& time: bus_times) {
int departure_time = my_arrival;
if (my_arrival % time != 0) {
departure_time = departure_time + time - (my_arrival % time);
}
if (departure_time < minimum_departure_time) {
minimum_departure_time = departure_time;
choosen_bus = time;
}
}
result = (minimum_departure_time - my_arrival) * choosen_bus;
::printf("Task 1 result: %d\n", result);
// Part 2
::printf("Task 2 result: %llu\n", get_time(contest_buses));
return 0;
}
| 28.836207 | 88 | 0.521674 | [
"vector"
] |
bc386735d98c85da1f9a27f688ce079a9e87cfaa | 4,893 | cpp | C++ | src/ampa_receptor.cpp | anupgp/astron | 5ef1b113b5025f5e0477a1fb2b5202fadbc5335c | [
"MIT"
] | null | null | null | src/ampa_receptor.cpp | anupgp/astron | 5ef1b113b5025f5e0477a1fb2b5202fadbc5335c | [
"MIT"
] | null | null | null | src/ampa_receptor.cpp | anupgp/astron | 5ef1b113b5025f5e0477a1fb2b5202fadbc5335c | [
"MIT"
] | null | null | null | // Time-stamp: <2019-01-05 16:43:42 macbookair>
// Units: all SI units - seconds, Volts, Ampere, Meters, Simenes, Farads
// Description: Generates AMPA receptor currents for a given glutamate concentration
// Note: The binding and unbinding of glutamate at the receptor will change local glutamate concentration. Currently this is not taken into account.
// Ref: Peter Jonas & Sakmann 1993
#include <vector>
#include <iostream>
#include <cmath>
#include "include/new_insilico.hpp"
#include "data_types.hpp"
#include "physical_constants.hpp"
#include "ampa_receptor.hpp"
namespace consts=astron::phy_const;
void ampa_receptor::current(state_type &variables, state_type &dxdt, const double t, unsigned index)
{
// Get indices of all pre cells that form synapses with this cell and has glu_ext variable declared
auto glu_ext_indices = newinsilico::get_pre_neuron_indices(index, "glu_ext");
// Sum up all glu_ext from all the pre_neuron synapses
auto glu_ext = 0.0;
for(unsigned iter = 0; iter < glu_ext_indices.size(); ++iter) {
glu_ext = glu_ext + std::max(variables[glu_ext_indices[iter]],0.0);
}
// Get post_neuron variable index
unsigned V_index = newinsilico::get_neuron_index(index, "V");
unsigned C0_index = newinsilico::get_neuron_index(index, "ampar_C0");
unsigned C1_index = newinsilico::get_neuron_index(index, "ampar_C1");
unsigned C2_index = newinsilico::get_neuron_index(index, "ampar_C2");
unsigned C3_index = newinsilico::get_neuron_index(index, "ampar_C3");
unsigned C4_index = newinsilico::get_neuron_index(index, "ampar_C4");
unsigned C5_index = newinsilico::get_neuron_index(index, "ampar_C5");
unsigned O_index = newinsilico::get_neuron_index(index, "ampar_O");
// Set lower limits on variable values
variables[C0_index] = std::max<double>(variables[C0_index],0.0);
variables[C1_index] = std::max<double>(variables[C1_index],0.0);
variables[C2_index] = std::max<double>(variables[C2_index],0.0);
variables[C3_index] = std::max<double>(variables[C3_index],0.0);
variables[C4_index] = std::max<double>(variables[C4_index],0.0);
variables[C5_index] = std::max<double>(variables[C5_index],0.0);
variables[O_index] = std::max<double>(variables[O_index],0.0);
// Get parameter values
double E_ampar = newinsilico::neuron_value(index, "E_ampar");
double G_ampar = newinsilico::neuron_value(index, "G_ampar");
double n_ampar = newinsilico::neuron_value(index, "n_ampar");
double k1 = newinsilico::neuron_value(index, "ampar_k1");
double k1b = newinsilico::neuron_value(index, "ampar_k1b");
double k2 = newinsilico::neuron_value(index, "ampar_k2");
double k2b = newinsilico::neuron_value(index, "ampar_k2b");
double k3 = newinsilico::neuron_value(index, "ampar_k3");
double k3b = newinsilico::neuron_value(index, "ampar_k3b");
double a = newinsilico::neuron_value(index, "ampar_a");
double b = newinsilico::neuron_value(index, "ampar_b");
double a1 = newinsilico::neuron_value(index, "ampar_a1");
double b1 = newinsilico::neuron_value(index, "ampar_b1");
double a2 = newinsilico::neuron_value(index, "ampar_a2");
double b2 = newinsilico::neuron_value(index, "ampar_b2");
double a3 = newinsilico::neuron_value(index, "ampar_a3");
double b3 = newinsilico::neuron_value(index, "ampar_b3");
double a4 = newinsilico::neuron_value(index, "ampar_a4");
double b4 = newinsilico::neuron_value(index, "ampar_b4");
// Get variable values
double V = variables[V_index];
double C0 = variables[C0_index];
double C1 = variables[C1_index];
double C2 = variables[C2_index];
double C3 = variables[C3_index];
double C4 = variables[C4_index];
double C5 = variables[C5_index];
double O = variables[O_index];
// dxdt values
dxdt[C0_index] = (-C0 * glu_ext * k1) + (C1 * k1b);
dxdt[C1_index] = (-C1 * glu_ext * k2) + (C2 * k2b) + (-C1 * a1) + (C3 * b1) + (-C1 * k1b) + (C0 * glu_ext * k1);
dxdt[C2_index] = (-C2 * a) + (O * b) + (-C2 * a2) + (C4 * b2) + (-C2 * k2b) + (C1 * glu_ext * k2);
dxdt[C3_index] = (-C3 * b1) + (C1 * a1) + (-C3 * glu_ext * k3) + (C4 * k3b);
dxdt[C4_index] = (-C4 * a4) + (C5 * b4) + (-C4 * k3b) + (C3 * glu_ext * k3) + (-C4 * b2) + (-C2 * a2);
dxdt[C5_index] = (-C5 * b4) + (C4 * a4) + (-C5 * b3) + (O * a3);
dxdt[O_index] = (-O * b) + (C2 * a) + (-O * a3) + (C5 * b3);
// double ampar_glu_flux = (-C0 * glu_ext * k1) + (C1 * k1b) + (-C1 * glu_ext * k2) + (C2 * k2b) + (-C3 * glu_ext * k3) + (C4 * k3b);
double fraction_of_open_channels = (O/(C0 + C1 + C2 + C3 + C4 + C5 + O));
double I_ampar = G_ampar * fraction_of_open_channels * (V - E_ampar) * n_ampar;
newinsilico::neuron_value(index, "I_ampar", I_ampar);
newinsilico::neuron_value(index, "ampar_open_fraction", fraction_of_open_channels);
newinsilico::neuron_value(index, "ampar_glu_flux", 0); // Note: needs to be modified as explained at the top!
};
| 45.728972 | 150 | 0.692213 | [
"vector"
] |
bc43906c7bb4ac353457dd2d183de2b8133adda6 | 6,627 | cpp | C++ | unittest/CppUnitLite/Actor.cpp | szk/reprize | a827aa0247f7954f9f36ae573f97db1397645bf5 | [
"BSD-2-Clause"
] | null | null | null | unittest/CppUnitLite/Actor.cpp | szk/reprize | a827aa0247f7954f9f36ae573f97db1397645bf5 | [
"BSD-2-Clause"
] | null | null | null | unittest/CppUnitLite/Actor.cpp | szk/reprize | a827aa0247f7954f9f36ae573f97db1397645bf5 | [
"BSD-2-Clause"
] | 1 | 2019-03-11T20:58:41.000Z | 2019-03-11T20:58:41.000Z | #include "Common.hpp"
#include "VFS.hpp"
#include "Body.hpp"
#include "scene/Cell.hpp"
#include "Script.hpp"
#include "Actor.hpp"
using namespace reprize;
using namespace std;
using namespace phy;
using namespace res;
Actor::Actor(Str name_, Model* mdl_, Body* body_, Script* script_)
: Entity(name_, new Matter(mdl_)), body(body_), here(NULL), script(NULL),
step(1.0), attached(false),
forward_toggle(false), back_toggle(false), right_toggle(false),
left_toggle(false), up_toggle(false), down_toggle(false),
attack_toggle(false), kf_cmd(KF_CTRL_WAIT)
{
attach();
cmd_off_all(Str());
}
Actor::Actor(const Actor& src_)
: Entity(src_),
body(src_.body), here(NULL), script(src_.script),
step(1.0), attached(false),
forward_toggle(false), back_toggle(false), right_toggle(false),
left_toggle(false), up_toggle(false), down_toggle(false),
attack_toggle(false), kf_cmd(KF_CTRL_WAIT)
{
attach();
cmd_off_all(Str());
}
Actor::~Actor(void)
{
}
const bool Actor::Put(Node* node_)
{
if (dynamic_cast<Body*>(node_)) { body = dynamic_cast<Body*>(node_); }
else if (dynamic_cast<Script*>(node_))
{ script = dynamic_cast<Script*>(node_); }
return Entity::Put(node_);
}
Actor* Actor::Clone(void) const
{
return new Actor(*this);
}
Body* Actor::get_body(void)
{
return body;
}
void Actor::update_body(void)
{
collider.clear();
}
void Actor::set_collider(Actor* actor_)
{
collider.push_back(actor_);
}
void Actor::eval(const Matter* parent_mtt_)
{
// move (local coordinates)
if (!dst_trans.is_origin())
{
Vec3 wld_trans(dst_trans.get_x(), dst_trans.get_z(), dst_trans.get_y());
Mtx44 n_mtx;
n_mtx.pos(wld_trans);
// n_mtx.rotate(90, 0, 0);
set_keyframe(KF_PROP_COORDINATE, false, 1, n_mtx.get_pos());
}
if (NULL != body) { update_body(); }
if (NULL != script)
{
if (kf[kf_cmd].get_interval() == 0)
{
script->NextKf();
if (script->IsDoneKf()) { script->FirstKf(); }
kf_cmd = script->CurrentKf().get_cmd();
set_keyframe(script->CurrentKf());
g_log->printf("script:%d, %d", kf_cmd, kf[kf_cmd].get_interval());
}
}
// attack
Entity::eval(parent_mtt_);
}
typedef Command<Actor> ActCmd;
void Actor::attach(void)
{
if (attached) { return; }
Put(new Node("+forward", new ActCmd(this, &Actor::cmd_on_forward)));
Put(new Node("+back", new ActCmd(this, &Actor::cmd_on_back)));
Put(new Node("+right", new ActCmd(this, &Actor::cmd_on_right)));
Put(new Node("+left", new ActCmd(this, &Actor::cmd_on_left)));
Put(new Node("+up", new ActCmd(this, &Actor::cmd_on_up)));
Put(new Node("+down", new ActCmd(this, &Actor::cmd_on_down)));
Put(new Node("+attack", new ActCmd(this, &Actor::cmd_on_attack)));
Put(new Node("+all", new ActCmd(this, &Actor::cmd_on_all)));
Put(new Node("-forward", new ActCmd(this, &Actor::cmd_off_forward)));
Put(new Node("-back", new ActCmd(this, &Actor::cmd_off_back)));
Put(new Node("-right", new ActCmd(this, &Actor::cmd_off_right)));
Put(new Node("-left", new ActCmd(this, &Actor::cmd_off_left)));
Put(new Node("-up", new ActCmd(this, &Actor::cmd_off_up)));
Put(new Node("-down", new ActCmd(this, &Actor::cmd_off_down)));
Put(new Node("-attack", new ActCmd(this, &Actor::cmd_off_attack)));
Put(new Node("-all", new ActCmd(this, &Actor::cmd_off_all)));
Put(new Node("pos", new ActCmd(this, &Actor::cmd_pos)));
Put(new Node("quat", new ActCmd(this, &Actor::cmd_quat)));
Put(new Node("color", new ActCmd(this, &Actor::cmd_color)));
attached = true;
}
void Actor::detach(void)
{
if (!attached) { return; }
attached = false;
}
Unit Actor::cmd_on_forward(const Str& arg_)
{
forward_toggle = true;
dst_trans.set_y(-step);
return 0;
}
Unit Actor::cmd_on_back(const Str& arg_)
{
back_toggle = true;
dst_trans.set_y(step);
return 0;
}
Unit Actor::cmd_on_right(const Str& arg_)
{
right_toggle = true;
dst_trans.set_x(step);
return 0;
}
Unit Actor::cmd_on_left(const Str& arg_)
{
left_toggle = true;
dst_trans.set_x(-step);
return 0;
}
Unit Actor::cmd_on_up(const Str& arg_)
{
up_toggle = true;
dst_trans.set_z(step);
return 0;
}
Unit Actor::cmd_on_down(const Str& arg_)
{
down_toggle = true;
dst_trans.set_z(-step);
return 0;
}
Unit Actor::cmd_on_attack(const Str& arg_)
{
attack_toggle = true;
mtt->get_c_mtx().debug();
return 0;
}
Unit Actor::cmd_on_all(const Str& arg_)
{
forward_toggle = back_toggle = right_toggle = left_toggle =
up_toggle = down_toggle = attack_toggle = true;
dst_trans.set(0, 0, 0);
return 0;
}
Unit Actor::cmd_off_forward(const Str& arg_)
{
forward_toggle = false;
if (back_toggle) { cmd_on_back(def_arg); }
else { dst_trans.set_y(0); }
return 0;
}
Unit Actor::cmd_off_back(const Str& arg_)
{
back_toggle = false;
if (forward_toggle) { cmd_on_forward(def_arg); }
else { dst_trans.set_y(0); }
return 0;
}
Unit Actor::cmd_off_right(const Str& arg_)
{
right_toggle = false;
if (left_toggle) { cmd_on_left(def_arg); }
else { dst_trans.set_x(0); }
return 0;
}
Unit Actor::cmd_off_left(const Str& arg_)
{
left_toggle = false;
if (right_toggle) { cmd_on_right(def_arg); }
else { dst_trans.set_x(0); }
return 0;
}
Unit Actor::cmd_off_up(const Str& arg_)
{
up_toggle = false;
if (down_toggle) { cmd_on_down(def_arg); }
else { dst_trans.set_z(0); }
return 0;
}
Unit Actor::cmd_off_down(const Str& arg_)
{
down_toggle = false;
if (up_toggle) { cmd_on_up(def_arg); }
else { dst_trans.set_z(0); }
return 0;
}
Unit Actor::cmd_off_attack(const Str& arg_)
{
attack_toggle = false;
return 0;
}
Unit Actor::cmd_off_all(const Str& arg_)
{
forward_toggle = back_toggle = right_toggle = left_toggle =
up_toggle = down_toggle = attack_toggle = false;
dst_trans.set(0, 0, 0);
return 0;
}
Unit Actor::cmd_pos(const Str& arg_)
{
if (arg_.empty()) { return mtt->get_c_mtx().get_pos().get_x(); }
Vec3 vec(arg_);
Entity::set_rel_pos(vec);
return 1;
}
Unit Actor::cmd_quat(const Str& arg_)
{
return mtt->get_c_mtx().get_quat().get_x();
}
Unit Actor::cmd_color(const Str& arg_)
{
if (arg_.empty()) { return mtt->get_c_mtx().get_pos().get_x(); }
Vec3 vec(arg_);
Entity::set_color(vec);
cerr << this << endl;
return 1;
}
| 23.752688 | 80 | 0.631206 | [
"model"
] |
a4bf4fe6032133e614838af6ee635fa5dc166c5e | 4,297 | hxx | C++ | com/ole32/com/objact/smstg.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/objact/smstg.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/objact/smstg.hxx | 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, 1992 - 1993.
//
// File: smstg.hxx
//
// Contents: Declaration for class to handle marshaled data as stg.
//
// Classes: CSafeMarshaledStg
// CSafeStgMarshaled
//
// Functions: CSafeMarshaledStg::operator->
// CSafeMarshaledStg::IStorage*
// CSafeStgMarshaled::operator->
// CSafeStgMarshaled::IStorage*
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
#ifndef __SMSTG_HXX__
#define __SMSTG_HXX__
#include <iface.h>
//+-------------------------------------------------------------------------
//
// Class: CSafeMarshaledStg (smstg)
//
// Purpose: Handle bookkeeping of translating a marshaled buffer into
// and IStorage
//
// Interface: operator-> - make class act like a pointer to an IStorage
// operator IStorage* - convert object into ptr to IStorage
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
class CSafeMarshaledStg
{
public:
CSafeMarshaledStg(InterfaceData *pIFD, HRESULT& hr);
~CSafeMarshaledStg(void);
IStorage * operator->(void);
operator IStorage*(void);
private:
IStorage * _pstg;
};
//+-------------------------------------------------------------------------
//
// Member: CSafeMarshaledStg::operator->
//
// Synopsis: Make object act like a pointer to an IStorage
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
inline IStorage *CSafeMarshaledStg::operator->(void)
{
return _pstg;
}
//+-------------------------------------------------------------------------
//
// Member: CSafeMarshaledStg::operator IStorage*
//
// Synopsis: Convert object to pointer to IStorage
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
inline CSafeMarshaledStg::operator IStorage*(void)
{
return _pstg;
}
//+-------------------------------------------------------------------------
//
// Class: CSafeStgMarshaled
//
// Purpose: Handle bookkeeping of creating a marshaled buffer from
// and IStorage
//
// Interface: operator-> - make class act like a pointer to marshaled data
// operator IStorage* - convert object into ptr to marshaled data
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
class CSafeStgMarshaled
{
public:
CSafeStgMarshaled(IStorage *pstg, DWORD dwDestCtx, HRESULT& hr);
~CSafeStgMarshaled(void);
InterfaceData *operator->(void);
operator InterfaceData*(void);
operator MInterfacePointer *(void);
private:
InterfaceData *_pIFD;
};
//+-------------------------------------------------------------------------
//
// Member: CSafeStgMarshaled::operator->
//
// Synopsis: Make object into pointer to the marshal buffer
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
inline InterfaceData *CSafeStgMarshaled::operator->(void)
{
return _pIFD;
}
//+-------------------------------------------------------------------------
//
// Member: CSafeStgMarshaled::operator InterfaceData*
//
// Synopsis: Convert object to pointer to marshal buffer
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
inline CSafeStgMarshaled::operator InterfaceData*(void)
{
return _pIFD;
}
//+-------------------------------------------------------------------------
//
// Member: CSafeStgMarshaled::operator MInterfacePointer*
//
// Synopsis: Convert object to pointer to marshal buffer
//
// History: 14-May-93 Ricksa Created
//
//--------------------------------------------------------------------------
inline CSafeStgMarshaled::operator MInterfacePointer*(void)
{
return (MInterfacePointer *) _pIFD;
}
#endif // __SMSTG_HXX__
| 24.414773 | 77 | 0.470095 | [
"object"
] |
a4bfe665da08f8b6d5d711e47e9d74af65e28857 | 9,985 | cpp | C++ | weex_core/Source/android/jsengine/bridge/script/script_side_in_queue.cpp | jwxbond/incubator-weex | eb3f28b1da57c9fbbd8efd0661c3affbad64178e | [
"Apache-2.0"
] | 2 | 2017-10-18T01:36:31.000Z | 2018-05-07T23:00:21.000Z | weex_core/Source/android/jsengine/bridge/script/script_side_in_queue.cpp | jwxbond/incubator-weex | eb3f28b1da57c9fbbd8efd0661c3affbad64178e | [
"Apache-2.0"
] | null | null | null | weex_core/Source/android/jsengine/bridge/script/script_side_in_queue.cpp | jwxbond/incubator-weex | eb3f28b1da57c9fbbd8efd0661c3affbad64178e | [
"Apache-2.0"
] | 5 | 2019-05-28T11:48:42.000Z | 2020-05-15T07:31:55.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
//
// Created by Darin on 2018/7/22.
//
#include "script_side_in_queue.h"
#include "android/jsengine/task/impl/init_framework_task.h"
#include "android/jsengine/task/impl/create_app_context_task.h"
#include "android/jsengine/task/impl/create_instance_task.h"
#include "android/jsengine/task/impl/call_js_on_app_context_task.h"
#include "android/jsengine/task/impl/destory_app_context_task.h"
#include "android/jsengine/task/impl/destory_instance_task.h"
#include "android/jsengine/task/impl/exe_js_on_app_with_result.h"
#include "android/jsengine/task/impl/update_global_config_task.h"
#include "android/jsengine/task/impl/ctime_callback_task.h"
#include "android/jsengine/task/impl/exe_js_services_task.h"
#include "android/jsengine/task/impl/exe_js_on_instance_task.h"
#include "android/jsengine/task/impl/exe_js_task.h"
#include "android/jsengine/task/impl/take_heap_snapshot.h"
#include "android/jsengine/task/impl/native_timer_task.h"
namespace weex {
namespace bridge {
namespace js {
int ScriptSideInQueue::InitFramework(
const char *script, std::vector<INIT_FRAMEWORK_PARAMS *> ¶ms) {
LOGD("ScriptSideInQueue::InitFramework");
// return runtime_->initFramework(String::fromUTF8(script), params);
weexTaskQueue_->addTask(new InitFrameworkTask(String::fromUTF8(script), params));
weexTaskQueue_->init();
return 1;
}
int ScriptSideInQueue::InitAppFramework(
const char *instanceId, const char *appFramework,
std::vector<INIT_FRAMEWORK_PARAMS *> ¶ms) {
LOGD("ScriptSideInQueue::InitAppFramework");
weexTaskQueue_->addTask(new InitFrameworkTask(String::fromUTF8(instanceId),
String::fromUTF8(appFramework), params));
return 1;
// return runtime_->initAppFramework(String::fromUTF8(instanceId),
// String::fromUTF8(appFramework), params);
}
int ScriptSideInQueue::CreateAppContext(const char *instanceId,
const char *jsBundle) {
LOGD("ScriptSideInQueue::CreateAppContext");
auto script = String::fromUTF8(jsBundle);
if(script.isEmpty()) {
return 0;
}
weexTaskQueue_->addTask(new CreateAppContextTask(String::fromUTF8(instanceId),
script));
return 1;
}
std::unique_ptr<WeexJSResult> ScriptSideInQueue::ExecJSOnAppWithResult(const char *instanceId,
const char *jsBundle) {
LOGD("ScriptSideInQueue::ExecJSOnAppWithResult");
WeexTask *task = new ExeJsOnAppWithResultTask(String::fromUTF8(instanceId),
String::fromUTF8(jsBundle));
auto future = std::unique_ptr<WeexTask::Future>(new WeexTask::Future());
task->set_future(future.get());
weexTaskQueue_->addTask(task);
return std::move(future->waitResult());
}
int ScriptSideInQueue::CallJSOnAppContext(
const char *instanceId, const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms) {
LOGD("ScriptSideInQueue::CallJSOnAppContext");
weexTaskQueue_->addTask(new CallJsOnAppContextTask(String::fromUTF8(instanceId),
String::fromUTF8(func), params));
return 1;
}
int ScriptSideInQueue::DestroyAppContext(const char *instanceId) {
LOGD("ScriptSideInQueue::DestroyAppContext");
weexTaskQueue_->addTask(new DestoryAppContextTask(String::fromUTF8(instanceId)));
return 1;
}
int ScriptSideInQueue::ExecJsService(const char *source) {
LOGD("ScriptSideInQueue::ExecJsService");
weexTaskQueue_->addTask(new ExeJsServicesTask(String::fromUTF8(source)));
return 1;
}
int ScriptSideInQueue::ExecTimeCallback(const char *source) {
LOGD("ScriptSideInQueue::ExecTimeCallback");
weexTaskQueue_->addTask(new CTimeCallBackTask(String::fromUTF8(source)));
return 1;
}
int ScriptSideInQueue::ExecJS(const char *instanceId, const char *nameSpace,
const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms) {
LOGD("ScriptSideInQueue::ExecJS");
ExeJsTask *task = new ExeJsTask(instanceId, params);
task->addExtraArg(String::fromUTF8(nameSpace));
task->addExtraArg(String::fromUTF8(func));
weexTaskQueue_->addTask(task);
return 1;
}
std::unique_ptr<WeexJSResult> ScriptSideInQueue::ExecJSWithResult(
const char *instanceId, const char *nameSpace, const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms) {
LOGD("ScriptSideInQueue::ExecJSWithResult");
ExeJsTask *task = new ExeJsTask(instanceId, params, true);
auto future = std::unique_ptr<WeexTask::Future>(new WeexTask::Future());
task->set_future(future.get());
task->addExtraArg(String::fromUTF8(nameSpace));
task->addExtraArg(String::fromUTF8(func));
weexTaskQueue_->addTask(task);
return std::move(future->waitResult());
}
void ScriptSideInQueue::ExecJSWithCallback(
const char *instanceId, const char *nameSpace, const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms, long callback_id) {
LOGD("ScriptSideInQueue::ExecJSWithCallback");
ExeJsTask *task = new ExeJsTask(instanceId, params, callback_id);
task->addExtraArg(String::fromUTF8(nameSpace));
task->addExtraArg(String::fromUTF8(func));
weexTaskQueue_->addTask(task);
}
int ScriptSideInQueue::CreateInstance(const char *instanceId, const char *func,
const char *script, const char *opts,
const char *initData,
const char *extendsApi, std::vector<INIT_FRAMEWORK_PARAMS*>& params) {
LOGD(
"CreateInstance id = %s, func = %s, script = %s, opts = %s, initData = "
"%s, extendsApi = %s",
instanceId, func, script, opts, initData, extendsApi);
auto string = String::fromUTF8(script);
if(string.isEmpty()) {
return 0;
}
CreateInstanceTask *task = new CreateInstanceTask(String::fromUTF8(instanceId),
string, params);
task->addExtraArg(String::fromUTF8(func));
task->addExtraArg(String::fromUTF8(opts));
task->addExtraArg(String::fromUTF8(initData));
task->addExtraArg(String::fromUTF8(extendsApi));
weexTaskQueue_->addTask(task);
return 1;
}
std::unique_ptr<WeexJSResult> ScriptSideInQueue::ExecJSOnInstance(const char *instanceId,
const char *script) {
LOGD("ScriptSideInQueue::ExecJSOnInstance");
ExeJsOnInstanceTask *task = new ExeJsOnInstanceTask(String::fromUTF8(instanceId),
String::fromUTF8(script));
weexTaskQueue_->addTask(task);
auto future = std::unique_ptr<WeexTask::Future>(new WeexTask::Future());
task->set_future(future.get());
return std::move(future->waitResult());
}
int ScriptSideInQueue::DestroyInstance(const char *instanceId) {
LOGD("ScriptSideInQueue::DestroyInstance instanceId: %s \n", instanceId);
weexTaskQueue_->addTask(new DestoryInstanceTask(String::fromUTF8(instanceId)));
return 1;
}
int ScriptSideInQueue::UpdateGlobalConfig(const char *config) {
LOGD("ScriptSideInQueue::UpdateGlobalConfig");
weexTaskQueue_->addTask(new UpdateGlobalConfigTask(String::fromUTF8(config)));
return 1;
}
} // namespace js
} // namespace bridge
} // namespace weex
| 45.386364 | 120 | 0.568052 | [
"vector"
] |
a4c03c73622b8e86514f207f27f9388912cc53c1 | 2,241 | cpp | C++ | LeetCode/C++/General/Easy/HouseRobber/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Easy/HouseRobber/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Easy/HouseRobber/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/*
* Approaches, from top-to-bottom:
*
* 1) Brute-force recursion, top-down: we either rob each house or we don't.
* This is based off of the inclusion-exclusion principle.
*
* Time complexity: O(2^n) [where n is the length of the input vector]
* Space complexity: O(2^n)
*
* 2) Memoized recursion, top-down: We still either rob or don't rob each house.
* However, we use a vector to cache our results as we go along.
*
* Time complexity: O(n)
* Space complexity: O(n)
*
* 3) Dynamic programming, bottom-up: we trade-in the recursion for a for-loop.
* Our base cases are handled by the first two iterations of the loop and the general case
* is handled by the remaining iterations.
*
* Time complexity: O(n)
* Space complexity: O(n)
*/
int helper(vector<int> & nums, int index, int n)
{
if(index==n-1)
{
return nums[index];
}
if(index==n-2)
{
return max(nums[n-2], nums[n-1]);
}
return max(helper(nums, index+2, n)+nums[index], helper(nums, index+1, n));
}
int memoization(vector<int> & nums, vector<int> & memo, int index, int n)
{
if(index==n-1)
{
return nums[index];
}
if(index==n-2)
{
return max(nums[n-2], nums[n-1]);
}
if(memo[index]!=-1)
{
return memo[index];
}
memo[index]=max(memoization(nums, memo, index+2, n)+nums[index], memoization(nums, memo, index+1, n));
return memo[index];
}
int rob(vector<int>& nums)
{
if(nums.empty())
{
return 0;
}
int n=int(nums.size());
vector<int> memo(n, -1);
int index=0;
//return helper(nums, index, n);
return memoization(nums, memo, index, n);
}
int rob(vector<int> & nums)
{
if(nums.empty())
{
return 0;
}
int n=int(nums.size());
vector<int> dp(n);
for(int index=0;index<n;++index)
{
if(index==0)
{
dp[index]=nums[index];
}
else if(index==1)
{
dp[index]=max(nums[index], nums[index-1]);
}
else
{
dp[index]=max(dp[index-2] + nums[index], dp[index-1]);
}
}
return dp[n-1];
} | 20.008929 | 106 | 0.569835 | [
"vector"
] |
a4c108569b02cee48dd5a1036c009a22f6565c38 | 27,239 | cpp | C++ | teleop_and_haptics/hviz/src/main.cpp | atp42/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | 3 | 2017-02-02T13:27:45.000Z | 2018-06-17T11:52:13.000Z | teleop_and_haptics/hviz/src/main.cpp | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | teleop_and_haptics/hviz/src/main.cpp | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | /*
* grasp_adjust_server
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Software License Agreement (BSD License)
*
*
* 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 Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
///\author Adam Leeper
///\brief Node for haptic interaction with a point cloud
#include "chai3d.h"
#include "CThreadWithArgument.h"
#include <ros/ros.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
#include <std_msgs/String.h>
#include <boost/bind.hpp>
#include <sensor_msgs/PointCloud2.h>
//#include <pcl/pcl_base.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl_ros/transforms.h>
#include <hviz/HapticsConfig.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
#include <stereo_msgs/DisparityImage.h>
#include <dynamic_reconfigure/server.h>
#include <object_manipulator/tools/shape_tools.h>
#include <iostream>
#include <fstream>
#include <queue>
#include "helpers.h"
#include "PointCloudObject.h"
#define PROF_ENABLED
#include <profiling/profiling.h>
PROF_DECLARE(TOTAL_TIMER)
PROF_DECLARE(FUNC_1)
//---------------------------------------------------------------------------
// DECLARED VARIABLES
//---------------------------------------------------------------------------
cWorld* world;
cCamera* camera;
cLight *light;
// a haptic device handler
cHapticDeviceHandler* handler;
cGeneric3dofPointer* tool;
cHapticDeviceInfo device_info;
// the implicit surface object
PointCloudObject* object = 0; //, *new_object = 0;
// label to show estimate of haptic update rate
cLabel* rateLabel;
double rateEstimate = 0;
double graphicRateEstimate = 0;
bool simulationRunning = false;
bool simulationFinished = false;
void hapticsDispatch(void *instance);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class HapticNode{
pcl::PointCloud<PointT> last_cloud_, cloud_in_;
ros::NodeHandle nh_, nh_pvt_;
// The input cloud
ros::Subscriber sub_cloud_;
ros::Subscriber sub_disparity_1_;
// A republished cloud for displaying the current haptic cloud
ros::Publisher pub_cloud_, pub_marker_cloud_;
// Publishers for markers (e.g. haptic tool)
ros::Publisher pub_marker_, pub_marker_array_;
// Publisher for string status data
ros::Publisher pub_status_;
// A timer callback
ros::Timer update_timer_;
ros::Timer slow_update_timer_;
std::string input_topic_;
std::string output_topic_;
tf::TransformListener tfl_;
tf::TransformBroadcaster tfb_;
//bool refresh_cloud;
ros::Time now_;
bool got_first_cloud_;
boost::mutex mutex_;
// ***** Dynamic reconfigure stuff *****
typedef hviz::HapticsConfig Config;
Config config_;
dynamic_reconfigure::Server<Config> dyn_srv;
dynamic_reconfigure::Server<Config>::CallbackType dyn_cb;
public:
/*!
* \brief Default contructor.
*
* This description is displayed lower in the doxygen as an extended description along with
* the above brief description.
*/
HapticNode(char* argv[]):
nh_("/")
, nh_pvt_("~")
, input_topic_("/cloud_in")
, output_topic_("/cloud_out")
//, dyn_srv(ros::NodeHandle("~config")),
{
got_first_cloud_ = false;
now_ = ros::Time::now() - ros::Duration(1.0);
// Clouds in and out
sub_cloud_ = nh_.subscribe<sensor_msgs::PointCloud2>
(input_topic_, 1, boost::bind(&HapticNode::cloudCallback,this, _1));
pub_cloud_ = nh_.advertise<sensor_msgs::PointCloud2>(output_topic_, 1);
pub_marker_cloud_ = nh_.advertise<visualization_msgs::MarkerArray>("/marker_cloud_array", 1);
// Disparity images in and out:
sub_disparity_1_ = nh_.subscribe<stereo_msgs::DisparityImage>
("/disparity_1", 1, boost::bind(&HapticNode::disparityCallback, this, _1));
// Marker topics
pub_marker_ = nh_.advertise<visualization_msgs::Marker>("/markers", 100);
pub_marker_array_ = nh_.advertise<visualization_msgs::MarkerArray>("/markers_array", 1);
// String status topic
pub_status_ = nh_pvt_.advertise<std_msgs::String>("status", 10);
// Create timer callback for auto-running of algorithm
update_timer_ = nh_.createTimer(ros::Duration(0.03333), boost::bind(&HapticNode::timerCallback, this));
slow_update_timer_ = nh_.createTimer(ros::Duration(0.5), boost::bind(&HapticNode::slowTimerCallback, this));
// This server is for the user to adjust the algorithm weights
dyn_cb = boost::bind( &HapticNode::dynamicCallback, this, _1, _2 );
dyn_srv.setCallback(dyn_cb);
// Set up the chai world and device
initializeHaptics();
ROS_INFO("Finished constructor!");
}
void initializeHaptics()
{
//-----------------------------------------------------------------------
// 3D - SCENEGRAPH
//-----------------------------------------------------------------------
// create a new world.
world = new cWorld();
// set the background color of the environment
// the color is defined by its (R,G,B) components.
world->setBackgroundColor(0.2, 0.2, 0.2);
// create a camera and insert it into the virtual world
camera = new cCamera(world);
world->addChild(camera);
// position and oriente the camera
camera->set( cVector3d (5.0, 0.0, 0.0), // camera position (eye)
cVector3d (0.0, 0.0, 0.0), // lookat position (target)
cVector3d (0.0, 0.0, 1.0)); // direction of the "up" vector
// set the near and far clipping planes of the camera
// anything in front/behind these clipping planes will not be rendered
camera->setClippingPlanes(0.01, 10.0);
// enable higher quality rendering for transparent objects
camera->enableMultipassTransparency(true);
// create a light source and attach it to the camera
light = new cLight(world);
camera->addChild(light); // attach light to camera
light->setEnabled(true); // enable light source
light->setPos(cVector3d( 3.0, 1.5, 2.0)); // position the light source
light->setDir(cVector3d(-2.0, 0.5, 1.0)); // define the direction of the light beam
// create a label that shows the haptic loop update rate
rateLabel = new cLabel();
rateLabel->setPos(8, 8, 0);
camera->m_front_2Dscene.addChild(rateLabel);
//-----------------------------------------------------------------------
// HAPTIC DEVICES / TOOLS
//-----------------------------------------------------------------------
ROS_INFO("Creating connection to device...");
// create a haptic device handler
handler = new cHapticDeviceHandler();
// get access to the first available haptic device
cGenericHapticDevice* hapticDevice;
handler->getDevice(hapticDevice, 0);
// retrieve information about the current haptic device
if (hapticDevice)
{
device_info = hapticDevice->getSpecifications();
}
// create a 3D tool and add it to the world
tool = new cGeneric3dofPointer(world);
tool->setHapticDevice(hapticDevice);
tool->start();
float workspace_radius = 0.25;
tool->setWorkspaceRadius(workspace_radius);
tool->setRadius(0.01);
printf("Device is %s\n", device_info.m_modelName.c_str());
if( !device_info.m_modelName.compare("PHANTOM Omni"))
tool->setPos(-workspace_radius/2.5, 0, 0);
else
tool->setPos(0, 0, 0);
world->addChild(tool);
double workspaceScaleFactor = tool->getWorkspaceScaleFactor();
//ROS_INFO("Tool has workspace scale factor %lf", workspaceScaleFactor);
double stiffnessMax = device_info.m_maxForceStiffness / workspaceScaleFactor;
object = new PointCloudObject(world);
object->addEffect(new cEffectSurface(object));
object->m_material.setStiffness(0.7 * stiffnessMax);
object->m_material.setDynamicFriction(0.2);
object->setUseVertexColors(true, false);
object->useDisplayList(false, true);
object->useVertexArrays(true, true);
object->m_tool = tool;
object->m_tag = 0;
object->setAsGhost(false);
object->m_configPtr = &config_;
// new_object = new PointCloudObject(world);
// new_object->addEffect(new cEffectSurface(object));
// new_object->m_material.setStiffness(0.9 * stiffnessMax);
// new_object->m_material.setDynamicFriction(0.2);
// new_object->setUseVertexColors(true, false);
// new_object->useDisplayList(false, true);
// new_object->useVertexArrays(true, true);
// new_object->m_tool = tool;
// new_object->m_tag = 1;
// new_object->setAsGhost(true);
// new_object->m_configPtr = &config_;
world->addChild(object);
// world->addChild(new_object);
//-----------------------------------------------------------------------
// START SIMULATION
//-----------------------------------------------------------------------
// simulation in now running
simulationRunning = true;
// create a thread which starts the main haptics rendering loop
cThreadWithArgument* hapticsThread = new cThreadWithArgument();
hapticsThread->set(hapticsDispatch, this, CHAI_THREAD_PRIORITY_HAPTICS);
}
private:
/*!
* \brief The timer callback sends graphical output to rviz.
*
* This description is displayed lower in the doxygen as an extended description along with
* the above brief description.
*/
void timerCallback()
{
if(!tool) return;
ros::Time time_now = ros::Time::now(); // use single time for all output
static bool firstTime = true;
static int counter = 0;
static cPrecisionClock pclock;
if(firstTime) // start a clock to estimate the rate
{
pclock.setTimeoutPeriodSeconds(1.0);
pclock.start(true);
firstTime = false;
}
// estimate the refresh rate and publish
++counter;
if (pclock.timeoutOccurred()) {
pclock.stop();
graphicRateEstimate = counter;
counter = 0;
pclock.start(true);
std_msgs::String msg;
char status_string[256];
sprintf(status_string, "Haptic rate: %.3f Graphics Rate: %.3f",
rateEstimate, graphicRateEstimate);
msg.data = status_string;
pub_status_.publish(msg);
}
// Transmit the visualizations of the tool/proxy
float proxy_radius = config_.tool_radius;
cVector3d pos = object->m_interactionProjectedPoint; //tool->getDeviceGlobalPos();
cVector3d HIP = tool->getDeviceGlobalPos();
cMatrix3d tool_rotation = tool->m_deviceGlobalRot;
if(false && device_info.m_sensedRotation)
{
object_manipulator::shapes::Mesh mesh;
mesh.dims = tf::Vector3(0.5, 0.5, 0.5);
mesh.frame.setRotation(chai_tools::cMatrixToTFQuaternion(tool_rotation));
mesh.frame.setOrigin(tf::Vector3(pos.x, pos.y, pos.z));
mesh.header.stamp = time_now;
mesh.header.frame_id = "/tool_frame";
mesh.use_embedded_materials = true;
mesh.mesh_resource = std::string("package://pr2_description/meshes/gripper_v0/gripper_palm.dae");
// std::string proximal_finger_string("package://pr2_description/meshes/gripper_v0/l_finger.dae");
// std::string distal_finger_string("package://pr2_description/meshes/gripper_v0/l_finger_tip.dae");
object_manipulator::drawMesh(pub_marker_, mesh, "gripper", 0, ros::Duration(), object_manipulator::msg::createColorMsg(1.0, 0.3, 0.7, 1.0));
}
else
{
object_manipulator::shapes::Sphere sphere;
sphere.dims = tf::Vector3(2*proxy_radius, 2*proxy_radius, 2*proxy_radius);
sphere.frame = tf::Transform(tf::Quaternion(0,0,0,1), tf::Vector3(pos.x, pos.y, pos.z));
sphere.header.frame_id = "/tool_frame";
sphere.header.stamp = time_now;
object_manipulator::drawSphere(pub_marker_, sphere, "proxy", 0, ros::Duration(), object_manipulator::msg::createColorMsg(1.0, 0.3, 0.7, 1.0));
//object_manipulator::shapes::Sphere sphere;
sphere.dims = tf::Vector3(1.9*proxy_radius, 1.9*proxy_radius, 1.9*proxy_radius);
sphere.frame = tf::Transform(tf::Quaternion(0,0,0,1), tf::Vector3(HIP.x, HIP.y, HIP.z));
sphere.header.frame_id = "/tool_frame";
sphere.header.stamp = time_now;
object_manipulator::drawSphere(pub_marker_, sphere, "HIP", 0, ros::Duration(), object_manipulator::msg::createColorMsg(1.0, 0.0, 0.0, 0.6));
}
object_manipulator::shapes::Cylinder box;
tf::Quaternion quat = chai_tools::cMatrixToTFQuaternion(object->tPlane->getRot());
box.frame.setRotation(quat);
box.frame.setOrigin(chai_tools::cVectorToTF(object->tPlane->getPos()) - 0.5*proxy_radius*box.frame.getBasis().getColumn(2));
box.dims = tf::Vector3(5*proxy_radius, 5*proxy_radius, 0.0015);
box.header.frame_id = "/tool_frame";
box.header.stamp = time_now;
if(object->m_interactionInside){
object_manipulator::drawCylinder(pub_marker_, box, "tPlane", 0, ros::Duration(), object_manipulator::msg::createColorMsg(0.2, 0.6, 1.0, 0.8), false);
}
else
object_manipulator::drawCylinder(pub_marker_, box, "tPlane", 0, ros::Duration(), object_manipulator::msg::createColorMsg(0.2, 0.6, 1.0, 0.8), true);
boost::mutex::scoped_lock lock(mutex_);
if(config_.publish_cloud)
{
if(object->last_normals->points.size() == object->last_points->points.size())
{
visualization_msgs::Marker marker;
marker.header = object->last_points->header;
marker.ns = "cloud";
marker.id = 0;
marker.type = visualization_msgs::Marker::SPHERE_LIST; // CUBE, SPHERE, ARROW, CYLINDER
marker.action = false?((int32_t)visualization_msgs::Marker::DELETE):((int32_t)visualization_msgs::Marker::ADD);
marker.lifetime = ros::Duration();
float scale = object->m_active_radius/2;
marker.scale = object_manipulator::msg::createVector3Msg(scale, scale, scale);
marker.color = object_manipulator::msg::createColorMsg(0.5, 0.5, 0.5,1.0);
float angle = time_now.toSec();
angle = config_.light_angle * M_PI/180.0;
tf::Vector3 light_source = tf::Vector3(0.1*cos(angle), 0.1*sin(angle), 0.3);
object_manipulator::shapes::Sphere sphere;
sphere.dims = tf::Vector3(0.02, 0.02, 0.02);
sphere.frame = tf::Transform(tf::Quaternion(0,0,0,1), light_source);
sphere.header.frame_id = "/tool_frame";
sphere.header.stamp = marker.header.stamp;
object_manipulator::drawSphere(pub_marker_, sphere, "light", 0, ros::Duration(), object_manipulator::msg::createColorMsg(1.0, 1.0, 1.0, 0.5));
for(int i = 0; i < object->last_points->points.size(); i++)
{
const PointT &pt = object->last_points->points[i];
const pcl::Normal &nl = object->last_normals->points[i];
tf::Vector3 point = tf::Vector3(pt.x, pt.y, pt.z);
tf::Vector3 N_vec = tf::Vector3(nl.normal[0], nl.normal[1], nl.normal[2]).normalized();
tf::Vector3 L_vec = (light_source - point).normalized();
tf::Vector3 color = fabs(L_vec.dot(N_vec))*tf::Vector3(1.0, 1.0, 1.0) + tf::Vector3(0.2, 0.2, 0.2);
//tf::Vector3 color = tf::Vector3(pt.x*pt.x, pt.y*pt.y, 1.0);
marker.colors.push_back(object_manipulator::msg::createColorMsg(color.x(), color.y(), color.z(), 1.0));;
marker.points.push_back(object_manipulator::msg::createPointMsg(pt.x, pt.y, pt.z));
}
//ROS_INFO("Publishing marker cloud with %d points!", marker.points.size());
pub_marker_.publish(marker);
}
sensor_msgs::PointCloud2 msg;
pcl::toROSMsg(*(object->last_points), msg);
msg.header.frame_id = "/tool_frame";
msg.header.stamp = time_now;
pub_cloud_.publish(msg);
}
}
void slowTimerCallback()
{
// visualization_msgs::Marker marker;
// marker.header = object->m_cloud_points->header;
// marker.ns = "cloud";
// marker.id = 0;
// marker.type = visualization_msgs::Marker::SPHERE_LIST; // CUBE, SPHERE, ARROW, CYLINDER
// marker.action = false?((int32_t)visualization_msgs::Marker::DELETE):((int32_t)visualization_msgs::Marker::ADD);
// //marker.lifetime = ros::Duration();
// float scale = config_.basis_radius/2;
// marker.scale = object_manipulator::msg::createVector3Msg(scale, scale, scale);
// marker.color = object_manipulator::msg::createColorMsg(1.0, 0.0, 0.0, 1.0);
//
// tf::Vector3 light_source = tf::Vector3(0.1, 0.1, 0.3);
// object_manipulator::shapes::Sphere sphere;
// sphere.dims = tf::Vector3(0.1, 0.1, 0.1);
// sphere.frame = tf::Transform(tf::Quaternion(0,0,0,1), light_source);
// sphere.header.frame_id = "/tool_frame";
// sphere.header.stamp = marker.header.stamp;
// object_manipulator::drawSphere(pub_marker_, sphere, "light", 0, ros::Duration(), object_manipulator::msg::createColorMsg(1.0, 1.0, 0.0, 1.0));
//
// for(int i = 0; i < object->m_cloud_points->points.size(); i++)
// {
// const PointT &pt = object->m_cloud_points->points[i];
// const pcl::Normal &nl = object->m_cloud_normals->points[i];
// tf::Vector3 point = tf::Vector3(pt.x, pt.y, pt.z);
// tf::Vector3 N_vec = tf::Vector3(nl.normal[0], nl.normal[1], nl.normal[2]);
// tf::Vector3 L_vec = (light_source - point).normalized();
// tf::Vector3 color = fabs(L_vec.dot(N_vec))*tf::Vector3(0.0, 0.0, 1.0) + tf::Vector3(1.0, 0.0, 0.0);
//// tf::Vector3 color = tf::Vector3(1.0, 0.2, 0.2);
// marker.colors.push_back(object_manipulator::msg::createColorMsg(color.x(), color.y(), color.z(), 1.0));
// marker.points.push_back(object_manipulator::msg::createPointMsg(pt.x, pt.y, pt.z));
// }
// ROS_INFO("Publishing marker cloud with %d points!", marker.points.size());
// pub_marker_.publish(marker);
}
/*!
* \brief The haptic update loop.
*
* This description is displayed lower in the doxygen as an extended description along with
* the above brief description.
*/
friend void hapticsDispatch(void *);
void updateHaptics(void)
{
// a clock to estimate the haptic simulation loop update rate
cPrecisionClock pclock;
pclock.setTimeoutPeriodSeconds(1.0);
pclock.start(true);
int counter = 0, loop_counter = 0;
// main haptic simulation loop
while(simulationRunning)
{
usleep(config_.haptics_sleep);
if(object->m_refresh_cloud)
{
// // Copy over state info from old object
// new_object->m_interactionInside = object->m_interactionInside;
// new_object->m_interactionProjectedPoint = object->m_interactionProjectedPoint;
// new_object->tPlane = object->tPlane;
// //new_object->tPlaneNormal = object->tPlaneNormal;
// new_object->m_shape = object->m_shape;
// new_object->m_showTangent = object->m_showTangent;
//
// PointCloudObject *temp = object;
// object = new_object;
// new_object = temp;
//
// object->setAsGhost(false);
// new_object->setAsGhost(true);
ros::WallTime begin = ros::WallTime::now();
object->applyLastCloud();
ROS_DEBUG_NAMED("time", "Applying cloud took %.3lf ms", (ros::WallTime::now() - begin).toSec()*1000.0);
//refresh_cloud = false;
}
object->m_material.setDynamicFriction(config_.dynamic_friction);
object->scaleZ = config_.scaleZ;
object->m_cloudType = config_.cloud_mode;
object->m_basisType = config_.basis_function;
// compute global reference frames for each object
world->computeGlobalPositions(true);
// update position and orientation of tool
tool->updatePose();
// compute interaction forces
tool->computeInteractionForces();
// send forces to device
tool->applyForces();
bool buttonState = false;
tool->getHapticDevice()->getUserSwitch(0, buttonState);
// This is how we move the workspace!
if(buttonState)
{
float translate_factor = 0.001;
cVector3d localPos = tool->getDeviceLocalPos();
if(sqrt(localPos.x*localPos.x + localPos.y*localPos.y) > 1.5){
camera->translate(translate_factor*cDot(localPos, cVector3d(1,0,0)),
translate_factor*cDot(localPos, cVector3d(0,1,0)),
0);
//m_cam.strafeRight(0.0005*cDot(localPos, cVector3d(0,1,0)));
//m_cam.moveForward(0.0005*cDot(localPos, cVector3d(-1,0,0)));
tool->m_lastComputedGlobalForce += 2*cVector3d(-localPos.x, -localPos.y, 0);
tool->applyForces();
}
}
// estimate the refresh rate
++counter;
if (pclock.timeoutOccurred()) {
pclock.stop();
rateEstimate = counter;
counter = 0;
pclock.start(true);
}
}
// exit haptics thread
simulationFinished = true;
}
/*!
* \brief Callback for receiving a point cloud.
*
* This description is displayed lower in the doxygen as an extended description along with
* the above brief description.
*/
void cloudCallback(const sensor_msgs::PointCloud2ConstPtr& input)
{
// const std::string& publisher_name = event.getPublisherName();
// ros::M_string connection_header = event.getConnectionHeader();
// ros::Time receipt_time = event.getReceiptTime();
// const std::string topic = connection_header["topic"];
// const sensor_msgs::PointCloud2& input = event.getMessage();
std::string topic = "none";
int cloud_size = input->width*input->height;
ROS_DEBUG_NAMED("haptics", "Got a cloud on topic %s in frame %s with %d points!",
topic.c_str(),
input->header.frame_id.c_str(),
cloud_size);
if(cloud_size == 0) return;
pcl::fromROSMsg(*input, last_cloud_);
if(last_cloud_.header.frame_id.compare("/tool_frame"))
{
// ROS_INFO("Transforming cloud with %d points from %s to %s.",
// (int)last_cloud_.points.size(), last_cloud_.header.frame_id.c_str(),
// "/world");
if(!tfl_.waitForTransform("/tool_frame", last_cloud_.header.frame_id,
last_cloud_.header.stamp, ros::Duration(2.0)) )
{
ROS_ERROR("Couldn't get transform for cloud, returning FAILURE!");
return;
}
pcl_ros::transformPointCloud("/tool_frame", last_cloud_, last_cloud_, tfl_);
}
//ROS_INFO("m_shape is %d", m_shape);
//if(new_object->m_shape == hviz::Haptics_CLOUD)
{
boost::mutex::scoped_lock lock(mutex_);
if(object->m_shape == hviz::Haptics_CLOUD)
object->createFromCloud(last_cloud_);
}
if(!got_first_cloud_){
got_first_cloud_ = true;
ROS_INFO("Got first cloud!");
}
static bool firstTime = true;
static int counter = 0;
static cPrecisionClock pclock;
float sample_period = 2.0;
if(firstTime) // start a clock to estimate the rate
{
pclock.setTimeoutPeriodSeconds(sample_period);
pclock.start(true);
firstTime = false;
}
// estimate the refresh rate and publish
++counter;
if (pclock.timeoutOccurred()) {
pclock.stop();
float rate = counter/sample_period;
counter = 0;
pclock.start(true);
std_msgs::String msg;
char status_string[256];
sprintf(status_string, "Cloud rate: %.3f",
rate );
msg.data = status_string;
pub_status_.publish(msg);
}
}
/*!
* \brief Callback for receiving a point cloud.
*
* This description is displayed lower in the doxygen as an extended description along with
* the above brief description.
*/
void disparityCallback(const stereo_msgs::DisparityImageConstPtr &input)
{
}
/*!
* \brief Callback for setting algorithm params, such as weights, through dynamic reconfigure.
*
* This description is displayed lower in the doxygen as an extended description along with
* the above brief description.
*/
void dynamicCallback(Config &new_config, uint32_t id)
{
// This info will get printed back to reconfigure gui
char status[256] = "\0";
switch(id){
case(-1): // Init
// If you are tempted to put anything here, it should probably go in the constructor
break;
case(0): // Connect
printf("Reconfigure GUI connected to me!\n");
new_config = config_;
break;
case(1): // Object select
//printf("Reconfigure GUI connected to me!\n");
config_.auto_threshold = new_config.auto_threshold;
object->updateShape(new_config.object_select);
//new_object->updateShape(new_config.object_select);
break;
case(10): // auto-threshold
config_.auto_threshold = new_config.auto_threshold;
object->updateShape(new_config.object_select);
default: // Error condition
ROS_INFO("Dynamic reconfigure did something, variable %d.", id);
}
if(new_config.auto_threshold)
{
// new_config.meta_thresh = config_.meta_thresh;
new_config.basis_radius = config_.basis_radius;
}
config_ = new_config;
if(tool) tool->setRadius(config_.tool_radius);
new_config.status = status;
}
}; // End of class definition
void hapticsDispatch(void *instance)
{
HapticNode *widget = reinterpret_cast<HapticNode *>(instance);
if (widget) widget->updateHaptics();
}
/* ---[ */
int main (int argc, char* argv[])
{
ros::init(argc, argv, "haptics_node");
HapticNode haptics(argv);
ros::MultiThreadedSpinner spinner(3); // Use 4 threads
spinner.spin();
return (0);
}
/* ]--- */
| 35.560052 | 155 | 0.647417 | [
"mesh",
"object",
"vector",
"transform",
"3d"
] |
a4cc7e3b7fb504b4893b2ad858b2eb578d1dc598 | 6,769 | cpp | C++ | _src_/Core/LazyStruct.cpp | VadimashRS/MuClientTools_Season_13 | 0e37e8cd9b364df5b5474687e6994137141eaecc | [
"MIT"
] | null | null | null | _src_/Core/LazyStruct.cpp | VadimashRS/MuClientTools_Season_13 | 0e37e8cd9b364df5b5474687e6994137141eaecc | [
"MIT"
] | null | null | null | _src_/Core/LazyStruct.cpp | VadimashRS/MuClientTools_Season_13 | 0e37e8cd9b364df5b5474687e6994137141eaecc | [
"MIT"
] | 3 | 2021-07-27T22:56:41.000Z | 2022-03-06T04:50:51.000Z | #include "LazyStruct.h"
//------------------------------------------------------------------------
//--LazyStruct
//------------------------------------------------------------------------
namespace LazyStruct
{
size_t ParseType(std::string& type)
{
static const std::unordered_map<std::string, int> TYPES =
{
{"cstr", LAZY_TYPE_FLAG::_CSTR_},
{"double", LAZY_TYPE_FLAG::_DOUBLE_},
{"float", LAZY_TYPE_FLAG::_FLOAT_},
//{"DWORD", LAZY_TYPE_FLAG::_4BYTE_},
{"WORD", LAZY_TYPE_FLAG::_2BYTE_},
{"BYTE", LAZY_TYPE_FLAG::_1BYTE_},
{"int", LAZY_TYPE_FLAG::_4BYTE_ | LAZY_TYPE_FLAG::_SIGNED_},
{"short", LAZY_TYPE_FLAG::_2BYTE_ | LAZY_TYPE_FLAG::_SIGNED_},
{"char", LAZY_TYPE_FLAG::_1BYTE_ | LAZY_TYPE_FLAG::_SIGNED_}
};
if (type.find("DWORD") != std::string::npos)
{
return LAZY_TYPE_FLAG::_4BYTE_;
}
for (auto it = TYPES.begin(); it != TYPES.end(); it++)
{
if (type.find(it->first) != std::string::npos)
{
return it->second;
}
}
return LAZY_TYPE_FLAG::_UNK_;
}
size_t ParseMember(std::string & member, std::string & member_type, std::string & member_name)
{
assert(member.find('*') & member.find('&') == std::string::npos); //no using of ptr/ref
int count = 0;
size_t _ = 0;
//compiler will automatically change multiple spaces or tab '\t' to a single space
if (member[_] == ' ') _++; // " int..."
size_t pos = min(member.find(' ', _), member.find('\t', _));
if (pos == std::string::npos)
return 0;
member_type = member.substr(_, pos - _);
if (member[pos] == ' ') pos++; // "int a..."
size_t a = member.find('[', pos);
size_t s = member_type.find("char");
bool is_arr = a != std::string::npos;
bool is_cstr = is_arr ? s != std::string::npos : false;
if (is_cstr)
member_type.replace(s, 4, "cstr"); //define cstr := char[]
if (!is_arr)
{
member_name = member.substr(pos);
count = 1;
}
else if (is_arr) //included cstr
{
member_name = member.substr(pos, a - pos);
a++;
if (member[pos] == ' ') pos++; // "[ 1]"
count = atoi(member.data() + a);
}
if (member_name.empty())
return 0;
if (*(member_name.end() - 1) == ' ') // "a [1]"->"a "
member_name.pop_back();
return count;
}
int ParseMemberType(std::string& member_type, std::string& format)
{
static const std::unordered_map<std::string, std::string> FORMATS =
{ {"double" ,"%lf"},{"float" ,"%f"},
{"int" ,"%d"}, //{"DWORD" ,"%d"}, //conflict DWORD vs WORD
{"short" ,"%hd"},{"WORD" ,"%hd"},
{ "char" ,"%hhd"},{"BYTE" ,"%hhd"} };
static const std::unordered_map<std::string, int> SIZES =
{ {"double", 8},{"float", 4},
{"int", 4}, //{"DWORD", 4}, //conflict DWORD vs WORD
{"short", 2},{"WORD", 2},
{ "char", 1},{"BYTE", 1} };
if (member_type.find("cstr") != std::string::npos)
{
format = "%[^\t]%*c";
return -1; //Unk size
}
else if (member_type.find("DWORD") != std::string::npos)
{
format = "%d";
return 4;
}
else
{
for (auto it = FORMATS.begin(); it != FORMATS.end(); it++)
{
if (member_type.find(it->first) != std::string::npos)
{
format = it->second;
return SIZES.at(it->first);
}
}
}
format.clear();
return 0;
}
void CalculateOffset(std::vector<OffsetInfo>& offset,int pack)
{
// vector saves members' sizes at the initial
// we have to calculate the offset positions (with padding) then replace it.
// for now only use pack 0 (default #pragma pack()) and pack 1
size_t pos = 0;
for (int i = 0; i < offset.size(); i++)
{
size_t& member_offset = offset[i].Offset; //ref
size_t member_size = member_offset; //value
int member_type = offset[i].Type;
if (pack == 0)
{
if (member_type != LAZY_TYPE_FLAG::_CSTR_)
while (pos % member_size)
pos++;
}
else if (pack == 1)
{
//do nothing
}
member_offset = pos;
pos += member_size;
}
}
std::string ParseMembersToLabel(std::string && members)
{
std::string label = "/";
size_t pos = 1;
size_t a = 0;
size_t b = members.find(';', a);
while (b != std::string::npos)
{
if (b > a)
{
std::string member, member_type, member_name;
member = members.substr(a, b - a);
int count = ParseMember(member, member_type, member_name);
if (count == 1)
label += '\t' + member_name;
else if (count > 1)
{
if (member_type.find("cstr") != std::string::npos)
{
label += '\t' + member_name;
}
else
{
for (int i = 0; i < count; i++)
label += '\t' + member_name + "[" + std::to_string(i) + "]";
}
}
}
a = b + 1;
b = members.find(';', a);
}
if (label.length() > 2)
label[1] = '/'; //put comment slashs at front
return label;
}
std::string ParseMembersToFormat(std::string && members)
{
std::string format = "";
size_t pos = 0;
size_t a = 0;
size_t b = members.find(';', a);
while (b != std::string::npos)
{
if (b > a)
{
std::string member, member_type, member_name;
member = members.substr(a, b - a);
int count = ParseMember(member, member_type, member_name);
if (count == 1)
{
std::string temp;
int size = ParseMemberType(member_type, temp);
if (size > 0)
format += "\t" + temp;
}
else if (count > 1)
{
std::string temp;
int size = ParseMemberType(member_type, temp);
if (size == -1) //cstr
{
format += "\t" + temp;
}
else if (size > 0)
{
for (int i = 0; i < count; i++)
format += "\t" + temp;
}
}
}
a = b + 1;
b = members.find(';', a);
}
if (format.length() > 1)
format = format.substr(1); //remove "\t" at the front
return format;
}
std::vector<OffsetInfo> ParseMembersToOffset(std::string && members, int pack)
{
std::vector<OffsetInfo> offset;
size_t pos = 0;
size_t a = 0;
size_t b = members.find(';', a);
while (b != std::string::npos)
{
if (b > a)
{
std::string member, member_type, member_name;
member = members.substr(a, b - a);
size_t count = ParseMember(member, member_type, member_name);
size_t type = ParseType(member_type);
if (count == 1)
{
std::string format;
int size = ParseMemberType(member_type, format);
if (size > 0)
offset.push_back({ type, (size_t)size, format });
}
else if (count > 1)
{
std::string format;
int size = ParseMemberType(member_type, format);
if (size == -1) //cstr
offset.push_back({ type, count, format });
else if (size > 0)
for (int i = 0; i < count; i++)
offset.push_back({ type, (size_t)size, format });
}
}
a = b + 1;
b = members.find(';', a);
}
CalculateOffset(offset, pack);
return offset;
}
}
| 23.422145 | 95 | 0.552814 | [
"vector"
] |
a4cf1933f6c9cb6a09e191a4df2ae176219184e9 | 1,318 | cpp | C++ | old/v1/src/sim/Tile.cpp | qiuwenhui/micromouse_-simulator | 6625b2814b8281a0db5d4e9d57ae8881ff31fed0 | [
"MIT"
] | 175 | 2016-02-11T11:19:53.000Z | 2022-03-29T17:24:30.000Z | old/v1/src/sim/Tile.cpp | qiuwenhui/micromouse_-simulator | 6625b2814b8281a0db5d4e9d57ae8881ff31fed0 | [
"MIT"
] | 16 | 2016-03-06T22:06:13.000Z | 2022-02-16T06:23:00.000Z | old/v1/src/sim/Tile.cpp | qiuwenhui/micromouse_-simulator | 6625b2814b8281a0db5d4e9d57ae8881ff31fed0 | [
"MIT"
] | 57 | 2015-03-31T22:30:46.000Z | 2022-02-10T06:12:27.000Z | #include "Tile.h"
#include "Constants.h"
#include "Parameters.h"
namespace sim{
Tile::Tile() : m_x(0), m_y(0), m_distance(MAX_DISTANCE), m_explored(false),
m_passes(0), m_posp(false), m_neighbors() {
m_walls[0] = false;
m_walls[1] = false;
m_walls[2] = false;
m_walls[3] = false;
}
Tile::~Tile()
{ }
int Tile::getX(){
return m_x;
}
int Tile::getY(){
return m_y;
}
int Tile::getDistance(){
return m_distance;
}
int Tile::getPasses(){
return m_passes;
}
bool Tile::getExplored(){
return m_explored;
}
bool Tile::getPosp(){
return m_posp;
}
bool Tile::isWall(int direction){
return m_walls[direction];
}
std::vector<Tile*> Tile::getNeighbors(){
return m_neighbors;
}
void Tile::setPos(int x, int y){
m_x = x;
m_y = y;
}
void Tile::setDistance(int distance){
m_distance = distance;
}
void Tile::incrementPasses(){
m_passes++;
}
void Tile::resetPasses(){
m_passes = 0;
}
void Tile::setExplored(bool explored){
m_explored = explored;
}
void Tile::setPosp(bool posp){
m_posp = posp;
}
void Tile::setWall(int wall, bool exists){
m_walls[wall] = exists;
}
void Tile::addNeighbor(Tile* neighbor){
m_neighbors.push_back(neighbor);
}
void Tile::resetNeighbors(){
m_neighbors.clear();
}
} // namespace sim
| 14.808989 | 75 | 0.637329 | [
"vector"
] |
a4dcbac203f5d9ff258e1701e92c5bc80389960b | 726 | hpp | C++ | src/GameEngineClasses/CompoundPrimitive.hpp | dmariaa/game-engine | b26a58b7cdfcabbb6952f5df62248a8e9ce3476c | [
"MIT"
] | null | null | null | src/GameEngineClasses/CompoundPrimitive.hpp | dmariaa/game-engine | b26a58b7cdfcabbb6952f5df62248a8e9ce3476c | [
"MIT"
] | null | null | null | src/GameEngineClasses/CompoundPrimitive.hpp | dmariaa/game-engine | b26a58b7cdfcabbb6952f5df62248a8e9ce3476c | [
"MIT"
] | null | null | null | //
// CompoundPrimitive.hpp
// src
//
// Created by David María Arribas on 14/11/17.
// Copyright © 2017 David María Arribas. All rights reserved.
//
#ifndef CompoundPrimitive_hpp
#define CompoundPrimitive_hpp
#include <stdio.h>
#include <vector>
#include "BasePrimitive.hpp"
class CompoundPrimitive : public BasePrimitive {
vector<BasePrimitive*> primitives;
public:
CompoundPrimitive();
CompoundPrimitive(const CompoundPrimitive &primitive);
CompoundPrimitive* clone() override;
virtual ~CompoundPrimitive();
// Parent implementations
void render() override;
void update(float dt) override;
BoundingBox calculateBoundingBox() override;
};
#endif /* CompoundPrimitive_hpp */
| 22.6875 | 62 | 0.731405 | [
"render",
"vector"
] |
a4f3c6398e52f3d24597aa6fda3da6f952e1ed25 | 1,047 | cpp | C++ | CodeForces/CF1108B.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | 1 | 2018-02-11T09:41:54.000Z | 2018-02-11T09:41:54.000Z | CodeForces/CF1108B.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | CodeForces/CF1108B.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | #pragma GCC optimize ("O2")
#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
#define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define ALL(x) begin(x),end(x)
#define SZ(x) ((int)(x).size())
#define REP(i,a,b) for (int i = a; i < b; i++)
// Let's Fight!
int main() {
_
int N;
cin >> N;
vi enter(10002);
REP(i, 0, N){
int s;
cin >> s;
enter[s]++;
}
int maxx = 0;
for(int i = 10000; i >= 1; i--){
if(enter[i]){
maxx = i;
break;
}
}
enter[maxx]--;
if(maxx != 1)
enter[1]--;
int ss = (int)sqrt(maxx);
for(int i = 2; i <= ss; i++){
if(maxx % i == 0){
enter[i]--;
if(i * i != maxx)
enter[maxx / i]--;
}
}
int minn = 0;
for(int i = 10000; i >= 1; i--){
if(enter[i] > 0){
minn = i;
break;
}
}
cout << maxx << ' ' << minn << '\n';
return 0;
} | 17.745763 | 57 | 0.545368 | [
"vector"
] |
a4f739167da5ee2f1b9fee35b804aa34c5e40c43 | 8,465 | hpp | C++ | Zephyrus/zephyrus.hpp | Iciclez/Zephyrus | e0ea12e6d21bec5f19708ce95a4f685b848f265a | [
"MIT"
] | 5 | 2018-02-04T17:11:20.000Z | 2020-04-27T07:16:13.000Z | Zephyrus/zephyrus.hpp | Iciclez/zephyrus | e0ea12e6d21bec5f19708ce95a4f685b848f265a | [
"MIT"
] | null | null | null | Zephyrus/zephyrus.hpp | Iciclez/zephyrus | e0ea12e6d21bec5f19708ce95a4f685b848f265a | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
#include <queue>
#include <windows.h>
#ifdef _WIN64
#define X64 1
#elif _WIN32
#define X86 1
#endif
#ifdef X86
typedef uint32_t address_t;
#elif X64
typedef uint64_t address_t;
#else
typedef uint32_t address_t;
#endif
enum hook_operation :
#ifdef X86
uint16_t
#elif X64
uint64_t
#endif
{
JECXZ = 0xE3, //jmp if ecx == 0 short
CALL = 0xE8,
JMP = 0xE9,
JMP_SPECIAL = 0xEA,
JMP_SHORT = 0xEB,
JE = 0x840F,
JNE = 0x850F,
JA = 0x870F,
JB = 0x820F,
CALL_PTR = 0x15FF,
JMP_PTR = 0x25FF, //jmp [imm32], jmp dword ptr, jmp qword ptr
#ifdef X86
//not in use
CALL_64 = 0,
JMP_64 = 0
#elif X64
CALL_64 = 0x08EB0000000215FF,
JMP_64 = 0xffffffff000025FF, //bytes for jmp imm64 is 0x0000000025FF
#endif
//0x70 <= pb[0] && pb[0] <= 0x7F
// jo, jno, jb, jnb, jz, jnz, jbe, ja, js, jns, jp, jnp, jl, jnl, jle, jnle
//(pb[0] == 0x0F && (0x80 <= pb[1] && pb[1] <= 0x8F))
//
};
class zephyrus
{
public:
enum padding_byte : uint8_t
{
NOP = 0x90,
INT3 = 0xCC,
};
zephyrus(padding_byte padding = NOP);
~zephyrus() noexcept;
bool pagereadwriteaccess(address_t address);
uint32_t protectvirtualmemory(address_t address, size_t size);
const std::vector<uint8_t> readmemory(address_t address, size_t size);
bool writememory(address_t address, const std::string &array_of_bytes, size_t padding_size = 0, bool retain_bytes = true);
bool writememory(address_t address, const std::vector<uint8_t> &bytes, bool retain_bytes = true);
bool copymemory(address_t address, void *bytes, size_t size, bool retain_bytes = true);
bool writeassembler(address_t address, const std::string &assembler_code, bool retain_bytes = true);
bool writepadding(address_t address, size_t padding_size);
bool revertmemory(address_t address);
bool redirect(hook_operation operation, address_t *address, address_t function, bool enable = true);
bool redirect(address_t *address, address_t function, bool enable = true);
template <class T> bool redirect(T *address, T function, bool enable = true);
template <class T> bool redirect(hook_operation operation, T *address, T function, bool enable = true);
bool detour(void **from, void *to, bool enable = true);
template <class T> bool detour(T *from, T to, bool enable = true);
bool sethook(hook_operation operation, address_t address, address_t function, size_t nop_count = -1, bool retain_bytes = true);
bool sethook(hook_operation operation, address_t address, const std::string &assembler_code, size_t nop_count = -1, bool retain_bytes = true);
bool sethook(hook_operation operation, address_t address, const std::vector<std::string> &assembler_code, size_t nop_count = -1, bool retain_bytes = true);
template <hook_operation T> bool sethook(address_t address, address_t function, size_t nop_count = -1, bool retain_bytes = true);
template <hook_operation T> bool sethook(address_t address, const std::string &assembler_code, size_t nop_count = -1, bool retain_bytes = true);
template <hook_operation T> bool sethook(address_t address, const std::vector<std::string> &assembler_code, size_t nop_count = -1, bool retain_bytes = true);
template <typename T> bool writedata(address_t address, T data);
template <typename T> const T readdata(address_t address);
template <typename T> static bool writepointer(address_t base, size_t offset, T value);
template <typename T> static const T readpointer(address_t base, size_t offset);
template <typename T> static bool writemultilevelpointer(address_t base, std::queue<size_t> offsets, T value);
template <typename T> static const T readmultilevelpointer(address_t base, std::queue<size_t> offsets);
//
bool assemble(const std::string &assembler_code, _Out_ std::vector<uint8_t> &bytecode);
size_t getnopcount(address_t address, hook_operation operation);
static const std::string byte_to_string(const std::vector<uint8_t> &bytes, const std::string &separator = " ");
static const std::vector<uint8_t> string_to_bytes(const std::string &array_of_bytes);
template <typename T> static T convert_to(const std::vector<uint8_t> &bytes);
static address_t getexportedfunctionaddress(const std::string &module_name, const std::string &function_name);
template <typename T> static T getexportedfunction(const std::string &module_name, const std::string &function_name);
private:
padding_byte padding;
std::unordered_map<address_t, std::vector<uint8_t>> memory_patches;
std::function<bool(address_t, size_t, const std::function<void(void)> &)> pageexecutereadwrite;
std::unordered_map<address_t, std::vector<uint8_t>> hook_memory;
std::unordered_map<address_t, std::pair<address_t, address_t>> trampoline_detour;
std::unordered_map<address_t, std::vector<uint8_t>> trampoline_table;
};
template<class T>
inline bool zephyrus::redirect(T * address, T function, bool enable)
{
return this->redirect(reinterpret_cast<address_t*>(address), reinterpret_cast<address_t>(function), enable);
}
template<class T>
inline bool zephyrus::redirect(hook_operation operation, T * address, T function, bool enable)
{
return this->redirect(operation, reinterpret_cast<address_t*>(address), reinterpret_cast<address_t>(function), enable);
}
template<class T>
inline bool zephyrus::detour(T * from, T to, bool enable)
{
return this->detour(reinterpret_cast<void**>(from), to, enable);
}
template<hook_operation T>
inline bool zephyrus::sethook(address_t address, address_t function, size_t nop_count, bool retain_bytes)
{
return this->sethook(T, address, function, nop_count, retain_bytes);
}
template<hook_operation T>
inline bool zephyrus::sethook(address_t address, const std::string & assembler_code, size_t nop_count, bool retain_bytes)
{
return this->sethook(T, address, assembler_code, nop_count, retain_bytes);
}
template<hook_operation T>
inline bool zephyrus::sethook(address_t address, const std::vector<std::string>& assembler_code, size_t nop_count, bool retain_bytes)
{
return this->sethook(T, address, assembler_code, nop_count, retain_bytes);
}
template<typename T>
inline bool zephyrus::writedata(address_t address, T data)
{
return this->pageexecutereadwrite(address, sizeof(T), [&]()
{
*reinterpret_cast<T*>(address) = data;
});
}
template<typename T>
inline const T zephyrus::readdata(address_t address)
{
return zephyrus::convert_to<T>(this->readmemory(address, sizeof(T)));
}
template<typename T>
inline bool zephyrus::writepointer(address_t base, size_t offset, T value)
{
if (!base)
{
return false;
}
__try
{
*reinterpret_cast<T*>(*reinterpret_cast<address_t*>(base) + offset) = value;
return true;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
}
template<typename T>
inline const T zephyrus::readpointer(address_t base, size_t offset)
{
__try
{
return base ? *reinterpret_cast<T*>(*reinterpret_cast<address_t*>(base) + offset) : 0;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return 0;
}
}
template<typename T>
inline bool zephyrus::writemultilevelpointer(address_t base, std::queue<size_t> offsets, T value)
{
if (!base)
{
return false;
}
for (base = *reinterpret_cast<address_t*>(base); !offsets.empty(); offsets.pop())
{
if (offsets.size() == 1)
{
*reinterpret_cast<T*>(base + offsets.front()) = value;
return true;
}
else
{
//the for loop deref our base
base = *reinterpret_cast<address_t*>(base + offsets.front());
}
}
return false;
}
template<typename T>
inline const T zephyrus::readmultilevelpointer(address_t base, std::queue<size_t> offsets)
{
if (!base)
{
return 0;
}
for (base = *reinterpret_cast<address_t*>(base); !offsets.empty(); offsets.pop())
{
if (offsets.size() == 1)
{
return *reinterpret_cast<T*>(base + offsets.front());
}
else
{
//the for loop deref our base
base = *reinterpret_cast<address_t*>(base + offsets.front());
}
}
return 0;
}
template<typename T>
inline T zephyrus::convert_to(const std::vector<uint8_t>& bytes)
{
std::vector<uint8_t> b = bytes;
if (sizeof(T) > b.size())
{
b.insert(b.end(), sizeof(T) - b.size(), 0);
}
T m = 0;
for (int32_t n = sizeof(m) - 1; n >= 0; --n)
{
m = (m << 8) + b.at(n);
}
return m;
}
template<typename T>
inline T zephyrus::getexportedfunction(const std::string & module_name, const std::string & function_name)
{
return reinterpret_cast<T>(getexportedfunctionaddress(module_name, function_name));
}
| 28.694915 | 158 | 0.734554 | [
"vector"
] |
a4f99ab7d0e229e6ffc4d1683dd237ea469385f2 | 1,054 | hh | C++ | PacDetector/PacElemFactory.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDetector/PacElemFactory.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDetector/PacElemFactory.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | /* Class: PacElemFactory
*
* A factory utility class to produce transient sub-detector elements
* from the corresponding EDML elements.
*/
#ifndef PacElemFactory_HH
#define PacElemFactory_HH
#include <vector>
#include <iostream>
class EdmlDetElement;
class DetElem;
class DetType;
class PacElemFactory {
public:
/// Get a sub-detector element for the specified EDML element
/**
* OWNERSHIP NOTE: The method will return the ownership over the object.
*/
static DetElem* get( const EdmlDetElement* theEdmlElement );
private:
/// The singleton
static PacElemFactory& instance();
/// No public c-tor because it's a singleton
PacElemFactory();
/// No public d-tor because it's a singleton
virtual ~PacElemFactory();
/// Get a sub-detector element for the specified EDML element (actuall implmentation)
DetElem* doGet( const EdmlDetElement* theEdmlElement );
void printElem(std::ostream& str, const EdmlDetElement* theEdmlElement ) const;
private:
};
#endif // PacElemFactory_HH
| 21.08 | 89 | 0.717268 | [
"object",
"vector"
] |
a4fccdbee942c94abf70d687b455e8477a2c75c4 | 532 | cpp | C++ | week_4/ANARC08G.cpp | juliolugo96/test | d2b95941eda16643adaab28a5b8bacb4fdc8959f | [
"MIT"
] | 3 | 2018-09-27T22:51:14.000Z | 2018-10-19T18:31:03.000Z | week_4/ANARC08G.cpp | juliolugo96/test | d2b95941eda16643adaab28a5b8bacb4fdc8959f | [
"MIT"
] | null | null | null | week_4/ANARC08G.cpp | juliolugo96/test | d2b95941eda16643adaab28a5b8bacb4fdc8959f | [
"MIT"
] | 2 | 2018-10-01T11:33:43.000Z | 2021-12-05T18:11:24.000Z | # include <bits/stdc++.h>
using namespace std;
int f(int a, int b)
{
a = a < 0 ? a : 0;
b = b < 0 ? b : 0;
return (a + b);
}
int main()
{
int n;
int k = 0;
scanf("%d", &n);
while(n != 0)
{
vector<int> v(n);
k++;
int acc = 0;
for(short i{0}; i < n; i++)
for(short j{0}; j < n; j++)
{
int val{0};
scanf("%d", &val);
acc += val;
v[j] += val;
v[i] -= val;
}
int sum = -1*accumulate(v.begin(), v.end(), 0, f);
printf("%d. %d %d\n",k, acc, sum);
scanf("%d", &n);
}
return 0;
} | 13.3 | 52 | 0.432331 | [
"vector"
] |
3505118a51e275e9f138af29dccf06d66aacfba8 | 40,460 | cpp | C++ | gos/windows/glop.cpp | runningwild/glop | abed7bd11be4f9655d967ab1850328cf571c8787 | [
"BSD-3-Clause"
] | 38 | 2015-02-14T23:10:57.000Z | 2022-03-31T15:29:54.000Z | gos/windows/glop.cpp | runningwild/glop | abed7bd11be4f9655d967ab1850328cf571c8787 | [
"BSD-3-Clause"
] | 2 | 2015-09-11T04:17:17.000Z | 2020-06-01T02:56:12.000Z | gos/windows/glop.cpp | runningwild/glop | abed7bd11be4f9655d967ab1850328cf571c8787 | [
"BSD-3-Clause"
] | 6 | 2015-09-22T22:22:15.000Z | 2019-03-12T08:58:52.000Z | #define DIRECTINPUT_VERSION 0x0700
#include "dinput.h"
#include <process.h>
#include <windows.h>
#include <map>
#include <set>
#include <vector>
#include <windows.h>
using namespace std;
// Do not show the console window for a console application running in release mode
#ifdef NDEBUG
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")
#endif
// Undefines, because Windows sucks
#undef CreateWindow
#undef MessageBox
extern "C" {
#include "glop.h"
struct OsMutex {
CRITICAL_SECTION critical_section;
};
void GlopStartThread(void(__cdecl *thread_function)(void *), void *data) {
_beginthread(thread_function, 0, data);
}
OsMutex *GlopNewMutex() {
OsMutex *result = new OsMutex();
InitializeCriticalSection(&result->critical_section);
return result;
}
void GlopDeleteMutex(OsMutex *mutex) {
DeleteCriticalSection(&mutex->critical_section);
delete mutex;
}
void GlopAcquireMutex(OsMutex *mutex) {
EnterCriticalSection(&mutex->critical_section);
}
void GlopReleaseMutex(OsMutex *mutex) {
LeaveCriticalSection(&mutex->critical_section);
}
void GlopSleep(int t) {
::Sleep(t);
}
// Thread class definition. This is the basic tool for threading. The user extends the Thread
// class and overloads the virtual function Run. Once Start is called, the new Run function is
// executed in a new thread. Join() can be used to wait for that thread to terminate.
class Thread {
public:
// Deletes this thread object. The thread must not be currently executing. Note: that calling
// Join() here is insufficient since we would still delete the extending part of the class
// before reaching this code.
virtual ~Thread() {}
// Begins executing this thread.
void Start();
// Returns whether the thread is currently executing.
bool IsRunning() const {return is_running_;}
// If the thread is currently executed, this requests that it stop. There is nothing requiring
// a thread to honor this request, although it should if possible.
void RequestStop() {is_stop_requested_ = true;}
// Blocks until the thread finishes execution.
void Join();
protected:
// Creates this thread object. It will not begin executing until Start is called.
Thread(): is_stop_requested_(false), is_running_(false) {}
// Returns is_stop_requested_ - for use within Run().
bool IsStopRequested() const {return is_stop_requested_;}
// Pure virtual function that is executed in the new thread. When this function returns, the
// thread is considered finished.
virtual void Run() = 0;
private:
static void StaticExecutor(void *thread_ptr);
bool is_stop_requested_, is_running_;
};
// Mutex class definition. This is a simple lock. At most one thread can have a single mutex
// acquired at any given time.
class Mutex {
public:
Mutex();
~Mutex();
void Acquire();
void Release();
private:
OsMutex *os_data_;
};
// MutexLock class definition. While in scope, a MutexLock keeps a mutex acquired. Once it goes
// out of scope, the mutex is released.
class MutexLock {
public:
MutexLock(Mutex *mutex): mutex_(mutex) {mutex_->Acquire();}
~MutexLock() {mutex_->Release();}
private:
Mutex *mutex_;
};
void Thread::Start() {
// Note that we need to set is_running_ right away in case the user calls Join() before we
// switch threads
is_stop_requested_ = false;
is_running_ = true;
GlopStartThread(StaticExecutor, this);
}
void Thread::Join() {
while (is_running_)
GlopSleep(0);
}
void Thread::StaticExecutor(void *thread_ptr) {
Thread *thread = (Thread*)thread_ptr;
thread->Run();
thread->is_running_ = false;
}
// Mutex
// =====
Mutex::Mutex(): os_data_(GlopNewMutex()) {}
Mutex::~Mutex() {GlopDeleteMutex(os_data_);}
void Mutex::Acquire() {GlopAcquireMutex(os_data_);}
void Mutex::Release() {GlopReleaseMutex(os_data_);}
static LARGE_INTEGER gTimerFrequency;
long long GlopGetTime() {
LARGE_INTEGER current_time; // A 64-bit integer (accessible via ::QuadPart)
QueryPerformanceCounter(¤t_time);
return (long long)((1000 * current_time.QuadPart) / gTimerFrequency.QuadPart);
}
long long GlopGetTimeMicro() {
LARGE_INTEGER current_time;
QueryPerformanceCounter(¤t_time);
return (long long)((1000000 * (long double)current_time.QuadPart) / gTimerFrequency.QuadPart); // on my windows box, the timer frequency is about 2.4 billion (clock speed ahoy). That gives one overflow every 2 hours if done with the same method GetTime() uses, and without floating-point. On a faster system that might go down to 1 hour. Unacceptable. We go to floating-point to avoid issues of this sort. Dividing by 1000 might do the job, but I'm unsure how *low* TimerFrequency might go. It's all kind of nasty.
}
class InputPollingThread;
// OsWindowData struct definition
struct OsWindowData {
OsWindowData()
: icon_handle(0), window_handle(0), device_context(0), rendering_context(0), direct_input(0),
keyboard_device(0), mouse_device(0), input_polling_thread(0), is_full_screen(0), x(0), y(0),
width(0), height(0), is_in_focus(false), focus_changed(false), is_minimized(false) {}
// Operating system values and handles. icon_handle is only non-zero if it will need to be
// deleted eventually.
HICON icon_handle;
HWND window_handle;
HDC device_context;
HGLRC rendering_context;
LPDIRECTINPUT direct_input;
LPDIRECTINPUTDEVICE keyboard_device, mouse_device;
vector<LPDIRECTINPUTDEVICE2> joystick_devices;
InputPollingThread *input_polling_thread;
Mutex input_mutex;
// Queriable window properties
bool is_full_screen;
int x, y;
int width, height;
bool is_in_focus, focus_changed, is_minimized;
};
// Constants
const int kBpp = 32;
const int kDirectInputBufferSize = 50;
const int kJoystickAxisRange = 10000;
const int kDIToGlopKeyIndex[] = {0,
27, '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'0', '-', '=', 8, 9,
'q', 'w', 'e', 'r', 't',
'y', 'u', 'i', 'o', 'p',
'[', ']', 13, kKeyLeftControl, 'a',
's', 'd', 'f', 'g', 'h',
'j', 'k', 'l', ';', '\'',
'`', kKeyLeftShift, '\\', 'z', 'x',
'c', 'v', 'b', 'n', 'm', // 50
',', '.', '/', kKeyRightShift, kKeyPadMultiply,
kKeyLeftAlt, ' ', kKeyCapsLock, kKeyF1, kKeyF2,
kKeyF3, kKeyF4, kKeyF5, kKeyF6, kKeyF7,
kKeyF8, kKeyF9, kKeyF10, kKeyNumLock, kKeyScrollLock,
kKeyPad7, kKeyPad8, kKeyPad9, kKeyPadSubtract, kKeyPad4,
kKeyPad5, kKeyPad6, kKeyPadAdd, kKeyPad1, kKeyPad2,
kKeyPad3, kKeyPad0, kKeyPadDecimal, -1, -1,
-1, kKeyF11, kKeyF12, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, // 100
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, // 150
-1, -1, -1, -1, -1,
kKeyPadEnter, kKeyRightControl, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
kKeyPadDivide, -1, kKeyPrintScreen, kKeyRightAlt, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, kKeyPause, -1, kKeyHome, kKeyUp, // 200
kKeyPageUp, -1, kKeyLeft, -1, kKeyRight,
-1, kKeyEnd, kKeyDown, kKeyPageDown, kKeyInsert,
kKeyDelete, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, // 250
-1, -1, -1, -1, -1};
// Globals
static map<HWND, OsWindowData*> gWindowMap;
static OsWindowData *gLocked;
HWND get_first_handle() {
// ASSERT(gWindowMap.size());
return gWindowMap.begin()->first;
}
void LockCursorNow(OsWindowData *window) {
RECT rect;
GetWindowRect(window->window_handle, &rect);
if(/*ClientAreaOnly && !FullScreen*/ true) {
RECT crect; //client rect
RECT arect; //adjusted rect
GetClientRect(window->window_handle, &crect);
arect = crect;
AdjustWindowRectEx(&arect, WS_CAPTION | WS_BORDER, FALSE, 0);
rect.left += (crect.left - arect.left);
rect.right += (crect.right - arect.right);
rect.top += (crect.top - arect.top);
rect.bottom += (crect.bottom - arect.bottom);
}
ClipCursor(&rect);
}
void UnlockCursorNow() {
ClipCursor(NULL);
}
// InputPollingThread
// ==================
//
// A separate thread devoted entirely to polling the input device state at regular intervals. This
// is necessitated on Windows because joystick event trapping seems not to work. By polling in a
// separate thread, we guarantee fast response times even when the program's frame rate lags.
class InputPollingThread: public Thread {
public:
// Constructor.
InputPollingThread(OsWindowData *window): window_(window) {}
// Returns all events since the last call to GetData.
vector<GlopKeyEvent> GetData() {
// Get the data
window_->input_mutex.Acquire();
vector<GlopKeyEvent> result = data_;
data_.clear();
window_->input_mutex.Release();
// Add a current state event
POINT cursor_pos;
GetCursorPos(&cursor_pos);
bool is_num_lock_set = (GetKeyState(VK_NUMLOCK) & 1) > 0;
bool is_caps_lock_set = (GetKeyState(VK_CAPITAL) & 1) > 0;
// TODO: Insert KeyEvent struct thingy here
//result.push_back(GlopKeyEvent(system()->GetTime(), cursor_pos.x, cursor_pos.y, is_num_lock_set,
// is_caps_lock_set));
return result;
}
protected:
// Continuously polls the input.
void Run() {
POINT prev_pos;
int mouse_buttons[3];
for (int i = 0; i < 3; i++) {
mouse_buttons[i] = 0;
}
while (!IsStopRequested()) {
window_->input_mutex.Acquire();
long long timestamp = GlopGetTime();
// Read metastate
POINT cursor_pos;
GetCursorPos(&cursor_pos);
bool is_num_lock_set = (GetKeyState(VK_NUMLOCK) & 1) > 0;
bool is_caps_lock_set = (GetKeyState(VK_CAPITAL) & 1) > 0;
GlopKeyEvent base;
GlopClearKeyEvent(&base);
base.timestamp = timestamp;
base.num_lock = is_num_lock_set;
base.caps_lock = is_caps_lock_set;
base.cursor_x = cursor_pos.x;
base.cursor_y = cursor_pos.y;
// Read keyboard events
DWORD num_items = kDirectInputBufferSize;
DIDEVICEOBJECTDATA buffer[kDirectInputBufferSize];
HRESULT hr = window_->keyboard_device->GetDeviceData(sizeof(buffer[0]), buffer,
&num_items, 0);
if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) {
window_->keyboard_device->Acquire();
hr = window_->keyboard_device->GetDeviceData(sizeof(buffer[0]), buffer, &num_items, 0);
}
if (!FAILED(hr)) {
for (int i = 0; i < (int)num_items; i++) {
bool is_pressed = ((buffer[i].dwData & 0x80) > 0);
if (buffer[i].dwOfs < 255 && kDIToGlopKeyIndex[buffer[i].dwOfs] != -1) {
GlopKeyEvent e = base;
e.index = kDIToGlopKeyIndex[buffer[i].dwOfs];
e.press_amt = !!is_pressed;
data_.push_back(e);
// data_.push_back(GlopKeyEvent(kDIToGlopKeyIndex[buffer[i].dwOfs], is_pressed, timestamp,
// cursor_pos.x, cursor_pos.y, is_num_lock_set,
// is_caps_lock_set));
}
}
}
// Read the mouse state
DIMOUSESTATE2 mouse_state;
hr = window_->mouse_device->GetDeviceState(sizeof(mouse_state), &mouse_state);
if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) {
window_->mouse_device->Acquire();
hr = window_->mouse_device->GetDeviceState(sizeof(mouse_state), &mouse_state);
}
if (!FAILED(hr)) {
// TODO: GlopKeyEvent
if (cursor_pos.x != prev_pos.x) {
GlopKeyEvent e = base;
e.index = kMouseXAxis;
e.press_amt = cursor_pos.x - prev_pos.x;
e.cursor_x = cursor_pos.x;
e.cursor_y = cursor_pos.y;
data_.push_back(e);
}
if (cursor_pos.y != prev_pos.y) {
GlopKeyEvent e = base;
e.index = kMouseYAxis;
e.press_amt = cursor_pos.y - prev_pos.y;
e.cursor_x = cursor_pos.x;
e.cursor_y = cursor_pos.y;
data_.push_back(e);
}
/*
data_.push_back(GlopKeyEvent(mouse_state.lX, mouse_state.lY, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
data_.push_back(GlopKeyEvent(kMouseWheelDown, mouse_state.lZ < 0, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
data_.push_back(GlopKeyEvent(kMouseWheelUp, mouse_state.lZ > 0, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
*/
// ASSERT(kNumMouseButtons == 8); // Update section if this changes
for (int i = 0; i < 3; i++) {
GlopKeyEvent e = base;
e.index = kMouseLButton + i;
int press = !!((mouse_state.rgbButtons[i] & 0x80) > 0);
if (press == mouse_buttons[i]) { continue; }
mouse_buttons[i] = press;
e.press_amt = press;
e.cursor_x = cursor_pos.x;
e.cursor_y = cursor_pos.y;
data_.push_back(e);
}
prev_pos = cursor_pos;
/*
for (int i = 0; i < kNumMouseButtons; i++) {
data_.push_back(GlopKeyEvent(GetMouseButton(i), (mouse_state.rgbButtons[i] & 0x80) > 0,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
}
*/
}
// Read the joystick states
/*
DIJOYSTATE2 joy_state;
for (int i = 0; i < (int)window_->joystick_devices.size(); i++) {
// Try to poll the device
hr = window_->joystick_devices[i]->Poll();
if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) {
window_->joystick_devices[i]->Acquire();
hr = window_->joystick_devices[i]->Poll();
}
if (FAILED(window_->joystick_devices[i]->GetDeviceState(sizeof(joy_state), &joy_state)))
continue;
// Read axis data
// ASSERT(kNumJoystickAxes == 6); // Update section if this changes
// TODO: GlopKeyEvent stuff
data_.push_back(GlopKeyEvent(GetJoystickRight(i), float(joy_state.lX)/kJoystickAxisRange,
data_.push_back(GlopKeyEvent(GetJoystickLeft(i), float(-joy_state.lX)/kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickUp(i), float(-joy_state.lY)/kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickDown(i), float(joy_state.lY)/kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisPos(2, i),
float(joy_state.lZ) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisNeg(2, i),
float(-joy_state.lZ) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisPos(3, i),
float(joy_state.lRz) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisNeg(3, i),
float(-joy_state.lRz) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisPos(4, i),
float(joy_state.lRx) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisNeg(4, i),
float(-joy_state.lRx) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisPos(5, i),
float(joy_state.lRy) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickAxisNeg(5, i),
float(-joy_state.lRy) / kJoystickAxisRange,
timestamp, cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
// Read hat data
// ASSERT(kNumJoystickHats <= 4); // Update section if this changes
for (int j = 0; j < kNumJoystickHats; j++) {
int angle = joy_state.rgdwPOV[j];
float hx = 0, hy = 0;
if (LOWORD(angle) != 0xFFFF) {
if (angle < 4500) hx = float(angle) / 4500;
else if (angle <= 13500) hx = 1;
else if (angle < 22500) hx = 1 - float(angle-13500) / 4500;
else if (angle <= 31500) hx = -1;
else hx = -1 + float(angle-31500) / 4500;
if (angle < 4500) hy = 1;
else if (angle <= 13500) hy = 1 - float(angle-4500) / 4500;
else if (angle < 22500) hy = -1;
else if (angle <= 31500) hy = -1 + float(angle-22500) / 4500;
else hy = 1;
}
data_.push_back(GlopKeyEvent(GetJoystickHatUp(j, i), hy, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickHatRight(j, i), hx, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickHatDown(j, i), -hy, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
data_.push_back(GlopKeyEvent(GetJoystickHatLeft(j, i), -hx, timestamp, cursor_pos.x,
cursor_pos.y, is_num_lock_set, is_caps_lock_set));
}
// Read button data
// ASSERT(kNumJoystickButtons <= 128); // Update section if this changes
for (int j = 0; j < kNumJoystickButtons; j++) {
bool is_pressed = ((joy_state.rgbButtons[j] & 0x80) > 0);
data_.push_back(Os::KeyEvent(GetJoystickButton(j, i), is_pressed, timestamp,
cursor_pos.x, cursor_pos.y, is_num_lock_set,
is_caps_lock_set));
}
}
*/
window_->input_mutex.Release();
GlopSleep(10);
}
}
// TODO: This needs to be replaced with some sort of something or other
vector<GlopKeyEvent> data_;
OsWindowData *window_;
};
// Initialization/Shut down
// ========================
void GlopInit() {
for (map<HWND, OsWindowData*>::iterator it = gWindowMap.begin(); it != gWindowMap.end(); it++)
it->second->input_mutex.Acquire();
// Timer initialization. timeBeginPeriod(1) ensures that Sleep calls return promptly when they
// are supposed to, and QueryPerformanceFrequency is needed for Os::GetTime.
timeBeginPeriod(1);
QueryPerformanceFrequency(&gTimerFrequency);
for (map<HWND, OsWindowData*>::iterator it = gWindowMap.begin(); it != gWindowMap.end(); it++)
it->second->input_mutex.Release();
}
void GlopShutDown() {}
// Logic functions
// ===============
// Handles Os messages that arrive through the message queue. Note that some, but not all, messages
// are sent directly to HandleMessage and bypass the message queue.
void GlopThink() {
MSG message;
while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessage(&message);
}
}
// Handles window messages that arrive by any means, message queue or by direct notification.
// However, key events are ignored, as input is handled by DirectInput in WindowThink().
LRESULT CALLBACK HandleMessage(HWND window_handle, UINT message, WPARAM wparam, LPARAM lparam) {
// Extract information from the parameters
if (!gWindowMap.count(window_handle))
return DefWindowProcW(window_handle, message, wparam, lparam);
OsWindowData *os_window = gWindowMap[window_handle];
unsigned short wparam1 = LOWORD(wparam), wparam2 = HIWORD(wparam);
unsigned short lparam1 = LOWORD(lparam), lparam2 = HIWORD(lparam);
// TODO: Only here for crashing later
int* x = 0;
// Handle each message
switch (message) {
case WM_SYSCOMMAND:
// Prevent screen saver and monitor power saving
if (wparam == SC_SCREENSAVE || wparam == SC_MONITORPOWER)
return 0;
// Prevent accidental pausing by pushing F10 or what not
if (wparam == SC_MOUSEMENU || wparam == SC_KEYMENU)
return 0;
break;
case WM_CLOSE:
// TODO: Need to figure out what is supposed to happen here. It shouldn't actually crash.
*x = 0;
// window()->Destroy(); // this is certainly not going to fail hideously
return 0;
case WM_MOVE:
os_window->x = (signed short)lparam1;
os_window->y = (signed short)lparam2;
break;
case WM_SIZE:
// Set the resolution if a full-screen window was alt-tabbed into.
if (os_window->is_minimized != (wparam == SIZE_MINIMIZED) && os_window->is_full_screen) {
if (wparam == SIZE_MINIMIZED) {
ChangeDisplaySettings(0, 0);
} else {
DEVMODE screen_settings;
screen_settings.dmSize = sizeof(screen_settings);
screen_settings.dmDriverExtra = 0;
screen_settings.dmPelsWidth = lparam1;
screen_settings.dmPelsHeight = lparam2;
screen_settings.dmBitsPerPel = kBpp;
screen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
ChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN);
}
}
os_window->is_minimized = (wparam == SIZE_MINIMIZED);
if (!os_window->is_minimized) {
os_window->width = lparam1;
os_window->height = lparam2;
}
break;
case WM_SIZING:
os_window->focus_changed = true;
break;
case WM_ACTIVATE:
os_window->is_in_focus = (wparam1 == WA_ACTIVE || wparam1 == WA_CLICKACTIVE);
os_window->focus_changed = true;
// If the user alt-tabs out of a fullscreen window, the window will keep drawing and will
// remain in full-screen mode. Here, we minimize the window, which fixes the drawing problem,
// and then the WM_SIZE event fixes the full-screen problem.
if (!os_window->is_in_focus && os_window->is_full_screen)
ShowWindow(os_window->window_handle, SW_MINIMIZE);
if (os_window->is_in_focus && gLocked == os_window)
LockCursorNow(os_window);
if (!os_window->is_in_focus)
UnlockCursorNow();
break;
}
// Pass on remaining messages to the default handler
return DefWindowProcW(window_handle, message, wparam, lparam);
}
void GlopWindowThink(OsWindowData *window) {}
// Window functions
// ================
// See Os.h
// Converts an image into a 32x32 ICO object in memory, and then returns a handle for the resulting
// icon.
/*
HICON CreateIcon(OsWindowData *data, const Image *image) {
bool scaling_needed = (image->GetWidth() != 32 || image->GetHeight() != 32 ||
image->GetBpp() != 32);
if (scaling_needed)
image = Image::AdjustedImage(image, 32, 32, 32);
// Set the header
unsigned char *icon = new unsigned char[3240];
*((unsigned int*)&icon[0]) = 40;
*((unsigned int*)&icon[4]) = 32;
*((unsigned int*)&icon[8]) = 64;
*((unsigned short*)&icon[12]) = 1;
*((unsigned short*)&icon[14]) = 24;
*((unsigned int*)&icon[16]) = 0;
*((unsigned int*)&icon[20]) = 3200;
*((unsigned int*)&icon[24]) = 0;
*((unsigned int*)&icon[28]) = 0;
*((unsigned int*)&icon[32]) = 0;
*((unsigned int*)&icon[36]) = 0;
// Set the colors
for (int y = 0; y < 32; y++)
for (int x = 0; x < 32; x++) {
const unsigned char *pixel = image->Get(x, 31-y);
for (int c = 0; c < 3; c++) {
unsigned char value = pixel[c];
if (pixel[3] == 0)
value = 0; // Do not do strange background blending
icon[40 + y*32*3 + x*3 + 2-c] = value;
}
}
// Set the mask using alpha values
for (int y = 0; y < 32; y++)
for (int x = 0; x < 32; x++) {
int icon_index = y*4 + x/8;
int icon_mask = 1 << (7-(x%8));
if (image->Get(x, 31-y)[3] == 0)
icon[3112+icon_index] |= icon_mask;
else
icon[3112+icon_index] &= (~icon_mask);
}
// Do the work
HICON result = CreateIconFromResource(icon, 3240, true, 0x00030000);
delete icon;
if (scaling_needed)
delete image;
return result;
}
*/
void GlopSetTitle(OsWindowData* window, char* title) {
SetWindowText(window->window_handle, title);
}
// Registers a new joystick with a window.
BOOL CALLBACK GlopJoystickCallback(const DIDEVICEINSTANCE *device_instance, void *void_window) {
OsWindowData *window = (OsWindowData*)void_window;
LPDIRECTINPUTDEVICE new_device;
if (FAILED(window->direct_input->CreateDevice(device_instance->guidInstance, &new_device, 0)))
return DIENUM_CONTINUE;
DIPROPRANGE prop_range;
prop_range.diph.dwSize = sizeof(DIPROPRANGE);
prop_range.diph.dwHeaderSize = sizeof(DIPROPHEADER);
prop_range.diph.dwHow = DIPH_DEVICE;
prop_range.diph.dwObj = 0;
prop_range.lMin = -kJoystickAxisRange;
prop_range.lMax = kJoystickAxisRange;
DIPROPDWORD prop_buffer_size;
prop_buffer_size.diph.dwSize = sizeof(DIPROPDWORD);
prop_buffer_size.diph.dwHeaderSize = sizeof(DIPROPHEADER);
prop_buffer_size.diph.dwObj = 0;
prop_buffer_size.diph.dwHow = DIPH_DEVICE;
prop_buffer_size.dwData = kDirectInputBufferSize;
if (FAILED(new_device->SetDataFormat(&c_dfDIJoystick2)) ||
FAILED(new_device->SetCooperativeLevel(window->window_handle,
DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)) ||
FAILED(new_device->SetProperty(DIPROP_RANGE, &prop_range.diph)) ||
FAILED(new_device->SetProperty(DIPROP_BUFFERSIZE, &prop_buffer_size.diph))) {
new_device->Release();
return DIENUM_CONTINUE;
}
window->joystick_devices.push_back((LPDIRECTINPUTDEVICE2)new_device);
return DIENUM_CONTINUE;
}
int GlopGetNumJoysticks(OsWindowData *window) {
return (int)window->joystick_devices.size();
}
void GlopRefreshJoysticks(OsWindowData *window) {
window->input_mutex.Acquire();
// Get the current joystick devices
vector<LPDIRECTINPUTDEVICE2> old_devices = window->joystick_devices;
window->joystick_devices.clear();
window->direct_input->EnumDevices(DIDEVTYPE_JOYSTICK, GlopJoystickCallback, window,
DIEDFL_ATTACHEDONLY);
bool joysticks_changed = (window->joystick_devices.size() != old_devices.size());
// Delete the superfluous devices. We delete the new devices if nothing has changed to ensure
// that key events are not affected.
if (!joysticks_changed) {
vector<LPDIRECTINPUTDEVICE2> temp = old_devices;
old_devices = window->joystick_devices;
window->joystick_devices = temp;
}
for (int i = 0; i < (int)old_devices.size(); i++)
old_devices[i]->Release();
window->input_mutex.Release();
}
// Destroys a window that is completely or partially created.
void GlopDestroyWindow(OsWindowData *window) {
window->input_polling_thread->RequestStop();
window->input_polling_thread->Join();
delete window->input_polling_thread;
if (window->is_full_screen && !window->is_minimized)
ChangeDisplaySettings(NULL, 0);
if (window->keyboard_device) {
window->keyboard_device->Unacquire();
window->keyboard_device->Release();
}
if (window->mouse_device) {
window->mouse_device->Unacquire();
window->mouse_device->Release();
}
if (window->rendering_context)
wglDeleteContext(window->rendering_context);
if (window->device_context)
ReleaseDC(window->window_handle, window->device_context);
if (window->window_handle) {
::DestroyWindow(window->window_handle);
gWindowMap.erase(window->window_handle);
}
if (window->icon_handle != 0)
DestroyIcon(window->icon_handle);
delete window;
}
void* GlopCreateWindow(void* _title, int x, int y,
int width, int height, int full_screen, int stencil_bits,
int is_resizable) {
char* title = (char*)_title;
const wchar_t *const kClassName = L"GlopWin32";
static bool is_class_initialized = false;
OsWindowData *result = new OsWindowData();
// Create a window class. This is essentially used by Windows to group together several windows
// for various purposes.
if (!is_class_initialized) {
WNDCLASSW window_class;
window_class.style = CS_OWNDC;
window_class.lpfnWndProc = HandleMessage;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = GetModuleHandle(0);
window_class.hIcon = 0;
window_class.hCursor = LoadCursor(NULL, IDC_ARROW);
window_class.hbrBackground = 0;
window_class.lpszMenuName = 0;
window_class.lpszClassName = kClassName;
if (!RegisterClassW(&window_class)) {
GlopDestroyWindow(result);
return 0;
}
is_class_initialized = true;
}
// Specify the desired window style
DWORD window_style = WS_POPUP;
if (!full_screen) {
window_style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
if (is_resizable)
window_style |= WS_MAXIMIZEBOX | WS_THICKFRAME;
}
// Specify the window dimensions and get the border size
RECT window_rectangle;
window_rectangle.left = 0;
window_rectangle.right = width;
window_rectangle.top = 0;
window_rectangle.bottom = height;
if (!AdjustWindowRectEx(&window_rectangle, window_style, false, 0)) {
GlopDestroyWindow(result);
return 0;
}
// Specify the desired window position
if (x == -1 && y == -1) {
x = y = CW_USEDEFAULT;
} else if (full_screen) {
x = y = 0;
} else {
x += window_rectangle.left;
y += window_rectangle.top;
}
// Create the window
result->window_handle = CreateWindowExW(0,
kClassName, L"Glop window",
window_style,
x, y,
window_rectangle.right - window_rectangle.left,
window_rectangle.bottom - window_rectangle.top,
NULL,
NULL,
GetModuleHandle(0),
NULL);
if (!result->window_handle) {
GlopDestroyWindow(result);
return 0;
}
GlopSetTitle(result, title);
gWindowMap[result->window_handle] = result;
// Set the icon
// if (icon != 0) {
// result->icon_handle = CreateIcon(result, icon);
// SendMessage(result->window_handle, WM_SETICON, ICON_BIG, (LPARAM)result->icon_handle);
// }
// Get the window position
RECT actual_position;
GetWindowRect(result->window_handle, &actual_position);
result->x = actual_position.left - window_rectangle.left;
result->y = actual_position.top - window_rectangle.top;
result->width = width;
result->height = height;
// Get the device context
result->device_context = GetDC(result->window_handle);
if (!result->device_context) {
GlopDestroyWindow(result);
return 0;
}
// Specify a pixel format by requesting one, and then selecting the best available match on the
// system. This is used to set up Open Gl.
PIXELFORMATDESCRIPTOR pixel_format_request;
memset(&pixel_format_request, 0, sizeof(pixel_format_request));
pixel_format_request.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pixel_format_request.nVersion = 1;
pixel_format_request.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pixel_format_request.iPixelType = PFD_TYPE_RGBA;
pixel_format_request.cColorBits = kBpp;
pixel_format_request.cStencilBits = (char)stencil_bits;
pixel_format_request.cDepthBits = 16;
unsigned int pixel_format_id = ChoosePixelFormat(result->device_context, &pixel_format_request);
if (!pixel_format_id) {
GlopDestroyWindow(result);
return 0;
}
if (!SetPixelFormat(result->device_context, pixel_format_id, &pixel_format_request)) {
GlopDestroyWindow(result);
return 0;
}
// Switch to full-screen mode if appropriate
if (full_screen) {
DEVMODE screen_settings;
screen_settings.dmSize = sizeof(screen_settings);
screen_settings.dmDriverExtra = 0;
screen_settings.dmPelsWidth = width;
screen_settings.dmPelsHeight = height;
screen_settings.dmBitsPerPel = kBpp;
screen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
if (ChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
GlopDestroyWindow(result);
return 0;
}
result->is_full_screen = true;
}
// Make a rendering context for this thread
result->rendering_context = wglCreateContext(result->device_context);
if (!result->rendering_context) {
GlopDestroyWindow(result);
return 0;
}
wglMakeCurrent(result->device_context, result->rendering_context);
// Show the window. Note that SetForegroundWindow can fail if the user is currently using another
// window, but this is fine and nothing to be alarmed about.
ShowWindow(result->window_handle, SW_SHOW);
SetForegroundWindow(result->window_handle);
SetFocus(result->window_handle);
result->is_in_focus = true;
// Attempt to initialize DirectInput.
// Settings: Non-exclusive (be friendly with other programs), foreground (only accept input
// events if we are currently in the foreground).
if (FAILED(DirectInputCreate(GetModuleHandle(0), DIRECTINPUT_VERSION,
&result->direct_input, 0))) {
GlopDestroyWindow(result);
return 0;
}
result->direct_input->CreateDevice(GUID_SysKeyboard, &result->keyboard_device, NULL);
result->keyboard_device->SetCooperativeLevel(result->window_handle,
DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
result->keyboard_device->SetDataFormat(&c_dfDIKeyboard);
result->direct_input->CreateDevice(GUID_SysMouse, &result->mouse_device, NULL);
result->mouse_device->SetCooperativeLevel(result->window_handle,
DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
result->mouse_device->SetDataFormat(&c_dfDIMouse2);
// Set the DirectInput buffer size - this is the number of events it can store at a single time
DIPROPDWORD prop_buffer_size;
prop_buffer_size.diph.dwSize = sizeof(DIPROPDWORD);
prop_buffer_size.diph.dwHeaderSize = sizeof(DIPROPHEADER);
prop_buffer_size.diph.dwObj = 0;
prop_buffer_size.diph.dwHow = DIPH_DEVICE;
prop_buffer_size.dwData = kDirectInputBufferSize;
result->keyboard_device->SetProperty(DIPROP_BUFFERSIZE, &prop_buffer_size.diph);
GlopRefreshJoysticks(result);
// Begin the input polling
result->input_polling_thread = new InputPollingThread(result);
result->input_polling_thread->Start();
// All done
return result;
}
bool GlopIsWindowMinimized(const OsWindowData *window) {
return window->is_minimized;
}
void GlopGetWindowFocusState(OsWindowData *window, bool *is_in_focus, bool *focus_changed) {
*is_in_focus = window->is_in_focus;
*focus_changed = window->focus_changed;
window->focus_changed = false;
}
void GlopGetWindowPosition(const OsWindowData *window, int *x, int *y) {
*x = window->x;
*y = window->y;
}
void GlopGetWindowSize(const OsWindowData *window, int *width, int *height) {
*width = window->width;
*height = window->height;
}
void GlopGetWindowDims(void* _window, int* x, int* y, int* dx, int* dy) {
OsWindowData* window = (OsWindowData*)_window;
*x = window->x;
*y = window->y;
*dx = window->width;
*dy = window->height;
}
/*
void GlopSetIcon(OsWindowData *window, const Image *icon) {
if (window->icon_handle != 0)
DestroyIcon(window->icon_handle);
window->icon_handle = (icon == 0? 0 : CreateIcon(window, icon));
SendMessage(window->window_handle, WM_SETICON, ICON_BIG, (LPARAM)window->icon_handle);
}
*/
void GlopSetWindowSize(OsWindowData *window, int width, int height) {
RECT rect;
GetWindowRect(window->window_handle, &rect);
rect.right += width - window->width;
rect.bottom += height - window->height;
MoveWindow(window->window_handle, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, true);
window->width = width;
window->height = height;
}
// Input functions
// ===============
// See Os.h
static GlopKeyEvent* glop_event_buffer = 0;
void GlopGetInputEvents(void* _window, void** _events_ret, void* _num_events, void* _horizon) {
*((long long*)_horizon) = GlopGetTime();
OsWindowData* window = (OsWindowData*)_window;
if (glop_event_buffer != 0) {
free(glop_event_buffer);
}
vector<GlopKeyEvent> events;
if (_window != 0) {
events = window->input_polling_thread->GetData();
}
// TODO: It *is* possible for an event to happen between the above and below lines, so we
// should make sure that the later events have their timestamps increased if they
// are below the horizon
glop_event_buffer = (GlopKeyEvent*)malloc(sizeof(GlopKeyEvent) * events.size());
*((GlopKeyEvent**)_events_ret) = glop_event_buffer;
*((int*)_num_events) = events.size();
for (int i = 0; i < events.size(); i++) {
glop_event_buffer[i] = events[i];
}
}
void GlopGetMousePosition(int* x, int* y) {
POINT cursor_pos;
GetCursorPos(&cursor_pos);
*x = cursor_pos.x;
*y = cursor_pos.y;
}
void GlopSetMousePosition(int x, int y) {
SetCursorPos(x, y);
}
void GlopShowMouseCursor(bool is_shown) {
ShowCursor(is_shown);
}
void GlopLockMouseCursor(OsWindowData *locked) {
gLocked = locked;
if (!locked) {
UnlockCursorNow();
} else {
if (locked->is_in_focus)
{
LockCursorNow(locked);
}
}
}
// Miscellaneous functions
// =======================
//void GlopMessageBox(const string &title, const string &message) {
// MessageBoxA(NULL, message.c_str(), title.c_str(), MB_OK | MB_ICONINFORMATION);
//}
vector<pair<int, int> > GlopGetFullScreenModes() {
set<pair<int,int> > result; // EnumDisplaySettings could return duplicates
DEVMODE dev_mode;
dev_mode.dmSize = sizeof(dev_mode);
dev_mode.dmDriverExtra = 0;
for (int i = 0; EnumDisplaySettings(0, DWORD(i), &dev_mode); i++)
if (dev_mode.dmBitsPerPel == kBpp)
result.insert(make_pair(dev_mode.dmPelsWidth, dev_mode.dmPelsHeight));
return vector<pair<int,int> >(result.begin(), result.end());
}
int GlopGetRefreshRate() {
DEVMODE dev_mode;
dev_mode.dmSize = sizeof(dev_mode);
dev_mode.dmDriverExtra = 0;
EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &dev_mode);
return dev_mode.dmDisplayFrequency;
}
void GlopEnableVSync(int is_enabled) {
// TODO: Stub
}
void GlopSwapBuffers(void* _window) {
OsWindowData* window = (OsWindowData*)_window;
::SwapBuffers(window->device_context);
}
} // extern "C" | 36.384892 | 521 | 0.641176 | [
"object",
"vector"
] |
3529bf1970af9e165b5b0a1b902b61639cb45624 | 1,229 | cc | C++ | cdcc/lex.cc | lopezfjose/CDCC | d087fbd48e58d1ca57cd6269a1896043f57e6d6f | [
"MIT"
] | null | null | null | cdcc/lex.cc | lopezfjose/CDCC | d087fbd48e58d1ca57cd6269a1896043f57e6d6f | [
"MIT"
] | null | null | null | cdcc/lex.cc | lopezfjose/CDCC | d087fbd48e58d1ca57cd6269a1896043f57e6d6f | [
"MIT"
] | null | null | null |
#include <CDCC/Lex.hxx>
namespace CDCC
{
Lexer::Lexer()
: yytext(nullptr), yyleng(0), yylineno(0), current(nullptr), inputBuffer { 0 }
{
// Default constructor
}
Lexer::Lexer(char *ptr, int len, int num)
: yytext(ptr), yyleng(len), yylineno(num), current(nullptr), inputBuffer { 0 }
{
// Custom constructor
}
template <typename CharT, typename Traits = std::char_traits<CharT>>
void Lexer::setInputStream(const std::basic_streambuf<CharT, Traits>& streamBuffer)
{
//inputStream { streamBuffer };
}
void Lexer::lexFile(const std::filebuf& inputFileBuffer)
{
// TODO: Implement lexFile
}
void Lexer::lex()
{
// TODO: Fix this bullshit
/*for (const auto& file : inputFiles)
{
std::filebuf inputFile { file, std::ios::in };
if (!inputFile.is_open())
{
std::cerr << "[Error]: Failed to open source file.\n";
std::exit(EXIT_FAILURE);
}
lexFile(inputFile);
}*/
}
std::vector<Token> Lexer::tokensVector() const noexcept
{
return std::vector<Token> { tokens };
}
void Lexer::printTokens() const noexcept
{
for (const auto& token : tokens)
{
std::cout << token << "\n";
}
}
} // End namespace CDCC
| 19.822581 | 83 | 0.615948 | [
"vector"
] |
352b47d53a6b2f7b2bc8a916a93709eca5690cb4 | 4,533 | cpp | C++ | cogs/Camera.cpp | VasilStamatov/cogs | 6f198bc88f9b9506c0991907e336ac645e79286c | [
"MIT"
] | null | null | null | cogs/Camera.cpp | VasilStamatov/cogs | 6f198bc88f9b9506c0991907e336ac645e79286c | [
"MIT"
] | 1 | 2017-04-05T02:01:56.000Z | 2017-04-05T02:01:56.000Z | cogs/Camera.cpp | VasilStamatov/cogs | 6f198bc88f9b9506c0991907e336ac645e79286c | [
"MIT"
] | null | null | null | #include "Camera.h"
#include "Entity.h"
#include "Skybox.h"
#include "Framebuffer.h"
#include "BulletDebugRenderer.h"
#include <glm\gtc\matrix_transform.hpp>
namespace cogs
{
std::weak_ptr<Camera> Camera::s_mainCamera;
std::weak_ptr<Camera> Camera::s_currentCamera;
std::vector<std::weak_ptr<Camera>> Camera::s_allCameras;
Camera::Camera(int _screenWidth,
int _screenHeight,
const ProjectionType& _projType) :
m_projType(_projType),
m_cameraWidth(_screenWidth),
m_cameraHeight(_screenHeight)
{
//projection matrix
updateProjection();
}
Camera::~Camera()
{
}
void Camera::init()
{
m_transform = m_entity.lock()->getComponent<Transform>();
m_oldTransform = *m_transform.lock();
if (m_entity.lock()->getName() == "MainCamera")
{
setMain(m_entity.lock()->getComponent<Camera>());
}
else
{
addCamera(m_entity.lock()->getComponent<Camera>());
}
}
void Camera::update(float _deltaTime)
{
if (!(*m_transform.lock() == m_oldTransform))
{
updateView();
}
}
void Camera::setFoV(int _value)
{
if (m_fov < 1)
{
m_fov = 1;
}
else if (m_fov > 179)
{
m_fov = 179;
}
updateProjection();
}
void Camera::offsetFoV(int _value)
{
m_fov += _value;
if (m_fov < 1)
{
m_fov = 1;
}
else if (m_fov > 179)
{
m_fov = 179;
}
updateProjection();
}
void Camera::setSize(float _value)
{
m_size = _value;
if (m_size < 1.0f)
{
m_size = 1.0f;
}
updateProjection();
}
void Camera::offsetSize(float _value)
{
m_size += _value;
if (m_size < 1.0f)
{
m_size = 1.0f;
}
updateProjection();
}
void Camera::setNearPlane(float _value)
{
m_nearPlane = _value;
updateProjection();
}
void Camera::setFarPlane(float _value)
{
m_farPlane = _value;
updateProjection();
}
void Camera::setClippingPlanes(float _zNear, float _zFar)
{
m_nearPlane = _zNear;
m_farPlane = _zFar;
updateProjection();
}
void Camera::setProjectionType(const ProjectionType & _projType)
{
m_projType = _projType;
updateProjection();
}
void Camera::resize(int _screenWidth, int _screenHeight)
{
m_cameraWidth = _screenWidth;
m_cameraHeight = _screenHeight;
//projection matrix
updateProjection();
}
const glm::mat4 & Camera::getProjectionMatrix() const noexcept
{
if (m_projType == ProjectionType::ORTHOGRAPHIC) return m_orthoMatrix;
else
return m_perspMatrix;
}
glm::vec2 Camera::convertWorldToScreen(const glm::vec3 & _worldCoordinate)
{
glm::vec4 clipCoords = m_perspMatrix * m_viewMatrix * glm::vec4(_worldCoordinate, 1.0f);
clipCoords.x /= clipCoords.w;
clipCoords.y /= clipCoords.w;
clipCoords.z /= clipCoords.w;
glm::vec2 screenPoint(0.0f);
screenPoint.x = ((clipCoords.x + 1) / 2.0f) * m_cameraWidth;
screenPoint.y = ((1 - clipCoords.y) / 2.0f) * m_cameraHeight;
return screenPoint;
}
glm::vec3 Camera::convertScreenToWorld(const glm::vec2 & _screenCoordinate)
{
float x = 2.0f * _screenCoordinate.x / m_cameraWidth - 1;
float y = -2.0f * _screenCoordinate.y / m_cameraHeight + 1;
glm::mat4 viewProjInverse = glm::inverse(m_perspMatrix * m_viewMatrix);
glm::vec3 worldCoord(x, y, 0.0f);
return viewProjInverse * glm::vec4(worldCoord, 1.0f);
}
void Camera::renderFrustum(BulletDebugRenderer* _renderer)
{
m_frustum.render(_renderer);
}
void Camera::renderSkybox()
{
if (!m_skybox.expired())
{
m_skybox.lock()->render();
}
}
void Camera::updateView()
{
m_oldTransform = *m_transform.lock();
m_viewMatrix = glm::inverse(m_oldTransform.worldTransform());
m_frustum.update(m_oldTransform.worldPosition(),
m_oldTransform.worldForwardAxis(),
m_oldTransform.worldRightAxis(),
m_oldTransform.worldUpAxis());
}
void Camera::updateProjection()
{
if (m_projType == ProjectionType::PERSPECTIVE)
{
m_perspMatrix = glm::perspective(glm::radians(static_cast<float>(m_fov)),
getAspectRatio(), m_nearPlane, m_farPlane);
//update the frustum
m_frustum.setCamInternals(glm::radians((float)m_fov), getAspectRatio(), m_nearPlane, m_farPlane);
}
else
{
m_orthoMatrix = glm::ortho(0.0f, static_cast<float>(m_cameraWidth) * m_size,
0.0f, static_cast<float>(m_cameraHeight) * m_size, m_nearPlane, m_farPlane);
}
}
} | 22.004854 | 103 | 0.643062 | [
"render",
"vector",
"transform"
] |
35338c7aeec6903f086b3cfd55d784a90ab9f447 | 2,849 | cpp | C++ | src/graph/osg/BoundingRectangle.cpp | SindenDev/3dimviewer | e23a3147edc35034ef4b75eae9ccdcbc7192b1a1 | [
"Apache-2.0"
] | 6 | 2020-04-14T16:10:55.000Z | 2021-05-21T07:13:55.000Z | src/graph/osg/BoundingRectangle.cpp | SindenDev/3dimviewer | e23a3147edc35034ef4b75eae9ccdcbc7192b1a1 | [
"Apache-2.0"
] | null | null | null | src/graph/osg/BoundingRectangle.cpp | SindenDev/3dimviewer | e23a3147edc35034ef4b75eae9ccdcbc7192b1a1 | [
"Apache-2.0"
] | 2 | 2020-07-24T16:25:38.000Z | 2021-01-19T09:23:18.000Z | ///////////////////////////////////////////////////////////////////////////////
// $Id$
//
// 3DimViewer
// Lightweight 3D DICOM viewer.
//
// Copyright 2008-2016 3Dim Laboratory s.r.o.
//
// 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 <osg/BoundingRectangle.h>
#include <algorithm>
osg::BoundingRectangle::BoundingRectangle()
: m_valid(false)
{ }
osg::BoundingRectangle::BoundingRectangle(const BoundingRectangle &other)
: m_valid(other.m_valid)
, m_min(other.m_min)
, m_max(other.m_max)
{ }
osg::BoundingRectangle::~BoundingRectangle()
{ }
osg::BoundingRectangle::BoundingRectangle(const osg::Vec2d min, const osg::Vec2d max)
: m_valid(false)
{
expandBy(min);
expandBy(max);
}
osg::BoundingRectangle &osg::BoundingRectangle::operator=(const BoundingRectangle &other)
{
if (this == &other)
{
return *this;
}
m_valid = other.m_valid;
m_min = other.m_min;
m_max = other.m_max;
return *this;
}
void osg::BoundingRectangle::expandBy(const osg::Vec2d &point)
{
if (!m_valid)
{
m_min = m_max = point;
m_valid = true;
}
else
{
m_min = osg::Vec2d(std::min(m_min.x(), point.x()), std::min(m_min.y(), point.y()));
m_max = osg::Vec2d(std::max(m_max.x(), point.x()), std::max(m_max.y(), point.y()));
}
}
bool osg::BoundingRectangle::intersects(const BoundingRectangle &other) const
{
return (m_valid && other.m_valid &&
!((m_max.x() < other.m_min.x()) || (m_min.x() > other.m_max.x()) || (m_max.y() < other.m_min.y()) || (m_min.y() > other.m_max.y())));
}
bool osg::BoundingRectangle::contains(const osg::Vec2d &point) const
{
return (m_valid &&
point.x() > m_min.x() && point.x() < m_max.x() && point.y() > m_min.y() && point.y() < m_max.y());
}
bool osg::BoundingRectangle::contains(const osg::BoundingRectangle &rectangle) const
{
return (contains(rectangle.getMin()) && contains(rectangle.getMax()));
}
bool osg::BoundingRectangle::isValid() const
{
return m_valid;
}
void osg::BoundingRectangle::invalidate()
{
m_valid = false;
}
osg::Vec2d osg::BoundingRectangle::getMin() const
{
return m_min;
}
osg::Vec2d osg::BoundingRectangle::getMax() const
{
return m_max;
}
| 25.666667 | 145 | 0.620218 | [
"3d"
] |
353773739e524ce08ac8a09f7352e31f4109f4d2 | 3,064 | cc | C++ | ccc/src/model/GetRecordOssUploadParamResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | ccc/src/model/GetRecordOssUploadParamResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | ccc/src/model/GetRecordOssUploadParamResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ccc/model/GetRecordOssUploadParamResult.h>
#include <json/json.h>
using namespace AlibabaCloud::CCC;
using namespace AlibabaCloud::CCC::Model;
GetRecordOssUploadParamResult::GetRecordOssUploadParamResult() :
ServiceResult()
{}
GetRecordOssUploadParamResult::GetRecordOssUploadParamResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetRecordOssUploadParamResult::~GetRecordOssUploadParamResult()
{}
void GetRecordOssUploadParamResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["HttpStatusCode"].isNull())
httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString());
if(!value["OssAccessKeyId"].isNull())
ossAccessKeyId_ = value["OssAccessKeyId"].asString();
if(!value["Policy"].isNull())
policy_ = value["Policy"].asString();
if(!value["Signature"].isNull())
signature_ = value["Signature"].asString();
if(!value["Expires"].isNull())
expires_ = value["Expires"].asString();
if(!value["Dir"].isNull())
dir_ = value["Dir"].asString();
if(!value["Host"].isNull())
host_ = value["Host"].asString();
if(!value["OssFileName"].isNull())
ossFileName_ = value["OssFileName"].asString();
}
std::string GetRecordOssUploadParamResult::getPolicy()const
{
return policy_;
}
std::string GetRecordOssUploadParamResult::getMessage()const
{
return message_;
}
std::string GetRecordOssUploadParamResult::getSignature()const
{
return signature_;
}
int GetRecordOssUploadParamResult::getHttpStatusCode()const
{
return httpStatusCode_;
}
std::string GetRecordOssUploadParamResult::getOssFileName()const
{
return ossFileName_;
}
std::string GetRecordOssUploadParamResult::getHost()const
{
return host_;
}
std::string GetRecordOssUploadParamResult::getExpires()const
{
return expires_;
}
std::string GetRecordOssUploadParamResult::getDir()const
{
return dir_;
}
std::string GetRecordOssUploadParamResult::getCode()const
{
return code_;
}
std::string GetRecordOssUploadParamResult::getOssAccessKeyId()const
{
return ossAccessKeyId_;
}
bool GetRecordOssUploadParamResult::getSuccess()const
{
return success_;
}
| 25.114754 | 90 | 0.74641 | [
"model"
] |
3537e1209275d2862664c3dcffd89ba419d668b5 | 887 | cpp | C++ | NumDistinguish/NeuralMatrix.cpp | tj41694/TNeuralNetwork | 733561b436f93ba1efde94bd5bd2d83f09e8ca9b | [
"MIT"
] | null | null | null | NumDistinguish/NeuralMatrix.cpp | tj41694/TNeuralNetwork | 733561b436f93ba1efde94bd5bd2d83f09e8ca9b | [
"MIT"
] | null | null | null | NumDistinguish/NeuralMatrix.cpp | tj41694/TNeuralNetwork | 733561b436f93ba1efde94bd5bd2d83f09e8ca9b | [
"MIT"
] | null | null | null | #include "NeuralMatrix.h"
#include <cstdlib> // Header file needed to use srand and rand
#include <ctime> // Header file needed to use time
#include "NumDistinguish.h"
#include "Sample.h"
using namespace std;
NeuralMatrix::NeuralMatrix(int row_, int colum_, float bias_) :row(row_), column(colum_), bias(bias_) {
static bool initial = false;
if (!initial) {
srand((unsigned int)time(0));
initial = true;
}
for (int r = 0; r < row_; r++) {
vector<double> row;
row.resize(colum_);
for (int c = 0; c < colum_; c++) {
row[c] = rand() * 2.0 / RAND_MAX - 1.0;
}
matrix.emplace_back(row);
}
}
NeuralMatrix::NeuralMatrix(const NeuralMatrix& neural, bool zeroIze) :row(neural.row), column(neural.column), bias(0) {
for (int r = 0; r < neural.row; r++) {
vector<double> row;
row.resize(column, 0);
matrix.emplace_back(row);
}
}
NeuralMatrix::~NeuralMatrix() {
}
| 24.638889 | 119 | 0.661781 | [
"vector"
] |
35381c1c377f218a32bfa5e5381ea43975521080 | 2,333 | cpp | C++ | test/common/object_pool_test.cpp | aaron-tian/terrier | c98d93ca5b88d085f9efdd6ec2a8641e57bd54ff | [
"MIT"
] | null | null | null | test/common/object_pool_test.cpp | aaron-tian/terrier | c98d93ca5b88d085f9efdd6ec2a8641e57bd54ff | [
"MIT"
] | null | null | null | test/common/object_pool_test.cpp | aaron-tian/terrier | c98d93ca5b88d085f9efdd6ec2a8641e57bd54ff | [
"MIT"
] | null | null | null | #include <atomic>
#include <thread> // NOLINT
#include <unordered_set>
#include <vector>
#include "common/object_pool.h"
#include "gtest/gtest.h"
#include "util/random_test_util.h"
#include "util/test_thread_pool.h"
namespace terrier {
// Rather minimalistic checks for whether we reuse memory
// NOLINTNEXTLINE
TEST(ObjectPoolTests, SimpleReuseTest) {
const uint32_t repeat = 10;
const uint64_t reuse_limit = 1;
common::ObjectPool<uint32_t> tested(reuse_limit);
// Put a pointer on the the reuse queue
uint32_t *reused_ptr = tested.Get();
// clang-tidy thinks gtest-printers will DefaultPrintTo the released pointer
// NOLINTNEXTLINE
tested.Release(reused_ptr);
// clang-tidy thinks gtest-printers will DefaultPrintTo the released pointer here too
// NOLINTNEXTLINE
for (uint32_t i = 0; i < repeat; i++) {
EXPECT_EQ(tested.Get(), reused_ptr);
tested.Release(reused_ptr);
}
}
class ObjectPoolTestType {
public:
ObjectPoolTestType *Use(uint32_t thread_id) {
user_ = thread_id;
return this;
}
ObjectPoolTestType *Release(uint32_t thread_id) {
// Nobody used this
EXPECT_EQ(thread_id, user_);
return this;
}
private:
std::atomic<uint32_t> user_;
};
// This test generates random workload and sees if the pool gives out
// the same pointer to two threads at the same time.
// NOLINTNEXTLINE
TEST(ObjectPoolTests, ConcurrentCorrectnessTest) {
TestThreadPool thread_pool;
// This should have no bearing on the correctness of test
const uint64_t reuse_limit = 100;
common::ObjectPool<ObjectPoolTestType> tested(reuse_limit);
auto workload = [&](uint32_t tid) {
// Randomly generate a sequence of use-free
std::default_random_engine generator;
// Store the pointers we use.
std::vector<ObjectPoolTestType *> ptrs;
auto allocate = [&] { ptrs.push_back(tested.Get()->Use(tid)); };
auto free = [&] {
if (!ptrs.empty()) {
auto pos = RandomTestUtil::UniformRandomElement(&ptrs, &generator);
tested.Release((*pos)->Release(tid));
ptrs.erase(pos);
}
};
RandomTestUtil::InvokeWorkloadWithDistribution({free, allocate}, {0.5, 0.5}, &generator, 100);
for (auto *ptr : ptrs) tested.Release(ptr->Release(tid));
};
thread_pool.RunThreadsUntilFinish(8, workload, 100);
}
} // namespace terrier
| 29.910256 | 98 | 0.707244 | [
"vector"
] |
3540016fd18f4ef94a4dfd1eba945eb0a354c5f4 | 1,313 | cpp | C++ | Plugins/GraphicsTools/Source/GraphicsTools/Private/GTClippingConeComponent.cpp | Myfreedom614/HLSpatialMapping | c68dfd08bfe502064f51b38b2c15021127f71161 | [
"MIT"
] | 53 | 2021-01-15T08:19:50.000Z | 2022-03-16T13:45:34.000Z | Plugins/GraphicsTools/Source/GraphicsTools/Private/GTClippingConeComponent.cpp | Myfreedom614/HLSpatialMapping | c68dfd08bfe502064f51b38b2c15021127f71161 | [
"MIT"
] | 9 | 2021-01-19T23:38:20.000Z | 2021-08-24T16:37:59.000Z | Plugins/GraphicsTools/Source/GraphicsTools/Private/GTClippingConeComponent.cpp | Myfreedom614/HLSpatialMapping | c68dfd08bfe502064f51b38b2c15021127f71161 | [
"MIT"
] | 12 | 2021-01-14T21:52:33.000Z | 2021-12-25T07:58:00.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "GTClippingConeComponent.h"
#include "GTWorldSubsystem.h"
#include "Engine/World.h"
UGTClippingConeComponent::UGTClippingConeComponent()
{
{
static const FName ParameterName("ClippingConeSettings");
SetSettingsParameterName(ParameterName);
}
{
static const FName ParameterNames[2] = {"ClippingConeStart", "ClippingConeEnd"};
TArray<FName> Names;
Names.Append(ParameterNames, UE_ARRAY_COUNT(ParameterNames));
SetTransformColumnParameterNames(Names);
}
}
TArray<UGTSceneComponent*>& UGTClippingConeComponent::GetWorldComponents()
{
return GetWorld()->GetSubsystem<UGTWorldSubsystem>()->ClippingCones;
}
void UGTClippingConeComponent::UpdateParameterCollectionTransform()
{
const FTransform& Transform = GetComponentTransform();
FVector HalfHeight = Transform.GetScaledAxis(EAxis::X) * 0.5f;
FVector Top = Transform.GetLocation() + HalfHeight;
FVector Bottom = Transform.GetLocation() - HalfHeight;
FVector ScaleBottomTop = Transform.GetScale3D() * 0.5f;
SetVectorParameterValue(GetTransformColumnParameterNames()[0], FLinearColor(Top.X, Top.Y, Top.Z, ScaleBottomTop.Z));
SetVectorParameterValue(GetTransformColumnParameterNames()[1], FLinearColor(Bottom.X, Bottom.Y, Bottom.Z, ScaleBottomTop.Y));
}
| 32.02439 | 126 | 0.78751 | [
"transform"
] |
3544ac257b6aff535f6a9fee02b66812167bf594 | 104,371 | cpp | C++ | src/generator-TD.cpp | CDR-lib/TD-InstancesGenerator | 79b2fe850f2725b321e1e2893cd8769994c6b410 | [
"MIT"
] | null | null | null | src/generator-TD.cpp | CDR-lib/TD-InstancesGenerator | 79b2fe850f2725b321e1e2893cd8769994c6b410 | [
"MIT"
] | null | null | null | src/generator-TD.cpp | CDR-lib/TD-InstancesGenerator | 79b2fe850f2725b321e1e2893cd8769994c6b410 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <cstring>
#include <algorithm> // for function min
#include <random>
#include <cmath>
#include <chrono>
#include <string>
using namespace std;
// ------- Problem data:
int n=10; // number of aircraft
int mode=6; // to indicate the scenario type, default=6 (pseudo random in 2D)
float vmin=400; float vmax=400; // random speeds will be generated in [vmin,vmax], default=[400,400]
float* x_0; float* y_0; float* z_0;// vectors of initial positions (x0,y0,z0)
float* x_t; float* y_t; float* z_t;// vectors of final position (only for drawing scenario in a .tex file)
float* hat_v; float* hat_theta; float* hat_phi; // vectors of nominal speed and heading angles (hat_teta wrt x, hat_phi wrt z)
float* vx; float* vy; float* vz; // vectors of nominal components of velocity (vx,vy,vz)=hat_v(sin hat_phi*cos hat_theta,sin hat_phi*sin hat_theta,cos hat_phi)
char* outputFile=0;
float D=5; // safety distance
int HP; int VP; // polyhedral problem: number of horizontal and vertical planes
const int hp=3; // default number of horizontal planes
const int vp=2; // default number of vertical planes
// ------- Other parameters:
//int random_seed=std::chrono::system_clock::now().time_since_epoch().count();;
int random_seed=14;
bool verbose=0;
bool is3D=false;
// --------------------------------------------------------------------------
// ----- AUXILIARY FUNCTIONS -------
// --------------------------------------------------------------------------
// 1. randomFloat(float a, float b): returns a random float in the interval [a,b]
float randomFloat(float a, float b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
// 2. randomInt(int a, int b): returns a random integer in the interval [a,b]
int randomInt(int a, int b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
int r = round(random * diff);
return a + r;
}
// 3. areSepatered(int i, int j): returns true if the distance between the initial
// positions of i and j is greater than or equal to D
bool areSepatered(int i, int j){
float xr0=x_0[i]-x_0[j];
float yr0=y_0[i]-y_0[j];
float zr0=z_0[i]-z_0[j];
bool areSepatered= (xr0*xr0+yr0*yr0+zr0*zr0 >= D*D);
return areSepatered;
}
// 4. dist_min(int i, int j): returns the distance between i and j at the time of minimal separation
double dist_min(int i, int j){
double xr0=x_0[i]-x_0[j];
double yr0=y_0[i]-y_0[j];
double zr0=z_0[i]-z_0[j];
double vrx=vx[i]-vx[j];
double vry=vy[i]-vy[j];
double vrz=vz[i]-vz[j];
float negative_zero=-1/std::numeric_limits<float>::infinity();
double a = (vrx*xr0+vry*yr0+vrz*zr0);
double dmin = (xr0*xr0+yr0*yr0+zr0*zr0) - (a*a)/(vrx*vrx+vry*vry+vrz*vrz); //minimum distance among i and j
return abs(dmin);
}
// 5. conflict(int i, int j): returns true if there is a conflict between i and j,
// i.e., if the separation constraints with safety distance D are not satisfied by their trajectories
bool conflict(int i, int j){
double xr0=x_0[i]-x_0[j];
double yr0=y_0[i]-y_0[j];
double zr0=z_0[i]-z_0[j];
double vrx=vx[i]-vx[j];
double vry=vy[i]-vy[j];
double vrz=vz[i]-vz[j];
float negative_zero=-1/std::numeric_limits<float>::infinity();
if ((vrx*vrx+vry*vry+vrz*vrz)==0) {return false;}
else if (dist_min(i,j)-D*D >=0 || dist_min(i,j)-D*D==negative_zero) {return false;}
else {return true;}
}
// 6. duration(int i, int j): returns the duration of conflict among i and j
double duration(int i, int j){
double xr0=x_0[i]-x_0[j];
double yr0=y_0[i]-y_0[j];
double zr0=z_0[i]-z_0[j];
double vrx=vx[i]-vx[j];
double vry=vy[i]-vy[j];
double vrz=vz[i]-vz[j];
float negative_zero=-1/std::numeric_limits<float>::infinity();
double a = (vrx*xr0+vry*yr0+vrz*zr0);
double vr = (vrx*vrx+vry*vry+vrz*vrz);
double pr0 = (xr0*xr0+yr0*yr0+zr0*zr0);
if (conflict(i,j))
{
double initial_inst = (-2*a - sqrt(4*(a*a - vr*pr0 + vr*D*D)))/(2*vr);
double final_inst = (-2*a + sqrt(4*(a*a - vr*pr0 + vr*D*D)))/(2*vr);
return(abs(final_inst-initial_inst));
}
else {return 0;}
}
// 7. numConflicts(int i,bool* explored): returns the number of conflicts between aircraft i and
// the rest of aircraft j such that explored[j]=true
int numConflicts(int i,bool* explored){
int num_conflicts=0;
for (int j = 0; j < n; ++j){
if(explored[j] && conflict(i,j))
num_conflicts++;
}
return num_conflicts;
}
// 8. crossing(float pos1, float vel1, float pos2): calculates horizontal or vertical crossing time
float crossing(float pos1, float vel1, float pos2){
return (pos2-pos1)/vel1;
}
// 9. getInstantBoundary(int i,float height,float width,float altitude): used in random and pseudo-random scenarios.
// Get instants in wich 'i' will cross boundary of the space window height x width.
// This serves to calculate final position (x_t,y_t) in which i leaves the observed airspace, which is returned by this method.
float getInstantBoundary(int i,float height,float width,float altitude){
float t[6];
for (int k = 0; k < 6; ++k) t[k]=-1;
float instant_boundary=std::numeric_limits<float>::infinity();
if(vy[i]!=0){
t[0]=crossing(y_0[i],vy[i],height); // north
t[1]=crossing(y_0[i],vy[i],0); // south
}
if(vx[i]!=0){
t[2]=crossing(x_0[i],vx[i],0); // west
t[3]=crossing(x_0[i],vx[i],width); // east
}
if(vz[i]!=0){
t[4]=crossing(z_0[i],vz[i],0); // down
t[5]=crossing(z_0[i],vz[i],altitude); // up
}
for (int k = 0; k < 6; ++k){
if(t[k]>0 && t[k]<instant_boundary) //we should exclude t[k]=0 (we are looking for 'exit' time, not 'entry' time)
instant_boundary=t[k];
}
return instant_boundary;
}
// 10. correctAngle(float angle): returns an equivalent angle in the interval [-pi,pi]
float correctAngle(float angle){
while( !( angle>= -M_PI && angle<= M_PI) ){
if(angle > M_PI)
angle=angle-2*M_PI;
if(angle <-M_PI)
angle=angle+2*M_PI;
}
return angle;
}
// 11. Norm of a vector
double norm(float* vector, int dimension){
double accum = 0.;
double norm = 0;
for (int j = 0; j < dimension; ++j)
{accum += (double)(vector[j]) * (double)(vector[j]);}
norm = sqrt((double) accum);
return norm;
}
//--------------------------------------------------------------------------
// I/O functions
//--------------------------------------------------------------------------
void printBenchmarkInfo(){
if(outputFile){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("\nInstance saved in file: \"%s\", with a graphical representation in: \"Figure.tex\".\n",outputFile);
ofstream f(outputFile);
f<<std::setprecision(5);
f<<"p0={\n";
printf("p0={\n"); //initial position
for (int i = 0; i < n; ++i){
printf("%f \t %f",x_0[i],y_0[i]);
f<<x_0[i]<<" \t "<<y_0[i];
if (is3D) {printf("\t %f",z_0[i]); f<<"\t "<<z_0[i];}
printf("\n");
f<<"\n";
}
printf("}\n");
f<<"}\n";
// printf("p1={\n"); //final position
// for (int i = 0; i < n; ++i){
// printf("%f \t %f",x_t[i],y_t[i]);
// if (is3D) printf("\t %f",z_t[i]);
// printf("\n");
// }
// printf("}\n");
printf("V_polar=(v,theta"); //polar velocity i.e. (hat_v,hat_theta,hat_phi)
f << "V_polar=(v,theta";
if (is3D) {printf(",phi"); f<<",phi";}
printf(")={\n");
f<<")={\n";
for (int i = 0; i < n; ++i){
printf("%f \t %f",hat_v[i],correctAngle(hat_theta[i]));
f<<hat_v[i]<<" \t "<<correctAngle(hat_theta[i]);
if (is3D) {printf("\t %f",correctAngle(hat_phi[i])); f<<"\t "<<correctAngle(hat_phi[i]);}
printf("\n");
f<<"\n";
}
printf("}\n");
f<<"}\n";
//---------------------complementary output
printf("(Vx,Vy"); //components of the velocity
f<<"(Vx,Vy";
if (is3D) {printf(",Vz"); f<<",Vz";}
printf(")={\n");
f<<")={\n";
for (int i = 0; i < n; ++i){
printf("%f \t %f",vx[i],vy[i]);
f<<vx[i]<<" \t "<<vy[i];
if (is3D) {printf("\t %f",vz[i]); f<<"\t "<<vz[i];}
printf("\n");
f<<"\n";
}
printf("}\n");
f<<"}\n";
f.close();
}
else{
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("\nInstance saved in file: \"instance.dat\", with a graphical representation in: \"Figure.tex\".\n");
ofstream f("instance.dat");
f<<std::setprecision(5);
f<<"p0={\n";
printf("p0={\n"); //initial position
for (int i = 0; i < n; ++i){
printf("%f \t %f",x_0[i],y_0[i]);
f<<x_0[i]<<" \t "<<y_0[i];
if (is3D) {printf("\t %f",z_0[i]); f<<"\t "<<z_0[i];}
printf("\n");
f<<"\n";
}
printf("}\n");
f<<"}\n";
// printf("p1={\n"); //final position
// for (int i = 0; i < n; ++i){
// printf("%f \t %f",x_t[i],y_t[i]);
// if (is3D) printf("\t %f",z_t[i]);
// printf("\n");
// }
// printf("}\n");
printf("V_polar=(v,theta"); //polar velocity i.e. (hat_v,hat_theta,hat_phi)
f << "V_polar=(v,theta";
if (is3D) {printf(",phi"); f<<",phi";}
printf(")={\n");
f<<")={\n";
for (int i = 0; i < n; ++i){
printf("%f \t %f",hat_v[i],correctAngle(hat_theta[i]));
f<<hat_v[i]<<" \t "<<correctAngle(hat_theta[i]);
if (is3D) {printf("\t %f",correctAngle(hat_phi[i])); f<<"\t "<<correctAngle(hat_phi[i]);}
printf("\n");
f<<"\n";
}
printf("}\n");
f<<"}\n";
//---------------------complementary output
printf("(Vx,Vy,Vz)={\n"); //components of the velocity
f<<"(Vx,Vy,Vz)={\n";
for (int i = 0; i < n; ++i){
printf("%f \t %f",vx[i],vy[i]);
f<<vx[i]<<" \t "<<vy[i];
if (is3D) {printf("\t %f",vz[i]); f<<"\t "<<vz[i];}
printf("\n");
f<<"\n";
}
printf("}\n");
f<<"}\n";
f.close();
}
printf("--------------------------------------------------------------------------------------------------\n");
printf("Some additional information about the instance you just generated:\n");
printf("\nPairs in conflict:\n");
int num_conflicts=0;
int conf_aircraft[n];
for (int i = 0; i < n; ++i) conf_aircraft[i]=0;
for (int i = 0; i < n; ++i) {
for (int j = i+1; j < n; ++j){
if(conflict(i,j)){
printf("(%i, %i) with distance at the time of minimal separation: %f,",i+1,j+1,sqrt(dist_min(i,j)));
printf(" and duration of conflict: %f hour.\n",duration(i,j));
conf_aircraft[i]++;
conf_aircraft[j]++;
num_conflicts++;
}
}
}
printf("Nº conflicts per aircraft:\n");
int aircraft_conflict=0;
for (int i = 0; i < n; ++i){
printf("%i, ", conf_aircraft[i]);
if(conf_aircraft[i]!=0) aircraft_conflict++;
}
printf("\nProportion of aircraft with one conflict or more: %f\nTotal pairs in conflict: %i\n",aircraft_conflict/(n*1.0),num_conflicts);
printf("Proportion of pairs of conflicts: %f\n",(2.0*num_conflicts)/(n*(n-1)));
// Generate Latex file with figure
string colors[18]={ "brown", "cyan", "blue","green",
"lightgray", "lime", "magenta", "olive", "gray", "orange",
"pink", "purple", "red", "teal", "violet", "teal", "yellow","darkgray"};
int color_index=0;
ofstream f("Figure.tex");
if (!f.is_open()){ printf("Error when trying to write latex file\n");return;}
f<<"\\documentclass[border=10pt,varwidth]{standalone}\n";
f<<"\\usepackage{tikz,tikz-3dplot}\n";
f<<"\\usetikzlibrary{shapes,snakes}\n";
f<<"\\begin{document}\n";
float scale;
if (mode==6 ||mode==7 || mode==14 || mode==1 || mode==0 || mode==8 || mode==9 || mode==15) {scale=0.02;}
else {scale=0.05;}
if (is3D){
f<<"\\tdplotsetmaincoords{70}{145}\n";
f<<"\\begin{tikzpicture} [scale="<<scale<<", tdplot_main_coords, axis/.style={->,black,thick}, vector/.style={-stealth,black,very thick},vector guide/.style={dotted,black,thick},]\n";
f<<"\\coordinate (O) at (0,0,0);\n";
f<<"\\pgfmathsetmacro{\\ax}{1}\n";
f<<"\\pgfmathsetmacro{\\ay}{-1}\n";
f<<"\\pgfmathsetmacro{\\az}{0.5}\n";
if (mode==10||mode==11|| mode==12 || mode==13){
f<<"\\draw[axis] (0,0,0) -- (150,0,0) node[anchor=north east]{$x$};\n";
f<<"\\draw[axis] (0,0,0) -- (0,150,0) node[anchor=south]{$y$};\n";
f<<"\\draw[axis] (0,0,0) -- (0,0,150) node[anchor=south]{$z$};\n";
}
else{
f<<"\\draw[axis] (0,0,0) -- (400,0,0) node[anchor=north east]{$x$};\n";
f<<"\\draw[axis] (0,0,0) -- (0,400,0) node[anchor=south]{$y$};\n";
f<<"\\draw[axis] (0,0,0) -- (0,0,400) node[anchor=south]{$z$};\n";
}
//f<<"\\node[star, fill, minimum size=3pt, inner sep=0pt,label=right:alt_step] at (0,0,"<<altitude_step<<") {};\n";
}
else{f<<"\\begin{tikzpicture}[scale="<<scale<<"]\n";}
for(int i=0;i<n;i++){
f<<"\\coordinate ("<<i+1<<") at ("<<x_0[i]<<", "<<y_0[i];
if(is3D) f<<", "<<z_0[i];
f<<");\n";
f<<"\\draw[color="<<colors[color_index]<<",thick, ->] ("<<i+1<<") -- ("<<x_t[i]<<", "<<y_t[i];
if(is3D) f<<", "<<z_t[i];
f<<");\n";
if(x_0[i]>=0.5) f<<"\\node[circle, fill, minimum size=3pt, inner sep=0pt,label=right:"<<i+1<<"] at ("<<i+1<<") {};\n";
else if(x_0[i]<=-0.5) f<<"\\node[circle, fill, minimum size=3pt, inner sep=0pt,label=left:"<<i+1<<"] at ("<<i+1<<") {};\n";
else {
if(y_0[i]>=0) f<<"\\node[circle, fill, minimum size=4pt, inner sep=0pt,label=above:"<<i+1<<"] at ("<<i+1<<") {};\n";
else f<<"\\node[circle, fill, minimum size=3pt, inner sep=0pt,label=below:"<<i+1<<"] at ("<<i+1<<") {};\n";
}
if(color_index<18) color_index++;
if(color_index==18) color_index=0;
}
f<<"\\end{tikzpicture}\n";
f<<"\\newline \\vspace*{2cm} \\newline Pairs in conflict: \\newline";
for (int i = 0; i < n; ++i) {
for (int j = i+1; j < n; ++j){
if(conflict(i,j))
f<<"("<<i+1<<","<<j+1<<") ";
}
}
f<<"\\newline Nº conflicts per aircraft: \\newline";
for (int i = 0; i < n; ++i){
if (i == n-1)
f<<conf_aircraft[i]<<".";
else
f<<conf_aircraft[i]<<", ";
}
f<<"\\end{document}\n";
f.close();
}
// --------------------------------------------------------------------------
// ----- SCENARIO GENERATORS -------
// --------------------------------------------------------------------------
/*
There are 15 scenarios in total, each one has an associated code in the variable "mode"
- 2D Scenarios:
*Predefined:
+ circle --> mode= 0
+ randomCircle --> mode= 1
+ rombo --> mode= 2
+ randomRombo --> mode= 3
+ grid --> mode= 4
+ randomGrid --> mode= 5
*Random:
+ pseudorandom --> mode= 6
+ random --> mode= 7
- 3D Scenarios:
*Predefined:
+ sphere --> mode= 8
+ randomsphere --> mode= 9
+ Polyhedral --> mode= 10
+ randomPolyhedralP --> mode= 11
+ Grid3d --> mode= 12
+ randomGrid3d --> mode= 13
*Random:
+ pseudorandom --> mode= 14
+ random --> mode= 15
*/
// --------------------------------------------------------------------------
// ----- PREDEFINED SCENARIOS -------
// --------------------------------------------------------------------------
//************** Predefined 2D scenarios *******************
// #### 1. CIRCLE SCENARIOS ####
// randomCircleP: set initial positions (x_0,y_0), vectors of velocity (vx,vy)
// and final positions (x_t,y_t) of the random circle problem.
// Heading angles are deviated from those of circle problem a random amount in the interval [hamin,hamax]
// sector_ini=0 and sector_angle=2*M_PI gives the classical circle configuration
// sector_ini=M_PI and sector_angle=M_PI/2 gives the "quarter" circle configuration in S. Cafieri & N. Durand. (2014):
// "Aircraft deconfliction with speed regulation: new modelsfrom mixed-integer optimization", JOGO.
// Otherwise, these parameters allow the user to select where the first aircraft is placed (sector_ini) and the
// total angle covered by the sector between the first and the last aircraft (sector_angle)
void randomCircleP(float radius,float sector_ini_x,double sector_angle_x,float hamin,float hamax){
float angle_step;
if (sector_angle_x==2*M_PI)
angle_step=sector_angle_x/n;
else
angle_step=sector_angle_x/(n-1);
float v,dev;
for (int i = 0; i < n; ++i){
x_0[i]=radius*cos(i*angle_step+sector_ini_x);
y_0[i]=radius*sin(i*angle_step+sector_ini_x);
v=randomFloat(vmin,vmax);
dev=randomFloat(hamin,hamax);
vx[i]=-v*cos(i*angle_step+sector_ini_x+dev);
vy[i]=-v*sin(i*angle_step+sector_ini_x+dev);
hat_v[i]=v;
hat_theta[i]=i*angle_step+dev+sector_ini_x;
x_t[i]=x_0[i]-2*radius*cos(i*angle_step+sector_ini_x+dev);
y_t[i]=y_0[i]-2*radius*sin(i*angle_step+sector_ini_x+dev);
float final_position[2]= { x_t[i],y_t[i] };
float final_position_norm=norm(final_position,2);
if(abs(x_t[i])>radius || abs(y_t[i])>radius)
{x_t[i]=radius*x_t[i]/final_position_norm; y_t[i]=radius*y_t[i]/final_position_norm;}
}
if (hamin==0 and hamax==0){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Circle Problem Generator: circle with radius: %.2f\n",radius);
printf("Aircraft generated with heading angles in the range: [%.2f,%.2f]",sector_ini_x,sector_angle_x);
}
else{
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random-circle Problem Generator: circle with radius: %.2f\n",radius);
printf("Aircraft generated with heading angles in the range: [%.2f,%.2f]",sector_ini_x,sector_angle_x);
}
}
// CircleP(float radius): scenario generated with the function randomCircleP and 0 angle deviation
void CircleP(float radius, float sector_ini_x,double sector_angle_x){
randomCircleP(radius,sector_ini_x,sector_angle_x,0,0);
}
// #### 2. RHOMBOIDAL and GRID SCENARIOS ###
// randomRomboP: set initial positions (x_0,y_0), vectors of velocity (vx,vy) and
// final positions (x_t,y_t) of the random rombo problem. Heading angles are deviated from
// those of rombo problem a random amount in the interval [hamin,hamax]
// horiz_trails (resp. verti_trails)= number of horizontal (resp. vertical) trails
// nx (resp. ny)= number of aircraft per horizontal (resp. vertical) trail
// dx (resp. dy)= separation between horizontal (resp. vertical) trails
void randomRomboP(double alpha_r,int horiz_trails,int verti_trails,int nx,int ny,float dx,float dy,float d_aircraft,float hamin,float hamax){
float v,dev;
float first_height=sin(alpha_r)*(ny-1)*d_aircraft+dx; // vertical position of the first horizontal trail (from lower to upper)
float first_width=(nx-1)*d_aircraft+dy; // horizontal position of the first vertical trail (from left to right)
float last_width=first_width+(verti_trails-1)*dy; // end of horizontal trails (for drawing)
// Loop to create trajectories at horizontal trails:
for (int i = 0; i < horiz_trails; ++i){
for (int k = 0; k < nx; ++k){ // * *------------------------------- i= horiz_trails-1
x_0[i*nx+k]=k*d_aircraft; // * *------------------------------- i=2
y_0[i*nx+k]=first_height+i*dx; // * *------------------------------- i=1
v=randomFloat(vmin,vmax); // * *------------------------------- i=0
dev=randomFloat(hamin,hamax); // *=aircraft, in this example nx=2 aircraft per trail
vx[i*nx+k]=v*cos(dev);
vy[i*nx+k]=v*sin(dev);
hat_v[i*nx+k]=v;
hat_theta[i*nx+k]=dev;
x_t[i*nx+k]=x_0[i*nx+k]+last_width*cos(dev);
y_t[i*nx+k]=y_0[i*nx+k]+last_width*sin(dev);
}
}
int cont=horiz_trails*nx; // number of aircraft for which we already generated trajectories
float ini_width;
int sign;
if(alpha_r<=M_PI/2){ // corresponds with this slope: "/"
ini_width=first_width;
sign=1;
}
else{ // corresponds with this slope: "\"
ini_width=last_width;
sign=-1;
}
// Loop to create trajectories at vertical trails
for (int i = 0; i < verti_trails; ++i){
for (int k = 0; k < ny; ++k){ //----/---/---/---/---/---/----
x_0[cont+i*ny+k]=ini_width+sign*i*dy+k*d_aircraft*cos(alpha_r); //----/---/---/---/---/---/-----
y_0[cont+i*ny+k]=k*d_aircraft*sin(alpha_r); //----/---/---/---/---/---/-----
v=randomFloat(vmin,vmax); //---/---/---/---/---/---/-----
dev=randomFloat(hamin,hamax); // i=0 i=1 i=2 i=verti_trails-1
vx[cont+i*ny+k]=v*cos(alpha_r+dev);
vy[cont+i*ny+k]=v*sin(alpha_r+dev);
hat_v[cont+i*ny+k]=v;
hat_theta[cont+i*ny+k]=alpha_r+dev;
x_t[cont+i*ny+k]=x_0[cont+i*ny+k]+(first_height+dx*horiz_trails)*cos(alpha_r+dev);
y_t[cont+i*ny+k]=y_0[cont+i*ny+k]+(first_height+dx*horiz_trails)*sin(alpha_r+dev);
}
}
if (hamin==0 and hamax==0 and alpha_r==M_PI/2){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Grid Problem Generator"); }
else if (hamin==0 and hamax==0) {
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Rombo Problem Generator");
}
else if (alpha_r==M_PI/2){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random-grid Problem Generator");
}
else{
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random-rombo Problem Generator");
}
}
// RomboP: scenario generated with the function randomRomboP and 0 angle deviation
void RomboP(float alpha_r,int horiz_trails,int verti_trails,int nx,int ny,float dx,float dy,float d_aircraft){
randomRomboP(alpha_r,horiz_trails,verti_trails,nx,ny,dx,dy,d_aircraft,0,0);
}
// GridP: scenario generated with the function randomRomboP, alpha_r=pi/2 and 0 angle deviation
void GridP(int horiz_trails,int verti_trails,int nx,int ny,float dx,float dy,float d_aircraft){
randomRomboP(M_PI/2,horiz_trails,verti_trails,nx,ny,dx,dy,d_aircraft,0,0);
}
// GridP: scenario generated with the function randomRomboP and alpha_r=pi/2
void randomGridP(int horiz_trails,int verti_trails,int nx,int ny,float dx,float dy,float d_aircraft,float hamin,float hamax){
randomRomboP(M_PI/2,horiz_trails,verti_trails,nx,ny,dx,dy,d_aircraft,hamin,hamax);
}
//************** Predefined 3D scenarios *******************
// #### 3. SPHERE SCENARIOS ###
// randomSphereP: set initial positions (x_0,y_0,z0), vectors of velocity (vx,vy,vz)
// and final positions (x_t,y_t,z_t) of the sphere problem, with the possibility to be in a certain portion of the sphere
// Heading angles are deviated from those of sphere problem a random amount in the interval [hamin,hamax]
void randomSphereP(float radius,float sector_ini_x,double sector_angle_x,float sector_ini_z,double sector_angle_z,float hamin,float hamax){
double theta[n]; double phi[n]; // starting angles of the 3d configuration
float v,dev1,dev2;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 gen(seed);
std::uniform_real_distribution<float> uniform01(0.0, 1.0); // uniform distribution
for (int i = 0; i < n; ++i){
theta[i] = sector_ini_x+sector_angle_x*uniform01(gen); // we generate uniformly distributed points on the sphere
phi[i] = abs(acos(cos((double)(sector_ini_z)) - (cos((double)(sector_ini_z))-cos((double)(sector_ini_z)+sector_angle_z)) * uniform01(gen))); //phi must be in [sector_ini_z,sector_ini_z+sector_angle_z]
x_0[i] = radius*sin(phi[i]) * cos(theta[i]);
y_0[i] = radius*sin(phi[i]) * sin(theta[i]);
z_0[i] = radius*cos(phi[i]);
v=randomFloat(vmin,vmax);
dev1=randomFloat(hamin,hamax);
dev2=randomFloat(hamin,hamax);
if (phi[i]+dev2<sector_ini_z) {dev2=sector_ini_z-phi[i];}
else if (phi[i]+dev2>sector_ini_z+sector_angle_z) {dev2=sector_ini_z+sector_angle_z-phi[i];}
vx[i]=-v*cos(theta[i]+dev1)*sin(phi[i]+dev2);
vy[i]=-v*sin(theta[i]+dev1)*sin(phi[i]+dev2);
vz[i]=-v*cos(phi[i]+dev2);
hat_v[i]=v;
hat_theta[i]=theta[i]+dev1;
hat_phi[i]=phi[i]+dev2;
x_t[i]=x_0[i]-2*radius*cos(theta[i]+dev1)*sin(phi[i]+dev2);
y_t[i]=y_0[i]-2*radius*sin(theta[i]+dev1)*sin(phi[i]+dev2);
z_t[i]=z_0[i]-2*radius*cos(phi[i]+dev2);
// we want the final positions of the aircraft being ON the surface of the sphere
float final_position[3]= { x_t[i],y_t[i],z_t[i] };
float final_position_norm=norm(final_position,3);
if(final_position_norm>radius) //points outside the sphere
{x_t[i]=radius*x_t[i]/final_position_norm; y_t[i]=radius*y_t[i]/final_position_norm; z_t[i]=radius*z_t[i]/final_position_norm;}
}
if (hamin==0 and hamax==0){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Sphere Problem Generator: sphere with radius: %.2f\n",radius);
printf("Aircraft generated with theta in the range [%.2f,%.2f], and phi in the range [%.2f,%.2f]",sector_ini_x,sector_ini_x+sector_angle_x,sector_ini_z,sector_ini_z+sector_angle_z);
}
else{
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random-sphere Problem Generator: sphere with radius: %.2f\n",radius);
printf("Aircraft generated with theta in the range [%.2f,%.2f], and phi in the range [%.2f,%.2f]",sector_ini_x,sector_ini_x+sector_angle_x,sector_ini_z,sector_ini_z+sector_angle_z);
}
}
// SphereP: scenario generated with the function randomSphereP and 0 angle deviation
void SphereP(float radius,float sector_ini_x,double sector_angle_x,float sector_ini_z,double sector_angle_z){
randomSphereP(radius,sector_ini_x,sector_angle_x,sector_ini_z,sector_angle_z,0,0);
}
// #### 4. POLYHEDRAL SCENARIOS ###
// ----------------------------------------
// HP = horizontal planes = planes parallel to xy plane
// VP = vertical planes = planes parallel to xz plane
// mx = horizontal trails on horizontal planes = trails parallel to x_axis and perpendicular to y_axis
// my = "vertical" trails on horizontal planes = trails forming an alpha angle with the HP_HT (and with x_axis)
// mz = "vertical" trails on vertical planes = trails forming a beta angle with the VP_HT (and with x axis)
// ----------------------------------------
// randomPolyhedralP: set initial positions (x_0,y_0,z_0), vectors of velocity (vx,vy,vz) and
// final positions (x_t,y_t,z_t) of the random polyhedral problem. Heading angles are deviated from
// those of polyhedral problem of a random amount in the interval [hamin,hamax]
void randomPolyhedralP(double* alpha,double* beta,int* mx,int* my,int* mz,int nx,int ny,int nz,float d_HP,float d_VP,float dx,float dy,float dz,float d_aircraft,float hamin,float hamax){
float v,dev;
float ini_my; float ini_mz; int sign; //necessary since alpha and beta could be > or < 90°
float first_VP=d_VP; // horizontal position of the first vertical plane (from left to right)
// since there is a different beta[j] for each vertical plane j, we use the following approach to compute the vertical position of the first horizontal plane
// (similar to the first position of the first horizontal trail on each horizontal plane, i.e. first_mx[j])
float a=0;
for (int j=0; j < VP; ++j){
if(sin(beta[j])*(nz-1)*d_aircraft>a)
a=sin(beta[j])*(nz-1)*d_aircraft;
}
float first_HP=a+d_HP; // vertical position of the first horizontal plane (from lower to upper)
// We focus on horizontal planes:
float first_mx[HP]; // vector of vertical positions of the first horizontal trail (from lower to upper) for each horizontal plane
float first_my=(nx-1)*d_aircraft+dy; // horizontal position of the first sloping trail (from left to right), the same for each horizontal plane
float last_my[HP]; // horizontal position of the last sloping trail for each horizontal plane
int cont=0; // number of aircraft for which we already generated trajectories
for (int j=0; j < HP; ++j){
// For each j, we consider the j-th HP:
first_mx[j]=sin(alpha[j])*(ny-1)*d_aircraft+dx; // vertical positions of the first horizontal trail on the j-th horizontal plane
last_my[j]=first_my+dy*(my[j]-1); // horizontal position of the last sloping trail on the j-th horizontal plane
// Loop to create trajectories at horizontal trails:
for (int i = 0; i < mx[j]; ++i){
for (int k = 0; k < nx; ++k){ // * *------------------------------- i= mx[j]-1
x_0[cont+i*nx+k]=k*d_aircraft; // * *------------------------------- i=2
y_0[cont+i*nx+k]=first_mx[j]+i*dx; // * *------------------------------- i=1
z_0[cont+i*nx+k]=first_HP+j*d_HP; // * *------------------------------- i=0
v=randomFloat(vmin,vmax); // *=aircraft, in this example nx=2 aircraft per trail
dev=randomFloat(hamin,hamax);
vx[cont+i*nx+k]=v*cos(dev);
vy[cont+i*nx+k]=v*sin(dev);
vz[cont+i*nx+k]=0;
hat_v[cont+i*nx+k]=v;
hat_theta[cont+i*nx+k]=dev;
x_t[cont+i*nx+k]=x_0[cont+i*nx+k]+last_my[j]*cos(dev);
y_t[cont+i*nx+k]=y_0[cont+i*nx+k]+last_my[j]*sin(dev);
z_t[cont+i*nx+k]=z_0[cont+i*nx+k];
}
}
cont=cont+mx[j]*nx;
if(alpha[j]<=M_PI/2){ // corresponds with this slope: "/"
ini_my=first_my;
sign=1;}
else{// corresponds with this slope: "\"
ini_my=last_my[j];
sign=-1;}
// Loop to create trajectories at sloping trails
for (int i = 0; i < my[j]; ++i){
for (int k = 0; k < ny; ++k){ //----/---/---/---/---/---/----
x_0[cont+i*ny+k]=ini_my+sign*i*dy+k*d_aircraft*cos(alpha[j]); //----/---/---/---/---/---/-----
y_0[cont+i*ny+k]=k*d_aircraft*sin(alpha[j]); //----/---/---/---/---/---/------
z_0[cont+i*ny+k]=first_HP+j*d_HP; //----/---/---/---/---/---/------
v=randomFloat(vmin,vmax); // i=0 i=1 i=2 i=my-1
dev=randomFloat(hamin,hamax);
vx[cont+i*ny+k]=v*cos(alpha[j]+dev);
vy[cont+i*ny+k]=v*sin(alpha[j]+dev);
vz[cont+i*ny+k]=0;
hat_v[cont+i*ny+k]=v;
hat_theta[cont+i*ny+k]=alpha[j]+dev;
x_t[cont+i*ny+k]=x_0[cont+i*ny+k]+(first_mx[j]+dx*mx[j])*cos(alpha[j]+dev);
y_t[cont+i*ny+k]=y_0[cont+i*ny+k]+(first_mx[j]+dx*mx[j])*sin(alpha[j]+dev);
z_t[cont+i*ny+k]=z_0[cont+i*ny+k];
}
}
cont=cont+my[j]*ny;
}
// We focus on vertical planes, where only sloping (parallel to (x,z)-plane and perpendicular to (x,y)-plane) trajectories are generated:
float first_mz=dz; // horizontal position of the first sloping trail (from left to right), the same for each vertical plane
float last_mz[VP]; // vector of horizontal positions of the last sloping trail (from left to right) for each vertical plane
for (int j=0; j < VP; ++j){
// For each j, we consider the j-th VP:
last_mz[j]=first_mz+dz*(mz[j]-1);
if(beta[j]<=M_PI/2){ // corresponds with this slope: "/"
ini_mz=first_mz;
sign=1;}
else{// corresponds with this slope: "\"
ini_mz=last_mz[j];
sign=-1;}
// Loop to create trajectories at sloping trails (assuming aircraft start flying from the bottom):
for (int i = 0; i < mz[j]; ++i){
for (int k = 0; k < nz; ++k){
x_0[cont+i*nz+k]=ini_mz+sign*i*dz+k*d_aircraft*cos(beta[j]); //----/---/---/---/---/---/-----
y_0[cont+i*nz+k]=first_VP+j*d_VP; //----/---/---/---/---/---/------
z_0[cont+i*nz+k]=k*d_aircraft*sin(beta[j]); //----/---/---/---/---/---/------
v=randomFloat(vmin,vmax); // i=0 i=1 i=2 i=mz[j]-1
dev=randomFloat(hamin,hamax);
vx[cont+i*nz+k]=v*cos(beta[j]+dev);
vy[cont+i*nz+k]=0;
vz[cont+i*nz+k]=v*sin(beta[j]+dev);
hat_v[cont+i*nz+k]=v;
hat_theta[cont+i*nz+k]=beta[j]+dev;
x_t[cont+i*nz+k]=x_0[cont+i*nz+k]+(first_HP+d_HP*HP)*cos(beta[j]+dev);
y_t[cont+i*nz+k]=y_0[cont+i*nz+k];
z_t[cont+i*nz+k]=z_0[cont+i*nz+k]+(first_HP+d_HP*HP)*sin(beta[j]+dev);
}
}
cont=cont+mz[j]*nz;
}
// output message:
bool grid = true;
for(int i=0;i<HP;++i){
if (alpha[i]!=M_PI/2){ grid = false;}
if (beta[i]!=M_PI/2) { grid =false;}
}
if (hamin==0 and hamax==0 and grid){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Cubic Problem Generator");
}
else if (hamin==0 and hamax==0) {
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Polyhedral Problem Generator");
}
else if (grid){
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random-cubic Problem Generator");
}
else{
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random-polyhedral Problem Generator");
}
}
// PolyhedralP: scenario generated with the function randomPolyhedralP and 0 angle deviation
void PolyhedralP(double* alpha,double* beta,int* mx,int* my,int* mz,int nx,int ny,int nz,float d_HP,float d_VP,float dx,float dy,float dz,float d_aircraft){
randomPolyhedralP(alpha,beta,mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft,0,0);
}
// Grid3dP: scenario generated with the function randomPolyhedralP and alpha=beta=pi/2 and 0 angle deviation
void Grid3dP(int* mx,int* my,int* mz,int nx,int ny,int nz,float d_HP,float d_VP,float dx,float dy,float dz,float d_aircraft){
double grid3dalpha[HP];
double grid3dbeta[VP];
for(int i=0;i<HP;++i){
grid3dalpha[i]=M_PI/2;
}
for(int i=0;i<VP;++i){
grid3dbeta[i]=M_PI/2;
}
randomPolyhedralP(grid3dalpha,grid3dbeta,mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft,0,0);
}
// randomGrid3dP: scenario generated with the function randomPolyhedral and alpha=beta=pi/2
void randomGrid3dP(int* mx,int* my,int* mz,int nx,int ny,int nz,float d_HP,float d_VP,float dx,float dy,float dz,float d_aircraft,float hamin,float hamax){
double grid3dalpha[HP];
double grid3dbeta[VP];
for(int i=0;i<HP;++i){
grid3dalpha[i]=M_PI/2;
}
for(int i=0;i<VP;++i){
grid3dbeta[i]=M_PI/2;
}
randomPolyhedralP(grid3dalpha,grid3dbeta,mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft,hamin,hamax);
}
//************** Random scenarios *******************
// This auxiliary method generates the initial position of aircraft for a pseudo-random scenario
void pseudoRandomP_iniPos(char* air_config,float height,float width, float altitude, float* hamin,float* hamax, float* phimin, float* phimax){
// 1. -------- Partition airspace into a 2d or 3d matrix of size (m x l) or (m x l x a) respectively s.t. m/l=height/width m/a=height/altitude l/a=width/altitude
// This is done to create cells in the airspace and place one aircraft in each cell, instead of randomly generating the initial positions in the full airspace.
// This guarantees that the aircraft are spread.
float m,l,a; // dimensions of the matrix. Each aircraft is placed on one cell of the resulting matrix
int new_n; // new_n is the total number of cells
// The value of new_n depends on configuration:
// ***** 2D cases *****
// "W-N": aircraft placed at left and top of R, new_n=m+l-1
// "N-S": aircraft placed at bottom and top of R, new_n=2l
// "W-E": aircraft placed at left and right of R, new_n=2m
// "all": aircraft placed at all sides of R, new_n=2*m+2*l-4
// ***** 3D cases ***** //D=bottom, U=top
// "W-U": aircraft placed at (x=0,y,z) and top faces of P, new_n=m*a+m*l-m
// "N-U": aircraft placed at (x,y=0,z) and top faces of P, new_n=l*a+m*l-l
// "U-D": aircraft placed at bottom and top faces of P, new_n=2*m*l
// "W-N": aircraft placed at (x=0,y,z) and (x,y=0,z) faces of P, new_n=m*a+l*a-a
// "N-S": aircraft placed at (x,y=0,z) and (x,y=height,z) faces of P, new_n=2*l*a
// "W-E": aircraft placed at (x=0,y,z) and (x=width,y,z) faces of P, new_n=2*m*a
// "all": aircraft placed at all faces of P, new_n=(2*m+2*l-4)*a+(l-2)*(m-2)*2
// new_n can be different from n, we will leave empty cells if needed
// In the following, we generate m,l,a and new_n depending on the selected airspace configuration:
int all=0; // will be set to 1 if the selected configuration is 'all'
if(is3D==false){
a=1; //it should be 0, but we set it to 1 in order to avoid an undefined altitude_step = altitude/a in the following
if(strcmp(air_config,"W-N")==0){ // Scenario W-N: (in the example, m=5 (rows), l=4 (columns))
l=(n+1)/(height/width+1); // x x x x
m=ceil(height*l/width); // x
l=ceil(l); // x
new_n=m+l-1; // number of "x" in the example:8 // x
} // x
else if(strcmp(air_config,"N-S")==0){ // Scenario N-S:
l=n/2.0; // x x x x x
m=ceil(height*l/width);
l=ceil(l);
new_n=2*l; // x x x x x
} // Scenario W-E:
else if(strcmp(air_config,"W-E")==0){ // x x
m=n/2.0; // x x
l=ceil(width*m/height); // x x
m=ceil(m); // x x
new_n=2*m; // x x
} // Scenario all:
else{ // x x x x x
l=(n+4)/(2*(height/width+1)); // x x
m=ceil(height*l/width); // x x
l=ceil(l); // x x
new_n=2*m+2*l-4; // x x x x x
all=1;
if(strcmp(air_config,"all")!=0 and verbose)
printf("Pseudo-random Problem Generator: unvalid or unexisting airspace configuration for random scenario, using default\n");
}
printf("\n----------------------------------------------------------------------------------------------\n");
printf("Pseudo-random Problem Generator: grid with %i rows, %i columns, %i cells, %i of them not used\n",(int)m,(int)l,new_n,new_n-n);
}
else{
if(strcmp(air_config,"W-U")==0){
float m_true;
m_true=(1+sqrt(1+4*n*(altitude+width)/height))/(2*(altitude+width)/height);
// we approximate al the parameters to the previous integer
l=floor(m_true*width/height);
a=floor(m_true*altitude/height);
m=floor(m_true);
new_n=m*a+m*l-m;
if(new_n<n){
// we approximate the maximum among m, l, and a to the next integer
if (max(max(m,l),a)==m){m=ceil(m_true);l=floor(m_true*width/height); a=floor(m_true*altitude/height);}
else if (max(max(m,l),a)==l){m=floor(m_true); l=ceil(m_true*width/height); a=floor(m_true*altitude/height);}
else{m=floor(m_true);l=floor(m_true*width/height); a=ceil(m_true*altitude/height);}
new_n=m*a+m*l-m;
}
if(new_n<n){
// we approximate the maximum among the remaining parameters to the next integer
if (m==ceil(m_true)&&max(l,a)==l){l=ceil(m_true*width/height);a=floor(m_true*altitude/height);}
else if (m==ceil(m_true)&&max(l,a)==a){l=floor(m_true*width/height);a=ceil(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==m){m=ceil(m_true);a=floor(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==a){m=floor(m_true);a=ceil(m_true*altitude/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==m){m=ceil(m_true);l=floor(m_true*width/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==l){m=floor(m_true);l=ceil(m_true*width/height);}
new_n=m*a+m*l-m;
}
if(new_n<n){
// we approximate all the parameters to the next integer
l=ceil(m_true*width/height);
a=ceil(m_true*altitude/height);
m=ceil(m_true);
new_n=m*a+m*l-m;
}
}
else if(strcmp(air_config,"S-U")==0){
float l_true;
l_true=(1+sqrt(1+4*n*(altitude+height)/width))/(2*(altitude+height)/width);
m=floor(l_true*height/width);
a=floor(l_true*altitude/width);
l=floor(l_true);
new_n=l*a+m*l-l;
if(new_n<n){
if (max(max(m,l),a)==m){m=ceil(l_true*height/width);l=floor(l_true);a=floor(l_true*altitude/width);}
else if (max(max(m,l),a)==l){m=floor(l_true*height/width);l=ceil(l_true);a=floor(l_true*altitude/width);}
else{m=floor(l_true*height/width);l=floor(l_true);a=ceil(l_true*altitude/width);}
new_n=l*a+m*l-l;
}
if(new_n<n){
if (m==ceil(l_true*height/width)&&max(l,a)==l){l=ceil(l_true);a=floor(l_true*altitude/width);}
else if (m==ceil(l_true*height/width)&&max(l,a)==l){l=floor(l_true);a=ceil(l_true*altitude/width);}
else if (l==ceil(l_true)&&max(m,a)==m){m=ceil(l_true*height/width);a=floor(l_true*altitude/width);}
else if (l==ceil(l_true)&&max(m,a)==a){m=floor(l_true*height/width);a=ceil(l_true*altitude/width);}
else if (a==ceil(l_true*altitude/width)&&max(m,l)==m){m=ceil(l_true*height/width);l=floor(l_true);}
else if (a==ceil(l_true*altitude/width)&&max(m,l)==l){m=floor(l_true*height/width);l=ceil(l_true);}
new_n=l*a+m*l-l;
}
if(new_n<n){
m=ceil(l_true*height/width);
a=ceil(l_true*altitude/width);
l=ceil(l_true);
new_n=l*a+m*l-l;
}
}
else if(strcmp(air_config,"U-D")==0){
float m_true;
m_true=sqrt(n*height/(width*2));
l=floor(m_true*width/height);
a=floor(m_true*altitude/height);
m=floor(m_true);
new_n=2*m*l;
if(new_n<n){
if (max(max(m,l),a)==m){m=ceil(m_true);l=floor(m_true*width/height); a=floor(m_true*altitude/height);}
else if (max(max(m,l),a)==l){m=floor(m_true); l=ceil(m_true*width/height); a=floor(m_true*altitude/height);}
else{m=floor(m_true);l=floor(m_true*width/height); a=ceil(m_true*altitude/height);}
new_n=2*m*l;
}
if(new_n<n){
if (m==ceil(m_true)&&max(l,a)==l){l=ceil(m_true*width/height);a=floor(m_true*altitude/height);}
else if (m==ceil(m_true)&&max(l,a)==a){l=floor(m_true*width/height);a=ceil(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==m){m=ceil(m_true);a=floor(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==a){m=floor(m_true);a=ceil(m_true*altitude/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==m){m=ceil(m_true);l=floor(m_true*width/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==l){m=floor(m_true);l=ceil(m_true*width/height);}
new_n=2*m*l;
}
if(new_n<n){
l=ceil(m_true*width/height);
a=ceil(m_true*altitude/height);
m=ceil(m_true);
new_n=2*m*l;
}
}
else if(strcmp(air_config,"W-N")==0){
float a_true;
a_true=(1+sqrt(1+4*n*(width+height)/altitude))/(2*(width+height)/altitude);
m=floor(a_true*height/altitude);
l=floor(a_true*width/altitude);
a=floor(a_true);
new_n=l*a+m*a-a;
if(new_n<n){
if (max(max(m,l),a)==m){m=ceil(a_true*height/altitude);l=floor(a_true*width/altitude);a=floor(a_true);}
else if (max(max(m,l),a)==l){m=floor(a_true*height/altitude);l=ceil(a_true*width/altitude);a=floor(a_true);}
else{m=floor(a_true*height/altitude);l=floor(a_true*width/altitude);a=ceil(a_true);}
new_n=l*a+m*a-a;
}
if(new_n<n){
if (m==ceil(a_true*height/altitude)&&max(l,a)==l){l=ceil(a_true*width/altitude);a=floor(a_true);}
else if (m==ceil(a_true*height/altitude)&&max(l,a)==a){l=floor(a_true*width/altitude);a=ceil(a_true);}
else if (l==ceil(a_true*width/altitude)&&max(m,a)==m){m=ceil(a_true*height/altitude);a=floor(a_true);}
else if (l==ceil(a_true*width/altitude)&&max(m,a)==a){m=floor(a_true*height/altitude);a=ceil(a_true);}
else if (a==ceil(a_true)&&max(m,l)==m){m=ceil(a_true*height/altitude);l=floor(a_true*width/altitude);}
else if (a==ceil(a_true)&&max(m,l)==l){m=floor(a_true*height/altitude);l=ceil(a_true*width/altitude);}
new_n=l*a+m*a-a;
}
if(new_n<n){
m=ceil(a_true*height/altitude);
l=ceil(a_true*width/altitude);
a=ceil(a_true);
new_n=l*a+m*a-a;
}
}
else if(strcmp(air_config,"N-S")==0){
float l_true;
l_true=sqrt(n*width/(altitude*2));
m=floor(l_true*height/width);
a=floor(l_true*altitude/width);
l=floor(l_true);
new_n=2*l*a;
if(new_n<n){
if (max(max(m,l),a)==m){m=ceil(l_true*height/width);l=floor(l_true);a=floor(l_true*altitude/width);}
else if (max(max(m,l),a)==l){m=floor(l_true*height/width);l=ceil(l_true);a=floor(l_true*altitude/width);}
else{m=floor(l_true*height/width);l=floor(l_true);a=ceil(l_true*altitude/width);}
new_n=2*l*a;
}
if(new_n<n){
if (m==ceil(l_true*height/width)&&max(l,a)==l){l=ceil(l_true);a=floor(l_true*altitude/width);}
else if (m==ceil(l_true*height/width)&&max(l,a)==l){l=floor(l_true);a=ceil(l_true*altitude/width);}
else if (l==ceil(l_true)&&max(m,a)==m){m=ceil(l_true*height/width);a=floor(l_true*altitude/width);}
else if (l==ceil(l_true)&&max(m,a)==a){m=floor(l_true*height/width);a=ceil(l_true*altitude/width);}
else if (a==ceil(l_true*altitude/width)&&max(m,l)==m){m=ceil(l_true*height/width);l=floor(l_true);}
else if (a==ceil(l_true*altitude/width)&&max(m,l)==l){m=floor(l_true*height/width);l=ceil(l_true);}
new_n=2*l*a;
}
if(new_n<n){
m=ceil(l_true*height/width);
a=ceil(l_true*altitude/width);
l=ceil(l_true);
new_n=2*l*a;
}
}
else if(strcmp(air_config,"W-E")==0){
float m_true;
m_true=sqrt(n*height/(altitude*2));
l=floor(m_true*width/height);
a=floor(m_true*altitude/height);
m=floor(m_true);
new_n=2*m*a;
if(new_n<n){
if (max(max(m,l),a)==m){m=ceil(m_true);l=floor(m_true*width/height); a=floor(m_true*altitude/height);}
else if (max(max(m,l),a)==l){m=floor(m_true); l=ceil(m_true*width/height); a=floor(m_true*altitude/height);}
else{m=floor(m_true);l=floor(m_true*width/height); a=ceil(m_true*altitude/height);}
new_n=2*m*a;
}
if(new_n<n){
if (m==ceil(m_true)&&max(l,a)==l){l=ceil(m_true*width/height);a=floor(m_true*altitude/height);}
else if (m==ceil(m_true)&&max(l,a)==a){l=floor(m_true*width/height);a=ceil(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==m){m=ceil(m_true);a=floor(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==a){m=floor(m_true);a=ceil(m_true*altitude/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==m){m=ceil(m_true);l=floor(m_true*width/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==l){m=floor(m_true);l=ceil(m_true*width/height);}
new_n=2*m*a;
}
if(new_n<n){
l=ceil(m_true*width/height);
a=ceil(m_true*altitude/height);
m=ceil(m_true);
new_n=2*m*a;
}
}
else{
all=1;
float m_true;
m_true=(2*((altitude+width+height)/height)+sqrt(4*pow((altitude+width+height)/height,2.0)-2*(8-n)*(altitude*height+width*height+width*altitude)/(pow(height, 2.0))))/(2*(altitude*height+width*height+width*altitude)/(pow(height, 2.0)));
l=floor(m_true*width/height);
a=floor(m_true*altitude/height);
m=floor(m_true);
if (l==1){new_n=a*m;}
else if (m==1){new_n=a*l;}
else if (a==1){new_n=m*l;}
else {new_n=(2*m+2*l-4)*a+(l-2)*(m-2)*2;}
if(new_n<n){
if (max(max(m,l),a)==m){m=ceil(m_true);l=floor(m_true*width/height); a=floor(m_true*altitude/height);}
else if (max(max(m,l),a)==l){m=floor(m_true); l=ceil(m_true*width/height); a=floor(m_true*altitude/height);}
else{m=floor(m_true);l=floor(m_true*width/height); a=ceil(m_true*altitude/height);}
if (l==1){new_n=a*m;}
else if (m==1){new_n=a*l;}
else if (a==1){new_n=m*l;}
else {new_n=(2*m+2*l-4)*a+(l-2)*(m-2)*2;}
}
if(new_n<n){
if (m==ceil(m_true)&&max(l,a)==l){l=ceil(m_true*width/height);a=floor(m_true*altitude/height);}
else if (m==ceil(m_true)&&max(l,a)==a){l=floor(m_true*width/height);a=ceil(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==m){m=ceil(m_true);a=floor(m_true*altitude/height);}
else if (l==ceil(m_true*width/height)&&max(m,a)==a){m=floor(m_true);a=ceil(m_true*altitude/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==m){m=ceil(m_true);l=floor(m_true*width/height);}
else if (a==ceil(m_true*altitude/height)&&max(m,l)==l){m=floor(m_true);l=ceil(m_true*width/height);}
if (l==1){new_n=a*m;}
else if (m==1){new_n=a*l;}
else if (a==1){new_n=m*l;}
else {new_n=(2*m+2*l-4)*a+(l-2)*(m-2)*2;}
}
if(new_n<n){
l=ceil(m_true*width/height);
a=ceil(m_true*altitude/height);
m=ceil(m_true);
if (l==1){new_n=a*m;}
else if (m==1){new_n=a*l;}
else if (a==1){new_n=m*l;}
else {new_n=(2*m+2*l-4)*a+(l-2)*(m-2)*2;}
}
}
if(strcmp(air_config,"all")!=0 and verbose)
printf("random Problem Generator: unvalid or unspecified airspace configuration for random scenario, using default (all configuration).\n");
printf("\n--------------------------------------------------------------------------------------------------------------------\n");
printf("Pseudo-random Problem Generator: three-dimensional matrix with dimensions (%i, %i, %i) and %i cells, %i of them not used\n",(int)m,(int)l,(int)a,new_n,new_n-n);
}
// 2.---------- Generate initial positions (x_0,y_0,z_0), one in each cell
float horizontal_step=width/l;
float vertical_step=height/m;
float altitude_step=altitude/a; //if 2D, altitude_step = 0/1 = 0
if( (horizontal_step< D && strcmp(air_config,"W-E")!=0)||
(vertical_step< D) && strcmp(air_config,"N-S")!=0 ||
((altitude_step< D) && strcmp(air_config,"U-D")!=0 && is3D==true) ){
if(is3D==false)
{D=min(horizontal_step,vertical_step);}
else
{D=min(horizontal_step,min(vertical_step,altitude_step));}
printf("random Problem Generator: safety distance D too big, using %f NM.\n",D);
}
int cont=0; // counts the number of aircraft for which we have alrady generated (x_0,y_0,z_0)
int excess_n=new_n-n; // if more cells than n some of them will be skipped
int skip_xN[(int)a];
int skip_xS[(int)a];
int skip_yW[(int)a];
int skip_yE[(int)a];
int skip_xU[(int)l];
int skip_xD[(int)l];
// randomly generated the cell that will be skipped if needed for each altitude step
for (int j=0; j<a; ++j){
skip_xN[j]=randomInt(0,l-1);
skip_xS[j]=randomInt(0,l-1);
skip_yW[j]=randomInt(0,m-1);
skip_yE[j]=randomInt(0,m-1);
}
for (int j=0; j<l; ++j){
skip_xU[j]=randomInt(0,m-1);
skip_xD[j]=randomInt(0,m-1);
}
//in order to record if we generate N,W,S,E faces
int generate_northface=0;
int generate_southface=0;
int generate_westface=0;
int generate_eastface=0;
bool sep_ok;
int u;
int north_final=a; //row of the north face from which no more cells will be skipped
int west_final=a; //row of the west face from which no more cells will be skipped
int south_final=a; //row of the south face from which no more cells will be skipped
if(strcmp(air_config,"W-E")!=0&&strcmp(air_config,"W-U")!=0&&strcmp(air_config,"U-D")!=0){ // north face
u=0;
generate_northface=1;
if (excess_n==0){north_final=0;} // we won't skip any other cell
for (int j = 0; j < a; ++j){ // we place aircraft starting from the bottom of the face
for (int i = 0; i < l; ++i){ // we place aircraft starting from the left of the face
if(excess_n!=0 && skip_xN[j]==i){ // in row j, we skip column i
excess_n--;
continue;
}
if(cont>=n){excess_n=0; continue;} // we already generated n aircraft
if(excess_n==0){u+=1; if(u==1 && north_final>0){north_final = j+1;}} // u=1 at the first row j s.t. no cell must be skipped (will be needed for the separation below)
sep_ok=false;
while(!sep_ok){// make sure that this aircraft and the previous are separated
x_0[cont]=randomFloat( horizontal_step*i, horizontal_step*(i+1) );
y_0[cont]=randomFloat( height-vertical_step, height );
z_0[cont]=randomFloat( j*altitude_step, altitude_step*(j+1) );
if (is3D==false)
{if(i==0) sep_ok=true;
else sep_ok=areSepatered(cont,cont-1);}
else{ // 3D configuration
if(i==0) { //first column of the face
if(j==0){sep_ok=true;} //first row of the face (from bottom to up)
else { //check if the aircraft is separated with the one in the cell BELOW (no aircraft on the PREVIOUS cell since i==0)
if(u>=2){sep_ok=areSepatered(cont,cont-l);} //no cell has been skipped at the previous j
else {sep_ok=areSepatered(cont,cont-l+1);} //a cell has been skipped at the previous j
}
}
else {
if(j==0){sep_ok=areSepatered(cont,cont-1);} //check if the aircraft is separated with the one in the PREVIOUS cell
else { //check if the aircraft is separated with the one in the PREVIOUS cell AND the one in the cell BELOW
//we must distinguish among different cases depending on the position of the cell
if(u>=2 || u==1 && i>= skip_xN[j-1]|| i<skip_xN[j] && i>= skip_xN[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l));}
else if (u==1 && i < skip_xN[j-1]|| i>skip_xN[j] && i>= skip_xN[j-1] || i<skip_xN[j] && i<skip_xN[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+1));}
else if (i>skip_xN[j] && i<= skip_xN[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+2));}
}
}
}
}
// heading angle bounds depends on the cell
if(i==0){ // left corner of the north face
hamin[cont]=-M_PI/2;
hamax[cont]=0;
if(j==0){ //left bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //left up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //left middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else if(i==l-1){// right corner of the north face
hamin[cont]=-M_PI;
hamax[cont]=-M_PI/2;
if(j==0){ //right bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //right up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //right middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else{// middle cell of the north face
hamin[cont]=-M_PI;
hamax[cont]=0;
if(j==0){ // bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ // up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ // middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
cont++;
}
}
if (verbose){cout<<"Number of aircraft on the north face: "<<cont<<"\n";}
}
if(strcmp(air_config,"N-S")!=0&&strcmp(air_config,"N-U")!=0&&strcmp(air_config,"U-D")!=0){ //west face
int k=cont;
u=0;
generate_westface=1;
if (excess_n==0){west_final=0;}
for (int j = 0; j < a; ++j){
for (int i = 0; i < m; ++i){
if(l==1&&generate_northface==1){continue;}
if(excess_n!=0 && skip_yW[j]==i){
excess_n--;
continue;
}
if(cont>=n){excess_n=0; continue;}
if(excess_n==0){u+=1; if(u==1 && west_final>0){west_final = j+1;}}
if (i==0 && generate_northface==1) continue; // first column already generated
sep_ok=false;
while(!sep_ok){
x_0[cont]=randomFloat( 0, horizontal_step );
y_0[cont]=randomFloat( vertical_step*(m-i-1), vertical_step*(m-i) );
z_0[cont]=randomFloat( j*altitude_step, altitude_step*(j+1) );
if (is3D==false){
if(i==0) sep_ok=true;
else if(i==1 && cont>1) sep_ok=areSepatered(cont,0);
else sep_ok=areSepatered(cont,cont-1);
}
else{
if (generate_northface==0){ //first face to be generated
if(i==0){
if(j==0){sep_ok=true;}
else {
if(u>=2){sep_ok=areSepatered(cont,cont-m);} //no cell has been skipped at the previous j
else {sep_ok=areSepatered(cont,cont-m+1);} // a cell has been skipped at the previous j
}
}
else{ //i>0
if (j==0){sep_ok=areSepatered(cont,cont-1);} //check the PREVIOUS cell
else{ //check the PREVIOUS cell and the cell BELOW
if(u>=2 || (u==1 && i>= skip_yW[j-1]) || (i<skip_yW[j] && i>= skip_yW[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m));}
else if ((u==1 && i< skip_yW[j-1]) || (i>skip_yW[j] && i>= skip_yW[j-1]) || (i<skip_yW[j] && i<=skip_yW[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+1));}
else if (i>skip_yW[j] && i<=skip_yW[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+2));}
}
}
}
else{ // generate_northface==1
if (m<=2){
if (j==0){sep_ok=(areSepatered(cont,0));}
else{sep_ok=(areSepatered(cont,cont-m+1)&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1)));}
}
else{
if (i==1){ //check the cell at the same altitude on the left corner of north face and the cell BELOW
if (j==0){sep_ok=(areSepatered(cont,0));}
else{
if(u>=2 || ( u==1 && i>= skip_yW[j-1] ) || ( i<skip_yW[j] && i>= skip_yW[j-1])){sep_ok=(areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-m+1));}
else if ((u==1 && i< skip_yW[j-1] ) || ( i>skip_yW[j] && i>= skip_yW[j-1] ) || ( i<skip_yW[j] && i<skip_yW[j-1])){ sep_ok=(areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-m+2));}
else if (i>skip_yW[j] && i <= skip_yW[j-1]){sep_ok=(areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-m+3));}
}
}
else{ //i>1
if (j==0){sep_ok=areSepatered(cont,cont-1);}
else{ //check the PREVIOUS cell and the cell BELOW
if(u>=2 || (u==1 && i>= skip_yW[j-1] ) || ( i<skip_yW[j] && i>= skip_yW[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+1));}
else if ((u==1 && i< skip_yW[j-1] ) || ( i>skip_yW[j] && i>= skip_yW[j-1] )|| (i<skip_yW[j] && i<skip_yW[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+2));}
else if (i>skip_yW[j] && i<= skip_yW[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+3));}
}
}
}
}
}
}
// heading angle bounds depends on the cell
if(i==0){ // north corner of west face
hamin[cont]=-M_PI/2;
hamax[cont]=0;
if(j==0){ //north bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //north up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //north middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else if(i==m-1){// south corner of the west face
hamin[cont]=0;
hamax[cont]=M_PI/2;
if(j==0){ //south bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //south up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //south middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else{// middle cell of the west face
hamin[cont]=-M_PI/2;
hamax[cont]=M_PI/2;
if(j==0){ // bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ // up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ // middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
cont++;
}
}
if (verbose){cout<<"Number of aircraft on the west face: "<<cont-k<<"\n";}
}
if(strcmp(air_config,"W-E")!=0 && strcmp(air_config,"W-N")!=0 && strcmp(air_config,"N-U")!=0 && strcmp(air_config,"W-U")!=0&&strcmp(air_config,"U-D")!=0){// south face
int k=cont;
u=0;
generate_southface=1;
if (excess_n==0){south_final=0;}
for (int j = 0; j < a; ++j){
for (int i = 0; i < l; ++i){
if(m==1&&generate_westface==1){continue;}
if(excess_n!=0 && skip_xS[j]==i){
excess_n--;
continue;
}
if (cont>=n){excess_n=0; continue;}
if(excess_n==0){u+=1; if(u==1&&south_final>0) {south_final=j+1;}}
if (i==0 && generate_westface==1 ) continue;
sep_ok=false;
while(!sep_ok){
x_0[cont]=randomFloat( horizontal_step*i, horizontal_step*(i+1) );
y_0[cont]=randomFloat( 0, vertical_step );
z_0[cont]=randomFloat( j*altitude_step, altitude_step*(j+1) );
if(is3D==false){
if(i==0) sep_ok=true;
else sep_ok=areSepatered(cont,cont-1);
}
else{
if(generate_westface==0 && generate_northface==1){ // just north face generated, we don't ignore any column - > 'N-S' configuration
if(i==0){
if(j==0){sep_ok=true;}
else {//check if the aircraft is separated with the one in the cell BELOW
if(u>=2){sep_ok=areSepatered(cont,cont-l);} //no cell has been skipped at the previous j
else {sep_ok=areSepatered(cont,cont-l+1);} // a cell has been skipped at the previous j
}
}
else{
if (j==0){sep_ok=areSepatered(cont,cont-1);}
else {//check if the aircraft is separated with the one in the cell BELOW *and* the one in the PREVIOUS cell
if(u>=2 || (u==1 && i>= skip_xS[j-1]) || ( i<skip_xS[j] && i>= skip_xS[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l));}
else if ((u==1 && i < skip_xS[j-1]) || ( i>skip_xS[j] && i>= skip_xS[j-1] ) || ( i<skip_xS[j] && i<skip_xS[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+1));}
else if (i>skip_xS[j] && i<= skip_xS[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+2));}
}
}
}
else if(generate_westface==1 && generate_northface==1){ //'all' configuration
//index of the last aircraft placed on the north face = l*a-north_final-1 (until j<north_final one cell is skipped for each j)
if (l<=2){if (j==0){sep_ok=areSepatered(cont,(l*a-north_final-1)+(m-1)-min(west_final,j+1));}
else {sep_ok=(areSepatered(cont,(l*a-north_final-1)+(j+1)*(m-1)-min(west_final,j+1))&&areSepatered(cont,cont-l+1));}
}
else{
if (i==1){ //check the cell at the same altitude on the south corner of west face and the cell BELOW
if (j==0){ sep_ok=(areSepatered(cont,(l*a-north_final-1)+(m-1)-min(west_final,j+1)));}
else{
if(u>=2 || (u==1 && i>= skip_xS[j-1] ) || ( i<skip_xS[j] && i>= skip_xS[j-1])){ sep_ok=(areSepatered(cont,(l*a-1-north_final)+(j+1)*(m-1)-min(west_final,j+1))&&areSepatered(cont,cont-l));}
else if ((u==1 && i< skip_xS[j-1] ) || ( i>skip_xS[j] && i>= skip_xS[j-1] ) || ( i<skip_xS[j] && i<skip_xS[j-1])){ sep_ok=(areSepatered(cont,(l*a-1-north_final)+(j+1)*(m-1)-min(west_final,j+1))&&areSepatered(cont,cont-l+1));}
else if (i>skip_xS[j] && i<= skip_xS[j-1]){ sep_ok=(areSepatered(cont,(l*a-1-north_final)+(j+1)*(m-1)-min(west_final,j+1))&&areSepatered(cont,cont-l+2));}
} //cont+1-l*a-m
}
else
{
if (j==0){sep_ok=areSepatered(cont,cont-1);}
else {//check if the aircraft is separated with the one in the PREVIOUS cell AND the one in the cell BELOW
if(u>=2 || (u==1 && i>= skip_xS[j-1]) || ( i<skip_xS[j] && i>= skip_xS[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+1));}
else if ((u==1 && i < skip_xS[j-1]) || ( i>skip_xS[j] && i>= skip_xS[j-1] ) || ( i<skip_xS[j] && i<skip_xS[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+2));}
else if (i>skip_xS[j] && i<=skip_xS[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l+3));}
}
}
}
}
}
}
// heading angle bounds depends on the cell
if(i==0){// left corner of south face
hamin[cont]=0;
hamax[cont]=M_PI/2;
if(j==0){ //left bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //left up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //left middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else if(i==l-1){// right corner of south face
hamin[cont]=M_PI/2;
hamax[cont]=M_PI;
if(j==0){ //right bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //right up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //right middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else{// middle cell of south face
hamin[cont]=0;
hamax[cont]=M_PI;
if(j==0){ // bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ // up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
cont++;
}
}
if (verbose){cout<<"Number of aircraft on the south face: "<<cont-k<<"\n";}
}
if(strcmp(air_config,"W-N")!=0 && strcmp(air_config,"N-S")!=0&&strcmp(air_config,"W-U")!=0 && strcmp(air_config,"N-U")!=0&&strcmp(air_config,"U-D")!=0){// east face
int k=cont;
generate_eastface=1;
u=0;
for (int j = 0; j < a; ++j){
for (int i = 0; i < m; ++i){//
if (m<=2&&generate_northface==1){ continue; }
else{
if(excess_n!=0 && skip_yE[j]==i){
excess_n--;
continue;
}
if (cont>=n){excess_n=0; continue;}
if(excess_n==0){u+=1;}
if (i==0 && generate_southface==1 ) continue;
if (i==m-1 && generate_northface==1 ) continue;
sep_ok=false;
while(!sep_ok){
x_0[cont]=randomFloat( width-horizontal_step, width );
y_0[cont]=randomFloat( vertical_step*i, vertical_step*(i+1) );
z_0[cont]=randomFloat( altitude_step*j, altitude_step*(j+1) );
if (is3D==false){
if(i==0) sep_ok=true;
else if (generate_northface==1&&i==m-2) {sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,l-1));}
else {sep_ok=areSepatered(cont,cont-1);}
}
else{
if(generate_southface==0 && generate_northface==0){ //only west has been already generated, we don't ignore any row -> 'W-E' configuration
if(i==0){
if(j==0){sep_ok=true;}
else {//check if the aircraft is separated with the one in the cell BELOW
if(u>=2){sep_ok=areSepatered(cont,cont-m);} //no cell has been skipped at the previous j
else {sep_ok=areSepatered(cont,cont-m+1);} // a cell has been skipped at the previous j
}
}
else{
if (j==0){sep_ok=areSepatered(cont,cont-1);}
else {//check if the aircraft is separated with the one in the cell BELOW *and* the one in the PREVIOUS cell
if(u>=2 || (u==1 && i>= skip_yE[j-1]) || ( i<skip_yE[j] && i>= skip_yE[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m));}
else if ((u==1 && i < skip_yE[j-1]) || ( i>skip_yE[j] && i>= skip_yE[j-1] ) || ( i<skip_yE[j] && i<skip_yE[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+1));}
else if (i>skip_yE[j] && i<= skip_yE[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+2));}
}
}
}
else if(generate_westface==1 && generate_northface==1 && generate_southface==1){ //'all' configuration
if (m==3) { //we have just one column for i=1, and we must check separation among the aircraft and BOTH previous AND next cell (and the cell below)
if (j==0){sep_ok=(areSepatered(cont,l*a-north_final-1+(m-1)*a-west_final+(j+1)*(l-1)-min(south_final,j+1))&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1)));}
else{sep_ok=(areSepatered(cont,l*a-north_final-1+(m-1)*a-west_final+(j+1)*(l-1)-min(south_final,j+1))&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-1));}
}
if (i==1 ){ //check the cell at the same altitude on the right corner of south face and the cell BELOW
//index of the last aircraft placed on the west face= (l*a-1-north_final)+(m-1)*a-west_final
if (j==0){sep_ok=(areSepatered(cont,(l*a-1-north_final+(m-1)*a-west_final)+(j+1)*(l-1)-min(south_final,j+1)));}
else{
if(u>=2 || (u==1 && i>= skip_yE[j-1] ) || ( i<skip_yE[j] && i>= skip_yE[j-1])){sep_ok=(areSepatered(cont,(l*a+(m-1)*a-1-north_final-west_final)+(j+1)*(l-1)-min(south_final,j+1))&&areSepatered(cont,cont-m+2));}
else if ((u==1 && i< skip_yE[j-1] ) || ( i>skip_yE[j] && i>= skip_yE[j-1] ) || ( i<skip_yE[j] && i<skip_yE[j-1])){sep_ok=(areSepatered(cont,(l*a+(m-1)*a-1-north_final-west_final)+(j+1)*(l-1)-min(south_final,j+1))&&areSepatered(cont,cont-m+3));}
else if (i>skip_yE[j] && i<= skip_yE[j-1]){sep_ok=(areSepatered(cont,(l*a+(m-1)*a-1-north_final-west_final )+(j+1)*(l-1)-min(south_final,j+1))&&areSepatered(cont,cont-m+4));}
} //cont+1-l*a-m
}
else if (1<i<m-2)
{
if (j==0){sep_ok=areSepatered(cont,cont-1);}
else {//check if the aircraft is separated with the one in the PREVIOUS cell AND the one in the cell BELOW
if(u>=2 || (u==1 && i>= skip_yE[j-1]) || ( i<skip_yE[j] && i>= skip_yE[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+2));}
else if ((u==1 && i < skip_yE[j-1]) || ( i>skip_yE[j] && i>= skip_yE[j-1] ) || ( i<skip_yE[j] && i<skip_yE[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+3));}
else if (i>skip_yE[j] && i<= skip_yE[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-m+4));}
}
}
else { //i=m-1
if (j==0){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1)));}
else {//check if the aircraft is separated with the one in the PREVIOUS cell, the one in the NEXT cell, AND the one in the cell BELOW
if(u>=2 || (u==1 && i>= skip_yE[j-1]) || ( i<skip_yE[j] && i>= skip_yE[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-m+2));}
else if ((u==1 && i < skip_yE[j-1]) || ( i>skip_yE[j] && i>= skip_yE[j-1] ) || ( i<skip_yE[j] && i<skip_yE[j-1])){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-m+3));}
else if (i>skip_yE[j] && i<= skip_yE[j-1]){sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,(j+1)*l-1-min(north_final,j+1))&&areSepatered(cont,cont-m+4));}
}
}
}
}
}
// heading angle bounds depends on the cell
if(i==0){ // north corner of east face
hamin[cont]=M_PI/2;
hamax[cont]=M_PI;
if(j==0){ //north bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //north up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //north middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else if(i==m-1){// south corner of east face
hamin[cont]=-M_PI;
hamax[cont]=-M_PI/2;
if(j==0){ //south bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ //south up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ //south middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
else{// middle cell of east face
hamin[cont]=M_PI/2;
hamax[cont]=3*M_PI/2;
if(j==0){ // bottom
phimin[cont]=0;
phimax[cont]=M_PI/2;}
else if (j==a-1){ // up
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;}
else{ // middle
phimin[cont]=0;
phimax[cont]=M_PI;}
}
cont++;
}
}
}
if (verbose){cout<<"Number of aircraft on the east face: "<<cont-k<<"\n";}
}
if(is3D==true&&strcmp(air_config,"W-N")!=0 && strcmp(air_config,"N-S")!=0&&strcmp(air_config,"W-E")!=0){ //upper face
int k=cont;
for (int j = 0; j < m; ++j){
for (int i = 0; i < l; ++i){
if ((m<=2 && generate_northface==1 && generate_southface==1) || (l<=2 && generate_westface==1 && generate_eastface==1)){continue;} //no space for other aircraft
else{
if(excess_n!=0 && skip_xU[j]==i){
excess_n--;//
continue;
}
if (cont>=n){excess_n=0; continue;}
if(i==0 && generate_westface==1 ) continue; //&& skip_yW[(int)(a-1)!=j]
if(i==l-1 && generate_eastface==1) continue; // && skip_yW[(int)(a-1)!=i]
if(j==0 && generate_southface==1 ) continue;
if(j==m-1 && generate_northface==1 ) continue;
sep_ok=false;
while(!sep_ok){
x_0[cont]=randomFloat(horizontal_step*i, horizontal_step*(i+1) );
y_0[cont]=randomFloat( vertical_step*j, vertical_step*(j+1) );
z_0[cont]=randomFloat(altitude-altitude_step,altitude );
//******todo add the separations for the corners
if(i==0 && j==0) sep_ok=true;
else sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l));
}
// heading angle bounds depends on the cell
phimin[cont]=M_PI/2;
phimax[cont]=M_PI;
if(i==0){ // south corner of upper face
if(j==0){ // south left
hamin[cont]=0;
hamax[cont]=M_PI/2;}
else if (j==l-1){ //south right
hamin[cont]=M_PI/2;
hamax[cont]=M_PI;}
else{ //south middle
hamin[cont]=0;
hamax[cont]=M_PI;}
}
else if(i==m-1){// north corner of upper face
if(j==0){ // north left
hamin[cont]=-M_PI/2;
hamax[cont]=0;}
else if (j==l-1){ //north right
hamin[cont]=-M_PI;
hamax[cont]=-M_PI/2;}
else{ //north middle
hamin[cont]=-M_PI;
hamax[cont]=0;}
}
else{// middle cell of upper face
if(j==0){ // left
hamin[cont]=-M_PI/2;
hamax[cont]=M_PI/2;}
else if (j==l-1){ // right
hamin[cont]=M_PI/2;
hamax[cont]=3*M_PI/2;}
else{ // middle
hamin[cont]=0;
hamax[cont]=2*M_PI;}
}
cont++;
}
}
}
if (verbose){cout<<"Number of aircraft on the upper face: "<<cont-k<<"\n";}
}
if(is3D==true&&strcmp(air_config,"W-N")!=0 && strcmp(air_config,"N-S")!=0&&strcmp(air_config,"W-E")!=0&& strcmp(air_config,"N-U")!=0&& strcmp(air_config,"W-U")!=0){ //bottom face
int k=cont;
for (int j = 0; j < m; ++j){
for (int i = 0; i < l; ++i){
if ((m<=2 && generate_northface==1 && generate_southface==1) || (l<=2 && generate_westface==1 && generate_eastface==1)){continue;} //no space for other aircraft
else{
if(excess_n!=0 && skip_xD[j]==i){
excess_n--;
continue;
}
if (cont>=n){excess_n=0; continue; }
if(i==0 && generate_westface==1 ) continue;
if(i==l-1 && generate_eastface==1 ) continue;
if(j==0 && generate_southface==1 ) continue;
if(j==m-1 && generate_northface==1 ) continue;
sep_ok=false;
while(!sep_ok){
x_0[cont]=randomFloat(horizontal_step*i, horizontal_step*(i+1) );
y_0[cont]=randomFloat(vertical_step*j, vertical_step*(j+1) );
z_0[cont]=randomFloat(0,altitude_step);
//******todo add the separations for the corners
if(i==0 &&j==0) sep_ok=true;
else sep_ok=(areSepatered(cont,cont-1)&&areSepatered(cont,cont-l));
}
// heading angle bounds depends on the cell
phimin[cont]=0;
phimax[cont]=M_PI/2;
if(i==0){ // south corner of bottom face
if(j==0){ // south left
hamin[cont]=0;
hamax[cont]=M_PI/2;}
else if (j==l-1){ //south right
hamin[cont]=M_PI/2;
hamax[cont]=M_PI;}
else{ //south middle
hamin[cont]=0;
hamax[cont]=M_PI;}
}
else if(i==m-1){// north corner of bottom face
if(j==0){ // north left
hamin[cont]=-M_PI/2;
hamax[cont]=0;}
else if (j==l-1){ //north right
hamin[cont]=-M_PI;
hamax[cont]=-M_PI/2;}
else{ //north middle
hamin[cont]=-M_PI;
hamax[cont]=0;}
}
else{// middle cell of bottom face
if(j==0){ // left
hamin[cont]=-M_PI/2;
hamax[cont]=M_PI/2;}
else if (j==l-1){ // right
hamin[cont]=M_PI/2;
hamax[cont]=3*M_PI/2;}
else{ // middle
hamin[cont]=0;
hamax[cont]=2*M_PI;}
}
cont++;
}
}
}
if (verbose){cout<<"Number of aircraft on the bottom face: "<<cont-k<<"\n";}
}
if (verbose){
if(is3D==false){
printf("coordinates generated in a rectangle %f x %f\n",width,height);
for (int i = 0; i < n; ++i)
printf("p_%i=(%f,%f)\n",i,x_0[i],y_0[i]);
}
else{
printf("coordinates generated in a parallelepiped %f x %f x %f\n",width,height,altitude);
for (int i = 0; i < n; ++i)
printf("p_%i=(%f,%f,%f)\n",i,x_0[i],y_0[i],z_0[i]);
}
}
}
// This auxiliary method generates the vectors of velocity of aircraft for a random scenario
void pseudoRandomP_vectors(int nc, float pc,int maxc, float* hamin,float* hamax, float* phimin, float* phimax){
float random;
int total_conflicts=0;
bool* explored=new bool[n];// vector to indicate if velocity was generated for an aircraft or not
for (int i = 0; i < n; ++i)
explored[i]=false;
bool* tried=new bool[n];
for (int i = 0; i < n; ++i)
tried[i]=false;
int total_explored=0;
int i;
int conflicts_i;
float vi, thetai, phii;
int num_trials, num_loops, max_conflicts;
int max_trials;
if (is3D==true){max_trials=1000;}
else {max_trials=1000;}
bool meet_requested; // true if we are close to the end and still do not have nc
bool zeroIniConf; // true if the first value generated for conflicts_i is 0
while(total_explored < n){
// A. randomly select an unexplored aircraft i:
i=randomInt(0,n-1);
while(explored[i]) i=randomInt(0,n-1);
// B. randomly chose velocity and heading angles for i:
vi=randomFloat(vmin,vmax);
thetai=randomFloat(hamin[i],hamax[i]);
if (is3D==true)
{phii=randomFloat(phimin[i],phimax[i]);}
else {phii=M_PI/2;}
vx[i]=vi*cos(thetai)*sin(phii);
vy[i]=vi*sin(thetai)*sin(phii);
vz[i]=vi*cos(phii);
// C. i will have at least 1 conflict with probability pc (if i is not the first for which we generate (vx,vy,vz) and
// we have not reached the maximum number of conflicts yet):
max_conflicts=min(min(maxc,total_explored),max(0,nc-total_conflicts)); // max num of conflicts we can generate
random = ((float) rand()) / (float) RAND_MAX;
meet_requested=ceil( (1.0*(nc-total_conflicts))/ ((maxc+1)/2) )>=n-total_explored;
if(total_explored>0 && !meet_requested && total_conflicts<nc && random < pc) {
conflicts_i=randomInt(1,max_conflicts);
zeroIniConf=false;
if (verbose)
printf("conflicts_i generated randomly\n");
}
else if (meet_requested){ // we are close to the end and still do not have nc
conflicts_i=max_conflicts;
zeroIniConf=false;
if (verbose)
printf("conflicts_i generated to meet requested\n");
}
else {
conflicts_i=0;
zeroIniConf=true;
if (verbose){
printf("conflicts_i set to 0\n");
printf("%f < %f, nc=%i \n",random, pc,nc );
}
}
// Loop: generate random trajectories until the desired number of conflicts are yielded
if (verbose){
if(is3D==true){
printf("conflicts already generated: %i, current aircraft i= %i conflicts_i=%i, p0=(%f,%f,%f), v=(%f,%f,%f)\n",
total_conflicts, i,conflicts_i,x_0[i],y_0[i],z_0[i],vx[i],vy[i],vz[i]);}
else{
printf("conflicts already generated: %i, current aircraft i= %i conflicts_i=%i, p0=(%f,%f), v=(%f,%f)\n",
total_conflicts, i,conflicts_i,x_0[i],y_0[i],vx[i],vy[i]);}
}
num_trials=0; // number of times we try to generate a vector with specific numConflicts
num_loops=0; // number of different values we try for numConflicts
while(num_trials==0){
if (verbose){
if(is3D==true){
printf("\t trying with num_conflicts= %i, v=(%f,%f,%f)...\n",conflicts_i,vx[i],vy[i],vz[i] );}
else{
printf("\t trying with num_conflicts= %i, v=(%f,%f)...\n",conflicts_i,vx[i],vy[i]);}
}
while((num_trials< max_trials) && (numConflicts(i,explored)!=conflicts_i)){
vi= randomFloat(vmin,vmax);
thetai=randomFloat(hamin[i],hamax[i]);
if (is3D==true)
{phii=randomFloat(phimin[i],phimax[i]);}
else {phii=M_PI/2;}
vx[i]=vi*cos(thetai)*sin(phii);
vy[i]=vi*sin(thetai)*sin(phii);
vz[i]=vi*cos(phii);
num_trials++;
}
if(numConflicts(i,explored)!=conflicts_i){ // try with another number of conflicts
num_trials=0;
tried[conflicts_i]=true;
if(num_loops<max_conflicts){
if(meet_requested && conflicts_i>0)
conflicts_i--;
else if(!zeroIniConf && num_loops==max_conflicts-1)
conflicts_i=0;
else{
conflicts_i=randomInt(1,max_conflicts);
while(tried[conflicts_i])
conflicts_i=randomInt(1,max_conflicts);
}
num_loops++;
}
else{
num_loops++;
conflicts_i=num_loops;
}
}
else{ // trajectory with conflicts_i generated successfully
num_trials++;
for (int k = 0; k < n; ++k)
tried[k]=false;
}
}
// D. Set speed and angle of i, and update loop variables
hat_v[i]=vi;
hat_theta[i]=thetai;
hat_phi[i]=phii;
total_conflicts +=conflicts_i;
total_explored++;
explored[i]=true;
if(total_explored!=n)
pc=(4.0*(nc-total_conflicts))/((n-total_explored)*(1+maxc));
}
// uncomment for bash file:
// float distmin_average = 0;
// float duration_average = 0;
// int num_conf =0;
// for (int i = 0; i < n; ++i) {
// for (int j = i+1; j < n; ++j){
// if(conflict(i,j)){
// //printf("(%i, %i) with distance at the time of minimal separation: %f,",i+1,j+1,sqrt(dist_min(i,j)));
// //printf(" and duration of conflict: %f.\n",duration(i,j));
// distmin_average += sqrt(dist_min(i,j));
// duration_average += duration(i,j);
// num_conf +=1;
// }
// }
// }
// distmin_average = distmin_average/num_conf;
// duration_average = duration_average/num_conf;
// printf("\t%f\t%i\t%f\t%f\n",pc,total_conflicts,distmin_average,duration_average);
if(nc!=total_conflicts){
printf("----------------------------------------------------------------------------------------------\n");
printf("Random Problem Generator: WARNING deviation from requested number of conflicts of %i\n",total_conflicts-nc );
if (nc < total_conflicts){
printf("We could not generate a scenario with the requested congestion, you can try to:\n");
printf("\ti)increase nc or maxc\n");
printf("\tii) increase window size\n");
printf("\tiii) decrease n\n");
printf("\tiv) change random seed by using -seed option\n");
}
else{
printf("We could not generate a scenario with the requested congestion, you can try to:\n");
printf("\ti)decrease nc or maxc\n");
printf("\tii) decrease window size\n");
printf("\tiii) increase n\n");
printf("\tiv) change random seed by using -seed option\n");
}
}
delete[] explored;
delete[] tried;
}
// #### 5. PSEUDO-RANDOM SCENARIOS ###
// pseudoRandomP: generates scenario with initial positions near the borders of a parallelepiped P of size height x width x altitude
// heading angles are generated randomly, depending on the initial positions of aircraft (in order to make sure that
// aircraft are flying crossing the parallelepiped P). There are different configurations for the initial positions,
// since aircraft can be on the 6 faces of P or only on 2 of them.
void pseudoRandomP(char* air_config,float height,float width,float altitude,int nc, float pc,int maxc){
float* hamin=new float[n]; // vectors to keep min and max heading angle theta for each aircraft depending on its initial position
float* hamax=new float[n];
float* phimin=new float[n]; // vectors to keep min and max heading angle phi for each aircraft depending on its initial position
float* phimax=new float[n];
pseudoRandomP_iniPos(air_config,height,width,altitude,hamin,hamax,phimin,phimax); // generates initial positions for aircraft
pseudoRandomP_vectors(nc,pc,maxc,hamin,hamax,phimin,phimax);// generate velocity vectors V_i i=1...n
// calculate ending points of the trajectories:
float t;
for (int i = 0; i < n; ++i){
t=getInstantBoundary(i,height,width,altitude); // get instant in wich i will cross boundary (space window)
x_t[i]=min(x_0[i]+t*vx[i],width);
y_t[i]=min(y_0[i]+t*vy[i],height);
z_t[i]=min(z_0[i]+t*vz[i],altitude);
}
delete[] hamin;
delete[] hamax;
}
// #### 6. RANDOM SCENARIOS ###
// randomP: generates random initial positions in 3D parallelepiped (if z_max !=0); vectors also generated randomly
void randomP(float x_max,float y_max,float z_max){
bool sep_ok;
for (int i = 0; i < n; ++i){
sep_ok=false;
while(!sep_ok){
x_0[i]=randomFloat(0,x_max);
y_0[i]=randomFloat(0,y_max);
z_0[i]=randomFloat(0,z_max);
sep_ok=true;
for (int j = 0; j < i; ++j){
sep_ok=areSepatered(i,j);
if(!sep_ok) break;
}
}
}
for (int i = 0; i < n; ++i){
hat_v[i]= randomFloat(vmin,vmax);
hat_theta[i]=randomFloat(-M_PI,M_PI);
vx[i]=hat_v[i]*cos(hat_theta[i]);
vy[i]=hat_v[i]*sin(hat_theta[i]);
vz[i]=0;
if(is3D){
hat_phi[i]=randomFloat(0,M_PI);
vx[i]=vx[i]*sin(hat_phi[i]);
vy[i]=vy[i]*sin(hat_phi[i]);
vz[i]=hat_v[i]*cos(hat_phi[i]);
}
}
float t;
for (int i = 0; i < n; ++i){
t=getInstantBoundary(i,x_max,y_max,z_max);// get instant in wich i will cross boundary (space window)
x_t[i]=min(x_0[i]+t*vx[i],x_max);
y_t[i]=min(y_0[i]+t*vy[i],y_max);
z_t[i]=min(z_0[i]+t*vz[i],z_max);
}
printf("\n--------------------------------------------------------------------------------------------------\n");
printf("Random Problem Generator");
}
// --------------------------------------------------------------------------
// ----- MAIN PROGRAM -------
// --------------------------------------------------------------------------
int main(int argc, char **argv) {
char* air_config=new char[5]; // random problem: airspace configuration (all,N-N,N-S,W-E,W-N)
char* char_mode=new char[5]; // when the mode of the generator is described by a code instead of a number
srand(random_seed);
// circle/sphere problem:
float radius=200; // circle/sphere problem: radius
float sector_ini_x=0; double sector_angle_x=2*M_PI; //circle/sphere problem: sector where aircraft will be placed
float sector_ini_z=0; double sector_angle_z=M_PI;
// rhomboidal problem:
float alpha_r=M_PI/4; // crossing angle
int horiz=2; int verti=2; // number of horizontal/sloping trails
// polyhedral problem:
double* alpha; double* beta;
int* mx; int* my; int* mz;
float d_HP=3*D; float d_VP=3*D;
// rhomboidal AND polyhedral
int nx=1; int ny=1; int nz=1;// number of aircraft at each trail
float dx=3*D; float dy=3*D; float dz=3*D; // distance between each trail
float d_aircraft=2*D; // distance between aircraft on the same trail
// random circle and rhomboidal problems:
float hamin=-M_PI/6; float hamax=M_PI/6; // angle incr limit
// random and pseudo-random scenarios:
int nc=-1; // total number of conflicts between different pairs of aircraft
float pc=-1; // probability that one aircraft have a conflict with at least one other aircraft
int maxc=-1; // max number of conflicts that a fixed aircraft can have with others
float height=400; float width=400; float altitude=400; //space window size
// 1..............Read input options
int i=1;
int j;
int insert_HP=0;
int insert_VP=0;
int insert_alpha=0;
int insert_beta=0;
int insert_mx=0;
int insert_my=0;
int insert_mz=0;
int insert_width=0;
int insert_height=0;
int insert_altitude=0;
char* key;
while(i<argc){
j=2;
key=argv[i];
if(strcmp(key,"-V")!=0 && i+1>=argc) {printf("Invalid syntax\n");return -1;}
// general input parameters:
if(strcmp(key,"-n")==0){
n=atoi(argv[i+1]);
}
else if(strcmp(key,"-mode")==0) {
char_mode=argv[i+1];
if(strcmp(char_mode,"CP")==0)// circle
mode=0;
else if(strcmp(char_mode,"RCP")==0)// random circle
mode=1;
else if(strcmp(char_mode,"RP")==0)// rhomboidal
mode=2;
else if(strcmp(char_mode,"RRP")==0)// random rhomboidal
mode=3;
else if(strcmp(char_mode,"GP")==0) // grid
mode=4;
else if(strcmp(char_mode,"RGP")==0)// random grid
mode=5;
else if(strcmp(char_mode,"PR2")==0)// pseudo-random 2D (num conflicts according to user)
mode=6;
else if(strcmp(char_mode,"PR3")==0){// pseudo-random 3D (num conflicts according to user)
mode=14;
is3D=true;
}
else if(strcmp(char_mode,"R2")==0)// random2D
mode=7;
else if(strcmp(char_mode,"R3")==0){// random3D
mode=15;
is3D=true;
}
else if(strcmp(char_mode,"SP")==0){// sphere
mode=8;
is3D=true;
}
else if(strcmp(char_mode,"RSP")==0){// random sphere
mode=9;
is3D=true;
}
else if(strcmp(char_mode,"PL")==0){// polyhedral
mode=10;
is3D=true;
}
else if(strcmp(char_mode,"RPL")==0){// random polyhedral
mode=11;
is3D=true;
}
else if(strcmp(char_mode,"QP")==0){// cubic
mode=12;
is3D=true;
}
else if(strcmp(char_mode,"RQP")==0){// random cubic
mode=13;
is3D=true;
}
else{// other scenarios or scenario mode defined using a number in [0,15]
mode=atoi(char_mode);
if (mode==0 and strcmp(char_mode,"0")!=0)
printf("WARNING The -mode value is not correctly written.\n");
if (mode>=8)
is3D=true;
}
}
else if(strcmp(key,"-seed")==0) {
srand(atoi(argv[i+1]));
}
else if(strcmp(key,"-vmin")==0){
vmin=atof(argv[i+1]);
}
else if(strcmp(key,"-vmax")==0){
vmax=atof(argv[i+1]);
}
else if(strcmp(key,"-vdefault")==0){
vmin=atof(argv[i+1]);
vmax=vmin;
}
else if(strcmp(key,"-D")==0){
D=atof(argv[i+1]);
d_HP=3*D;
d_VP=3*D;
dx=3*D;
dy=3*D;
dz=3*D;
d_aircraft=2*D;
}
else if(strcmp(key,"-V")==0){
verbose=true;
i=i-1;
}
else if(strcmp(key,"-f")==0){
outputFile=argv[i+1];
}
// random problem :
else if(strcmp(key,"-nc")==0)
nc=atoi(argv[i+1]);
else if(strcmp(key,"-pc")==0)
pc=atof(argv[i+1]);
else if(strcmp(key,"-maxc")==0)
maxc=atoi(argv[i+1]);
else if(strcmp(key,"-airconfig")==0)
air_config=argv[i+1];
else if(strcmp(key,"-h")==0)
{height=atof(argv[i+1]);
insert_height=1;}
else if(strcmp(key,"-w")==0)
{width=atof(argv[i+1]);
insert_width=1;}
else if(strcmp(key,"-a")==0)
{altitude=atof(argv[i+1]);
insert_altitude=1;}
//polyhedral problems
else if(strcmp(key,"-HP")==0){
HP=atoi(argv[i+1]);
alpha = new double[HP]; // crossing angle diagonal trails on horizontal planes
mx = new int[HP]; my = new int[HP]; //number of trails on each horizontal plane (mx,my)
for (int h=0;h<HP;++h)
{mx[h]=2; my[h]=2; alpha[h]=M_PI/6;}
insert_HP=1; //to record that the user is inserting HP
}
else if(strcmp(key,"-VP")==0){
VP=atoi(argv[i+1]);
beta = new double[VP]; // crossing angle diagonal trails on vertical planes
mz= new int[VP]; //number of trails on each vertical plane
for (int v=0;v<VP;++v)
{mz[v]=2; beta[v]=2*M_PI/3;}
insert_VP=1; //to record that the user is inserting VP
}
else if(strcmp(key,"-dHP")==0)
d_HP=atoi(argv[i+1]);
else if(strcmp(key,"-dVP")==0)
d_VP=atoi(argv[i+1]);
else if(strcmp(key,"-beta")==0){
insert_beta=1; //to record that the user is inserting beta
if (insert_VP==0){VP=vp; beta = new double[VP];} //if the user does not insert VP
int k=i+1;
int b=0;
while(k<argc && argv[k][0]!='-'){ //until the user does not insert a new parameter OR stop giving inputs
if (b<VP)
{beta[b]=atof(argv[k]);
k=k+1;
b=b+1;}
else //if the user insert more than VP values for beta, we must store the number of values we must ignore
{k=k+1;
b=b+1;}
}
if (b<VP){ //if the user insert less than VP beta values we set the others to the default value
for(int v=b;v<VP;++v)
beta[v]=2*M_PI/3;
printf("\nInserted less than VP=%i values for beta. The last %i are set to default=%f.\n",VP,VP-b,beta[b]);
}
else if(b>VP){ //if the user insert more than VP beta values, we ignore the last ones
printf("\nInserted more than VP=%i values for beta. The last %i values are ignored.\n",VP,b-VP);}
j=k-i; //when updating i, we will set i=i+j =i+k-i =k
}
else if(strcmp(key,"-betad")==0) {
insert_beta=1; //to record that the user is inserting beta
if (insert_VP==0){VP=vp; beta = new double[VP];} //if the user does not insert VP
int k=i+1;
int b=0;
while(k<argc && argv[k][0]!='-'){ //until the user does not insert a new parameter OR stop giving inputs
if (b<VP)
{beta[b]=atof(argv[k]);
beta[b]=M_PI*beta[b]/180;
k=k+1;
b=b+1;}
else
{k=k+1;
b=b+1;}
}
if (b<VP){ //if the user insert less than VP beta values we set the others to the default value
for(int v=b;v<VP;++v)
beta[v]=2*M_PI/3;
printf("\nInserted less than VP=%i values for beta. The last %i are set to default=%f.\n",VP,VP-b,beta[b]);
}
else if(b>VP){ //if the user insert more than VP beta values, we ignore the last ones
printf("\nInserted more than VP=%i values for beta. The last %i values are ignored.\n",VP,b-VP);}
j=k-i;
}
else if(strcmp(key,"-mz")==0){
insert_mz=1; //to record that the user is inserting mz
if (insert_VP==0){VP=vp; mz = new int[VP];} //if the user does not insert VP
int k=i+1;
int b=0;
while(k<argc && argv[k][0]!='-'){
if (b<VP)
{mz[b]=atoi(argv[k]);
k=k+1;
b=b+1;}
else
{k=k+1;
b=b+1;}
}
if (b<VP){ //if the user insert less than VP mz values we set the others to the default value
for(int v=b;v<VP;++v)
mz[v]=2;
printf("\nInserted the number of vertical trails only for %i vertical planes. The last %i are set to default=%i.\n",b,VP-b,mz[b]);
}
else if(b>VP){ //if the user insert more than VP mz values, we ignore the last ones
printf("\nInserted %i vertical trails, but there are only VP=%i vertical planes. The last %i values are ignored.\n",b,VP,b-VP);
}
j=k-i;
}
// rhomboidal AND polyhedral problems:
else if(strcmp(key,"-nx")==0)
nx=atoi(argv[i+1]);
else if(strcmp(key,"-ny")==0)
ny=atoi(argv[i+1]);
else if(strcmp(key,"-nz")==0)
nz=atoi(argv[i+1]);
else if(strcmp(key,"-dx")==0)
dx=atof(argv[i+1]);
else if(strcmp(key,"-dy")==0)
dy=atof(argv[i+1]);
else if(strcmp(key,"-dz")==0)
dz=atof(argv[i+1]);
else if(strcmp(key,"-d_aircraft")==0)
d_aircraft=atof(argv[i+1]);
else if(strcmp(key,"-alpha")==0){
insert_alpha=1; //to record that the user is inserting alpha
if (insert_HP==0){HP=hp; alpha = new double[HP];} //the user does not insert HP
if (mode==2 || mode==3 || mode ==4 || mode==5) //rhomboidal instance
alpha_r=atoi(argv[i+1]);
else{ //pholyhedral instance
int k=i+1;
int a=0;
while(k<argc && argv[k][0]!='-'){ //until the user does not insert any other parameter OR stop giving inputs
if (a<HP)
{alpha[a]=atof(argv[k]);
k=k+1;
a=a+1;}
else //the user could insert more than HP values for alpha: we must remember how many values to ignore
{k=k+1;
a=a+1;}
}
if (a<HP){ //if the user insert less than HP alpha values we set the others to the default value
for(int h=a;h<HP;++h)
alpha[h]=M_PI/6;
printf("\nInserted less than HP=%i values for alpha. The last %i are set to default=%f.\n",HP,HP-a,alpha[a]);
}
else if(a>HP){ //if the user insert more than HP alpha values, we ignore the last ones
printf("\nInserted more than HP=%i values for alpha. The last %i values are ignored.\n",HP,a-HP);
}
j=k-i;
}
}
else if(strcmp(key,"-alphad")==0){
insert_alpha=1; //to record that the user is inserting alpha
if (insert_HP==0){HP=hp; alpha = new double[HP];}//the user does not insert HP
if (mode==2 || mode==3 || mode ==4 || mode==5) //rhomboidal instance
{alpha_r=atoi(argv[i+1]);
alpha_r=M_PI*alpha_r/180;}
else{
int k=i+1;
int a=0;
while(k<argc && argv[k][0]!='-' ){ //until the user does not insert any other parameter OR stop giving inputs
if (a<HP)
{alpha[a]=atof(argv[k]);
alpha[a]=M_PI*alpha[a]/180;
k=k+1;
a=a+1;}
else
{k=k+1;
a=a+1;}
}
if (a<HP){ //if the user insert less than HP alpha values we set the others to the default value
for(int h=a;h<HP;++h)
alpha[h]=M_PI/6;
printf("\nInserted less than HP=%i values for alpha. The last %i are set to default=%f.\n",HP,HP-a,alpha[a]);
}
else if(a>HP){ //if the user insert more than HP alpha values, we ignore the last ones
printf("\nInserted more than HP=%i values for alpha. The last %i values are ignored.\n",HP,a-HP);
}
j=k-i;
}
}
else if(strcmp(key,"-mx")==0){
insert_mx=1; //to record that the user is inserting mx
if (insert_HP==0){HP=hp; mx = new int[HP];} //if the user does not insert HP
if (mode==2 || mode==3 || mode ==4 || mode==5) //rhomboidal instance
horiz=atoi(argv[i+1]);
else{ //polyhedral instance
int k=i+1;
int a=0;
while(k<argc && argv[k][0]!='-'){
if (a<HP)
{mx[a]=atoi(argv[k]);
k=k+1;
a=a+1;}
else
{k=k+1;
a=a+1;}
}
if (a<HP){ //if the user insert less than HP mx values we set the others to the default value
for(int h=a;h<HP;++h)
mx[h]=2;
printf("\nInserted the number of horizontal trails only for %i horizontal planes. The last %i are set to default=%i.\n",a,HP-a,mx[a]);
}
else if(a>HP){ //if the user insert more than HP mx values, we ignore the last ones
printf("\nInserted %i horizontal trails, but there are only HP=%i horizontal planes. The last %i values are ignored.\n",a,HP,a-HP);
}
j=k-i;
}
}
else if(strcmp(key,"-my")==0){
insert_my=1; //to record that the user is inserting my
if (insert_HP==0){HP=hp; my = new int[HP];} //if the user does not insert HP
if (mode==2 || mode==3 || mode ==4 || mode==5) //rhomboidal instance
verti=atoi(argv[i+1]);
else{ // polyhedral instance
int k=i+1;
int a=0;
while(k<argc && argv[k][0]!='-'){
if (a<HP)
{my[a]=atoi(argv[k]);
k=k+1;
a=a+1;}
else
{k=k+1;
a=a+1;}
}
if (a<HP){ //if the user insert less than HP my values we set the others to the default value
for(int h=a;h<HP;++h)
my[h]=2;
printf("\nInserted the number of vertical trails only for %i horizontal planes. The last %i are set to default=%i.\n",a,HP-a,my[a]);
}
else if(a>HP){ //if the user insert more than HP my values, we ignore the last ones
printf("\nInserted %i vertical trails, but there are only HP=%i horizontal planes. The last %i values are ignored.\n",a,HP,a-HP);
}
j=k-i;
}
}
// circle/sphere problem:
else if(strcmp(key,"-r")==0)
radius=atof(argv[i+1]);
else if(strcmp(key,"-secInix")==0)
sector_ini_x=atof(argv[i+1]);
else if(strcmp(key,"-secAngx")==0)
sector_angle_x=atof(argv[i+1]);
else if(strcmp(key,"-secInixd")==0){
sector_ini_x=atof(argv[i+1]);
sector_ini_x=M_PI*sector_ini_x/180;
}
else if(strcmp(key,"-secAngxd")==0){
sector_angle_x=atof(argv[i+1]);
sector_angle_x=M_PI*sector_angle_x/180;
}
else if(strcmp(key,"-secIniz")==0)
sector_ini_z=atof(argv[i+1]);
else if(strcmp(key,"-secAngz")==0)
sector_angle_z=atof(argv[i+1]);
else if(strcmp(key,"-secInizd")==0){
sector_ini_z=atof(argv[i+1]);
sector_ini_z=M_PI*sector_ini_z/180;
}
else if(strcmp(key,"-secAngzd")==0){
sector_angle_z=atof(argv[i+1]);
sector_angle_z=M_PI*sector_angle_z/180;
}
// random circle, sphere, rhomboidal, grid, polyhedral, and cubic:
else if(strcmp(key,"-hamin")==0)
hamin=atof(argv[i+1]);
else if(strcmp(key,"-hamax")==0)
hamax=atof(argv[i+1]);
else
printf("Skipping unrecognized option: %s\n", key);
i=i+j; //either i+2 or k
}
// if the user does not insert HP and/or alpha and/or mx and/or my
if (insert_HP==0){
HP=hp;
if(insert_alpha==0){
alpha = new double[HP];
for (int i=0;i<HP;++i)
{alpha[i]=M_PI/6;}
}
if (insert_mx==0){
mx = new int[HP];
for (int i=0;i<HP;++i)
mx[i]=2;
}
if (insert_my==0){
my = new int[HP];
for (int i=0;i<HP;++i)
my[i]=2;
}
}
// if the user does not insert VP and/or beta and/or mz
if (insert_VP==0){
VP=vp;
if(insert_beta==0){
beta = new double[VP];
for (int i=0;i<VP;++i)
{beta[i]=2*M_PI/3;}
}
if (insert_mz==0){
mz = new int[VP];
for (int i=0;i<VP;++i)
mz[i]=2;
}
}
if(mode==14 && insert_width==0){width=100;}
if(mode==14 && insert_height==0){height=100;}
if(mode==14 && insert_altitude==0){altitude=100;}
// 2............Print alerts
if(vmin<=0 || vmax <=0 || vmax < vmin){
printf("WARNING: At least one unvalid bound for velocity: %f, %f",vmin, vmax);
vmin=400;
vmax=400;
printf(", set to default: vmin=vmax=%f NM/h.\n",vmin);
}
if ((mode==8 || mode==9)&& sector_ini_z+sector_angle_z>M_PI){
printf("WARNING: the angle Phi must be in [0,PI]. ");
sector_angle_z=M_PI;
sector_ini_z=0;
printf("The sector boundaries are set to default: Sector_init_phi=0, Sector_angle_phi=PI.");
}
if (mode==6 || mode==14){
// detect unvalid parameters:
if (nc>n*(n-1)/2.0) nc=-1;
if (pc>1) pc=-1;
if (maxc>n) maxc=-1;
// nc and pc missing:
if(nc==-1 && pc==-1){
pc=0.5;
printf("random Problem Generator: missing probability of conflicts set to 0.5 \n");
}
// maxc missing:
if(maxc==-1 && (nc==-1 || pc==-1)){
if (nc==-1) maxc=n-1;
else if (pc==-1) maxc=round(8.0*nc/n-1); // this will yield pc=0.5
printf("random Problem Generator: missing max conflicts per aircraft set to %i\n",maxc);
}
// at this point at least 2 parameters among nc, pc and maxc are not -1, we calculate the remaining one:
if(nc==-1)
nc=round(pc*(n/2.0)*((1+maxc)/2.0));
else if(pc==-1){
pc=nc*(2.0/n)*(2.0/(1+maxc));
if (pc>1){
pc=1;
printf("WARNING random Problem Generator: saturated scenario, all aircraft having more than (maxc+1)/2 conflicts\n");
}
}
else if(maxc==-1)
maxc=round((4.0*nc)/(n*pc)-1);
else{
float new_pc=nc*(2.0/n)*(2.0/(1+maxc));
if (new_pc>1){
pc=1;
printf("WARNING random Problem Generator: saturated scenario, all aircraft having more than (maxc+1)/2 conflicts\n");
}
else if(new_pc!=pc){
pc=new_pc;
printf("WARNING random Problem Generator: unvalid probability of conflicts set to %f\n",pc);
}
}
if (verbose)
printf("random Problem Generator: congestion measures nc=%i, maxc=%i, pc=%f\n",nc,maxc,pc);
}
else if(mode==2 ||mode==3 ||mode==4 ||mode==5 ){// rhomboidal or grid problems
n=nx*horiz+ny*verti;
if( mode==2 || mode==3 ){// rhomboidal problem
alpha_r=correctAngle(alpha_r);
if(alpha_r < 0){
alpha_r=M_PI/4;
printf("Rhomboidal Problem generator: unvalid crossing angle, set to default=%f\n",alpha_r);
}
}
}
else if(mode==10 ||mode==11 ||mode==12 ||mode==13){// polyhedral or cubic problems
n=0;
for(int i=0; i<HP; ++i){
n=n+nx*mx[i]+ny*my[i];}
for(int i=0; i<VP; ++i){
n=n+nz*mz[i];}
if( mode==10 || mode==11 ){ //polyhedral
for (int i=0; i<HP; ++i){
alpha[i]=correctAngle(alpha[i]);
if(alpha[i] < 0){
alpha[i]=M_PI/6;
printf("Unvalid crossing angle alpha[%i], set to default=%f\n",i,alpha[i]);
}
}
for (int i=0; i<VP;++i){
beta[i]=correctAngle(beta[i]);
if(beta[i] < 0){
beta[i]=2*M_PI/3;
printf("Polyhderal Problem generator: unvalid crossing angle beta[%i], set to default=%f\n",i,beta[i]);
}
}
}
}
// 3...............Create scenarios
x_0=new float[n];
y_0=new float[n];
z_0=new float[n];
x_t=new float[n];
y_t=new float[n];
z_t=new float[n];
vx=new float[n];
vy=new float[n];
vz=new float[n];
hat_v =new float[n];
hat_theta=new float[n];
hat_phi=new float[n];
if(!is3D){
for (int i = 0; i < n; ++i){
z_0[i]=0;
z_t[i]=0;
vz[i]=0;
hat_phi[i]=M_PI/2;
}
}
switch(mode){// CP,RCP,RP,RRP,GP,RGP,PR2,R2,SP,RSP,PL,RPL,QP,RQP,PR3,R3
case 0:{CircleP(radius,sector_ini_x,sector_angle_x);break;} //CP
case 1:{randomCircleP(radius,sector_ini_x,sector_angle_x,hamin,hamax);break;} //RCP
case 2:{RomboP(alpha_r,horiz,verti,nx,ny,dx,dy,d_aircraft);break;} //RP
case 3:{randomRomboP(alpha_r,horiz,verti,nx,ny,dx,dy,d_aircraft,hamin,hamax);break;} //RRP
case 4:{GridP(horiz,verti,nx,ny,dx,dy,d_aircraft);break;} //GP
case 5:{randomGridP(horiz,verti,nx,ny,dx,dy,d_aircraft,hamin,hamax);break;} //RGP
case 6:{pseudoRandomP(air_config,height,width,0,nc,pc,maxc);break;} //PR2
case 7:{randomP(height,width,0);break;} //R2
case 8:{SphereP(radius,sector_ini_x,sector_angle_x,sector_ini_z,sector_angle_z);break;} //SP
case 9:{randomSphereP(radius,sector_ini_x,sector_angle_x,sector_ini_z,sector_angle_z,hamin,hamax);break;} //RSP
case 10:{PolyhedralP(alpha,beta,mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft);break;} //PL
case 11:{randomPolyhedralP(alpha,beta,mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft,hamin,hamax);break;} //RPL
case 12:{Grid3dP(mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft);break;} //QP
case 13:{randomGrid3dP(mx,my,mz,nx,ny,nz,d_HP,d_VP,dx,dy,dz,d_aircraft,hamin,hamax);break;} //RQP
case 14:{pseudoRandomP(air_config,height,width,altitude,nc,pc,maxc);break;} //PR3
case 15:{randomP(height,width,altitude);break;} //R3
}
// 4............Print output
printBenchmarkInfo();
return 0;
}
| 41.269672 | 254 | 0.598528 | [
"vector",
"3d"
] |
3546290885871a003deef0742464999add8b5456 | 215 | hh | C++ | include/screen_none.hh | frequem/gbemu | 3675595d742bf9bcad9abdabf940c169072c556c | [
"MIT"
] | null | null | null | include/screen_none.hh | frequem/gbemu | 3675595d742bf9bcad9abdabf940c169072c556c | [
"MIT"
] | null | null | null | include/screen_none.hh | frequem/gbemu | 3675595d742bf9bcad9abdabf940c169072c556c | [
"MIT"
] | null | null | null | #ifndef SCREEN_NONE_H
#define SCREEN_NONE_H
#include "screen.hh"
class NoneScreen : public Screen{
public:
NoneScreen();
void render(uint8_t screenbuffer[160][144][3]);
void draw();
bool enabled();
};
#endif
| 14.333333 | 48 | 0.725581 | [
"render"
] |
35584293cb03988be853a11421d5a072d65eff23 | 160,092 | cpp | C++ | src/main.cpp | withthelemons/novacoin | 543862f5601e3a65eee6cde5212f4127eb900a80 | [
"MIT"
] | 1 | 2018-03-06T16:36:02.000Z | 2018-03-06T16:36:02.000Z | src/main.cpp | MarceloGra/novacoin | 543862f5601e3a65eee6cde5212f4127eb900a80 | [
"MIT"
] | null | null | null | src/main.cpp | MarceloGra/novacoin | 543862f5601e3a65eee6cde5212f4127eb900a80 | [
"MIT"
] | 1 | 2018-01-18T14:12:47.000Z | 2018-01-18T14:12:47.000Z | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "txdb.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "kernel.h"
#include "zerocoin/Zerocoin.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
libzerocoin::Params* ZCParams;
CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
int nCoinbaseMaturity = 500;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 nBestChainTrust = 0;
uint256 nBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
set<CBlockIndex*, CBlockIndexTrustComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
map<uint256, CTransaction> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "NovaCoin Signed Message:\n";
// Settings
int64 nTransactionFee = MIN_TX_FEE;
int64 nMinimumInputValue = MIN_TXOUT_AMOUNT;
extern enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// ppcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void ResendWalletTransactions(bool fForce)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions(fForce);
}
//////////////////////////////////////////////////////////////////////////////
//
// CCoinsView implementations
//
bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
bool CCoinsView::HaveCoins(uint256 txid) { return false; }
CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
if (cacheCoins.count(txid)) {
coins = cacheCoins[txid];
return true;
}
if (base->GetCoins(txid, coins)) {
cacheCoins[txid] = coins;
return true;
}
return false;
}
// Select coins from read-only cache or database
bool CCoinsViewCache::GetCoinsReadOnly(uint256 txid, CCoins &coins) {
if (cacheCoins.count(txid)) {
coins = cacheCoins[txid]; // get from cache
return true;
}
if (cacheCoinsReadOnly.count(txid)) {
coins = cacheCoinsReadOnly[txid]; // get from read-only cache
return true;
}
if (base->GetCoins(txid, coins)) {
cacheCoinsReadOnly[txid] = coins; // save to read-only cache
return true;
}
return false;
}
std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end())
return it;
CCoins tmp;
if (!base->GetCoins(txid,tmp))
return it;
std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
return ret.first;
}
CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
assert(it != cacheCoins.end());
return it->second;
}
bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
cacheCoins[txid] = coins;
return true;
}
bool CCoinsViewCache::HaveCoins(uint256 txid) {
return FetchCoins(txid) != cacheCoins.end();
}
CBlockIndex *CCoinsViewCache::GetBestBlock() {
if (pindexTip == NULL)
pindexTip = base->GetBestBlock();
return pindexTip;
}
bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
pindexTip = pindex;
return true;
}
bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
cacheCoins[it->first] = it->second;
pindexTip = pindex;
return true;
}
bool CCoinsViewCache::Flush() {
cacheCoinsReadOnly.clear(); // purge read-only cache
bool fOk = base->BatchWrite(cacheCoins, pindexTip);
if (fOk)
cacheCoins.clear();
return fOk;
}
unsigned int CCoinsViewCache::GetCacheSize() {
return cacheCoins.size();
}
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
if (base->GetCoins(txid, coins))
return true;
if (mempool.exists(txid)) {
const CTransaction &tx = mempool.lookup(txid);
coins = CCoins(tx, MEMPOOL_HEIGHT, -1);
return true;
}
return false;
}
bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
return mempool.exists(txid) || base->HaveCoins(txid);
}
CCoinsViewCache *pcoinsTip = NULL;
CBlockTreeDB *pblocktree = NULL;
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (nSize > 5000)
{
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
return false;
}
mapOrphanTransactions[hash] = tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CTransaction& tx = mapOrphanTransactions[hash];
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction
//
bool CTransaction::IsStandard() const
{
if (nVersion > CTransaction::CURRENT_VERSION) {
return false;
}
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500) {
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
return false;
}
if (fEnforceCanonical && !txin.scriptSig.HasCanonicalPushes()) {
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH(const CTxOut& txout, vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
return false;
}
if (whichType == TX_NULL_DATA)
nDataOut++;
else {
if (txout.nValue == 0) {
return false;
}
if (fEnforceCanonical && !txout.scriptPubKey.HasCanonicalPushes()) {
return false;
}
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
return false;
}
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL) {
CCoins coins;
if (pcoinsTip->GetCoins(GetHash(), coins)) {
CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
if (pindex) {
if (!blockTmp.ReadFromDisk(pindex))
return 0;
pblock = &blockTmp;
}
}
}
if (pblock) {
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
{
// Use new fees approach if we are on test network or
// switch date has been reached
bool fNewApproach = fTestNet || nTime > FEE_SWITCH_TIME;
int64 nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
if(!fNewApproach || IsCoinStake())
{
// Enforce 0.01 as minimum fee for old approach or coinstake
nMinTxFee = CENT;
nMinRelayTxFee = CENT;
}
// Base fee is either nMinTxFee or nMinRelayTxFee
int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
if (fNewApproach)
{
if (fAllowFree)
{
if (nBlockSize == 1)
{
// Transactions under 1K are free
if (nBytes < 1000)
nMinFee = 0;
}
else
{
// Free transaction area
if (nNewBlockSize < 27000)
nMinFee = 0;
}
}
// To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
// each non empty output which is less than 0.01
//
// It's safe to ignore empty outputs here, because these inputs are allowed
// only for coinbase and coinstake transactions.
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT && !txout.IsEmpty())
nMinFee += nBaseFee;
}
else if (nMinFee < nBaseFee)
{
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if
// any output is less than 0.01
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
{
LOCK(cs);
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
// iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
while (it != mapNextTx.end() && it->first.hash == hashTx) {
coins.Spend(it->first.n); // and remove those outputs from coins
it++;
}
}
bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// Coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// is it already in the memory pool?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
CCoinsViewCache &view = *pcoinsTip;
// do we already have it?
if (view.HaveCoins(hash))
return false;
// do all inputs exist?
BOOST_FOREACH(const CTxIn txin, tx.vin) {
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
if (!tx.HaveInputs(view))
return error("CTxMemPool::accept() : inputs already spent");
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(view) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(*this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
++nTransactionsUpdated;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
// Return depth of transaction in blockchain:
// -1 : not in blockchain, and not in memory pool (conflicted transaction)
// 0 : in memory pool, waiting to be included in a block
// >=1 : this many blocks deep in the main chain
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
bool fInMemPool = mempool.exists(GetHash());
if (hashBlock == 0 || nIndex == -1) {
return fInMemPool ? 0 : -1;
}
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end()) {
return fInMemPool ? 0 : -1;
}
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain()) {
return fInMemPool ? 0 : -1;
}
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) {
return fInMemPool ? 0 : -1;
}
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientCheckInputs())
return false;
return CTransaction::AcceptToMemoryPool(false);
}
else
{
return CTransaction::AcceptToMemoryPool(fCheckInputs);
}
}
bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
tx.AcceptToMemoryPool(fCheckInputs);
}
}
return AcceptToMemoryPool(fCheckInputs);
}
return false;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
{
CBlockIndex *pindexSlow = NULL;
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
txOut = mempool.lookup(hash);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
int nHeight = -1;
{
CCoinsViewCache &view = *pcoinsTip;
CCoins coins;
if (view.GetCoins(hash, coins))
nHeight = coins.nHeight;
}
if (nHeight > 0)
pindexSlow = FindBlockByHeight(nHeight);
}
}
if (pindexSlow) {
CBlock block;
if (block.ReadFromDisk(pindexSlow)) {
BOOST_FOREACH(const CTransaction &tx, block.vtx) {
if (tx.GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
// select stake target limit according to hard-coded conditions
CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
{
if(fTestNet) // separate proof of stake target limit for testnet
return bnProofOfStakeLimit;
if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
return bnProofOfStakeLimit;
if(nHeight + 1 > 15000) // 24 bits since block 15000
return bnProofOfStakeLegacyLimit;
if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
return bnProofOfStakeHardLimit;
return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
}
// miner's coin base reward based on nBits
int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees)
{
CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
CBigNum bnTargetLimit = bnProofOfWorkLimit;
bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
// NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
// A reasonably continuous curve is used to avoid shock to market
// (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
//
// Human readable form:
//
// nSubsidy = 100 / (diff ^ 1/6)
CBigNum bnLowerBound = CENT;
CBigNum bnUpperBound = bnSubsidyLimit;
while (bnLowerBound + CENT <= bnUpperBound)
{
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
bnUpperBound = bnMidValue;
else
bnLowerBound = bnMidValue;
}
int64 nSubsidy = bnUpperBound.getuint64();
nSubsidy = (nSubsidy / CENT) * CENT;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d" nFees=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy, nFees);
return min(nSubsidy + nFees, MAX_MINT_PROOF_OF_WORK);
}
// miner's coin stake reward based on nBits and coin age spent (coin-days)
int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
{
int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
if(fTestNet || nTime > STAKE_SWITCH_TIME)
{
// Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
// NovaCoin: A reasonably continuous curve is used to avoid shock to market
CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
bnMidPart, bnRewardPart;
while (bnLowerBound + CENT <= bnUpperBound)
{
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
{
//
// Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
//
// (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
//
// Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
//
bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
}
else
{
//
// Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
//
// (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
//
// Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
//
bnMidPart = bnMidValue * bnMidValue * bnMidValue;
bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
}
if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
bnUpperBound = bnMidValue;
else
bnLowerBound = bnMidValue;
}
nRewardCoinYear = bnUpperBound.getuint64();
nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
}
else
{
// Old creation amount per coin-year, 5% fixed stake mint rate
nRewardCoinYear = 5 * CENT;
}
if(bCoinYearOnly)
return nRewardCoinYear;
nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
// Set reasonable reward limit for large inputs since 20 Oct 2013
//
// This will stimulate large holders to use smaller inputs, that's good for the network protection
if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
{
if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
nSubsidy = min(nSubsidy, nSubsidyLimit);
}
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
return nSubsidy;
}
static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
// get proof of work blocks max spacing according to hard-coded conditions
int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
{
if(nTime > TARGETS_SWITCH_TIME)
return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
if(fTestNet)
return 3 * nStakeTargetSpacing; // 15 minutes on testNet
return 12 * nStakeTargetSpacing; // 2 hours otherwise
}
//
// maximum nBits value could possible be required nTime after
//
unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
{
CBigNum bnResult;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < bnTargetLimit)
{
// Maximum 200% adjustment per day...
bnResult *= 2;
nTime -= 24 * 60 * 60;
}
if (bnResult > bnTargetLimit)
bnResult = bnTargetLimit;
return bnResult.GetCompact();
}
//
// minimum amount of work that could possibly be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
}
//
// minimum amount of stake that could possibly be required nTime after
// minimum proof-of-stake required was nBase
//
unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
{
return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
}
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
int64 nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->nChainTrust > nBestInvalidTrust)
{
nBestInvalidTrust = pindexNew->nChainTrust;
pblocktree->WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
uiInterface.NotifyBlocksChanged();
}
uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
CBigNum(pindexBest->nChainTrust).ToString().c_str(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
}
void static InvalidBlockFound(CBlockIndex *pindex) {
pindex->nStatus |= BLOCK_FAILED_VALID;
pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
setBlockIndexValid.erase(pindex);
InvalidChainFound(pindex);
if (pindex->pnext)
ConnectBestBlock(); // reorganise away from the failed block
}
bool ConnectBestBlock() {
do {
CBlockIndex *pindexNewBest;
{
std::set<CBlockIndex*,CBlockIndexTrustComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
if (it == setBlockIndexValid.rend())
return true;
pindexNewBest = *it;
}
if (pindexNewBest == pindexBest)
return true; // nothing to do
// check ancestry
CBlockIndex *pindexTest = pindexNewBest;
std::vector<CBlockIndex*> vAttach;
do {
if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
// mark descendants failed
CBlockIndex *pindexFailed = pindexNewBest;
while (pindexTest != pindexFailed) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
setBlockIndexValid.erase(pindexFailed);
pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
pindexFailed = pindexFailed->pprev;
}
InvalidChainFound(pindexNewBest);
break;
}
if (pindexBest == NULL || pindexTest->nChainTrust > pindexBest->nChainTrust)
vAttach.push_back(pindexTest);
if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
reverse(vAttach.begin(), vAttach.end());
BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach)
if (!SetBestChain(pindexSwitch))
return false;
return true;
}
pindexTest = pindexTest->pprev;
} while(true);
} while(true);
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
{
const CCoins &coins = view.GetCoins(input.prevout.hash);
assert(coins.IsAvailable(input.prevout.n));
return coins.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
nResult += GetOutputFor(vin[i], inputs).nValue;
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut &prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, unsigned int nTimeStamp, const uint256 &txhash) const
{
// mark inputs spent
if (!IsCoinBase()) {
BOOST_FOREACH(const CTxIn &txin, vin) {
CCoins &coins = inputs.GetCoins(txin.prevout.hash);
if (coins.nTime > nTimeStamp)
return error("UpdateCoins() : timestamp violation");
CTxInUndo undo;
if (!coins.Spend(txin.prevout, undo))
return error("UpdateCoins() : cannot spend input");
txundo.vprevout.push_back(undo);
}
}
// add outputs
if (!inputs.SetCoins(txhash, CCoins(*this, nHeight, nTimeStamp)))
return error("UpdateCoins() : cannot update output");
return true;
}
bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
{
if (!IsCoinBase()) {
// first check whether information about the prevout hash is available
for (unsigned int i = 0; i < vin.size(); i++) {
const COutPoint &prevout = vin[i].prevout;
if (!inputs.HaveCoins(prevout.hash))
return false;
}
// then check whether the actual outputs are available
for (unsigned int i = 0; i < vin.size(); i++) {
const COutPoint &prevout = vin[i].prevout;
const CCoins &coins = inputs.GetCoins(prevout.hash);
if (!coins.IsAvailable(prevout.n))
return false;
}
}
return true;
}
bool CTransaction::CheckInputs(CCoinsViewCache &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
{
if (!IsCoinBase())
{
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!HaveInputs(inputs))
return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str());
CBlockIndex *pindexBlock = inputs.GetBestBlock();
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint &prevout = vin[i].prevout;
const CCoins &coins = inputs.GetCoins(prevout.hash);
// If prev is coinbase or coinstake, check that it's matured
if (coins.IsCoinBase() || coins.IsCoinStake()) {
if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
}
// Check transaction timestamp
if (coins.nTime > nTime)
return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += coins.vout[prevout.n].nValue;
if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("CheckInputs() : txin values out of range"));
}
if (IsCoinStake())
{
if (!pblock)
return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
// Coin stake tx earns reward instead of paying fee
uint64 nCoinAge;
if (!GetCoinAge(nCoinAge))
return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
unsigned int nTxSize = fProtocol048 ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
int64 nReward = GetValueOut() - nValueIn;
int64 nCalculatedReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
if (nReward > nCalculatedReward)
return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nReward, nCalculatedReward));
}
else
{
if (nValueIn < GetValueOut())
return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("CheckInputs() : nFees out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip ECDSA signature verification when connecting blocks
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (csmode == CS_ALWAYS ||
(csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
for (unsigned int i = 0; i < vin.size(); i++) {
const COutPoint &prevout = vin[i].prevout;
const CCoins &coins = inputs.GetCoins(prevout.hash);
// Verify signature
if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
}
}
return true;
}
bool CTransaction::ClientCheckInputs() const
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view)
{
assert(pindex == view.GetBestBlock());
CBlockUndo blockUndo;
{
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
return error("DisconnectBlock() : no undo data available");
FILE *file = OpenUndoFile(pos, true);
if (file == NULL)
return error("DisconnectBlock() : undo file not available");
CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
fileUndo >> blockUndo;
}
assert(blockUndo.vtxundo.size() + 1 == vtx.size());
// undo transactions in reverse order
for (int i = vtx.size() - 1; i >= 0; i--) {
const CTransaction &tx = vtx[i];
uint256 hash = tx.GetHash();
// don't check coinbase coins for proof-of-stake block
if(IsProofOfStake() && tx.IsCoinBase())
continue;
// check that all outputs are available
if (!view.HaveCoins(hash))
return error("DisconnectBlock() : outputs still spent? database corrupted");
CCoins &outs = view.GetCoins(hash);
CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
if (outs != outsBlock)
return error("DisconnectBlock() : added transaction mismatch? database corrupted");
// remove outputs
outs = CCoins();
// restore inputs
if (i > 0) { // not coinbases
const CTxUndo &txundo = blockUndo.vtxundo[i-1];
assert(txundo.vprevout.size() == tx.vin.size());
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint &out = tx.vin[j].prevout;
const CTxInUndo &undo = txundo.vprevout[j];
CCoins coins;
view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
if (coins.IsPruned()) {
if (undo.nHeight == 0)
return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
coins.fCoinBase = undo.fCoinBase;
coins.fCoinStake = undo.fCoinStake;
coins.nHeight = undo.nHeight;
coins.nTime = undo.nTime;
coins.nBlockTime = undo.nBlockTime;
coins.nVersion = undo.nVersion;
} else {
if (undo.nHeight != 0)
return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
}
if (coins.IsAvailable(out.n))
return error("DisconnectBlock() : prevout output not spent? database corrupted");
if (coins.vout.size() < out.n+1)
coins.vout.resize(out.n+1);
coins.vout[out.n] = undo.txout;
if (!view.SetCoins(out.hash, coins))
return error("DisconnectBlock() : cannot restore coin inputs");
}
}
// clean up wallet after disconnecting coinstake
SyncWithWallets(vtx[i].GetHash(), vtx[i], this, false, false);
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev);
return true;
}
bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock(!fJustCheck, !fJustCheck))
return false;
// verify that the view's current state corresponds to the previous block
assert(pindex->pprev == view.GetBestBlock());
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = true;
bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
if (fEnforceBIP30) {
for (unsigned int i=0; i<vtx.size(); i++) {
uint256 hash = GetTxHash(i);
if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
return error("ConnectBlock() : tried to overwrite transaction");
}
}
// BIP16 always active
bool fStrictPayToScriptHash = true;
CBlockUndo blockundo;
int64 nFees = 0, nValueIn = 0, nValueOut = 0;
unsigned int nSigOps = 0;
for (unsigned int i=0; i<vtx.size(); i++)
{
const CTransaction &tx = vtx[i];
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
if (!tx.IsCoinBase())
{
if (!tx.HaveInputs(view))
return DoS(100, error("ConnectBlock() : inputs missing/spent"));
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(view);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
int64 nTxValueOut = tx.GetValueOut();
int64 nTxValueIn = tx.GetValueIn(view);
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
return false;
}
else
{
nValueOut += tx.GetValueOut();
}
// don't create coinbase coins for proof-of-stake block
if(IsProofOfStake() && tx.IsCoinBase())
continue;
CTxUndo txundo;
if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime, GetTxHash(i)))
return error("ConnectBlock() : UpdateInputs failed");
if (!tx.IsCoinBase())
blockundo.vtxundo.push_back(txundo);
}
if (IsProofOfWork())
{
int64 nBlockReward = GetProofOfWorkReward(nBits, fProtocol048 ? nFees : 0);
// Check coinbase reward
if (vtx[0].GetValueOut() > nBlockReward)
return error("ConnectBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
vtx[0].GetValueOut(),
nBlockReward);
}
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
{
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos pos;
if (!FindUndoPos(pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
return error("ConnectBlock() : FindUndoPos failed");
if (!blockundo.WriteToDisk(pos))
return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
// update nUndoPos in block index
pindex->nUndoPos = pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
CDiskBlockIndex blockindex(pindex);
if (!pblocktree->WriteBlockIndex(blockindex))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// add this block to the view's blockchain
if (!view.SetBestBlock(pindex))
return false;
// fees are destroyed to compensate the entire network
if (fDebug && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
// Watch for transactions paying to me
for (unsigned int i=0; i<vtx.size(); i++)
SyncWithWallets(GetTxHash(i), vtx[i], this, true);
return true;
}
bool SetBestChain(CBlockIndex* pindexNew)
{
CCoinsViewCache &view = *pcoinsTip;
// special case for attaching the genesis block
// note that no ConnectBlock is called, so its coinbase output is non-spendable
if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
{
view.SetBestBlock(pindexNew);
if (!view.Flush())
return false;
pindexGenesisBlock = pindexNew;
pindexBest = pindexNew;
hashBestChain = pindexNew->GetBlockHash();
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexNew->nChainTrust;
return true;
}
// Find the fork (typically, there is none)
CBlockIndex* pfork = view.GetBestBlock();
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("SetBestChain() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("SetBestChain() : pfork->pprev is null");
}
// List of what to disconnect (typically nothing)
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect (typically only pindexNew)
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
if (vDisconnect.size() > 0) {
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
}
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("SetBestChain() : ReadFromDisk for disconnect failed");
CCoinsViewCache viewTemp(view, true);
if (!block.DisconnectBlock(pindex, viewTemp))
return error("SetBestChain() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
if (!viewTemp.Flush())
return error("SetBestChain() : Cache flush failed after disconnect");
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!tx.IsCoinBase() && !tx.IsCoinStake())
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("SetBestChain() : ReadFromDisk for connect failed");
CCoinsViewCache viewTemp(view, true);
if (!block.ConnectBlock(pindex, viewTemp)) {
InvalidChainFound(pindexNew);
InvalidBlockFound(pindex);
return error("SetBestChain() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
if (!viewTemp.Flush())
return error("SetBestChain() : Cache flush failed after connect");
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
// Make sure it's successfully written to disk before changing memory structure
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload || view.GetCacheSize()>5000)
if (!view.Flush())
return false;
// At this point, all changes have been done to the database.
// Proceed by updating the memory structures.
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
// Update best block in wallet (so we can detect restored wallets)
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = pindexNew->GetBlockHash();
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexNew->nChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%s tx=%lu date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(), CBigNum(nBestBlockTrust).ToString().c_str(), (unsigned long)pindexNew->nChainTx,
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// Total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(uint64& nCoinAge) const
{
CCoinsViewCache &inputs = *pcoinsTip;
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint &prevout = vin[i].prevout;
CCoins coins;
if (!inputs.GetCoins(prevout.hash, coins))
continue;
if (nTime < coins.nTime)
return false; // Transaction timestamp violation
// only count coins meeting min age requirement
if (coins.nBlockTime + nStakeMinAge > nTime)
continue;
int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// Total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64& nCoinAge) const
{
nCoinAge = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64 nTxCoinAge;
if (tx.GetCoinAge(nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(*this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
pindexNew->nTx = vtx.size();
pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
// Compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// Record proof-of-stake hash value
if (pindexNew->IsProofOfStake())
{
if (!mapProofOfStake.count(hash))
return error("AddToBlockIndex() : hashProofOfStake not found in map");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// Compute stake modifier
uint64 nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
setBlockIndexValid.insert(pindexNew);
pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew));
// New best?
if (!ConnectBestBlock())
return false;
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = GetTxHash(0);
}
pblocktree->Flush();
uiInterface.NotifyBlocksChanged();
return true;
}
bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
{
bool fUpdatedLast = false;
LOCK(cs_LastBlockFile);
while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
FILE *file = OpenBlockFile(pos);
FileCommit(file);
fclose(file);
file = OpenUndoFile(pos);
FileCommit(file);
fclose(file);
nLastBlockFile++;
infoLastBlockFile.SetNull();
pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
fUpdatedLast = true;
}
pos.nFile = nLastBlockFile;
pos.nPos = infoLastBlockFile.nSize;
infoLastBlockFile.nSize += nAddSize;
infoLastBlockFile.AddBlock(nHeight, nTime);
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
FILE *file = OpenBlockFile(pos);
if (file) {
printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
}
fclose(file);
}
if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
return error("FindBlockPos() : cannot write updated block info");
if (fUpdatedLast)
pblocktree->WriteLastBlockFile(nLastBlockFile);
return true;
}
bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
if (nFile == nLastBlockFile) {
pos.nPos = infoLastBlockFile.nUndoSize;
nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
return error("FindUndoPos() : cannot write updated block info");
} else {
CBlockFileInfo info;
if (!pblocktree->ReadBlockFileInfo(nFile, info))
return error("FindUndoPos() : cannot read block info");
pos.nPos = info.nUndoSize;
nNewSize = (info.nUndoSize += nAddSize);
if (!pblocktree->WriteBlockFileInfo(nFile, info))
return error("FindUndoPos() : cannot write updated block info");
}
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
FILE *file = OpenUndoFile(pos);
if (file) {
printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
}
fclose(file);
}
return true;
}
bool CBlock::CheckBlockHeader(bool fCheckPoW, bool fCheckSig) const
{
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
return error("CheckBlockHeader() : block timestamp too far in the future");
if (IsProofOfWork())
{
// Check proof of work matches claimed amount
if (fCheckPoW && !CheckProofOfWork(GetHash(), nBits))
return DoS(50, error("CheckBlockHeader() : proof of work failed"));
// Should we check proof-of-work block signature or not?
//
// * Always skip on TestNet
// * Perform checking for the first 9689 blocks
// * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
if(!fTestNet && fCheckSig)
{
bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
// check legacy proof-of-work block signature
if (checkEntropySig && !CheckLegacySignature())
return DoS(100, error("CheckBlockHeader() : bad proof-of-work block signature"));
}
}
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
{
bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
if (!CheckBlockHeader(fCheckPOW, fCheckSig))
return false;
// First transaction must be coinbase
if (!vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
if (!vtx[0].CheckTransaction())
return DoS(100, error("CheckBlock() : CheckTransaction failed for coinbase"));
// Check coinbase timestamp
if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
if (!fProtocol048)
{
// Check coinbase timestamp
if (GetBlockTime() < (int64)vtx[0].nTime)
return DoS(100, error("CheckBlock() : coinbase timestamp violation"));
}
if (IsProofOfStake())
{
// Coinbase output should be empty if proof-of-stake block
if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Second transaction must be coinstake
if (!vtx[1].IsCoinStake())
return DoS(100, error("CheckBlock() : second tx is not coinstake"));
// Check coinstake timestamp
if (GetBlockTime() != (int64)vtx[1].nTime)
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
if (!vtx[1].CheckTransaction())
return DoS(100, error("CheckBlock() : CheckTransaction failed for coinstake"));
if (fProtocol048)
{
if (nNonce != 0)
return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
}
}
else
{
if (GetBlockTime() < PastDrift((int64)vtx[0].nTime))
return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
}
// Check user transactions
for (unsigned int i = 2; i < vtx.size(); i++)
{
const CTransaction& tx = vtx[i];
// check transaction timestamp
if (GetBlockTime() < (int64)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp (vtx[%d])", i));
// coinbase is allowed only for vtx[0]
if (tx.IsCoinBase())
return DoS(100, error("CheckBlock() : coinbase in wrong position (vtx[%d])", i));
// coinstake is allowed only for vtx[1]
if (tx.IsCoinStake())
return DoS(100, error("CheckBlock() : coinstake in wrong position (vtx[%d])", i));
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed (vtx[%d])", i));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
BuildMerkleTree();
set<uint256> uniqueTx;
for (unsigned int i=0; i<vtx.size(); i++) {
uniqueTx.insert(GetTxHash(i));
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect proof-of-%s amount", IsProofOfWork() ? "work" : "stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
return error("AcceptBlock() : rejected by synchronized checkpoint");
if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
// Enforce rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
CDiskBlockPos blockPos;
{
if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, nTime))
return error("AcceptBlock() : FindBlockPos failed");
}
if (!WriteToDisk(blockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(blockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// Check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
uint256 CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
/* Old protocol */
if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
/* New protocol */
// Calculate work amount for block
uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
// Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
// Return nPoWTrust for the first 12 blocks
if (pprev == NULL || pprev->nHeight < 12)
return nPoWTrust;
const CBlockIndex* currentIndex = pprev;
if(IsProofOfStake())
{
CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
// Return 1/3 of score if parent block is not the PoW block
if (!pprev->IsProofOfWork())
return (bnNewTrust / 3).getuint256();
int nPoWCount = 0;
// Check last 12 blocks type
while (pprev->nHeight - currentIndex->nHeight < 12)
{
if (currentIndex->IsProofOfWork())
nPoWCount++;
currentIndex = currentIndex->pprev;
}
// Return 1/3 of score if less than 3 PoW blocks found
if (nPoWCount < 3)
return (bnNewTrust / 3).getuint256();
return bnNewTrust.getuint256();
}
else
{
CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
// Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
int nPoSCount = 0;
// Check last 12 blocks type
while (pprev->nHeight - currentIndex->nHeight < 12)
{
if (currentIndex->IsProofOfStake())
nPoSCount++;
currentIndex = currentIndex->pprev;
}
// Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
if (nPoSCount < 7)
return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
bnTarget.SetCompact(pprev->nBits);
if (bnTarget <= 0)
return 0;
CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
// Return nPoWTrust + full trust score for previous block nBits
return nPoWTrust + bnNewTrust.getuint256();
}
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
if (pblock->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
bool fFatal = false;
uint256 hashProofOfStake;
// Verify proof-of-stake script, hash target and signature
if (!pblock->CheckSignature(fFatal, hashProofOfStake))
{
if (fFatal)
{
// Invalid coinstake script, blockhash signature or no generator defined, nothing to do here
// This also may occur when supplied proof-of-stake doesn't satisfy required target
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : invalid signatures found in proof-of-stake block %s", hash.ToString().c_str());
}
else
{
// Blockhash and coinstake signatures are OK but target checkings failed
// This may occur during initial block download
if (pfrom)
pfrom->Misbehaving(1); // Small DoS penalty
printf("WARNING: ProcessBlock(): proof-of-stake target checkings failed for block %s, we'll try again later\n", hash.ToString().c_str());
return false;
}
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
if (pblock->IsProofOfStake())
bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
else
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little proof-of-%s", pblock->IsProofOfStake() ? "stake" : "work");
}
}
// Ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
if (pblock2->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
else
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
}
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// attempt to generate suitable proof-of-stake
bool CBlock::SignBlock(CWallet& wallet)
{
// if we are trying to sign
// something except proof-of-stake block template
if (!vtx[0].vout[0].IsEmpty())
return false;
// if we are trying to sign
// a complete proof-of-stake block
if (IsProofOfStake())
return true;
static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
CKey key;
CTransaction txCoinStake;
int64 nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
{
if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
{
// make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
vtx[0].nTime = nTime = txCoinStake.nTime;
nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
// we have to make sure that we have no future timestamps in
// our transactions set
for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
vtx.insert(vtx.begin() + 1, txCoinStake);
hashMerkleRoot = BuildMerkleTree();
// append a signature to our block
return key.Sign(GetHash(), vchBlockSig);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
return false;
}
// get generation key
bool CBlock::GetGenerator(CKey& GeneratorKey) const
{
if(!IsProofOfStake())
return false;
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
CKey key;
return GeneratorKey.SetPubKey(vchPubKey);
}
return false;
}
// verify proof-of-stake signatures
bool CBlock::CheckSignature(bool& fFatal, uint256& hashProofOfStake) const
{
CKey key;
// no generator or invalid hash signature means fatal error
fFatal = !GetGenerator(key) || !key.Verify(GetHash(), vchBlockSig);
if (fFatal)
return false;
uint256 hashTarget = 0;
if (!CheckProofOfStake(vtx[1], nBits, hashProofOfStake, hashTarget, fFatal))
return false; // hash target mismatch or invalid coinstake signature
return true;
}
// verify legacy proof-of-work signature
bool CBlock::CheckLegacySignature() const
{
if (IsProofOfStake())
return false;
vector<valtype> vSolutions;
txnouttype whichType;
for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
{
const CTxOut& txout = vtx[0].vout[i];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Verify
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
continue;
if (vchBlockSig.empty())
continue;
if(!key.Verify(GetHash(), vchBlockSig))
continue;
return true;
}
}
return false;
}
// entropy bit for stake modifier if chosen by modifier
unsigned int CBlock::GetStakeEntropyBit(unsigned int nTime) const
{
// Protocol switch at novacoin block #9689
if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
// Before novacoin block #9689 - old protocol
uint160 hashSig = Hash160(vchBlockSig);
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
hashSig >>= 159; // take the first bit of the hash
if (fDebug && GetBoolArg("-printstakemodifier"))
printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
return hashSig.Get64();
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low!");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
CCriticalSection cs_LastBlockFile;
CBlockFileInfo infoLastBlockFile;
int nLastBlockFile = 0;
FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
{
if (pos.IsNull())
return NULL;
boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+");
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
printf("Unable to open file %s\n", path.string().c_str());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
fclose(file);
return NULL;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "blk", fReadOnly);
}
FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "rev", fReadOnly);
}
CBlockIndex * InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("InsertBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool static LoadBlockIndexDB()
{
if (!pblocktree->LoadBlockIndexGuts())
return false;
if (fRequestShutdown)
return true;
// Calculate nChainTrust
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
setBlockIndexValid.insert(pindex);
// Calculate stake modifier checksum
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
return error("LoadBlockIndexDB() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
}
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
printf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
printf("LoadBlockIndexDB(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
// Load hashBestChain pointer to end of best chain
pindexBest = pcoinsTip->GetBestBlock();
if (pindexBest == NULL)
{
if (pindexGenesisBlock == NULL)
return true;
return error("LoadBlockIndexDB() : hashBestChain not loaded");
}
hashBestChain = pindexBest->GetBlockHash();
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexBest->nChainTrust;
// set 'next' pointers in best chain
CBlockIndex *pindex = pindexBest;
while(pindex != NULL && pindex->pprev != NULL) {
CBlockIndex *pindexPrev = pindex->pprev;
pindexPrev->pnext = pindex;
pindex = pindexPrev;
}
printf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// Load sync-checkpoint
if (!pblocktree->ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
return error("LoadBlockIndexDB() : hashSyncCheckpoint not loaded");
printf("LoadBlockIndexDB(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
// Load bnBestInvalidTrust, OK if it doesn't exist
CBigNum bnBestInvalidTrust;
pblocktree->ReadBestInvalidTrust(bnBestInvalidTrust);
nBestInvalidTrust = bnBestInvalidTrust.getuint256();
// Verify blocks in the best chain
int nCheckLevel = GetArg("-checklevel", 1);
int nCheckDepth = GetArg( "-checkblocks", 288);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndexDB() : block.ReadFromDisk failed");
// check level 1: verify block validity
if (nCheckLevel>0 && !block.CheckBlock())
{
printf("LoadBlockIndexDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// TODO: stronger verifications
}
if (pindexFork && !fRequestShutdown)
{
// TODO: reorg back
return error("LoadBlockIndexDB(): chain database corrupted");
}
return true;
}
bool LoadBlockIndex(bool fAllowNew)
{
CBigNum bnTrustedModulus;
if (fTestNet)
{
pchMessageStart[0] = 0xcd;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0xc0;
pchMessageStart[3] = 0xef;
bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
nCoinbaseMaturity = 10; // test maturity is 10 blocks
nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
}
else
{
bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
}
// Set up the Zerocoin Params object
ZCParams = new libzerocoin::Params(bnTrustedModulus);
//
// Load block index from databases
//
if (!LoadBlockIndexDB())
return false;
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis block
// MainNet:
//CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
// Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
// CTxOut(empty)
// vMerkleTree: 4cb33b3b6a
// TestNet:
//CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
// Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
// CTxOut(empty)
// vMerkleTree: 4cb33b3b6a
const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
CTransaction txNew;
txNew.nTime = 1360105017;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1360105017;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = !fTestNet ? 1575379 : 46534;
//// debug print
uint256 hash = block.GetHash();
printf("%s\n", hash.ToString().c_str());
assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
block.print();
assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
assert(block.CheckBlock());
// Start new block file
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
if (!FindBlockPos(blockPos, nBlockSize+8, 0, block.nTime))
return error("AcceptBlock() : FindBlockPos failed");
if (!block.WriteToDisk(blockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(blockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
return error("LoadBlockIndex() : failed to init sync checkpoint");
// upgrade time set to zero if txdb initialized
if (!pblocktree->WriteModifierUpgradeTime(0))
return error("LoadBlockIndex() : failed to init upgrade info");
printf(" Upgrade Info: blocktreedb initialization\n");
}
string strPubKey = "";
// if checkpoint master key changed must reset sync-checkpoint
if (!pblocktree->ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
// write checkpoint master key to db
if (!pblocktree->WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
}
if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
// upgrade time set to zero if blocktreedb initialized
if (pblocktree->ReadModifierUpgradeTime(nModifierUpgradeTime))
{
if (nModifierUpgradeTime)
printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
else
printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
}
else
{
nModifierUpgradeTime = GetTime();
printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
if (!pblocktree->WriteModifierUpgradeTime(nModifierUpgradeTime))
return error("LoadBlockIndex() : failed to write upgrade info");
}
return true;
}
void PrintBlockTree()
{
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
pindex->nHeight,
pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64 nStart = GetTimeMillis();
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// if detected unmet upgrade requirement enter safe mode
// Note: Modifier upgrade requires blockchain redownload if past protocol switch
if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
{
nPriority = 5000;
strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.7b6 upgrade deadline.";
}
// ppcoin: if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
strRPC = strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = mempool.exists(inv.hash);
}
return txInMap || mapOrphanTransactions.count(inv.hash) ||
pcoinsTip->HaveCoins(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
if (pfrom->nVersion < 60010)
{
printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return true;
}
// record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nStartingHeight > (nBestHeight - 144)) &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// Relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %"PRIszu"", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %"PRIszu"", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %"PRIszu"", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// ppcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
LOCK(mempool.cs);
if (mempool.exists(inv.hash)) {
CTransaction tx = mempool.lookup(inv.hash);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
}
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
// ppcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(true, &fMissingInputs))
{
SyncWithWallets(inv.hash, tx, NULL, true);
RelayTransaction(tx, inv.hash);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const uint256& orphanTxHash = *mi;
CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
bool fMissingInputs2 = false;
if (orphanTx.AcceptToMemoryPool(true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
SyncWithWallets(inv.hash, tx, NULL, true);
RelayTransaction(orphanTx, orphanTxHash);
mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
vWorkQueue.push_back(orphanTxHash);
vEraseQueue.push_back(orphanTxHash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(orphanTxHash);
printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(tx);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, hashBlock);
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
// Don't return addresses older than nCutOff timestamp
int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
if(addr.nTime > nCutOff)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
while (true)
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
// * call the result n
// * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
uint64 CTxOutCompressor::CompressAmount(uint64 n)
{
if (n == 0)
return 0;
int e = 0;
while (((n % 10) == 0) && e < 9) {
n /= 10;
e++;
}
if (e < 9) {
int d = (n % 10);
assert(d >= 1 && d <= 9);
n /= 10;
return 1 + (n*9 + d - 1)*10 + e;
} else {
return 1 + (n - 1)*10 + 9;
}
}
uint64 CTxOutCompressor::DecompressAmount(uint64 x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
return 0;
x--;
// x = 10*(9*n + d - 1) + e
int e = x % 10;
x /= 10;
uint64 n = 0;
if (e < 9) {
// x = 9*n + d - 1
int d = (x % 9) + 1;
x /= 9;
// x = n
n = x*10 + d;
} else {
n = x+1;
}
while (e) {
n *= 10;
e--;
}
return n;
}
| 36.170809 | 1,060 | 0.604896 | [
"object",
"vector"
] |
355b06803fa5ec7094bdfb46f192c21e4a006dcd | 832 | cpp | C++ | C++/1025.cpp | AndroAvi/DSA | 5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582 | [
"MIT"
] | 4 | 2021-08-28T19:16:50.000Z | 2022-03-04T19:46:31.000Z | C++/1025.cpp | AndroAvi/DSA | 5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582 | [
"MIT"
] | 8 | 2021-10-29T19:10:51.000Z | 2021-11-03T12:38:00.000Z | C++/1025.cpp | AndroAvi/DSA | 5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582 | [
"MIT"
] | 4 | 2021-09-06T05:53:07.000Z | 2021-12-24T10:31:40.000Z | // trick solution
// Time : O(1)
class Solution {
public:
bool divisorGame(int n) {
return n % 2 == 0;
}
};
// solution using dynamic programming
// Time : O(n^2)
class Solution {
public:
vector<int>dp = vector<int>(1001, -1);
int solve(int n){
if(n == 1)
return 0;
if(dp[n] != -1)
return dp[n];
else{
for(int i=1; i*i <= n; i++){
if(n % i == 0){
if(solve(n - i) == 0)
return dp[n] = 1;
if((i != 1) && solve(n - (n/i)) == 0)
return dp[n] = 1;
}
}
return dp[n] = 0;
}
}
bool divisorGame(int n) {
return solve(n);
}
};
| 19.809524 | 57 | 0.34976 | [
"vector"
] |
355f178830a6735a798805e32f339686059a9786 | 294 | hpp | C++ | src/lproto.hpp | liubai01/Lua-Lab1-luacFormatter | 92887d0952993514a97a58a0e9072c417871bdf8 | [
"Apache-2.0"
] | 1 | 2021-12-17T05:10:59.000Z | 2021-12-17T05:10:59.000Z | src/lproto.hpp | liubai01/Lua-Lab1-luacFormatter | 92887d0952993514a97a58a0e9072c417871bdf8 | [
"Apache-2.0"
] | null | null | null | src/lproto.hpp | liubai01/Lua-Lab1-luacFormatter | 92887d0952993514a97a58a0e9072c417871bdf8 | [
"Apache-2.0"
] | null | null | null | #ifndef LPROTO_H // include guard
#define LPROTO_H
#include <vector>
#include "utils.hpp"
#include "lobject.hpp"
using namespace std;
class Proto {
public:
ProtoData ptdb;
// sub functions
vector<Proto> subprotos;
void print(string name="main", string prompt="");
};
#endif | 15.473684 | 53 | 0.690476 | [
"vector"
] |
3561271d1037bf933999e18d05012b61f26a5f55 | 3,848 | cpp | C++ | src/RunVisitor.cpp | kstemp/jsc | a0a992a0d443560449f332c16bf14b17cf83009f | [
"MIT"
] | null | null | null | src/RunVisitor.cpp | kstemp/jsc | a0a992a0d443560449f332c16bf14b17cf83009f | [
"MIT"
] | null | null | null | src/RunVisitor.cpp | kstemp/jsc | a0a992a0d443560449f332c16bf14b17cf83009f | [
"MIT"
] | null | null | null | /*
jScript
copyright (C) 2019 K. Stempinski
@filename: Visitor.cpp
@description: Visitor pattern implementation.
*/
#include "RunVisitor.h"
void RunVisitor::visit(ValueNode& valueNode){
result = valueNode._value;
}
void RunVisitor::visit(UnaryNode& unaryNode){
unaryNode.arg->accept(this);
result = unaryNode.function(result);
}
void RunVisitor::visit(VariableNode& variableNode){
Scope& s = scopes[scopes.size() - 1 - variableNode.up];
auto varit = s.variables.find(variableNode.varName);
if (varit != s.variables.end()){
//Console::writeLn("VariableNode: found variable '" + varName + "' = " + std::to_string(it->second->Int()) + " in scope '" + s->name + "' (we are in scope '" + currentScope->name + "')", Color::Yellow);
variableNode.var = &varit->second;
result = varit->second;
return;
}
// Variable was not found in any enclosing scope
throw Exception("variable '" + variableNode.varName + "' does not exist", -69);
}
void RunVisitor::visit(BinOpNode& binOpNode){
binOpNode.arg1->accept(this);
const Variable res1 = result;
binOpNode.arg2->accept(this);
const Variable res2 = result;
result = binOpNode.function(res1, res2);
}
void RunVisitor::visit(VarAssignNode& varAssignNode){
varAssignNode.arg1->accept(this);
varAssignNode.arg2->accept(this);
// we assign the evaluated node both to the Variable in question,
// and this node. This allows us to have c = a = 56, for instance.
*static_cast<VariableNode*>(varAssignNode.arg1)->var = result;
}
void RunVisitor::visit(WhileNode& whileNode){
while (true) {
whileNode.expr->accept(this);
if (result.getData<int>()) {
scopes.emplace_back(Scope());
Variable temp;//TODO figure out a better method
bool caught = false;
try {
for (const auto& jt : whileNode.body)
jt->accept(this);
}
catch (Variable var) {
caught = true;
temp = var;
}
scopes.pop_back();
if (caught)
throw temp;
}
else break;
}
}
void RunVisitor::visit(FunctionNode& functionNode){
//TODO maybe we should have a derived GlobalScope : Scope instead...?
if (scopes.back().name != "global")
throw Exception("functions may only be declared in top-level (i.e. global) scope");
methods[functionNode.name] = &functionNode;
}
void RunVisitor::visit(FuncCallNode& funcCallNode){
auto it = methods.find(funcCallNode.name);
Console::writeDebug("calling func " + funcCallNode.name);
if (it == methods.end())
throw Exception("method '" + funcCallNode.name + "' does not exist", -69);
if (it->second->parameters.size() != funcCallNode.arguments.size())
throw Exception("invalid number: " + std::to_string(funcCallNode.arguments.size()) + " of arguments for function '" + funcCallNode.name + "' (expected " + std::to_string(it->second->parameters.size()) + ")", -69);
std::vector<Variable> results;
for (size_t i = 0; i < funcCallNode.arguments.size(); ++i){
funcCallNode.arguments[i]->accept(this);
results.push_back(result);
}
scopes.emplace_back(Scope(it->first));
for (size_t i = 0; i < funcCallNode.arguments.size(); ++i)
scopes.back().variables[it->second->parameters[i]] = results[i];
try{
for (auto& jt : it->second->body)
jt->accept(this);
}
catch (Variable var){
//TODO val or ref???
result = var;
}
scopes.pop_back();
}
void RunVisitor::visit(ReturnNode& returnNode){
returnNode.expr->accept(this);
throw result;
}
void RunVisitor::visit(VarDeclNode& varDeclNode){
if (scopes.back().variables.count(varDeclNode.varName))
throw Exception("variable '" + varDeclNode.varName + "' has already been declared in this scope");
if (varDeclNode.valueExpr != nullptr){
varDeclNode.valueExpr->accept(this);
scopes.back().variables[varDeclNode.varName] = result;
}
else
scopes.back().variables[varDeclNode.varName] = Variable();
}
| 22.769231 | 215 | 0.683992 | [
"vector"
] |
3563642990571a6b4184b3e4dae3945fded489b4 | 1,001 | cc | C++ | chapter4/4-5.cc | HelloCodeMing/TMP | 49573215d1c88eadda8273499b31c3b184a64d0f | [
"MIT"
] | 1 | 2017-09-02T03:03:43.000Z | 2017-09-02T03:03:43.000Z | chapter4/4-5.cc | HelloCodeMing/TMP | 49573215d1c88eadda8273499b31c3b184a64d0f | [
"MIT"
] | null | null | null | chapter4/4-5.cc | HelloCodeMing/TMP | 49573215d1c88eadda8273499b31c3b184a64d0f | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
#include <iostream>
#include "common-header.hpp"
template <class Container>
struct iterator_type
: mpl::if_<
std::is_const<Container>,
typename Container::const_iterator,
typename Container::iterator> {
};
static_assert(std::is_same<
iterator_type<const std::vector<int> >::type,
std::vector<int>::const_iterator
>::value, "const iterator");
static_assert(std::is_same<
iterator_type<std::vector<int> >::type,
std::vector<int>::iterator
>::value, "iterator");
template <class Container, class value_type>
typename iterator_type<Container>::type
container_find(Container& c, const value_type& v) {
return std::find(c.begin(), c.end(), v);
}
int main()
{
std::vector<int> vec = {1, 2, 3};
container_find(vec, 1);
const std::vector<int> vec_const = {1, 2, 3};
container_find(vec_const, 1);
return 0;
}
| 25.025 | 61 | 0.612388 | [
"vector"
] |
8313900f6bd59e09a733ce0603e03f5670c6f4f5 | 4,777 | cpp | C++ | src/kfusion/imgproc.cpp | LuyaooChen/sobfu | 688e06a2e81fdf30bd2d019516dc025a951bcbc2 | [
"BSD-3-Clause"
] | 142 | 2019-01-10T14:38:03.000Z | 2022-03-18T08:45:30.000Z | src/kfusion/imgproc.cpp | GucciPrada/sobfu | c83646582a146a3f4b8d8ad62de31ec60f8004d6 | [
"BSD-3-Clause"
] | 17 | 2019-01-18T05:15:33.000Z | 2021-12-22T15:00:44.000Z | src/kfusion/imgproc.cpp | GucciPrada/sobfu | c83646582a146a3f4b8d8ad62de31ec60f8004d6 | [
"BSD-3-Clause"
] | 27 | 2019-02-16T10:11:49.000Z | 2021-11-02T19:51:28.000Z | #include <kfusion/precomp.hpp>
void kfusion::cuda::depthBilateralFilter(const Depth &in, Depth &out, int kernel_size, float sigma_spatial,
float sigma_depth) {
out.create(in.rows(), in.cols());
device::bilateralFilter(in, out, kernel_size, sigma_spatial, sigma_depth);
}
void kfusion::cuda::depthTruncation(Depth &depth, float threshold) { device::truncateDepth(depth, threshold); }
void kfusion::cuda::depthBuildPyramid(const Depth &depth, Depth &pyramid, float sigma_depth) {
pyramid.create(depth.rows() / 2, depth.cols() / 2);
device::depthPyr(depth, pyramid, sigma_depth);
}
void kfusion::cuda::waitAllDefaultStream() { cudaSafeCall(cudaDeviceSynchronize()); }
void kfusion::cuda::computeNormalsAndMaskDepth(const Intr &intr, Depth &depth, Normals &normals) {
normals.create(depth.rows(), depth.cols());
device::Reprojector reproj(intr.fx, intr.fy, intr.cx, intr.cy);
device::Normals &n = (device::Normals &) normals;
device::computeNormalsAndMaskDepth(reproj, depth, n);
}
void kfusion::cuda::computePointNormals(const Intr &intr, const Depth &depth, Cloud &points, Normals &normals) {
points.create(depth.rows(), depth.cols());
normals.create(depth.rows(), depth.cols());
device::Reprojector reproj(intr.fx, intr.fy, intr.cx, intr.cy);
device::Points &p = (device::Points &) points;
device::Normals &n = (device::Normals &) normals;
device::computePointNormals(reproj, depth, p, n);
}
void kfusion::cuda::computeDists(const Depth &depth, Dists &dists, const Intr &intr) {
dists.create(depth.rows(), depth.cols());
device::compute_dists(depth, dists, make_float2(intr.fx, intr.fy), make_float2(intr.cx, intr.cy));
}
void kfusion::cuda::resizeDepthNormals(const Depth &depth, const Normals &normals, Depth &depth_out,
Normals &normals_out) {
depth_out.create(depth.rows() / 2, depth.cols() / 2);
normals_out.create(normals.rows() / 2, normals.cols() / 2);
device::Normals &nsrc = (device::Normals &) normals;
device::Normals &ndst = (device::Normals &) normals_out;
device::resizeDepthNormals(depth, nsrc, depth_out, ndst);
}
void kfusion::cuda::resizePointsNormals(const Cloud &points, const Normals &normals, Cloud &points_out,
Normals &normals_out) {
points_out.create(points.rows() / 2, points.cols() / 2);
normals_out.create(normals.rows() / 2, normals.cols() / 2);
device::Points &pi = (device::Points &) points;
device::Normals &ni = (device::Normals &) normals;
device::Points &po = (device::Points &) points_out;
device::Normals &no = (device::Normals &) normals_out;
device::resizePointsNormals(pi, ni, po, no);
}
void kfusion::cuda::rasteriseSurface(const Intr &intr, const Affine3f &vol2cam, const Surface &s, Cloud &vertices_out,
Normals &normals_out) {
device::Projector proj(intr.fx, intr.fy, intr.cx, intr.cy);
device::Aff3f dev_vol2cam = device_cast<device::Aff3f>(vol2cam);
/* convert warped triangle vertices & normals to point clouds */
pcl::PointCloud<pcl::PointXYZ> vertices_warped;
s.vertices.download(vertices_warped.points);
pcl::PointCloud<pcl::Normal> normals_warped;
s.normals.download(normals_warped.points);
/* lay out the warped triangle vertices and normals in memory */
std::vector<pcl::PointXYZ>
triangle_vertices; /* the index of each entry in the vector, modulo 3, stores the 1st, 2nd, and 3rd vertex of a
triangle */
std::vector<pcl::Normal> triangle_normals;
for (size_t i = 0; i < vertices_warped.size() / 3; i++) {
triangle_vertices.emplace_back(vertices_warped[i * 3 + 0]);
triangle_vertices.emplace_back(vertices_warped[i * 3 + 1]);
triangle_vertices.emplace_back(vertices_warped[i * 3 + 2]);
triangle_normals.emplace_back(normals_warped[i * 3 + 0]);
triangle_normals.emplace_back(normals_warped[i * 3 + 1]);
triangle_normals.emplace_back(normals_warped[i * 3 + 2]);
}
kfusion::cuda::Vertices vertices;
vertices.upload(triangle_vertices);
kfusion::cuda::Norms normals;
normals.upload(triangle_normals);
kfusion::cuda::Surface surface;
surface.vertices = vertices;
surface.normals = normals;
/* convert to classes that can be used in cuda */
const device::Surface &dev_surface = (const device::Surface &) surface;
device::Points &vo = (device::Points &) vertices_out;
device::Normals &no = (device::Normals &) normals_out;
device::rasteriseSurface(proj, dev_vol2cam, dev_surface, vo, no);
waitAllDefaultStream();
}
| 42.274336 | 119 | 0.667783 | [
"vector"
] |
831fc2691424d1b4bc6ede9e4ca309f76703e3f1 | 97 | cpp | C++ | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/QtAutogen/MocDepends/testATDTarget.cpp | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 107 | 2021-08-28T20:08:42.000Z | 2022-03-22T08:02:16.000Z | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/QtAutogen/MocDepends/testATDTarget.cpp | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 3 | 2021-09-08T02:18:00.000Z | 2022-03-12T00:39:44.000Z | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/QtAutogen/MocDepends/testATDTarget.cpp | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 16 | 2021-08-30T06:57:36.000Z | 2022-03-22T08:05:52.000Z |
#include "ATDTarget.hpp"
#include "moc_ATDTarget.cpp"
int main()
{
Object obj;
return 0;
}
| 9.7 | 28 | 0.670103 | [
"object"
] |
831fd4383ba9f689b875d2f25a62e7b4d37738d7 | 1,447 | hh | C++ | libsrc/spatialdata/geocoords/CSPicklerAscii.hh | rwalkerlewis/spatialdata | 515c8d9dec21d261d0d654b5c30e6759565268d2 | [
"MIT"
] | 6 | 2017-09-19T11:05:33.000Z | 2019-09-26T08:18:30.000Z | libsrc/spatialdata/geocoords/CSPicklerAscii.hh | rwalkerlewis/spatialdata | 515c8d9dec21d261d0d654b5c30e6759565268d2 | [
"MIT"
] | 38 | 2017-06-28T15:44:50.000Z | 2022-02-17T04:04:02.000Z | libsrc/spatialdata/geocoords/CSPicklerAscii.hh | rwalkerlewis/spatialdata | 515c8d9dec21d261d0d654b5c30e6759565268d2 | [
"MIT"
] | 11 | 2015-11-09T06:29:35.000Z | 2021-06-02T14:13:59.000Z | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
/** @file libsrc/geocoords/CSPicklerAscii.hh
*
* @brief C++ CSPicklerAscii object
*
* C++ object for pickling/unpickling coordinate systems for ascii streams.
*/
#if !defined(spatialdata_geocoords_cspicklerascii_hh)
#define spatialdata_geocoords_cspicklerascii_hh
#include "geocoordsfwd.hh"
#include <iosfwd> // USES std::istream, std::ostream
class spatialdata::geocoords::CSPicklerAscii {
public:
// PUBLIC METHODS /////////////////////////////////////////////////////
/** Pickle coordinate system.
*
* @param s Ouput stream
* @param cs Pointer to coordinate system
*/
static
void pickle(std::ostream& s,
const CoordSys* cs);
/** Unpickle coordinate system.
*
* @param s Input stream
* @param cs Pointer to pointer to coordinate system
*/
static
void unpickle(std::istream& s,
CoordSys** cs);
}; // class CSPicklerAscii
#endif // spatialdata_geocoords_cspicklerascii_hh
// End of file
| 24.525424 | 75 | 0.575674 | [
"object"
] |
8328cd929d80a7333b57962949c5dab3973ad3a7 | 4,609 | cpp | C++ | CP/Assign1/LCS/src/LCS.cpp | abilng/MTech-Assignments | edb7a468eef6d8364551e8b6c04acf7c79831138 | [
"MIT"
] | 1 | 2016-03-01T10:42:57.000Z | 2016-03-01T10:42:57.000Z | CP/Assign1/LCS/src/LCS.cpp | abilng/MTech-Assignments | edb7a468eef6d8364551e8b6c04acf7c79831138 | [
"MIT"
] | null | null | null | CP/Assign1/LCS/src/LCS.cpp | abilng/MTech-Assignments | edb7a468eef6d8364551e8b6c04acf7c79831138 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cilk/cilk.h>
#define TOP 1
#define LEFT 2
#define DIAG 3
#define BLOCKSIZE 16
using namespace std;
void printMatrix(int *,int,int );
void LCS(int *,int *,const char *,const char * ,int,int);
string getLCS(int *,string,int,int,int,int);
inline string getLCS(int * B,string s,int length1,int length2);
void readInput(vector<string> &strVector1, vector<string> &strVector2);
void readInput(vector<string> &strVector1, vector<string> &strVector2)
{
string curStr;
string line ;
while(getline(std::cin, line))
{
if(line[0]=='>') {
//comment
continue;
} else if(line=="$$$") {
//EOF
break;
} else if(line=="$$") {
strVector2.push_back(curStr);
curStr = "";
} else if(line=="$") {
strVector1.push_back(curStr);
curStr = "";
} else {
curStr += line ;
}
}
}
void LCS(int * C,int * B,const char * s1,const char * s2 ,int length1,int length2)
{
if(length1==0||length2==0)
return;
int nBlock = length1/BLOCKSIZE;
int mBlock = length2/BLOCKSIZE;
if(mBlock<1) mBlock = 1;
if(nBlock<1) nBlock = 1;
for (int slice = 0; slice < nBlock + mBlock - 1; ++slice) {
// printf("Slice %d: \n", slice);
int z1 = slice < mBlock ? 0 : slice - mBlock + 1;
int z2 = slice < nBlock ? 0 : slice - nBlock + 1;
cilk_for (int k = slice - z2; k >= z1; --k) {
int starti,endi,startj,endj;
starti = k*BLOCKSIZE;
startj = (slice - k)*BLOCKSIZE;
endi = (k+1)*BLOCKSIZE;
endj = (slice - k+1)*BLOCKSIZE;
if(starti==0) starti=1;
if(startj==0) startj=1;
if(endi+BLOCKSIZE>length1) endi=length1;
if(endj+BLOCKSIZE>length2) endj=length2;
//cout<< starti<<"->"<<endi<<" "<<startj<<"->"<<endj<<endl;
for(int i=starti; i<endi;i++) {
for(int j=startj; j<endj;j++) {
if(s1[i-1] == s2[j-1])
{
C[i*length2+j] = C[(i-1)*length2+(j-1)] + 1;
B[i*length2+j] = DIAG;
}
else if(C[(i-1)*length2+j]>= C[i*length2+(j-1)])
{
C[i*length2+j] = C[(i-1)*length2+j];
B[i*length2+j] = TOP;
}
else
{
C[i*length2+j] = C[i*length2+(j-1)];
B[i*length2+j] = LEFT;
}
#ifdef DEBUG
cout<<i<<j<<" "<<i*length2+j<<" ["<<s1[j-1]<<s2[i-1]<<"]"<<endl;
printMatrix(C,length1,length2);
cout<<endl;
#endif
}
}
}
}
}
string getLCS(int * B,string s,int i,int j,int length1,int length2)
{
if(i == 0 || j == 0)
return "";
if(B[i*length2+j]== DIAG)
return getLCS(B,s,i-1,j-1,length1,length2)+s[i-1];
else if(B[i*length2+j]== LEFT)
return getLCS(B,s,i,j-1,length1,length2);
else
return getLCS(B,s,i-1,j,length1,length2);
}
inline string getLCS(int * B,string s,int length1,int length2)
{
return getLCS(B,s,length1-1,length2-1,length1,length2);
}
void printMatrix(int *A,int n,int m)
{
cout<<n<<"-- "<<m<<endl;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cout << A[i*m+j]<< " ";
}
cout << endl;
}
}
int main()
{
int **l,**b;
int * strlen1;
int * strlen2;
int * matchlen;
string * matchStr;
vector<string> strVector1;
vector<string> strVector2;
readInput(strVector1,strVector2);
l = new int*[strVector1.size()];
b = new int*[strVector1.size()];
strlen1 = new int[strVector1.size()];
strlen2 = new int[strVector1.size()];
matchlen = new int[strVector1.size()];
matchStr = new string[strVector1.size()];
for(int i=0;i<strVector1.size();i++)
{
strlen1[i] = strVector1[i].length()+1;
strlen2[i] = strVector2[i].length()+1;
}
for(int i=0;i<strVector1.size();i++)
{
l[i] = (int*) calloc(strlen1[i]*strlen2[i], sizeof(int));
b[i] = (int*) calloc(strlen1[i]*strlen2[i], sizeof(int));
if(l[i]==NULL || b[i]==NULL)
{
cerr<<"Memory Allocation Failed"<<endl;
return -1;
}
}
cilk_for(int i=0;i<strVector1.size();i++)
{
int n = strlen1[i];
int m= strlen2[i];
LCS(l[i],b[i],strVector1[i].c_str(),
strVector2[i].c_str(),n,m);
#ifdef DEBUG
printMatrix(l,str1len,str2len);
cout<<endl;
#endif
matchlen[i] = l[i][n*m-1];
matchStr[i] = getLCS(b[i],strVector1[i],n,m);
}
for(int i=0;i<strVector1.size();i++)
{
cout<<matchlen[i]<<" "<<matchStr[i]<<endl;
}
for(int i=0;i<strVector1.size();i++)
{
free(l[i]);
free(b[i]);
}
delete []l;
delete []b;
delete []strlen1;
delete []strlen2;
delete []matchStr;
delete []matchlen;
return 0;
}
| 20.393805 | 82 | 0.55934 | [
"vector"
] |
832912e20be637e883c8f96ec9e4834773d0d473 | 2,042 | hpp | C++ | include/Proxy.hpp | fixstars/cRTOS-loader | d3da5738d2511b497a56d320eafe1f3dc628347b | [
"Apache-2.0"
] | null | null | null | include/Proxy.hpp | fixstars/cRTOS-loader | d3da5738d2511b497a56d320eafe1f3dc628347b | [
"Apache-2.0"
] | null | null | null | include/Proxy.hpp | fixstars/cRTOS-loader | d3da5738d2511b497a56d320eafe1f3dc628347b | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 Yang, Chung-Fan @ Fixstars corporation
* <chungfan.yang@fixstars.com>
* 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 <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <thread>
#include <list>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "MMAP.hpp"
#include "IO.hpp"
#ifndef __PROXY_HPP__
#define __PROXY_HPP__
class Proxy;
struct thread_s {
pthread_t tid;
Proxy* tproxy;
int tpip[2];
};
class Proxy {
public:
Proxy(IO &io, std::string shadow, bool verbose);
virtual ~Proxy();
void rexec(std::string &path,
std::vector<std::string> &argv,
std::vector<std::string> &envp);
void run();
void send_remote_signal(int signo);
uint64_t get_slot_num() { return slot_num; };
void _self_init();
void self_init();
void init_sched();
void init_signal_handling();
protected:
private:
bool is_main;
IO &io;
MMAP *kernel_memory;
std::string shadow;
size_t shadow_size;
int fd;
uint64_t slot_num;
std::list<struct thread_s*> threads;
std::list<MMAP*> mappings;
int priority;
int policy;
bool verbose;
};
#endif // __PROXY_HPP__
| 22.688889 | 75 | 0.631734 | [
"vector"
] |
833beb2bd6ef6ed2b3dd3ec835d9b1d914054ecc | 162 | cpp | C++ | src/DotNet/QuickFASTDotNetPch.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 198 | 2015-04-26T08:06:18.000Z | 2022-03-13T01:31:50.000Z | src/DotNet/QuickFASTDotNetPch.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 15 | 2015-07-07T19:47:08.000Z | 2022-02-04T05:56:51.000Z | src/DotNet/QuickFASTDotNetPch.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 96 | 2015-04-24T15:19:43.000Z | 2022-03-28T13:15:11.000Z | // Copyright (c) 2009, 2010 Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#include "QuickFASTDotNetPch.h"
| 32.4 | 54 | 0.753086 | [
"object"
] |
834275c41e0cb858f6689d328aff6ff3f909a8c4 | 3,480 | cpp | C++ | Cramers_rule/Cpp/Cramer/Cramer/cramer.cpp | ncoe/rosetta | 15c2302a247dfbcea694ff095238a525c60226d4 | [
"MIT"
] | 3 | 2018-02-26T18:12:31.000Z | 2019-08-26T06:47:30.000Z | Cramers_rule/Cpp/Cramer/Cramer/cramer.cpp | ncoe/rosetta | 15c2302a247dfbcea694ff095238a525c60226d4 | [
"MIT"
] | null | null | null | Cramers_rule/Cpp/Cramer/Cramer/cramer.cpp | ncoe/rosetta | 15c2302a247dfbcea694ff095238a525c60226d4 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
class SubMatrix {
const std::vector<std::vector<double>> *source;
std::vector<double> replaceColumn;
const SubMatrix *prev;
size_t sz;
int colIndex = -1;
public:
SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) {
sz = replaceColumn.size();
}
SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) {
sz = p.size() - 1;
}
SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) {
sz = p.size() - 1;
}
int columnIndex() const {
return colIndex;
}
void columnIndex(int index) {
colIndex = index;
}
size_t size() const {
return sz;
}
double index(int row, int col) const {
if (source != nullptr) {
if (col == colIndex) {
return replaceColumn[row];
} else {
return (*source)[row][col];
}
} else {
if (col < colIndex) {
return prev->index(row + 1, col);
} else {
return prev->index(row + 1, col + 1);
}
}
}
double det() const {
if (sz == 1) {
return index(0, 0);
}
if (sz == 2) {
return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0);
}
SubMatrix m(*this);
double det = 0.0;
int sign = 1;
for (size_t c = 0; c < sz; ++c) {
m.columnIndex(c);
double d = m.det();
det += index(0, c) * d * sign;
sign = -sign;
}
return det;
}
};
std::vector<double> solve(SubMatrix &matrix) {
double det = matrix.det();
if (det == 0.0) {
throw new std::runtime_error("The determinant is zero.");
}
std::vector<double> answer(matrix.size());
for (int i = 0; i < matrix.size(); ++i) {
matrix.columnIndex(i);
answer[i] = matrix.det() / det;
}
return answer;
}
std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) {
int size = equations.size();
if (std::any_of(
equations.cbegin(), equations.cend(),
[size](const std::vector<double> &a) { return a.size() != size + 1; }
)) {
throw new std::runtime_error("Each equation must have the expected size.");
}
std::vector<std::vector<double>> matrix(size);
std::vector<double> column(size);
for (int r = 0; r < size; ++r) {
column[r] = equations[r][size];
matrix[r].resize(size);
for (int c = 0; c < size; ++c) {
matrix[r][c] = equations[r][c];
}
}
SubMatrix sm(matrix, column);
return solve(sm);
}
template<typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it++;
}
while (it != end) {
os << ", " << *it++;
}
return os << ']';
}
int main() {
std::vector<std::vector<double>> equations = {
{ 2, -1, 5, 1, -3},
{ 3, 2, 2, -6, -32},
{ 1, 3, 3, -1, -47},
{ 5, -2, -3, 3, 49},
};
auto solution = solveCramer(equations);
std::cout << solution << '\n';
return 0;
}
| 25.217391 | 154 | 0.496552 | [
"vector"
] |
834932a4293159349fc71c853a9b1560762c9613 | 30,160 | cpp | C++ | src/Main/NRG_main_bkup.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | 3 | 2015-09-21T20:58:45.000Z | 2019-03-20T01:21:41.000Z | src/Main/NRG_main_bkup.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | null | null | null | src/Main/NRG_main_bkup.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <vector>
#include <cmath>
#include <cstring>
#include <unistd.h>
#include "NRGclasses.hpp"
#include "NRGfunctions.hpp"
#include "NRGOpMatRules.hpp"
#include "NRG_main.hpp"
#include "TwoChQS.hpp"
#ifndef pi
#define pi 3.141592653589793238462643383279502884197169
#endif
#ifndef _CHIN_
#define _CHIN_
double chiN(int Nsites, double Lambda)
{
double daux[3];
daux[0]=1.0-pow( Lambda,-((double)(Nsites)+1.0) );
daux[1]=sqrt( 1.0-pow(Lambda,-(2.0*(double)(Nsites)+1.0)) );
daux[2]=sqrt( 1.0-pow(Lambda,-(2.0*(double)(Nsites)+3.0)) );
return(daux[0]/(daux[1]*daux[2]));
}
#endif
int main (int argc, char* argv[]){
// Parameters for command-line passing (GetOpt)
CNRGCodeHandler ThisCode;
// char ModelOption[]="Anderson";
// int ModelNo=5;
// Read Model, etc. (not now)
#include"ModelOptMain.cpp"
strcpy(ThisCode.Symmetry,ModelSymmetry);
strcpy(ThisCode.ModelOption,ModelOption);
ThisCode.ModelNo=ModelNo;
ThisCode.SymNo=SymNo;
ThisCode.SaveData=false;
// NRG objects
CNRGarray Aeig;
CNRGbasisarray AeigCut;
CNRGbasisarray Abasis;
CNRGbasisarray SingleSite;
// STL vector
CNRGmatrix HN;
CNRGmatrix Qm1fNQ;
//CNRGmatrix MQQp1;
CNRGmatrix* MatArray;
int NumNRGarrays=4;
// Jul 09: Will this work???
vector<CNRGmatrix> STLMatArray;
CNRGmatrix auxNRGMat;
// MatArray 0 is f_ch1
// MatArray 1 is f_ch2
// MatArray 2 is Sz
// MatArray 3 is Sz2
// STL vectors
vector <double> Params;
vector <double> ParamsHN;
vector <double> ParamsBetabar;
vector<int> CommonQNs;
vector<int> totSpos;
// Integers
//int Nsites;
// Thermodynamics
CNRGthermo Suscep;
CNRGthermo Entropy;
CNRGthermo *ThermoArray;
int NumThermoArrays=2;
double TM=0.0;
//double DN=0.0;
//double betabar=0.727;
ThisCode.Nsites=0;
ThisCode.betabar=0.727;
// instream
ifstream InFile;
// outstream
ofstream OutFile;
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////
/// ///
/// Main code ///
/// ///
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////
// Read stuff (separate routine)
// Allocate MatArray (hope this works!)
// Yes, but, for some reason, needs to be BEFORE everything!
MatArray = new CNRGmatrix [NumNRGarrays];
ThermoArray = new CNRGthermo [NumThermoArrays];
for (int imat=0;imat<NumNRGarrays;imat++){STLMatArray.push_back(auxNRGMat);}
ThisCode.Nsites0=0;
ThisCode.NumChannels=1;
ThisCode.NumNRGmats=NumNRGarrays;
ThisCode.NumThermoMats=NumThermoArrays;
ThisCode.InitialSetUp();
//InFile.open("input_nrg.dat"); // Needs this here is I
// new MatArray after!! Why????
ThisCode.SetSingleSite(&SingleSite);
// Copy pointers for saving/reading.
ThisCode.pAbasis=&Abasis;
//ThisCode.MatArray=MatArray;
ThisCode.MatArray=&STLMatArray[0];
ThisCode.pAcut=&AeigCut;
// Set H0
// HN.SetH0(Params,&SingleSite,&Aeig,&Abasis,MatArray);
//(vector<double> Params,CNRGbasisarray* pSingleSite,CNRGarray* pAeig,CNRGbasisarray* pAbasisH0,CNRGmatrix* NRGMats)
// Set initial Aeig and matrices (such as Qm1fNQ[])/Operators
// - Model dependent functions (hardest part)
// - Set quantum numbers, etc,etc,
// - HN. will
// Thermobasics
strcpy(ThermoArray[0].ArqName,"SuscepImp_Main.dat");
strcpy(ThermoArray[0].ChainArqName,"SuscepChain2Ch.dat");
ThermoArray[0].Calc=CalcSuscep;
strcpy(ThermoArray[1].ArqName,"EntropyImp_Main.dat");
strcpy(ThermoArray[1].ChainArqName,"EntropyChain2Ch.dat");
ThermoArray[1].Calc=CalcEntropy;
for (int ithermo=0;ithermo<NumThermoArrays;ithermo++){
if (ThisCode.calcdens==3)
ThermoArray[ithermo].CalcChain=true;
else
ThermoArray[ithermo].CalcChain=false;
}
// HN basics
HN.NeedOld=false;
HN.UpperTriangular=true;
HN.CheckForMatEl=Diag_check;
/// For all codes
double Gamma=0.0282691;
double Lambda=2.5;
if (ThisCode.dInitParams.size()>1)
Gamma=ThisCode.dInitParams[1];
if (ThisCode.Lambda>0.0)
Lambda=ThisCode.Lambda;
double HalfLambdaFactor=0.5*(1.0+(1.0/Lambda));
double chi_m1=sqrt(2.0*Gamma/pi)/(sqrt(Lambda)*HalfLambdaFactor);
// Jul 09: NRG chain
CNRGchain chain1(ThisCode.Lambda,ThisCode.Nsitesmax);
// Sep 08: 1ChQ chain calculations diverted to Anderson (ModelNo=0)
// Aug 09: Why?? Is this correct?
if ( (ThisCode.ModelNo==3)&&(ThisCode.SymNo==3) ){
ThisCode.ZeroParams();
ThisCode.ModelNo=0;
}
///////////////////////////////////
//// Model specific hamiltonians ///
///////////////////////////////////
switch(ThisCode.ModelNo){
case 0: // Anderson
switch(ThisCode.SymNo){
case 2: // Anderson model: OneChQSz
// Initialize matrices (OneChQ routines work here!)
// Jul 09: using STMatArray
STLMatArray[0].NeedOld=false;
STLMatArray[0].CheckForMatEl=OneChQ_cd_check;
STLMatArray[0].CalcMatEl=OneChQ_fNup_MatEl;
STLMatArray[0].SaveMatYN=false;
STLMatArray[1].NeedOld=false;
STLMatArray[1].CheckForMatEl=OneChQ_cd_check;
STLMatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;
STLMatArray[1].SaveMatYN=false;
// Param for H0
Params.push_back(ThisCode.dInitParams[0]); // U
Params.push_back(ThisCode.dInitParams[2]); // ed
Params.push_back(Lambda);
Params.push_back(HalfLambdaFactor);
Params.push_back(ThisCode.dInitParams[3]); // Mag Field
//OneChQSz_SetAnderson_Hm1(Params,&Aeig,MatArray);
OneChQSz_SetAnderson_Hm1(Params,&Aeig,STLMatArray);
// cd_up and cd_dn (OneChQSz_SetAnderson equals
// MatArray[2,3] to MatArray[0,1]
STLMatArray[2].NeedOld=true;
STLMatArray[2].CheckForMatEl=OneChQSz_cdup_check;
STLMatArray[2].CalcMatEl=OneChQSz_cdup_MatEl;
STLMatArray[2].SaveMatYN=true;
STLMatArray[3].NeedOld=true;
STLMatArray[3].CheckForMatEl=OneChQSz_cddn_check;
STLMatArray[3].CalcMatEl=OneChQSz_cddn_MatEl;
STLMatArray[3].SaveMatYN=true;
cout << " N = -1" << endl;
// cout << " fN_up : " << endl;
// MatArray[0].PrintAllBlocks();
// cout << " fN_dn : " << endl;
// MatArray[1].PrintAllBlocks();
cout << " cdN_up : " << endl;
STLMatArray[2].PrintAllBlocks();
cout << " cdN_dn : " << endl;
STLMatArray[3].PrintAllBlocks();
////////////////////////
// BuildBasis params
CommonQNs.push_back(2); // No of common QNs
CommonQNs.push_back(0); // pos of QN 1 in old
CommonQNs.push_back(1); // pos of QN 2 in old
CommonQNs.push_back(0); // pos of QN 1 in SingleSite
CommonQNs.push_back(1); // pos of QN 1 in SingleSite
// No total S variables. Leave totSpos empty
HN.CalcHNMatEl=OneChQSz_HN_MatEl;
ThisCode.NumChannels=1;
ThisCode.Nsites0=0;
//ThisCode.NumNRGmats=4;//2
ThisCode.NumNRGmats=STLMatArray.size();
ThisCode.MatArray=&STLMatArray[0]; // Need to do this after
// changes in STLMatArray!
ThisCode.SaveData=true;
break;
case 3: // Anderson model: OneChQ
// OLD!!
// MatArray[0].NeedOld=false;
// MatArray[0].CheckForMatEl=OneChQ_cd_check;
// MatArray[0].CalcMatEl=OneChQ_fNup_MatEl;
// MatArray[1].NeedOld=false;
// MatArray[1].CheckForMatEl=OneChQ_cd_check;
// MatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;
// // Sz and Sz2
// MatArray[2].NeedOld=true;
// MatArray[2].UpperTriangular=false;
// MatArray[2].CheckForMatEl=Diag_check;
// MatArray[2].CalcMatEl=ImpOnly_MatEl;
// MatArray[3].NeedOld=true;
// MatArray[3].UpperTriangular=false;
// MatArray[3].CheckForMatEl=Diag_check;
// MatArray[3].CalcMatEl=ImpOnly_MatEl;
// Initialize matrices (uncomment later)
STLMatArray[0].NeedOld=false;
STLMatArray[0].CheckForMatEl=OneChQ_cd_check;
STLMatArray[0].CalcMatEl=OneChQ_fNup_MatEl;
STLMatArray[1].NeedOld=false;
STLMatArray[1].CheckForMatEl=OneChQ_cd_check;
STLMatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;
// Sz and Sz2
STLMatArray[2].NeedOld=true;
STLMatArray[2].UpperTriangular=false;
STLMatArray[2].CalcAvg=true; // CalcAvg
STLMatArray[2].CheckForMatEl=Diag_check;
STLMatArray[2].CalcMatEl=ImpOnly_MatEl;
strcpy(STLMatArray[2].MatName,"Sz");
STLMatArray[3].NeedOld=true;
STLMatArray[3].UpperTriangular=false;
STLMatArray[3].CalcAvg=true; // CalcAvg
STLMatArray[3].CheckForMatEl=Diag_check;
STLMatArray[3].CalcMatEl=ImpOnly_MatEl;
strcpy(STLMatArray[3].MatName,"Sz2");
if (ThisCode.calcdens==1){
// All operators have the same Checks/MatEls in |Q> basis
// what changes is the initial set-up
auxNRGMat.NeedOld=true;
auxNRGMat.UpperTriangular=false;
auxNRGMat.CheckForMatEl=OneChQ_cd_check;
auxNRGMat.CalcMatEl=OneChQ_cd_MatEl;
auxNRGMat.SaveMatYN=true;
STLMatArray.push_back(auxNRGMat); // 4 - cd1_up
STLMatArray.push_back(auxNRGMat); // 5 - cd1_dn
NumNRGarrays=STLMatArray.size();
ThisCode.NumNRGmats=NumNRGarrays;
ThisCode.MatArray=&STLMatArray[0]; //
// changes in STLMatArray!
ThisCode.SaveData=true;
strcpy(ThisCode.SaveArraysFileName,"1chQAnd");
}
else{
// Set Thermodynamics
// Entropy calculation only
strcpy(ThermoArray[0].ArqName,"EntropyImp1Ch_Anderson_Q.dat");
strcpy(ThermoArray[0].ChainArqName,"EntropyChain1Ch_Q.dat");
ThermoArray[0].Calc=CalcEntropy;
ThermoArray[0].dImpValue=2.0*log(2.0);
//ThermoArray[0].CalcChain=false;
ThisCode.NumThermoMats=1;
}
// calculate spec function or thermo?
// Param for H0
Params.push_back(ThisCode.dInitParams[0]); // U
Params.push_back(ThisCode.dInitParams[2]); // ed
Params.push_back(Lambda);
Params.push_back(HalfLambdaFactor);
OneChQ_SetAnderson_Hm1(Params,&Aeig,STLMatArray);
//OneChQ_SetAnderson_Hm1_old(Params,&Aeig,MatArray);
////////////////////////
// BuildBasis params
CommonQNs.push_back(1); // No of common QNs
CommonQNs.push_back(0); // pos of QN 1 in old
CommonQNs.push_back(0); // pos of QN 1 in SingleSite
// No total S variables. Leave totSpos empty
HN.CalcHNMatEl=OneChQ_HN_MatEl;
ThisCode.NumChannels=1;
ThisCode.Nsites0=0;
break;
default:
cout << " Symmetry " << ThisCode.Symmetry
<< " not implemented for " << ThisCode.ModelOption << endl;
exit(0);
}
break;
case 3: // Chain only
ThisCode.ZeroParams();
ThisCode.Nsites0=1;
ThisCode.NumThermoMats=2;
switch(ThisCode.SymNo){
case 0: // Chain model: OneChQS
// fN (reduced)
STLMatArray[0].NeedOld=false;
STLMatArray[0].UpperTriangular=false;
STLMatArray[0].CheckForMatEl=OneChQS_cd_check;
STLMatArray[0].CalcMatEl=OneChQS_fN_MatEl;
STLMatArray.pop_back(); // Only ONE array
STLMatArray.pop_back(); // Only ONE array
STLMatArray.pop_back(); // Only ONE array
// Set ChainH0: SingleSite is already set, just get Aeig and STLMatArray.
OneChQS_SetChainH0(&Aeig,STLMatArray);
ThisCode.NumNRGmats=STLMatArray.size();
ThisCode.MatArray=&STLMatArray[0]; // Need to do this after
ThisCode.SaveData=false;
// BuildBasis params
CommonQNs.push_back(2); // Q and S and commont QNs
CommonQNs.push_back(0); // position of Q in old basis
CommonQNs.push_back(1); // position of S in old basis
CommonQNs.push_back(0); // position of Q in SingleSite
CommonQNs.push_back(1); // position of S in SingleSite
totSpos.push_back(1); // SU(2) symmetry in position 1
// HN params
HN.CalcHNMatEl=OneChQS_HN_MatEl;
ThisCode.NumChannels=1;
chi_m1=chiN(0,Lambda); // is actually chi0
strcpy(ThermoArray[0].ChainArqName,"SuscepChain1Ch_QS.dat");
strcpy(ThermoArray[1].ChainArqName,"EntropyChain1Ch_QS.dat");
break;
// case 1: // Chain model: TwoChQS
// TwoChQS_SetChainH0(&Aeig,STLMatArray);
// break;
// case 2: // Chain model: OneChQSz
// OneChQSz_SetChainH0(&Aeig,STLMatArray);
// break;
// case 3: // Chain model: OneChQ
// OneChQ_SetChainH0(&Aeig,STLMatArray);
// break;
default:
cout << " Symmetry " << ThisCode.Symmetry
<< " not implemented for " << ThisCode.ModelOption << endl;
exit(0);
}
//cout << " Chain calculation still under implementation" << endl;
//exit(0);
break;
case 5: // SMM model, symmetry is OneChQ
// Params for H0
Params.push_back(Lambda); // Lambda
Params.push_back(HalfLambdaFactor); // Lambda factor
if (ThisCode.dInitParams.size()>10){
Params.push_back(ThisCode.dInitParams[0]); // U1
Params.push_back(ThisCode.dInitParams[2]); // ed1
Params.push_back(ThisCode.dInitParams[3]); // U2
Params.push_back(ThisCode.dInitParams[5]); // ed2
Params.push_back(ThisCode.dInitParams[6]); // J12
Params.push_back(ThisCode.dInitParams[7]); // BmagPar
Params.push_back(ThisCode.dInitParams[8]); // BmagPerp
Params.push_back(ThisCode.dInitParams[9]); // Dz
Params.push_back(ThisCode.dInitParams[10]); // B2 anisot
double chi2_m1=sqrt(2.0*ThisCode.dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);
Params.push_back(chi_m1); // gamma1
Params.push_back(chi2_m1); // gamma2
}
else{
double U=0.5;
double ed=-0.5*U;
Params.push_back(U); // U1
Params.push_back(ed); // ed1
Params.push_back(0.0); // U2
Params.push_back(0.0); // ed2
Params.push_back(0.0); // J12
Params.push_back(0.0); // BmagPar
Params.push_back(0.0); // BmagPerp
Params.push_back(0.0); // Dz
Params.push_back(0.0); // B2 anisot
Params.push_back(chi_m1); // gamma1
Params.push_back(0.0); // gamma2
}
// Set rules for MatArray
// Jul 09: using STMatArray
// fN_up
STLMatArray[0].NeedOld=false;
STLMatArray[0].CheckForMatEl=OneChQ_cd_check;
STLMatArray[0].CalcMatEl=OneChQ_fNup_MatEl;
// fN_dn
STLMatArray[1].NeedOld=false;
STLMatArray[1].CheckForMatEl=OneChQ_cd_check;
STLMatArray[1].CalcMatEl=OneChQ_fNdn_MatEl;
// Sz and Sz2
STLMatArray[2].NeedOld=true;
STLMatArray[2].UpperTriangular=false;
STLMatArray[2].CalcAvg=true; // CalcAvg
STLMatArray[2].CheckForMatEl=Diag_check;
STLMatArray[2].CalcMatEl=ImpOnly_MatEl;
strcpy(STLMatArray[2].MatName,"Sz");
STLMatArray[3].NeedOld=true;
STLMatArray[3].UpperTriangular=false;
STLMatArray[2].CalcAvg=true;
STLMatArray[3].CheckForMatEl=Diag_check;
STLMatArray[3].CalcMatEl=ImpOnly_MatEl;
strcpy(STLMatArray[3].MatName,"Sz2");
// cd1_up, cd1_dn, cd2_up, cd2_dn
// MatArray is an STL vector!!!
if (ThisCode.calcdens==1){
// All operators have the same Checks/MatEls in |Q> basis
// what changes is the initial set-up
auxNRGMat.NeedOld=true;
auxNRGMat.CheckForMatEl=OneChQ_cd_check;
auxNRGMat.CalcMatEl=OneChQ_cd_MatEl;
auxNRGMat.SaveMatYN=true;
STLMatArray.push_back(auxNRGMat); // 4 - cd1_up
STLMatArray.push_back(auxNRGMat); // 5 - cd1_dn
STLMatArray.push_back(auxNRGMat); // 6 - cd2_up
STLMatArray.push_back(auxNRGMat); // 7 - cd2_dn
NumNRGarrays=STLMatArray.size();
ThisCode.NumNRGmats=NumNRGarrays;
ThisCode.MatArray=&STLMatArray[0]; // Need to do this after
// changes in STLMatArray!
ThisCode.SaveData=true;
strcpy(ThisCode.SaveArraysFileName,"SMM");
}
else{
// Set Thermodynamics
// Entropy calculation only
strcpy(ThermoArray[0].ArqName,"EntropyImp1Ch_Anderson_Q.dat");
strcpy(ThermoArray[0].ChainArqName,"EntropyChain1Ch_Q.dat");
ThermoArray[0].Calc=CalcEntropy;
ThermoArray[0].dImpValue=4.0*log(2.0);
ThermoArray[0].CalcChain=false;
ThisCode.NumThermoMats=1;
}
// calculate spec function or thermo?
// Set H0: output pAeig, MatArray
OneChQ_SetSMM_H0(Params,&Aeig,&SingleSite,STLMatArray);
// BuildBasis params
CommonQNs.push_back(1); // No of common QNs
CommonQNs.push_back(0); // pos of QN 1 in old
CommonQNs.push_back(0); // pos of QN 1 in SingleSite
// No total S variables. Leave totSpos empty
HN.CalcHNMatEl=OneChQ_HN_MatEl;
ThisCode.Nsites0=1;
ThisCode.NumChannels=1;
chi_m1=chiN(0,Lambda);
break;
case 4: // CM Phonons - 2channel
switch(ThisCode.SymNo){
case 4:{ // TwoChQSP
Params.push_back(Lambda); // Lambda
Params.push_back(HalfLambdaFactor); // Lambda factor
Params.push_back(ThisCode.dInitParams[0]); // U1
Params.push_back(ThisCode.dInitParams[2]); // ed1
Params.push_back(chi_m1); // sqrt(2gamma1/Pi)/sqrt(L)*HalfLambdaFactor
Params.push_back(ThisCode.dInitParams[3]); // w0
Params.push_back(ThisCode.dInitParams[4]); // lambda_ph
Params.push_back(ThisCode.dInitParams[5]); // alpha
Params.push_back(ThisCode.dInitParams[6]); // Nph
// Update rules for f_ch1 and fch2
// Set rules for MatArray
// fN_ch1 (reduced)
MatArray[0].NeedOld=false;
MatArray[0].CheckForMatEl=TwoChQS_cd_check;
MatArray[0].CalcMatEl=TwoChQS_cd_ich1_Phonon_MatEl;
// fN_ch2 (reduced)
MatArray[1].NeedOld=false;
MatArray[1].CheckForMatEl=TwoChQSP_fA_check; // mixes parities
MatArray[1].CalcMatEl=TwoChQS_cd_ich2_Phonon_MatEl;
//CNRGarray MyTest1;
// Set H0, get pAeig and Update MatArray
TwoChQSP_SetH0CMphonon(Params, &Aeig,&SingleSite,MatArray);
// No phonons needed from now on
MatArray[0].CalcMatEl=TwoChQS_fNch1_MatEl;
MatArray[1].CalcMatEl=TwoChQS_fNch2_MatEl;
// BuildBasis params
CommonQNs.push_back(3); // No of common QNs
CommonQNs.push_back(0); // pos of QN 1 in old
CommonQNs.push_back(1); // pos of QN 2 in old
CommonQNs.push_back(2); // pos of QN 3 in old
CommonQNs.push_back(0); // pos of QN 1 in SingleSite
CommonQNs.push_back(1); // pos of QN 2 in SingleSite
CommonQNs.push_back(3); // pos of QN 3 in SingleSite
CommonQNs.push_back(2); // Pos of parity in old
totSpos.push_back(1); // Pos of S in old
// Hamiltonian/Code params
HN.CalcHNMatEl=TwoChQS_HN_MatEl;
ThisCode.Nsites0=1;
chi_m1=chiN(0,Lambda);
ThisCode.NumNRGmats=2;
ThisCode.NumChannels=2;
ThisCode.NumThermoMats=2;
ThermoArray[0].dImpValue=0.0;
ThermoArray[1].dImpValue=0.0; // Check this!!
// Thermobasics
strcpy(ThermoArray[0].ArqName,"SuscepImp2Ch_CMphonon_QSP.dat");
strcpy(ThermoArray[0].ChainArqName,"SuscepChain2Ch.dat");
ThermoArray[0].Calc=CalcSuscep;
strcpy(ThermoArray[1].ArqName,"EntropyImp2Ch_CMphonon_QSP.dat");
strcpy(ThermoArray[1].ChainArqName,"EntropyChain2Ch.dat");
ThermoArray[1].Calc=CalcEntropy;
cout << " Implementing this model NOW " << endl;
cout << " fN_ch1 : " << endl;
MatArray[0].PrintAllBlocks();
cout << " fN_ch2 : " << endl;
MatArray[1].PrintAllBlocks();
break;
}// Need curly braces in "case" is declaring anything in it
default:
cout << " Symmetry " << ThisCode.Symmetry
<< " not implemented for " << ThisCode.ModelOption << endl;
exit(0);
}
break;
case 6: // Double Quantum dot
switch(ThisCode.SymNo){
case 0:{ // OneChQS
cout << " Implementing DQD case... " << endl;
double chi2_m1=sqrt(2.0*ThisCode.dInitParams[4]/pi)/(sqrt(Lambda)*HalfLambdaFactor);
Params.push_back(Lambda);
Params.push_back(HalfLambdaFactor);
Params.push_back(ThisCode.dInitParams[0]); // U1
Params.push_back(ThisCode.dInitParams[2]); // ed1
Params.push_back(chi_m1); // gamma1
Params.push_back(ThisCode.dInitParams[3]); // U2
Params.push_back(ThisCode.dInitParams[5]); // ed2
Params.push_back(chi2_m1); // gamma2
// Question: Can these things be implemented within the subroutine??
// fN (reduced)
STLMatArray[0].NeedOld=false;
STLMatArray[0].UpperTriangular=false;
STLMatArray[0].CheckForMatEl=OneChQS_cd_check;
STLMatArray[0].CalcMatEl=OneChQS_fN_MatEl;
switch (ThisCode.calcdens){
case 0: // Calculates Op averages only
auxNRGMat.NeedOld=true;
auxNRGMat.UpperTriangular=false; // update procedure only works for 'false'
auxNRGMat.CalcAvg=true; // CalcAvg
auxNRGMat.CheckForMatEl=Diag_check;
auxNRGMat.CalcMatEl=ImpOnly_MatEl;
STLMatArray[1]=auxNRGMat; // 1 - ndot (there already)
STLMatArray[2]=auxNRGMat; // 2 - ndot^2 (there already)
STLMatArray[3]=auxNRGMat; // 3 - Sdot^2 (there already)
STLMatArray.push_back(auxNRGMat); // 4 - S1 dot S2
strcpy(STLMatArray[1].MatName,"Ndqd");
strcpy(STLMatArray[2].MatName,"NdqdSq");
strcpy(STLMatArray[3].MatName,"SdqdSq");
strcpy(STLMatArray[4].MatName,"S1dotS2");
NumNRGarrays=STLMatArray.size();
ThisCode.NumNRGmats=NumNRGarrays;
ThisCode.MatArray=&STLMatArray[0]; // Need to do this after
// changes in STLMatArray!
ThisCode.SaveData=false;
break;
case 1: // Calc Spectral functions
// All operators have the same Checks/MatEls in |Q> basis
// what changes is the initial set-up
auxNRGMat.NeedOld=true;
auxNRGMat.CheckForMatEl=OneChQS_cd_check;
auxNRGMat.CalcMatEl=OneChQS_cd_MatEl;
auxNRGMat.SaveMatYN=true;
STLMatArray[1]=auxNRGMat; // 1 - cd1
STLMatArray[2]=auxNRGMat; // 2 - cd2
strcpy(STLMatArray[1].MatName,"cdot1");
strcpy(STLMatArray[2].MatName,"cdot2");
STLMatArray.pop_back(); // 3 elements only
NumNRGarrays=STLMatArray.size();
ThisCode.NumNRGmats=NumNRGarrays;
ThisCode.MatArray=&STLMatArray[0]; // Need to do this after
// changes in STLMatArray!
ThisCode.SaveData=true;
strcpy(ThisCode.SaveArraysFileName,"DQD");
break;
case 2: // Thermodynamics
STLMatArray.pop_back(); // 1 Matrix only
STLMatArray.pop_back(); // 1 Matrix only
STLMatArray.pop_back(); // 1 Matrix only
strcpy(ThermoArray[0].ArqName,"SuscepImp1ChQS_DQD.dat");
strcpy(ThermoArray[0].ChainArqName,"SuscepChain1Ch_QS.dat");
strcpy(ThermoArray[1].ArqName,"EntropyImp1ChQS_DQD.dat");
strcpy(ThermoArray[1].ChainArqName,"EntropyChain1Ch_QS.dat");
ThermoArray[0].Calc=CalcSuscep;
ThermoArray[0].dImpValue=1.0/4.0; // check
ThermoArray[1].Calc=CalcEntropy;
ThermoArray[1].dImpValue=4.0*log(2.0);
ThisCode.NumThermoMats=2;
break;
default:
cout << " Calculating levels only " << endl;
}
// end switch calcdens
OneChQS_SetHm1DQD(Params,&Aeig,&SingleSite,STLMatArray);
// BuildBasis params
CommonQNs.push_back(2); // Q and S and commont QNs
CommonQNs.push_back(0); // position of Q in old basis
CommonQNs.push_back(1); // position of S in old basis
CommonQNs.push_back(0); // position of Q in SingleSite
CommonQNs.push_back(1); // position of S in SingleSite
totSpos.push_back(1); // SU(2) symmetry in position 1
// HN params
HN.CalcHNMatEl=OneChQS_HN_MatEl;
ThisCode.Nsites0=1;
ThisCode.NumChannels=1;
chi_m1=chiN(0,Lambda);
break;
}
default:
cout << " Symmetry " << ThisCode.Symmetry
<< " not implemented for " << ThisCode.ModelOption << endl;
exit(0);
}
break;
default:
cout << " Model not implemented. Exiting... " << endl;
exit(0);
}
// end switch ModelNo
// Set Initial AeigCut
//CNRGbasisarray AeigCut=CutStates(&Aeig, ThisCode.Ncutoff);
// ThisCode.pAcut=&AeigCut;
CutStates(Aeig, AeigCut, ThisCode.Ncutoff);
//AeigCut=CutStates(&Aeig, ThisCode.Ncutoff);
cout << "Got here... I" << endl;
// watch out for the "Nsites0-2"
ThisCode.DN=HalfLambdaFactor*pow(Lambda,(-(ThisCode.Nsites0-2)/2.0) );
TM=ThisCode.DN/ThisCode.betabar;
cout << "DN = " << ThisCode.DN << " TM = " << TM << endl;
//
// The idea is to eliminate this and put into CalcStuff
//
// if (ThisCode.SymNo==3){
// ParamsBetabar.clear();
// ParamsBetabar.push_back(ThisCode.betabar);
// //double dSz=CalcOpAvg(ParamsBetabar,&AeigCut,&MatArray[2],false,0);
// //double dSz2=CalcOpAvg(ParamsBetabar,&AeigCut,&MatArray[3],false,0);
// double dSz=CalcOpAvg(ParamsBetabar,&AeigCut,&STLMatArray[2],false,0);
// double dSz2=CalcOpAvg(ParamsBetabar,&AeigCut,&STLMatArray[3],false,0);
// cout << " T = " << TM << " Sz = " << dSz << " Sz2 = " << dSz2
// << " T_M chi = " << dSz2-dSz*dSz << endl;
// }
//
for (int ithermo=0;ithermo<NumThermoArrays;ithermo++){
ThisCode.ThermoSTLArray.push_back(ThermoArray[ithermo]);
}
if (ThisCode.Nsites0=1) // Calculates Thermo from N=0 on (not N=-1)
ThisCode.CalcThermo(ThermoArray,&Aeig);
ThisCode.CalcStuff(&Aeig,&AeigCut);
// Save Params?
if (ThisCode.SaveData){ThisCode.SaveGenPars();}
// Ok, with that we can go into the main loop
// Parameters for HN (always the same?)
ParamsHN.push_back(Lambda);
for (int ich=0;ich<ThisCode.NumChannels;ich++)
ParamsHN.push_back(chi_m1);
// Entering calculation of H_Nsites0
ThisCode.Nsites=ThisCode.Nsites0;
while (ThisCode.Nsites<ThisCode.Nsitesmax){
ThisCode.DN=HalfLambdaFactor*pow(Lambda,(-(ThisCode.Nsites-1)/2.0) );
TM=ThisCode.DN/ThisCode.betabar;
cout << "DN = " << ThisCode.DN << "TM = " << TM << endl;
// Debugging...
//bool disp=(ThisCode.Nsites==3?true:false);
bool disp=false;
// Build Basis
//SingleSite.PrintQNumbers();
//Aeig.PrintQNumbers();
BuildBasis(CommonQNs, totSpos,&AeigCut,&Abasis,
&SingleSite,ThisCode.UpdateBefCut);
//Abasis.PrintAll();
// Diagonalize HN
cout << "Diagonalizing HN... " << endl;
cout << " chi_N = " << ParamsHN[1] << endl;
// Need to adapt ALL models to use STLMatArray...
// in the meantime, this will work.
// if ( (ThisCode.ModelNo==5)||(ThisCode.ModelNo==0)||(ThisCode.ModelNo==6) ){
// HN.DiagHN(ParamsHN,&Abasis,&SingleSite,&STLMatArray[0],&Aeig,disp);
// }else{
// HN.DiagHN(ParamsHN,&Abasis,&SingleSite,MatArray,&Aeig);
// }
if ( (ThisCode.ModelNo==4) ){
HN.DiagHN(ParamsHN,&Abasis,&SingleSite,MatArray,&Aeig);
}else{
HN.DiagHN(ParamsHN,&Abasis,&SingleSite,&STLMatArray[0],&Aeig,disp);
}
cout << "... done diagonalizing HN. " << endl;
Aeig.PrintEn();
// for (int ibl=0;ibl<Aeig.NumBlocks();ibl++)
// Aeig.PrintBlock(ibl);
// Calculate Susceptibility/Entropy (does not need update)
ThisCode.CalcThermo(ThermoArray,&Aeig);
// Update matrices (if UpdateBefCut)
// Cut and Update AC (If it does not need updated matrices, this should be cut).
// OLD
//AeigCut.ClearAll();
//AeigCut=CutStates(&Aeig, ThisCode.Ncutoff);
// NEW (updates after cutting)
CutStates(Aeig, AeigCut, ThisCode.Ncutoff);
if (ThisCode.Nsites<ThisCode.Nsitesmax){
// Need to adapt ALL models to use STLMatArray...
// in the meantime, this will work.
if ( (ThisCode.ModelNo==4) ){
UpdateMatrices(&SingleSite,&AeigCut,
&Abasis,MatArray, ThisCode.NumNRGmats);
}else{
// UpdateMatrices(&SingleSite,&AeigCut,
// &Abasis,&STLMatArray[0],STLMatArray.size());
// Debugging
UpdateMatrices(&SingleSite,&AeigCut,
&Abasis,&STLMatArray[0],STLMatArray.size(),disp);
}
}
// end update matrices
// Q Sz tests (remove later)
cout << " N = " << ThisCode.Nsites << endl;
// Save stuff to files
//// Read/Write test (remove later) ///////////
if (ThisCode.SaveData){ThisCode.SaveArrays();}
// Calculate Other things that need updated matrices
//
// The idea is to eliminate this and put into CalcStuff
// (need to test with OneChQ!!
if (ThisCode.SymNo==3){
ParamsBetabar.clear();
ParamsBetabar.push_back(ThisCode.betabar);
double dSz=CalcOpAvg(ParamsBetabar,&AeigCut,&STLMatArray[2],false,0);
double dSz2=CalcOpAvg(ParamsBetabar,&AeigCut,&STLMatArray[3],false,0);
//double dSz=CalcOpAvg(ParamsBetabar,&AeigCut,MatArray,false,0);
//double dSz2=CalcOpAvg(ParamsBetabar,&AeigCut,MatArray,false,0);
cout << " T = " << TM << " Sz = " << dSz << " Sz2 = " << dSz2
<< " T_M chi = " << dSz2-dSz*dSz << endl;
}
ThisCode.CalcStuff(&Aeig,&AeigCut);
// Update ParamsHN
//ParamsHN[1]=chiN(ThisCode.Nsites,Lambda); // Old
for (int ich=0;ich<ThisCode.NumChannels;ich++)
//ParamsHN[ich+1]=chiN(ThisCode.Nsites,Lambda);
// Try this...
ParamsHN[ich+1]=chain1.GetChin(ThisCode.Nsites);
// Update sites
ThisCode.Nsites++;
}
// end Nsites loop
// De-allocate MatArray
delete[] ThermoArray;
delete[] MatArray;
ThisCode.WrapUp();
}
// end main
| 30.806946 | 118 | 0.635245 | [
"vector",
"model"
] |
8351c0b74499099d9b09e26cfdce96adc0fa0454 | 3,116 | hpp | C++ | src/material.hpp | White-Link/PathTracer | 4419c5c23ee897d7859c78e34bc88e4ef2beca59 | [
"MIT"
] | null | null | null | src/material.hpp | White-Link/PathTracer | 4419c5c23ee897d7859c78e34bc88e4ef2beca59 | [
"MIT"
] | null | null | null | src/material.hpp | White-Link/PathTracer | 4419c5c23ee897d7859c78e34bc88e4ef2beca59 | [
"MIT"
] | null | null | null | /**
* \file material.hpp
* \brief Defines class Material.
*/
#include "utils.hpp"
/**
* \class Material
* \brief Represents the material of an object (e.g. its color, refractive
* index...).
*/
class Material {
private:
/// Diffuse (R,G,B) of the Material, each component being between 0 and 1.
Vector color_diffuse_ = Vector{1, 1, 1};
/// Specular (R,G,B) of the Material.
Vector color_specular_ = Vector{1, 1, 1};
/// Transparent (R,G,B) of the Material (filters the color due to
/// refraction).
Vector color_transparent_ = Vector{1, 1, 1};
/// Fraction of the light that is returned as diffuse color by the Material.
/// Assumed to lie between 0 and 1.
double opacity_ = 1;
/// Fraction of the diffuse light coming from indirect illumination.
/// Assumed to lie between 0 and 1.
double fraction_diffuse_brdf_ = 0.5;
/// Specular coefficient of the Material.
double specular_coefficient_ = 30;
/// Ponderation of the specular color. Assumed to lie between 0 and 1.
double fraction_specular_ = 1;
/// Indicates if there is refraction on the Material.
bool refractive_ = true;
/// Refractive index of the Material.
double index_ = 1;
public:
/// Constructs a Material from the set of its defining fields.
Material(
const Vector &color_diffuse = Vector{1, 1, 1},
const Vector &color_specular = Vector{1, 1, 1},
const Vector &color_transparent = Vector{1, 1, 1},
double opacity=1,
double fraction_diffuse_brdf=0.5,
double specular_coefficient=30,
double fraction_specular=0,
bool refractive=true,
double refractive_index=1
) :
color_diffuse_{color_diffuse},
color_specular_{color_specular},
color_transparent_{color_transparent},
opacity_{opacity},
fraction_diffuse_brdf_{fraction_diffuse_brdf},
specular_coefficient_{specular_coefficient},
fraction_specular_{fraction_specular},
refractive_{refractive},
index_{refractive_index}
{
}
/// Outputs the diffuse color of the Material.
inline const Vector& DiffuseColor() const {
return color_diffuse_;
}
/// Outputs the specular color of the Material.
inline const Vector& SpecularColor() const {
return color_specular_;
}
/// Outputs the transparent color of the Material.
inline const Vector& TransparentColor() const {
return color_transparent_;
}
/// Outputs the specular coefficient of the Material.
inline double SpecularCoefficient() const {
return specular_coefficient_;
}
/// Outputs the ponderation of the specular color of the Material.
inline double FractionSpecular() const {
return fraction_specular_;
}
/// Outputs the fraction of the light that is returned as diffuse color by
/// the Material.
inline double Opacity() const {
return opacity_;
}
/// Outputs the fraction of the diffuse light coming from reflection.
inline double FractionDiffuseBRDF() const {
return fraction_diffuse_brdf_;
}
/// Indicates if there is refraction on the Material.
inline bool Refraction() const {
return refractive_;
}
/// Outputs the refractive index of the Material.
inline double RefractiveIndex() const {
return index_;
}
};
| 26.632479 | 77 | 0.731386 | [
"object",
"vector"
] |
835443bd3ec020b651c8be1cbdb99f3bf8dec032 | 7,330 | inl | C++ | modules/SofaBoundaryCondition/FixedTranslationConstraint.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaBoundaryCondition/FixedTranslationConstraint.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaBoundaryCondition/FixedTranslationConstraint.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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.1 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_FIXEDTRANSLATIONCONSTRAINT_INL
#define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_FIXEDTRANSLATIONCONSTRAINT_INL
#include <sofa/core/topology/BaseMeshTopology.h>
#include <SofaBoundaryCondition/FixedTranslationConstraint.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/helper/gl/template.h>
#include <SofaBaseTopology/TopologySubsetData.inl>
namespace sofa
{
namespace component
{
namespace projectiveconstraintset
{
// Define TestNewPointFunction
template< class DataTypes>
bool FixedTranslationConstraint<DataTypes>::FCPointHandler::applyTestCreateFunction(unsigned int, const sofa::helper::vector<unsigned int> &, const sofa::helper::vector<double> &)
{
return fc != 0;
}
// Define RemovalFunction
template< class DataTypes>
void FixedTranslationConstraint<DataTypes>::FCPointHandler::applyDestroyFunction(unsigned int pointIndex, value_type &)
{
if (fc)
{
fc->removeIndex((unsigned int) pointIndex);
}
}
template< class DataTypes>
FixedTranslationConstraint<DataTypes>::FixedTranslationConstraint()
: core::behavior::ProjectiveConstraintSet<DataTypes>(NULL)
, f_indices( initData(&f_indices,"indices","Indices of the fixed points") )
, f_fixAll( initData(&f_fixAll,false,"fixAll","filter all the DOF to implement a fixed object") )
, _drawSize( initData(&_drawSize,(SReal)0.0,"drawSize","0 -> point based rendering, >0 -> radius of spheres") )
, f_coordinates( initData(&f_coordinates,"coordinates","Coordinates of the fixed points") )
{
// default to indice 0
f_indices.beginEdit()->push_back(0);
f_indices.endEdit();
pointHandler = new FCPointHandler(this, &f_indices);
}
template <class DataTypes>
FixedTranslationConstraint<DataTypes>::~FixedTranslationConstraint()
{
if (pointHandler)
delete pointHandler;
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::clearIndices()
{
f_indices.beginEdit()->clear();
f_indices.endEdit();
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::addIndex(unsigned int index)
{
f_indices.beginEdit()->push_back(index);
f_indices.endEdit();
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::removeIndex(unsigned int index)
{
removeValue(*f_indices.beginEdit(),index);
f_indices.endEdit();
}
// -- Constraint interface
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::init()
{
this->core::behavior::ProjectiveConstraintSet<DataTypes>::init();
topology = this->getContext()->getMeshTopology();
// Initialize functions and parameters
f_indices.createTopologicalEngine(topology, pointHandler);
f_indices.registerTopologicalData();
f_coordinates.createTopologicalEngine(topology);
f_coordinates.registerTopologicalData();
}
template<int N, class T>
static inline void clearPos(defaulttype::RigidDeriv<N,T>& v)
{
getVCenter(v).clear();
}
template<class T>
static inline void clearPos(defaulttype::Vec<6,T>& v)
{
for (unsigned int i=0; i<3; ++i)
v[i] = 0;
}
template <class DataTypes> template <class DataDeriv>
void FixedTranslationConstraint<DataTypes>::projectResponseT(const core::MechanicalParams* /*mparams*/, DataDeriv& res)
{
const SetIndexArray & indices = f_indices.getValue();
if (f_fixAll.getValue() == true)
{
for (int i = 0; i < topology->getNbPoints(); ++i)
{
clearPos(res[i]);
}
}
else
{
for (SetIndexArray::const_iterator it = indices.begin(); it
!= indices.end(); ++it)
{
clearPos(res[*it]);
}
}
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::projectResponse(const core::MechanicalParams* mparams, DataVecDeriv& resData)
{
helper::WriteAccessor<DataVecDeriv> res = resData;
projectResponseT(mparams, res.wref());
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::projectVelocity(const core::MechanicalParams* /*mparams*/, DataVecDeriv& /*vData*/)
{
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::projectPosition(const core::MechanicalParams* /*mparams*/, DataVecCoord& /*xData*/)
{
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::projectJacobianMatrix(const core::MechanicalParams* mparams, DataMatrixDeriv& cData)
{
helper::WriteAccessor<DataMatrixDeriv> c = cData;
MatrixDerivRowIterator rowIt = c->begin();
MatrixDerivRowIterator rowItEnd = c->end();
while (rowIt != rowItEnd)
{
projectResponseT<MatrixDerivRowType>(mparams, rowIt.row());
++rowIt;
}
}
template <class DataTypes>
void FixedTranslationConstraint<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
#ifndef SOFA_NO_OPENGL
const SetIndexArray & indices = f_indices.getValue();
if (!vparams->displayFlags().getShowBehaviorModels())
return;
const VecCoord& x = this->mstate->read(core::ConstVecCoordId::position())->getValue();
glDisable(GL_LIGHTING);
glPointSize(10);
glColor4f(1, 0.5, 0.5, 1);
glBegin(GL_POINTS);
if (f_fixAll.getValue() == true)
{
for (unsigned i = 0; i < x.size(); i++)
{
sofa::helper::gl::glVertexT(x[i].getCenter());
}
}
else
{
for (SetIndex::const_iterator it = indices.begin(); it != indices.end(); ++it)
{
sofa::helper::gl::glVertexT(x[*it].getCenter());
}
}
glEnd();
#endif /* SOFA_NO_OPENGL */
}
} // namespace constraint
} // namespace component
} // namespace sofa
#endif
| 32.149123 | 179 | 0.639427 | [
"object",
"vector"
] |
83566b2f4fe25b80c836da3d27a867bfdea6bc59 | 2,589 | cpp | C++ | cpp/language_reference_initialization_5.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | cpp/language_reference_initialization_5.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | cpp/language_reference_initialization_5.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | /*
g++ --std=c++20 -pthread -o ../_build/cpp/language_reference_initialization_5.exe ./cpp/language_reference_initialization_5.cpp && (cd ../_build/cpp/;./language_reference_initialization_5.exe)
https://en.cppreference.com/w/cpp/language/reference_initialization
*/
#include <utility>
#include <sstream>
struct S {
int mi;
const std::pair<int, int>& mp; // reference member
};
void foo(int) {}
struct A {};
struct B : A {
int n;
operator int&() { return n; }
};
B bar() { return B(); }
//int& bad_r; // error: no initializer
extern int& ext_r; // OK
int main() {
// Lvalues
int n = 1;
int& r1 = n; // lvalue reference to the object n
const int& cr(n); // reference can be more cv-qualified
volatile int& cv{n}; // any initializer syntax can be used
int& r2 = r1; // another lvalue reference to the object n
// int& bad = cr; // error: less cv-qualified
int& r3 = const_cast<int&>(cr); // const_cast is needed
void (&rf)(int) = foo; // lvalue reference to function
int ar[3];
int (&ra)[3] = ar; // lvalue reference to array
B b;
A& base_ref = b; // reference to base subobject
int& converted_ref = b; // reference to the result of a conversion
// Rvalues
// int& bad = 1; // error: cannot bind lvalue ref to rvalue
const int& cref = 1; // bound to rvalue
int&& rref = 1; // bound to rvalue
const A& cref2 = bar(); // reference to A subobject of B temporary
A&& rref2 = bar(); // same
int&& xref = static_cast<int&&>(n); // bind directly to n
// int&& copy_ref = n; // error: can't bind to an lvalue
double&& copy_ref = n; // bind to an rvalue temporary with value 1.0
// Restrictions on temporary lifetimes
std::ostream& buf_ref = std::ostringstream() << 'a'; // the ostringstream temporary
// was bound to the left operand of operator<<
// but its lifetime ended at the semicolon
// so buf_ref is a dangling reference
S a {1, {2, 3} }; // temporary pair {2, 3} bound to the reference member
// a.mp and its lifetime is extended to match
// the lifetime of object a
S* p = new S{1, {2, 3} }; // temporary pair {2, 3} bound to the reference
// member p->mp, but its lifetime ended at the semicolon
// p->mp is a dangling reference
delete p;
}
| 44.637931 | 192 | 0.564311 | [
"object"
] |
835ddf6afbb8c741be9052fc9eae98695adcdac9 | 1,864 | cpp | C++ | db/Relations/pathsegment.cpp | rduan036/YoMap | 60fc5ac86740765d168d1e54c11faa4fcb190a07 | [
"MIT"
] | 1 | 2021-05-22T10:31:49.000Z | 2021-05-22T10:31:49.000Z | db/Relations/pathsegment.cpp | rduan036/YoMap | 60fc5ac86740765d168d1e54c11faa4fcb190a07 | [
"MIT"
] | null | null | null | db/Relations/pathsegment.cpp | rduan036/YoMap | 60fc5ac86740765d168d1e54c11faa4fcb190a07 | [
"MIT"
] | null | null | null | #include "pathsegment.h"
PathSegment::PathSegment(unsigned long int i):Relation(i,ns_relation::path_segment)
{
cost = 0.0f;
}
PathSegment::~PathSegment(){
for(vector<WaySegment*>::iterator it = segments.begin();it!=segments.end();it++){
delete (*it)->getPointA();
delete (*it)->getPointB();
delete (*it);
}
}
bool PathSegment::isEmpty(){
return segments.empty();
}
void PathSegment::addSegment(WaySegment* &ws){
segments.push_back(ws);
cost+=ws->getCost();
}
vector<WaySegment*>::iterator PathSegment::getWaySegmentsBegin(){
return segments.begin();
}
vector<WaySegment*>::iterator PathSegment::getWaySegmentsEnd(){
return segments.end();
}
float PathSegment::calculateCost(){
//Go through all segments and sum for the cost of the path segment
if(!segments.empty())
{
cost=0.0f;
for (vector<WaySegment*>::iterator it=segments.begin(); it!=segments.end(); it++){
cost +=(*it)->getCost();
}
}
return cost;
}
float PathSegment::getCost(){
return cost;
}
void PathSegment::setCost(float &c){
cost = c;
}
//Calculate travel time according to means of transport
float PathSegment::getTravelTime(ns_permisions::transport_type &tt){
float time=0.0f;
for (vector<WaySegment*>::iterator it=segments.begin(); it!=segments.end(); it++){
float d=(*it)->getCost();
(*it)->getWay()->getWayType();
float v = getSpeedFromWayType(tt,(*it)->getWay()->getWayType());
//if speed is 0 we return as 0 (it would be inf);
if(v==0)
return 0;
time += (d/v);
}
return time;
}
void PathSegment::setStartEnd(Node* &start, Node* &end){
startNode = start;
endNode = end;
}
Node* PathSegment::getStartNode(){
return startNode;
}
Node* PathSegment::getEndNode(){
return endNode;
}
| 25.888889 | 90 | 0.630365 | [
"vector"
] |
8364df7a13c9fe7c1400ee67d1698738d8bbbf3e | 1,275 | cpp | C++ | Codeforces/Contest 1634/1634C.cpp | Sansiff/Coding-Practice | b76f5a403c478abedc7bf22acb314b6cebb538ea | [
"MIT"
] | 1 | 2021-09-14T11:25:21.000Z | 2021-09-14T11:25:21.000Z | Codeforces/Contest 1634/1634C.cpp | Sansiff/Coding-Practice | b76f5a403c478abedc7bf22acb314b6cebb538ea | [
"MIT"
] | null | null | null | Codeforces/Contest 1634/1634C.cpp | Sansiff/Coding-Practice | b76f5a403c478abedc7bf22acb314b6cebb538ea | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define int long long
#define lowbit(x) (x&-x)
#define rep(i, l, r) for(int i = l; i < r; i ++)
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;
typedef vector<PII> VPII;
void read(VI& a){
for(int& x : a) cin >> x;
}
void solve() {
int n, k; cin >> n >> k;
int cnt1 = (n * k + 1) / 2, cnt2 = n * k / 2;
vector<int> ans[n + 1];
for (int i = 1; i <= n; i++){
if(cnt1>=k) {
int res = k;
while(res){
ans[i].push_back(cnt1*2-1);
cnt1--;
res--;
}
}
else if(cnt2 >= k) {
int res = k;
while(res){
ans[i].push_back(cnt2*2);
cnt2--, res--;
}
}
else {
cout << "NO\n";
return ;
}
}
cout << "YES\n";
for(int i=1;i<=n;i++){
for(auto x:ans[i])
cout << x << " ";
cout << endl;
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int _; cin >> _;
while(_--){
solve();
}
return 0;
} | 21.610169 | 49 | 0.432941 | [
"vector"
] |
837582805ff36c3a34f34fa1c01473a2a540cb0c | 1,100 | cpp | C++ | pat1028.cpp | Lollipopcc/PAT-Advanced-Level- | 1896890df32ed162601b96bbbb3c56ce904a6122 | [
"Apache-2.0"
] | null | null | null | pat1028.cpp | Lollipopcc/PAT-Advanced-Level- | 1896890df32ed162601b96bbbb3c56ce904a6122 | [
"Apache-2.0"
] | null | null | null | pat1028.cpp | Lollipopcc/PAT-Advanced-Level- | 1896890df32ed162601b96bbbb3c56ce904a6122 | [
"Apache-2.0"
] | null | null | null | #include<stdio.h>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct{
char sid[8];
char sname[10];
int grade;
}node;
vector<node> student;
bool cmp1(node a,node b){
if(strcmp(a.sid,b.sid)<0) return true;
return false;
}
bool cmp2(node a,node b){
if(strcmp(a.sname,b.sname)==0){
if(strcmp(a.sid,b.sid)<0) return true;
return false;
}
if(strcmp(a.sname,b.sname)<0) return true;
return false;
}
bool cmp3(node a,node b){
if(a.grade==b.grade){
if(strcmp(a.sid,b.sid)<0) return true;
return false;
}
return a.grade<b.grade;
}
int main(void){
int n,c;
int i;
while(scanf("%d%d",&n,&c)!=EOF){
student.clear();
for(int i=0;i<n;i++){
node tn;
scanf("%s %s %d",tn.sid,tn.sname,&tn.grade);
student.push_back(tn);
}
if(c==1){
sort(student.begin(),student.end(),cmp1);
}else if(c==2){
sort(student.begin(),student.end(),cmp2);
}else {
sort(student.begin(),student.end(),cmp3);
}
for(i=0;i<student.size();i++){
printf("%s %s %d\n",student[i].sid,student[i].sname,student[i].grade);
}
}
return 0;
} | 18.032787 | 73 | 0.623636 | [
"vector"
] |
8375ecd2c228d7bfc68436caabef571f69f48abc | 7,504 | cpp | C++ | FSGDEngine-Student/FSGDGame/ExampleGame.cpp | Cabrra/Engine-Development | cce5930e2264048b0be58b691729407ca507d1af | [
"MIT"
] | 2 | 2019-03-30T11:14:01.000Z | 2020-10-27T00:55:01.000Z | FSGDEngine-Student/FSGDGame/ExampleGame.cpp | Cabrra/Engine-Development | cce5930e2264048b0be58b691729407ca507d1af | [
"MIT"
] | null | null | null | FSGDEngine-Student/FSGDGame/ExampleGame.cpp | Cabrra/Engine-Development | cce5930e2264048b0be58b691729407ca507d1af | [
"MIT"
] | 1 | 2019-01-29T20:12:24.000Z | 2019-01-29T20:12:24.000Z | #include <windows.h>
#include "ExampleGame.h"
#include "../EDGameCore/Camera.h"
#include "../EDGameCore/Transform.h"
#include "../EDGameCore/RigidBody.h"
#include "../EDRendererD3D/ViewPortManager.h"
#include "RenderController.h"
#include "../EDRendererD3D/DebugRenderer.h"
#include "../EDRendererD3D/GraphicsProfiler.h"
#include "ShapeRenderer.h"
#include "KeyboardController.h"
#include "MouseLookController.h"
#include "GamepadController.h"
#include "Mover.h"
#include "BuggyDriver.h"
#include "PointLightSource.h"
#include "SpotLightSource.h"
#include "DirectionalLightSource.h"
#include "FollowObserver.h"
#include "../EDUtilities/ContentManager.h"
#include "RenderController.h"
#include "SkyBox.h"
#include "JumpPad.h"
#include "Manipulator.h"
#include "PlayerController.h"
#include "Seeker.h"
#include "Evader.h"
#include "LookAt.h"
#include "TurnTo.h"
#include "PythonBehavior.h"
#include "PIDFollower.h"
#include "Picking.h"
#include "Target.h"
#include "HardAttach.h"
#include "Crosshair.h"
#include "Blast.h"
#include "ExplodeOnCollide.h"
#include "Sparkle.h"
#include "TerrainController.h"
#include "../EDUtilities/Settings.h"
#include "../EDRendererD3D/RenderShapeSkinned.h"
#include "../EDGameCore/Animation.h"
void ExampleGame::Initialize(void)
{
Game::Initialize();
string which_level;
Settings::GetInstance()->GetSetting("Level", which_level, "Levels/empty_level.xml");
//LoadScene(which_level.c_str());
LoadGame(which_level.c_str());
}
void ExampleGame::RegisterStrings(void)
{
//RegisterString("MainBuggy");
//RegisterString("MainBuggyGun");
//RegisterString("MainCamera");
//RegisterString("Box");
}
void ExampleGame::RegisterTypes(void)
{
RegisterType(ShapeRenderer);
RegisterType(Mover);
RegisterType(BuggyDriver);
RegisterType(KeyboardController);
RegisterType(MouseLookController);
RegisterType(GamepadController);
RegisterType(PointLightSource);
RegisterType(SpotLightSource);
RegisterType(DirectionalLightSource);
//RegisterType(FollowObserver);
RegisterType(SkyBox);
RegisterType(JumpPad);
RegisterType(Manipulator);
RegisterType(PlayerController);
RegisterType(Seeker);
RegisterType(Evader);
RegisterType(LookAt);
RegisterType(TurnTo);
RegisterType(PIDFollower);
RegisterType(PythonBehavior);
RegisterType(Picking);
RegisterType(Target);
RegisterType(HardAttach);
RegisterType(Crosshair);
RegisterType(Blast);
RegisterType(ExplodeOnCollide);
RegisterType(Sparkle);
RegisterType(TerrainController);
}
// #1
void ExampleGame::ProcessCamera(void)
{
EDGameCore::Camera* camera = GetCurrentCamera();
EDGameCore::Camera::CameraRect rect = camera->GetCameraRect();
float diffX = rect.maxX - rect.minX;
float diffY = rect.maxY - rect.minY;
float ratio = (diffX * GetWindowWidth()) / (diffY * GetWindowHeight());
camera->SetAspectRatio(ratio);
EDRendererD3D::ViewPortManager::GetReference().UpdateViewPort(
camera->GetDepth(), camera->GetGameObject()->GetTransform()->GetWorldMatrix(), camera->GetViewMatrix(), camera->GetProjectionMatrix(),
camera->GetNearDistance(), camera->GetFarDistance());
}
// HACK light yo
EDRendererD3D::DirectionalLightWithShadow *hackLightPtr;
// #4
// This method clears the current (camera) view set.
// Creates a view set of objects based on the light volume.
// Renders the given light, processing only the objects in the lights view for shadows
void ExampleGame::ProcessLight(EDGameCore::ILight* light)
{
RenderController::GetInstance()->ClearLightRenderSets();
light->Render();
ForwardLightManager &forwardLightManager = RenderController::GetInstance()->GetForardLightManager();
// If this is a shadow casting light, rebuild the view set for the given light
if( EDGameCore::ILight::NONE != light->GetShadows())
{
RenderController::GetInstance()->GetShadowMappingContextHandle().GetContent()->ClearRenderSet();
RenderController::GetInstance()->GetShadowMappingSkinnedContextHandle().GetContent()->ClearRenderSet();
BuildLightViewSet(light);
}
switch(light->GetLightType())
{
case EDGameCore::ILight::LightType::POINT:
{
EDRendererD3D::GraphicsProfiler::GetReference().BeginEvent(0,
L"Rendering a point light");
RenderController::GetInstance()->RenderPointLight((PointLightSource *)light);
EDRendererD3D::GraphicsProfiler::GetReference().EndEvent();
forwardLightManager.AddPointLight(((PointLightSource *)light)->GetLightPtr());
}
break;
case EDGameCore::ILight::LightType::SPOT:
{
EDRendererD3D::GraphicsProfiler::GetReference().BeginEvent(0,
L"Rendering a spot light");
RenderController::GetInstance()->RenderSpotLight((SpotLightSource *)light);
EDRendererD3D::GraphicsProfiler::GetReference().EndEvent();
forwardLightManager.AddSpotLight(((SpotLightSource *)light)->GetLightPtr());
}
break;
case EDGameCore::ILight::LightType::DIRECTIONAL:
{
EDRendererD3D::GraphicsProfiler::GetReference().BeginEvent(0,
L"Rendering a directional light");
hackLightPtr = ((DirectionalLightSource *)light)->GetLightPtr();
RenderController::GetInstance()->RenderDirectionalLight((DirectionalLightSource *)light,
GetCurrentCamera());
EDRendererD3D::GraphicsProfiler::GetReference().EndEvent();
forwardLightManager.AddDirectionalLight(((DirectionalLightSource *)light)->GetLightPtr());
}
break;
default:
break;
};
}
// #6
// This method is currently being used to rebuild the camera view set after the lighting stage.
// The camera's view set is required again to perform forward pass rendering operations
void ExampleGame::ProcessRendererPostLit(EDGameCore::IRenderer* renderer)
{
renderer->Render();
}
// #2
// This method builds the main camera view set
void ExampleGame::ProcessRendererPreLit(EDGameCore::IRenderer* renderer)
{
renderer->Render();
}
// #8
// This method is in charge of handling any final pass rendering and clean up needed.
void ExampleGame::PostProcessCamera(void)
{
hackLightPtr->ApplyCBuffer();
RenderController::GetInstance()->PostRender();
}
// #5
// This method clears the current view set, and adds any objects not handled by the spatial system
// to the view set before entering the ProcessRendererPostLit stage
void ExampleGame::ProcessVisibleLightSet(void)
{
RenderController::GetInstance()->RenderDebugPrimitives();
RenderController::GetInstance()->ClearRenderSets();
if( Game::GetSkyBox() != 0 )
Game::GetSkyBox()->Render();
}
// #3
// This method handles rendering of geometry data
void ExampleGame::ProcessPreLitVisibleSet(void)
{
EDRendererD3D::GraphicsProfiler::GetReference().BeginEvent(0, L"Render GBuffers Begin!");
RenderController::GetInstance()->RenderGBuffers();
EDRendererD3D::GraphicsProfiler::GetReference().EndEvent();
}
// #7
// This method executes rendering forward rendered objects
void ExampleGame::ProcessPostLitVisibleSet(void)
{
RenderController::GetInstance()->GetForardLightManager().ApplyForwardLights();
RenderController::GetInstance()->RenderUnlitObjects();
RenderController::GetInstance()->RenderTransparentObjects();
}
void ExampleGame::BuildLightViewSet(EDGameCore::ILight *light)
{
auto func = [&](EDGameCore::IRenderer *renderPtr)
{
ShapeRenderer *shapeRenderer = static_cast<ShapeRenderer *>(renderPtr);
if(shapeRenderer->GetAnimation())
shapeRenderer->Render(RenderController::GetInstance()->GetShadowMappingSkinnedContextHandle().GetContent());
else
shapeRenderer->Render(RenderController::GetInstance()->GetShadowMappingContextHandle().GetContent());
};
light->ForEachRendererInLight(func);
}
| 31.529412 | 137 | 0.765458 | [
"geometry",
"render",
"transform"
] |
83886af88c6a5c4cdefbaeff6bcc1379a88d6770 | 3,819 | cpp | C++ | rust/protocols-sys/c++/src/bin/benchmark.cpp | yexincheng/delphi | 7230fc9977008eab20bc1918c479c8294c93667c | [
"Apache-2.0",
"MIT"
] | 81 | 2020-01-15T18:48:51.000Z | 2022-03-30T11:51:44.000Z | rust/protocols-sys/c++/src/bin/benchmark.cpp | yexincheng/delphi | 7230fc9977008eab20bc1918c479c8294c93667c | [
"Apache-2.0",
"MIT"
] | 23 | 2020-07-07T09:28:32.000Z | 2022-03-17T20:30:02.000Z | rust/protocols-sys/c++/src/bin/benchmark.cpp | yexincheng/delphi | 7230fc9977008eab20bc1918c479c8294c93667c | [
"Apache-2.0",
"MIT"
] | 25 | 2020-01-16T02:51:53.000Z | 2022-03-31T04:50:08.000Z | /*
* Benchmark homomorphic convolution
*
* Created on: August 10, 2019
* Author: ryanleh
*/
#include <cstddef>
#include <iostream>
#include <iomanip>
#include <string>
#include <chrono>
#include <random>
#include <thread>
#include <mutex>
#include <memory>
#include <limits>
#include <math.h>
#include "conv2d.h"
#include "run_conv.cpp"
using namespace std;
/* Generates a random image and filters with the given dimensions and times
* convolution operation */
void benchmark(int image_h, int image_w, int filter_h, int filter_w,
int inp_chans, int out_chans, int stride, bool padding_valid) {
// Create uniform distribution
// We only sample up to 20 bits because the plaintext evaluation
// doesn't support 128 bit numbers so we need to make sure
// multiplication doesn't overfloow 64 bits
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<u64> dis(0, 1<<20);
// Create Eigen inputs for the plaintext and raw arrays for HE
EImage eimage(inp_chans);
Image image = new Channel[inp_chans];
for (int chan = 0; chan < inp_chans; chan++) {
EChannel tmp_chan(image_h, image_w);
image[chan] = new u64[image_h*image_w];
for (int idx = 0; idx < image_h*image_w; idx++) {
u64 val = dis(gen);
tmp_chan(idx/image_w, idx%image_w) = val;
image[chan][idx] = val;
}
eimage[chan] = tmp_chan;
}
EFilters efilters(out_chans);
Filters filters = new Image[out_chans];
for (int out_c = 0; out_c < out_chans; out_c++) {
EImage tmp_img(inp_chans);
filters[out_c] = new Channel[inp_chans];
for (int inp_c = 0; inp_c < inp_chans; inp_c++) {
EChannel tmp_chan(filter_h, filter_w);
filters[out_c][inp_c] = new u64[filter_h*filter_w];
for (int idx = 0; idx < filter_h*filter_w; idx++) {
u64 val = dis(gen);
tmp_chan(idx/filter_w, idx%filter_w) = val;
filters[out_c][inp_c][idx] = val;
}
tmp_img[inp_c] = tmp_chan;
}
efilters[out_c] = tmp_img;
}
cout << "\n\n--------------------------------------------\n";
cout << "Image shape: (" << image_h << "x" << image_w << ", " << inp_chans
<< ") - Filters shape: (" << filter_h << "x" << filter_w << ", " << out_chans
<< ") - Padding = " << (padding_valid ? "VALID" : "SAME") << ", Stride = (" <<
stride << "x" << stride << ")\n";
cout << "--------------------------------------------\n\n";
bool pass = run_conv(image, filters, image_h, image_w, filter_h, filter_w, inp_chans, out_chans, padding_valid, stride, stride, 0);
if (pass)
cout << "PASS" << endl;
else
cout << "FAIL" << endl;
}
int main()
{
/* Debugging */
//benchmark(3, 3, 2, 2, 1, 1, 1, 0);
//benchmark(32, 32, 3, 3, 16, 16, 1, 0);
//benchmark(16, 16, 3, 3, 32, 32, 1, 0);
//benchmark(8, 8, 3, 3, 64, 64, 1, 0);
/* Gazelle Benchmarks */
//benchmark(28, 28, 5, 5, 5, 5, 1, 1);
//benchmark(16, 16, 1, 1, 128, 128, 1, 1);
//benchmark(32, 32, 3, 3, 32, 32, 1, 1);
//benchmark(16, 16, 3, 3, 128, 128, 1, 1);
/* ResNet Benchmarks */
benchmark(32, 32, 3, 3, 3, 16, 1, 0);
benchmark(32, 32, 3, 3, 16, 16, 1, 0);
benchmark(32, 32, 1, 1, 16, 16, 1, 1);
benchmark(32, 32, 3, 3, 16, 32, 2, 0);
benchmark(16, 16, 3, 3, 32, 32, 1, 1);
benchmark(16, 16, 3, 3, 32, 64, 2, 0);
benchmark(8, 8, 3, 3, 64, 64, 1, 1);
/* Minionn Benchmarks */
//benchmark(32, 32, 3, 3, 3, 64, 1, 0);
//benchmark(32, 32, 3, 3, 64, 64, 1, 0);
//benchmark(16, 16, 3, 3, 64, 64, 1, 0);
//benchmark(8, 8, 1, 1, 64, 64, 1, 1);
//benchmark(8, 8, 1, 1, 64, 16, 1, 1);
return 0;
}
| 33.5 | 135 | 0.547264 | [
"shape"
] |
838ba61be278313a474dd7d5fb8973df2e6ed6db | 409 | cpp | C++ | ZhenTiBan/1-12.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | ZhenTiBan/1-12.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | ZhenTiBan/1-12.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main(){
int n=0,k=0;
cin >> n >> k;
int x=0;
vector<int> e0(32,0);
for(int i=0;i<n;i++){
cin >> x;
int index=0;
while(x){
e0[index++] += x%k;
x /= k;
}
}
int res=0;
for(int i=31;i>=0;i--){
res = res*k+(e0[i]%k);
}
cout << res;
return 0;
} | 17.782609 | 31 | 0.410758 | [
"vector"
] |
83902011fb330702c9aaa28c326f295af5f3f22c | 10,291 | cpp | C++ | solid/system/src/crashhandler_unix.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 26 | 2015-08-25T16:07:58.000Z | 2019-07-05T15:21:22.000Z | solid/system/src/crashhandler_unix.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-10-15T22:55:15.000Z | 2017-09-19T12:41:10.000Z | solid/system/src/crashhandler_unix.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-09-15T10:34:52.000Z | 2018-10-30T11:46:46.000Z | /** ==========================================================================
* Addapted for SolidFrame from https://github.com/KjellKod/g3log
* 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/
#include "solid/system/crashhandler.hpp"
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) && !defined(__GNUC__))
#error "crashhandler_unix.cpp used but it's a windows system"
#endif
#include <atomic>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <cxxabi.h>
#include <execinfo.h>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <thread>
#include <unistd.h>
// Linux/Clang, OSX/Clang, OSX/gcc
#if (defined(__clang__) || defined(__APPLE__))
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif
namespace {
const std::map<int, std::string> kSignals = {
{SIGABRT, "SIGABRT"},
{SIGFPE, "SIGFPE"},
{SIGILL, "SIGILL"},
{SIGSEGV, "SIGSEGV"},
{SIGTERM, "SIGTERM"},
};
std::map<int, std::string> gSignals = kSignals;
std::map<int, struct sigaction> gSavedSigActions;
bool shouldDoExit()
{
static std::atomic<uint64_t> firstExit{0};
auto const count = firstExit.fetch_add(1, std::memory_order_relaxed);
return (0 == count);
}
// Dump of stack,. then exit through g3log background worker
// ALL thanks to this thread at StackOverflow. Pretty much borrowed from:
// Ref: http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
void signalHandler(int signal_number, siginfo_t* info, void* unused_context)
{
// Only one signal will be allowed past this point
if (!shouldDoExit()) {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
using namespace solid::internal;
{
const auto dump = stackdump();
std::ostringstream fatal_stream;
const auto fatal_reason = exit_reason_name("FATAL_SIGNAL", signal_number);
fatal_stream << "Received fatal signal: " << fatal_reason;
fatal_stream << "(" << signal_number << ")\tPID: " << getpid() << std::endl;
fatal_stream << "\n***** SIGNAL " << fatal_reason << "(" << signal_number << ")" << std::endl;
std::cerr << fatal_stream.str() << " " << dump << std::endl;
}
// wait to die
}
//
// Installs FATAL signal handler that is enough to handle most fatal events
// on *NIX systems
void install_signal_handler()
{
#if !(defined(DISABLE_FATAL_SIGNALHANDLING))
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_sigaction = &signalHandler; // callback to crashHandler for fatal signals
// sigaction to use sa_sigaction file. ref: http://www.linuxprogrammingblog.com/code-examples/sigaction
action.sa_flags = SA_SIGINFO;
// do it verbose style - install all signal actions
for (const auto& sig_pair : gSignals) {
struct sigaction old_action;
memset(&old_action, 0, sizeof(old_action));
if (sigaction(sig_pair.first, &action, &old_action) < 0) {
std::string signalerror = "sigaction - " + sig_pair.second;
perror(signalerror.c_str());
} else {
gSavedSigActions[sig_pair.first] = old_action;
}
}
#endif
}
} // end anonymous namespace
// Redirecting and using signals. In case of fatal signals g3log should log the fatal signal
// and flush the log queue and then "rethrow" the signal to exit
namespace solid {
// References:
// sigaction : change the default action if a specific signal is received
// http://linux.die.net/man/2/sigaction
// http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=%2Fcom.ibm.aix.basetechref%2Fdoc%2Fbasetrf2%2Fsigaction.html
//
// signal: http://linux.die.net/man/7/signal and
// http://msdn.microsoft.com/en-us/library/xdkz3x12%28vs.71%29.asp
//
// memset + sigemptyset: Maybe unnecessary to do both but there seems to be some confusion here
// ,plenty of examples when both or either are used
// http://stackoverflow.com/questions/6878546/why-doesnt-parent-process-return-to-the-exact-location-after-handling-signal_number
namespace internal {
bool should_block_for_fatal_handling()
{
return true; // For windows we will after fatal processing change it to false
}
/// Generate stackdump. Or in case a stackdump was pre-generated and non-empty just use that one
/// i.e. the latter case is only for Windows and test purposes
std::string stackdump(const char* rawdump)
{
if (nullptr != rawdump && !std::string(rawdump).empty()) {
return {rawdump};
}
const size_t max_dump_size = 50;
void* dump[max_dump_size];
size_t size = backtrace(dump, max_dump_size);
char** messages = backtrace_symbols(dump, static_cast<int>(size)); // overwrite sigaction with caller's address
// dump stack: skip first frame, since that is here
std::ostringstream oss;
for (size_t idx = 1; idx < size && messages != nullptr; ++idx) {
char *mangled_name = 0, *offset_begin = 0, *offset_end = 0;
// find parantheses and +address offset surrounding mangled name
for (char* p = messages[idx]; *p; ++p) {
if (*p == '(') {
mangled_name = p;
} else if (*p == '+') {
offset_begin = p;
} else if (*p == ')') {
offset_end = p;
break;
}
}
// if the line could be processed, attempt to demangle the symbol
if (mangled_name && offset_begin && offset_end && mangled_name < offset_begin) {
*mangled_name++ = '\0';
*offset_begin++ = '\0';
*offset_end++ = '\0';
int status;
char* real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);
// if demangling is successful, output the demangled function name
if (status == 0) {
oss << "\n\tstack dump [" << idx << "] " << messages[idx] << " : " << real_name << "+";
oss << offset_begin << offset_end << std::endl;
} // otherwise, output the mangled function name
else {
oss << "\tstack dump [" << idx << "] " << messages[idx] << mangled_name << "+";
oss << offset_begin << offset_end << std::endl;
}
free(real_name); // mallocated by abi::__cxa_demangle(...)
} else {
// no demangling done -- just dump the whole line
oss << "\tstack dump [" << idx << "] " << messages[idx] << std::endl;
}
} // END: for(size_t idx = 1; idx < size && messages != nullptr; ++idx)
free(messages);
return oss.str();
}
/// string representation of signal ID
std::string exit_reason_name(const char* _text, solid::SignalType fatal_id)
{
int signal_number = static_cast<int>(fatal_id);
switch (signal_number) {
case SIGABRT:
return "SIGABRT";
break;
case SIGFPE:
return "SIGFPE";
break;
case SIGSEGV:
return "SIGSEGV";
break;
case SIGILL:
return "SIGILL";
break;
case SIGTERM:
return "SIGTERM";
break;
default:
std::ostringstream oss;
oss << "UNKNOWN SIGNAL(" << signal_number << ") for " << _text;
return oss.str();
}
}
// Triggered by g3log->g3LogWorker after receiving a FATAL trigger
// which is LOG(FATAL), CHECK(false) or a fatal signal our signalhandler caught.
// --- If LOG(FATAL) or CHECK(false) the signal_number will be SIGABRT
// void exit_with_default_signal_handler(const LEVELS& level, g3::SignalType fatal_signal_id) {
// const int signal_number = static_cast<int>(fatal_signal_id);
// restore_signal_handler(signal_number);
// std::cerr << "\n\n" << __FUNCTION__ << ":" << __LINE__ << ". Exiting due to " << level.text << ", " << signal_number << " \n\n" << std::flush;
//
//
// kill(getpid(), signal_number);
// exit(signal_number);
//
// }
} // namespace internal
std::string signal_to_string(int signal_number)
{
std::string signal_name;
const char* signal_name_sz = strsignal(signal_number);
// From strsignal(3): On some systems (but not on Linux), NULL may instead
// be returned for an invalid signal number.
if (nullptr == signal_name_sz) {
signal_name = "Unknown signal " + std::to_string(signal_number);
} else {
signal_name = signal_name_sz;
}
return signal_name;
}
void restore_signal_handler(int signal_number)
{
#if !(defined(DISABLE_FATAL_SIGNALHANDLING))
auto old_action_it = gSavedSigActions.find(signal_number);
if (old_action_it == gSavedSigActions.end()) {
return;
}
if (sigaction(signal_number, &(old_action_it->second), nullptr) < 0) {
auto signalname = std::string("sigaction - ") + signal_to_string(signal_number);
perror(signalname.c_str());
}
gSavedSigActions.erase(old_action_it);
#endif
}
// This will override the default signal handler setup and instead
// install a custom set of signals to handle
void override_setup_signals(const std::map<int, std::string> overrideSignals)
{
static std::mutex signalLock;
std::lock_guard<std::mutex> guard(signalLock);
for (const auto& sig : gSignals) {
restore_signal_handler(sig.first);
}
gSignals = overrideSignals;
install_crash_handler(); // installs all the signal handling for gSignals
}
// restores the signal handler back to default
void restore_signal_handler_to_default()
{
override_setup_signals(kSignals);
}
// installs the signal handling for whatever signal set that is currently active
// If you want to setup your own signal handling then
// You should instead call overrideSetupSignals()
void install_crash_handler()
{
install_signal_handler();
}
} //namespace solid
| 35.364261 | 156 | 0.629579 | [
"solid"
] |
83915aed0b4624f7592b0886f30824313d8ffb22 | 7,787 | hxx | C++ | src/devices/cpu/mips/o2dprintf.hxx | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/cpu/mips/o2dprintf.hxx | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/cpu/mips/o2dprintf.hxx | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Ryan Holtz
static char digit[] = "0123456789abcdef";
static void dprintdec(int64_t val, bool zeropad, int size)
{
if (val == 0 && !zeropad)
{
printf("0");
return;
}
char dc[22];
for (int rem = 0; rem < 22; rem++) dc[rem] = '0';
int ptr = 0;
int64_t v = val;
char c = ' ';
if (val < 0)
{
c = '-';
val = -val;
}
int indx1 = 0;
while (v > 10)
{
int64_t rem = v / 10;
int indx = v - (rem * 10);
dc[ptr] = digit[indx];
v = rem;
if (indx != 0)
indx1 = ptr;
ptr += 1;
}
dc[ptr] = digit[v];
if (v != 0)
indx1 = ptr; // the leading non zero digit.
if (zeropad && size != 0)
ptr = size;
else
ptr = indx1; // don't print leading 0s
if (c == '-')
printf("-");
while (ptr >= 0)
{
printf("%c", dc[ptr]);
ptr -= 1;
}
}
static void dprintudec(uint64_t val, bool zeropad, int size)
{
if (val == 0 && !zeropad)
{
printf("0");
return;
}
char dc[22];
for (int rem = 0; rem < 22; dc[rem++] = '0');
int ptr = 0;
uint64_t v = val;
int indx1 = 0;
while (v > 10)
{
uint64_t rem = v / 10;
int indx = v - (rem * 10);
dc[ptr] = digit[indx];
v = rem;
if (indx != 0)
indx1 = ptr;
ptr += 1;
}
dc[ptr] = digit[v];
if (v != 0)
indx1 = ptr; // the leading non zero digit.
if (zeropad && size != 0)
ptr = size;
else
ptr = indx1; // don't print leading 0s
while (ptr >= 0)
{
printf("%c", dc[ptr]);
ptr -= 1;
}
}
static void dprinthex(uint64_t val, bool zeropad, int pos)
{
if (val == 0 && !zeropad)
{
printf("0");
return;
}
int pcount = pos;
int indx = 0;
char c;
while (pcount >= 0)
{
if (pcount == 0)
c = digit[val & 0xf];
else
c = digit[(val >> pcount) & 0xf];
if ((c == 'X') && (c > '9'))
c = c - 'a' + 'A';
if (c != '0')
{
indx += 1;
printf("%c", c);
}
else
{
if (zeropad || indx != 0)
printf("%c", c);
}
pcount -= 4;
}
}
void dprintoct(uint64_t val, bool zeropad, int pos)
{
if (val == 0 && !zeropad)
{
printf("0");
return;
}
int pcount = pos;
int indx = 0;
char c;
while (pcount >= 0)
{
if (pcount == 0)
c = digit[val & 0x7];
else
c = digit[(val >> pcount) & 0x7];
if (c != '0')
{
indx += 1;
printf("%c", c);
}
else
{
if (zeropad || indx != 0)
printf("%c", c);
}
pcount -= 3;
}
}
#define Bhex 4
#define Shex 12
#define Ihex 28
#define Lhex 60
#define Boct 3
#define Soct 15
#define Ioct 30
#define Loct 63
static uint64_t dprintf_get_arg64(uint8_t *buf, uint32_t &curr)
{
curr = (curr + 3) & ~3;
const uint64_t ret = ((uint64_t)buf[curr+0] << 56) | ((uint64_t)buf[curr+1] << 48) | ((uint64_t)buf[curr+2] << 40) | ((uint64_t)buf[curr+3] << 32) |
((uint64_t)buf[curr+4] << 24) | ((uint64_t)buf[curr+5] << 16) | ((uint64_t)buf[curr+6] << 8) | buf[curr+7];
curr += 8;
return ret;
}
static uint32_t dprintf_get_arg32(uint8_t *buf, uint32_t &curr)
{
curr = (curr + 3) & ~3;
const uint32_t ret = ((uint32_t)buf[curr+0] << 24) | ((uint32_t)buf[curr+1] << 16) | ((uint32_t)buf[curr+2] << 8) | buf[curr+3];
curr += 4;
return ret;
}
static uint16_t dprintf_get_arg16(uint8_t *buf, uint32_t &curr)
{
curr = (curr + 1) & ~1;
const uint16_t ret = ((uint16_t)buf[curr+0] << 8) | buf[curr+1];
curr += 2;
return ret;
}
static uint8_t dprintf_get_arg8(uint8_t *buf, uint32_t &curr)
{
const uint8_t ret = buf[curr++];
return ret;
}
void mips3_device::do_o2_dprintf(uint32_t fmt_addr, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t stack)
{
char buf[4096];
uint8_t argbuf[4096];
int idx = 0;
uint8_t byte_val = 0;
fmt_addr &= 0x1fffffff;
argbuf[0] = (uint8_t)(a1 >> 24);
argbuf[1] = (uint8_t)(a1 >> 16);
argbuf[2] = (uint8_t)(a1 >> 8);
argbuf[3] = (uint8_t)a1;
argbuf[4] = (uint8_t)(a2 >> 24);
argbuf[5] = (uint8_t)(a2 >> 16);
argbuf[6] = (uint8_t)(a2 >> 8);
argbuf[7] = (uint8_t)a2;
argbuf[8] = (uint8_t)(a3 >> 24);
argbuf[9] = (uint8_t)(a3 >> 16);
argbuf[10] = (uint8_t)(a3 >> 8);
argbuf[11] = (uint8_t)a3;
stack &= 0x1fffffff;
for (int i = 0; i < 4096-12; i++)
{
argbuf[i+12] = m_program->read_byte(i+stack);
}
uint32_t argcurr = 0;
do
{
byte_val = m_program->read_byte(fmt_addr++);
buf[idx++] = (char)byte_val;
} while(byte_val != 0);
char *p = buf;
char errQ[3];
int state = 0;
int size = 0;
int errP = 0;
bool zeropad = false;
while (*p)
{
switch (state)
{
case 0:
if (*p != '%')
{
printf("%c", *p);
}
else
{
errQ[errP++] = '%';
state = 1;
}
p++;
break;
case 1: // check for zero padding
state = 2;
if (*p == '0')
{
errQ[errP++] = '0';
zeropad = true;
p++;
}
else
{
zeropad = false;
}
break;
case 2: // check the size of the object to be printed
state = 3;
switch (*p)
{
case 'l':
errQ[errP++] = 'l';
size = 64;
p++;
break;
case 'h':
errQ[errP++] = 'h';
size = 16;
p++;
break;
case 'b':
errQ[errP++] = 'b';
size = 8;
p++;
break;
default:
size = 32;
break;
}
break;
case 3: // do the print
switch (*p)
{
case '%':
printf("%c", '%');
break;
case 'd':
case 'i':
switch (size)
{
case 64:
dprintdec((int64_t)dprintf_get_arg64(argbuf, argcurr), zeropad, 0);
break;
case 16: // short
dprintdec((int64_t)dprintf_get_arg16(argbuf, argcurr), zeropad, 4);
break;
case 8: // byte
dprintdec((int64_t)dprintf_get_arg8(argbuf, argcurr), zeropad, 3);
break;
default: // int
dprintdec((int64_t)dprintf_get_arg32(argbuf, argcurr), zeropad, 9);
break;
}
break;
case 'u':
switch (size)
{
case 64:
dprintudec((uint64_t)dprintf_get_arg64(argbuf, argcurr), zeropad, 0);
break;
case 16:
dprintudec((uint64_t)dprintf_get_arg16(argbuf, argcurr), zeropad, 4);
break;
case 8:
dprintudec((uint64_t)dprintf_get_arg8(argbuf, argcurr), zeropad, 3);
break;
default:
dprintudec((uint64_t)dprintf_get_arg32(argbuf, argcurr), zeropad, 9);
break;
}
break;
case 'o':
switch (size)
{
case 64:
dprintoct((uint64_t)dprintf_get_arg64(argbuf, argcurr), zeropad, Loct);
break;
case 16: // short
dprintoct((uint64_t)dprintf_get_arg16(argbuf, argcurr), zeropad, Soct);
break;
case 8: // byte
dprintoct((uint64_t)dprintf_get_arg8(argbuf, argcurr), zeropad, Boct);
break;
default: // int
dprintoct((uint64_t)dprintf_get_arg32(argbuf, argcurr), zeropad, Ioct);
break;
}
break;
case 'x':
case 'X':
switch (size)
{
case 64:
dprinthex((uint64_t)dprintf_get_arg64(argbuf, argcurr), zeropad, Lhex);
break;
case 16:
dprinthex((uint64_t)dprintf_get_arg16(argbuf, argcurr), zeropad, Shex);
break;
case 8:
dprinthex((uint64_t)dprintf_get_arg8(argbuf, argcurr), zeropad, Bhex);
break;
default:
dprinthex((uint64_t)dprintf_get_arg32(argbuf, argcurr), zeropad, Ihex);
break;
}
break;
case 'c':
printf("%c", (char)dprintf_get_arg8(argbuf, argcurr));
break;
case 's':
{
uint64_t str_addr = dprintf_get_arg64(argbuf, argcurr);
uint8_t strbyte = 0;
do
{
strbyte = m_program->read_byte(str_addr);
str_addr++;
printf("%c", (char)strbyte);
} while(strbyte);
break;
}
case '0': // error
case 'l': // error
case 'h': // error
default: // error
for (int i = 0; i < 3; i++)
printf("%c", (char)errQ[i]);
printf("%c", *p++);
break;
}
state = 0; // reset the state machine
size = 0; // reset the size
zeropad = false; // reset the zero padding
errP = 0; // reset errQ
p++;
}
}
}
| 19.132678 | 149 | 0.550019 | [
"object"
] |
8b5417d02ccfe422095420a62cda3eb89a596a43 | 1,588 | hpp | C++ | src/include/zap/zap/graph.hpp | chybz/zap | ccc67d85def09faa962e44b9e36ca414207d4ec3 | [
"MIT"
] | null | null | null | src/include/zap/zap/graph.hpp | chybz/zap | ccc67d85def09faa962e44b9e36ca414207d4ec3 | [
"MIT"
] | null | null | null | src/include/zap/zap/graph.hpp | chybz/zap | ccc67d85def09faa962e44b9e36ca414207d4ec3 | [
"MIT"
] | null | null | null | #pragma once
#include <functional>
#include <string>
#include <unordered_map>
#include <stack>
#include <zap/types.hpp>
namespace zap {
class graph
{
public:
graph();
graph(const strings& names);
graph(const graph& other) = default;
graph(graph&& other) = default;
graph& operator=(const graph& other) = default;
graph& operator=(graph&& other) = default;
virtual ~graph();
void add_node(const std::string& name, const std::string& from = {});
void add_nodes(const strings& names, const std::string& from = {});
void add_nodes(const string_set& names, const std::string& from = {});
void add_edge(const std::string& from, const std::string& to);
void build();
void clear();
// From least to most dependent
const strings& ordered() const;
// From most to least dependent
const strings& reversed() const;
bool is_tree() const;
private:
struct node
{
std::string name;
int index;
int low_link;
bool on_stack;
string_set edges;
std::size_t dep_count = 0;
void reset()
{
index = -1;
low_link = -1;
on_stack = false;
}
};
using node_ref = std::reference_wrapper<node>;
using node_map = std::unordered_map<std::string, node>;
using node_stack = std::vector<node_ref>;
void reset();
void order_func(
node& v,
strings& ordered,
node_stack& st,
int& index
);
node_map nodes_;
strings ordered_;
strings reversed_;
};
}
| 19.85 | 74 | 0.595088 | [
"vector"
] |
8b6a08ed500c7d5ab61a5a3da9458ce83908ed01 | 9,222 | cpp | C++ | Assignment 3/assignment3/src/base/skeleton.cpp | Yanko96/CS-C3100-Computer-Graphics | 83b369a6fd5723f53b6ba1c84e8e8babd750f562 | [
"MIT"
] | null | null | null | Assignment 3/assignment3/src/base/skeleton.cpp | Yanko96/CS-C3100-Computer-Graphics | 83b369a6fd5723f53b6ba1c84e8e8babd750f562 | [
"MIT"
] | null | null | null | Assignment 3/assignment3/src/base/skeleton.cpp | Yanko96/CS-C3100-Computer-Graphics | 83b369a6fd5723f53b6ba1c84e8e8babd750f562 | [
"MIT"
] | null | null | null | #include "skeleton.hpp"
#include "utility.hpp"
#include <cassert>
#include <fstream>
#include <stack>
#include <sstream>
using namespace std;
using namespace FW;
void Skeleton::setJointRotation(unsigned index, Vec3f euler_angles) {
Joint& joint = joints_[index];
// For convenient reading, we store the rotation angles in the joint
// as-is, in addition to setting the to_parent matrix to match the rotation.
joint.rotation = euler_angles;
joint.to_parent = Mat4f();
joint.to_parent.setCol(3, Vec4f(joint.position, 1.0f));
// YOUR CODE HERE (R2)
// Modify the "to_parent" matrix of the joint to match
// the given rotation Euler angles. Thanks to the line above,
// "to_parent" already contains the correct transformation
// component in the last column. Compute the rotation that
// corresponds to the current Euler angles and replace the
// upper 3x3 block of "to_parent" with the result.
// Hints: You can use Mat3f::rotation() three times in a row,
// once for each main axis, and multiply the results.
Mat3f x = Mat3f::rotation(Vec3f(1, 0, 0), euler_angles.x);
Mat3f y = Mat3f::rotation(Vec3f(0, 1, 0), euler_angles.y);
Mat3f z = Mat3f::rotation(Vec3f(0, 0, 1), euler_angles.z);
Mat3f eulerMatrix = x * y * z;
joint.to_parent.setCol(0, Vec4f(eulerMatrix.getCol(0), 0.0f));
joint.to_parent.setCol(1, Vec4f(eulerMatrix.getCol(1), 0.0f));
joint.to_parent.setCol(2, Vec4f(eulerMatrix.getCol(2), 0.0f));
}
void Skeleton::incrJointRotation(unsigned index, Vec3f euler_angles) {
setJointRotation(index, getJointRotation(index) + euler_angles);
}
void Skeleton::updateToWorldTransforms() {
// Here we just initiate the hierarchical transformation from the root node (at index 0)
// and an identity transformation, precisely as in the lecture slides on hierarchical modeling.
if (!animationMode)
updateToWorldTransforms(0, Mat4f());
else
// If we're running an animation, we need to set all of the joint rotations of the current frame
// and translate the root so it matches the animation.
setAnimationState();
}
void Skeleton::updateToWorldTransforms(unsigned joint_index, const Mat4f& parent_to_world) {
// YOUR CODE HERE (R1)
// Update transforms for joint at joint_index and its children.
joints_[joint_index].to_world = parent_to_world * joints_[joint_index].to_parent;
for (int i = 0; i < joints_[joint_index].children.size(); i++)
{
updateToWorldTransforms(joints_[joint_index].children[i], joints_[joint_index].to_world);
}
}
void Skeleton::computeToBindTransforms() {
updateToWorldTransforms();
// YOUR CODE HERE (R4)
// Given the current to_world transforms for each bone,
// compute the inverse bind pose transformations (as per the lecture slides),
// and store the results in the member to_bind_joint of each joint.
for (int i = 0; i < joints_.size(); i++)
{
joints_[i].to_bind_joint = joints_[i].to_world.inverted();
}
}
vector<Mat4f> Skeleton::getToWorldTransforms() {
updateToWorldTransforms();
vector<Mat4f> transforms;
for (const auto& j : joints_)
transforms.push_back(j.to_world);
return transforms;
}
vector<Mat4f> Skeleton::getSSDTransforms() {
updateToWorldTransforms();
// YOUR CODE HERE (R4)
// Compute the relative transformations between the bind pose and current pose,
// store the results in the vector "transforms". These are the transformations
// passed into the actual skinning code. (In the lecture slides' terms,
// these are the T_i * inv(B_i) matrices.)
vector<Mat4f> transforms;
for (int i = 0; i < joints_.size(); i++)
{
transforms.push_back(joints_[i].to_world * joints_[i].to_bind_joint);
}
return transforms;
}
float Skeleton::loadBVH(string skeleton_file) {
ifstream in(skeleton_file);
std::vector<Vec3i> axisPermutation;
string s;
string line;
while (getline(in, line))
{
stringstream stream(line);
stream >> s;
if (s == "ROOT")
{
string jointName;
stream >> jointName;
loadJoint(in, -1, jointName, axisPermutation);
}
else if (s == "MOTION")
{
loadAnim(in, axisPermutation);
}
}
float scale = normalizeScale();
// initially set to_parent matrices to identity
for (auto j = 0u; j < joints_.size(); ++j)
setJointRotation(j, Vec3f(0, 0, 0));
// this needs to be done while skeleton is still in bind pose
computeToBindTransforms();
return scale;
}
void Skeleton::loadJoint(ifstream& in, int parent, string name, std::vector<Vec3i>& axisPermutation)
{
Joint j;
j.name = name;
j.parent = parent;
bool pushed = false;
int curIdx = -1;
string s;
string line;
while (getline(in, line))
{
stringstream stream(line);
stream >> s;
if (s == "JOINT")
{
string jointName;
stream >> jointName;
loadJoint(in, curIdx, jointName, axisPermutation);
}
else if (s == "End")
{
while (getline(in, line))
{
// Read End block so it doesn't get interpreted as a closing bracket or offset keyword
stringstream end(line);
end >> s;
if (s == "}")
break;
}
}
else if (s == "}")
{
return;
}
else if (s == "CHANNELS")
{
int channelCount;
stream >> channelCount;
if (channelCount == 6)
stream >> s >> s >> s;
Vec3i permutation;
for (int i = 0; i < 3; ++i)
{
stream >> s;
if (s == "Xrotation")
permutation[0] = i;
else if (s == "Yrotation")
permutation[1] = i;
else if (s == "Zrotation")
permutation[2] = i;
}
axisPermutation.push_back(permutation);
}
else if (s == "OFFSET")
{
Vec3f pos;
stream >> pos.x >> pos.y >> pos.z;
j.position = pos;
if (!pushed)
{
pushed = true;
joints_.push_back(j);
curIdx = int(joints_.size() - 1);
if (parent != -1)
joints_[parent].children.push_back(curIdx);
}
jointNameMap[name] = curIdx;
}
}
}
void Skeleton::loadAnim(ifstream& in, std::vector<Vec3i>& axisPermutation)
{
string word;
in >> word;
int frames;
in >> frames;
animationData.resize(frames);
int frameNum = 0;
string line;
// Discard unused lines
getline(in, line);
getline(in, line);
// Load animation angle and position data for each frame
while (getline(in, line))
{
float* frameData = (float*)(animationData.data() + frameNum);
stringstream stream(line);
int i = 0;
while(stream.good())
stream >> frameData[i++];
frameNum++;
}
// Permute angle axes
Vec3f posAccum;
for (auto& f : animationData)
{
posAccum += f.position;
for (int i = 0; i < ANIM_JOINT_COUNT; ++i)
{
Vec3f angles = f.angles[i];
f.angles[i] = Vec3f(angles[axisPermutation[i].x], angles[axisPermutation[i].y], angles[axisPermutation[i].z]);
}
}
// Offset position so that average stays at origin
for (auto& f : animationData)
f.position -= posAccum / float(animationData.size());
}
void Skeleton::load(string skeleton_file) {
ifstream in(skeleton_file);
Joint joint;
Vec3f pos;
int parent;
string name;
unsigned current_joint = 0;
while (in.good()) {
in >> pos.x >> pos.y >> pos.z >> parent >> name;
joint.name = name;
joint.parent = parent;
// set position of joint in parent's space
joint.position = pos;
if (in.good()) {
joints_.push_back(joint);
jointNameMap[name] = int(joints_.size() - 1);
if (current_joint == 0) {
assert(parent == -1 && "first node read should always be the root node");
} else {
assert(parent != -1 && "there should not be more than one root node");
joints_[parent].children.push_back(current_joint);
}
++current_joint;
}
}
// initially set to_parent matrices to identity
for (auto j = 0u; j < joints_.size(); ++j)
setJointRotation(j, Vec3f(0, 0, 0));
// this needs to be done while skeleton is still in bind pose
computeToBindTransforms();
}
// Make sure the skeleton is of sensible size.
// Here we just search for the largest extent along any axis and divide by twice
// that, effectively causing the model to fit in a [-0.5, 0.5]^3 cube.
float Skeleton::normalizeScale()
{
float scale = 0;
for (auto& j : joints_)
scale = max(scale, abs(j.position).max());
scale *= 2;
for (auto& j : joints_)
j.position /= scale;
for (auto& f : animationData)
f.position /= scale;
return scale;
}
string Skeleton::getJointName(unsigned index) const {
return joints_[index].name;
}
Vec3f Skeleton::getJointRotation(unsigned index) const {
return joints_[index].rotation;
}
int Skeleton::getJointParent(unsigned index) const {
return joints_[index].parent;
}
int Skeleton::getJointIndex(string name) {
return jointNameMap[name];
}
void Skeleton::setAnimationFrame(int AnimationFrame)
{
animationFrame = AnimationFrame;
animationMode = true;
}
void Skeleton::setAnimationState()
{
// No actual animation exists.
if (!animationData.size()) {
animationMode = false;
updateToWorldTransforms(0, Mat4f());
return;
}
// Get the current position in the animation..
int frame = animationFrame % animationData.size();
auto& frameData = animationData[frame];
// .. and set all joint rotations accordingly.
for (int j = 0; j < ANIM_JOINT_COUNT; ++j)
setJointRotation(j, frameData.angles[j] * FW_PI / 180.0f);
// Also translate the root to the position given in the animation description.
updateToWorldTransforms(0, Mat4f::translate(frameData.position));
} | 26.198864 | 113 | 0.687486 | [
"vector",
"model"
] |
8b6b39b046636b6482a40909b9fb30fc563776ee | 1,553 | hpp | C++ | Spades Game/Game/Handler/LightMeterHandler.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 6 | 2017-01-04T22:40:50.000Z | 2019-11-24T15:37:46.000Z | Spades Game/Game/Handler/LightMeterHandler.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 1 | 2016-09-18T19:10:01.000Z | 2017-08-04T23:53:38.000Z | Spades Game/Game/Handler/LightMeterHandler.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 2 | 2015-11-21T16:42:18.000Z | 2019-04-21T20:41:39.000Z | #ifndef CGE_LIGHT_METER_HANDLER_HPP
#define CGE_LIGHT_METER_HANDLER_HPP
#include "Game/Element/LightMeter.hpp"
#include "Game/Handler/ClientEventListener.hpp"
#include "Game/Resource/SpriteManager.hpp"
#include "Game/UI/GuiFontManager.hpp"
#include "Game/Handler/GameEventProvider.hpp"
#include "Game/Handler/SceneEventProvider.hpp"
#include "Game/Engine/LanguageManager.hpp"
namespace cge
{
class LightMeterHandler : public DynamicElement, public ClientEventListener,
public GameEventProvider, public SceneEventProvider
{
std::vector<LightMeter> m_lightMeters;
GuiFontManager* m_fontMan;
LanguageManager* m_langMan;
public:
LightMeterHandler(SpriteManager* spriteManager, int numTricks, GuiFontManager* fontMan, LanguageManager* langMan);
virtual void render(GraphicsContext* g);
virtual void elemLogic(double t);
virtual void resize(int w, int h);
virtual void playerBidChanged(int player, int newBid);
virtual void bidStateChanged(const std::vector<SpadesPointEnum> &b, const std::vector<SpadesPointEnum> &l, const std::vector<SpadesPointEnum> &t, const std::vector<SpadesPointEnum> &r, std::vector<int> bids);
virtual void playerMadeTrick(int player, SpadesPointEnum trickType);
virtual void roundEnded();
virtual void setProportions(ProportionsManager* manager);
virtual void gameBegin();
virtual void roundBegan();
virtual void playerFailedNil(int player);
virtual void bidMeterStyleChanged(bool useLights);
virtual void loadSettings( ClientShared* shared );
virtual ~LightMeterHandler(void);
};
}
#endif | 41.972973 | 210 | 0.797811 | [
"render",
"vector"
] |
8b7017432103452665ecc3f4ce70650459daf539 | 1,175 | cpp | C++ | day6.cpp | TobbeOlsson/AoC21 | 3824f2e65137270d54c99c60d1f106da556c81f2 | [
"MIT"
] | null | null | null | day6.cpp | TobbeOlsson/AoC21 | 3824f2e65137270d54c99c60d1f106da556c81f2 | [
"MIT"
] | null | null | null | day6.cpp | TobbeOlsson/AoC21 | 3824f2e65137270d54c99c60d1f106da556c81f2 | [
"MIT"
] | null | null | null | #include "readInput.h"
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <numeric>
int main(){
std::ifstream in("inputs/input_day6");
std::string line;
long long fish[10] = {};
while (std::getline(in, line)){
std::istringstream ss(line);
std::string s;
while (std::getline(ss, s, ',')){
switch (std::stoi(s)){
case 0: fish[0]++; break;
case 1: fish[1]++; break;
case 2: fish[2]++; break;
case 3: fish[3]++; break;
case 4: fish[4]++; break;
case 5: fish[5]++; break;
case 6: fish[6]++; break;
case 7: fish[7]++; break;
case 8: fish[8]++; break;
default: break;
}
}
}
for (size_t days = 0; days < 256; days++){
long long spawns = fish[0];
for (int j = 1; j < 9; j++){
fish[j - 1] = fish[j];
}
fish[6] += spawns;
fish[8] = spawns;
}
std::cout << "Fish: " << std::accumulate(std::begin(fish), std::end(fish), 0ull, std::plus<long long>()) << "\n";
return 0;
}
| 27.325581 | 117 | 0.473191 | [
"vector"
] |
8b74e91ffbcd40ad7cb48f6be619affd57f760cd | 1,022 | cpp | C++ | Codeforces/Solutions/1333D.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | Codeforces/Solutions/1333D.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | Codeforces/Solutions/1333D.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | // Problem Code: 1333D
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void head_turns(int n, int k, string& s) {
int i, j, mx = 0;
bool done = false;
vector<vector<int>> moves;
while (!done) {
done = true;
vector<int> move;
for (int i = 0; i < n - 1; i++)
if (s[i] == 'R' && s[i + 1] == 'L') {
mx++;
done = false;
swap(s[i], s[i + 1]);
move.push_back(++i);
}
if (!done)
moves.push_back(move);
}
if (moves.size() > k || mx < k) {
cout << "-1" << '\n';
return;
}
// endl is slow as it flushes the buffer each time hence '\n'
i = j = 0;
while (i < moves.size()) {
if (moves.size() - i < k)
cout << 1 << " " << moves[i][j++] << '\n';
else {
cout << moves[i].size() - j;
while (j < moves[i].size())
cout << " " << moves[i][j++];
cout << '\n';
}
if (j == moves[i].size()) {
j = 0;
i++;
}
k--;
}
}
int main() {
int n, k;
string s;
cin >> n >> k >> s;
head_turns(n, k, s);
return 0;
} | 17.322034 | 62 | 0.486301 | [
"vector"
] |
8b78c31c5fe3ff19e322a7b78e3ea8bcd0dc999c | 2,421 | hpp | C++ | ige/include/ige/plugin/TransformPlugin.hpp | NoOverflow/ige | 4859a97e5d3f75f45d8db578e476ef55bc1df95c | [
"MIT"
] | null | null | null | ige/include/ige/plugin/TransformPlugin.hpp | NoOverflow/ige | 4859a97e5d3f75f45d8db578e476ef55bc1df95c | [
"MIT"
] | null | null | null | ige/include/ige/plugin/TransformPlugin.hpp | NoOverflow/ige | 4859a97e5d3f75f45d8db578e476ef55bc1df95c | [
"MIT"
] | null | null | null | #ifndef F4DF8A5F_1CCD_443F_8D71_8A439340E94F
#define F4DF8A5F_1CCD_443F_8D71_8A439340E94F
#include "ige/ecs/VecStorage.hpp"
#include "ige/ecs/World.hpp"
#include <optional>
#include <unordered_set>
#include <vector>
#include <glm/ext/quaternion_float.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec3.hpp>
; // TODO: https://bit.ly/3hhMJ58
namespace ige::plugin::transform {
/**
* @brief Component giving a parent to an entity.
*/
struct Parent {
ecs::EntityId entity;
Parent(ecs::EntityId parent_entity);
bool operator==(const Parent&) const = default;
};
/**
* @brief Component holding a list of entities that have this entity as their
* parent.
*
* This component is automatically added and updated by the parenting system.
* Any modification made to it will be overwritten by the engine!
*/
struct Children {
std::unordered_set<ecs::EntityId> entities;
};
class Transform {
private:
glm::vec3 m_translation = glm::vec3(0.0f);
glm::quat m_rotation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
glm::vec3 m_scale = glm::vec3(1.0f);
bool m_dirty = false;
glm::mat4 m_local_to_world { 1.0f };
glm::mat4 m_world_to_local { 1.0f };
public:
using Storage = ecs::VecStorage<Transform>;
static Transform from_pos(glm::vec3 position);
constexpr explicit Transform() = default;
glm::vec3 translation() const;
glm::quat rotation() const;
glm::vec3 scale() const;
Transform& set_translation(glm::vec3) &;
Transform& set_rotation(glm::quat) &;
Transform& set_scale(glm::vec3) &;
Transform& set_scale(float) &;
Transform& translate(glm::vec3);
Transform& rotate(glm::vec3);
Transform& rotate(glm::quat);
Transform& scale(glm::vec3);
Transform&
look_at(glm::vec3 target, glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f)) &;
Transform set_translation(glm::vec3) &&;
Transform set_rotation(glm::quat) &&;
Transform set_scale(glm::vec3) &&;
Transform set_scale(float) &&;
Transform
look_at(glm::vec3 target, glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f)) &&;
void force_update(const glm::mat4& parent);
bool needs_update() const;
const glm::mat4& local_to_world() const;
const glm::mat4& world_to_local() const;
};
class TransformPlugin : public core::App::Plugin {
public:
void plug(core::App::Builder&) const override;
};
}
#endif /* F4DF8A5F_1CCD_443F_8D71_8A439340E94F */
| 25.484211 | 77 | 0.684015 | [
"vector",
"transform"
] |
8b7a57d77948ae6fbc0b9cd1c29554f34a5410bf | 1,822 | cpp | C++ | Geeks4Geeks/G4G-Solutions/topological_sort.cpp | vijay-jaisankar/Competetive_programming | 860c165ce42337a7380112938b14772e6a553647 | [
"MIT"
] | null | null | null | Geeks4Geeks/G4G-Solutions/topological_sort.cpp | vijay-jaisankar/Competetive_programming | 860c165ce42337a7380112938b14772e6a553647 | [
"MIT"
] | null | null | null | Geeks4Geeks/G4G-Solutions/topological_sort.cpp | vijay-jaisankar/Competetive_programming | 860c165ce42337a7380112938b14772e6a553647 | [
"MIT"
] | null | null | null | // https://practice.geeksforgeeks.org/problems/topological-sort/1
using namespace std;
vector <int> topoSort(int N, vector<int> adj[]);
/* Function to check if elements returned by user
* contains the elements in topological sorted form
* V: number of vertices
* *res: array containing elements in topological sorted form
* adj[]: graph input
*/
bool check(int V, vector <int> &res, vector<int> adj[]) {
vector<int> map(V, -1);
for (int i = 0; i < V; i++) {
map[res[i]] = i;
}
for (int i = 0; i < V; i++) {
for (int v : adj[i]) {
if (map[i] > map[v]) return false;
}
}
return true;
}
// Driver Code
int main() {
int T;
cin >> T;
while (T--) {
int N, E;
cin >> E >> N;
int u, v;
vector<int> adj[N];
for (int i = 0; i < E; i++) {
cin >> u >> v;
adj[u].push_back(v);
}
vector <int> res = topoSort(N, adj);
cout << check(N, res, adj) << endl;
}
}// } Driver Code Ends
// The Graph structure is as folows
/* Function which sorts the graph vertices in topological form
* N: number of vertices
* adj[]: input graph
*/
void explore(vector<int>adj[], int v,stack<int>&s,bool vis[])
{
vis[v] = true;
for(auto u : adj[v])
{
if(!vis[u])
{
explore(adj,u,s,vis);
}
}
s.push(v);
}
void bfs(vector<int>adj[], int n,stack<int>&s)
{
bool vis[n] = {false};
for(int i=0;i<n;i++)
{
if(!vis[i])
{
explore(adj,i,s,vis);
}
}
}
vector<int> topoSort(int n, vector<int> adj[]) {
stack<int>s;
bfs(adj,n,s);
vector<int>v;
while(!s.empty())
{
int x = s.top();
v.push_back(x);
s.pop();
}
return v;
}
| 19.382979 | 65 | 0.498902 | [
"vector"
] |
8b8318a01bbfa27c49c0989e5d98ec917038cd63 | 12,678 | cpp | C++ | correspondences/graph/src/graph.cpp | jwdinius/nmsac | b765be4340cf8367e1af345dc156597ce425c818 | [
"Apache-2.0"
] | null | null | null | correspondences/graph/src/graph.cpp | jwdinius/nmsac | b765be4340cf8367e1af345dc156597ce425c818 | [
"Apache-2.0"
] | 8 | 2020-07-19T23:38:48.000Z | 2020-09-14T22:36:30.000Z | correspondences/graph/src/graph.cpp | jwdinius/nmsac | b765be4340cf8367e1af345dc156597ce425c818 | [
"Apache-2.0"
] | 1 | 2020-08-06T06:59:04.000Z | 2020-08-06T06:59:04.000Z | //! c/c++ headers
#include <cstdlib>
#include <limits>
#include <vector>
//! dependency headers
//! project headers
#include "correspondences/common/utilities.hpp"
#include "correspondences/graph/graph.hpp"
//! namespaces
namespace cg = correspondences::graph;
/** UndirectedGraph::UndirectedGraph()
* @brief default undirected graph constructor
*
* @param[in]
* @return
*
* @note creates an empty graph
*/
// LCOV_EXCL_START
cg::UndirectedGraph::UndirectedGraph() { }
// LCOV_EXCL_STOP
/**
* UndirectedGraph::UndirectedGraph(vertices_t const&, edges_t const&)
*
* @brief constructor that builds undirected graph from input
* vertices and edges
*
* @param[in] vertices_t const&, graph vertices
* @param[in] edges_t const&, graph edges
*
* @note the application will exit with error if graph is invalid
* @see UndirectedGraph::validate_graph() method
*/
cg::UndirectedGraph::UndirectedGraph(vertices_t const & vertices,
edges_t const & edges) : vertices_(vertices), edges_(edges) {
if (!validate_graph()) {
std::cerr << "Graph is invalid!!" << std::endl;
exit(INVALID_GRAPH);
}
std::for_each(edges_.cbegin(), edges_.cend(), [&](auto &e){ add_adjacency(e); });
}
/**
* UndirectedGraph::UndirectedGraph(arma::mat const&, arma::mat const&,
* double const&, double const &)
*
* @brief constructor that builds graph from source and target point clouds,
* as well as consistency thresholds
*
* @param[in] arma::mat const&, source point cloud
* @param[in] arma::mat const&, target point cloud
* @param[in] double const&, distance between correspondences threshold
* @param[in] double const&, pairwise distance threshold - reject pairwise
* consideration when points in a set are too close
*/
cg::UndirectedGraph::UndirectedGraph(arma::mat const & source_pts,
arma::mat const & target_pts, double const & eps,
double const & pw_thresh) {
size_t const & m = source_pts.n_cols;
size_t const & n = target_pts.n_cols;
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
for (size_t k = 0; k < m; ++k) {
for (size_t l = 0; l < n; ++l) {
if (i != k && j != l) {
arma::vec3 const si = arma::vec3(source_pts.col(i));
arma::vec3 const tj = arma::vec3(target_pts.col(j));
arma::vec3 const sk = arma::vec3(source_pts.col(k));
arma::vec3 const tl = arma::vec3(target_pts.col(l));
double const c = consistency(si, tj, sk, tl);
if (c <= eps
&& arma::norm(si - sk, 2) >= pw_thresh
&& arma::norm(tj - tl, 2) >= pw_thresh) {
vertex_t const v1 = i*n + j;
vertex_t const v2 = k*n + l;
add_edge({v1, v2});
}
}
}
}
}
}
}
// LCOV_EXCL_START
/** UndirectedGraph::~UndirectedGraph()
* @brief destructor for constrained objective function
*
* @param[in]
* @return
*
* @note nothing to do; resources are automatically deleted
*/
cg::UndirectedGraph::~UndirectedGraph() { }
// LCOV_EXCL_STOP
/**
* UndirectedGraph::add_edge(edge_t)
*
* @brief add edge to graph
*
* @param[in] vertex_t, vertex to add
*
* @note adds vertex to graph if it doesn't already exist
*/
void cg::UndirectedGraph::add_edge(edge_t e) noexcept {
auto const & v1 = e.first;
auto const & v2 = e.second;
if (v1 == v2) return;
//! v1, v2 will only be added if they are missing (see std::set docs)
add_vertex(v1);
add_vertex(v2);
edges_.insert(e);
add_adjacency(e);
}
/**
* UndirectedGraph::validate_graph()
*
* @brief validate graph based on vertices and edges declared
*
* @note a graph is valid if, for every edge, the following are true
* (1) the first vertex is in the set of vertices
* (2) the second vertex is in the set of vertices
* (3) the first and second vertex indices are unique
* @return true, if all 3 conditions are met, false otherwise
*/
bool cg::UndirectedGraph::validate_graph() const noexcept {
auto is_vertex = [&](vertex_t v) { return (vertices_.find(v) != vertices_.end()); };
for (auto &e : edges_) {
if (!is_vertex(e.first) || !is_vertex(e.second) || (e.first == e.second)) return false;
}
return true;
}
/**
* UndirectedGraph::add_vertex(vertex_t)
*
* @brief add vertex to graph
*
* @param[in] vertex_t, vertex to add
*/
void cg::UndirectedGraph::add_vertex(vertex_t v) noexcept {
vertices_.insert(v);
}
/**
* UndirectedGraph::add_adjacency(edge_t)
*
* @brief add to adjacency sets for vertices in an edge
*
* @param[in] edge_t, edge to incorporate in adjacency sets
*/
void cg::UndirectedGraph::add_adjacency(edge_t e) noexcept {
auto const & v1 = e.first;
auto const & v2 = e.second;
if (v1 == v2) return;
/**
* add_to_adj(vertex_t, vertex_t)
*
* @brief simple helper function that inserts the first vertex into the
* the second vertex's adjacency set, or creates the adjacency set if
* this is the first vertex to be added (adjacency was empty)
*
* @note this fn uses calling scope (see [&] for lambda capture)
*/
auto add_to_adj = [&](vertex_t v1, vertex_t v2) {
//! adjacency set for v1 is non-empty, so insert v2 into it
if (adjacency_.find(v1) != adjacency_.end()) {
adjacency_[v1].insert(v2);
} else {
//! adjacency set is empty, so create the adjacency set with v2 as
//! the first entry
adjacency_t s = {v2};
adjacency_.insert({v1, s});
}
};
//! adjacency is symmetric: if v2 is in v1's adjacency set, then v1 is in v2's
add_to_adj(v1, v2);
add_to_adj(v2, v1);
}
/**
* next_available_color(std::list<size_t> const&)
*
* @brief return next available color based on adjacency coloring
* @see Section 3.2 of https://arxiv.org/pdf/1902.01534.pdf
*
* @param std::list<size_t>, list of accounted for colors
* @return size_t, smallest unsigned integer not in input list
*/
size_t cg::next_available_color(std::list<size_t> const & colors) noexcept {
std::vector<size_t> count(colors.size() + 1, 0);
std::for_each(colors.cbegin(), colors.cend(), [&](auto &c){
if (c < count.size()) { ++count[c]; } } );
for (size_t c = 0; c < count.size(); ++c) {
if (count[c] == 0) return c;
}
// LCOV_EXCL_START
//! this should never be called, but tell the user (loudly) if the color is not valid
return std::numeric_limits<size_t>::signaling_NaN();
// LCOV_EXCL_STOP
}
/**
* greedy_vertices_coloring(vertices_t const&, UndirectedGraph const&)
*
* @brief create greedy coloring of vertices, based on degree of vertex
* @see Section 3.2 of https://arxiv.org/pdf/1902.01534.pdf
*
* @param vertices_t, set of vertices to color
* @param UndirectedGraph, graph containing vertices to color
* @return size_t, smallest unsigned integer not in input list
*/
cg::coloring_t cg::greedy_vertices_coloring(vertices_t const & vertices,
UndirectedGraph const & graph) noexcept {
//! create empty coloring - this will be filled later
coloring_t coloring = {};
//! create coloring helper function
auto f = [&](vertex_t v) {
auto adj = graph.get_adjacency(v);
std::list<size_t> colors = {};
for (auto &a : adj) {
if (coloring.find(a) != coloring.end()) {
colors.emplace_back( coloring[a] );
}
}
return colors;
};
//! create graph coloring based on vertex degree
std::for_each(vertices.cbegin(), vertices.cend(), [&](auto &v) {
coloring[v] = next_available_color( f(v) ); });
return coloring;
}
/**
* max_cliq_bnb_basic(UndirectedGraph const&, vertices_t const&,
* vertices_t&, vertices_t&)
*
* @brief find maximum clique using a recursive basic branch-and-bound (bnb)
* algorithm
* @see Section 3.1 of https://arxiv.org/pdf/1902.01534.pdf
*
* @param[in] UndirectedGraph, graph to find maximum clique within
* @param[in] vertices_t, set of candidate vertices to check
* @param[in][out] vertices_t&, current clique to check for optimality
* @param[in][out] vertices_t&, biggest clique found so far
*/
void cg::max_cliq_bnb_basic(UndirectedGraph const & graph, vertices_t S,
vertices_t & R, vertices_t & R_best) noexcept {
//! only execute call if set of vertices to expand is non-empty
while (!S.empty()) {
//! if the current max clique is bigger than what is possible
//! given the current expansion, the algorithm is done
if (R.size() + S.size() <= R_best.size()) return;
//! expand first vertex in vertices
auto v = *S.begin();
R.insert(v);
//! add all vertices in v's adjacency set to list of candidate vertices
vertices_t Sp;
auto adj = graph.get_adjacency(v);
std::for_each(S.cbegin(), S.cend(), [&](auto &a){
if (adj.find(a) != adj.end()) { Sp.insert(a); } });
//! if the list of vertices to expand is non-empty, make recursive call
if (!Sp.empty()) {
max_cliq_bnb_basic(graph, Sp, R, R_best);
} else if (R.size() > R_best.size()) {
//! if the current clique is bigger than the current best estimate,
//! update the estimate
R_best = R;
}
//! remove vertex from candidate expansion sets
R.extract(v);
S.extract(v);
}
}
/**
* max_cliq_bnb_color(UndirectedGraph const&, vertices_t const&,
* coloring_t const&, vertices_t&, vertices_t&)
*
* @brief find maximum clique using a recursive basic branch-and-bound (bnb)
* algorithm
* @see Section 3.1 of https://arxiv.org/pdf/1902.01534.pdf
*
* @param[in] UndirectedGraph, graph to find maximum clique within
* @param[in] vertices_t, set of candidate vertices to check
* @param[in] coloring_t, vertex coloring (@see greedy_vertices_coloring)
* @param[in][out] vertices_t&, current clique to check for optimality
* @param[in][out] vertices_t&, biggest clique found so far
*/
void cg::max_cliq_bnb_color(UndirectedGraph const & graph, vertices_t const & S,
coloring_t const & f, vertices_t & R, vertices_t & R_best) noexcept {
//! this algorithm requires a data structure sorted by vertex degree, so
//! convert the input vertices set to a list
std::list<vertex_t> S_sort(S.begin(), S.end());
//! sort the candidate list based on vertex degree - smallest to largest
S_sort.sort([&](vertex_t const & a, vertex_t const & b) {
return graph.get_adjacency(a).size() < graph.get_adjacency(b).size(); });
//! only execute call if set of vertices to expand is non-empty
while (!S_sort.empty()) {
//! consider vertex with largest degree - this is the last element of S_sort
auto v = *S_sort.rbegin();
//! if the current max clique is bigger than what is possible
//! given the current expansion (and coloring), the algorithm is done
if (R.size() + f.at(v) < R_best.size()) return;
//! add v to current clique
R.insert(v);
//! add all vertices in v's adjacency set to list of candidate vertices
vertices_t Sp;
auto adj = graph.get_adjacency(v);
std::for_each(S.cbegin(), S.cend(), [&](auto &a){
if (adj.find(a) != adj.end()) { Sp.insert(a); } });
//! if the list of vertices to expand is non-empty, make recursive call
if (!Sp.empty()) {
auto fp = greedy_vertices_coloring(Sp, graph);
max_cliq_bnb_color(graph, Sp, fp, R, R_best);
} else if (R.size() > R_best.size()) {
//! if the current clique is bigger than the current best estimate,
//! update the estimate
R_best = R;
}
//! remove vertex from candidate expansion sets
R.extract(v);
S_sort.remove(v);
}
}
/**
* find_max_clique(UndirectedGraph const&, max_clique_algo_e const&,
* vertices_t&)
*
* @brief find maximum clique using a recursive basic branch-and-bound (bnb)
* algorithm
* @see Section 3.1 of https://arxiv.org/pdf/1902.01534.pdf
*
* @param[in] UndirectedGraph, graph to find maximum clique within
* @param[in] max_clique_algo_e, algorithm to use
* @param[in][out] vertices_t&, maximum clique of graph
*/
void cg::find_max_clique(UndirectedGraph const & graph, max_clique_algo_e const & algo,
vertices_t & R_best) noexcept {
//! make sure that R_best is currently empty
R_best.clear();
//! initialize clique container
cg::vertices_t R = {};
if (algo == max_clique_algo_e::bnb_basic) {
//! call basic bnb implementation
max_cliq_bnb_basic(graph, graph.get_vertices(), R, R_best);
} else if (algo == max_clique_algo_e::bnb_color) {
//! call colored bnb implementation
//! - first, create coloring of vertices in the entire graph to improve
//! - candidate vertices selection
auto f = greedy_vertices_coloring(graph.get_vertices(), graph);
max_cliq_bnb_color(graph, graph.get_vertices(), f, R, R_best);
}
}
| 33.015625 | 91 | 0.660909 | [
"vector"
] |
8b8c46b63616c4769e8eba91891b263a91d87ece | 1,196 | cpp | C++ | Days 051 - 060/Day 60/SplitSetIntoEqualSubsets.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 051 - 060/Day 60/SplitSetIntoEqualSubsets.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 051 - 060/Day 60/SplitSetIntoEqualSubsets.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
bool CanSplitEquallyHelper(const std::vector<int>& numbers, unsigned int startIndex, unsigned int endIndex, int firstSum, int secondSum) noexcept
{
if (startIndex >= endIndex)
{
return false;
}
else if (firstSum == secondSum)
{
return true;
}
else
{
return CanSplitEquallyHelper(numbers, startIndex + 1, endIndex, firstSum + numbers[startIndex], secondSum - numbers[startIndex]) ||
CanSplitEquallyHelper(numbers, startIndex, endIndex - 1, firstSum + numbers[endIndex], secondSum - numbers[endIndex]);
}
}
bool CanSplitEqually(const std::vector<int>& numbers)
{
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
if (numbers.empty() || sum % 2 == 1)
{
return false;
}
std::vector<int> sortedNumbers = numbers;
std::sort(sortedNumbers.begin(), sortedNumbers.end());
return CanSplitEquallyHelper(sortedNumbers, 0, numbers.size() - 1, 0, sum);
}
int main(int argc, char* argv[])
{
std::cout << std::boolalpha;
std::cout << CanSplitEqually({ 15, 5, 20, 10, 35, 15, 10 }) << "\n";
std::cout << CanSplitEqually({ 15, 5, 20, 10, 35 }) << "\n";
std::cin.get();
return 0;
}
| 24.916667 | 145 | 0.680602 | [
"vector"
] |
8b9b0d42867636d8e09c03726c778a196e9b0517 | 2,729 | hpp | C++ | RKF/RKF_class.hpp | dkaramit/NaBBODES | abbd276623a01c2ea95c089190def6d66478bac5 | [
"MIT"
] | null | null | null | RKF/RKF_class.hpp | dkaramit/NaBBODES | abbd276623a01c2ea95c089190def6d66478bac5 | [
"MIT"
] | 1 | 2021-07-19T17:08:25.000Z | 2021-07-19T17:08:25.000Z | RKF/RKF_class.hpp | dkaramit/NaBBODES | abbd276623a01c2ea95c089190def6d66478bac5 | [
"MIT"
] | null | null | null | #ifndef RKF_class
#define RKF_class
#include<array>
#include<vector>
#include<functional>
//This is a general implementation of explicit embedded RK solver of
// a system of differential equations in the interval [0,tmax].
/*
diffeq is a class of the system of equations to be solved
N_eqs is ten number of equations to be solved
RKF_method is the method (the DormandPrince seems to be the standard here)
*/
template<unsigned int N_eqs, class RK_method, class LD>
class RKF{
private://There is no reason to make things private (if you break it it's not my fault)...
using diffeq=std::function<void(std::array<LD, N_eqs> &lhs, std::array<LD, N_eqs> &y, LD t)>;
LD hmin, hmax, abs_tol, rel_tol, beta, fac_max, fac_min;
LD h_old, delta_acc, delta_rej;//these will be initialized at the beginning of next_step
unsigned int max_N;
bool h_stop;//h_stop becomes true when suitable stepsize is found.
public:
//Inputs. The initial condition is given as a Array (the type is users choice as long as it can be called with [])
diffeq dydt;
LD tmax, h, tn;
std::array<LD, N_eqs> yprev;
std::vector<LD> time;
std::array<std::vector<LD>, N_eqs> solution;
std::array<std::vector<LD>, N_eqs> error;
std::array<std::array<LD,RK_method::s>,N_eqs> k;
// LD k[N_eqs][RK_method::s];
//these are here to hold the k's, sum_i b_i*k_i, sum_i b_i^{\star}*k_i, and sum_j a_{ij}*k_j
std::array<LD,N_eqs> ak, bk, bstark;
// abs_delta=abs(ynext-ynext_star)
std::array<LD,N_eqs> abs_delta;
std::array<LD,N_eqs> ynext;//this is here to hold the prediction
std::array<LD,N_eqs> ynext_star;//this is here to hold the second prediction
RKF(diffeq dydt, const std::array<LD,N_eqs>& init_cond, LD tmax,
LD initial_step_size=1e-5, LD minimum_step_size=1e-11, LD maximum_step_size=1e-3,
int maximum_No_steps=1000000, LD absolute_tolerance=1e-8,LD relative_tolerance=1e-8,
LD beta=0.85,LD fac_max=3, LD fac_min=0.3);
~RKF()=default;
/*-------------------it would be nice to have a way to define these sums more generaly-----------------*/
void next_step();
void calc_k();
void sum_ak(unsigned int stage); // calculate sum_j a_{ij}*k_j and passit to this->ak
void sum_bk();// calculate sum_i b_i*k_i and passit to this->bk
void sum_bstark();// calculate sum_i b^{\star}_i*k_i and passit to this->bk
void step_control();//adjust stepsize until error is acceptable
void solve();
};
#endif
| 35.907895 | 122 | 0.632833 | [
"vector"
] |
8ba462a67c0a51e59c044829c63c29e180318e6b | 3,513 | cc | C++ | kernel/ocl/algebra/quaternion.cc | nthend/hypertrace | 5072849f8a10465ba1260626fbef6b013d756f90 | [
"Apache-2.0",
"MIT"
] | 5 | 2020-05-20T21:04:49.000Z | 2021-07-08T05:29:41.000Z | kernel/ocl/algebra/quaternion.cc | nthend/hypertrace | 5072849f8a10465ba1260626fbef6b013d756f90 | [
"Apache-2.0",
"MIT"
] | 2 | 2021-01-27T09:07:22.000Z | 2021-02-22T11:17:11.000Z | kernel/ocl/algebra/quaternion.cc | nthend/hypertrace | 5072849f8a10465ba1260626fbef6b013d756f90 | [
"Apache-2.0",
"MIT"
] | 2 | 2020-04-30T04:46:07.000Z | 2021-02-02T21:11:39.000Z | #include "quaternion.hh"
quat q_conj(quat a) {
return q_new(a.x, -a.yzw);
}
real q_abs2(quat a) {
return dot(a, a);
}
real q_abs(quat a) {
return length(a);
}
quat q_mul(quat a, quat b) {
return q_new(
a.x*b.x - a.y*b.y - a.z*b.z - a.w*b.w,
a.x*b.y + a.y*b.x + a.z*b.w - a.w*b.z,
a.x*b.z + a.z*b.x - a.y*b.w + a.w*b.y,
a.x*b.w + a.w*b.x + a.y*b.z - a.z*b.y
);
}
quat qc_mul(quat a, comp b) {
return q_new(
a.x*b.x - a.y*b.y,
a.x*b.y + a.y*b.x,
a.z*b.x + a.w*b.y,
a.w*b.x - a.z*b.y
);
}
quat cq_mul(comp a, quat b) {
return q_new(
a.x*b.x - a.y*b.y,
a.x*b.y + a.y*b.x,
a.x*b.z - a.y*b.w,
a.x*b.w + a.y*b.z
);
}
quat q_inverse(quat a) {
return q_conj(a)/q_abs2(a);
}
quat q_div(quat a, quat b) {
return q_mul(a, q_inverse(b));
}
quat qc_div(quat a, comp b) {
return qc_mul(a, c_inverse(b));
}
quat cq_div(comp a, quat b) {
return cq_mul(a, q_inverse(b));
}
#ifdef UNITTEST
#include <gtest/gtest.h>
#include <vector>
#include <utility>
#include <functional>
class QuaternionTest : public testing::Test {
protected:
TestRng<quat> qrng = TestRng<quat>(0xfeed);
};
TEST_F(QuaternionTest, imaginary_units) {
ASSERT_EQ(q_mul(QI, QI), approx(-Q1));
ASSERT_EQ(q_mul(QJ, QJ), approx(-Q1));
ASSERT_EQ(q_mul(QK, QK), approx(-Q1));
ASSERT_EQ(q_mul(q_mul(QI, QJ), QK), approx(-Q1));
ASSERT_EQ(q_mul(QI, QJ), approx(QK));
ASSERT_EQ(q_mul(QJ, QK), approx(QI));
ASSERT_EQ(q_mul(QK, QI), approx(QJ));
ASSERT_EQ(q_mul(QJ, QI), approx(-QK));
ASSERT_EQ(q_mul(QK, QJ), approx(-QI));
ASSERT_EQ(q_mul(QI, QK), approx(-QJ));
}
TEST_F(QuaternionTest, inversion) {
for (int i = 0; i < TEST_ATTEMPTS; ++i) {
quat a = qrng.nonzero();
ASSERT_EQ(q_div(a, a), approx(Q1));
}
}
TEST_F(QuaternionTest, law_of_cosines) {
for (int i = 0; i < TEST_ATTEMPTS; ++i) {
quat a = qrng.normal(), b = qrng.normal();
ASSERT_EQ(q_abs2(a) + q_abs2(b) + 2*dot(a, b), Approx(q_abs2(a + b)));
}
}
TEST_F(QuaternionTest, conjugation) {
for (int i = 0; i < TEST_ATTEMPTS; ++i) {
quat a = qrng.normal();
ASSERT_EQ(q_mul(a, q_conj(a)), approx(q_abs2(a)*Q1));
ASSERT_EQ(q_mul(q_conj(a), a), approx(q_abs2(a)*Q1));
}
}
TEST_F(QuaternionTest, derivation) {
std::vector<std::pair<
std::function<quat(quat)>,
std::function<quat(quat, quat)>
>> cases = {
std::make_pair(
[](quat p) { return p; },
[](quat, quat v) { return v; }
),
std::make_pair(
[](quat p) { return q_mul(p, p); },
[](quat p, quat v) { return q_mul(p, v) + q_mul(v, p); }
),
std::make_pair(
[](quat p) { return q_inverse(p); },
[](quat p, quat v) {
real p2 = q_abs2(p);
return (q_conj(v) - (2*dot(p, v)/p2)*q_conj(p))/p2;
}
)
};
const real DEPS = sqrt(EPS);
for (auto p : cases) {
auto f = p.first;
auto dfdv = p.second;
for (int i = 0; i < TEST_ATTEMPTS; ++i) {
quat p = qrng.normal();
quat v = qrng.unit();
quat deriv = dfdv(p, v);
real dabs = q_abs(deriv);
ASSERT_EQ(
(f(p + DEPS*v) - f(p))/DEPS,
approx(deriv).epsilon(sqrt(DEPS)*dabs)
);
}
}
}
#endif // UNITTEST
| 24.227586 | 78 | 0.509821 | [
"vector"
] |
8baa1573732e7cc176cf774599f3e5c904780eea | 2,919 | cpp | C++ | src/main.cpp | junjieqian/BP-Neural-Network | b8bb899c6eb98e26d5bbd1d43d1fac83885f67ef | [
"MIT"
] | 3 | 2016-06-18T04:23:46.000Z | 2021-09-11T06:03:44.000Z | src/main.cpp | junjieqian/BP-Neural-Network | b8bb899c6eb98e26d5bbd1d43d1fac83885f67ef | [
"MIT"
] | null | null | null | src/main.cpp | junjieqian/BP-Neural-Network | b8bb899c6eb98e26d5bbd1d43d1fac83885f67ef | [
"MIT"
] | null | null | null | /* main.cpp
* This is taken as demo main function
* Junjie Qian, jqian.unl@gmail.com
*/
#include <fstream> // std::fstream
//#include <stdio.h>
#include <stdlib.h> // atoi
#include <iostream> // std::cout
#include <string> // std::string
#include <sstream>
#include "trainner.h"
#include "tester.h"
using namespace std;
// everything starts from here
int main(int argc, char ** argv) {
if (argc>1) {
printf("No arguments taken, modify the config file instead\n");
return 0;
}
ifstream fp("config");
string line;
string trainfile = "";
string testfile = "";
string trainset = "model";
string resfile = "results";
int inNode = 19;
int hideNode = 30;
int outNode = 1;
double threshold = 0.9;
int iterations = 400;
double learningRate = 0.2;
double momentum = 0.2;
if (fp) {
while(getline(fp, line)) {
stringstream ss(line);
string a, b;
ss >> a >> b;
if (a == "TrainDataset:") trainfile = b;
else if (a == "TestDataset:") testfile = b;
else if (a == "TrainModel: ") trainset = b;
else if (a == "TestingResults: ") resfile = b;
else if (a == "InputNodeNumber:") inNode = atoi(b.c_str());
else if (a == "HideNodeNumber:") hideNode = atoi(b.c_str());
else if (a == "OutputNodeNumber:") outNode = atoi(b.c_str());
else if (a == "Iterations:") iterations = atoi(b.c_str());
else if (a == "LearningRate:") learningRate = atof(b.c_str());
else if (a == "Threshold:") threshold = atof(b.c_str());
else if (a == "Momentum:") momentum = atof(b.c_str());
else cout << "Attention: argument " << a << " not recognized\n";
}
} else {
printf("Config file needed\n");
return 0;
}
cout << "========Defined parameters include: ========\n\tDataSet name: " << trainfile
<< "\n\tInput node number: " << inNode << "\n\tHide node number: "
<< hideNode << "\n\tOutput node number: " << outNode << "\n\tMax Iterations: "
<< iterations << "\n\tLearning Rate: " << learningRate << "\n\tThreshold: "
<< threshold << "\n\tMomentum: " << momentum << endl;
/******************** Parameters set ***********************/
Trainner tr(inNode, hideNode, outNode, learningRate, momentum, iterations);
int max_match = 300000;
cout << "============Trainning=================\n";
tr.train(trainfile, max_match, threshold);
cout << "===== Train finished, dumping models ===== \n";
tr.dumpNetWork(trainset);
cout << "============Testing=================\n";
cout << "\tTrainning model file is: " << trainset << "\n\tTesting file is: "
<< testfile << "\n\tResults file is: " << resfile << endl;
Tester te(trainset);
te.test(testfile, inNode, resfile);
return 0;
} | 36.037037 | 90 | 0.539911 | [
"model"
] |
8bba375f02db6d7157f7371d283b81a5e3fd0682 | 6,943 | cpp | C++ | dotnect_platform/src/data_container.cpp | vwas2/Dotnet_stack | 77edf5eb3dbea98c1a7c43868b435d862e8058d9 | [
"BSD-3-Clause"
] | null | null | null | dotnect_platform/src/data_container.cpp | vwas2/Dotnet_stack | 77edf5eb3dbea98c1a7c43868b435d862e8058d9 | [
"BSD-3-Clause"
] | null | null | null | dotnect_platform/src/data_container.cpp | vwas2/Dotnet_stack | 77edf5eb3dbea98c1a7c43868b435d862e8058d9 | [
"BSD-3-Clause"
] | null | null | null | // file: data_container.cpp, style: README.md
//
// License http://opensource.org/licenses/BSD-3-Clause
// Copyright (c) 2016 14U2g4ocMy5aB2cY4cmCtbXD6qyNQzujuA (serves donations as well)
// All rights reserved.
//
// The class object stores data for thread [i] safe access.
// Each thread has its own list of flags [j].
// -> v_dbls_[j] and v_dbls_flags_[i][j]
//
// [i] GET SET
// 0: marker_array_publisher 21
// 1:moving_average 15,20 16,17
// ?? 11,19 18
// 2:joints_publisher 18
// 3:transform_handler 11,16,18
// 4:pub_multi_array 17
// -:interactive_marker_node - 19,20,21
// -:via topic 11,15,19,20
// [j]: STRUCTURE INFO
// 0;-
// 1: acc t,j,accuracy,val1-3 accelerometer sensor
// 2: mag t,j,accuracy,val1-3 magnetometer sensor
// 3: orient t,j,accuracy,val1-3 orientation sensor
// 4: gyro t,j,accuracy,val1-3 gyroscope sensor
// 5: light light sensor
// 6: pres pressure sensor
// 7: temp, temperature sensor
// 8: prox proximity sensor
// 9: gravity gravity sensor
// 10:linacc linear accelerometer sensor (no grav)
// 11:rot t,j,accuracy,val1-4 rotation vector sensor
// 12:humid humidity sensor
// 13:ambtmp ambient temperature sensor
// 14:-
// 15:point_f1 t,j,frameCount,val1-3 kinect_tracking point (frame_1, 3D, mm, t [s])
// 16:point_f1_xma t,j,accuracy,val1-3 same point averaged [ns]
// 17:point_pxpos t,j,u,v position of point_f1 in picture matrix
// 18:q_rf2tof0 t,j,02,val1-4 quaternion that rotates frame_2 to frame_0
// [k]
// 0:-
// 1:xma 0-2 -> dotnect_platform:printInfo
// 2:posVel 0-3 TODO remove arg support
// 3:nPoints 0<x
// 4:showURDF 0-1
// 5:initEndEffX x
// 6:initEndEffY x
// 7:initEndEffZ x
// 8:scaleX x
// 9:scaleY x
// 10:scaleZ x
// 11:-
// 12:discards 0:ok indicates a current series of discarded points
// 1:discards
// 13:ui_validjumps 0:off .ui element, also enables jump range markers for user guidance
// 1:on
// 14:ui_xma_change 0:no change
// 1:changed
// [t] timers
// 0:MarkerArrayPublisher::publishMarkerCallback
// 1:TransformHandler::publishTransform
// 2:findRefFrame2
//
#include <stdio.h>
#include <vector>
// boost
#include <boost/thread/mutex.hpp>
// ros
#include <ros/time.h>
#include <ros/timer.h>
// local
#include "custom_defines.h"
#include "data_container.h"
DataContainer::DataContainer()
{
// v_ints_ indicates certain states e.g. menu is checked or not
v_ints_.resize(15, 0);
// 1-10 are set by user arguments right after startup TODO what
v_ints_[11] = 2;
v_ints_[12] = 0;
v_ints_[13] = 2;
// v_dbls_ comprises all sensor related data
// initialize with empty vector of biggest size in j
std::vector<double> def(7, 0);
def[0] = ros::Time::now().toNSec();
v_dbls_.resize(19, def);
for (int i = 0; i < v_dbls_.size(); ++i)
{
v_dbls_[i][1] = i;
}
// set defaults
v_dbls_[11][6] = 1;
v_dbls_[15][5] = 1;
v_dbls_[16][5] = 1;
v_dbls_[18][6] = 1;
// down all v_dbls_flags_
v_dbls_flags_.resize(5);
for (int i = 0; i < 5; ++i)
{
v_dbls_flags_[i].resize(19, 0);
}
// prepare timers and threads
v_timers_.resize(3, ros::Timer());
}
// member functions
int DataContainer::getInt(int k)
{
if (checkArgsInts(k))
{
lock_shared_shared_(mtx_shr_ints_);
return v_ints_[k];
}
return 0;
}
void DataContainer::setInt(int k, int value)
{
if (checkArgsInts(k))
{
boost::unique_lock<boost::shared_mutex> WriteLock(mtx_shr_ints_);
v_ints_[k] = value;
}
return;
}
bool DataContainer::checkArgsInts(uint k)
{
if (k < v_ints_.size())
{
return true;
}
printf(ACYELLOW NNAME " checkArgsInts: bad k %d" ACRESETN, k);
return false;
}
void DataContainer::setVec(const std::vector<double>& v_in)
{
// only one thread can enter at once
boost::upgrade_lock<boost::shared_mutex> lock(mtx_shr_dbls_);
int j = v_in[1];
if (checkArgsDbls(j))
{
// to start writing readers need to be blocked
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
v_dbls_[j] = v_in;
for (int i = 0; i < 5; ++i)
{
v_dbls_flags_[i][j] = 1;
}
}
return;
}
void DataContainer::getVec(int i, int j, std::vector<double>& v_out)
{
if (checkArgsDbls(i, j))
{
lock_shared_shared_(mtx_shr_dbls_);
v_out = v_dbls_[j];
v_dbls_flags_[i][j] = 0;
return;
}
}
double DataContainer::getVecDbl(int i, int j, int l)
{
if (checkArgsDbls(i, j, l))
{
lock_shared_shared_(mtx_shr_dbls_);
v_dbls_flags_[i][j] = 0;
return v_dbls_[j][l];
}
return 0.;
}
int DataContainer::checkVecFlag(int i, int j)
{
if (checkArgsDbls(i, j))
{
lock_shared_shared_(mtx_shr_dbls_);
return v_dbls_flags_[i][j];
}
return 0;
}
ros::Timer* DataContainer::getTimerPtr(int t){
return &v_timers_[t];
}
ros::NodeHandle* DataContainer::getNodeHandle(){
return &nh_;
}
boost::thread* DataContainer::getThreadXMA(){
return &t_xma_average_;
}
// privates
bool DataContainer::checkArgsDbls(uint j)
{
if (j < v_dbls_.size())
{
return true;
}
printf(ACYELLOW NNAME " checkArgsDbls: rejected j %d" ACRESETN, j);
return false;
}
bool DataContainer::checkArgsDbls(uint i, uint j)
{
if (i < v_dbls_flags_.size() || j < v_dbls_.size())
{
return true;
}
printf(ACYELLOW NNAME " checkArgsDbls: rejected i %d j %d" ACRESETN, i, j);
return false;
}
bool DataContainer::checkArgsDbls(uint i, uint j, uint l)
{
if (i < v_dbls_flags_.size() || j < v_dbls_.size() || l < v_dbls_[j].size())
{
return true;
}
printf(ACYELLOW NNAME " checkArgsDbls: rejected i %d j %d l %d" ACRESETN, i, j, l);
return false;
}
bool DataContainer::customSleep(int sec, int nsec)
{
struct timespec req, rem;
req.tv_sec = sec;
req.tv_nsec = nsec;
if (nanosleep(&req, &rem) != 0)
{
printf(ACYELLOW NNAME ": nanosleep rem %d:%d strerror:%s" ACRESETN, (int)rem.tv_sec, (int)rem.tv_nsec, strerror(errno));
return false;
}
return true;
}
// EOF
| 29.926724 | 124 | 0.567334 | [
"object",
"vector",
"3d"
] |
8bbc77c0de6926d9d12f044c4f5d07980c5b522c | 882 | cpp | C++ | lib/chiavdf/fast_vdf/python_bindings/chiavdf.cpp | davision/chia-blockchain | d5a66579c00cb926e0d266e5b8077ac16b220932 | [
"Apache-2.0"
] | null | null | null | lib/chiavdf/fast_vdf/python_bindings/chiavdf.cpp | davision/chia-blockchain | d5a66579c00cb926e0d266e5b8077ac16b220932 | [
"Apache-2.0"
] | null | null | null | lib/chiavdf/fast_vdf/python_bindings/chiavdf.cpp | davision/chia-blockchain | d5a66579c00cb926e0d266e5b8077ac16b220932 | [
"Apache-2.0"
] | null | null | null | #include <pybind11/pybind11.h>
#include "../verifier.h"
namespace py = pybind11;
PYBIND11_MODULE(chiavdf, m) {
m.doc() = "Chia proof of time";
m.def("verify", [] (int discriminant_size_bits, const py::bytes& challenge_hash, const string& a,
const string& b, uint64_t num_iterations, const py::bytes& witness,
uint8_t witness_type) {
std::string challenge_hash_str(challenge_hash);
std::string witness_str(witness);
ProofOfTimeType pot(
discriminant_size_bits,
std::vector<uint8_t>(challenge_hash_str.begin(), challenge_hash_str.end()),
integer(a),
integer(b),
num_iterations,
std::vector<uint8_t>(witness_str.begin(), witness_str.end()),
witness_type
);
return CheckProofOfTimeType(pot);
});
}
| 33.923077 | 102 | 0.602041 | [
"vector"
] |
8bd9098e6ef505c6ddd5fee06a02990bc4b03dcb | 5,339 | cpp | C++ | backends/analysis/dj_set_expl.cpp | dragosdmtrsc/bf4 | 2e15e50acc4314737d99093b3d900fa44d795958 | [
"Apache-2.0"
] | 10 | 2020-08-05T12:52:37.000Z | 2021-05-20T02:15:04.000Z | backends/analysis/dj_set_expl.cpp | shellqiqi/bf4 | 6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f | [
"Apache-2.0"
] | 4 | 2020-09-28T12:17:50.000Z | 2021-11-23T12:23:38.000Z | backends/analysis/dj_set_expl.cpp | shellqiqi/bf4 | 6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f | [
"Apache-2.0"
] | 2 | 2020-10-13T07:59:42.000Z | 2021-12-08T21:35:05.000Z |
#include "dj_set_expl.h"
namespace analysis {
std::vector<id_t> dj_set_expl::ancestors(const std::vector<id_t> &vs, id_t e) {
std::vector<id_t> ancs;
while (e > 0) {
ancs.push_back(e);
e = vs[e];
}
return ancs;
}
void dj_set_expl::explain(id_t xid, id_t yid,
std::vector<std::pair<id_t, id_t>> &eqns) const {
if (xid == yid)
return;
auto ancs_x = ancestors(raw_parents, xid);
auto ancs_y = ancestors(raw_parents, yid);
auto I = ancs_x.rbegin();
auto J = ancs_y.rbegin();
for (; I != ancs_x.rend() && J != ancs_y.rend() && *I == *J; ++I, ++J) {
}
--I;
for (auto x = xid; x != *I; x = raw_parents[x]) {
eqns.emplace_back(x, raw_parents[x]);
}
for (auto y = yid; y != *I; y = raw_parents[y]) {
eqns.emplace_back(y, raw_parents[y]);
}
}
std::vector<std::pair<id_t, id_t>> dj_set_expl::explain(id_t xid,
id_t yid) const {
auto rxid = rep(xid);
auto ryid = rep(yid);
if (rxid != ryid) return {};
std::vector<std::pair<id_t, id_t>> eqns;
explain(xid, yid, eqns);
return eqns;
}
id_t dj_set_expl::rep(id_t a) const {
auto p = a;
while (parents[p] > 0)
p = parents[p];
auto rt = p;
p = a;
// do path compression
while (p != rt) {
parents[p] = rt;
p = parents[p];
}
return rt;
}
int dj_set_expl::set_union(id_t xid, id_t yid) {
auto rxid = rep(xid);
auto ryid = rep(yid);
// check if current equation is redundant
if (rxid == ryid)
return -1;
auto s1 = sizes[rxid];
auto s2 = sizes[ryid];
// int factor = 1;
if (s1 < s2) {
std::swap(rxid, ryid);
std::swap(xid, yid);
std::swap(s1, s2);
// factor = -1;
}
equations.emplace_back(xid, yid);
int eq_id = equations.size() - 1;
// size(rxid) > size(ryid)
sizes[rxid] += sizes[ryid];
parents[ryid] = rxid;
// this is for O(k * log(n)) implementation
// raw_parents[ryid] = rxid;
// parent_equation[ryid] = factor * eq_id;
// this is for O(k) implementation
auto yancestors = ancestors(raw_parents, yid);
// reverse path from y to its root
for (auto I = yancestors.rbegin(); I != yancestors.rend(); ++I) {
auto rp = raw_parents[*I];
raw_parents[rp] = *I;
}
// create edge y -> x
raw_parents[yid] = xid;
return eq_id;
}
id_t dj_set_expl::newid() {
parents.push_back(-1);
raw_parents.push_back(-1);
sizes.push_back(1);
return latestId++;
}
std::pair<congruence_closure_t::var_t, congruence_closure_t::var_t>
congruence_closure_t::get_reason(
const congruence_closure_t::reason_for_equality_t &reason) {
if (auto vet = boost::get<var_eq_t>(&reason)) {
return {vet->left, vet->right};
} else if (auto fep = boost::get<fun_eq_pair_t>(&reason)) {
return {fep->first.a, fep->second.a};
} else {
assert(false);
}
}
void congruence_closure_t::propagate() {
while (!pending.empty()) {
auto E = pending.back();
pending.pop_back();
var_t a, b;
std::tie(a, b) = get_reason(E);
auto aprime = get_representative(a);
auto bprime = get_representative(b);
if (aprime != bprime) {
auto &cls_list_a = class_list[aprime];
auto &cls_list_b = class_list[bprime];
if (cls_list_a.size() > cls_list_b.size()) {
std::swap(aprime, bprime);
std::swap(a, b);
std::swap(cls_list_a, cls_list_b);
}
// INSERT edge (a, b) in proof forest
auto eqid = proof_forest.set_union(a, b);
if (eqid >= 0) {
proof_forest_edge_labels[eqid] = E;
for (auto c : cls_list_a) {
representatives[c] = bprime;
}
cls_list_b.insert(cls_list_b.end(), cls_list_a.begin(),
cls_list_a.end());
class_list.erase(aprime);
auto &ause_lists = use_lists[aprime];
auto &buse_lists = use_lists[bprime];
for (const auto &e : ause_lists) {
auto c1_ = get_representative(e.a1);
auto c2_ = get_representative(e.a2);
auto Jlp = lookup.find(std::make_pair(c1_, c2_));
if (Jlp != lookup.end()) {
pending.push_back(std::make_pair(Jlp->second, e));
} else {
lookup.emplace(std::make_pair(c1_, c2_), e);
buse_lists.push_back(e);
}
}
ause_lists.clear();
}
}
}
}
void congruence_closure_t::add_equality(
const boost::variant<congruence_closure_t::var_eq_t,
congruence_closure_t::var_fun_eq_t> &eq) {
if (const var_eq_t *veq = boost::get<var_eq_t>(&eq)) {
pending.push_back(*veq);
propagate();
} else if (const var_fun_eq_t *vfe = boost::get<var_fun_eq_t>(&eq)) {
auto a1_ = get_representative(vfe->a1);
auto a2_ = get_representative(vfe->a2);
auto Jlp = lookup.find(std::make_pair(a1_, a2_));
if (Jlp != lookup.end()) {
pending.emplace_back(std::make_pair(*vfe, Jlp->second));
propagate();
} else {
lookup.emplace(std::make_pair(a1_, a2_), *vfe);
use_lists[a1_].push_back(*vfe);
use_lists[a2_].push_back(*vfe);
}
} else {
assert(false);
}
}
congruence_closure_t::var_t congruence_closure_t::create_new_var() {
auto id = representatives.size();
representatives.push_back(id);
class_list[id] = {id};
proof_forest.newid();
return id;
}
}; // namespace analysis | 28.398936 | 79 | 0.593931 | [
"vector"
] |
8bd98a7faa9a231d084ebb23ea30f08daae479d3 | 40,748 | hpp | C++ | src/core/grabber/include/device_grabber.hpp | cyrusccy/Karabiner-Elements | 90f83e487a0b6c671bc76f48c01e91fb28ae67c2 | [
"Unlicense"
] | null | null | null | src/core/grabber/include/device_grabber.hpp | cyrusccy/Karabiner-Elements | 90f83e487a0b6c671bc76f48c01e91fb28ae67c2 | [
"Unlicense"
] | null | null | null | src/core/grabber/include/device_grabber.hpp | cyrusccy/Karabiner-Elements | 90f83e487a0b6c671bc76f48c01e91fb28ae67c2 | [
"Unlicense"
] | null | null | null | #pragma once
#include "boost_defs.hpp"
#include "apple_hid_usage_tables.hpp"
#include "constants.hpp"
#include "device_detail.hpp"
#include "event_tap_utility.hpp"
#include "grabbable_state_queues_manager.hpp"
#include "hid_grabber.hpp"
#include "hid_manager.hpp"
#include "human_interface_device.hpp"
#include "iokit_utility.hpp"
#include "json_utility.hpp"
#include "krbn_notification_center.hpp"
#include "logger.hpp"
#include "manipulator/details/post_event_to_virtual_devices.hpp"
#include "manipulator/manipulator_managers_connector.hpp"
#include "monitor/configuration_monitor.hpp"
#include "monitor/event_tap_monitor.hpp"
#include "spdlog_utility.hpp"
#include "system_preferences_utility.hpp"
#include "types.hpp"
#include "virtual_hid_device_client.hpp"
#include <boost/algorithm/string.hpp>
#include <deque>
#include <fstream>
#include <json/json.hpp>
#include <thread>
#include <time.h>
namespace krbn {
class device_grabber final : public pqrs::dispatcher::extra::dispatcher_client {
public:
device_grabber(const device_grabber&) = delete;
device_grabber(std::weak_ptr<grabbable_state_queues_manager> weak_grabbable_state_queues_manager,
std::weak_ptr<console_user_server_client> weak_console_user_server_client) : dispatcher_client(),
weak_grabbable_state_queues_manager_(weak_grabbable_state_queues_manager),
profile_(nlohmann::json()),
led_monitor_timer_(*this) {
simple_modifications_manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>();
complex_modifications_manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>();
fn_function_keys_manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>();
post_event_to_virtual_devices_manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>();
merged_input_event_queue_ = std::make_shared<event_queue::queue>();
simple_modifications_applied_event_queue_ = std::make_shared<event_queue::queue>();
complex_modifications_applied_event_queue_ = std::make_shared<event_queue::queue>();
fn_function_keys_applied_event_queue_ = std::make_shared<event_queue::queue>();
posted_event_queue_ = std::make_shared<event_queue::queue>();
virtual_hid_device_client_ = std::make_shared<virtual_hid_device_client>();
client_connected_connection_ = virtual_hid_device_client_->client_connected.connect([this] {
logger::get_logger().info("virtual_hid_device_client_ is connected");
update_virtual_hid_keyboard();
update_virtual_hid_pointing();
});
client_disconnected_connection_ = virtual_hid_device_client_->client_disconnected.connect([this] {
logger::get_logger().info("virtual_hid_device_client_ is disconnected");
stop();
});
if (auto m = weak_grabbable_state_queues_manager_.lock()) {
grabbable_state_changed_connection_ = m->grabbable_state_changed.connect([this](auto&& registry_entry_id, auto&& grabbable_state) {
retry_grab(registry_entry_id, grabbable_state);
});
}
post_event_to_virtual_devices_manipulator_ = std::make_shared<manipulator::details::post_event_to_virtual_devices>(system_preferences_,
weak_console_user_server_client);
post_event_to_virtual_devices_manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::details::base>(post_event_to_virtual_devices_manipulator_));
complex_modifications_applied_event_queue_->enable_manipulator_environment_json_output(constants::get_manipulator_environment_json_file_path());
// Connect manipulator_managers
manipulator_managers_connector_.emplace_back_connection(simple_modifications_manipulator_manager_,
merged_input_event_queue_,
simple_modifications_applied_event_queue_);
manipulator_managers_connector_.emplace_back_connection(complex_modifications_manipulator_manager_,
complex_modifications_applied_event_queue_);
manipulator_managers_connector_.emplace_back_connection(fn_function_keys_manipulator_manager_,
fn_function_keys_applied_event_queue_);
manipulator_managers_connector_.emplace_back_connection(post_event_to_virtual_devices_manipulator_manager_,
posted_event_queue_);
input_event_arrived_connection_ = krbn_notification_center::get_instance().input_event_arrived.connect([this] {
manipulate(time_utility::mach_absolute_time());
});
// macOS 10.12 sometimes synchronize caps lock LED to internal keyboard caps lock state.
// The behavior causes LED state mismatch because device_grabber does not change the caps lock state of physical keyboards.
// Thus, we monitor the LED state and update it if needed.
led_monitor_timer_.start(
[this] {
update_caps_lock_led();
},
std::chrono::milliseconds(1000));
// hid_manager_
std::vector<std::pair<krbn::hid_usage_page, krbn::hid_usage>> targets({
std::make_pair(hid_usage_page::generic_desktop, hid_usage::gd_keyboard),
std::make_pair(hid_usage_page::generic_desktop, hid_usage::gd_mouse),
std::make_pair(hid_usage_page::generic_desktop, hid_usage::gd_pointer),
});
hid_manager_ = std::make_unique<hid_manager>(targets);
hid_manager_->device_detecting.connect([](auto&& device) {
if (iokit_utility::is_karabiner_virtual_hid_device(device)) {
return false;
}
return true;
});
hid_manager_->device_detected.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
hid->values_arrived.connect([this, weak_hid](auto&& shared_event_queue) {
if (auto hid = weak_hid.lock()) {
values_arrived(hid, shared_event_queue);
}
});
auto grabber = std::make_shared<hid_grabber>(weak_hid);
grabber->device_grabbing.connect([this, weak_hid] {
if (auto hid = weak_hid.lock()) {
return is_grabbable_callback(hid);
}
return grabbable_state::state::ungrabbable_permanently;
});
grabber->device_grabbed.connect([this, weak_hid] {
if (auto hid = weak_hid.lock()) {
logger::get_logger().info("{0} is grabbed.", hid->get_name_for_log());
set_grabbed(hid->get_registry_entry_id(), true);
update_caps_lock_led();
update_virtual_hid_pointing();
apple_notification_center::post_distributed_notification_to_all_sessions(constants::get_distributed_notification_device_grabbing_state_is_changed());
}
});
grabber->device_ungrabbed.connect([this, weak_hid] {
if (auto hid = weak_hid.lock()) {
logger::get_logger().info("{0} is ungrabbed.", hid->get_name_for_log());
set_grabbed(hid->get_registry_entry_id(), false);
if (auto m = weak_grabbable_state_queues_manager_.lock()) {
m->unset_first_grabbed_event_time_stamp(hid->get_registry_entry_id());
}
post_device_ungrabbed_event(hid->get_device_id());
update_virtual_hid_pointing();
apple_notification_center::post_distributed_notification_to_all_sessions(constants::get_distributed_notification_device_grabbing_state_is_changed());
}
});
hid_grabbers_[hid->get_registry_entry_id()] = grabber;
output_devices_json();
output_device_details_json();
update_virtual_hid_pointing();
// ----------------------------------------
async_grab_devices();
}
});
hid_manager_->device_removed.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
logger::get_logger().info("{0} is removed.", hid->get_name_for_log());
auto registry_entry_id = hid->get_registry_entry_id();
hid_grabbers_.erase(registry_entry_id);
device_states_.erase(registry_entry_id);
if (auto m = weak_grabbable_state_queues_manager_.lock()) {
m->erase_queue(registry_entry_id);
}
output_devices_json();
output_device_details_json();
// ----------------------------------------
if (hid->is_keyboard() &&
hid->is_karabiner_virtual_hid_device()) {
virtual_hid_device_client_->async_close();
async_ungrab_devices();
virtual_hid_device_client_->async_connect();
async_grab_devices();
}
update_virtual_hid_pointing();
// ----------------------------------------
// Refresh grab state in order to apply disable_built_in_keyboard_if_exists.
async_grab_devices();
}
});
hid_manager_->async_start();
}
virtual ~device_grabber(void) {
detach_from_dispatcher([this] {
stop();
led_monitor_timer_.stop();
hid_manager_ = nullptr;
hid_grabbers_.clear();
input_event_arrived_connection_.disconnect();
grabbable_state_changed_connection_.disconnect();
client_connected_connection_.disconnect();
client_disconnected_connection_.disconnect();
post_event_to_virtual_devices_manipulator_ = nullptr;
simple_modifications_manipulator_manager_ = nullptr;
complex_modifications_manipulator_manager_ = nullptr;
fn_function_keys_manipulator_manager_ = nullptr;
post_event_to_virtual_devices_manipulator_manager_ = nullptr;
});
}
void async_start(const std::string& user_core_configuration_file_path) {
enqueue_to_dispatcher([this, user_core_configuration_file_path] {
// We should call CGEventTapCreate after user is logged in.
// So, we create event_tap_monitor here.
event_tap_monitor_ = std::make_unique<event_tap_monitor>();
event_tap_monitor_->caps_lock_state_changed.connect([this](auto&& state) {
last_caps_lock_state_ = state;
post_caps_lock_state_changed_event(state);
update_caps_lock_led();
});
event_tap_monitor_->pointing_device_event_arrived.connect([this](auto&& event_type, auto&& event) {
auto e = event_queue::event::make_pointing_device_event_from_event_tap_event();
event_queue::entry entry(device_id(0),
event_queue::event_time_stamp(time_utility::mach_absolute_time()),
e,
event_type,
event);
merged_input_event_queue_->push_back_event(entry);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
});
event_tap_monitor_->async_start();
configuration_monitor_ = std::make_unique<configuration_monitor>(user_core_configuration_file_path);
configuration_monitor_->core_configuration_updated.connect([this](auto&& weak_core_configuration) {
if (auto core_configuration = weak_core_configuration.lock()) {
core_configuration_ = core_configuration;
logger_unique_filter_.reset();
set_profile(core_configuration->get_selected_profile());
async_grab_devices();
}
});
configuration_monitor_->async_start();
virtual_hid_device_client_->async_connect();
});
}
void async_stop(void) {
enqueue_to_dispatcher([this] {
stop();
});
}
void async_grab_devices(void) {
enqueue_to_dispatcher([this] {
for (auto& pair : hid_grabbers_) {
if (pair.second->make_grabbable_state() == grabbable_state::state::ungrabbable_permanently) {
pair.second->async_ungrab();
} else {
pair.second->async_grab();
}
}
enable_devices();
});
}
void async_ungrab_devices(void) {
enqueue_to_dispatcher([this] {
for (auto& pair : hid_grabbers_) {
pair.second->async_ungrab();
}
logger::get_logger().info("Connected devices are ungrabbed");
});
}
void async_unset_profile(void) {
enqueue_to_dispatcher([this] {
profile_ = core_configuration::profile(nlohmann::json());
manipulator_managers_connector_.invalidate_manipulators();
});
}
void async_set_system_preferences(const system_preferences& value) {
enqueue_to_dispatcher([this, value] {
system_preferences_ = value;
update_fn_function_keys_manipulators();
async_post_keyboard_type_changed_event();
});
}
void async_post_frontmost_application_changed_event(const std::string& bundle_identifier,
const std::string& file_path) {
enqueue_to_dispatcher([this, bundle_identifier, file_path] {
auto event = event_queue::event::make_frontmost_application_changed_event(bundle_identifier,
file_path);
event_queue::entry entry(device_id(0),
event_queue::event_time_stamp(time_utility::mach_absolute_time()),
event,
event_type::single,
event);
merged_input_event_queue_->push_back_event(entry);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
});
}
void async_post_input_source_changed_event(const input_source_identifiers& input_source_identifiers) {
enqueue_to_dispatcher([this, input_source_identifiers] {
auto event = event_queue::event::make_input_source_changed_event(input_source_identifiers);
event_queue::entry entry(device_id(0),
event_queue::event_time_stamp(time_utility::mach_absolute_time()),
event,
event_type::single,
event);
merged_input_event_queue_->push_back_event(entry);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
});
}
void async_post_keyboard_type_changed_event(void) {
enqueue_to_dispatcher([this] {
auto keyboard_type_string = system_preferences_utility::get_keyboard_type_string(system_preferences_.get_keyboard_type());
auto event = event_queue::event::make_keyboard_type_changed_event(keyboard_type_string);
event_queue::entry entry(device_id(0),
event_queue::event_time_stamp(time_utility::mach_absolute_time()),
event,
event_type::single,
event);
merged_input_event_queue_->push_back_event(entry);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
});
}
private:
class device_state final {
public:
device_state(void) : grabbed_(false),
disabled_(false) {
}
bool get_grabbed(void) const {
return grabbed_;
}
void set_grabbed(bool value) {
grabbed_ = value;
}
bool get_disabled(void) const {
return disabled_;
}
void set_disabled(bool value) {
disabled_ = value;
}
private:
bool grabbed_;
bool disabled_;
};
void stop(void) {
configuration_monitor_ = nullptr;
async_ungrab_devices();
event_tap_monitor_ = nullptr;
virtual_hid_device_client_->async_close();
}
std::shared_ptr<device_state> find_device_state(registry_entry_id registry_entry_id) const {
auto it = device_states_.find(registry_entry_id);
if (it != std::end(device_states_)) {
return it->second;
}
return nullptr;
}
bool grabbed(registry_entry_id registry_entry_id) const {
if (auto s = find_device_state(registry_entry_id)) {
return s->get_grabbed();
}
return false;
}
void set_grabbed(registry_entry_id registry_entry_id, bool value) {
auto s = find_device_state(registry_entry_id);
if (!s) {
s = std::make_shared<device_state>();
device_states_[registry_entry_id] = s;
}
s->set_grabbed(value);
}
bool disabled(registry_entry_id registry_entry_id) const {
if (auto s = find_device_state(registry_entry_id)) {
return s->get_disabled();
}
return false;
}
void set_disabled(registry_entry_id registry_entry_id, bool value) {
auto s = find_device_state(registry_entry_id);
if (!s) {
s = std::make_shared<device_state>();
device_states_[registry_entry_id] = s;
}
s->set_disabled(value);
}
void retry_grab(registry_entry_id registry_entry_id, boost::optional<grabbable_state> grabbable_state) {
if (auto grabber = find_hid_grabber(registry_entry_id)) {
// Check grabbable state
bool grabbable = false;
if (grabbable_state &&
grabbable_state->get_state() == grabbable_state::state::grabbable) {
grabbable = true;
}
// Grab device
if (grabbable) {
// Call `grab` again if current_grabbable_state is `grabbable` and not grabbed yet.
if (!grabbed(registry_entry_id)) {
grabber->async_ungrab();
grabber->async_grab();
}
} else {
// We should `ungrab` since current_grabbable_state is not `grabbable`.
grabber->async_ungrab();
}
}
}
std::shared_ptr<hid_grabber> find_hid_grabber(registry_entry_id registry_entry_id) {
auto it = hid_grabbers_.find(registry_entry_id);
if (it != std::end(hid_grabbers_)) {
return it->second;
}
return nullptr;
}
void manipulate(absolute_time now) {
{
// Avoid recursive call
std::unique_lock<std::mutex> lock(manipulate_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
manipulator_managers_connector_.manipulate(now);
posted_event_queue_->clear_events();
post_event_to_virtual_devices_manipulator_->async_post_events(virtual_hid_device_client_);
}
}
if (auto min = manipulator_managers_connector_.min_input_event_time_stamp()) {
auto when = when_now();
if (now < *min) {
when += time_utility::to_milliseconds(*min - now);
}
enqueue_to_dispatcher(
[this, min] {
manipulate(*min);
},
when);
}
}
void values_arrived(std::shared_ptr<human_interface_device> hid,
std::shared_ptr<event_queue::queue> event_queue) {
// Update grabbable_state_queue
if (auto m = weak_grabbable_state_queues_manager_.lock()) {
m->update_first_grabbed_event_time_stamp(*event_queue);
}
// Manipulate events
if (disabled(hid->get_registry_entry_id())) {
// Do nothing
} else {
for (const auto& entry : event_queue->get_entries()) {
event_queue::entry qe(entry.get_device_id(),
entry.get_event_time_stamp(),
entry.get_event(),
entry.get_event_type(),
entry.get_original_event());
merged_input_event_queue_->push_back_event(qe);
}
}
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
// manipulator_managers_connector_.log_events_sizes(logger::get_logger());
}
void post_device_ungrabbed_event(device_id device_id) {
auto event = event_queue::event::make_device_ungrabbed_event();
event_queue::entry entry(device_id,
event_queue::event_time_stamp(time_utility::mach_absolute_time()),
event,
event_type::single,
event);
merged_input_event_queue_->push_back_event(entry);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
}
void post_caps_lock_state_changed_event(bool caps_lock_state) {
event_queue::event event(event_queue::event::type::caps_lock_state_changed, caps_lock_state);
event_queue::entry entry(device_id(0),
event_queue::event_time_stamp(time_utility::mach_absolute_time()),
event,
event_type::single,
event);
merged_input_event_queue_->push_back_event(entry);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
}
grabbable_state::state is_grabbable_callback(std::shared_ptr<human_interface_device> device) const {
if (is_ignored_device(*device)) {
// If we need to disable the built-in keyboard, we have to grab it.
if (device->is_built_in_keyboard() && need_to_disable_built_in_keyboard()) {
// Do nothing
} else {
auto message = fmt::format("{0} is ignored.", device->get_name_for_log());
logger_unique_filter_.info(message);
return grabbable_state::state::ungrabbable_permanently;
}
}
// ----------------------------------------
// Ungrabbable while virtual_hid_device_client_ is not ready.
if (!virtual_hid_device_client_->is_connected()) {
std::string message = "virtual_hid_device_client is not connected yet. Please wait for a while.";
logger_unique_filter_.warn(message);
return grabbable_state::state::ungrabbable_temporarily;
}
if (!virtual_hid_device_client_->is_virtual_hid_keyboard_ready()) {
std::string message = "virtual_hid_keyboard is not ready. Please wait for a while.";
logger_unique_filter_.warn(message);
return grabbable_state::state::ungrabbable_temporarily;
}
// ----------------------------------------
// Check observer state
if (auto m = weak_grabbable_state_queues_manager_.lock()) {
auto state = m->find_current_grabbable_state(device->get_registry_entry_id());
if (!state) {
std::string message = fmt::format("{0} is not observed yet. Please wait for a while.",
device->get_name_for_log());
logger_unique_filter_.warn(message);
return grabbable_state::state::ungrabbable_temporarily;
}
switch (state->get_state()) {
case grabbable_state::state::none:
return grabbable_state::state::ungrabbable_temporarily;
case grabbable_state::state::grabbable:
break;
case grabbable_state::state::ungrabbable_temporarily: {
std::string message;
switch (state->get_ungrabbable_temporarily_reason()) {
case grabbable_state::ungrabbable_temporarily_reason::none: {
message = fmt::format("{0} is ungrabbable temporarily",
device->get_name_for_log());
break;
}
case grabbable_state::ungrabbable_temporarily_reason::key_repeating: {
message = fmt::format("{0} is ungrabbable temporarily while a key is repeating.",
device->get_name_for_log());
break;
}
case grabbable_state::ungrabbable_temporarily_reason::modifier_key_pressed: {
message = fmt::format("{0} is ungrabbable temporarily while any modifier flags are pressed.",
device->get_name_for_log());
break;
}
case grabbable_state::ungrabbable_temporarily_reason::pointing_button_pressed: {
message = fmt::format("{0} is ungrabbable temporarily while mouse buttons are pressed.",
device->get_name_for_log());
break;
}
}
logger_unique_filter_.warn(message);
return grabbable_state::state::ungrabbable_temporarily;
}
case grabbable_state::state::ungrabbable_permanently: {
std::string message = fmt::format("{0} is ungrabbable permanently.",
device->get_name_for_log());
logger_unique_filter_.warn(message);
return grabbable_state::state::ungrabbable_permanently;
}
case grabbable_state::state::device_error: {
std::string message = fmt::format("{0} is ungrabbable temporarily by a failure of accessing device.",
device->get_name_for_log());
logger_unique_filter_.warn(message);
return grabbable_state::state::ungrabbable_temporarily;
}
}
}
// ----------------------------------------
return grabbable_state::state::grabbable;
}
void device_disabled(human_interface_device& device) {
// Post device_ungrabbed event in order to release modifier_flags.
post_device_ungrabbed_event(device.get_device_id());
}
void event_tap_pointing_device_event_callback(CGEventType type, CGEventRef event) {
}
void update_caps_lock_led(void) {
if (last_caps_lock_state_) {
if (core_configuration_) {
for (const auto& pair : hid_grabbers_) {
if (auto hid = pair.second->get_weak_hid().lock()) {
auto& di = hid->get_connected_device()->get_identifiers();
bool manipulate_caps_lock_led = core_configuration_->get_selected_profile().get_device_manipulate_caps_lock_led(di);
if (grabbed(hid->get_registry_entry_id()) &&
manipulate_caps_lock_led) {
hid->async_set_caps_lock_led_state(*last_caps_lock_state_ ? led_state::on : led_state::off);
}
}
}
}
}
}
bool is_pointing_device_grabbed(void) const {
for (const auto& pair : hid_grabbers_) {
if (auto hid = pair.second->get_weak_hid().lock()) {
if (hid->is_pointing_device() &&
grabbed(hid->get_registry_entry_id())) {
return true;
}
}
}
return false;
}
void update_virtual_hid_keyboard(void) {
if (virtual_hid_device_client_->is_connected()) {
pqrs::karabiner_virtual_hid_device::properties::keyboard_initialization properties;
properties.country_code = profile_.get_virtual_hid_keyboard().get_country_code();
virtual_hid_device_client_->async_initialize_virtual_hid_keyboard(properties);
}
}
void update_virtual_hid_pointing(void) {
if (virtual_hid_device_client_->is_connected()) {
if (is_pointing_device_grabbed() ||
manipulator_managers_connector_.needs_virtual_hid_pointing()) {
virtual_hid_device_client_->async_initialize_virtual_hid_pointing();
return;
}
virtual_hid_device_client_->async_terminate_virtual_hid_pointing();
}
}
bool is_ignored_device(const human_interface_device& device) const {
if (core_configuration_) {
return core_configuration_->get_selected_profile().get_device_ignore(device.get_connected_device()->get_identifiers());
}
return false;
}
bool get_disable_built_in_keyboard_if_exists(const human_interface_device& device) const {
if (core_configuration_) {
return core_configuration_->get_selected_profile().get_device_disable_built_in_keyboard_if_exists(device.get_connected_device()->get_identifiers());
}
return false;
}
bool need_to_disable_built_in_keyboard(void) const {
for (const auto& hid : hid_manager_->copy_hids()) {
if (get_disable_built_in_keyboard_if_exists(*hid)) {
return true;
}
}
return false;
}
void enable_devices(void) {
if (hid_manager_) {
for (const auto& hid : hid_manager_->copy_hids()) {
if (hid->is_built_in_keyboard() && need_to_disable_built_in_keyboard()) {
set_disabled(hid->get_registry_entry_id(), true);
} else {
set_disabled(hid->get_registry_entry_id(), false);
}
}
}
}
void output_devices_json(void) const {
if (hid_manager_) {
connected_devices connected_devices;
for (const auto& hid : hid_manager_->copy_hids()) {
connected_devices.push_back_device(*(hid->get_connected_device()));
}
auto file_path = constants::get_devices_json_file_path();
connected_devices.async_save_to_file(file_path);
}
}
void output_device_details_json(void) const {
if (hid_manager_) {
std::vector<device_detail> device_details;
for (const auto& hid : hid_manager_->copy_hids()) {
device_details.push_back(hid->make_device_detail());
}
std::sort(std::begin(device_details),
std::end(device_details),
[](auto& a, auto& b) {
return a.compare(b);
});
auto file_path = constants::get_device_details_json_file_path();
json_utility::async_save_to_file(nlohmann::json(device_details), file_path, 0755, 0644);
}
}
void set_profile(const core_configuration::profile& profile) {
profile_ = profile;
update_simple_modifications_manipulators();
update_complex_modifications_manipulators();
update_fn_function_keys_manipulators();
update_virtual_hid_keyboard();
update_virtual_hid_pointing();
}
void update_simple_modifications_manipulators(void) {
simple_modifications_manipulator_manager_->invalidate_manipulators();
for (const auto& device : profile_.get_devices()) {
for (const auto& pair : device.get_simple_modifications().get_pairs()) {
if (auto m = make_simple_modifications_manipulator(pair)) {
auto c = make_device_if_condition(device);
m->push_back_condition(c);
simple_modifications_manipulator_manager_->push_back_manipulator(m);
}
}
}
for (const auto& pair : profile_.get_simple_modifications().get_pairs()) {
if (auto m = make_simple_modifications_manipulator(pair)) {
simple_modifications_manipulator_manager_->push_back_manipulator(m);
}
}
}
std::shared_ptr<manipulator::details::conditions::base> make_device_if_condition(const core_configuration::profile::device& device) const {
nlohmann::json json;
json["type"] = "device_if";
json["identifiers"] = nlohmann::json::array();
json["identifiers"].push_back(nlohmann::json::object());
json["identifiers"].back()["vendor_id"] = type_safe::get(device.get_identifiers().get_vendor_id());
json["identifiers"].back()["product_id"] = type_safe::get(device.get_identifiers().get_product_id());
json["identifiers"].back()["is_keyboard"] = device.get_identifiers().get_is_keyboard();
json["identifiers"].back()["is_pointing_device"] = device.get_identifiers().get_is_pointing_device();
return std::make_shared<manipulator::details::conditions::device>(json);
}
std::shared_ptr<manipulator::details::base> make_simple_modifications_manipulator(const std::pair<std::string, std::string>& pair) const {
if (!pair.first.empty() && !pair.second.empty()) {
try {
auto from_json = nlohmann::json::parse(pair.first);
from_json["modifiers"]["optional"] = nlohmann::json::array();
from_json["modifiers"]["optional"].push_back("any");
auto to_json = nlohmann::json::parse(pair.second);
return std::make_shared<manipulator::details::basic>(manipulator::details::basic::from_event_definition(from_json),
manipulator::details::to_event_definition(to_json));
} catch (std::exception&) {
}
}
return nullptr;
}
void update_complex_modifications_manipulators(void) {
complex_modifications_manipulator_manager_->invalidate_manipulators();
for (const auto& rule : profile_.get_complex_modifications().get_rules()) {
for (const auto& manipulator : rule.get_manipulators()) {
auto m = manipulator::manipulator_factory::make_manipulator(manipulator.get_json(),
manipulator.get_parameters());
for (const auto& c : manipulator.get_conditions()) {
m->push_back_condition(manipulator::manipulator_factory::make_condition(c.get_json()));
}
complex_modifications_manipulator_manager_->push_back_manipulator(m);
}
}
}
void update_fn_function_keys_manipulators(void) {
fn_function_keys_manipulator_manager_->invalidate_manipulators();
auto from_mandatory_modifiers = nlohmann::json::array();
auto from_optional_modifiers = nlohmann::json::array();
from_optional_modifiers.push_back("any");
auto to_modifiers = nlohmann::json::array();
if (system_preferences_.get_keyboard_fn_state()) {
// f1 -> f1
// fn+f1 -> display_brightness_decrement
from_mandatory_modifiers.push_back("fn");
to_modifiers.push_back("fn");
} else {
// f1 -> display_brightness_decrement
// fn+f1 -> f1
// fn+f1 ... fn+f12 -> f1 .. f12
for (int i = 1; i <= 12; ++i) {
auto from_json = nlohmann::json::object({
{"key_code", fmt::format("f{0}", i)},
{"modifiers", nlohmann::json::object({
{"mandatory", nlohmann::json::array({"fn"})},
{"optional", nlohmann::json::array({"any"})},
})},
});
auto to_json = nlohmann::json::object({
{"key_code", fmt::format("f{0}", i)},
{"modifiers", nlohmann::json::array({"fn"})},
});
auto manipulator = std::make_shared<manipulator::details::basic>(manipulator::details::basic::from_event_definition(from_json),
manipulator::details::to_event_definition(to_json));
fn_function_keys_manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::details::base>(manipulator));
}
}
// from_modifiers+f1 -> display_brightness_decrement ...
for (const auto& device : profile_.get_devices()) {
for (const auto& pair : device.get_fn_function_keys().get_pairs()) {
if (auto m = make_fn_function_keys_manipulator(pair,
from_mandatory_modifiers,
from_optional_modifiers,
to_modifiers)) {
auto c = make_device_if_condition(device);
m->push_back_condition(c);
fn_function_keys_manipulator_manager_->push_back_manipulator(m);
}
}
}
for (const auto& pair : profile_.get_fn_function_keys().get_pairs()) {
if (auto m = make_fn_function_keys_manipulator(pair,
from_mandatory_modifiers,
from_optional_modifiers,
to_modifiers)) {
fn_function_keys_manipulator_manager_->push_back_manipulator(m);
}
}
// fn+return_or_enter -> keypad_enter ...
{
nlohmann::json data = nlohmann::json::array();
data.push_back(nlohmann::json::object({
{"from", nlohmann::json::object({{"key_code", "return_or_enter"}})},
{"to", nlohmann::json::object({{"key_code", "keypad_enter"}})},
}));
data.push_back(nlohmann::json::object({
{"from", nlohmann::json::object({{"key_code", "delete_or_backspace"}})},
{"to", nlohmann::json::object({{"key_code", "delete_forward"}})},
}));
data.push_back(nlohmann::json::object({
{"from", nlohmann::json::object({{"key_code", "right_arrow"}})},
{"to", nlohmann::json::object({{"key_code", "end"}})},
}));
data.push_back(nlohmann::json::object({
{"from", nlohmann::json::object({{"key_code", "left_arrow"}})},
{"to", nlohmann::json::object({{"key_code", "home"}})},
}));
data.push_back(nlohmann::json::object({
{"from", nlohmann::json::object({{"key_code", "down_arrow"}})},
{"to", nlohmann::json::object({{"key_code", "page_down"}})},
}));
data.push_back(nlohmann::json::object({
{"from", nlohmann::json::object({{"key_code", "up_arrow"}})},
{"to", nlohmann::json::object({{"key_code", "page_up"}})},
}));
for (const auto& d : data) {
auto from_json = d["from"];
from_json["modifiers"]["mandatory"] = nlohmann::json::array({"fn"});
from_json["modifiers"]["optional"] = nlohmann::json::array({"any"});
auto to_json = d["to"];
to_json["modifiers"] = nlohmann::json::array({"fn"});
auto manipulator = std::make_shared<manipulator::details::basic>(manipulator::details::basic::from_event_definition(from_json),
manipulator::details::to_event_definition(to_json));
fn_function_keys_manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::details::base>(manipulator));
}
}
}
std::shared_ptr<manipulator::details::base> make_fn_function_keys_manipulator(const std::pair<std::string, std::string>& pair,
const nlohmann::json& from_mandatory_modifiers,
const nlohmann::json& from_optional_modifiers,
const nlohmann::json& to_modifiers) {
try {
auto from_json = nlohmann::json::parse(pair.first);
if (from_json.empty()) {
return nullptr;
}
from_json["modifiers"]["mandatory"] = from_mandatory_modifiers;
from_json["modifiers"]["optional"] = from_optional_modifiers;
auto to_json = nlohmann::json::parse(pair.second);
if (to_json.empty()) {
return nullptr;
}
to_json["modifiers"] = to_modifiers;
return std::make_shared<manipulator::details::basic>(manipulator::details::basic::from_event_definition(from_json),
manipulator::details::to_event_definition(to_json));
} catch (std::exception&) {
}
return nullptr;
}
std::weak_ptr<grabbable_state_queues_manager> weak_grabbable_state_queues_manager_;
std::shared_ptr<virtual_hid_device_client> virtual_hid_device_client_;
boost::signals2::connection client_connected_connection_;
boost::signals2::connection client_disconnected_connection_;
boost::signals2::connection grabbable_state_changed_connection_;
std::unique_ptr<configuration_monitor> configuration_monitor_;
std::shared_ptr<const core_configuration> core_configuration_;
std::unique_ptr<event_tap_monitor> event_tap_monitor_;
boost::optional<bool> last_caps_lock_state_;
std::unique_ptr<hid_manager> hid_manager_;
std::unordered_map<registry_entry_id, std::shared_ptr<hid_grabber>> hid_grabbers_;
std::unordered_map<registry_entry_id, std::shared_ptr<device_state>> device_states_;
core_configuration::profile profile_;
system_preferences system_preferences_;
manipulator::manipulator_managers_connector manipulator_managers_connector_;
boost::signals2::connection input_event_arrived_connection_;
std::mutex manipulate_mutex_;
std::shared_ptr<event_queue::queue> merged_input_event_queue_;
std::shared_ptr<manipulator::manipulator_manager> simple_modifications_manipulator_manager_;
std::shared_ptr<event_queue::queue> simple_modifications_applied_event_queue_;
std::shared_ptr<manipulator::manipulator_manager> complex_modifications_manipulator_manager_;
std::shared_ptr<event_queue::queue> complex_modifications_applied_event_queue_;
std::shared_ptr<manipulator::manipulator_manager> fn_function_keys_manipulator_manager_;
std::shared_ptr<event_queue::queue> fn_function_keys_applied_event_queue_;
std::shared_ptr<manipulator::details::post_event_to_virtual_devices> post_event_to_virtual_devices_manipulator_;
std::shared_ptr<manipulator::manipulator_manager> post_event_to_virtual_devices_manipulator_manager_;
std::shared_ptr<event_queue::queue> posted_event_queue_;
pqrs::dispatcher::extra::timer led_monitor_timer_;
mutable logger::unique_filter logger_unique_filter_;
};
} // namespace krbn
| 38.405278 | 168 | 0.646756 | [
"object",
"vector"
] |
8bdc5c0eeae312c47f981bfd10fd9dc145e1a5a8 | 4,312 | cpp | C++ | modules/task_3/bessolitsyn_s_gauss/bessolitsyn_s_gauss.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/bessolitsyn_s_gauss/bessolitsyn_s_gauss.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2021-02-13T03:00:05.000Z | 2021-02-13T03:00:05.000Z | modules/task_3/bessolitsyn_s_gauss/bessolitsyn_s_gauss.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2020-10-11T09:11:57.000Z | 2020-10-11T09:11:57.000Z | // Copyright 2020 Bessolitsyn Sergey
#include <mpi.h>
#include <string>
#include <random>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
#include <cstring>
#include "../../../modules/task_3/bessolitsyn_s_gauss/bessolitsyn_s_gauss.h"
const std::vector<std::vector<double>> gauss_matrix = { {1, 2, 1},
{2, 4, 2},
{1, 2, 1} };
std::vector<double> filter_seq(std::vector<double> input_image, int w, int h) {
std::vector<double> bordered_image((w + 2) * (h + 2));
double t = MPI_Wtime();
for (int i = 0; i < h + 2; i++) {
for (int j = 0; j < w + 2; j++) {
if ((i == 0) || (j == 0) || (i == h + 1) || (j == w + 1)) {
bordered_image[i * (w + 2) + j] = 0;
} else {
bordered_image[i * (w + 2) + j] = input_image[(i - 1) * w + j - 1];
}
}
}
int pos = 0;
double sum = 0;
for (int i = 1; i < h + 1; i++) {
for (int j = 1; j < w + 1; j++) {
sum = 0;
for (int ii = -1; ii < 2; ++ii)
for (int jj = -1; jj < 2; ++jj) {
sum += bordered_image[(i + ii) * (w + 2) + j + jj] * gauss_matrix[ii + 1][jj + 1];
}
input_image[pos] = sum / 16;
++pos;
}
}
int p_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &p_rank);
std::cout << "Procces " << p_rank << " filter time:" << -t + MPI_Wtime() << std::endl;
return input_image;
}
std::vector<double> filter_par(std::vector<double> input_image, int w, int h) {
int p_size, p_rank;
MPI_Comm_size(MPI_COMM_WORLD, &p_size);
MPI_Comm_rank(MPI_COMM_WORLD, &p_rank);
int n = w * h;
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&w, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&h, 1, MPI_INT, 0, MPI_COMM_WORLD);
int* array_counts = new int[p_size];
int* array_dist = new int[p_size];
if (p_size != 1) {
if (p_rank == 0) {
int length = 0;
int i;
for (i = 0; i < ((h % p_size == 0) ? p_size : (p_size - 1)); i++) {
array_counts[i] = h / ((h % p_size == 0) ? p_size : (p_size - 1)) * w;
array_dist[i] = length;
length += h / ((h % p_size == 0) ? p_size : (p_size - 1)) * w;
}
if (h % p_size != 0) {
array_counts[i] = (h % (p_size - 1)) * w;
array_dist[i] = length;
}
}
} else {
array_counts[0] = h * w;
array_dist[0] = 0;
}
int local_image_size;
if (p_size != 1) {
if ((p_rank < p_size && h % p_size == 0) || (p_rank < (p_size - 1) && h % p_size != 0)) {
local_image_size = h / ((h % p_size == 0) ? p_size : (p_size - 1)) * w;
} else {
local_image_size = h % ((h % p_size == 0) ? p_size : (p_size - 1)) * w;
}
} else {
local_image_size = h * w;
}
std::vector<double> local_image(local_image_size);
MPI_Scatterv(input_image.data(), array_counts, array_dist, MPI_DOUBLE,
local_image.data(), local_image_size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
local_image = filter_seq(local_image, w, local_image_size / w);
std::vector<double> res;
if (p_rank == 0) {
res.resize(w * h);
}
MPI_Gatherv(local_image.data(), local_image_size, MPI_DOUBLE,
res.data(), array_counts, array_dist, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if (p_size != 1 && p_rank == 0) {
for (int i = 0; i < p_size - 1; i++) {
for (int j = 0; j < w; j++) {
res[local_image_size + i * local_image_size + j] =
input_image[local_image_size + i * local_image_size +j];
if (local_image_size + i * local_image_size + j + w < static_cast<int>(res.size()))
res[local_image_size + i * local_image_size + j + w] =
input_image[local_image_size + i * local_image_size + j + w];
res[local_image_size + i * local_image_size + j - w] =
input_image[local_image_size + i * local_image_size + j - w];
}
}
}
return res;
}
| 35.056911 | 102 | 0.489564 | [
"vector"
] |
8be4a76ba754e60238f057503dced887d76229d0 | 6,431 | cpp | C++ | Source/WebCore/Modules/applepay/PaymentRequestValidator.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/WebCore/Modules/applepay/PaymentRequestValidator.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebCore/Modules/applepay/PaymentRequestValidator.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2015, 2016 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "PaymentRequestValidator.h"
#if ENABLE(APPLE_PAY)
#include "PaymentRequest.h"
#include <unicode/ucurr.h>
#include <unicode/uloc.h>
namespace WebCore {
static ExceptionOr<void> validateCountryCode(const String&);
static ExceptionOr<void> validateCurrencyCode(const String&);
static ExceptionOr<void> validateMerchantCapabilities(const PaymentRequest::MerchantCapabilities&);
static ExceptionOr<void> validateSupportedNetworks(const Vector<String>&);
static ExceptionOr<void> validateShippingMethods(const Vector<PaymentRequest::ShippingMethod>&);
static ExceptionOr<void> validateShippingMethod(const PaymentRequest::ShippingMethod&);
ExceptionOr<void> PaymentRequestValidator::validate(const PaymentRequest& paymentRequest)
{
auto validatedCountryCode = validateCountryCode(paymentRequest.countryCode());
if (validatedCountryCode.hasException())
return validatedCountryCode.releaseException();
auto validatedCurrencyCode = validateCurrencyCode(paymentRequest.currencyCode());
if (validatedCurrencyCode.hasException())
return validatedCurrencyCode.releaseException();
auto validatedSupportedNetworks = validateSupportedNetworks(paymentRequest.supportedNetworks());
if (validatedSupportedNetworks.hasException())
return validatedSupportedNetworks.releaseException();
auto validatedMerchantCapabilities = validateMerchantCapabilities(paymentRequest.merchantCapabilities());
if (validatedMerchantCapabilities.hasException())
return validatedMerchantCapabilities.releaseException();
auto validatedTotal = validateTotal(paymentRequest.total());
if (validatedTotal.hasException())
return validatedTotal.releaseException();
auto validatedShippingMethods = validateShippingMethods(paymentRequest.shippingMethods());
if (validatedShippingMethods.hasException())
return validatedShippingMethods.releaseException();
for (auto& countryCode : paymentRequest.supportedCountries()) {
auto validatedCountryCode = validateCountryCode(countryCode);
if (validatedCountryCode.hasException())
return validatedCountryCode.releaseException();
}
return { };
}
ExceptionOr<void> PaymentRequestValidator::validateTotal(const PaymentRequest::LineItem& total)
{
if (!total.label)
return Exception { TypeError, "Missing total label." };
if (!total.amount)
return Exception { TypeError, "Missing total amount." };
if (*total.amount <= 0)
return Exception { TypeError, "Total amount must be greater than zero." };
if (*total.amount > 10000000000)
return Exception { TypeError, "Total amount is too big." };
return { };
}
static ExceptionOr<void> validateCountryCode(const String& countryCode)
{
if (!countryCode)
return Exception { TypeError, "Missing country code." };
for (auto *countryCodePtr = uloc_getISOCountries(); *countryCodePtr; ++countryCodePtr) {
if (countryCode == *countryCodePtr)
return { };
}
return Exception { TypeError, makeString("\"" + countryCode, "\" is not a valid country code.") };
}
static ExceptionOr<void> validateCurrencyCode(const String& currencyCode)
{
if (!currencyCode)
return Exception { TypeError, "Missing currency code." };
UErrorCode errorCode = U_ZERO_ERROR;
auto currencyCodes = std::unique_ptr<UEnumeration, void (*)(UEnumeration*)>(ucurr_openISOCurrencies(UCURR_ALL, &errorCode), uenum_close);
int32_t length;
while (auto *currencyCodePtr = uenum_next(currencyCodes.get(), &length, &errorCode)) {
if (currencyCodePtr == currencyCode)
return { };
}
return Exception { TypeError, makeString("\"" + currencyCode, "\" is not a valid currency code.") };
}
static ExceptionOr<void> validateMerchantCapabilities(const PaymentRequest::MerchantCapabilities& merchantCapabilities)
{
if (!merchantCapabilities.supports3DS && !merchantCapabilities.supportsEMV && !merchantCapabilities.supportsCredit && !merchantCapabilities.supportsDebit)
return Exception { TypeError, "Missing merchant capabilities." };
return { };
}
static ExceptionOr<void> validateSupportedNetworks(const Vector<String>& supportedNetworks)
{
if (supportedNetworks.isEmpty())
return Exception { TypeError, "Missing supported networks." };
return { };
}
static ExceptionOr<void> validateShippingMethod(const PaymentRequest::ShippingMethod& shippingMethod)
{
if (shippingMethod.amount < 0)
return Exception { TypeError, "Shipping method amount must be greater than or equal to zero." };
return { };
}
static ExceptionOr<void> validateShippingMethods(const Vector<PaymentRequest::ShippingMethod>& shippingMethods)
{
for (const auto& shippingMethod : shippingMethods) {
auto validatedShippingMethod = validateShippingMethod(shippingMethod);
if (validatedShippingMethod.hasException())
return validatedShippingMethod.releaseException();
}
return { };
}
}
#endif
| 38.975758 | 158 | 0.746229 | [
"vector"
] |
8bf40642e5b6505cdc315827963f4fd19a547d5c | 5,463 | cpp | C++ | glscene/Test/parseTest.cpp | Morozov-5F/glsdk | bff2b5074681bf3d2c438216e612d8a0ed80cead | [
"MIT"
] | 2 | 2020-09-13T20:38:14.000Z | 2020-09-13T20:38:23.000Z | glscene/Test/parseTest.cpp | Morozov-5F/glsdk | bff2b5074681bf3d2c438216e612d8a0ed80cead | [
"MIT"
] | 1 | 2021-01-10T13:39:51.000Z | 2021-01-12T10:50:56.000Z | glscene/Test/parseTest.cpp | Morozov-5F/glsdk | bff2b5074681bf3d2c438216e612d8a0ed80cead | [
"MIT"
] | null | null | null | #include <string>
#include <exception>
#include <stdexcept>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <glload/gl_3_3.h>
#include <glload/gl_load.hpp>
#include <GL/glfw.h>
#include <glscene/glscene.h>
#include <glutil/glutil.h>
#include <glmesh/glmesh.h>
#include <glimg/glimg.h>
#include <boost/typeof/typeof.hpp>
#include <boost/utility/string_ref.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
int g_width = 640;
int g_height = 480;
glscene::SceneGraph *g_pGraph = NULL;
std::string g_nameCamera("main-camera");
glutil::ObjectData g_objData = {glm::vec3(0, 3.0f, 0), glm::fquat(1.0f, 0.0f, 0.0f, 0.0f)};
glutil::ObjectPole g_objectPole(g_objData, 90.0f/250.0f,
glutil::MB_RIGHT_BTN, NULL);
void init()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
}
//Called to update the display.
//You should call glutSwapBuffers after all of your rendering to display what you rendered.
//If you need continuous updates of the screen, call glutPostRedisplay() at the end of the function.
void display()
{
glViewport(0, 0, g_width, g_height); // Reset The Current Viewport
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glm::mat4 persp = glm::perspective(45.0f, g_width/(float)g_height, 0.1f, 100.0f);
g_pGraph->GetResources().SetUniform("perspective_matrix", persp);
SetMatrixCompose(GetNodeTM(*g_pGraph->FindNode("object")),
g_objectPole.CalcMatrix());
g_pGraph->Render(g_pGraph->GetResources().GetCamera(g_nameCamera).CalcMatrix(), glscene::ORDER_ARBITRARY, 0, "main");
glfwSwapBuffers();
}
//Called whenever the window is resized. The new window size is given, in pixels.
//This is an opportunity to call glViewport or glScissor to keep up with the change in size.
void reshape (int w, int h)
{
g_width = w;
g_height = h;
}
int calc_glfw_modifiers()
{
int ret = 0;
if((glfwGetKey(GLFW_KEY_LALT) == GLFW_PRESS) ||
(glfwGetKey(GLFW_KEY_RALT) == GLFW_PRESS))
ret |= glutil::MM_KEY_ALT;
if((glfwGetKey(GLFW_KEY_LSHIFT) == GLFW_PRESS) ||
(glfwGetKey(GLFW_KEY_RSHIFT) == GLFW_PRESS))
ret |= glutil::MM_KEY_SHIFT;
if((glfwGetKey(GLFW_KEY_LCTRL) == GLFW_PRESS) ||
(glfwGetKey(GLFW_KEY_RCTRL) == GLFW_PRESS))
ret |= glutil::MM_KEY_CTRL;
return ret;
}
void GLFWCALL mouse_button_callback(int button, int action)
{
glm::ivec2 mousePos(0, 0);
glfwGetMousePos(&mousePos.x, &mousePos.y);
int modifiers = calc_glfw_modifiers();
int poleButton = 0;
switch(button)
{
case GLFW_MOUSE_BUTTON_LEFT: poleButton = glutil::MB_LEFT_BTN; break;
case GLFW_MOUSE_BUTTON_MIDDLE: poleButton = glutil::MB_MIDDLE_BTN; break;
case GLFW_MOUSE_BUTTON_RIGHT: poleButton = glutil::MB_RIGHT_BTN; break;
}
g_objectPole.MouseClick((glutil::MouseButtons)poleButton, action == GLFW_PRESS, modifiers, mousePos);
if(g_pGraph)
g_pGraph->GetResources().GetCamera(g_nameCamera).MouseClick(
(glutil::MouseButtons)poleButton, action == GLFW_PRESS, modifiers, mousePos);
}
void GLFWCALL mouse_move_callback(int x, int y)
{
g_objectPole.MouseMove(glm::ivec2(x, y));
if(g_pGraph)
g_pGraph->GetResources().GetCamera(g_nameCamera).MouseMove(glm::ivec2(x, y));
}
void GLFWCALL mouse_wheel_callback(int pos)
{
static int lastPos = pos;
int delta = pos - lastPos;
glm::ivec2 mousePos(0, 0);
glfwGetMousePos(&mousePos.x, &mousePos.y);
int modifiers = calc_glfw_modifiers();
g_objectPole.MouseWheel(delta, modifiers, mousePos);
if(g_pGraph)
g_pGraph->GetResources().GetCamera(g_nameCamera).MouseWheel(delta, modifiers, mousePos);
lastPos = pos;
}
void GLFWCALL character_callback(int unicodePoint, int action)
{
//Only interested in pressing.
if(action == GLFW_RELEASE)
return;
if(unicodePoint > 127)
return;
if(g_pGraph)
g_pGraph->GetResources().GetCamera(g_nameCamera).CharPress((char)unicodePoint);
}
int main(int argc, char** argv)
{
if(!glfwInit())
return -1;
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef DEBUG
glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif
if(!glfwOpenWindow(g_width, g_height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW))
{
glfwTerminate();
return -1;
}
glfwEnable(GLFW_KEY_REPEAT);
glfwSetWindowTitle("Test");
glfwSetWindowSizeCallback(reshape);
glfwSetMouseButtonCallback(mouse_button_callback);
glfwSetMousePosCallback(mouse_move_callback);
glfwSetMouseWheelCallback(mouse_wheel_callback);
glfwSetCharCallback(character_callback);
glload::LoadFunctions();
glutil::RegisterDebugOutput(glutil::STD_OUT);
init();
{
try
{
g_pGraph = glscene::ParseFromFile("test.glscene");
g_objectPole.SetLookatProvider(&g_pGraph->GetResources().GetCamera(g_nameCamera));
}
catch(std::runtime_error &e)
{
printf("%s\n", e.what());
glfwTerminate();
return 0;
}
//Main loop
while(true)
{
display();
if(glfwGetKey(GLFW_KEY_ESC) || !glfwGetWindowParam(GLFW_OPENED))
break;
glfwSleep(0.005f);
}
delete g_pGraph;
}
glfwTerminate();
return 0;
}
| 25.890995 | 119 | 0.710232 | [
"render",
"object"
] |
8bfcc8754f2d4a0f09a7c2fc8114cc0b27b340bf | 3,506 | cpp | C++ | 2D_Engine_Exercise/ModuleRender.cpp | baransrc/UPC_Cpp_Exercises | 2e680c653a2754239d11ca7f8f694d53f536d43d | [
"MIT"
] | 1 | 2021-11-11T21:53:56.000Z | 2021-11-11T21:53:56.000Z | 2D_Engine_Exercise/ModuleRender.cpp | baransrc/UPC_Cpp_Exercises | 2e680c653a2754239d11ca7f8f694d53f536d43d | [
"MIT"
] | null | null | null | 2D_Engine_Exercise/ModuleRender.cpp | baransrc/UPC_Cpp_Exercises | 2e680c653a2754239d11ca7f8f694d53f536d43d | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModuleRender.h"
#include "ModuleWindow.h"
#include "ModuleInput.h"
#include "SDL/include/SDL.h"
#include "Utilfuncs.h"
ModuleRender::ModuleRender()
{
camera.x = 0;
camera.y = 0;
camera.w = SCREEN_WIDTH * SCREEN_SIZE;
camera.h = SCREEN_HEIGHT* SCREEN_SIZE;
camera_lerping = false;
camera_lerp_destination = iPoint(camera.x, camera.y);
camera_lerp_start = camera_lerp_destination;
camera_lerp_speed = 0.0f;
camera_lerp_value = 0.0f;
}
// Destructor
ModuleRender::~ModuleRender()
{}
// Called before render is available
bool ModuleRender::Init()
{
LOG("Creating Renderer context");
bool ret = true;
Uint32 flags = 0;
if(VSYNC == true)
{
flags |= SDL_RENDERER_PRESENTVSYNC;
}
renderer = SDL_CreateRenderer(App->window->window, -1, flags);
if(renderer == nullptr)
{
LOG("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
return ret;
}
update_status ModuleRender::PreUpdate()
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
return UPDATE_CONTINUE;
}
// Called every draw update
update_status ModuleRender::Update()
{
// debug camera
int speed = 1;
/*if(App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT)
App->renderer->camera.y += speed;
if(App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT)
App->renderer->camera.y -= speed;
if(App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT)
App->renderer->camera.x += speed;
if(App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT)
App->renderer->camera.x -= speed;*/
LerpToPosition();
return UPDATE_CONTINUE;
}
update_status ModuleRender::PostUpdate()
{
SDL_RenderPresent(renderer);
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleRender::CleanUp()
{
LOG("Destroying renderer");
//Destroy window
if(renderer != nullptr)
{
SDL_DestroyRenderer(renderer);
}
return true;
}
// Blit to screen
bool ModuleRender::Blit(SDL_Texture* texture, int x, int y, SDL_Rect* section, float speed)
{
bool ret = true;
SDL_Rect rect;
rect.x = (int)(camera.x * speed) + x * SCREEN_SIZE;
rect.y = (int)(camera.y * speed) + y * SCREEN_SIZE;
if(section != NULL)
{
rect.w = section->w;
rect.h = section->h;
}
else
{
SDL_QueryTexture(texture, NULL, NULL, &rect.w, &rect.h);
}
rect.w *= SCREEN_SIZE;
rect.h *= SCREEN_SIZE;
if(SDL_RenderCopy(renderer, texture, section, &rect) != 0)
{
LOG("Cannot blit to screen. SDL_RenderCopy error: %s", SDL_GetError());
ret = false;
}
return ret;
}
void ModuleRender::MoveCameraToPosition(iPoint position, float speed)
{
camera_lerping = true;
camera_lerp_destination = position;
camera_lerp_speed = speed;
camera_lerp_value = 0.0f;
camera_lerp_start = iPoint(camera.x, camera.y);
}
void ModuleRender::LerpToPosition()
{
if (!camera_lerping)
{
return;
}
camera_lerp_value += camera_lerp_speed;
camera_lerp_value = camera_lerp_value > 1.0f ? 1.0f : camera_lerp_value;
camera.x = utilfuncs::lerp(camera_lerp_start.x, camera_lerp_destination.x, camera_lerp_value);
camera.y= utilfuncs::lerp(camera_lerp_start.y, camera_lerp_destination.y, camera_lerp_value);
if (camera.x == camera_lerp_destination.x && camera.y == camera_lerp_destination.y)
{
camera_lerp_value = 1.0f;
}
if (camera_lerp_value == 1.0f)
{
camera_lerping = false;
camera_lerp_value = 0.0f;
camera_lerp_destination = {0,0};
camera_lerp_speed = 0.0f;
camera_lerp_value = 0.0f;
camera_lerp_start = {0,0};
}
}
| 21.120482 | 95 | 0.714489 | [
"render"
] |
8bfcf81c39e6d3077982ab357be3e79a3a49111c | 1,595 | cpp | C++ | src/internal/functions/FunctionsProvider.cpp | st235/xcalc-core | e02acde80537c168c287ef9a5f7d1ccd86a85bb0 | [
"MIT"
] | 1 | 2020-08-20T17:48:34.000Z | 2020-08-20T17:48:34.000Z | src/internal/functions/FunctionsProvider.cpp | st235/xcalc-core | e02acde80537c168c287ef9a5f7d1ccd86a85bb0 | [
"MIT"
] | null | null | null | src/internal/functions/FunctionsProvider.cpp | st235/xcalc-core | e02acde80537c168c287ef9a5f7d1ccd86a85bb0 | [
"MIT"
] | null | null | null | #include "FunctionsProvider.h"
#include <string>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <stdexcept>
#include "../utils/Formatter.h"
#include "../utils/EvaluationError.h"
#include "../terms/Terms.h"
#include "../utils/AngleUnitsProvider.h"
namespace xcalc_internal {
double FunctionsProvider::evaluate(xcalc::DegreeMode degreeMode, const std::string& identifier, double innerExpression) {
std::string lowercaseId = identifier;
std::transform(lowercaseId.begin(), lowercaseId.end(), lowercaseId.begin(), [](unsigned char c) {
return std::tolower(c);
});
if (lowercaseId == Terms::FUNCTION_COS) {
return std::cos(ConvertToRads(degreeMode, innerExpression));
}
if (lowercaseId == Terms::FUNCTION_SIN) {
return std::sin(ConvertToRads(degreeMode, innerExpression));
}
if (lowercaseId == Terms::FUNCTION_TAN) {
return std::tan(ConvertToRads(degreeMode, innerExpression));
}
if (lowercaseId == Terms::FUNCTION_LOG) {
return std::log(innerExpression);
}
if (lowercaseId == Terms::FUNCTION_LOG2) {
return std::log2(innerExpression);
}
if (lowercaseId == Terms::FUNCTION_LOG10) {
return std::log10(innerExpression);
}
if (lowercaseId == Terms::FUNCTION_SQRT) {
return std::sqrt(innerExpression);
}
if (lowercaseId == Terms::FUNCTION_EXP) {
return std::exp(innerExpression);
}
throw EvaluationError(EvaluationError::FUNCTION_NOT_FOUND, Formatter() << "cannot find function: " << identifier >> Formatter::end);
}
}
| 27.033898 | 136 | 0.671473 | [
"transform"
] |
8bfd8cdf62d1e53c198cc9fa7e488dfd49f8d638 | 1,710 | cc | C++ | ns-3-dev/src/internet/model/ipv6-l4-protocol.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 11 | 2015-11-24T11:07:28.000Z | 2021-12-23T04:10:29.000Z | ns-3-dev/src/internet/model/ipv6-l4-protocol.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | null | null | null | ns-3-dev/src/internet/model/ipv6-l4-protocol.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 6 | 2016-03-01T06:32:21.000Z | 2022-03-24T19:31:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2007-2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
*/
#include "ns3/uinteger.h"
#include "ipv6-l4-protocol.h"
namespace ns3
{
NS_OBJECT_ENSURE_REGISTERED (Ipv6L4Protocol);
TypeId Ipv6L4Protocol::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6L4Protocol")
.SetParent<Object> ()
.AddAttribute ("ProtocolNumber", "The IPv6 protocol number.",
UintegerValue (0),
MakeUintegerAccessor (&Ipv6L4Protocol::GetProtocolNumber),
MakeUintegerChecker<int> ())
;
return tid;
}
Ipv6L4Protocol::~Ipv6L4Protocol ()
{
}
void Ipv6L4Protocol::ReceiveIcmp (Ipv6Address icmpSource, uint8_t icmpTtl,
uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo,
Ipv6Address payloadSource, Ipv6Address payloadDestination,
const uint8_t* payload)
{}
} /* namespace ns3 */
| 31.666667 | 92 | 0.673684 | [
"object"
] |
bdf4d2514ebed5fb3160b12c47848c8eb2be875e | 5,097 | hpp | C++ | scenn/experimental/model/sequential_network.hpp | Catminusminus/scenn | 69f09449768deec811acea453f9e081c7c170a56 | [
"MIT"
] | 4 | 2019-08-18T10:54:22.000Z | 2021-05-08T17:44:52.000Z | scenn/experimental/model/sequential_network.hpp | Catminusminus/scenn | 69f09449768deec811acea453f9e081c7c170a56 | [
"MIT"
] | null | null | null | scenn/experimental/model/sequential_network.hpp | Catminusminus/scenn | 69f09449768deec811acea453f9e081c7c170a56 | [
"MIT"
] | null | null | null | #ifndef SCENN_EXPERIMENTAL_MODEL_SEQUENTIAL_NETWORK_HPP
#define SCENN_EXPERIMENTAL_MODEL_SEQUENTIAL_NETWORK_HPP
#include <scenn/util.hpp>
#include <sprout/tuple.hpp>
namespace scenn::experimental {
template <class LossFunction, class... Layers>
class SequentialNetwork {
LossFunction loss;
using T = sprout::tuple<Layers...>;
T layers;
public:
SCENN_CONSTEXPR SequentialNetwork(LossFunction &&loss, Layers &&... layers)
: loss(loss), layers(sprout::make_tuple(layers...)){};
SCENN_CONSTEXPR SequentialNetwork(const LossFunction &loss,
const Layers &... layers)
: loss(loss), layers(sprout::make_tuple(layers...)){};
private:
template <size_t index>
SCENN_CONSTEXPR auto get_forward_input() {
if constexpr (index == 0) {
return sprout::get<index>(layers).input_data;
} else {
return sprout::get<index - 1>(layers).output_data;
}
}
template <size_t index>
SCENN_CONSTEXPR auto get_backward_input() {
if constexpr (index + 1 == std::tuple_size_v<T>) {
return sprout::get<index>(layers).input_delta;
} else {
return sprout::get<index + 1>(layers).output_delta;
}
}
template <std::size_t index = 0, class I>
SCENN_CONSTEXPR auto update_impl_impl(I rate) {
if constexpr (index < std::tuple_size_v<T>) {
sprout::get<index>(layers).update_params(rate);
update_impl_impl<index + 1>(rate);
}
}
template <class I>
SCENN_CONSTEXPR auto update_params(I rate) {
update_impl_impl(rate);
}
template <std::size_t index = 0>
SCENN_CONSTEXPR auto clear_impl_impl() {
if constexpr (index < std::tuple_size_v<T>) {
sprout::get<index>(layers).clear_deltas();
clear_impl_impl<index + 1>();
}
}
SCENN_CONSTEXPR auto clear_deltas() { clear_impl_impl(); }
template <class Train, class I>
SCENN_CONSTEXPR auto update(Train &&mini_batch, I &&learning_rate) {
auto mini_learning_rate =
learning_rate / sprout::get<0>(mini_batch.shape());
update_params(mini_learning_rate);
clear_deltas();
}
template <std::size_t index = 0>
SCENN_CONSTEXPR auto forward_impl() {
if constexpr (index < std::tuple_size_v<T>) {
sprout::get<index>(layers).forward(get_forward_input<index>());
forward_impl<index + 1>();
}
}
template <std::size_t index = std::tuple_size_v<T> - 1>
SCENN_CONSTEXPR auto backward_impl() {
sprout::get<index>(layers).backward(get_forward_input<index>(),
get_backward_input<index>());
if constexpr (index > 0) {
backward_impl<index - 1>();
}
}
template <class Train>
SCENN_CONSTEXPR auto forward_backward(Train &&mini_batch) {
for (auto &&[x, y] : mini_batch.get_data()) {
sprout::get<0>(layers).input_data = x.transposed();
forward_impl();
sprout::get<std::tuple_size_v<T> - 1>(layers).input_delta =
loss.loss_derivative(
sprout::get<std::tuple_size_v<T> - 1>(layers).output_data,
y.transposed());
backward_impl();
#ifdef SCENN_DISABLE_CONSTEXPR
std::cout << loss.loss_function(
single_forward(x.transposed()).transposed(), y)
<< std::endl;
#endif
}
}
template <class Train, class I>
SCENN_CONSTEXPR auto train_batch(Train &&mini_batch, I learning_rate) {
forward_backward(mini_batch);
update(std::forward<Train>(mini_batch), learning_rate);
}
template <std::size_t Index = 0, std::size_t Upper, std::size_t Interval,
class Train, class T>
SCENN_CONSTEXPR auto train_impl(Train &&training_data, T &&learning_rate) {
if constexpr (Index < Upper) {
auto data = training_data.template slice<Index, Index + Interval>();
train_batch(std::move(data), learning_rate);
train_impl<Index + Interval, Upper, Interval, Train, T>(
std::forward<Train>(training_data), std::forward<T>(learning_rate));
}
}
public:
template <std::size_t MiniBatchSize, class Train, class T>
SCENN_CONSTEXPR auto train(Train &&training_data, std::size_t epochs,
T &&learning_rate) {
constexpr auto N = std::remove_reference_t<Train>::length();
for (std::size_t epoch = 0; epoch < epochs; ++epoch) {
auto shuffled_training_data = training_data.shuffle(epoch);
train_impl<0, N, MiniBatchSize, std::remove_reference_t<Train> &&, T>(
std::move(shuffled_training_data), std::forward<T>(learning_rate));
}
return *this;
}
template <class Test>
SCENN_CONSTEXPR auto single_forward(Test &&x) {
sprout::get<0>(layers).input_data = std::forward<Test>(x);
forward_impl();
return sprout::get<std::tuple_size_v<T> - 1>(layers).output_data;
}
template <class Test>
SCENN_CONSTEXPR auto evaluate(Test &&test_data) {
auto sum = 0;
for (auto &&[x, y] : std::forward<Test>(test_data).get_data()) {
if (single_forward(x.transposed()).transposed().argmax() == y.argmax())
++sum;
}
return sum;
}
};
} // namespace scenn::experimental
#endif
| 33.754967 | 78 | 0.653325 | [
"shape"
] |
bdfd5a7233ddc700a260bf50adfeb61d64372bcc | 633 | cpp | C++ | source/S3/AIZ/Dummy.cpp | theclashingfritz/sonic-3-remastered | 36210fa69d468b4d90cf26a67c6be0410b53c595 | [
"Apache-2.0",
"MIT"
] | 3 | 2018-07-26T02:12:08.000Z | 2022-02-27T20:57:05.000Z | source/S3/AIZ/Dummy.cpp | theclashingfritz/sonic-3-remastered | 36210fa69d468b4d90cf26a67c6be0410b53c595 | [
"Apache-2.0",
"MIT"
] | null | null | null | source/S3/AIZ/Dummy.cpp | theclashingfritz/sonic-3-remastered | 36210fa69d468b4d90cf26a67c6be0410b53c595 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "Dummy.h"
#include <LevelScene.h>
void IDummy::Create() {
Active = true;
Priority = false;
W = 32;
H = 32;
Sprite = App->Sprites["Ring"];
}
void IDummy::Update() {
}
void IDummy::Render(int CamX, int CamY) {
G->PaletteShift(0);
G->DrawSprite(Sprite, (int)X - CamX, (int)Y - CamY, 0.1f, 0, IE::CenterAlign | IE::MiddleAlign);
if (Scene->ShowHitboxes) {
G->PaletteShift(-1);
G->DrawRectangle((int)X - CamX - W / 2, (int)Y - CamY - H / 2, -2.11f, W, H, IColor(1, 1, 1, 0.5f));
}
}
int IDummy::OnCollisionWithPlayer(int PlayerID, int HitFrom, int Data) {
return 1;
}
| 21.1 | 108 | 0.582938 | [
"render"
] |
bdfd9e692cf583c6377af3102c082583e08167f3 | 20,548 | hpp | C++ | src/abstraction.hpp | yinanl/rocs | bf2483903e39f4c0ea254a9ef56720a1259955ad | [
"BSD-3-Clause"
] | null | null | null | src/abstraction.hpp | yinanl/rocs | bf2483903e39f4c0ea254a9ef56720a1259955ad | [
"BSD-3-Clause"
] | null | null | null | src/abstraction.hpp | yinanl/rocs | bf2483903e39f4c0ea254a9ef56720a1259955ad | [
"BSD-3-Clause"
] | null | null | null | /**
* The definition of an abstraction class.
*
* Created by Yinan Li on Aug. 30, 2017.
*
* Hybrid Systems Group, University of Waterloo.
*/
#ifndef _abstraction_h_
#define _abstraction_h_
#include <armadillo>
#include <boost/dynamic_bitset.hpp>
#include <functional>
#include <set>
#include "transition.hpp"
#include "system.hpp"
namespace rocs {
// /**
// * Boolean function defining a set.
// */
// typedef bool (*gset)(const ivec &x);
/**
* \brief Weighting function (of edges) of transitions.
*/
typedef double (*WGT)(std::vector<double> &x0,
std::vector<double> &x1,
std::vector<double> &u0);
/**
* \brief An abstraction class of a dynamical system.
*
* This is a template class where the typename %S will be replaced by the actual dynamical system type.
*/
template<typename S>
class abstraction {
public:
grid _x; /**< A grid of states */
S *_ptrsys; /**< A pointer to the system object */
std::vector<int> _labels; /**< A vector of labels for the state grid _x */
WGT _wf; /**< Weighting callback function */
fts _ts; /**< The finite transition system */
/**
* \brief A constructor.
*
* Assign user defined system dynamics to an abstraction.
*
* @param[in] sys The pointer to a system object
*/
abstraction(S *sys) : _x(sys->_xdim), _ptrsys(sys), _wf(NULL) {}
/**
* \brief A constructor.
*
* Assign user defined system dynamics as well as a weighting function to an abstraction.
*
* @param[in] sys The pointer to a system object
* @param[in] wf A weighting function
*/
abstraction(S *sys, WGT wf) : _x(sys->_xdim), _ptrsys(sys), _wf(wf) {}
/**
* \brief Initialize the states in the abstraction.
*
* This includes
* - assigning a grid of states by the given bounds and grid size.
* - assigning labels
*
* @param[in] eta An array of grid size
* @param[in] xlb An array of lower bounds
* @param[in] xub An array of upper bounds
*/
void init_state(const double eta[], const double xlb[], const double xub[]) {
_x.gridding(eta, xlb, xub);
_labels.resize(_x._nv+1, 0); //the extra one is an out-of-domain node
}
/**
* \brief Initialize the finite transition system.
*
* Assign the number of predecessing (fts._npre) and successing (fts._npost) states.
*/
bool init_transitions() {
if (_x._nv > 0 && _ptrsys->_ugrid._nv > 0) {
_ts.init(_x._nv+1, _ptrsys->_ugrid._nv);
} else {
std::cout << "Transition initialization failed: gridding problem.\n";
return false;
}
return true;
}
/**
* \brief Get state indicies of a given hyper-rectangle area.
*
* The area is given by its lower and upper bounds.
* It is allowed to be out of domain, but only the inside domain part is considered.
*
* @param xlb The lower bound of the area
* @param xub The upper bound of the area
* @return a list of indicies.
*/
std::vector<size_t> get_discrete_states(const double xlb[], const double xub[]) {
ivec states(_x._dim);
for (int i = 0; i < _x._dim; ++i) {
states.setval(i, interval(xlb[i], xub[i]));
}
return _x.subset(states, false, false); // allow area out of domain, and collect grids intersect the area
}
/**
* Get discrete state indicies of a given area:
* \f$\{x|g(x)=\text{True}\}\f$.
*
* @param[in] g The function that determines if x is inside the set
* @return a list of indicies.
*/
std::vector<size_t> get_discrete_states(std::function<bool(const ivec &)> g) {
std::vector<size_t> r;
if (_x._nv>0 && !_x._data.empty()) {
ivec x(_x._dim);
for (int i = 0; i < _x._nv; ++i) {
/* set interval x */
for (int j = 0; j < _x._dim; ++j) {
x.setval(j, interval(_x._data[i][j]-_x._gw[j]/2, _x._data[i][j]+_x._gw[j]/2));
}
/* test */
if (g(x)) {
r.push_back(i);
}
}
} else {
std::cout << "get_discrete_states: a grid of state space hasn't been iniitlized.\n";
}
return r;
}
/**
* \brief A template function that assigns labels to the state grid.
*
* @param[in] labeling A function that returns the label of a grid id
*/
template<typename F>
void assign_labels(F labeling) {
for (size_t i = 0; i < _x._nv; ++i) {
if(_labels[i] > -1)
_labels[i] = labeling(i);
}
}
/**
* \brief Assign the label to the out-of-domain part.
*
* @param[in] label The label given to the out-of-domain part
*/
void assign_label_outofdomain(int label) {
_labels[_x._nv] = label;
}
/**
* \brief Assign transitions with robustness margins e1,e2.
*
* This function constructs an fts according to the given system.
*
* @param[in] e1 the robustness margin at the initial point.
* @param[in] e2 the robustness margin at the end point.
* @return whether construction is successful.
*/
bool assign_transitions(const double e1[], const double e2[]) {
/* Initialize _ts (the transition system) */
if (!init_transitions())
return false;
int n = _x._dim;
size_t nx = _x._nv;
size_t nu = _ptrsys->_ugrid._nv;
// std::cout << "dim=" << n << ',' << "#states=" << nx << ",#inputs=" << nu <<'\n';
ivec ie2(n);
for (int j = 0; j < n; ++j)
ie2.setval(j, interval(-e2[j],e2[j]));
std::vector<double> xmin(n), xmax(n);
for (int k = 0; k < n; ++k) {
xmin[k] = _x._valmin[k]-_x._gw[k]/2.0;
xmax[k] = xmin[k] + _x._gw[k]*_x._size[k];
}
ivec xbds(n);
for (int k = 0; k < n; ++k)
xbds.setval(k, interval(xmin[k], xmax[k]));
/* Out-of-domain indicator:
* 0:inside, 1:fully outside, 2:partially outside
*/
std::vector<int> out_of_domain(nx*nu,0);
ivec y0(n);
std::vector<ivec> yt(nu, ivec(n));
std::vector<double> ytl(n), ytu(n);
size_t r, postid;
double idu;
std::vector<size_t> il(n), iu(n);
std::vector<size_t> stpost(nx*nu, 0), rngpost(nx*nu*n, 0);
/* loop state grids */
for (size_t row = 0; row < nx; ++row) {
/* the avoid points (labeled by -1) has no outgoing edges */
if (_labels[row] == -1)
continue;
/* compute reachable set */
for (int k = 0; k < n; ++k) {
y0.setval(k, interval(_x._data[row][k]-_x._gw[k]/2.0,
_x._data[row][k]+_x._gw[k]/2.0));
// y0.setval(k, interval(_x._data[row][k]-_x._gw[k]/2.0-e1[k],
// _x._data[row][k]+_x._gw[k]/2.0+e1[k]));
}
_ptrsys->get_reach_set(yt, y0);
if (!yt.empty()) {
/* loop inputs */
for (size_t col = 0; col < nu; ++col) {
// yt[col] += ie2;
// /* Skip the yt[col] that is out of the domain _bds.
// * No need to delete the transitions to avoid area, since they are sinks.
// * */
// if (!xbds.isin(yt[col]))
// continue;
// /** Using this line will probably result in failure in synthesis **/
// // if (!_x._bds.isin(yt[col]))
// // continue;
if(xbds.isout(yt[col])) { //fully out of domain
out_of_domain[row*nu+col] = 1;
_ts._npost[row*nu+col] = 1;
_ts._ptrpost[row*nu+col] = _ts._ntrans;
++_ts._ntrans;
continue;
}
if(!xbds.isin(yt[col])) {//partially inside domain
out_of_domain[row*nu+col] = 2;
/* Take intersection of xbds and yt[col] */
for(int k = 0; k < n; ++k) {
ytl[k] = yt[col][k].getinf()<xmin[k] ? xmin[k] : yt[col][k].getinf();
ytu[k] = yt[col][k].getsup()>xmax[k] ? xmax[k] : yt[col][k].getsup();
}
} else { //fully inside domain
yt[col].getinf(ytl);
yt[col].getsup(ytu);
}
/* compute the indices of the bounds of the yt[col] */
_ts._npost[row*nu + col] = 1;
for (int k = 0; k < n; ++k) {
il[k] = static_cast<size_t> ((ytl[k]-_x._valmin[k])/_x._gw[k]+0.5);
idu = (ytu[k]-_x._valmin[k])/_x._gw[k] + 0.5;
iu[k] = static_cast<size_t> (idu);
if (std::fabs(idu - iu[k]) < EPSIVAL)
iu[k] = iu[k] - 1;
// if (std::fabs(fmod(ytu[k]-_x._valmin[k], _x._gw[k]) - _x._gw[k]/2.) < EPSIVAL) /* fmod is slow */
// iu[k] = static_cast<size_t> ((ytu[k]-_x._valmin[k])/_x._gw[k]);
// else
// iu[k] = static_cast<size_t> ((ytu[k]-_x._valmin[k]+_x._gw[k]/2.0)/_x._gw[k]);
stpost[row*nu+col] += _x._base[k] * il[k]; /* compute the smallest post ID of all the post grid points */
rngpost[n*(row*nu+col)+k] = iu[k] - il[k] + 1;
_ts._npost[row*nu+col] *= rngpost[n*(row*nu+col)+k];
}
_ts._ptrpost[row*nu+col] = _ts._ntrans;
_ts._ntrans += _ts._npost[row*nu+col];
/* Add an out-of-domain transition */
if(out_of_domain[row*nu+col]) {
++_ts._npost[row*nu+col];
++_ts._ntrans;
}
// /********** logging **********/
// if(row == 0 && col == 16) {
// std::cout << "y0=" << y0 << '\n'
// << "yt=" << yt[col] << '\n'
// << "out_of_domain=" << out_of_domain[row*nu+col] << '\n';
// if(out_of_domain[row*nu+col]>1) {
// std::cout << "Intersection with domain: ";
// for(int k = 0; k < n; ++k)
// std::cout << '[' << ytl[k] << ',' << ytu[k] << "] ";
// std::cout << '\n';
// }
// std::cout << "starting address of post transitions: "
// << _ts._ptrpost[row*nu+col] << '\n';
// std::cout << "# of post transitions: "
// << _ts._npost[row*nu+col] << '\n';
// }
// /********** logging **********/
} // end input loop
} else {
yt.resize(nu, ivec(n));
}// end yt empty check
} //end loop state grids
/* Assign out-of-domain posts */
if(_labels[nx] >= 0) {//assign a self-loop if the out-of-domain node is not avoided
for(size_t col = 0; col < nu; ++col) {
_ts._npost[nx*nu+col] = 1;
_ts._ptrpost[nx*nu+col] = _ts._ntrans;
++_ts._ntrans;
}
}
/* assign _idpost, _cost and _npre */
_ts._idpost.resize(_ts._ntrans);
double w;
// for (size_t row = 0; row < nx; ++row) {
// for (size_t col = 0; col < nu; ++col) {
// /* assign post grid point IDs to _idpost */
// if (_ts._npost[row*nu+col] == 0)
// continue;
// for (int l = 0; l < _ts._npost[row*nu+col]; ++l) {
// postid = stpost[row*nu+col];
// r = l;
// for (int k = 0; k < n; ++k) {
// postid += (r % rngpost[n*(row*nu+col)+k])*_x._base[k];
// r = r / rngpost[n*(row*nu+col)+k];
// }
// _ts._idpost[_ts._ptrpost[row*nu+col]+l] = postid;
// /* assign cost (worst case): maximum from all posts */
// if (_wf) {
// w = (*_wf)(_x._data[row], _x._data[postid], _ptrsys->_ugrid._data[col]);
// _ts._cost[row*nu+col] = _ts._cost[row*nu+col]<w ? w : _ts._cost[row*nu+col];
// }
// _ts._npre[postid*nu+col] ++;
// }
// } /* end for col */
// } /* end for row */
int num_post;
size_t ptrout;
for (size_t row = 0; row < nx; ++row) {
for (size_t col = 0; col < nu; ++col) {
// /********** logging **********/
// if(row == 0 && col == 16) {
// std::cout << "post nodes: ";
// }
// /********** logging **********/
/* assign post grid point IDs to _idpost */
if(out_of_domain[row*nu+col] != 1) {//intersect with domain
if(out_of_domain[row*nu+col]) {
num_post = _ts._npost[row*nu+col] - 1;
} else {
num_post = _ts._npost[row*nu+col];
}
for (int l = 0; l < num_post; ++l) {
postid = stpost[row*nu+col];
r = l;
for (int k = 0; k < n; ++k) {
postid += (r % rngpost[n*(row*nu+col)+k])*_x._base[k];
r = r / rngpost[n*(row*nu+col)+k];
}
_ts._idpost[_ts._ptrpost[row*nu+col]+l] = postid;
// /********** logging **********/
// if(row == 0 && col == 16) {
// std::cout << "ptrpost[" << _ts._ptrpost[row*nu+col]+l << "]="
// << postid << '\n';
// }
// /********** logging **********/
/* assign cost (worst case): maximum from all posts */
if (_wf) {
w = (*_wf)(_x._data[row], _x._data[postid], _ptrsys->_ugrid._data[col]);
_ts._cost[row*nu+col] = _ts._cost[row*nu+col]<w ? w : _ts._cost[row*nu+col];
}
++_ts._npre[postid*nu+col];
// /********** logging **********/
// if(postid == 0 && col == 16)
// std::cout << "current # of predecessor of node x=0 under u=16: "
// << _ts._npre[postid*nu+col] << '\n';
// /********** logging **********/
}
}
if(out_of_domain[row*nu+col]) {//fully or partially out of domain
ptrout = _ts._ptrpost[row*nu+col]+_ts._npost[row*nu+col]-1;
_ts._idpost[ptrout] = nx; //post node is xout
++_ts._npre[nx*nu+col];
// /********** logging **********/
// if(row == 0 && col == 16) {
// std::cout << "ptrpost[" << ptrout << "]="
// << nx << '\n';
// }
// /********** logging **********/
}
} /* end for col */
} /* end for row */
if(_labels[nx] >= 0) {//assign a self-loop if the out-of-domain node is not avoided
for(size_t col = 0; col < nu; ++col) {
_ts._idpost[_ts._ptrpost[nx*nu+col]] = nx; //xout is a sink
++_ts._npre[nx*nu+col];
}
}
/* Determine pre's by post's: loop _npost and _idpost */
_ts._idpre.resize(_ts._ntrans); // initialize the size of pre's
/* assign _ptrpre by _npre */
size_t sum = 0;
for (size_t row = 0; row < nx+1; ++row) {
for (size_t col = 0; col < nu; ++col) {
_ts._ptrpre[row*nu+col] = sum;
sum += _ts._npre[row*nu+col];
}
}
assert(sum == _ts._ntrans);
/* assign _idpre */
std::vector<size_t> precount(nu*(nx+1), 0);
size_t idtspre;
for (size_t row = 0; row < nx+1; ++row) {
for (size_t col = 0; col < nu; ++col) {
// /********** logging **********/
// if (row == 0 && col == 16) {
// std::cout << "Assign pre transitions:\n";
// }
// /********** logging **********/
for (int ip = 0; ip < _ts._npost[row*nu+col]; ++ip) {
postid = _ts._idpost[_ts._ptrpost[row*nu+col]+ip];
idtspre = postid * nu + col;
_ts._idpre[_ts._ptrpre[idtspre]+precount[idtspre]++] = row;
// precount[idtspre]++;
// /********** logging **********/
// if (row == 0 && col == 16) {
// std::cout << postid << ": idpre[" << _ts._ptrpre[idtspre]
// << '+' << precount[idtspre]-1 << "]="
// << row << '\n';
// }
// if(_ts._ptrpre[idtspre]+precount[idtspre]-1 == 46) {
// std::cout << "idpre[46] is filled at: "
// << row << "->(" << col << ")->" << postid
// << '\n';
// }
// /********** logging **********/
}
}
}
return true;
}
/**
* \brief Assign transitions by subgridding.
* see assign_transitions()
*
* @param[in] rp[] the pointer to an array of relative subgridding size
* @return whether construction is successful.
*/
bool assign_transitions_subgridding(const double rp[]) {
/*********** logging ***********/
// std::fstream logfile;
// logfile.open("y.log", std::ios::out | std::ios::ate);
// std::fstream logfile2;
// logfile2.open("post946.log", std::ios::out | std::ios::ate);
/*********** logging ***********/
if (!init_transitions())
return false;
int n = _x._dim;
size_t nx = _x._nv;
size_t nu = _ptrsys->_ugrid._nv;
/* compute the number of sub grid points */
size_t subnv = 1;
std::vector<double> subgw(n);
std::vector<size_t> number(n);
for (int k = 0; k < n; ++k) {
number[k] = ceil(1.0 / rp[k]);
subgw[k] = _x._gw[k] / number[k];
subnv *= number[k];
}
// std::cout << "number of subgrids: " << subnv << '\n';
/* transition computation by interval subgridding: loop states */
std::vector<double> xmin(n);
// std::vector<double> xc(n);
ivec v(n);
std::vector<size_t> subposts;
std::vector<std::vector<double>> sub(subnv, std::vector<double> (n));
std::vector<size_t>::iterator iter;
int np = 0;
/* loop state grids */
for (size_t row = 0; row < nx; ++row) {
if (_labels[row] == -1) /* skip the avoid grid points (labeled by -1) */
continue;
/* compute reachable set by interval subgridding */
if (subnv == 1) { // no subgridding
sub[0] = _x._data[row];
} else { // subnv > 1
for (int k = 0; k < n; ++k) {
// xmin[k] = xc[k] - _gw[k]/2. + _rp[k]*_gw[k]/2.;
xmin[k] = _x._data[row][k] - _x._gw[k]/2. + subgw[k]/2.;
}
_x.griddingHelper(sub, xmin, subgw, number, subnv);
}
std::vector< std::vector<ivec> > ys(subnv, std::vector<ivec> (nu)); // ys[vi][ui]
for (int vi = 0; vi < subnv; ++vi) {
for (int k = 0; k < n; ++k) {
v.setval(k, interval(sub[vi][k]-subgw[k]/2, sub[vi][k]+subgw[k]/2));
} // assign v
/* get a list of post intervals w.r.t. different inputs */
_ptrsys->get_reach_set(ys[vi], v);
} // end for loop (subgrid)
/* loop inputs */
for (size_t col = 0; col < nu; ++col) {
std::set<size_t> posts;
/*********** logging ***********/
// logfile << col << ":\n";
/*********** logging ***********/
/* loop subgrids: collect all unique posts */
for (int vi = 0; vi < subnv; ++vi) {
subposts = _x.subset(ys[vi][col], true, false);
if (subposts.empty()) { // out of domain
np = 0;
posts.clear();
break; // jump out of the subgrid loop
} else {
posts.insert(subposts.begin(), subposts.end());
} // end if
/*********** logging ***********/
// logfile << ys[vi][col] << "(";
// for (int i = 0; i < subposts.size(); ++i)
// logfile << subposts[i] << ',';
// logfile << ")\n";
/*********** logging ***********/
} // end collecting posts
/* assign posts */
if (!posts.empty()) {
/*********** logging ***********/
// logfile2 << col << '(' << posts.size() << "): ";
/*********** logging ***********/
_ts._npost[row*nu + col] = posts.size();
_ts._ptrpost[row*nu + col] = _ts._ntrans;
_ts._ntrans += posts.size();
for (std::set<size_t>::iterator it = posts.begin(); it != posts.end(); ++it) {
_ts._idpost.push_back(*it);
/* record the number of pres for state (*it) */
_ts._npre[(*it) * nu + col] ++;
/*********** logging ***********/
// logfile2 << *it << ", ";
/*********** logging ***********/
}
// logfile2 << '\n';
} // end transition assignment
} // end input loop
// /*********** logging ***********/
// logfile << '\n';
// /*********** logging ***********/
} // end for loop states
std::cout << "# of transitions: " << _ts._ntrans << '\n';
std::cout << "length of _idpost: " << _ts._idpost.size() << '\n';
assert(_ts._idpost.size() == _ts._ntrans);
/* assign _cost */
double w;
size_t postid;
for (size_t row = 0; row < nx; ++row) {
for (size_t col = 0; col < nu; ++col) {
/* assign post grid point IDs to _idpost */
if (_ts._npost[row*nu+col] == 0)
continue;
for (int l = 0; l < _ts._npost[row*nu+col]; ++l) {
/* assign cost (worst case): maximum from all posts */
postid = _ts._ptrpost[row*nu+col]+l;
if (_wf) {
w = (*_wf)(_x._data[row], _x._data[_ts._idpost[postid]], _ptrsys->_ugrid._data[col]);
_ts._cost[row*nu+col] = _ts._cost[row*nu+col]<w ? w : _ts._cost[row*nu+col];
}
}
} /* end for col */
} /* end for row */
/* determine pre's by post's: loop _ts._npost and _idpost */
_ts._idpre.resize(_ts._ntrans); // initialize the size of pre's
size_t sum = 0;
for (size_t row = 0; row < nx; ++row) {
for (size_t col = 0; col < nu; ++col) {
_ts._ptrpre[row*nu + col] = sum;
sum += _ts._npre[row*nu + col];
}
}
/* assign _idpre */
std::vector<size_t> precount(_ptrsys->_ugrid._nv*_x._nv, 0);
size_t idtspre;
for (size_t row = 0; row < nx; ++row) {
for (size_t col = 0; col < nu; ++col) {
for (int ip = 0; ip < _ts._npost[row*nu + col]; ++ip) {
idtspre = _ts._idpost[_ts._ptrpost[row*nu+col] + ip]*nu + col;
_ts._idpre[_ts._ptrpre[idtspre] + precount[idtspre]] = row;
precount[idtspre] ++;
}
}
}
std::cout << "length of _idpre: " << _ts._idpre.size() << '\n';
assert(_ts._idpre.size() == _ts._ntrans);
// logfile.close();
// logfile2.close();
return true;
}
}; /* the abstraction class */
} // namespace rocs
#endif
| 32.982343 | 112 | 0.524236 | [
"object",
"vector"
] |
da140a2d0c513f1a940299bdf003e3632c40c36d | 2,262 | cpp | C++ | src/MathClass/FanucModel/RoboModelGeneral/RoboModelGeneral.cpp | ptrdiff/ComputeUnit | 72d1ef2939667636f4a6390b8f3706be7c841602 | [
"Apache-2.0"
] | 1 | 2021-02-18T18:14:12.000Z | 2021-02-18T18:14:12.000Z | src/MathClass/FanucModel/RoboModelGeneral/RoboModelGeneral.cpp | robot-lab/rcs-control-un | 72d1ef2939667636f4a6390b8f3706be7c841602 | [
"Apache-2.0"
] | 33 | 2018-09-05T18:38:19.000Z | 2018-10-01T13:41:46.000Z | src/MathClass/FanucModel/RoboModelGeneral/RoboModelGeneral.cpp | robot-lab/rcs-control-unit | 72d1ef2939667636f4a6390b8f3706be7c841602 | [
"Apache-2.0"
] | null | null | null | #include "RoboModelGeneral.h"
#include <opencv2/core.hpp>
struct nikita::RoboModel::DhParameters
{
double _dParam;
double _qParam;
double _aParam;
double _alphaParam;
DhParameters(const double d, const double q, const double a, const double alpha)
: _dParam(d),
_qParam(q),
_aParam(a),
_alphaParam(alpha)
{
}
};
nikita::RoboModel::RoboModel(std::vector<std::array<double, 4>> input)
{
_kinematicChain.reserve(input.size());
for (auto &i : input)
_kinematicChain.emplace_back(i[0], i[1], i[2], i[3]);
}
nikita::RoboModel::~RoboModel()
= default;
cv::Mat nikita::RoboModel::forwardTask(std::vector<double> inputq)
{
_kinematicChain[0]._qParam = inputq[0];
cv::Mat transformMatrix = prevMatTransform(0);
for (std::vector<double>::size_type i = 1; i < inputq.size(); ++i)
{
_kinematicChain[i]._qParam = inputq[i];
transformMatrix = transformMatrix * prevMatTransform(i);
}
return transformMatrix;
}
cv::Mat nikita::RoboModel::prevMatTransform(const int i)
{
cv::Mat result(4, 4, CV_64F);
result.at<double>(0, 0) = cos(_kinematicChain[i]._qParam);
result.at<double>(0, 1) = -cos(_kinematicChain[i]._alphaParam) *
sin(_kinematicChain[i]._qParam);
result.at<double>(0, 2) = sin(_kinematicChain[i]._alphaParam) * sin(_kinematicChain[i]._qParam);
result.at<double>(0, 3) = _kinematicChain[i]._aParam * cos(_kinematicChain[i]._qParam);
result.at<double>(1, 0) = sin(_kinematicChain[i]._qParam);
result.at<double>(1, 1) = cos(_kinematicChain[i]._alphaParam) * cos(_kinematicChain[i]._qParam);
result.at<double>(1, 2) = -sin(_kinematicChain[i]._alphaParam) *
cos(_kinematicChain[i]._qParam);
result.at<double>(1, 3) = _kinematicChain[i]._aParam * sin(_kinematicChain[i]._qParam);
result.at<double>(2, 0) = 0;
result.at<double>(2, 1) = sin(_kinematicChain[i]._alphaParam);
result.at<double>(2, 2) = cos(_kinematicChain[i]._alphaParam);
result.at<double>(2, 3) = _kinematicChain[i]._dParam;
result.at<double>(3, 0) = result.at<double>(3, 1) = result.at<double>(3, 2) = 0;
result.at<double>(3, 3) = 1;
return result;
}
| 32.782609 | 100 | 0.641468 | [
"vector"
] |
da22b6652240291c3a78d8ee0539dabfb4be1816 | 14,007 | hpp | C++ | legacy/db/serializable.hpp | veluca93/cpp-db-lib | 6b8599a7cfca299fed5c72b21c5afbb1b75d1f0c | [
"MIT"
] | null | null | null | legacy/db/serializable.hpp | veluca93/cpp-db-lib | 6b8599a7cfca299fed5c72b21c5afbb1b75d1f0c | [
"MIT"
] | null | null | null | legacy/db/serializable.hpp | veluca93/cpp-db-lib | 6b8599a7cfca299fed5c72b21c5afbb1b75d1f0c | [
"MIT"
] | null | null | null | #pragma once
#include <kj/filesystem.h>
#include <tuple>
#include <utility>
#include "db/json.hpp"
#include "db/util.hpp"
#include "db/value.hpp"
// NOTE: do not declare containers of Values as members. Instead, use
// Collection.
#define DECLARE_MEMBER_N(tp, name_, json_name) \
template <typename T> \
struct name_##_m { \
using type_ = typename util::argument_type<void(tp)>::type; \
using value_type_ = db::Value<T, type_>; \
\
protected: \
using parent_t = T; \
static constexpr const char* json_name_ = json_name; \
\
template <typename... Args> \
name_##_m(Args... args) : name_##_priv(std::move(args)...) {} \
name_##_m(util::JsonConstructorTag(), \
kj::Maybe<kj::Own<const kj::Directory>>&& dir, T* parent, \
const json& j) \
: name_##_priv(util::JsonConstructorTag(), std::move(dir), json_name_, \
parent, j) {} \
\
json Serialize() const { return name_.Serialize(); } \
\
struct Editor_ : protected db::detail::ValueEditor<T, type_> { \
protected: \
using BaseCls = db::detail::ValueEditor<T, type_>; \
using type = typename name_##_m::type_; \
friend name_##_m<T>; \
template <typename U> \
using parent_t = name_##_m<U>; \
Editor_(db::detail::ValueEditor<T, type_> e) : BaseCls(std::move(e)) {} \
Editor_(Editor_&& e) : BaseCls(std::move(e)) {} \
\
public: \
db::detail::ValueEditor<T, type_>& name_ = *this; \
}; \
\
protected: \
auto* Ptr() { return &name_##_priv; } \
auto& Raw() { return name_##_priv; } \
const auto& Raw() const { return name_##_priv; } \
const auto& Get() const { return *Raw(); } \
auto Edit() { return Editor_(name_##_priv.Edit(/*autocommit=*/false)); } \
\
private: \
value_type_ name_##_priv; \
\
public: \
using name_##_t = db::detail::Value<T, type_>; \
typename ::db::detail::member_ref<value_type_>::type name_ = name_##_priv; \
};
#define DECLARE_MEMBER(type, name) DECLARE_MEMBER_N(type, name, #name)
namespace db {
template <typename U, template <typename T> class... Args>
class Data;
namespace detail {
template <typename T, typename = void>
struct member_ref {
using type = const T&;
};
template <typename U, typename T>
struct member_ref<db::Value<U, T>, std::enable_if_t<T::kIsSubObject>> {
using type = T&;
};
template <typename U, typename... Args>
class DataEditor : public Args... {
template <typename T>
void TryUndoCommit(size_t& done) {
if (!done) return;
this->T::Rollback();
done--;
}
template <typename T>
void TryCommit(size_t& done, bool& fail) {
if (fail) return;
if (this->T::Commit()) {
done++;
} else {
fail = true;
}
}
void UndoAllCommits(size_t& done) { (TryUndoCommit<Args>(done), ...); }
protected:
DataEditor(DataEditor&& other) : Args(std::move((Args&)other))... {
obj = other.obj;
autocommit_ = other.autocommit_;
finalized_ = other.finalized_;
rolled_back_ = other.rolled_back_;
other.finalized_ = true;
other.rolled_back_ = true;
other.obj = nullptr;
}
DataEditor& operator=(DataEditor&& other) {
((this->Args::editor_ = std::move((Args&)other)), ...);
if (this == &other) return *this;
obj = other.obj;
autocommit_ = other.autocommit_;
finalized_ = other.finalized_;
rolled_back_ = other.rolled_back_;
other.finalized_ = true;
other.rolled_back_ = true;
other.obj = nullptr;
return *this;
}
bool Commit() {
KJ_REQUIRE(!finalized_);
finalized_ = true;
size_t done = 0;
bool fail = false;
try {
(TryCommit<Args>(done, fail), ...);
} catch (...) {
UndoAllCommits(done);
throw;
}
if (fail) {
try {
UndoAllCommits(done);
} catch (std::exception& exc) {
std::terminate();
}
} else {
KJ_ASSERT(done == sizeof...(Args));
if (obj) {
try {
if (!obj->Commit()) {
try {
UndoAllCommits(done);
} catch (std::exception& exc) {
std::terminate();
}
return false;
} else {
return true;
}
} catch (std::exception& exc) {
UndoAllCommits(done);
throw;
}
}
}
return !fail;
}
void Rollback() {
KJ_REQUIRE(!rolled_back_);
rolled_back_ = true;
if (finalized_) {
UndoCommit();
}
finalized_ = true;
}
void UndoCommit() {
KJ_REQUIRE(finalized_);
size_t done = sizeof...(Args);
UndoAllCommits(done);
if (obj) {
obj->UndoCommit();
}
}
~DataEditor() {
if (!finalized_ && autocommit_) Commit();
}
DataEditor(Data<U, Args::template parent_t...>* obj, bool autocommit,
Args... args)
: Args(std::move(args))..., obj(obj), autocommit_(autocommit) {}
friend Data<U, Args::template parent_t...>;
protected:
Data<U, Args::template parent_t...>* obj;
bool autocommit_;
bool finalized_ = false;
bool rolled_back_ = false;
};
} // namespace detail
template <typename U, template <typename T> class... Args>
class Data : public Args<Data<U, Args...>>... {
public:
// No move constructor. Use unique pointers.
Data(Data&&) = delete;
template <typename... T>
class BuilderClass {
public:
BuilderClass(T... args) : args(std::move(args)...) {}
BuilderClass&& SetParent(U* parent_) {
parent = parent_;
return std::move(*this);
}
BuilderClass&& SetDir(kj::Maybe<kj::Own<const kj::Directory>> dir_) {
dir = std::move(dir_);
return std::move(*this);
}
BuilderClass&& SetField(const char* name_) {
field_name = name_;
return std::move(*this);
}
template <size_t N>
auto& Get() {
return std::get<N>(args);
}
std::tuple<T...> args;
U* parent = nullptr;
kj::Maybe<kj::Own<const kj::Directory>> dir = nullptr;
const char* field_name = nullptr;
};
// Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79501
template <typename... T>
static BuilderClass<T...> Builder(T... t) {
return BuilderClass<T...>(std::move(t)...);
}
Data(util::JsonConstructorTag, kj::Maybe<kj::Own<const kj::Directory>> dir,
const char* field_name, U* parent, const json& js)
: Args<Data<U, Args...>>(util::JsonConstructorTag(),
util::SubDir(dir, field_name),
Args<Data<U, Args...>>::json_name_, this,
js.at(Args<Data<U, Args...>>::json_name_))...,
dir_(util::SubDir(dir, field_name)),
parent_(parent) {}
template <typename... T>
Data(kj::Maybe<kj::Own<const kj::Directory>> dir, const char* field_name,
U* parent, BuilderClass<T...> builder)
: Data(std::move(builder.SetDir(std::move(dir))
.SetField(field_name)
.SetParent(parent))) {}
template <typename... T, std::size_t... Is>
Data(std::index_sequence<Is...>, BuilderClass<T...> builder)
: Args<Data<U, Args...>>(util::SubDir(builder.dir, builder.field_name),
Args<Data<U, Args...>>::json_name_, this,
std::move(builder.template Get<Is>()))...,
dir_(util::SubDir(builder.dir, builder.field_name)),
parent_(builder.parent) {
Commit();
}
template <typename... T>
explicit Data(BuilderClass<T...> builder)
: Data(std::index_sequence_for<T...>{}, std::move(builder)) {}
json Serialize() const {
json j;
((void)(Args<Data<U, Args...>>::value_type_::SkipSerialize ||
(j[std::string(Args<Data<U, Args...>>::json_name_)] =
this->Args<Data<U, Args...>>::Serialize(),
true)),
...);
return j;
}
void SetDir(kj::Maybe<kj::Own<const kj::Directory>>&& dir,
const char* field_name) {
KJ_IF_MAYBE(d, dir_) {
KJ_FAIL_ASSERT("SetDir should only be called when dir is null");
}
dir_ = util::SubDir(dir, field_name);
Commit();
}
#define DECLARE_OPERATOR(op) \
bool operator op(const Data& other) const { \
return std::tuple<decltype(Args<Data<U, Args...>>::Get())&...>( \
Args<Data<U, Args...>>::Get()...) op \
std::tuple<decltype(Args<Data<U, Args...>>::Get())&...>( \
other.Args<Data<U, Args...>>::Get()...); \
}
DECLARE_OPERATOR(==);
DECLARE_OPERATOR(<);
DECLARE_OPERATOR(>);
DECLARE_OPERATOR(<=);
DECLARE_OPERATOR(>=);
DECLARE_OPERATOR(!=);
// Returns true if successful.
using callback_t = std::function<bool()>;
// Should never fail, as it would leave everything in an inconsistent state.
using revert_callback_t = std::function<void()>;
void OnChange(callback_t action, revert_callback_t revert = []() {}) {
on_commit.push_back(action);
on_undo_commit.push_back(revert);
}
friend detail::DataEditor<U, typename Args<Data<U, Args...>>::Editor_...>;
template <template <typename> class T>
typename T<Data<U, Args...>>::value_type_& Get() {
return this->T<Data<U, Args...>>::Raw();
}
template <template <typename> class T>
const typename T<Data<U, Args...>>::value_type_& Get() const {
return this->T<Data<U, Args...>>::Raw();
}
U* Parent() { return parent_; }
const U* Parent() const { return parent_; }
using ParentType = U;
const constexpr static bool kIsAlsoValue = true;
const constexpr static bool kIsSubObject = true;
const constexpr static bool SkipSerialize = false;
using Editor = detail::DataEditor<U, typename Args<Data>::Editor_...>;
auto Edit(bool autocommit = false) {
return detail::ValueEditor<U, Data>(this, autocommit,
this->Args<Data>::Edit()...);
}
const kj::Maybe<kj::Own<const kj::Directory>>& Directory() const {
return dir_;
}
template <typename GetObject, typename Fun>
static void Visit(std::vector<std::string>& path, const GetObject& get_object,
const Fun& reg) {
reg(path, get_object);
(VisitSingle<Args<Data>>(path, get_object, reg), ...);
}
private:
template <typename A, typename GetObject, typename Fun>
static void VisitSingle(std::vector<std::string>& path,
const GetObject& get_object, const Fun& reg) {
path.push_back(A::json_name_);
KJ_DEFER(path.pop_back());
A::value_type_::Visit(path,
[get_object](const std::vector<std::string>& path) ->
typename A::value_type_* {
auto* obj = get_object(path);
if (!obj) return nullptr;
return obj->A::Ptr();
},
reg);
}
bool Commit() {
if (!util::propagate_callback_safe(on_commit, on_undo_commit)) return false;
KJ_IF_MAYBE(d, dir_) {
auto replacer = (*d)->replaceFile(
kj::Path("data.json"), kj::WriteMode::CREATE | kj::WriteMode::MODIFY);
replacer->get().writeAll(std::string(Serialize().dump()).c_str());
replacer->commit();
}
return true;
}
void UndoCommit() noexcept {
for (const auto& f : on_undo_commit) f();
KJ_IF_MAYBE(d, dir_) {
auto replacer = (*d)->replaceFile(
kj::Path("data.json"), kj::WriteMode::CREATE | kj::WriteMode::MODIFY);
replacer->get().writeAll(std::string(Serialize().dump()).c_str());
replacer->commit();
}
}
kj::Maybe<kj::Own<const kj::Directory>> dir_;
std::vector<callback_t> on_commit;
std::vector<revert_callback_t> on_undo_commit;
U* parent_;
friend U;
};
template <template <typename T> class... Args>
using MainData = Value<void, Data<void, Args...>>;
} // namespace db
| 35.732143 | 80 | 0.492397 | [
"vector"
] |
da23897a397a5ddfd40e10269e6a3321d5f1fe09 | 4,815 | cpp | C++ | src/builtin/btrc/builtin/material/glass.cpp | AirGuanZ/Btrc | 8865eb1506f96fb0230fb394b9fadb1e38f2b9d8 | [
"MIT"
] | 17 | 2022-02-03T09:35:14.000Z | 2022-03-28T04:27:05.000Z | src/builtin/btrc/builtin/material/glass.cpp | AirGuanZ/Btrc | 8865eb1506f96fb0230fb394b9fadb1e38f2b9d8 | [
"MIT"
] | 1 | 2022-02-09T15:11:55.000Z | 2022-02-09T15:11:55.000Z | src/builtin/btrc/builtin/material/glass.cpp | AirGuanZ/Btrc | 8865eb1506f96fb0230fb394b9fadb1e38f2b9d8 | [
"MIT"
] | null | null | null | #include <btrc/builtin/material/glass.h>
#include <btrc/builtin/material/utils/fresnel.h>
#include <btrc/builtin/material/utils/shader_closure.h>
#include <btrc/builtin/material/utils/shader_frame.h>
BTRC_BUILTIN_BEGIN
namespace
{
boolean refr(ref<CVec3f> nwo, ref<CVec3f> nor, f32 eta, ref<CVec3f> output)
{
boolean result;
f32 cos_theta_i = cstd::abs(nwo.z);
f32 sin_theta_i_2 = (cstd::max)(f32(0), 1.0f - cos_theta_i * cos_theta_i);
f32 sin_theta_t_2 = eta * eta * sin_theta_i_2;
$if(sin_theta_t_2 >= 1)
{
result = false;
}
$else
{
f32 cosThetaT = cstd::sqrt(1.0f - sin_theta_t_2);
output = normalize((eta * cos_theta_i - cosThetaT) * nor - eta * nwo);
result = true;
};
return result;
}
} // namespace anonymous
CUJ_CLASS_BEGIN(GlassShaderImpl)
CUJ_MEMBER_VARIABLE(ShaderFrame, raw_frame)
CUJ_MEMBER_VARIABLE(CSpectrum, color)
CUJ_MEMBER_VARIABLE(f32, ior)
Shader::SampleResult sample(
ref<CVec3f> wo, ref<CVec3f> sam, TransportMode mode) const
{
return Shader::discard_pdf_rev(sample_bidir(wo, sam, mode));
}
Shader::SampleBidirResult sample_bidir(
ref<CVec3f> wo, ref<CVec3f> sam, TransportMode mode) const
{
Shader::SampleBidirResult result;
$scope
{
var frame = raw_frame.flip_for_black_fringes(wo);
var nwo = normalize(frame.shading.global_to_local(wo));
var fr = dielectric_fresnel(ior, 1, nwo.z);
$if(sam.x < fr)
{
var lwi = CVec3f(-nwo.x, -nwo.y, nwo.z);
var wi = frame.shading.local_to_global(lwi);
$if(raw_frame.is_black_fringes(wi))
{
result.clear();
$exit_scope;
};
var bsdf = color * fr / cstd::abs(lwi.z);
var norm = frame.correct_shading_energy(wi);
result.dir = wi;
result.bsdf = bsdf * norm;
result.pdf = fr;
result.pdf_rev = fr;
result.is_delta = true;
$exit_scope;
};
var nor = CVec3f(0, 0, cstd::select(nwo.z > 0, f32(1), f32(-1)));
var eta = cstd::select(nwo.z > 0, 1.0f / ior, f32(ior));
CVec3f nwi;
$if(!refr(nwo, nor, eta, nwi))
{
result.clear();
$exit_scope;
};
var wi = frame.shading.local_to_global(nwi);
$if(raw_frame.is_black_fringes(wi))
{
result.clear();
$exit_scope;
};
var corr = mode == TransportMode::Radiance ? eta * eta : f32(1);
var f = corr * color * (1.0f - fr) / cstd::abs(nwi.z);
var pdf = 1.0f - fr;
var norm = frame.correct_shading_energy(wi);
result.bsdf = f * norm;
result.dir = wi;
result.pdf = pdf;
result.pdf = 1.0f - dielectric_fresnel(ior, 1, nwi.z);
result.is_delta = true;
};
return result;
}
CSpectrum eval(ref<CVec3f> wi, ref<CVec3f> wo, TransportMode mode) const
{
return CSpectrum::zero();
}
f32 pdf(ref<CVec3f> wi, ref<CVec3f> wo, TransportMode mode) const
{
return 0;
}
CSpectrum albedo() const
{
return color;
}
CVec3f normal() const
{
return raw_frame.shading.z;
}
CUJ_CLASS_END
void Glass::set_color(RC<Texture2D> color)
{
color_ = std::move(color);
}
void Glass::set_ior(RC<Texture2D> ior)
{
ior_ = std::move(ior);
}
void Glass::set_normal(RC<NormalMap> normal)
{
normal_ = std::move(normal);
}
RC<Shader> Glass::create_shader(CompileContext &cc, const SurfacePoint &inct) const
{
GlassShaderImpl impl;
impl.raw_frame.geometry = inct.frame;
impl.raw_frame.shading = inct.frame.rotate_to_new_z(inct.interp_z);
impl.raw_frame.shading = normal_->adjust_frame(cc, inct, impl.raw_frame.shading);
impl.color = color_->sample_spectrum(cc, inct);
impl.ior = ior_->sample_float(cc, inct);
return newRC<ShaderClosure<GlassShaderImpl>>(as_shared(), impl);
}
RC<Material> GlassCreator::create(RC<const factory::Node> node, factory::Context &context)
{
auto color = context.create<Texture2D>(node->child_node("color"));
auto ior = context.create<Texture2D>(node->child_node("ior"));
auto normal = newRC<NormalMap>();
normal->load(node, context);
auto glass = newRC<Glass>();
glass->set_color(std::move(color));
glass->set_ior(std::move(ior));
glass->set_normal(std::move(normal));
return glass;
}
BTRC_BUILTIN_END
| 29.722222 | 90 | 0.569678 | [
"geometry"
] |
da258149a54c6bfab8b6a27b49f40dad65ed0ccd | 13,624 | cpp | C++ | Core/src/Algorithms/cgls.cpp | vais-ral/CCPi-Reconstruction | 6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd | [
"Apache-2.0"
] | 1 | 2018-11-09T11:58:32.000Z | 2018-11-09T11:58:32.000Z | Core/src/Algorithms/cgls.cpp | vais-ral/CCPi-Reconstruction | 6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd | [
"Apache-2.0"
] | 8 | 2018-05-22T12:58:27.000Z | 2020-10-15T14:54:04.000Z | Core/src/Algorithms/cgls.cpp | vais-ral/CCPi-Reconstruction | 6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd | [
"Apache-2.0"
] | 1 | 2019-01-11T12:04:53.000Z | 2019-01-11T12:04:53.000Z |
#include <iostream>
#include "base_types.hpp"
#include "instruments.hpp"
#include "algorithms.hpp"
#include "timer.hpp"
#include "ui_calls.hpp"
#include "blas.hpp"
#include "cgls.hpp"
#include "regularize.hpp"
#ifndef USE_TIMER
# define USE_TIMER false
#endif // USE_TIMER
void CCPi::reconstruction_alg::convergence_data(real_1d &data) const
{
}
void CCPi::cgls_base::convergence_data(real_1d &data) const
{
for (int i = 0; i < iterations; i++)
data[i] = norm_r[i];
}
bool CCPi::cgls_base::reconstruct(instrument *device, voxel_data &voxels,
const real origin[3],
const real voxel_size[3])
{
const voxel_data::size_type *sz = voxels.shape();
//sl_int n_vox = sl_int(sz[0]) * sl_int(sz[1]) * sl_int(sz[2]);
//voxel_type *const x = voxels.data();
pixel_data &b = device->get_pixel_data();
int n_angles = device->get_num_angles();
int n_h = device->get_num_h_pixels();
int n_v = device->get_num_v_pixels();
sl_int nx = sl_int(sz[0]);
sl_int ny = sl_int(sz[1]);
sl_int nz = sl_int(sz[2]);
// Prepare for CG iteration.
voxel_data d(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
initialise_progress(2 * iterations + 1, "CGLS iterating...");
device->backward_project(d, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
voxel_1d normr2(size_of_voxel_norm(nz));
normalise_voxels(d, nx, ny, nz, normr2);
update_progress(1);
// Iterate.
timer iter_time(USE_TIMER);
for (int iter = 0; iter < iterations; iter++) {
//add_output("iter ");
//add_output(j + 1);
//send_output();
iter_time.reset();
// Update x and r vectors.
{
pixel_data Ad(boost::extents[n_angles][n_h][n_v]);
device->forward_project(Ad, d, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
pixel_update(Ad, b, n_angles, n_v, n_h, d, voxels, nx, ny, nz, normr2);
}
update_progress(2 * iter + 2);
{
voxel_data s(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
device->backward_project(b, s, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
// Update d vector.
voxel_update(s, d, nx, ny, nz, normr2);
}
update_progress(2 * iter + 3);
iter_time.accumulate();
add_output("|R| = ");
add_output(std::sqrt(normr2[0]));
set_norm(std::sqrt(normr2[0]), iter);
iter_time.output(", iteration ");
}
//delete [] d;
return true;
}
int CCPi::cgls_3d::size_of_voxel_norm(const int nz) const
{
return 1;
}
int CCPi::cgls_2d::size_of_voxel_norm(const int nz) const
{
return nz;
}
void CCPi::cgls_3d::normalise_voxels(voxel_data &v, const sl_int nx,
const sl_int ny, const sl_int nz,
voxel_1d &norm) const
{
norm[0] = norm_voxels(v, nx, ny, nz);
}
void CCPi::cgls_2d::normalise_voxels(voxel_data &v, const sl_int nx,
const sl_int ny, const sl_int nz,
voxel_1d &norm) const
{
norm_voxels(v, nx, ny, nz, norm);
}
void CCPi::cgls_3d::pixel_update(const pixel_data &Ad, pixel_data &b,
const sl_int n_angles, const sl_int n_v,
const sl_int n_h, const voxel_data &d,
voxel_data &voxels, const sl_int nx,
const sl_int ny, const sl_int nz,
const voxel_1d &norm) const
{
pixel_type alpha = norm_pixels(Ad, n_angles, n_v, n_h);
alpha = norm[0] / alpha;
sum_axpy(alpha, d, voxels, nx, ny, nz);
sum_axpy(-alpha, Ad, b, n_angles, n_h, n_v);
}
void CCPi::cgls_2d::pixel_update(const pixel_data &Ad, pixel_data &b,
const sl_int n_angles, const sl_int n_v,
const sl_int n_h, const voxel_data &d,
voxel_data &voxels, const sl_int nx,
const sl_int ny, const sl_int nz,
const voxel_1d &norm) const
{
pixel_1d alpha_v(n_v);
norm_pixels(Ad, n_angles, n_v, n_h, alpha_v);
pixel_1d alpha(nz);
int count = 0;
for (int i = 0; i < nz; i++) {
int step = pixels_per_voxel;
if (count + step > n_v)
step = n_v - count;
alpha[i] = 0.0;
for (int j = 0; j < step; j++)
alpha[i] += alpha_v[count + j];
count += step;
alpha[i] = norm[i] / alpha[i];
}
sum_axpy(alpha, d, voxels, nx, ny, nz);
sub_axpy(alpha, Ad, b, n_angles, n_v, n_h, pixels_per_voxel);
}
void CCPi::cgls_3d::voxel_update(const voxel_data &s, voxel_data &d,
const sl_int nx, const sl_int ny,
const sl_int nz, voxel_1d &norm) const
{
real normr2_new = norm_voxels(s, nx, ny, nz);
real beta = normr2_new / norm[0];
norm[0] = normr2_new;
scal_xby(s, beta, d, nx, ny, nz);
}
void CCPi::cgls_2d::voxel_update(const voxel_data &s, voxel_data &d,
const sl_int nx, const sl_int ny,
const sl_int nz, voxel_1d &norm) const
{
voxel_1d normr2_new(nz);
norm_voxels(s, nx, ny, nz, normr2_new);
for (int i = 0; i < nz; i++) {
voxel_type n = normr2_new[i];
normr2_new[i] /= norm[i];
norm[i] = n;
}
scal_xby(s, normr2_new, d, nx, ny, nz);
}
bool CCPi::cgls_3d::supports_blocks() const
{
return false;
}
bool CCPi::cgls_2d::supports_blocks() const
{
return true;
}
bool CCPi::bi_cgls_3d::reconstruct(instrument *device, voxel_data &voxels,
const real origin[3],
const real voxel_size[3])
{
const voxel_data::size_type *sz = voxels.shape();
//pixel_data &b = device->get_pixel_data();
int n_angles = device->get_num_angles();
int n_h = device->get_num_h_pixels();
int n_v = device->get_num_v_pixels();
sl_int nx = sl_int(sz[0]);
sl_int ny = sl_int(sz[1]);
sl_int nz = sl_int(sz[2]);
// Prepare for CG iteration.
voxel_data r0(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
initialise_progress(2 * get_iterations() + 1, "BiCGLS iterating...");
device->backward_project(r0, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
voxel_type gamma0 = 0.0;
gamma0 = norm_voxels(r0, nx, ny, nz);
//voxel_data rt0(boost::extents[sz[0]][sz[1]][sz[2]],
// boost::c_storage_order());
//copy(r0, rt0, nz, ny, nz);
voxel_data p0(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
copy(r0, p0, nz, ny, nz);
//voxel_data pt0(boost::extents[sz[0]][sz[1]][sz[2]],
// boost::c_storage_order());
//copy(r0, pt0, nz, ny, nz);
update_progress(1);
// Issue - I don't see how pt0/rt0/qt can ever differ from p0/r0/q
// Iterate.
timer iter_time(USE_TIMER);
for (int iter = 0; iter < get_iterations(); iter++) {
iter_time.reset();
pixel_data q(boost::extents[n_angles][n_h][n_v]);
//pixel_data qt(boost::extents[n_angles][n_h][n_v]);
//init_data(qt, n_angles, n_h, n_v);
device->forward_project(q, p0, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
//device->forward_project(qt, pt0, origin, voxel_size,
// (int)sz[0], (int)sz[1], (int)sz[2]);
update_progress(2 * iter + 2);
voxel_data vq(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
//voxel_data vqt(boost::extents[sz[0]][sz[1]][sz[2]],
// boost::c_storage_order());
//init_data(vqt, nx, ny, nz);
device->backward_project(q, vq, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
//device->backward_project(qt, vqt, origin, voxel_size,
// (int)sz[0], (int)sz[1], (int)sz[2]);
gamma0 = voxel_update(voxels, p0, r0, vq, nx, ny, nz,
q, n_angles, n_h, n_v, gamma0);
update_progress(2 * iter + 3);
iter_time.accumulate();
iter_time.output("Iteration ");
}
return true;
}
voxel_type CCPi::bi_cgls_3d::voxel_update(voxel_data &v, voxel_data &p0,
voxel_data &r0, const voxel_data &vq,
const sl_int nx, const sl_int ny,
const sl_int nz, const pixel_data &q,
const sl_int n_angles,
const sl_int n_h, const sl_int n_v,
const voxel_type gamma) const
{
real alpha = norm_pixels(q, n_angles, n_v, n_h);
alpha = real(gamma) / alpha;
// x = x + alpha * p0
sum_axpy(alpha, p0, v, nx, ny, nz);
// r0 = r0 - alpha * vq
sum_axpy(- alpha, vq, r0, nx, ny, nz);
real g = norm_voxels(r0, nx, ny, nz);
real beta = g / real(gamma);
scal_xby(p0, beta, r0, nx, ny, nz);
return g;
}
bool CCPi::bi_cgstabls_3d::reconstruct(instrument *device, voxel_data &voxels,
const real origin[3],
const real voxel_size[3])
{
const voxel_data::size_type *sz = voxels.shape();
//pixel_data &b = device->get_pixel_data();
int n_angles = device->get_num_angles();
int n_h = device->get_num_h_pixels();
int n_v = device->get_num_v_pixels();
sl_int nx = sl_int(sz[0]);
sl_int ny = sl_int(sz[1]);
sl_int nz = sl_int(sz[2]);
// Prepare for CG iteration.
voxel_data r0(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
initialise_progress(2 * get_iterations() + 1, "BiCGSTABLS iterating...");
device->backward_project(r0, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
voxel_data r(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
copy(r0, r, nx, ny, nz);
voxel_data p0(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
copy(p0, r0, nx, ny, nz);
voxel_data v0(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
copy(v0, r0, nx, ny, nz);
voxel_type gamma0 = 1.0;
voxel_type alpha = 1.0;
voxel_type omega = 1.0;
update_progress(1);
// Iterate.
timer iter_time(USE_TIMER);
for (int iter = 0; iter < get_iterations(); iter++) {
iter_time.reset();
voxel_type gamma = norm_voxels(r0, r, nx, ny, nz);
voxel_type beta = (gamma * alpha) / (gamma0 * omega);
scal_xby(r, beta, p0, nx, ny, nz);
sum_axpy(- beta * omega, v0, p0, nx, ny, nz);
pixel_data pv(boost::extents[n_angles][n_h][n_v]);
device->forward_project(pv, p0, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
init_data(v0, nx, ny, nz);
device->backward_project(v0, pv, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
alpha = gamma / norm_voxels(r0, v0, nx, ny, nz);
update_progress(2 * iter + 2);
voxel_data s(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
// Todo - combine these
copy(r, s, nx, ny, nz);
sum_axpy(- alpha, v0, s, nx, ny, nz);
init_data(pv, n_angles, n_h, n_v);
device->forward_project(pv, s, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
voxel_data t(boost::extents[sz[0]][sz[1]][sz[2]],
boost::c_storage_order());
device->backward_project(t, pv, origin, voxel_size,
(int)sz[0], (int)sz[1], (int)sz[2]);
omega = norm_voxels(t, s, nx, ny, nz) / norm_voxels(t, nx, ny, nz);
sum_axpy(alpha, p0, voxels, nx, ny, nz);
sum_axpy(omega, s, voxels, nx, ny, nz);
// Todo - combine
copy(s, r, nx, ny, nz);
sum_axpy(- omega, t, r, nx, ny, nz);
gamma0 = gamma;
update_progress(2 * iter + 3);
iter_time.accumulate();
iter_time.output("Iteration ");
}
return true;
}
bool CCPi::cgls_regularize::reconstruct(instrument *device, voxel_data &voxels,
const real origin[3],
const real voxel_size[3])
{
const voxel_data::size_type *sz = voxels.shape();
//sl_int n_vox = sl_int(sz[0]) * sl_int(sz[1]) * sl_int(sz[2]);
//voxel_type *const x = voxels.data();
pixel_data &r_pix = device->get_pixel_data();
int n_angles = device->get_num_angles();
int n_h = device->get_num_h_pixels();
int n_v = device->get_num_v_pixels();
sl_int nx = sl_int(sz[0]);
sl_int ny = sl_int(sz[1]);
sl_int nz = sl_int(sz[2]);
// Prepare for CG iteration.
voxel_data d(boost::extents[nx][ny][nz]);
initialise_progress(2 * get_iterations() + 1, "CGLS iterating...");
device->backward_project(d, origin, voxel_size, nx, ny, nz);
voxel_data r_vox(boost::extents[nx][ny][nz]);
voxel_data Ad_vox(boost::extents[nx][ny][nz]);
voxel_type normr2 = norm_voxels(d, nx, ny, nz);
update_progress(1);
// Iterate.
timer iter_time(USE_TIMER);
for (int iter = 0; iter < get_iterations(); iter++) {
iter_time.reset();
// Update x and r vectors.
{
pixel_data Ad_pix(boost::extents[n_angles][n_h][n_v]);
device->forward_project(Ad_pix, d, origin, voxel_size, nx, ny, nz);
voxel_data L(boost::extents[nx][ny][nz]);
regularize(L, d, nx, ny, nz);
sum_axpy(regularisation_param, L, Ad_vox, nx, ny, nz);
pixel_type alpha = (norm_pixels(Ad_pix, n_angles, n_v, n_h)
+ norm_voxels(Ad_vox, nx, ny, nz));
alpha = normr2 / alpha;
// voxels += alpha * d
sum_axpy(alpha, d, voxels, nx, ny, nz);
// r -= alpha * Ad
sum_axpy(-alpha, Ad_pix, r_pix, n_angles, n_h, n_v);
sum_axpy(-alpha, Ad_vox, r_vox, n_angles, n_h, n_v);
regularize(L, voxels, nx, ny, nz);
sum_axpy(regularisation_param, L, voxels, nx, ny, nz);
}
update_progress(2 * iter + 2);
{
voxel_data s(boost::extents[nx][ny][nz]);
device->backward_project(r_pix, s, origin, voxel_size, nx, ny, nz);
// Update d vector.
real normr2_new = norm_voxels(s, nx, ny, nz);
real beta = normr2_new / normr2;
normr2 = normr2_new;
// d = s + beta * d
scal_xby(s, beta, d, nx, ny, nz);
}
update_progress(2 * iter + 3);
iter_time.accumulate();
add_output("|R| = ");
add_output(std::sqrt(normr2));
set_norm(std::sqrt(normr2), iter);
iter_time.output(", iteration ");
}
//delete [] d;
return true;
}
void CCPi::cgls_tikhonov::regularize(voxel_data &b, const voxel_data &a,
const int nx, const int ny, const int nz)
{
tikhonov_regularize(b, a, nx, ny, nz);
}
void CCPi::cgls_tv_reg::regularize(voxel_data &b, const voxel_data &a,
const int nx, const int ny, const int nz)
{
tv_regularize(b, a, nx, ny, nz);
}
| 32.132075 | 79 | 0.628083 | [
"shape",
"vector"
] |
da2cbf27cf5797329c18595bd212d59d434d6f91 | 1,109 | cpp | C++ | src/Game/Game.cpp | vilfa/gold-rush | a6d936c3a3df841d567a65500aa9bcb4c7407318 | [
"MIT"
] | null | null | null | src/Game/Game.cpp | vilfa/gold-rush | a6d936c3a3df841d567a65500aa9bcb4c7407318 | [
"MIT"
] | null | null | null | src/Game/Game.cpp | vilfa/gold-rush | a6d936c3a3df841d567a65500aa9bcb4c7407318 | [
"MIT"
] | null | null | null | #include "Game.h"
const glm::vec3 Game::_DEFAULT_CAMERA_POSITION_ = glm::vec3(0.0f, 0.0f, 0.0f);
const glm::vec3 Game::_DEFAULT_PLAYER_POSITION_ = glm::vec3(0.0f, 0.0f, 0.0f);
const glm::vec3 Game::_WORLD_CENTER_ = glm::vec3(0.0f, 0.0f, 0.0f);
Game::Game(Window &window)
: renderer_(window), camera_(Camera(_DEFAULT_CAMERA_POSITION_)), game_world_(GameWorld()),
player_(Player(_DEFAULT_PLAYER_POSITION_))
{
glm::vec3 player_start_pos = _DEFAULT_PLAYER_POSITION_;
player_start_pos.y = game_world_.GetGridHeight(player_start_pos);
player_.position_ = player_start_pos;
camera_.SetPlayerPosition(player_start_pos);
camera_.FollowPlayer();
player_.SetTimeLimit(300.0);
player_.SetScore(0);
}
void Game::Start() { renderer_.Render(camera_, player_, game_world_); }
void Game::HandleFramebuffer(GLFWwindow *window, int width, int height)
{
renderer_.ProcessFramebuffer(window, width, height);
}
void Game::HandleMouse(GLFWwindow *window, double x_pos, double y_pos)
{
renderer_.ProcessMouse(camera_, player_, window, x_pos, y_pos);
}
| 35.774194 | 95 | 0.722272 | [
"render"
] |
da2da30dde9c4e14924d769a24e22cf941242029 | 5,342 | cpp | C++ | src/ui/ColumnView.cpp | mmahmoudian/Gittyup | 96702f3b96160fff540886722f7f195163c4e41b | [
"MIT"
] | 127 | 2021-10-29T19:01:32.000Z | 2022-03-31T18:23:56.000Z | src/ui/ColumnView.cpp | mmahmoudian/Gittyup | 96702f3b96160fff540886722f7f195163c4e41b | [
"MIT"
] | 90 | 2021-11-05T13:03:58.000Z | 2022-03-30T16:42:49.000Z | src/ui/ColumnView.cpp | mmahmoudian/Gittyup | 96702f3b96160fff540886722f7f195163c4e41b | [
"MIT"
] | 20 | 2021-10-30T12:25:33.000Z | 2022-02-18T03:08:21.000Z | //
// Copyright (c) 2016, Scientific Toolworks, Inc.
//
// This software is licensed under the MIT License. The LICENSE.md file
// describes the conditions under which this software may be distributed.
//
// Author: Jason Haslam
//
#include "ColumnView.h"
#include "TreeModel.h"
#include "ViewDelegate.h"
#include <QFormLayout>
#include <QItemDelegate>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QVBoxLayout>
#ifdef Q_OS_WIN
#define ICON_SIZE 48
#define SCROLL_BAR_WIDTH 18
#else
#define ICON_SIZE 64
#define SCROLL_BAR_WIDTH 0
#endif
namespace {
const QString kNameFmt = "<p style='font-size: large'>%1</p>";
const QString kLabelFmt = "<p style='color: gray; font-weight: bold'>%1</p>";
/*!
* \brief The PreviewWidget class
* Widget shown in the next column when file selected instead of a folder
*/
class PreviewWidget : public QFrame {
Q_OBJECT
public:
PreviewWidget(ColumnView *parent) : QFrame(parent) {
mIcon = new QLabel(this);
mIcon->setAlignment(Qt::AlignHCenter);
mName = new QLabel(this);
mName->setAlignment(Qt::AlignHCenter);
mName->setContentsMargins(4, 4, 4, 4);
mKind = new QLabel(this);
mKind->setAlignment(Qt::AlignHCenter);
mAdded = new QLabel(this);
mModified = new QLabel(this);
connect(mAdded, &QLabel::linkActivated, parent, &ColumnView::linkActivated);
connect(mModified, &QLabel::linkActivated, parent,
&ColumnView::linkActivated);
QFormLayout *form = new QFormLayout;
form->setLabelAlignment(Qt::AlignRight);
form->setFormAlignment(Qt::AlignHCenter | Qt::AlignTop);
form->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
form->setHorizontalSpacing(4);
form->setVerticalSpacing(2);
form->addRow(kLabelFmt.arg(tr("Added")), mAdded);
form->addRow(kLabelFmt.arg(tr("Modified")), mModified);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(2);
layout->addWidget(mIcon);
layout->addWidget(mName);
layout->addWidget(mKind);
layout->addLayout(form);
}
void setFile(const QModelIndex &index, int width) {
mIndex = index;
if (!index.isValid() || index.model()->rowCount(index) > 0) {
hide();
return;
}
QWindow *win = window()->windowHandle();
QIcon icon = index.data(Qt::DecorationRole).value<QIcon>();
mIcon->setPixmap(icon.pixmap(win, QSize(ICON_SIZE, ICON_SIZE)));
mName->setText(kNameFmt.arg(index.data(Qt::DisplayRole).toString()));
QString kind = index.data(TreeModel::KindRole).toString();
mKind->setVisible(!kind.isEmpty());
mKind->setText(kLabelFmt.arg(kind));
mAdded->setText(index.data(TreeModel::AddedRole).toString());
mModified->setText(index.data(TreeModel::ModifiedRole).toString());
// QColumnView resizes the preview container
// to the *size* of the preview widget.
resize(QSize(width, sizeHint().height()));
show();
}
signals:
void iconDoubleClicked(const QModelIndex &index);
protected:
void mouseDoubleClickEvent(QMouseEvent *event) override {
if (mIcon->geometry().contains(event->pos()))
emit iconDoubleClicked(mIndex);
}
private:
QLabel *mIcon;
QLabel *mName;
QLabel *mKind;
QLabel *mAdded;
QLabel *mModified;
QModelIndex mIndex;
};
} // namespace
ColumnView::ColumnView(QWidget *parent)
: QColumnView(parent), mSharedDelegate(new ViewDelegate(this)) {
PreviewWidget *preview = new PreviewWidget(this);
connect(preview, &PreviewWidget::iconDoubleClicked, this,
&ColumnView::doubleClicked);
setPreviewWidget(preview);
}
void ColumnView::setModel(QAbstractItemModel *model) {
QColumnView::setModel(model);
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this,
&ColumnView::handleSelectionChange);
}
bool ColumnView::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::MouseButtonPress) {
QWidget *columnViewport = static_cast<QWidget *>(obj);
QPoint globalPos = static_cast<QMouseEvent *>(event)->globalPos();
QModelIndex index = indexAt(viewport()->mapFromGlobal(globalPos));
if (!columnViewport->hasFocus() && index.row() < 0) {
columnViewport->setFocus();
selectionModel()->clearSelection();
}
}
return false;
}
QAbstractItemView *ColumnView::createColumn(const QModelIndex &index) {
QAbstractItemView *view = QColumnView::createColumn(index);
view->setItemDelegate(mSharedDelegate);
view->viewport()->installEventFilter(this);
return view;
}
void ColumnView::handleSelectionChange(const QItemSelection &selected,
const QItemSelection &deselected) {
// FIXME: The argument sent by Qt doesn't contain the whole selection.
int width = columnWidths().last() - SCROLL_BAR_WIDTH;
QModelIndexList indexes = selectionModel()->selectedIndexes();
QModelIndex index = (indexes.size() == 1) ? indexes.first() : QModelIndex();
static_cast<PreviewWidget *>(previewWidget())->setFile(index, width);
emit fileSelected(index);
// Handle deselection.
if (indexes.isEmpty() && !deselected.indexes().isEmpty()) {
QModelIndex parent = deselected.indexes().first().parent();
setCurrentIndex(parent);
if (!parent.isValid())
setRootIndex(QModelIndex());
}
}
#include "ColumnView.moc"
| 29.843575 | 80 | 0.698802 | [
"geometry",
"model"
] |
da316655f5c62fc1b1d45d55da3556100cc36cbc | 4,889 | cpp | C++ | Scripts/AudioPlayer.cpp | RaskiTech/AI-Composer | c6afdf89cef039a3fa303b395a5e8470286e68f3 | [
"Apache-2.0"
] | null | null | null | Scripts/AudioPlayer.cpp | RaskiTech/AI-Composer | c6afdf89cef039a3fa303b395a5e8470286e68f3 | [
"Apache-2.0"
] | null | null | null | Scripts/AudioPlayer.cpp | RaskiTech/AI-Composer | c6afdf89cef039a3fa303b395a5e8470286e68f3 | [
"Apache-2.0"
] | null | null | null | #include <Eagle.h>
#include <glm/gtx/common.hpp>
#include "AudioPlayer.h"
constexpr double tau = 2.0 * glm::pi<double>();
constexpr double twoOverPI = 2.0 / glm::pi<double>();
constexpr double halfPI = glm::pi<double>() / 2;
NoiseMaker<short>* NotePlayer::emitter;
uint8_t NotePlayer::soundTypeIndex;
struct Note {
Note(double pitch, double activateTime, uint8_t instrumentIndex) : pitch(pitch), activateTime(activateTime), instrumentIndex(instrumentIndex) {}
bool pressedDown = true;
bool finishedPlaying = false;
double activateTime;
double deactivateTime;
float pitch = 0;
uint8_t instrumentIndex = 0;
};
struct SimpleInstrument {
SimpleInstrument(double attackTime, double decayTime, double(*MakeSoundWave)(double, double))
: attackTime(attackTime), decayTime(decayTime), MakeSoundWave(MakeSoundWave) {}
double attackTime;
double decayTime;
double(*MakeSoundWave)(double, double);
};
double MakeSineWave(double hz, double deltaTime) { return glm::sin(hz * tau * deltaTime); }
double MakeSquareWave(double hz, double deltaTime) { return glm::sin(hz * tau * deltaTime) > 0.0 ? 0.7 : -0.7;; }
double MakeTriangleWave(double hz, double deltaTime) { return glm::asin(glm::sin(hz * tau * deltaTime)) * twoOverPI; }
double MakeSawWave(double hz, double deltaTime)
{ return twoOverPI * (hz * glm::pi<double>() * glm::fmod(deltaTime, 1.0 / hz) - halfPI);}
double MakeCustomWave(double hz, double deltaTime) {
return 0.5 * MakeSquareWave(hz, deltaTime) + 0.5 * MakeSquareWave(hz * 2, deltaTime);
}
SimpleInstrument SineInstrument (0.05f, 0.05f, MakeSineWave);
SimpleInstrument SquareInstrument (0.05f, 0.05f, MakeSquareWave);
SimpleInstrument triangleInstrument(0.05f, 0.05f, MakeTriangleWave);
SimpleInstrument sawInstrument (0.05f, 0.05f, MakeSawWave);
SimpleInstrument customInstrument (0.1f, 0.5f, MakeCustomWave);
std::vector<Note> playingNotes;
mutex mutexNotes;
atomic<double> masterVolume = 1.0;
typedef bool(*lambda)(Note const& item);
template<class T>
void safe_remove(T& v, lambda f)
{
auto n = v.begin();
while (n != v.end())
if (!f(*n))
n = v.erase(n);
else
++n;
}
SimpleInstrument& GetInstrument(uint8_t index) {
switch (index) {
case 0:
return SineInstrument;
case 1:
return SquareInstrument;
case 2:
return triangleInstrument;
case 3:
return sawInstrument;
case 4:
return customInstrument;
}
}
double CalculateNoiseSample(double deltaTime) {
unique_lock<mutex> lm(mutexNotes);
double output = 0.0;
for (auto& note : playingNotes)
{
double sound = 0;
SimpleInstrument& instrument = GetInstrument(note.instrumentIndex);
sound = instrument.MakeSoundWave(note.pitch, deltaTime);
double loudnessFactor;
if (note.pressedDown) {
double attackedTime = deltaTime - note.activateTime;
if (attackedTime < instrument.attackTime)
loudnessFactor = attackedTime / instrument.attackTime;
else
loudnessFactor = 1;
}
else {
double decayedTime = deltaTime - note.deactivateTime;
loudnessFactor = 1 - decayedTime / instrument.decayTime;
if (loudnessFactor < .001) {
note.finishedPlaying = true;
loudnessFactor = 0;
}
}
output += sound * loudnessFactor;
//LOG("It's {0}", output);
}
safe_remove<std::vector<Note>>(playingNotes, [](Note const& item) { return !item.finishedPlaying; });
double returnVal = output * masterVolume * 0.2;
//LOG("{0} {1}", returnVal, masterVolume);
//if (returnVal > 1)
// LOG("Y. Keys: {0}", playingNotes.size());
//else
// LOG("N");
return returnVal; // Constant so the output isn't over 1 when pressing multiple keys
}
void NotePlayer::Init() {
playingNotes = std::vector<Note>();
std::vector<std::wstring> devices = NoiseMaker<short>::Enumerate();
for (auto d : devices) std::wcout << "Found an input device: " << d << std::endl;
emitter = new NoiseMaker<short>(devices[0], 44100, 1, 8, 512);
emitter->SetUserFunction(CalculateNoiseSample);
}
void NotePlayer::SetVolume(float val) {
masterVolume = val;
}
void NotePlayer::KeyDown(double pitch) {
mutexNotes.lock();
playingNotes.emplace_back(pitch, emitter->GetTime(), soundTypeIndex);
mutexNotes.unlock();
}
void NotePlayer::KeyUp(double remove) {
mutexNotes.lock();
for (Note& note : playingNotes) {
if (note.pitch == (float)remove) {
note.pressedDown = false;
note.deactivateTime = emitter->GetTime();
}
}
mutexNotes.unlock();
}
void NotePlayer::ClearKeys() {
mutexNotes.lock();
playingNotes.clear();
mutexNotes.unlock();
}
void NotePlayer::SetWaveType(SoundWaveType type) {
soundTypeIndex = (uint8_t)type;
}
double NotePlayer::IndexToPitch(int keycode) {
constexpr double lowestNote = 41.20; // E1
constexpr double twoToPowerOneTwelwth = 1.05946398436;
return lowestNote * glm::pow(twoToPowerOneTwelwth, keycode);
}
double NotePlayer::GetSoundWaveAt(double deltaTime) {
//LOG_WARN("New:");
return CalculateNoiseSample(deltaTime);
}
| 28.928994 | 145 | 0.718347 | [
"vector"
] |
da319f0ad04c8507997a8662641ab87cbbc2c795 | 5,208 | cpp | C++ | Source/model/session/session.cpp | TheEvilRoot/2CourseWork | 6fee1a5955b55f09f512d9988efdf5ae16917e3e | [
"MIT"
] | null | null | null | Source/model/session/session.cpp | TheEvilRoot/2CourseWork | 6fee1a5955b55f09f512d9988efdf5ae16917e3e | [
"MIT"
] | 1 | 2019-12-07T23:36:32.000Z | 2019-12-07T23:36:32.000Z | Source/model/session/session.cpp | TheEvilRoot/2CourseWork | 6fee1a5955b55f09f512d9988efdf5ae16917e3e | [
"MIT"
] | null | null | null | #include "session.hpp"
#include "model/data/choicetest.hpp"
#include <cmath>
#include <QDateTime>
#include <QDebug>
Session::Session(TestList tests, int maxAttempts):
mTests(tests),
mPosition(0),
mMaxAttempts(maxAttempts),
mMagicConstant(1377),
mState(new SessionState) {
applyResult();
}
Session::~Session() {
qDebug() << "Session descruction initiated!!!!!!\n";
for (auto& test : mTests) {
delete test;
}
}
int Session::getCorrectAnswersCount() const {
return mState->mCorrect;
}
int Session::getMaxAttempts() const {
return mMaxAttempts;
}
int Session::getMagic() const {
return mMagicConstant;
}
int Session::getWrongAnswersCount() const {
return mState->mWrong;
}
int Session::getPoints() const{
return mState->getPoints();
}
size_t Session::getTestsCount() const {
return mTests.size();
}
size_t Session::getTestPosition() const {
return mPosition;
}
void Session::applyResult() {
if (!mState->mTestResults.empty()) {
auto mSecs = abs(QDateTime::currentDateTime().msecsTo(mState->mTestResults.back()->mSolveTime));
mState->mTestResults.back()->mSolveTime = QDateTime::fromMSecsSinceEpoch(mSecs);
}
if (!currentTest()) return;
auto test = currentTest();
mState->mTestResults.push_back(new Result(test->getQuestion(), test->getAnswer(), mPosition, QDateTime::currentDateTime()));
}
void Session::nextTest() {
mPosition++;
}
/**
* @brief Session::submitTest
* @param result - r
* @param answer
*/
int Session::submitTest(size_t index, QString answer) {
auto test = currentTest();
if (test == nullptr) return false;
auto isCorrect = false;
if (test->getType() == ViewType::CHOICE || test->getType() == ViewType::CHECK) {
auto choiceTest = dynamic_cast<ChoiceTest *>(test);
isCorrect = choiceTest->checkAnswerByIndex(index);
answer = choiceTest->getAnswers()[index];
} else {
isCorrect = test->checkResult(answer);
}
auto result = mState->mTestResults.back();
result->mUserAnswers.push_back(answer);
result->mAttempts++;
result->mPointsForTest = isCorrect ? calculatePoints(result, test) : 0;
if (isCorrect) {
mState->mCorrect++;
} else {
mState->mWrong++;
}
if (isCorrect || result->mAttempts >= mMaxAttempts) {
nextTest();
applyResult();
return isCorrect;
}
// Ghosts:
// is not correct
// maxAttempts > 0
// mAttemps <= maxAttempts
return mMagicConstant + result->mAttempts;
}
BaseTest* Session::currentTest() const {
if (mPosition < mTests.size()){
return mTests[mPosition];
}
return nullptr;
}
bool Session::isFinished() {
return mPosition >= mTests.size();
}
int Session::calculatePoints(Result *result, BaseTest *test) {
int modifyer = std::min(result->mAttempts, 3);
if (test->getType() == ViewType::CHOICE) {
return 30 / modifyer;
} else if (test->getType() == ViewType::INPUT) {
return 60 / modifyer;
} else if (test->getType() == ViewType::CHECK) {
return 33 / modifyer;
} else {
return 27 / modifyer;
}
}
SessionState * Session::getState() {
return mState;
}
void Session::generateConclusion() {
int countOfWordBasedTests = 0;
int correctWordBased = 0;
int countOfSentenceBasedTests = 0;
int correctSentenceBased = 0;
for (auto result : mState->getTestResults()) {
bool isSentenceBased = mTests[result->mIndex]->isSentenceBased();
countOfWordBasedTests += !isSentenceBased;
countOfSentenceBasedTests += isSentenceBased;
correctSentenceBased += isSentenceBased && result->mPointsForTest != 0;
correctWordBased += !isSentenceBased && result->mPointsForTest != 0;
}
double percentCorrectOfWordBased = (correctWordBased * 1.0) / countOfWordBasedTests;
double percentCorrectOfSentenceBased = (correctSentenceBased * 1.0) / countOfSentenceBasedTests;
// A1: WB > 0.05
// A2: WB > 0.2 & SB > 0.05
// B1: WB > 0.5 & SB > 0.2
// B2 WB > 0.8 & SB > 0.5
// C1: WB > 0.9 & SB > 0.8
// C2: WB == 1 && SB > 0.9
if (percentCorrectOfWordBased >= 0.999 && percentCorrectOfSentenceBased > 0.9) {
// C2
mState->mCefrResult = CEFR::C2;
} else if (percentCorrectOfWordBased >= 0.9 && percentCorrectOfSentenceBased > 0.8) {
// C1
mState->mCefrResult = CEFR::C1;
} else if (percentCorrectOfWordBased > 0.8 && percentCorrectOfSentenceBased > 0.5) {
// B2
mState->mCefrResult = CEFR::B2;
} else if (percentCorrectOfWordBased > 0.5 && percentCorrectOfSentenceBased > 0.2) {
// B1
mState->mCefrResult = CEFR::B1;
} else if (percentCorrectOfWordBased > 0.2 && percentCorrectOfSentenceBased > 0.05) {
// A2
mState->mCefrResult = CEFR::A2;
} else if (percentCorrectOfWordBased > 0.05) {
// A1
mState->mCefrResult = CEFR::A1;
} else {
// Need more practice
mState->mCefrResult = CEFR::NOTHING;
}
mState->mWordBasedCorrect = percentCorrectOfWordBased;
mState->mSentenceBasedCorrect = percentCorrectOfSentenceBased;
}
| 28.151351 | 128 | 0.640361 | [
"model"
] |
da327a7e7132d0a1d0ed424f36e4f32df9fa4ed2 | 2,926 | cpp | C++ | OpenGL/Engine/Source/Private/Core/Mesh.cpp | Milswanca/OpenGL_FINAL | a16e0f6ce62e34b4b27866afba63463c6fce5ed0 | [
"MIT"
] | null | null | null | OpenGL/Engine/Source/Private/Core/Mesh.cpp | Milswanca/OpenGL_FINAL | a16e0f6ce62e34b4b27866afba63463c6fce5ed0 | [
"MIT"
] | null | null | null | OpenGL/Engine/Source/Private/Core/Mesh.cpp | Milswanca/OpenGL_FINAL | a16e0f6ce62e34b4b27866afba63463c6fce5ed0 | [
"MIT"
] | null | null | null | #include "PCH.h"
#include "Mesh.h"
#include "Engine.h"
Mesh::Mesh(const ObjectInitData& _data) : Object(_data)
{
verts = nullptr;
p = nullptr;
n = nullptr;
c = nullptr;
numVerts = 0;
shapes = std::vector<MeshShape>();
}
Mesh* Mesh::Create(Object* _outer, Vector3* _verts, Vector3* _normals, Vector4* _colours, int _numVerts, int _numNormals, int _numColours)
{
Mesh* mesh = _outer->GetEngine()->NewObject<Mesh>(_outer);
mesh->p = new Vector3[_numVerts];
mesh->n = new Vector3[_numNormals];
mesh->c = new Vector4[_numColours];
mesh->numVerts = _numVerts;
mesh->numNormals = _numNormals;
mesh->numColours = _numColours;
std::memcpy(mesh->p, _verts, sizeof(Vector3) * _numVerts);
std::memcpy(mesh->n, _normals, sizeof(Vector3) * _numNormals);
std::memcpy(mesh->c, _colours, sizeof(Vector4) * _numColours);
mesh->RebuildVertices();
return mesh;
}
void Mesh::RebuildVertices()
{
if (verts != nullptr)
{
delete[] verts;
verts = nullptr;
}
verts = new Vertex[numVerts];
for (int i = 0; i < numVerts; ++i)
{
verts[i].position = p[i];
if (numColours > i)
{
verts[i].colour = c[i];
}
if (numNormals > i)
{
verts[i].normal = n[i];
}
}
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, numVerts * sizeof(Vertex), &verts[0], GL_STATIC_DRAW);
// vertex positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal));
// vertex colours
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, colour));
glBindVertexArray(0);
}
void Mesh::SetIndices(int _meshIndex, int* _indices, int _numIndices)
{
while (_meshIndex >= shapes.size())
{
MeshShape shape = MeshShape();
shape.indices = nullptr;
shape.numIndices = 0;
shapes.push_back(shape);
}
if (shapes[_meshIndex].indices != nullptr)
{
delete[] shapes[_meshIndex].indices;
shapes[_meshIndex].indices = nullptr;
}
MeshShape shape = shapes[_meshIndex];
shape.indices = new int[_numIndices];
shape.numIndices = _numIndices;
std::memcpy(shape.indices, _indices, _numIndices * sizeof(int));
glBindVertexArray(VAO);
glGenBuffers(1, &shape.EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, shape.EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, _numIndices * sizeof(unsigned int), &shape.indices[0], GL_STATIC_DRAW);
glBindVertexArray(0);
shapes[_meshIndex] = shape;
}
int Mesh::GetNumShapes() const
{
return shapes.size();
}
unsigned int Mesh::GetVAO() const
{
return VAO;
}
unsigned int Mesh::GetEBO(int _shape) const
{
return shapes[_shape].EBO;
}
unsigned int Mesh::GetNumIndices(int _shape) const
{
return shapes[_shape].numIndices;
} | 22.859375 | 138 | 0.709159 | [
"mesh",
"object",
"shape",
"vector"
] |
da5533b9f871d990e593f80e2ceca545a25988bc | 9,075 | hpp | C++ | include/BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData_ObstacleData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData_ObstacleData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData_ObstacleData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData
#include "BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData.hpp"
// Including type: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveDataItem
#include "BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveDataItem.hpp"
// Including type: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleType
#include "BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData_ObstacleType.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData);
DEFINE_IL2CPP_ARG_TYPE(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData*, "BeatmapSaveDataVersion2_6_0AndEarlier", "BeatmapSaveData/ObstacleData");
// Type namespace: BeatmapSaveDataVersion2_6_0AndEarlier
namespace BeatmapSaveDataVersion2_6_0AndEarlier {
// Size: 0x24
#pragma pack(push, 1)
// Autogenerated type: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleData
// [TokenAttribute] Offset: FFFFFFFF
class BeatmapSaveData::ObstacleData : public ::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveDataItem {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.Single _time
// Size: 0x4
// Offset: 0x10
float time;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Int32 _lineIndex
// Size: 0x4
// Offset: 0x14
int lineIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
// private BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleType _type
// Size: 0x4
// Offset: 0x18
::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleType type;
// Field size check
static_assert(sizeof(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleType) == 0x4);
// private System.Single _duration
// Size: 0x4
// Offset: 0x1C
float duration;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Int32 _width
// Size: 0x4
// Offset: 0x20
int width;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Get instance field reference: private System.Single _time
float& dyn__time();
// Get instance field reference: private System.Int32 _lineIndex
int& dyn__lineIndex();
// Get instance field reference: private BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleType _type
::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleType& dyn__type();
// Get instance field reference: private System.Single _duration
float& dyn__duration();
// Get instance field reference: private System.Int32 _width
int& dyn__width();
// public System.Int32 get_lineIndex()
// Offset: 0x2819314
int get_lineIndex();
// public BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleType get_type()
// Offset: 0x281931C
::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleType get_type();
// public System.Single get_duration()
// Offset: 0x2819324
float get_duration();
// public System.Int32 get_width()
// Offset: 0x281932C
int get_width();
// public System.Void .ctor(System.Single time, System.Int32 lineIndex, BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleType type, System.Single duration, System.Int32 width)
// Offset: 0x2819334
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BeatmapSaveData::ObstacleData* New_ctor(float time, int lineIndex, ::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleType type, float duration, int width) {
static auto ___internal__logger = ::Logger::get().WithContext("::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BeatmapSaveData::ObstacleData*, creationType>(time, lineIndex, type, duration, width)));
}
// public override System.Single get_time()
// Offset: 0x281930C
// Implemented from: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveDataItem
// Base method: System.Single BeatmapSaveDataItem::get_time()
float get_time();
}; // BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.ObstacleData
#pragma pack(pop)
static check_size<sizeof(BeatmapSaveData::ObstacleData), 32 + sizeof(int)> __BeatmapSaveDataVersion2_6_0AndEarlier_BeatmapSaveData_ObstacleDataSizeCheck;
static_assert(sizeof(BeatmapSaveData::ObstacleData) == 0x24);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_lineIndex
// Il2CppName: get_lineIndex
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::*)()>(&BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_lineIndex)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData*), "get_lineIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_type
// Il2CppName: get_type
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleType (BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::*)()>(&BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_type)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData*), "get_type", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_duration
// Il2CppName: get_duration
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::*)()>(&BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_duration)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData*), "get_duration", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_width
// Il2CppName: get_width
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::*)()>(&BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_width)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData*), "get_width", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_time
// Il2CppName: get_time
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::*)()>(&BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData::get_time)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::ObstacleData*), "get_time", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 58.928571 | 300 | 0.784904 | [
"vector"
] |
da5bd2c51381326a852a6b2f9ffc2489c84aa1af | 3,454 | cpp | C++ | Week.7/Task.2.LeftRotate.cpp | v1nnyb0y/Coursera.AaDS | 9f536cd231b7676c2a6462c0d88f4be353a5a37f | [
"MIT"
] | null | null | null | Week.7/Task.2.LeftRotate.cpp | v1nnyb0y/Coursera.AaDS | 9f536cd231b7676c2a6462c0d88f4be353a5a37f | [
"MIT"
] | null | null | null | Week.7/Task.2.LeftRotate.cpp | v1nnyb0y/Coursera.AaDS | 9f536cd231b7676c2a6462c0d88f4be353a5a37f | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <stdio.h>
#include <iomanip>
#include <deque>
#include <stack>
#include <cassert>
using namespace std;
vector<vector<long>> vLines;
#define pBinaryTree BinaryTree *
struct BinaryTree
{
long Data;
long High;
long Balance;
pBinaryTree Left;
pBinaryTree Right;
BinaryTree() : Data(), High(), Balance(), Left(), Right() {}
BinaryTree(long _Data, long _High, long _Balance, pBinaryTree _Left, pBinaryTree _Right) {
Data = _Data;
High = _High;
Balance = _Balance;
Left = _Left;
Right = _Right;
}
};
pBinaryTree copy(pBinaryTree root) {
if (root == nullptr) {
return nullptr;
}
pBinaryTree newT = new BinaryTree(root->Data, root->High, root->Balance, root->Left, root->Right);
return newT;
}
pBinaryTree Create(pBinaryTree root, int index) {
root = new BinaryTree(vLines[index][0], 1, 0, nullptr, nullptr);
if (vLines[index][1] == 0 && vLines[index][2] == 0) {
return root;
}
if (vLines[index][1] != 0) {
root->Left = new BinaryTree();
root->Left = Create(root->Left, vLines[index][1] - 1);
root->High = root->Left->High;
}
if (vLines[index][2] != 0) {
root->Right = new BinaryTree;
root->Right = Create(root->Right, vLines[index][2] - 1);
root->High = max(root->High, root->Right->High);
}
root->High++;
if (root->Left == nullptr) {
root->Balance = root->Right->High;
return root;
}
if (root->Right == nullptr) {
root->Balance = 0 - root->Left->High;
return root;
}
root->Balance = root->Right->High - root->Left->High;
return root;
}
pBinaryTree SmallLeft(pBinaryTree root) {
pBinaryTree newT = copy(root);
pBinaryTree X = copy(root->Left);
pBinaryTree Y = copy(root->Right->Left);
pBinaryTree Z = copy(root->Right->Right);
newT->Data = root->Right->Data;
newT->Left = new BinaryTree(root->Data, 0, 0, X, Y);
newT->Right = Z;
return newT;
}
pBinaryTree BigLeft(pBinaryTree root) {
pBinaryTree newT = copy(root);
pBinaryTree W = copy(root->Left);
pBinaryTree X = copy(root->Right->Left->Left);
pBinaryTree Y = copy(root->Right->Left->Right);
pBinaryTree Z = copy(root->Right->Right);
newT->Data = root->Right->Left->Data;
newT->Right = new BinaryTree(root->Right->Data, 0, 0, Y, Z);
newT->Left = new BinaryTree(root->Data, 0, 0, W, X);
return newT;
}
pBinaryTree LeftSwap(pBinaryTree root) {
if (root->Right->Balance == -1) {
return BigLeft(root);
}
return SmallLeft(root);
}
void Output(pBinaryTree root) {
queue<pBinaryTree> q;
int count = 2;
q.push(root);
while (q.size() != 0) {
pBinaryTree t = q.front();
q.pop();
printf("%d ", t->Data);
if (t->Left != nullptr) {
q.push(t->Left);
printf("%d ", count);
count++;
}
else {
printf("%d ", 0);
}
if (t->Right != nullptr) {
q.push(t->Right);
printf("%d\n", count);
count++;
}
else {
printf("%d\n", 0);
}
}
}
int main() {
//ios::sync_with_stdio(false);
//cin.tie(NULL);
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
//ifstream input("input.txt");
int n;
scanf("%d", &n);
vLines.resize(n);
for (int id = 0; id < n; id++) {
vLines[id].resize(3);
scanf("%d %d %d", &vLines[id][0], &vLines[id][1], &vLines[id][2]);
}
pBinaryTree root = nullptr;
root = Create(root, 0);
root = LeftSwap(root);
printf("%d\n", n);
Output(root);
return 0;
}
| 21.453416 | 99 | 0.6326 | [
"vector"
] |
da5cd75b465ae160829c665c3ca0187fcd0056bc | 1,847 | cpp | C++ | External_aob/StringManipulate.cpp | ShaddyAQN/External_aob_scanner_lib | c8a59be86e87668afa96128e9a96d46723fe5c8f | [
"MIT"
] | 3 | 2019-02-24T18:18:05.000Z | 2020-07-30T09:29:17.000Z | External_aob/StringManipulate.cpp | ShaddyDC/External_aob_scanner_lib | c8a59be86e87668afa96128e9a96d46723fe5c8f | [
"MIT"
] | null | null | null | External_aob/StringManipulate.cpp | ShaddyDC/External_aob_scanner_lib | c8a59be86e87668afa96128e9a96d46723fe5c8f | [
"MIT"
] | null | null | null | #include "StringManipulate.hpp"
#include <locale>
#include <codecvt>
bool StringManipulate::EndsWith(std::wstring const &str, std::wstring const &end)
{
auto len = static_cast<signed>(end.length());
auto pos = static_cast<signed>(str.length()) - len;
if(pos < 0)
return false;
auto pos_a = &str[pos];
auto pos_b = &end[0];
while(*pos_a)
if(*pos_a++ != *pos_b++)
return false;
return true;
}
bool StringManipulate::EndsWith(std::string const &str, std::string const &end)
{
auto len = static_cast<signed>(end.length());
auto pos = static_cast<signed>(str.length()) - len;
if(pos < 0)
return false;
auto pos_a = &str[pos];
auto pos_b = &end[0];
while(*pos_a)
if(*pos_a++ != *pos_b++)
return false;
return true;
}
std::vector<std::string> StringManipulate::SplitString(const std::string &str, const std::string &delimiter)
{
std::vector<std::string> Return;
auto start = 0U;
auto end = str.find(delimiter);
while(end != std::string::npos)
{
Return.push_back(str.substr(start, end - start));
start = end + delimiter.length();
end = str.find(delimiter, start);
}
Return.push_back(str.substr(start, end));
return Return;
}
std::string StringManipulate::WstringToString(const std::wstring &str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(str);
}
std::wstring StringManipulate::StringToWString(const std::string &str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
std::string StringManipulate::Trim(const std::string &str)
{
size_t first = str.find_first_not_of(' ');
if(first == std::string::npos)
return "";
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
| 25.30137 | 108 | 0.701137 | [
"vector"
] |
da670f302eabeb6a8ea89852a7b19028e1994487 | 20,872 | cc | C++ | Core/DianYing/Source/Element/FActor.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | 4 | 2019-03-17T19:46:54.000Z | 2019-12-09T20:11:01.000Z | Core/DianYing/Source/Element/FActor.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | Core/DianYing/Source/Element/FActor.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | #include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
/// Header file
#include <Dy/Element/FActor.h>
#include <Dy/Component/CTransform.h>
#include <Dy/Component/CModelFilter.h>
#include <Dy/Component/CModelRenderer.h>
#include <Dy/Component/CCamera.h>
#include <Dy/Component/CLightDirectional.h>
#include <Dy/Component/CModelAnimator.h>
#include <Dy/Component/CSoundSource.h>
#include <Dy/Component/CPhysicsColliderSphere.h>
#include <Dy/Component/CPhysicsColliderCapsule.h>
#include <Dy/Component/CPhysicsColliderBox.h>
#include <Dy/Component/CSkybox.h>
#include <Dy/Element/Type/PActorCreationDescriptor.h>
#include <Dy/Helper/Internal/FNameGenerator.h>
#include <Dy/Management/MInput.h>
#include <Dy/Management/MWorld.h>
#include <Dy/Management/IO/MIOMeta.h>
#include <Dy/Management/Helper/SProfilingHelper.h>
#include <Dy/Helper/Library/HelperRegex.h>
//!
//! Implementation
//!
namespace dy
{
class FActor::PImplDesc
{
public:
PImplDesc(
const PDyObjectMetaInfo* iObjectMetaDesc,
const PActorCreationDescriptor* iObjectCreationDesc,
FActor* iPtrParentActor)
: mObjectMetaDesc(iObjectMetaDesc),
mObjectCreationDesc(iObjectCreationDesc),
mPtrParentActor(iPtrParentActor) {}
const PDyObjectMetaInfo* mObjectMetaDesc = nullptr;
const PActorCreationDescriptor* mObjectCreationDesc = nullptr;
FActor* mPtrParentActor = nullptr;
};
class FActor::Impl final : public FNameGenerator, public IInitializeHelper<PImplDesc>
{
public:
Impl(FActor& iActor);
virtual ~Impl() = default;
/// @brief Initialize FActor.
EDySuccess pInitilaize(const PDyObjectMetaInfo& objectMetaDesc, FActor* iPtrParent);
EDySuccess pInitilaize(const PActorCreationDescriptor& iDesc, FActor* iPtrParent);
EDySuccess Initialize(const PImplDesc& descriptor) override final
{
if (descriptor.mObjectCreationDesc == nullptr)
{
return this->pInitilaize(*descriptor.mObjectMetaDesc, descriptor.mPtrParentActor);
}
else
{
return this->pInitilaize(*descriptor.mObjectCreationDesc, descriptor.mPtrParentActor);
}
}
void Release() override final
{
SProfilingHelper::DecreaseOnBindActorCount(1);
for (auto& item : this->mComponentList)
{
this->ReleaseComponent(item);
}
this->mComponentList.clear();
// Detach if alreayd attached to picking target of system.
if (this->mIsAttachedToPickingTarget == true) { this->MDY_PRIVATE(DetachPickingTargetFromSystem)(); }
// Release rigidbody also.
if (this->mRigidbody != nullptr) { this->mRigidbody->Release(); }
}
FActor& mRefActor;
void DestroySelf();
void SetParent(FActor& refParentActor) noexcept;
void SetParentAsRoot() noexcept;
/// @brief Check FActor has a parent FActor.
/// @return If it has valid parent, return true but false.
bool HasParent() const noexcept;
/// @brief Return valid parent FActor pointer instance with wrapping optional.
/// @return If parent is binded and exist, return optional valid pointer but just no value.
FActor* GetPtrParent() const noexcept;
/// @brief Return this actor has children object, empty object will be neglected.
/// @return If having children, return true.
bool HasChildrenActor() const noexcept;
/// @brief Return this actor.
TActorMap& GetChildrenContainer() noexcept;
/// @brief Get actual actor type
/// @return Object type specifier
EWorldObjectType GetActorType() const noexcept;
/// @brief Get actor's tag name.
const std::string& GetActorTag() const noexcept;
/// @brief Get valid level reference.
/// @return Valid level reference. when level is not specified, unexpected behaviour.
std::vector<NotNull<FActor*>>
GetAllActorsWithTag(const std::string& iTagSpecifier) const noexcept;
/// @brief Get all actors with tag. Tag must be valid. \n
/// If iTagSpecifier is empty, this function get all actors which is not specified any tag. \n
/// and this function search all actor of object tree from root to leaf, so might take some time.
std::vector<NotNull<FActor*>>
GetAllActorsWithTagRecursive(const std::string& iTagSpecifier) const noexcept;
/// @brief Get all actors with matched name within only one depth of level object tree. \n
/// If iNameSpecifier is empty, just return empty list.
std::vector<NotNull<FActor*>>
GetAllActorsWithName(const std::string& iNameSpecifier) const noexcept;
/// @brief Get all actors with matched name within overall level object tree. \n
/// If iNameSpecifier is empty, just return empty list.
std::vector<NotNull<FActor*>>
GetAllActorsWithNameRecursive(const std::string& iNameSpecifier) const noexcept;
/// @brief Get pointer of actor with object id.
/// If not found, just return nullptr.
FActor* GetActorWithObjectId(TU32 iObjectId) noexcept;
/// @brief Helper function for release component.
void ReleaseComponent(_MINOUT_ TComponentList::value_type& iItem);
/// @brief Try remove script instances list. \n
/// But this funtion does not remove script instance actually, but just forward script list to GC-list.
void MDY_PRIVATE(TryRemoveScriptInstances)() noexcept;
/// @brief Try detach dependent components from dy level management system.
void MDY_PRIVATE(TryDetachDependentComponents)() noexcept;
/// @brief Get script component pointer from script list using scriptName to verify.
/// @param scriptName Script name to verify and get.
/// @return The pointer instance of CDyScript. If not found, return just no value.
MDY_NODISCARD CActorScript* GetScriptComponent(_MIN_ const std::string& scriptName) noexcept;
/// @brief Remove script component manually from script list using scriptName to verify.
/// @param scriptName Script name to verify and remove from FActor.
/// @return The pointer instance of CDyScript. If not found, return just no value.
MDY_NODISCARD EDySuccess RemoveScriptComponent(_MIN_ const std::string& scriptName) noexcept;
/// @brief Get tranform component pointer from FActor instance.
/// @return Valid transform pointer instance.
MDY_NODISCARD NotNull<CTransform*> GetTransform() noexcept;
/// @brief Get rigidbody component pointer from FActor instance.
/// @return Valid rigidbody component pointer instance.
MDY_NODISCARD CPhysicsRigidbody* GetRigidbody() noexcept;
/// @brief Propagate activation flag from parent. This function could not be called independently.
void pUpdateActivateFlagFromParent() noexcept;
/// @brief Attach this actor to picking target pointer variable of internal system.
void MDY_PRIVATE(AttachPickingTargetFromSystem)(_MINOUT_ FActor** iPPtrTarget);
/// @brief Detach this actor from target pointer variable of internal system.
/// If already or not attached to pointer, just do nothing but return EDySuccess::DY_FAILURE.
EDySuccess MDY_PRIVATE(DetachPickingTargetFromSystem)();
CActorScript* pAddScriptComponent(const PDyScriptComponentMetaInfo& iInfo)
{
// Validation check.
const auto specifierName = iInfo.mDetails.mSpecifierName;
auto& metaManager = MIOMeta::GetInstance();
if (metaManager.IsScriptMetaInformationExist(specifierName) == false)
{
DyPushLogDebugError("Failed to create script, {}. Script information is not exist.", specifierName);
return nullptr;
};
// Get information of script to be created.
const auto& instanceInfo = metaManager.GetScriptMetaInformation(specifierName);
MDY_ASSERT_MSG(
instanceInfo.mScriptType != EDyScriptType::NoneError,
"Script type must be valid.");
return this->AddScriptComponent(instanceInfo);
}
CActorScript* AddScriptComponent(const PDyScriptInstanceMetaInfo& iComponentInfo);
template<class TComponent, typename... TArgs>
NotNull<TComponent*> AddComponent(TArgs&&... args)
{
// Validation test
static_assert(
IsInheritancedFrom<TComponent, ABaseComponent>,
"Failed to create component, required component type is not inheritenced from ABaseComponent");
// If component is script, process the other subroutine.
if constexpr (IsSameClass<CActorScript, TComponent> == true)
{
// Add and initialize component itself.
// If component which just added is CDyScript, Call Initiate script first.
auto* ptrComponent = this->pAddScriptComponent(std::forward<TArgs...>(args)...);
MDY_ASSERT_MSG_FORCE(ptrComponent != nullptr, "");
return DyMakeNotNull(ptrComponent);
}
else
{
// Add and initialize component itself.
auto componentPtr = std::make_unique<TComponent>(std::ref(this->mRefActor));
MDY_CALL_ASSERT_SUCCESS(componentPtr->Initialize(std::forward<TArgs>(args)...));
// If it is transform, move it to separated space.
if constexpr (IsSameClass<CTransform, TComponent> == true)
{ // If component is not CDyScript but related to ADyBaseTransform (Transform components)
MDY_ASSERT_MSG_FORCE(
this->mTransform == nullptr,
"FActor::mTransform must be empty when insert transform component.");
this->mTransform = std::move(componentPtr);
return DyMakeNotNull(this->mTransform.get());
}
else if constexpr (IsSameClass<TComponent, CPhysicsRigidbody> == true)
{ // If component is CPhysicsRigidbody...
MDY_ASSERT_MSG_FORCE(
this->mRigidbody == nullptr,
"FActor::mRigidbody must be empty when insert rigidbody component.");
this->mRigidbody = std::move(componentPtr);
return DyMakeNotNull(this->mRigidbody.get());
}
else
{ // Otherwise remain, just return Ptr.
auto& [value, reference] = this->mComponentList.emplace_back(
std::make_pair(TComponentUnbindingType<TComponent>::Value, std::move(componentPtr))
);
return DyMakeNotNull(static_cast<TComponent*>(reference.get()));
}
}
}
template<class TGeneralComponent>
std::optional<TGeneralComponent*> GetGeneralComponent()
{
static_assert(
IsInheritancedFrom<TGeneralComponent, ABaseComponent>,
"Failed to get component, required component type is not inheritenced from ABaseComponent");
// Component matching process is using recursion of each component
// from last derived component class to highest base component class.
for (auto& [type, component] : this->mComponentList)
{
if (component != nullptr) { continue; }
if (component->IsTypeMatched(TGeneralComponent::__mHashVal) == true)
{
return static_cast<TGeneralComponent*>(component.get());
}
}
// If there is no component to find.
return std::nullopt;
}
template <class TGeneralComponent>
std::vector<NotNull<TGeneralComponent*>> GetGeneralComponentList()
{
static_assert(
IsInheritancedFrom<TGeneralComponent, AGeneralBaseComponent>,
"Failed to get component list, required component type is not inheritenced from ABaseComponent");
// Component matching process is using recursion of each component
// from last derived component class to highest base component class.
std::vector<NotNull<TGeneralComponent*>> resultList = {};
for (auto& [type, component] : this->mComponentList)
{
if (component == nullptr) { continue; }
if (component->IsTypeMatched(TGeneralComponent::__mHashVal) == true)
{
resultList.emplace_back(static_cast<TGeneralComponent*>(component.get()));
}
}
return resultList;
}
template <class TComponent, typename... TArgs>
EDySuccess RemoveComponent(TArgs&&... args)
{
static_assert(
IsInheritancedFrom<TComponent, ABaseComponent>,
"Failed to remove component, required component type is not inheritenced from ABaseComponent");
if constexpr (std::is_base_of_v<AGeneralBaseComponent, TComponent>)
{
auto it = std::find_if(
MDY_BIND_BEGIN_END(this->mComponentList),
[](const auto& item) { return item->IsTypeMatched(TComponent::__mHashVal); }
);
if (it == this->mComponentList.end()) { return EDySuccess::DY_FAILURE; }
this->ReleaseComponent(*it);
this->mComponentList.erase(it);
return EDySuccess::DY_SUCCESS;
}
else if constexpr (std::is_same_v<CActorScript, TComponent>)
{
// @TODO IMPLEMENT SCRIPT DELETION USING DESCRIPTOR OR SCRIPT NAME.
return this->RemoveScriptComponent(std::forward<TArgs>(args)...);
}
return EDySuccess::DY_FAILURE;
}
/// Actual actor type to discriminate actor type is so cast object with statically.
MDY_TRANSIENT EWorldObjectType mActorType = EWorldObjectType::NoneError;
void TryActivateInstance();
void TryDeactivateInstance();
/// @brief
void CreateComponentsWithList(_MIN_ const TComponentMetaList& iMetaComponentList);
/// @brief
void pPropagateActivationFlag() noexcept;
/// Parent FActor raw-pointer data.
FActor* mPtrParentActor = MDY_INITIALIZE_NULL;
/// Transform component.
std::unique_ptr<CTransform> mTransform = MDY_INITIALIZE_NULL;
/// Rigidbody component.
std::unique_ptr<CPhysicsRigidbody> mRigidbody = MDY_INITIALIZE_NULL;
/// Component list (randomly) which attached to FActor instance (this!)
TComponentList mComponentList = {};
/// Script list (specialized!)
TScriptList mScriptList = {};
/// Actor list (hierarchial version)
TActorMap mChildrenActors = {};
/// @brief Tag specifier
std::string mActorTagSpecifier = MDY_INITIALIZE_EMPTYSTR;
/// @brief Internal variable.
bool mIsAttachedToPickingTarget = false;
};
} /// ::dy namespace
#include <Dy/Element/Inline/FActorImpl.inl>
//!
//! Proxy
//!
namespace dy
{
FActor::FActor(const PDyObjectMetaInfo& objectMetaDesc, FActor* iPtrParent)
{
this->mInternal = new Impl(*this);
this->pSetObjectName(objectMetaDesc.mSpecifierName);
this->mInternal->Initialize(PImplDesc{&objectMetaDesc, nullptr, iPtrParent});
}
FActor::FActor(const PActorCreationDescriptor& iDesc, FActor* iPtrParent)
{
this->mInternal = new Impl(*this);
this->pSetObjectName(iDesc.mActorSpecifierName);
this->mInternal->Initialize(PImplDesc{nullptr, &iDesc, iPtrParent});
}
FActor::~FActor()
{
this->mInternal->Release();
delete this->mInternal; this->mInternal = nullptr;
}
FActor* FActor::GetActorWithFullName(const std::vector<std::string>& iKeywords) const noexcept
{
if (iKeywords.empty() == true) { return nullptr; }
// Find actor by searching with name.
for (auto& [actorSpecifier, smtptrActor] : this->mInternal->mChildrenActors)
{
if (smtptrActor == nullptr) { continue; }
if (actorSpecifier == iKeywords.front())
{
// If keyword is last keyword, return actor's pointer.
if (iKeywords.size() == 1)
{
return smtptrActor.get();
}
// Otherwise, do recursion one more..
std::vector<std::string> nextKeywords;
nextKeywords.insert(nextKeywords.end(), iKeywords.cbegin() + 1, iKeywords.cend());
return smtptrActor->GetActorWithFullName(nextKeywords);
}
}
return nullptr;
}
FActor* FActor::GetActorWithFullName(const std::string& iFullName) const noexcept
{
auto optKeywords = regex::GetMatchedKeywordFrom(iFullName, R"regex(([\w]+))regex");
if (optKeywords.has_value() == false)
{
return nullptr;
}
return this->GetActorWithFullName(*optKeywords);
}
void FActor::DestroySelf()
{
MWorld::GetInstance().DestroyActor(*this);
}
const std::string& FActor::GetActorName() const noexcept
{
return this->pGetObjectName();
}
std::string FActor::GetActorFullName() const noexcept
{
if (this->HasParent() == false)
{
return this->GetActorName();
}
else
{
const auto headFullSpecifierName = this->GetPtrParent()->GetActorFullName();
return MakeStringU8("{}.{}", headFullSpecifierName, this->GetActorName());
}
}
void FActor::pUpdateActivateFlagFromParent() noexcept
{
this->mInternal->pUpdateActivateFlagFromParent();
}
void FActor::MDY_PRIVATE(AttachPickingTargetFromSystem)(_MINOUT_ FActor** iPPtrTarget)
{
this->mInternal->__AttachPickingTargetFromSystem(iPPtrTarget);
}
EDySuccess FActor::MDY_PRIVATE(DetachPickingTargetFromSystem)()
{
return this->mInternal->__DetachPickingTargetFromSystem();
}
void FActor::SetParent(FActor& iValidParent) noexcept
{
return this->mInternal->SetParent(iValidParent);
}
void FActor::SetParentAsRoot() noexcept
{
return this->mInternal->SetParentAsRoot();
}
EWorldObjectType FActor::GetActorType() const noexcept
{
return this->mInternal->GetActorType();
}
const std::string& FActor::GetActorTag() const noexcept
{
return this->mInternal->GetActorTag();
}
std::vector<NotNull<FActor*>>
FActor::GetAllActorsWithTag(const std::string& iTagSpecifier) const noexcept
{
return this->mInternal->GetAllActorsWithTag(iTagSpecifier);
}
std::vector<NotNull<FActor*>>
FActor::GetAllActorsWithTagRecursive(const std::string& iTagSpecifier) const noexcept
{
return this->mInternal->GetAllActorsWithTagRecursive(iTagSpecifier);
}
std::vector<NotNull<FActor*>>
FActor::GetAllActorsWithName(const std::string& iNameSpecifier) const noexcept
{
return this->mInternal->GetAllActorsWithName(iNameSpecifier);
}
std::vector<NotNull<FActor*>>
FActor::GetAllActorsWithNameRecursive(const std::string& iNameSpecifier) const noexcept
{
return this->mInternal->GetAllActorsWithNameRecursive(iNameSpecifier);
}
FActor* FActor::GetActorWithObjectId(TU32 iObjectId) noexcept
{
return this->mInternal->GetActorWithObjectId(iObjectId);
}
bool FActor::HasParent() const noexcept { return this->mInternal->HasParent(); }
FActor* FActor::GetPtrParent() const noexcept { return this->mInternal->GetPtrParent(); }
bool FActor::HasChildrenActor() const noexcept { return this->mInternal->HasChildrenActor(); }
FActor::TActorMap& FActor::GetChildrenContainer() noexcept
{
return this->mInternal->GetChildrenContainer();
}
std::string FActor::ToString()
{
return MakeStringU8("Actor name : {}, Id : {}", this->GetActorName(), this->GetId());
}
void FActor::CreateActorInstantly(const PActorCreationDescriptor& iDescriptor)
{
// Get Auto generated name.
PActorCreationDescriptor desc = iDescriptor;
desc.mActorSpecifierName = this->mInternal->TryGetGeneratedName(iDescriptor.mActorSpecifierName);
auto instancePtr = std::make_unique<FActor>(desc, this);
auto [it, isSucceeded] = this->mInternal->mChildrenActors.try_emplace(
instancePtr->GetActorName(),
std::move(instancePtr));
MDY_ASSERT_MSG(
isSucceeded == true,
"Unexpected error occured in inserting FActor to object map.");
// Try propagate transform.
auto& [specifier, ptrsmtActor] = *it;
if (ptrsmtActor->HasParent() == true)
{
ptrsmtActor->GetPtrParent()->GetTransform()->TryPropagateTransformToChildren();
}
}
void FActor::MDY_PRIVATE(TryRemoveScriptInstances)() noexcept
{
this->mInternal->__TryRemoveScriptInstances();
}
void FActor::MDY_PRIVATE(TryDetachDependentComponents)() noexcept
{
this->mInternal->__TryDetachDependentComponents();
}
NotNull<CTransform*> FActor::GetTransform() noexcept
{
return this->mInternal->GetTransform();
}
CPhysicsRigidbody* FActor::GetRigidbody() noexcept
{
return this->mInternal->GetRigidbody();
}
CActorScript* FActor::pAddScriptComponent(const PDyScriptComponentMetaInfo& iInfo)
{
// Validation check.
const auto specifierName = iInfo.mDetails.mSpecifierName;
auto& metaManager = MIOMeta::GetInstance();
if (metaManager.IsScriptMetaInformationExist(specifierName) == false)
{
DyPushLogDebugError("Failed to create script, {}. Script information is not exist.", specifierName);
return nullptr;
};
// Get information of script to be created.
const auto& instanceInfo = metaManager.GetScriptMetaInformation(specifierName);
MDY_ASSERT_MSG(
instanceInfo.mScriptType != EDyScriptType::NoneError,
"Script type must be valid.");
return this->mInternal->AddScriptComponent(instanceInfo);
}
FActor::TComponentList& FActor::pGetComponentList() noexcept
{
return this->mInternal->mComponentList;
}
void FActor::pReleaseComponent(TComponentItem& ioItem)
{
this->mInternal->ReleaseComponent(ioItem);
}
void FActor::TryActivateInstance()
{
this->mInternal->TryActivateInstance();
}
void FActor::TryDeactivateInstance()
{
this->mInternal->TryDeactivateInstance();
}
} /// ::dy namespace
| 34.328947 | 106 | 0.730931 | [
"object",
"vector",
"transform"
] |
da6732a25b89f6f3d663cf3ced1fb29dff433686 | 6,695 | cpp | C++ | main.cpp | Sandalmoth/mandelbrot | c6913108b2df2e671099c67d4389b6604c421a46 | [
"Zlib"
] | null | null | null | main.cpp | Sandalmoth/mandelbrot | c6913108b2df2e671099c67d4389b6604c421a46 | [
"Zlib"
] | null | null | null | main.cpp | Sandalmoth/mandelbrot | c6913108b2df2e671099c67d4389b6604c421a46 | [
"Zlib"
] | null | null | null | #include <iostream>
#include <map>
#include <memory>
#include <SDL2/SDL.h>
#include <string>
#include <tclap/CmdLine.h>
#include <tuple>
#include "man.h"
#include "man-thrd.h"
#include "man-sycl.h"
#include "man-opencl.h"
using namespace std;
const string VERSION = "0.2";
struct Parameters {
int window_width;
int window_height;
uint64_t max_iters;
int n_threads;
string renderer;
string palette;
};
struct State {
int mouse_x;
int mouse_y;
int mip_width;
int mip_height;
int mip = 1;
int mipdiv = 1 << (1 - mip);
};
tuple<int, int, int> interpolate_colour(tuple<int, int, int > a, tuple<int, int, int> b, double x);
int main(int argc, char **argv) {
Parameters p;
try {
TCLAP::CmdLine cmd("Mandelbrot drawer", ' ', VERSION);
TCLAP::ValueArg<int> a_window_width("", "window-width", "Width of window in pixels", false, 1536, "positive integer", cmd);
TCLAP::ValueArg<int> a_window_height("", "window-height", "Height of window in pixels", false, 1024, "positive integer", cmd);
TCLAP::ValueArg<int> a_max_iters("x", "max-iters", "Maximum iterations per pixel default", false, 1000, "positive integer", cmd);
TCLAP::ValueArg<int> a_n_threads("n", "n-threads", "Maximum number of threads to use in thread mode", false, 4, "positive integer", cmd);
vector<string> allowed_rendermodes;
allowed_rendermodes.push_back("single");
allowed_rendermodes.push_back("thread");
allowed_rendermodes.push_back("sycl");
allowed_rendermodes.push_back("opencl");
TCLAP::ValuesConstraint<string> allowedVals(allowed_rendermodes);
TCLAP::ValueArg<string> a_renderer("r", "renderer", "Renderer to use", false, "thread", &allowedVals, cmd);
vector<string> allowed_palettes;
allowed_rendermodes.push_back("rainbow");
TCLAP::ValuesConstraint<string> allowedVals2(allowed_palettes);
TCLAP::ValueArg<string> a_palette("p", "palette", "Palette to use", false, "rainbow", &allowedVals2, cmd);
cmd.parse(argc, argv);
p.window_width = a_window_width.getValue();
p.window_height = a_window_height.getValue();
p.max_iters = a_max_iters.getValue();
p.n_threads = a_n_threads.getValue();
p.renderer = a_renderer.getValue();
p.palette = a_palette.getValue();
} catch (TCLAP::ArgException &e) {
cerr << "TCLAP Error: " << e.error() << endl << "\targ: " << e.argId() << endl;
}
unique_ptr<Man> mandel;
// TODO add selection code
// mandel = make_unique<Man>();
if (p.renderer == "single") {
mandel = make_unique<Man>();
} else if (p.renderer == "thread") {
mandel = make_unique<ManThrd>();
} else if (p.renderer == "sycl") {
mandel = make_unique<ManSYCL>();
} else if (p.renderer == "opencl") {
mandel = make_unique<ManOpenCL>();
}
mandel->set_n_threads(p.n_threads);
mandel->set_dims(p.window_width, p.window_height);
mandel->set_max_iters(p.max_iters);
// Set up SDL
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow
( "Mandelbrot"
, SDL_WINDOWPOS_UNDEFINED
, SDL_WINDOWPOS_UNDEFINED
, p.window_width
, p.window_height
, SDL_WINDOW_SHOWN
);
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
// Generate palette
vector<tuple<int, int, int>> palette;
if (p.palette == "rainbow") {
palette.push_back(tuple<int, int, int>{0xFF, 0x10, 0x10});
palette.push_back(tuple<int, int, int>{0xFF, 0x88, 0x10});
palette.push_back(tuple<int, int, int>{0xFF, 0xFF, 0x10});
palette.push_back(tuple<int, int, int>{0x88, 0xFF, 0x10});
palette.push_back(tuple<int, int, int>{0x10, 0xFF, 0x10});
palette.push_back(tuple<int, int, int>{0x10, 0xFF, 0x88});
palette.push_back(tuple<int, int, int>{0x10, 0xFF, 0xFF});
palette.push_back(tuple<int, int, int>{0x10, 0x88, 0xFF});
palette.push_back(tuple<int, int, int>{0x10, 0x10, 0xFF});
palette.push_back(tuple<int, int, int>{0x88, 0x10, 0xFF});
palette.push_back(tuple<int, int, int>{0xFF, 0x10, 0xFF});
palette.push_back(tuple<int, int, int>{0xFF, 0x10, 0x88});
}
// main loop
SDL_Event event;
bool run = true;
bool redraw = true;
bool update = true;
State s;
s.mip_width = p.window_width;
s.mip_height = p.window_height;
while (run) {
if (update) {
s.mipdiv = 1 << (s.mip - 1);
s.mip_width = p.window_width/s.mipdiv;
s.mip_height = p.window_height/s.mipdiv;
mandel->set_dims(s.mip_width, s.mip_height);
mandel->update();
redraw = true;
update = false;
if (s.mip > 1) {
--s.mip;
update = true;
}
}
if (redraw) {
SDL_SetRenderDrawColor( renderer, 0x0, 0x0, 0x0, 0xFF);
SDL_RenderClear(renderer);
auto data = mandel->get_data();
for (int x = 0; x < s.mip_width; ++x) {
for (int y = 0; y < s.mip_height; ++y) {
double i = data[y*s.mip_width + x];
auto colour1 = palette[static_cast<int>(i) % palette.size()];
auto colour2 = palette[static_cast<int>(i+1.0) % palette.size()];
auto icol = interpolate_colour(colour1, colour2, i - floor(i));
if (i >= static_cast<double>(p.max_iters)) {
SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF);
} else {
SDL_SetRenderDrawColor(renderer, get<0>(icol), get<1>(icol), get<2>(icol), 0xFF);
}
if (s.mip > 0) {
SDL_Rect rect = {x*s.mipdiv, y*s.mipdiv, s.mipdiv, s.mipdiv};
SDL_RenderFillRect(renderer, &rect);
} else {
SDL_RenderDrawPoint(renderer, x, y);
}
}
}
SDL_RenderPresent(renderer);
redraw = false;
}
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT) {
run = false;
} else if (event.type == SDL_MOUSEWHEEL) {
if (event.wheel.y > 0) {
mandel->zoom_towards(s.mouse_x / static_cast<double>(p.window_width), s.mouse_y / static_cast<double>(p.window_height));
} else if (event.wheel.y < 0) {
mandel->zoom_away();
}
if (s.mip < 8) {
++s.mip;
}
update = true;
} else if (event.type == SDL_MOUSEMOTION) {
s.mouse_x = event.motion.x;
s.mouse_y = event.motion.y;
}
}
}
// Exit SDL
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
tuple<int, int, int> interpolate_colour(tuple<int, int, int> a, tuple<int, int, int> b, double i) {
double x, y, z;
x = get<0>(a) + (get<0>(b) - get<0>(a)) * i;
y = get<1>(a) + (get<1>(b) - get<1>(a)) * i;
z = get<2>(a) + (get<2>(b) - get<2>(a)) * i;
return tuple<int, int, int>{x, y, z};
}
| 31.580189 | 141 | 0.622704 | [
"vector"
] |
da6c44577ab0bd8dd4e93f9b07a351a2d8698f00 | 423 | hpp | C++ | source/tm/files_in_path.hpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 7 | 2021-03-05T16:50:19.000Z | 2022-02-02T04:30:07.000Z | source/tm/files_in_path.hpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 47 | 2021-02-01T18:54:23.000Z | 2022-03-06T19:06:16.000Z | source/tm/files_in_path.hpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 1 | 2021-01-28T13:10:41.000Z | 2021-01-28T13:10:41.000Z | // Copyright David Stone 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <containers/vector.hpp>
#include <filesystem>
namespace technicalmachine {
auto files_in_path(std::filesystem::path const & path) -> containers::vector<std::filesystem::path>;
} // namespace technicalmachine
| 24.882353 | 100 | 0.756501 | [
"vector"
] |
da7a29728510e7db869ab7c39164a61a8ff6ef2d | 566 | cpp | C++ | client/transportableobject.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 1 | 2015-08-23T11:03:58.000Z | 2015-08-23T11:03:58.000Z | client/transportableobject.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | null | null | null | client/transportableobject.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 3 | 2016-12-05T02:43:52.000Z | 2021-06-30T21:35:46.000Z | #include "transportableobject.h"
namespace MoodBox
{
TransportableObject::~TransportableObject()
{
}
PropertyInfo TransportableObject::getPropertyInfo(Model *model, QString name)
{
return model->getPropertyInfo(getTypeId(), name);
}
void TransportableObject::writeProperties(PropertyWriter *writer)
{
Q_UNUSED(writer);
}
PropertyReadResult TransportableObject::readProperty(qint32 propertyId, qint32 typeId, PropertyReader *reader)
{
Q_UNUSED(propertyId);
Q_UNUSED(typeId);
Q_UNUSED(reader);
return PropertyReadResult(false);
}
} | 20.962963 | 111 | 0.761484 | [
"model"
] |
da903f3c5753538ae711fba9fd666e5a81feaa9e | 2,327 | hpp | C++ | Nana.Cpp03/include/nana/gui/widgets/checkbox.hpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | 1 | 2018-02-09T21:25:13.000Z | 2018-02-09T21:25:13.000Z | Nana.Cpp03/include/nana/gui/widgets/checkbox.hpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | null | null | null | Nana.Cpp03/include/nana/gui/widgets/checkbox.hpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | null | null | null | /*
* A CheckBox Implementation
* Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: nana/gui/widgets/checkbox.hpp
*/
#ifndef NANA_GUI_WIDGET_CHECKBOX_HPP
#define NANA_GUI_WIDGET_CHECKBOX_HPP
#include "widget.hpp"
#include <vector>
namespace nana{ namespace gui{
namespace drawerbase
{
namespace checkbox
{
class drawer
: public drawer_trigger
{
struct implement;
public:
drawer();
~drawer();
void bind_window(widget_reference);
void attached(graph_reference);
void detached();
void refresh(graph_reference);
void mouse_enter(graph_reference, const eventinfo&);
void mouse_leave(graph_reference, const eventinfo&);
void mouse_down(graph_reference, const eventinfo&);
void mouse_up(graph_reference, const eventinfo&);
public:
implement * impl() const;
private:
void _m_draw(graph_reference);
void _m_draw_background(graph_reference);
void _m_draw_checkbox(graph_reference, unsigned first_line_height);
void _m_draw_title(graph_reference);
private:
static const int interval = 4;
widget* widget_;
unsigned state_;
implement * impl_;
};
}//end namespace checkbox
}//end namespace drawerbase
class checkbox
: public widget_object<category::widget_tag, drawerbase::checkbox::drawer>
{
public:
checkbox();
checkbox(window, bool visible);
checkbox(window, const nana::string& text, bool visible = true);
checkbox(window, const nana::char_t* text, bool visible = true);
checkbox(window, const rectangle& = rectangle(), bool visible = true);
void element_set(const char* name);
void react(bool want);
bool checked() const;
void check(bool chk);
void radio(bool);
void transparent(bool value);
bool transparent() const;
};//end class checkbox
class radio_group
{
struct element_tag
{
checkbox * uiobj;
event_handle eh_checked;
event_handle eh_destroy;
};
public:
~radio_group();
void add(checkbox&);
std::size_t checked() const;
private:
void _m_checked(const eventinfo&);
void _m_destroy(const eventinfo&);
private:
std::vector<element_tag> ui_container_;
};
}//end namespace gui
}//end namespace nana
#endif
| 24.494737 | 76 | 0.727976 | [
"vector"
] |
da9d3898f4d322b78396486132b8622cbeaa968f | 5,894 | hh | C++ | inc/Dron.hh | filepix13/dron | 5f98c764cf876c8ba57dfce0862d2e8494498442 | [
"MIT"
] | null | null | null | inc/Dron.hh | filepix13/dron | 5f98c764cf876c8ba57dfce0862d2e8494498442 | [
"MIT"
] | null | null | null | inc/Dron.hh | filepix13/dron | 5f98c764cf876c8ba57dfce0862d2e8494498442 | [
"MIT"
] | null | null | null | #ifndef DRON_HH
#define DRON_HH
#include "InterfejsDrona.hh"
#include "InterfejsPrzeszkody.hh"
#include "Prostopadloscian.hh"
#include <unistd.h>
/*!
* \brief Klasa modeluje menu do sterowania dronem
*/
class Dron : public InterfejsDrona, public InterfejsPrzeszkody, public Prostopadloscian, public std::enable_shared_from_this<Dron>
{
public:
/*!
* \brief Konstruktor parametryczny
* \param api - gunplot
*/
Dron(std::shared_ptr<drawNS::Draw3DAPI> &api, Wektor<double, 3> W)
{
srodek = W;
Prostopadloscian p(W);
L.zmienWierzcholkiW(srodek, orientacja);
P.zmienWierzcholkiW(srodek, orientacja);
index[0] = rysuj(api);
index[1] = L.rysuj(api);
index[2] = P.rysuj(api);
}
/*!
* \brief Funkcja zwraca pole środek drona
*/
Wektor<double, 3> zwrocSrodek() override
{
return srodek;
}
/*!
* \brief Funkcja zwraca pole R drona
*/
double zwrocR() override
{
return R;
}
/*!
* \brief Funkcja przesuwa drona, oraz animuje jego ruch
* \param api - wskaźnik na gunplota,
* \param b - wartość y wektora o jaką przesuwamy drona
* \param kat- kąt obrotu wokół osi X
* \param kolekcja_przeszkod - przeszkody z którymi koliduje dron
*/
void Przesun(std::shared_ptr<drawNS::Draw3DAPI> &api, double b, double kat, std::vector<std::shared_ptr<InterfejsPrzeszkody>> kolekcja_przeszkod) override
{
Wektor<double,3> W;
Wektor<double,3> Back;
W.ustaw(0,b/100,0);
Back.ustaw(0,-0.1,0);
MacierzOb a('x',kat/100);
MacierzOb pa('x',-kat/100);
if(kat>90 || kat<-90)
{
std::cout << "Kąt powinen być >= -90 oraz <= 90"<< std::endl << std::endl;
return;
}
for(int i = 0; i<100; i++)
{
usun(api, index[0]);
usun(api, index[1]);
usun(api, index[2]);
zmien_orient(a);
L.obrotW();
L.zmienWierzcholkiW(srodek, orientacja);
P.obrotW();
P.zmienWierzcholkiW(srodek, orientacja);
index[0] = rysuj(api);
index[1] = L.rysuj(api);
index[2] = P.rysuj(api);
usleep(5000);
}
for(int i = 0; i<100; i++)
{
usun(api, index[0]);
usun(api, index[1]);
usun(api, index[2]);
przesuniecie(W);
L.obrotW();
L.zmienWierzcholkiW(srodek, orientacja);
P.obrotW();
P.zmienWierzcholkiW(srodek, orientacja);
index[0] = rysuj(api);
index[1] = L.rysuj(api);
index[2] = P.rysuj(api);
usleep(5000);
for (auto elem : kolekcja_przeszkod) /* Sprawdzanie kolizji dla każdej klatki ruchu*/
{
if(elem->czy_kolizja(shared_from_this()))
{
usun(api, index[0]);
usun(api, index[1]);
usun(api, index[2]);
przesuniecie(Back);
L.obrotW();
L.zmienWierzcholkiW(srodek, orientacja);
P.obrotW();
P.zmienWierzcholkiW(srodek, orientacja);
index[0] = rysuj(api);
index[1] = L.rysuj(api);
index[2] = P.rysuj(api);
usleep(5000);
i=100;
break;
}
}
}
for(int i = 0; i<100; i++)
{
usun(api, index[0]);
usun(api, index[1]);
usun(api, index[2]);
zmien_orient(pa);
L.obrotW();
L.zmienWierzcholkiW(srodek, orientacja);
P.obrotW();
P.zmienWierzcholkiW(srodek, orientacja);
index[0] = rysuj(api);
index[1] = L.rysuj(api);
index[2] = P.rysuj(api);
usleep(5000);
}
}
/*!
* \brief Funkcja obraca drona wokół osi Z oraz animuje ten ruch
* \param api - wskaźnik na gunplota,
* \param kat- kąt obrotu wokół osi Z,
*/
void obrot(std::shared_ptr<drawNS::Draw3DAPI> &api, double kat) override
{
MacierzOb M('z', kat/100);
for(int i = 0; i<100; i++)
{
usun(api, index[0]);
usun(api, index[1]);
usun(api, index[2]);
zmien_orient(M);
L.obrotW();
L.zmienWierzcholkiW(srodek, orientacja);
P.obrotW();
P.zmienWierzcholkiW(srodek, orientacja);
index[0] = rysuj(api);
index[1] = L.rysuj(api);
index[2] = P.rysuj(api);
usleep(25000);
}
}
/*!
* \brief Funkcja sprawdza kolizję drona z dronem
* \param dron - wskaźnik na dron którym prowadzimy
*/
bool czy_kolizja(std::shared_ptr<InterfejsDrona> dron) override
{
Wektor<double, 3> Wek = dron->zwrocSrodek();
if(Wek[0] == srodek[0] && Wek[1] == srodek[1] && Wek[2] == srodek[2])
return false;
if(Wek[0] <= srodek[0] + 2*dron->zwrocR() && Wek[0] >= srodek[0] - 2*dron->zwrocR())
{
if(Wek[1] <= srodek[1] + 2*dron->zwrocR() && Wek[1] >= srodek[1] - 2*dron->zwrocR())
{
if(Wek[2] <= srodek[2] + 2*dron->zwrocR() && Wek[2] >= srodek[2] - 2*dron->zwrocR())
{
std::cout << std::endl << "Nastąpiła kolizja drona z dronem" << std::endl << std::endl;
return true;
}
else
return false;
}
else
return false;
}
else
return false;
}
};
#endif | 27.413953 | 158 | 0.483034 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.