hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0835c0274bfc544a1f0bcb3953c322fc1bba3b9d
2,362
cpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/icd2/mmio/mmio.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
1,414
2015-06-28T09:57:51.000Z
2021-10-14T03:51:10.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/icd2/mmio/mmio.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
2,369
2015-06-25T01:45:44.000Z
2021-10-16T08:44:18.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/icd2/mmio/mmio.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
430
2015-06-29T04:28:58.000Z
2021-10-05T18:24:17.000Z
#ifdef ICD2_CPP //convert linear pixel data { 0x00, 0x55, 0xaa, 0xff } to 2bpp planar tiledata void ICD2::render(const uint16 *source) { memset(lcd.output, 0x00, 320 * sizeof(uint16)); for(unsigned y = 0; y < 8; y++) { for(unsigned x = 0; x < 160; x++) { unsigned pixel = *source++; unsigned addr = y * 2 + (x / 8 * 16); lcd.output[addr + 0] |= ((pixel & 1) >> 0) << (7 - (x & 7)); lcd.output[addr + 1] |= ((pixel & 2) >> 1) << (7 - (x & 7)); } } } uint8 ICD2::read(unsigned addr) { addr &= 0xffff; //LY counter if(addr == 0x6000) { r6000_ly = GameBoy::lcd.status.ly; r6000_row = lcd.row; return r6000_ly; } //command ready port if(addr == 0x6002) { bool data = packetsize > 0; if(data) { for(unsigned i = 0; i < 16; i++) r7000[i] = packet[0][i]; packetsize--; for(unsigned i = 0; i < packetsize; i++) packet[i] = packet[i + 1]; } return data; } //ICD2 revision if(addr == 0x600f) { return 0x21; } //command port if((addr & 0xfff0) == 0x7000) { return r7000[addr & 15]; } //VRAM port if(addr == 0x7800) { uint8 data = lcd.output[r7800]; r7800 = (r7800 + 1) % 320; return data; } return 0x00; } void ICD2::write(unsigned addr, uint8 data) { addr &= 0xffff; //VRAM port if(addr == 0x6001) { r6001 = data; r7800 = 0; unsigned offset = (r6000_row - (4 - (r6001 - (r6000_ly & 3)))) & 3; render(lcd.buffer + offset * 160 * 8); return; } //control port //d7: 0 = halt, 1 = reset //d5,d4: 0 = 1-player, 1 = 2-player, 2 = 4-player, 3 = ??? //d1,d0: 0 = frequency divider (clock rate adjust) if(addr == 0x6003) { if((r6003 & 0x80) == 0x00 && (data & 0x80) == 0x80) { reset(); } switch(data & 3) { case 0: frequency = cpu.frequency / 4; break; //fast (glitchy, even on real hardware) case 1: frequency = cpu.frequency / 5; break; //normal case 2: frequency = cpu.frequency / 7; break; //slow case 3: frequency = cpu.frequency / 9; break; //very slow } r6003 = data; return; } if(addr == 0x6004) { r6004 = data; return; } //joypad 1 if(addr == 0x6005) { r6005 = data; return; } //joypad 2 if(addr == 0x6006) { r6006 = data; return; } //joypad 3 if(addr == 0x6007) { r6007 = data; return; } //joypad 4 } #endif
24.350515
92
0.546571
redscientistlabs
0838510a006e06108c5319dd79c131f2c16bf7b3
1,031
cpp
C++
example/basic/d3d_renderer.cpp
area55git/dynamix
c800209c6f467c19065235e87cbfe60171e75d68
[ "MIT" ]
null
null
null
example/basic/d3d_renderer.cpp
area55git/dynamix
c800209c6f467c19065235e87cbfe60171e75d68
[ "MIT" ]
null
null
null
example/basic/d3d_renderer.cpp
area55git/dynamix
c800209c6f467c19065235e87cbfe60171e75d68
[ "MIT" ]
null
null
null
// DynaMix // Copyright (c) 2013-2016 Borislav Stanimirov, Zahary Karadjov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #include "basic.hpp" #include "d3d_renderer.hpp" #include "rendering_messages.hpp" #include "transform_messages.hpp" #include "system_messages.hpp" using namespace std; void d3d_renderer::render() const { render(0); } void d3d_renderer::render(int render_target) const { int transform = get_combined_transform(dm_this); // main_devince->SetTransform(D3DTS_WORLD, transform); cout << "D3D rendering object " << get_id(dm_this) << endl << "\ton target " << render_target << endl << "\twith transformation: " << transform << endl << "\t" << (_casts_shadows ? "" : "not ") << "casting shadows" << endl; } void d3d_renderer::trace(std::ostream& o) const { o << "\twith a d3d renderer" << endl; } DYNAMIX_DEFINE_MIXIN(d3d_renderer, all_rendering_messages & trace_msg);
26.435897
80
0.690592
area55git
083f05a3f9243aa0df1528f44d7ca3d4e6d82808
1,281
cpp
C++
src/guiCamera.cpp
moxor/remoteX-1
49e8cf3f4025425edcf6e4e4e8f7505b83570652
[ "MIT" ]
2
2015-09-23T23:35:33.000Z
2015-11-04T21:50:45.000Z
src/guiCamera.cpp
nanu-c/remoteX-1
49e8cf3f4025425edcf6e4e4e8f7505b83570652
[ "MIT" ]
null
null
null
src/guiCamera.cpp
nanu-c/remoteX-1
49e8cf3f4025425edcf6e4e4e8f7505b83570652
[ "MIT" ]
1
2015-09-05T15:07:04.000Z
2015-09-05T15:07:04.000Z
#include "guiCamera.h" void GuiCamera::setup(){ cameraParameters.add(gCtoggleOnOff.set("Camera On/Off",false)); //cameraParameters.add(gCtoggleShowImage.set("Camera show image",false)); //cameraParameters.add(gCtoggleGrayscale.set("Camera grayscale",false)); //cameraParameters.add(gCtoggleMask.set("Camera mask",false)); //cameraParameters.add(gCtoggleDetect.set("Camera detect",false)); cameraParameters.add(gC2SliderScale.set("Scale Camera ",ofVec2f(1,1), ofVec2f(0.1, 0.1), ofVec2f(10,10))); cameraParameters.add(gCtoggFit.set("Fit Camera to quad",false)); cameraParameters.add(gCtoggKeepAspect.set("Keep Camera aspect ratio",false)); cameraParameters.add(gCtoggHflip.set("Camera horizontal flip",false)); cameraParameters.add(gCtoggVflip.set("Camera vertical flip",false)); cameraParameters.add(gCcolor.set("Camera color",ofFloatColor(1,1,1), ofFloatColor(0, 0), ofFloatColor(1,1))); cameraParameters.add(gCtoggGreenscreen.set("Camera Greenscreen",false)); cameraParameters.add(gCfsliderVolume.set("Camera Volume",0.0, 0.0, 1.0)); cameraParametersSecond.add(gCtoggleSampler.set("Camera sampler playback",false)); } void GuiCamera::draw(){ //ofSetColor(red, green, blue); //ofCircle(posX, posY, radius); }
44.172414
113
0.735363
moxor
0840f62ec3147029925c2304cbb066c160be164f
949
cpp
C++
android-31/android/renderscript/Script_FieldBase.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/renderscript/Script_FieldBase.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/renderscript/Script_FieldBase.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./Allocation.hpp" #include "./Element.hpp" #include "./RenderScript.hpp" #include "./Type.hpp" #include "./Script_FieldBase.hpp" namespace android::renderscript { // Fields // QJniObject forward Script_FieldBase::Script_FieldBase(QJniObject obj) : JObject(obj) {} // Constructors // Methods android::renderscript::Allocation Script_FieldBase::getAllocation() const { return callObjectMethod( "getAllocation", "()Landroid/renderscript/Allocation;" ); } android::renderscript::Element Script_FieldBase::getElement() const { return callObjectMethod( "getElement", "()Landroid/renderscript/Element;" ); } android::renderscript::Type Script_FieldBase::getType() const { return callObjectMethod( "getType", "()Landroid/renderscript/Type;" ); } void Script_FieldBase::updateAllocation() const { callMethod<void>( "updateAllocation", "()V" ); } } // namespace android::renderscript
20.191489
74
0.708114
YJBeetle
08418e8cfd403298cc6b5247455469aa83411b8c
586
hpp
C++
detail/dynamic_loading.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/dynamic_loading.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/dynamic_loading.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
// Andrew Naplavkov #ifndef BRIG_DETAIL_DYNAMIC_LOADING_HPP #define BRIG_DETAIL_DYNAMIC_LOADING_HPP #include <brig/detail/stringify.hpp> #ifdef _WIN32 #include <windows.h> #define BRIG_DL_LIBRARY(win, lin) LoadLibraryA(win) #define BRIG_DL_FUNCTION(lib, fun) (decltype(fun)*)GetProcAddress(lib, BRIG_STRINGIFY(fun)) #elif defined __linux__ #include <dlfcn.h> #define BRIG_DL_LIBRARY(win, lin) dlopen(lin, RTLD_LAZY) #define BRIG_DL_FUNCTION(lib, fun) (decltype(fun)*)dlsym(lib, BRIG_STRINGIFY(fun)) #endif #endif // BRIG_DETAIL_DYNAMIC_LOADING_HPP
27.904762
94
0.754266
isadchenko
0846ad49573f690806d542070818bce698a9dd07
12,579
cpp
C++
Lib/Tools/FilterTool.cpp
vfdev-5/GeoImageViewer
31e8d6c9340a742c0ffad4c159338da2c15564d7
[ "Apache-2.0" ]
3
2016-08-27T10:46:43.000Z
2022-03-11T11:39:37.000Z
Lib/Tools/FilterTool.cpp
vfdev-5/GeoImageViewer
31e8d6c9340a742c0ffad4c159338da2c15564d7
[ "Apache-2.0" ]
null
null
null
Lib/Tools/FilterTool.cpp
vfdev-5/GeoImageViewer
31e8d6c9340a742c0ffad4c159338da2c15564d7
[ "Apache-2.0" ]
2
2016-08-27T10:46:45.000Z
2018-06-06T01:50:54.000Z
// Qt #include <QPainter> #include <QAction> #include <QGraphicsItem> #include <QGraphicsPixmapItem> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsSceneMouseEvent> #include <QWheelEvent> #include <QPoint> #include <qmath.h> // Opencv #include <opencv2/imgproc/imgproc.hpp> // Project #include "FilterTool.h" #include "Core/LayerUtils.h" namespace Tools { //****************************************************************************** /*! \class FilterTool \brief Abstract class inherits from ImageCreationTool class and represent a base structure to filter image part under the mouse in real-time mode. Abstract method processData() should be subclassed to process input data under the mouse. Virtual method onFinalize() should be subclassed to finish the processing and send the result. The result of the filtering can be a QGraphicsItem or Core::DrawingsItem which is not owned by the class. */ //****************************************************************************** FilterTool::FilterTool(QGraphicsScene *scene, QGraphicsView *view, QObject *parent): ImageCreationTool(parent), _scene(scene), _view(view), _dataProvider(0), _cursorShape(0), _cursorShapeScale(-1), _cursorShapeZValue(1000), _size(100), _isValid(false), _opacity(0.5), _color(Qt::green) { _toolType = Type; _finalize = new QAction(tr("Finalize"), this); _finalize->setEnabled(false); connect(_finalize, SIGNAL(triggered()), this, SLOT(onFinalize())); _actions.append(_finalize); _hideShowResult = new QAction(tr("Hide result"), this); _hideShowResult->setEnabled(false); connect(_hideShowResult, SIGNAL(triggered()), this, SLOT(onHideShowResult())); _actions.append(_hideShowResult); QAction * separator = new QAction(this); separator->setSeparator(true); _actions.append(separator); _clear = new QAction(tr("Clear"), this); _clear->setEnabled(false); connect(_clear, SIGNAL(triggered()), this, SLOT(clear())); _actions.append(_clear); _isValid = _scene && _view; } //****************************************************************************** bool FilterTool::dispatch(QEvent *e, QGraphicsScene *scene) { if (!_isValid) return false; if (e->type() == QEvent::GraphicsSceneMousePress) { QGraphicsSceneMouseEvent * event = static_cast<QGraphicsSceneMouseEvent*>(e); if (event->button() == Qt::LeftButton && !_pressed && !(event->modifiers() & Qt::ControlModifier)) { // check if _drawingsItem exists if (!_drawingsItem) { // create drawings item for the current visible extent QRect wr = _view->viewport()->rect(); QRectF r = _view->mapToScene(wr).boundingRect(); if (r.width() < 2000 && r.height() < 2000) { _drawingsItem = new Core::DrawingsItem(r.width(), r.height(), QColor(Qt::transparent)); _drawingsItem->setPos(r.x(), r.y()); _drawingsItem->setZValue(_cursorShapeZValue-10); _drawingsItem->setOpacity(_opacity); // visible canvas QGraphicsRectItem * canvas = new QGraphicsRectItem(QRectF(0.0,0.0,r.width(), r.height()), _drawingsItem); canvas->setPen(QPen(Qt::white, 0)); canvas->setBrush(QBrush(QColor(127,127,127,50))); canvas->setFlag(QGraphicsItem::ItemStacksBehindParent); scene->addItem(_drawingsItem); _finalize->setEnabled(true); _clear->setEnabled(true); _hideShowResult->setEnabled(true); } else { SD_WARN("Visible zone is too large. Zoom to define smaller zone"); } } if (_drawingsItem && _cursorShape) { _pressed = true; _anchor = event->scenePos(); drawAtPoint(event->scenePos()); return true; } } } else if (e->type() == QEvent::GraphicsSceneMouseMove) { QGraphicsSceneMouseEvent * event = static_cast<QGraphicsSceneMouseEvent*>(e); if (_cursorShape) { double size = _size / qMin(_view->matrix().m11(), _view->matrix().m22()); QPointF pos = event->scenePos(); _cursorShape->setPos(pos - QPointF(0.5*size, 0.5*size)); if (_dataProvider && !_erase) { size *= _cursorShape->scale(); pos -= QPointF(0.5*size, 0.5*size); // SD_TRACE(QString("rect : %1, %2, %3, %4") // .arg(pos.x()) // .arg(pos.y()) // .arg(size) // .arg(size)); QRect r(pos.x(), pos.y(), size, size); cv::Mat data = _dataProvider->getImageData(r); if (!data.empty()) { cv::Mat out = processData(data); // SD_TRACE(QString("out : %1, %2, %3, %4") // .arg(out.rows) // .arg(out.cols) // .arg(out.channels()) // .arg(out.elemSize1())); QPixmap p = QPixmap::fromImage(QImage(out.data, out.cols, out.rows, QImage::Format_ARGB32).copy()); p = p.scaled(QSize(_size,_size)); _cursorShape->setPixmap(p); } } } if (_pressed && (event->buttons() & Qt::LeftButton) && _drawingsItem && _cursorShape) { drawAtPoint(event->scenePos()); } // Allow to process other options on mouse move. Otherwise should return true return false; } else if (e->type() == QEvent::GraphicsSceneMouseRelease) { QGraphicsSceneMouseEvent * event = static_cast<QGraphicsSceneMouseEvent*>(e); if (event->button() == Qt::LeftButton && _pressed) { _pressed=false; _anchor = QPointF(); return true; } return false; } return false; } //****************************************************************************** bool FilterTool::dispatch(QEvent *e, QWidget *viewport) { if (!_isValid) return false; if (e->type() == QEvent::Enter) { // This handle the situation when GraphicsScene was cleared between Enter and Leave events if (!_cursorShape) { createCursor(); viewport->setCursor(_cursor); } return true; } else if (e->type() == QEvent::Leave) { // This handle the situation when GraphicsScene was cleared between Enter and Leave events if (_cursorShape) { destroyCursor(); viewport->setCursor(QCursor()); } return true; } else if (e->type() == QEvent::Wheel) { QWheelEvent * event = static_cast<QWheelEvent*>(e); if (event->modifiers() & Qt::ControlModifier ) { if (_cursorShape) { // mouse has X units that covers 360 degrees. Zoom when 15 degrees is provided #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QPoint numDegrees = event->angleDelta() / 8; #else QPoint numDegrees(0,event->delta() / 8); #endif double scale = _cursorShape->scale(); if (!numDegrees.isNull()) { if (numDegrees.y() >= 15) { // make smaller scale *= 0.6667; scale = scale < 0.2 ? 0.2 : scale; } else if (numDegrees.y() <= -15) { // make larger scale *= 1.5; scale = scale > 5.0 ? 5.0 : scale; } // emit sizeChanged(_size); _cursorShape->setScale(scale); event->accept(); return true; } } } } return false; } //****************************************************************************** void FilterTool::createCursor() { // if (!_cursorShape) // { QPixmap p = QPixmap(_size,_size); p.fill(_drawingsItem ? _drawingsItem->getBackground() : Qt::transparent); QGraphicsPixmapItem * item = new QGraphicsPixmapItem(p); item->setTransformOriginPoint(0.5*_size,0.5*_size); item->setZValue(_cursorShapeZValue); item->setFlag(QGraphicsItem::ItemIgnoresTransformations); item->setOpacity(_opacity); QGraphicsRectItem * br = new QGraphicsRectItem(item->boundingRect(), item); br->setZValue(+1); br->setPen(QPen(Qt::green, 0)); br->setBrush(Qt::transparent); br->setFlag(QGraphicsItem::ItemIgnoresParentOpacity); _cursorShape = item; if (_cursorShapeScale>0) _cursorShape->setScale(_cursorShapeScale); _scene->addItem(_cursorShape); // } } //****************************************************************************** void FilterTool::destroyCursor() { _cursorShapeScale = _cursorShape->scale(); QGraphicsScene * scene = _cursorShape->scene(); if (scene) { scene->removeItem(_cursorShape); delete _cursorShape; _cursorShape = 0; } } //****************************************************************************** void FilterTool::onHideShowResult() { if (_drawingsItem->isVisible()) { _drawingsItem->setVisible(false); _hideShowResult->setText(tr("Show result")); } else { _drawingsItem->setVisible(true); _hideShowResult->setText(tr("Hide result")); } } //****************************************************************************** void FilterTool::onFinalize() { _drawingsItem = 0; _finalize->setEnabled(false); _clear->setEnabled(false); _hideShowResult->setEnabled(false); } //****************************************************************************** void FilterTool::clear() { if (_cursorShape) { destroyCursor(); _cursorShapeScale = -1.0; } if (_drawingsItem) { _scene->removeItem(_drawingsItem); delete _drawingsItem; } FilterTool::onFinalize(); } //****************************************************************************** void FilterTool::setErase(bool erase) { ImageCreationTool::setErase(erase); } //****************************************************************************** void FilterTool::drawAtPoint(const QPointF &pos) { // check if the rectangle to paint is in the drawingItem zone: QRectF r = _drawingsItem->boundingRect(); r.moveTo(_drawingsItem->pos()); double size = _size * _cursorShape->scale() / qMin(_view->matrix().m11(), _view->matrix().m22()); QRectF r2 = QRectF(pos.x()-size*0.5, pos.y()-size*0.5, size, size); if (r.intersects(QRectF(pos.x()-_size*0.5, pos.y()-_size*0.5, _size, _size))) { r2.translate(-_drawingsItem->scenePos()); QPainter p(&_drawingsItem->getImage()); p.setCompositionMode((QPainter::CompositionMode)_mode); QPixmap px = _cursorShape->pixmap(); p.drawPixmap(r2, px, QRectF(0.0,0.0,px.width(),px.height())); r2=r2.adjusted(-size*0.25, -size*0.25, size*0.25, size*0.25); _drawingsItem->update(r2); } } //****************************************************************************** }
32.672727
126
0.479688
vfdev-5
36b02faad043d5086efea43c41e3631cc5b93616
1,005
cpp
C++
MTD/Player.cpp
Hapaxia/MyPracticeBeginnerGames
2289c05677c9630a78fa9188c9c81c33846e2860
[ "MIT" ]
7
2015-08-28T06:57:14.000Z
2019-07-24T18:18:21.000Z
MTD/Player.cpp
Hapaxia/MyPracticeBeginnerGames
2289c05677c9630a78fa9188c9c81c33846e2860
[ "MIT" ]
1
2016-02-12T17:07:32.000Z
2016-02-19T19:22:09.000Z
MTD/Player.cpp
Hapaxia/MyPracticeBeginnerGames
2289c05677c9630a78fa9188c9c81c33846e2860
[ "MIT" ]
1
2019-10-13T03:54:41.000Z
2019-10-13T03:54:41.000Z
#include "Player.hpp" #include <Plinth/Sfml/Generic.hpp> namespace { const pl::Vector2d playerSize{ 64.0, 32.0 }; constexpr double initialSpeed{ 300.0 }; const double minimumPosition{ 0.0 + playerSize.x / 2.0 }; } Player::Player(const sf::RenderWindow& window, const double dt, const Graphics& graphics) : m_dt(dt) , m_speed(initialSpeed) , m_size(playerSize) , m_positionLimits({ minimumPosition, window.getSize().x - playerSize.x / 2.0 }) , m_position(m_positionLimits.min) { } void Player::move(const Direction direction) { double movement; switch (direction) { case Direction::Left: movement = -1.0; break; case Direction::Right: movement = 1.0; break; default: movement = 0.0; } m_position += movement * m_speed * m_dt; m_position = m_positionLimits.clamp(m_position); } void Player::reset() { m_position = minimumPosition; m_speed = initialSpeed; } double Player::getPosition() const { return m_position; } pl::Vector2d Player::getSize() const { return m_size; }
18.272727
89
0.711443
Hapaxia
36b0f5b84cceeaeb398f514b32f30eac377e812d
6,323
cpp
C++
sky/engine/bindings/core/v8/custom/V8InjectedScriptManager.cpp
viettrungluu-cr/mojo
950de5bc66e00aeb1f7bdf2987f253986c0a7614
[ "BSD-3-Clause" ]
5
2019-05-24T01:25:34.000Z
2020-04-06T05:07:01.000Z
sky/engine/bindings/core/v8/custom/V8InjectedScriptManager.cpp
viettrungluu-cr/mojo
950de5bc66e00aeb1f7bdf2987f253986c0a7614
[ "BSD-3-Clause" ]
null
null
null
sky/engine/bindings/core/v8/custom/V8InjectedScriptManager.cpp
viettrungluu-cr/mojo
950de5bc66e00aeb1f7bdf2987f253986c0a7614
[ "BSD-3-Clause" ]
5
2016-12-23T04:21:10.000Z
2020-06-18T13:52:33.000Z
/* * Copyright (C) 2012 Google 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: * * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sky/engine/config.h" #include "sky/engine/core/inspector/InjectedScriptManager.h" #include "bindings/core/v8/V8InjectedScriptHost.h" #include "bindings/core/v8/V8Window.h" #include "sky/engine/bindings/core/v8/BindingSecurity.h" #include "sky/engine/bindings/core/v8/ScopedPersistent.h" #include "sky/engine/bindings/core/v8/ScriptDebugServer.h" #include "sky/engine/bindings/core/v8/ScriptValue.h" #include "sky/engine/bindings/core/v8/V8Binding.h" #include "sky/engine/bindings/core/v8/V8ObjectConstructor.h" #include "sky/engine/bindings/core/v8/V8ScriptRunner.h" #include "sky/engine/core/frame/LocalDOMWindow.h" #include "sky/engine/core/inspector/InjectedScriptHost.h" #include "sky/engine/wtf/RefPtr.h" namespace blink { InjectedScriptManager::CallbackData* InjectedScriptManager::createCallbackData(InjectedScriptManager* injectedScriptManager) { OwnPtr<InjectedScriptManager::CallbackData> callbackData = adoptPtr(new InjectedScriptManager::CallbackData()); InjectedScriptManager::CallbackData* callbackDataPtr = callbackData.get(); callbackData->injectedScriptManager = injectedScriptManager; m_callbackDataSet.add(callbackData.release()); return callbackDataPtr; } void InjectedScriptManager::removeCallbackData(InjectedScriptManager::CallbackData* callbackData) { ASSERT(m_callbackDataSet.contains(callbackData)); m_callbackDataSet.remove(callbackData); } static v8::Local<v8::Object> createInjectedScriptHostV8Wrapper(PassRefPtr<InjectedScriptHost> host, InjectedScriptManager* injectedScriptManager, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(host); v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toScriptWrappableBase(host.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; // Create a weak reference to the v8 wrapper of InspectorBackend to deref // InspectorBackend when the wrapper is garbage collected. InjectedScriptManager::CallbackData* callbackData = injectedScriptManager->createCallbackData(injectedScriptManager); callbackData->host = host.get(); callbackData->handle.set(isolate, wrapper); callbackData->handle.setWeak(callbackData, &InjectedScriptManager::setWeakCallback); V8DOMWrapper::setNativeInfo(wrapper, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toScriptWrappableBase(host.get())); ASSERT(V8DOMWrapper::isDOMWrapper(wrapper)); return wrapper; } ScriptValue InjectedScriptManager::createInjectedScript(const String& scriptSource, ScriptState* inspectedScriptState, int id) { v8::Isolate* isolate = inspectedScriptState->isolate(); ScriptState::Scope scope(inspectedScriptState); // Call custom code to create InjectedScripHost wrapper specific for the context // instead of calling toV8() that would create the // wrapper in the current context. // FIXME: make it possible to use generic bindings factory for InjectedScriptHost. v8::Local<v8::Object> scriptHostWrapper = createInjectedScriptHostV8Wrapper(m_injectedScriptHost, this, inspectedScriptState->context()->Global(), inspectedScriptState->isolate()); if (scriptHostWrapper.IsEmpty()) return ScriptValue(); // Inject javascript into the context. The compiled script is supposed to evaluate into // a single anonymous function(it's anonymous to avoid cluttering the global object with // inspector's stuff) the function is called a few lines below with InjectedScriptHost wrapper, // injected script id and explicit reference to the inspected global object. The function is expected // to create and configure InjectedScript instance that is going to be used by the inspector. v8::Local<v8::Value> value = V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, scriptSource), isolate); ASSERT(!value.IsEmpty()); ASSERT(value->IsFunction()); v8::Local<v8::Object> windowGlobal = inspectedScriptState->context()->Global(); v8::Handle<v8::Value> info[] = { scriptHostWrapper, windowGlobal, v8::Number::New(inspectedScriptState->isolate(), id) }; v8::Local<v8::Value> injectedScriptValue = V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(value), windowGlobal, WTF_ARRAY_LENGTH(info), info, inspectedScriptState->isolate()); return ScriptValue(inspectedScriptState, injectedScriptValue); } void InjectedScriptManager::setWeakCallback(const v8::WeakCallbackData<v8::Object, InjectedScriptManager::CallbackData>& data) { InjectedScriptManager::CallbackData* callbackData = data.GetParameter(); callbackData->injectedScriptManager->removeCallbackData(callbackData); } } // namespace blink
53.134454
207
0.779061
viettrungluu-cr
36b48f5cf7e7cd1fc16c9ab380c51c84f0857e67
2,693
cpp
C++
services/diffpatch/diffpatch.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
null
null
null
services/diffpatch/diffpatch.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
null
null
null
services/diffpatch/diffpatch.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
1
2021-09-13T12:07:24.000Z
2021-09-13T12:07:24.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "diffpatch.h" #include <cstdlib> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <vector> #include "openssl/sha.h" namespace updatepatch { int32_t WriteDataToFile(const std::string &fileName, const std::vector<uint8_t> &data, size_t dataSize) { std::ofstream patchFile(fileName, std::ios::out | std::ios::binary); PATCH_CHECK(patchFile, return -1, "Failed to open %s", fileName.c_str()); patchFile.write(reinterpret_cast<const char*>(data.data()), dataSize); patchFile.close(); return PATCH_SUCCESS; } int32_t PatchMapFile(const std::string &fileName, MemMapInfo &info) { int32_t file = open(fileName.c_str(), O_RDONLY); PATCH_CHECK(file >= 0, return -1, "Failed to open file %s", fileName.c_str()); struct stat st {}; int32_t ret = fstat(file, &st); PATCH_CHECK(ret >= 0, close(file); return ret, "Failed to fstat"); info.memory = static_cast<uint8_t*>(mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, file, 0)); PATCH_CHECK(info.memory != nullptr, close(file); return -1, "Failed to memory map"); info.length = st.st_size; close(file); return PATCH_SUCCESS; } std::string GeneraterBufferHash(const BlockBuffer &buffer) { SHA256_CTX sha256Ctx; SHA256_Init(&sha256Ctx); SHA256_Update(&sha256Ctx, buffer.buffer, buffer.length); std::vector<uint8_t> digest(SHA256_DIGEST_LENGTH); SHA256_Final(digest.data(), &sha256Ctx); return ConvertSha256Hex({ digest.data(), SHA256_DIGEST_LENGTH }); } std::string ConvertSha256Hex(const BlockBuffer &buffer) { const std::string hexChars = "0123456789abcdef"; std::string haxSha256 = ""; unsigned int c; for (size_t i = 0; i < buffer.length; ++i) { auto d = buffer.buffer[i]; c = (d >> SHIFT_RIGHT_FOUR_BITS) & 0xf; // last 4 bits haxSha256.push_back(hexChars[c]); haxSha256.push_back(hexChars[d & 0xf]); } return haxSha256; } } // namespace updatepatch
35.906667
104
0.67137
openharmony-gitee-mirror
36b7c352f9c44a8b4fb1fd8d260eddc313d4a4e7
22,899
cpp
C++
perception/object_segmentation/src/object_segmentation.cpp
probabilistic-anchoring/probanch
cfba24fd431ed7e7109b715018e344d7989f565d
[ "Apache-2.0" ]
1
2020-02-27T14:00:27.000Z
2020-02-27T14:00:27.000Z
perception/object_segmentation/src/object_segmentation.cpp
probabilistic-anchoring/probanch
cfba24fd431ed7e7109b715018e344d7989f565d
[ "Apache-2.0" ]
null
null
null
perception/object_segmentation/src/object_segmentation.cpp
probabilistic-anchoring/probanch
cfba24fd431ed7e7109b715018e344d7989f565d
[ "Apache-2.0" ]
null
null
null
#include <opencv2/highgui/highgui.hpp> #include <algorithm> #include <ros/ros.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/transforms.h> #include <pcl/io/pcd_io.h> #include <opencv2/opencv.hpp> #include <cv_bridge/cv_bridge.h> #include <image_geometry/pinhole_camera_model.h> #include <sensor_msgs/image_encodings.h> #include <geometry_msgs/TransformStamped.h> #include <tf2/convert.h> #include <tf2/transform_datatypes.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_eigen/tf2_eigen.h> #include <std_msgs/String.h> #include <anchor_msgs/ObjectArray.h> #include <anchor_msgs/ClusterArray.h> #include <anchor_msgs/MovementArray.h> #include <hand_tracking/TrackingService.h> #include <object_segmentation/object_segmentation.hpp> #include <pcl_ros/point_cloud.h> // ------------------------ // Public functions // ------------------------- ObjectSegmentation::ObjectSegmentation(ros::NodeHandle nh, bool useApprox) : nh_(nh) , it_(nh) , priv_nh_("~") , tf2_listener_(buffer_) , useApprox_(useApprox) , queueSize_(5) , display_image_(false) { // Subscribers / publishers //image_transport::TransportHints hints(useCompressed ? "compressed" : "raw"); //image_sub_ = new image_transport::SubscriberFilter( it_, topicColor, "image", hints); image_sub_ = new image_transport::SubscriberFilter( it_, "image", queueSize_); camera_info_sub_ = new message_filters::Subscriber<sensor_msgs::CameraInfo>( nh_, "camera_info", queueSize_); cloud_sub_ = new message_filters::Subscriber<sensor_msgs::PointCloud2>( nh_, "cloud", queueSize_); obj_pub_ = nh_.advertise<anchor_msgs::ObjectArray>("/objects/raw", queueSize_); cluster_pub_ = nh_.advertise<anchor_msgs::ClusterArray>("/objects/clusters", queueSize_); move_pub_ = nh_.advertise<anchor_msgs::MovementArray>("/movements", queueSize_); // Hand tracking _tracking_client = nh_.serviceClient<hand_tracking::TrackingService>("/hand_tracking"); // Used for the web interface display_trigger_sub_ = nh_.subscribe("/display/trigger", 1, &ObjectSegmentation::triggerCb, this); display_image_pub_ = it_.advertise("/display/image", 1); // Set up sync policies if(useApprox) { syncApproximate_ = new message_filters::Synchronizer<ApproximateSyncPolicy>(ApproximateSyncPolicy(queueSize_), *image_sub_, *camera_info_sub_, *cloud_sub_); syncApproximate_->registerCallback( boost::bind( &ObjectSegmentation::segmentationCb, this, _1, _2, _3)); } else { syncExact_ = new message_filters::Synchronizer<ExactSyncPolicy>(ExactSyncPolicy(queueSize_), *image_sub_, *camera_info_sub_, *cloud_sub_); syncExact_->registerCallback( boost::bind( &ObjectSegmentation::segmentationCb, this, _1, _2, _3)); } // Read the base frame priv_nh_.param( "base_frame", base_frame_, std::string("base_link")); // Read segmentation parameters int type, size; double th, factor; if( priv_nh_.getParam("compare_type", type) ) { if( type >= 0 && type <= 3 ) { this->seg_.setComparatorType(type); } else { ROS_WARN("[ObjectSegmentation::ObjectSegmentation] Not a valid comparator type, using default instead."); } } if( priv_nh_.getParam("plane_min_size", size) ) { this->seg_.setPlaneMinSize (size); } if( priv_nh_.getParam("cluster_min_size", size) ) { this->seg_.setClusterMinSize (size); } if( priv_nh_.getParam("cluster_min_size", size) ) { this->seg_.setClusterMinSize (size); } if( priv_nh_.getParam("angular_th", th) ) { this->seg_.setAngularTh (th); } if( priv_nh_.getParam("distance_th", th) ) { this->seg_.setDistanceTh (th); } if( priv_nh_.getParam("refine_factor", factor) ) { this->seg_.setRefineFactor (factor); } // Read spatial thresholds (default values = no filtering) this->priv_nh_.param<double>( "min_x", this->min_x_, 0.0); this->priv_nh_.param<double>( "max_x", this->max_x_, -1.0); this->priv_nh_.param<double>( "min_y", this->min_y_, 0.0); this->priv_nh_.param<double>( "max_y", this->max_y_, -1.0); this->priv_nh_.param<double>( "min_z", this->min_z_, 0.0); this->priv_nh_.param<double>( "max_z", this->max_z_, -1.0); // Read toggle paramter for displayig the result (OpenCV window view) this->priv_nh_.param<bool>( "display_window", display_window_, false); } ObjectSegmentation::~ObjectSegmentation() { if(useApprox_) { delete syncApproximate_; } else { delete syncExact_; } delete image_sub_; delete camera_info_sub_; delete cloud_sub_; //delete tf_listener_; } void ObjectSegmentation::spin() { ros::Rate rate(100); while(ros::ok()) { // OpenCV window for display if( this->display_window_ ) { if( !this->result_img_.empty() ) { cv::imshow( "Segmented clusters...", this->result_img_ ); } // Wait for a keystroke in the window char key = cv::waitKey(1); if( key == 27 || key == 'Q' || key == 'q' ) { break; } } ros::spinOnce(); rate.sleep(); } } void ObjectSegmentation::triggerCb( const std_msgs::String::ConstPtr &msg) { this->display_image_ = (msg->data == "segmentation") ? true : false; ROS_WARN("Got trigger: %s", msg->data.c_str()); } // -------------------------- // Callback function (ROS) // -------------------------- void ObjectSegmentation::segmentationCb( const sensor_msgs::Image::ConstPtr image_msg, const sensor_msgs::CameraInfo::ConstPtr camera_info_msg, const sensor_msgs::PointCloud2::ConstPtr cloud_msg) { // Get the transformation (as geoemtry message) geometry_msgs::TransformStamped tf_forward, tf_inverse; try{ tf_forward = this->buffer_.lookupTransform( base_frame_, cloud_msg->header.frame_id, cloud_msg->header.stamp); tf_inverse = this->buffer_.lookupTransform( cloud_msg->header.frame_id, base_frame_, cloud_msg->header.stamp); } catch (tf2::TransformException &ex) { ROS_WARN("[ObjectSegmentation::callback] %s" , ex.what()); return; } // Get the transformation (as tf/tf2) //tf2::Stamped<tf2::Transform> transform2; //tf2::fromMsg(tf_forward, transform2); //tf::Vector3d tf::Transform transform = tf::Transform(transform2.getOrigin(), transform2.getRotation()); //tf::Transform transfrom = tf::Transform(tf_forward.transfrom); // Read the cloud pcl::PointCloud<segmentation::Point>::Ptr raw_cloud_ptr (new pcl::PointCloud<segmentation::Point>); pcl::fromROSMsg (*cloud_msg, *raw_cloud_ptr); // Transform the cloud to the world frame pcl::PointCloud<segmentation::Point>::Ptr transformed_cloud_ptr (new pcl::PointCloud<segmentation::Point>); //pcl_ros::transformPointCloud( *raw_cloud_ptr, *transformed_cloud_ptr, transform); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_forward.transform).matrix(), *raw_cloud_ptr, *transformed_cloud_ptr); // Filter the transformed point cloud this->filter (transformed_cloud_ptr); // ---------------------- pcl::PointCloud<segmentation::Point>::Ptr original_cloud_ptr (new pcl::PointCloud<segmentation::Point>); //pcl_ros::transformPointCloud( *transformed_cloud_ptr, *original_cloud_ptr, transform.inverse()); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_inverse.transform).matrix(), *raw_cloud_ptr, *transformed_cloud_ptr); // Read the RGB image cv::Mat img; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy( image_msg, image_msg->encoding); cv_ptr->image.copyTo(img); } catch (cv_bridge::Exception& ex){ ROS_ERROR("[ObjectSegmentation::callback]: Failed to convert image."); return; } // Saftey check if( img.empty() ) { return; } // TEST // -------------------------------------- // Downsample the orignal point cloud int scale = 2; pcl::PointCloud<segmentation::Point>::Ptr downsampled_cloud_ptr( new pcl::PointCloud<segmentation::Point> ); downsampled_cloud_ptr->width = original_cloud_ptr->width / scale; downsampled_cloud_ptr->height = original_cloud_ptr->height / scale; downsampled_cloud_ptr->resize( downsampled_cloud_ptr->width * downsampled_cloud_ptr->height ); for( uint i = 0, k = 0; i < original_cloud_ptr->width; i += scale, k++ ) { for( uint j = 0, l = 0; j < original_cloud_ptr->height; j += scale, l++ ) { downsampled_cloud_ptr->at(k,l) = original_cloud_ptr->at(i,j); } } // ----------- // Convert to grayscale and back (for display purposes) if( display_image_ || display_window_) { cv::cvtColor( img, this->result_img_, CV_BGR2GRAY); cv::cvtColor( this->result_img_, this->result_img_, CV_GRAY2BGR); this->result_img_.convertTo( this->result_img_, -1, 1.0, 50); } // Camera information image_geometry::PinholeCameraModel cam_model; cam_model.fromCameraInfo(camera_info_msg); // Make a remote call to get the 'hand' (or glove) //double t = this->timerStart(); std::map< int, pcl::PointIndices > hand_indices; std::vector< std::vector<cv::Point> > hand_contours; hand_tracking::TrackingService srv; srv.request.image = *image_msg; if( this->_tracking_client.call(srv)) { // Get the hand mask contour for( int i = 0; i < srv.response.contours.size(); i++) { std::vector<cv::Point> contour; for( uint j = 0; j < srv.response.contours[i].contour.size(); j++) { cv::Point p( srv.response.contours[i].contour[j].x, srv.response.contours[i].contour[j].y ); contour.push_back(p); } hand_contours.push_back(contour); } // Filter the indices of all 3D points within the hand contour int key = 0; for ( int i = 0; i < hand_contours.size(); i++) { cv::Mat mask( img.size(), CV_8U, cv::Scalar(0)); cv::drawContours( mask, hand_contours, i, cv::Scalar(255), -1); uint idx = 0; pcl::PointIndices point_idx; BOOST_FOREACH ( const segmentation::Point pt, downsampled_cloud_ptr->points ) { tf2::Vector3 trans_pt( pt.x, pt.y, pt.z); //tf2::doTransform( trans_pt, trans_pt, tf_forward); trans_pt = transform * trans_pt; if( ( trans_pt.x() > this->min_x_ && trans_pt.x() < this->max_x_ ) && ( trans_pt.y() > this->min_y_ && trans_pt.y() < this->max_y_ ) && ( trans_pt.z() > this->min_z_ && trans_pt.z() < this->max_z_ ) ) { cv::Point3d pt_3d( pt.x, pt.y, pt.z); cv::Point pt_2d = cam_model.project3dToPixel(pt_3d); if ( pt_2d.y >= 0 && pt_2d.y < mask.rows && pt_2d.x >= 0 && pt_2d.x < mask.cols ) { if( mask.at<uchar>( pt_2d.y, pt_2d.x) != 0 ) { point_idx.indices.push_back(idx); } } } idx++; } //ROS_WARN("[TEST] Points: %d", (int)point_idx.indices.size()); if( point_idx.indices.size() >= this->seg_.getClusterMinSize() ) hand_indices.insert( std::pair< int, pcl::PointIndices>( key, point_idx) ); key++; } } //this->timerEnd( t, "Hand detection"); // Cluster cloud into objects // ---------------------------------------- std::vector<pcl::PointIndices> cluster_indices; //this->seg_.clusterOrganized(transformed_cloud_ptr, cluster_indices); //this->seg_.clusterOrganized(raw_cloud_ptr, cluster_indices); // TEST - Use downsampled cloud instead // ----------------------------------------- //t = this->timerStart(); this->seg_.clusterOrganized( downsampled_cloud_ptr, cluster_indices); //this->timerEnd( t, "Clustering"); // Post-process the segmented clusters (filter out the 'hand' points) //t = this->timerStart(); if( !hand_indices.empty() ) { for( uint i = 0; i < hand_indices.size(); i++ ) { for ( uint j = 0; j < cluster_indices.size (); j++) { for( auto &idx : hand_indices[i].indices) { auto ite = std::find (cluster_indices[j].indices.begin(), cluster_indices[j].indices.end(), idx); if( ite != cluster_indices[j].indices.end() ) { cluster_indices[j].indices.erase(ite); } } if( cluster_indices[j].indices.size() < this->seg_.getClusterMinSize() ) cluster_indices.erase( cluster_indices.begin() + j ); } } // Add the 'hand' indecies to the reaming cluster indices for( auto &ite : hand_indices ) { cluster_indices.insert( cluster_indices.begin() + ite.first, ite.second ); } //ROS_INFO("Clusters: %d (include a 'hand' cluster)", (int)cluster_indices.size()); } else { //ROS_INFO("Clusters: %d", (int)cluster_indices.size()); } //this->timerEnd( t, "Post-processing"); /* ROS_INFO("Clusters: \n"); for (size_t i = 0; i < cluster_indices.size (); i++) { if( hand_indices.find(i) != hand_indices.end() ) ROS_INFO("Hand size: %d", (int)cluster_indices[i].indices.size()); else ROS_INFO("Object size: %d", (int)cluster_indices[i].indices.size()); } ROS_INFO("-----------"); */ // Process all segmented clusters (including the 'hand' cluster) if( !cluster_indices.empty() ) { // Image & Cloud output anchor_msgs::ClusterArray clusters; anchor_msgs::ObjectArray objects; anchor_msgs::MovementArray movements; objects.header = cloud_msg->header; objects.image = *image_msg; objects.info = *camera_info_msg; objects.transform = tf_forward; /* // Store the inverse transformation tf::Quaternion tf_quat = transform.inverse().getRotation(); objects.transform.rotation.x = tf_quat.x(); objects.transform.rotation.y = tf_quat.y(); objects.transform.rotation.z = tf_quat.z(); objects.transform.rotation.w = tf_quat.w(); tf::Vector3 tf_vec = transform.inverse().getOrigin(); objects.transform.translation.x = tf_vec.getX(); objects.transform.translation.y = tf_vec.getY(); objects.transform.translation.z = tf_vec.getZ(); */ // Process the segmented clusters int sz = 5; cv::Mat kernel = cv::getStructuringElement( cv::BORDER_CONSTANT, cv::Size( sz, sz), cv::Point(-1,-1) ); for (size_t i = 0; i < cluster_indices.size (); i++) { // Get the cluster pcl::PointCloud<segmentation::Point>::Ptr cluster_ptr (new pcl::PointCloud<segmentation::Point>); //pcl::copyPointCloud( *original_cloud_ptr, cluster_indices[i], *cluster_ptr); // TEST - Use downsampled cloud instead // ----------------------------------------- pcl::copyPointCloud( *downsampled_cloud_ptr, cluster_indices[i], *cluster_ptr); //std::cout << cluster_ptr->points.size() << std::endl; if( cluster_ptr->points.empty() ) continue; // Post-process the cluster try { // Create the cluster image cv::Mat cluster_img( img.size(), CV_8U, cv::Scalar(0)); BOOST_FOREACH ( const segmentation::Point pt, cluster_ptr->points ) { cv::Point3d pt_cv( pt.x, pt.y, pt.z); cv::Point2f p = cam_model.project3dToPixel(pt_cv); circle( cluster_img, p, 2, cv::Scalar(255), -1, 8, 0 ); } // Apply morphological operations the cluster image cv::dilate( cluster_img, cluster_img, kernel); cv::erode( cluster_img, cluster_img, kernel); // Find the contours of the cluster std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( cluster_img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Get the contour of the convex hull std::vector<cv::Point> contour = getLargetsContour( contours ); // Create and add the object output message if( contour.size() > 0 ) { anchor_msgs::Object obj; for( size_t j = 0; j < contour.size(); j++) { anchor_msgs::Point2d p; p.x = contour[j].x; p.y = contour[j].y; obj.visual.border.contour.push_back(p); } // Add segmented object to display image img.copyTo( this->result_img_, cluster_img); // Draw the contour (for display) cv::Scalar color = cv::Scalar( 32, 84, 233); // Orange //cv::Scalar color = cv::Scalar( 0, 0, 233); // Red //cv::Scalar color = cv::Scalar::all(64); // Dark gray // Check if we have a hand countour if( hand_indices.find(i) != hand_indices.end() ) { color = cv::Scalar( 0, 233, 0); // Green } cv::drawContours( this->result_img_, contours, -1, color, 1); // Transfrom the the cloud once again //tf2::doTransform( *cluster_ptr, *cluster_ptr, tf_forward); //pcl_ros::transformPointCloud( *cluster_ptr, *cluster_ptr, transform); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_forward.transform).matrix(), *cluster_ptr, *cluster_ptr); // 1. Extract the position geometry_msgs::PoseStamped pose; pose.header.stamp = cloud_msg->header.stamp; segmentation::getOrientedPosition( cluster_ptr, pose.pose); obj.position.data = pose; // Add the position to the movement array movements.movements.push_back(pose); //std::cout << "Position: [" << obj.position.data.pose.position.x << ", " << obj.position.data.pose.position.y << ", " << obj.position.data.pose.position.z << "]" << std::endl; // 2. Extract the shape segmentation::getSize( cluster_ptr, obj.size.data ); // Ground size symbols std::vector<double> data = { obj.size.data.x, obj.size.data.y, obj.size.data.z}; std::sort( data.begin(), data.end(), std::greater<double>()); if( data.front() <= 0.1 ) { // 0 - 15 [cm] = small obj.size.symbols.push_back("small"); } else if( data.front() <= 0.20 ) { // 16 - 30 [cm] = medium obj.size.symbols.push_back("medium"); } else { // > 30 [cm] = large obj.size.symbols.push_back("large"); } if( data[0] < data[1] * 1.1 ) { obj.size.symbols.push_back("square"); } else { obj.size.symbols.push_back("rectangle"); if( data[0] > data[1] * 1.5 ) { obj.size.symbols.push_back("long"); } else { obj.size.symbols.push_back("short"); } } // TEST // --------------------------------------- // Attempt to filter out glitchs if ( obj.size.data.z < 0.02 ) continue; // Add the object to the object array message objects.objects.push_back(obj); /* Eigen::Vector4f centroid; pcl::compute3DCentroid ( transformed_cloud, centroid); if( centroid[0] > 0.0 && centroid[1] < 0.5 && centroid[1] > -0.5 ) std::cout << "Position [" << centroid[0] << ", " << centroid[1] << ", " << centroid[2] << "]" << std::endl; */ // Add the (un-transformed) cluster to the array message geometry_msgs::Pose center; segmentation::getPosition( cluster_ptr, center ); clusters.centers.push_back(center); sensor_msgs::PointCloud2 cluster; pcl::toROSMsg( *cluster_ptr, cluster ); clusters.clusters.push_back(cluster); } } catch( cv::Exception &exc ) { ROS_ERROR("[object_recognition] CV processing error: %s", exc.what() ); } } //std::cout << "---" << std::endl; // Publish the "segmented" image if( display_image_ ) { cv_ptr->image = this->result_img_; cv_ptr->encoding = "bgr8"; display_image_pub_.publish(cv_ptr->toImageMsg()); } // Publish the object array if( !objects.objects.empty() || !clusters.clusters.empty() ) { // ROS_INFO("Publishing: %d objects.", (int)objects.objects.size()); obj_pub_.publish(objects); cluster_pub_.publish(clusters); move_pub_.publish(movements); } } } void ObjectSegmentation::filter( pcl::PointCloud<segmentation::Point>::Ptr &cloud_ptr ) { // Filter the transformed point cloud if( cloud_ptr->isOrganized ()) { segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "x", this->min_x_, this->max_x_); segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "y", this->min_y_, this->max_y_); segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "z", this->min_z_, this->max_z_); /* for( auto &p: cloud_ptr->points) { if( !( p.x > this->min_x_ && p.x < this->max_x_ ) || !( p.y > this->min_y_ && p.y < this->max_y_ ) || !( p.z > this->min_z_ && p.z < this->max_z_ ) ) { p.x = std::numeric_limits<double>::quiet_NaN(); //infinity(); p.y = std::numeric_limits<double>::quiet_NaN(); p.z = std::numeric_limits<double>::quiet_NaN(); p.b = p.g = p.r = 0; } } */ } else { pcl::PointCloud<segmentation::Point>::Ptr result_ptr (new pcl::PointCloud<segmentation::Point>); for( auto &p: cloud_ptr->points) { if( ( p.x > this->min_x_ && p.x < this->max_x_ ) && ( p.y > this->min_y_ && p.y < this->max_y_ ) && ( p.z > this->min_z_ && p.z < this->max_z_ ) ) { result_ptr->points.push_back (p); } } cloud_ptr.swap (result_ptr); } } std::vector<cv::Point> ObjectSegmentation::getLargetsContour( std::vector<std::vector<cv::Point> > contours ) { std::vector<cv::Point> result = contours.front(); for ( size_t i = 1; i< contours.size(); i++) if( contours[i].size() > result.size() ) result = contours[i]; return result; } std::vector<cv::Point> ObjectSegmentation::contoursConvexHull( std::vector<std::vector<cv::Point> > contours ) { std::vector<cv::Point> result; std::vector<cv::Point> pts; for ( size_t i = 0; i< contours.size(); i++) for ( size_t j = 0; j< contours[i].size(); j++) pts.push_back(contours[i][j]); cv::convexHull( pts, result ); return result; } // Detect a 'hand'/'glove' object based on color segmentation std::vector<cv::Point> ObjectSegmentation::handDetection( cv::Mat &img ) { cv::Mat hsv_img; int sz = 5; // Convert to HSV color space cv::cvtColor( img, hsv_img, cv::COLOR_BGR2HSV); // Pre-process the image by blur cv::blur( hsv_img, hsv_img, cv::Size( sz, sz)); // Extrace binary mask cv::Mat mask; cv::inRange( hsv_img, cv::Scalar( 31, 68, 141), cv::Scalar( 47, 255, 255), mask); // Post-process the threshold image cv::Mat kernel = cv::getStructuringElement( cv::BORDER_CONSTANT, cv::Size( sz, sz), cv::Point(-1,-1) ); cv::dilate( mask, mask, kernel); cv::erode( mask, mask, kernel); // Find the contours std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( mask, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Filter the contoruse based on size std::vector<std::vector<cv::Point> > result; for ( int i = 0; i < contours.size(); i++) { if ( cv::contourArea(contours[i]) > 500 ) { result.push_back(contours[i]); } } return result[0]; } // Timer functions double ObjectSegmentation::timerStart() { return (double)cv::getTickCount(); } void ObjectSegmentation::timerEnd( double t, std::string msg) { t = ((double)cv::getTickCount() - t) / (double)cv::getTickFrequency(); ROS_INFO("[Timer] %s: %.4f (s)", msg.c_str(), t); } // ---------------------- // Main function // ------------------ int main(int argc, char **argv) { ros::init(argc, argv, "object_segmentation_node"); ros::NodeHandle nh; // Saftey check if(!ros::ok()) { return 0; } ObjectSegmentation node(nh); node.spin(); ros::shutdown(); return 0; }
34.907012
181
0.649373
probabilistic-anchoring
36b81c19aeda7c00fbd9db5ed053f3783b4ca23b
26,872
cpp
C++
src/components/SuperContainer.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
src/components/SuperContainer.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
src/components/SuperContainer.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
// ------------------------------------ // #include "SuperContainer.h" #include "Common.h" #include "DualView.h" using namespace DV; // ------------------------------------ // //#define SUPERCONTAINER_RESIZE_REFLOW_CHECK_ONLY_FIRST_ROW SuperContainer::SuperContainer() : Gtk::ScrolledWindow(), View(get_hadjustment(), get_vadjustment()) { _CommonCtor(); } SuperContainer::SuperContainer( _GtkScrolledWindow* widget, Glib::RefPtr<Gtk::Builder> builder) : Gtk::ScrolledWindow(widget), View(get_hadjustment(), get_vadjustment()) { _CommonCtor(); } void SuperContainer::_CommonCtor() { add(View); View.add(Container); View.show(); Container.show(); PositionIndicator.property_width_request() = 2; PositionIndicator.set_orientation(Gtk::ORIENTATION_VERTICAL); PositionIndicator.get_style_context()->add_class("PositionIndicator"); signal_size_allocate().connect(sigc::mem_fun(*this, &SuperContainer::_OnResize)); signal_button_press_event().connect( sigc::mem_fun(*this, &SuperContainer::_OnMouseButtonPressed)); // Both scrollbars need to be able to appear, otherwise the width cannot be reduced // so that wrapping occurs set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); } SuperContainer::~SuperContainer() { Clear(); } // ------------------------------------ // void SuperContainer::Clear(bool deselect /*= false*/) { DualView::IsOnMainThreadAssert(); // This could be made more efficient if(deselect) DeselectAllItems(); // This will delete all the widgets // Positions.clear(); _PositionIndicator(); LayoutDirty = false; } // ------------------------------------ // void SuperContainer::UpdatePositioning() { if(!LayoutDirty) return; LayoutDirty = false; WidestRow = Margin; if(Positions.empty()) { _PositionIndicator(); return; } int32_t CurrentRow = Margin; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(WidestRow < CurrentRow) WidestRow = CurrentRow; CurrentRow = position.X; CurrentY = position.Y; } CurrentRow += position.Width + Padding; _ApplyWidgetPosition(position); } // Last row needs to be included, too // if(WidestRow < CurrentRow) WidestRow = CurrentRow; // Add margin WidestRow += Margin; _PositionIndicator(); } void SuperContainer::UpdateRowWidths() { WidestRow = Margin; int32_t CurrentRow = Margin; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(WidestRow < CurrentRow) WidestRow = CurrentRow; CurrentRow = position.X; CurrentY = position.Y; } CurrentRow += position.Width + Padding; } // Last row needs to be included, too // if(WidestRow < CurrentRow) WidestRow = CurrentRow; // Add margin WidestRow += Margin; } // ------------------------------------ // size_t SuperContainer::CountRows() const { size_t count = 0; int32_t CurrentY = -1; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.Y != CurrentY) { ++count; CurrentY = position.Y; } } return count; } size_t SuperContainer::CountItems() const { size_t count = 0; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; ++count; } return count; } // ------------------------------------ // size_t SuperContainer::CountSelectedItems() const { size_t count = 0; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget->IsSelected()) ++count; } return count; } void SuperContainer::DeselectAllItems() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Deselect(); } } void SuperContainer::SelectAllItems() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Select(); } } void SuperContainer::DeselectAllExcept(const ListItem* item) { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget.get() == item) continue; position.WidgetToPosition->Widget->Deselect(); } } void SuperContainer::DeselectFirstItem() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget->IsSelected()) { position.WidgetToPosition->Widget->Deselect(); return; } } } void SuperContainer::SelectFirstItems(int count) { int selected = 0; for(auto& position : Positions) { // If enough are selected stop if(selected >= count) break; // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Select(); ++selected; } } void SuperContainer::SelectNextItem() { bool select = false; for(auto iter = Positions.begin(); iter != Positions.end(); ++iter) { auto& position = *iter; // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(select == true) { position.WidgetToPosition->Widget->Select(); DeselectAllExcept(position.WidgetToPosition->Widget.get()); break; } if(position.WidgetToPosition->Widget->IsSelected()) { select = true; } } if(!select) { // None selected // SelectFirstItem(); } } void SuperContainer::SelectPreviousItem() { bool select = false; for(auto iter = Positions.rbegin(); iter != Positions.rend(); ++iter) { auto& position = *iter; // When reversing we can't stop when the tailing empty slots are reached if(!position.WidgetToPosition) continue; if(select == true) { position.WidgetToPosition->Widget->Select(); DeselectAllExcept(position.WidgetToPosition->Widget.get()); break; } if(position.WidgetToPosition->Widget->IsSelected()) { select = true; } } if(!select) { // None selected // SelectFirstItem(); } } void SuperContainer::ShiftSelectTo(const ListItem* item) { // Find first non-matching item to start from size_t selectStart = 0; // And also where item is size_t itemsPosition = 0; for(size_t i = 0; i < Positions.size(); ++i) { auto& position = Positions[i]; if(!position.WidgetToPosition) continue; if(position.WidgetToPosition->Widget.get() == item) { itemsPosition = i; } else if(selectStart == 0 && position.WidgetToPosition->Widget->IsSelected()) { selectStart = i; } } // Swap so that the order is always the lower to higher if(selectStart > itemsPosition) std::swap(selectStart, itemsPosition); // TODO: pre-select callback // Perform actual selections for(size_t i = selectStart; i <= itemsPosition; ++i) { auto& position = Positions[i]; if(!position.WidgetToPosition) continue; position.WidgetToPosition->Widget->Select(); } // TODO: post-select callback } // ------------------------------------ // bool SuperContainer::IsEmpty() const { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; // Found non-empty return false; } return true; } // ------------------------------------ // std::shared_ptr<ResourceWithPreview> SuperContainer::GetFirstVisibleResource( double scrollOffset) const { for(const auto& position : Positions) { if(((position.Y + 5) > scrollOffset) && position.WidgetToPosition) { return position.WidgetToPosition->CreatedFrom; } } return nullptr; } std::vector<std::shared_ptr<ResourceWithPreview>> SuperContainer::GetResourcesVisibleAfter( double scrollOffset) const { std::vector<std::shared_ptr<ResourceWithPreview>> result; result.reserve(Positions.size() / 3); for(const auto& position : Positions) { if(((position.Y + 5) > scrollOffset) && position.WidgetToPosition) { result.push_back(position.WidgetToPosition->CreatedFrom); } } return result; } double SuperContainer::GetResourceOffset(std::shared_ptr<ResourceWithPreview> resource) const { for(const auto& position : Positions) { if(position.WidgetToPosition && position.WidgetToPosition->CreatedFrom == resource) { return position.Y; } } return -1; } // ------------------------------------ // void SuperContainer::UpdateMarginAndPadding(int newmargin, int newpadding) { Margin = newmargin; Padding = newpadding; LayoutDirty = true; Reflow(0); UpdatePositioning(); } // ------------------------------------ // void SuperContainer::Reflow(size_t index) { if(Positions.empty() || index >= Positions.size()) return; LayoutDirty = true; // The first one doesn't have a previous position // if(index == 0) { LastWidthReflow = get_width(); _PositionGridPosition(Positions.front(), nullptr, Positions.size()); ++index; } // This is a check for debugging //_CheckPositions(); for(size_t i = index; i < Positions.size(); ++i) { _PositionGridPosition(Positions[i], &Positions[i - 1], i - 1); } } void SuperContainer::_PositionGridPosition( GridPosition& current, const GridPosition* const previous, size_t previousindex) const { // First is at fixed position // if(previous == nullptr) { current.X = Margin; current.Y = Margin; return; } LEVIATHAN_ASSERT(previousindex < Positions.size(), "previousindex is out of range"); // Check does it fit on the line // if(previous->X + previous->Width + Padding + current.Width <= get_width()) { // It fits on the line // current.Y = previous->Y; current.X = previous->X + previous->Width + Padding; return; } // A new line is needed // // Find the tallest element in the last row int32_t lastRowMaxHeight = previous->Height; // Start from the one before previous, doesn't matter if the index wraps around as // the loop won't be entered in that case size_t scanIndex = previousindex - 1; const auto rowY = previous->Y; while(scanIndex < Positions.size()) { if(Positions[scanIndex].Y != rowY) { // Full row scanned // break; } // Check current height // const auto currentHeight = Positions[scanIndex].Height; if(currentHeight > lastRowMaxHeight) lastRowMaxHeight = currentHeight; // Move to previous // --scanIndex; if(scanIndex == 0) break; } // Position according to the maximum height of the last row current.X = Margin; current.Y = previous->Y + lastRowMaxHeight + Padding; } SuperContainer::GridPosition& SuperContainer::_AddNewGridPosition( int32_t width, int32_t height) { GridPosition pos; pos.Width = width; pos.Height = height; if(Positions.empty()) { _PositionGridPosition(pos, nullptr, 0); } else { _PositionGridPosition(pos, &Positions.back(), Positions.size() - 1); } Positions.push_back(pos); return Positions.back(); } // ------------------------------------ // void SuperContainer::_SetWidgetSize(Element& widget) { int width_min, width_natural; int height_min, height_natural; widget.Widget->SetItemSize(SelectedItemSize); Container.add(*widget.Widget); widget.Widget->show(); widget.Widget->get_preferred_width(width_min, width_natural); widget.Widget->get_preferred_height_for_width(width_natural, height_min, height_natural); widget.Width = width_natural; widget.Height = height_natural; widget.Widget->set_size_request(widget.Width, widget.Height); } void SuperContainer::SetItemSize(LIST_ITEM_SIZE newsize) { if(SelectedItemSize == newsize) return; SelectedItemSize = newsize; if(Positions.empty()) return; // Resize all elements // for(const auto& position : Positions) { if(position.WidgetToPosition) { _SetWidgetSize(*position.WidgetToPosition); } } LayoutDirty = true; UpdatePositioning(); } // ------------------------------------ // void SuperContainer::_SetKeepFalse() { for(auto& position : Positions) { if(position.WidgetToPosition) position.WidgetToPosition->Keep = false; } } void SuperContainer::_RemoveElementsNotMarkedKeep() { size_t reflowStart = Positions.size(); for(size_t i = 0; i < Positions.size();) { auto& current = Positions[i]; // If the current position has no widget try to get the next widget, or end // if(!current.WidgetToPosition) { if(i + 1 < Positions.size()) { // Swap with the next one // if(Positions[i].SwapWidgets(Positions[i + 1])) { if(reflowStart > i) reflowStart = i; } } // If still empty there are no more widgets to process // It doesn't seem to be right for some reason to break here if(!current.WidgetToPosition) { ++i; continue; } } if(!Positions[i].WidgetToPosition->Keep) { LayoutDirty = true; // Remove this widget // Container.remove(*current.WidgetToPosition->Widget); current.WidgetToPosition.reset(); // On the next iteration the next widget will be moved to this position } else { ++i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } // ------------------------------------ // void SuperContainer::_RemoveWidget(size_t index) { if(index >= Positions.size()) throw Leviathan::InvalidArgument("index out of range"); LayoutDirty = true; size_t reflowStart = Positions.size(); Container.remove(*Positions[index].WidgetToPosition->Widget); Positions[index].WidgetToPosition.reset(); // Move forward all the widgets // for(size_t i = index; i + 1 < Positions.size(); ++i) { if(Positions[i].SwapWidgets(Positions[i + 1])) { if(reflowStart > i) reflowStart = i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } void SuperContainer::_SetWidget( size_t index, std::shared_ptr<Element> widget, bool selectable, bool autoreplace) { if(index >= Positions.size()) throw Leviathan::InvalidArgument("index out of range"); if(Positions[index].WidgetToPosition) { if(!autoreplace) { throw Leviathan::InvalidState("index is not empty and no autoreplace specified"); } else { // Remove the current one Container.remove(*Positions[index].WidgetToPosition->Widget); } } // Initialize a size for the widget _SetWidgetSize(*widget); _SetWidgetAdvancedSelection(*widget->Widget, selectable); // Set it // if(Positions[index].SetNewWidget(widget)) { // Do a reflow // Reflow(index); } else { // Apply positioning now // if(!LayoutDirty) { _ApplyWidgetPosition(Positions[index]); UpdateRowWidths(); _PositionIndicator(); } } } // ------------------------------------ // void SuperContainer::_PushBackWidgets(size_t index) { if(Positions.empty()) return; LayoutDirty = true; size_t reflowStart = Positions.size(); // Create a new position and then pull back widgets until index is reached and then // stop // We can skip adding if the last is empty // if(Positions.back().WidgetToPosition) _AddNewGridPosition(Positions.back().Width, Positions.back().Height); for(size_t i = Positions.size() - 1; i > index; --i) { // Swap pointers around, the current index is always empty so the empty // spot will propagate to index // Also i - 1 cannot be out of range as the smallest index 0 wouldn't enter // this loop if(Positions[i].SwapWidgets(Positions[i - 1])) { if(reflowStart > i) reflowStart = i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } void SuperContainer::_AddWidgetToEnd(std::shared_ptr<ResourceWithPreview> item, const std::shared_ptr<ItemSelectable>& selectable) { // Create the widget // auto element = std::make_shared<Element>(item, selectable); // Initialize a size for the widget _SetWidgetSize(*element); _SetWidgetAdvancedSelection(*element->Widget, selectable.operator bool()); // Find the first empty spot // for(size_t i = 0; i < Positions.size(); ++i) { if(!Positions[i].WidgetToPosition) { if(Positions[i].SetNewWidget(element)) { // Do a reflow // Reflow(i); } return; } } // No empty spots, create a new one // GridPosition& pos = _AddNewGridPosition(element->Width, element->Height); pos.WidgetToPosition = element; if(!LayoutDirty) { _ApplyWidgetPosition(pos); UpdateRowWidths(); _PositionIndicator(); } } // ------------------------------------ // void SuperContainer::_SetWidgetAdvancedSelection(ListItem& widget, bool selectable) { if(widget.HasAdvancedSelection() == selectable) return; if(selectable) { widget.SetAdvancedSelection([=](ListItem& item) { ShiftSelectTo(&item); }); } else { widget.SetAdvancedSelection(nullptr); } } // ------------------------------------ // void SuperContainer::_CheckPositions() const { // Find duplicate stuff // for(size_t i = 0; i < Positions.size(); ++i) { for(size_t a = 0; a < Positions.size(); ++a) { if(a == i) continue; if(Positions[i].WidgetToPosition.get() == Positions[a].WidgetToPosition.get()) { LEVIATHAN_ASSERT( false, "SuperContainer::_CheckPositions: duplicate Element ptr"); } if(Positions[i].X == Positions[a].X && Positions[i].Y == Positions[a].Y) { LEVIATHAN_ASSERT(false, "SuperContainer::_CheckPositions: duplicate position"); } if(Positions[i].WidgetToPosition->Widget.get() == Positions[a].WidgetToPosition->Widget.get()) { LEVIATHAN_ASSERT( false, "SuperContainer::_CheckPositions: duplicate ListItem ptr"); } } } } // ------------------------------------ // // Position indicator void SuperContainer::EnablePositionIndicator() { if(PositionIndicatorEnabled) return; PositionIndicatorEnabled = true; Container.add(PositionIndicator); // Enable the click to change indicator position add_events(Gdk::BUTTON_PRESS_MASK); _PositionIndicator(); } size_t SuperContainer::GetIndicatorPosition() const { return IndicatorPosition; } void SuperContainer::SetIndicatorPosition(size_t position) { if(IndicatorPosition == position) return; IndicatorPosition = position; _PositionIndicator(); } void SuperContainer::SuperContainer::_PositionIndicator() { if(!PositionIndicatorEnabled) { return; } constexpr auto indicatorHeightSmallerBy = 6; // Detect emptyness, but also the widget size bool found = false; for(const auto& position : Positions) { if(position.WidgetToPosition) { found = true; PositionIndicator.property_height_request() = position.WidgetToPosition->Height - indicatorHeightSmallerBy; break; } } if(!found) { // Empty PositionIndicator.property_visible() = false; return; } PositionIndicator.property_visible() = true; // Optimization for last if(IndicatorPosition >= Positions.size()) { for(size_t i = Positions.size() - 1;; --i) { const auto& position = Positions[i]; if(position.WidgetToPosition) { // Found the end Container.move(PositionIndicator, position.X + position.Width + Padding / 2, position.Y + indicatorHeightSmallerBy / 2); return; } if(i == 0) { break; } } } else { if(IndicatorPosition == 0) { // Optimization for first Container.move( PositionIndicator, Margin / 2, Margin + indicatorHeightSmallerBy / 2); return; } else { // Find a suitable position (or leave hidden) bool after = false; for(size_t i = IndicatorPosition;; --i) { const auto& position = Positions[i]; if(position.WidgetToPosition) { Container.move(PositionIndicator, after ? position.X + Positions[i].Width + Padding / 2 : position.X - Padding / 2, position.Y + indicatorHeightSmallerBy / 2); return; } else { after = true; } if(i == 0) { break; } } } } LOG_ERROR("SuperContainer: failed to find position for indicator"); PositionIndicator.property_visible() = false; } size_t SuperContainer::CalculateIndicatorPositionFromCursor(int cursorx, int cursory) { size_t newPosition = -1; // The cursor position needs to be adjusted by the scroll offset const auto x = get_hadjustment()->get_value() + cursorx; const auto y = get_vadjustment()->get_value() + cursory; for(size_t i = 0; i < Positions.size(); ++i) { const auto& position = Positions[i]; if(!position.WidgetToPosition) break; // If click is not on this row, ignore if(y < position.Y || y > position.Y + position.Height + Padding) continue; // If click is to the left of position this is the target if(position.X + position.Width / 2 > x) { newPosition = i; break; } // If click is to the right of this the next position (if it exists) might be the // target if(x > position.X + position.Width) { newPosition = i + 1; } } return newPosition; } // ------------------------------------ // // Callbacks void SuperContainer::_OnResize(Gtk::Allocation& allocation) { if(Positions.empty()) return; // Skip if width didn't change // if(allocation.get_width() == LastWidthReflow) return; // Even if we don't reflow we don't want to be called again with the same width LastWidthReflow = allocation.get_width(); bool reflow = false; // If doesn't fit dual margins if(allocation.get_width() < WidestRow + Margin) { // Rows don't fit anymore // reflow = true; } else { // Check would wider rows fit // int32_t CurrentRow = 0; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(Margin + CurrentRow + Padding + position.Width < allocation.get_width()) { // The previous row (this is the first position of the first row) could // now fit this widget reflow = true; break; } CurrentRow = 0; CurrentY = position.Y; // Break if only checking first row #ifdef SUPERCONTAINER_RESIZE_REFLOW_CHECK_ONLY_FIRST_ROW break; #endif } CurrentRow += position.Width; } } if(reflow) { Reflow(0); UpdatePositioning(); // Forces update of positions Container.check_resize(); } } bool SuperContainer::_OnMouseButtonPressed(GdkEventButton* event) { if(event->type == GDK_BUTTON_PRESS) { SetIndicatorPosition(CalculateIndicatorPositionFromCursor(event->x, event->y)); return true; } return false; } // ------------------------------------ // // GridPosition bool SuperContainer::GridPosition::SetNewWidget(std::shared_ptr<Element> widget) { const auto newWidth = widget->Width; const auto newHeight = widget->Height; WidgetToPosition = widget; if(newWidth != Width && newHeight != Height) { Width = newWidth; Height = newHeight; return true; } return false; } bool SuperContainer::GridPosition::SwapWidgets(GridPosition& other) { WidgetToPosition.swap(other.WidgetToPosition); if(Width != other.Width || Height != other.Height) { Width = other.Width; Height = other.Height; return true; } return false; } std::string SuperContainer::GridPosition::ToString() const { return "[" + std::to_string(X) + ", " + std::to_string(Y) + " dim: " + std::to_string(Width) + ", " + std::to_string(Height) + " " + (WidgetToPosition ? "(filled)" : "(empty)"); }
24.384755
95
0.578818
hhyyrylainen
36babb2c262f98e60e259cada00e847ab0b90a80
6,585
cpp
C++
src/xr_3da/xrGame/WeaponKnife.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
src/xr_3da/xrGame/WeaponKnife.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
null
null
null
src/xr_3da/xrGame/WeaponKnife.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
#include "stdafx.h" #include "WeaponKnife.h" #include "WeaponHUD.h" #include "Entity.h" #include "Actor.h" #include "level.h" #include "xr_level_controller.h" #include "game_cl_base.h" #include "../skeletonanimated.h" #include "gamemtllib.h" #include "level_bullet_manager.h" #include "ai_sounds.h" #define KNIFE_MATERIAL_NAME "objects\\knife" CWeaponKnife::CWeaponKnife() : CWeapon("KNIFE") { m_attackStart = false; m_bShotLight = false; SetState ( eHidden ); SetNextState ( eHidden ); knife_material_idx = (u16)-1; } CWeaponKnife::~CWeaponKnife() { HUD_SOUND::DestroySound(m_sndShot); } void CWeaponKnife::Load (LPCSTR section) { // verify class inherited::Load (section); fWallmarkSize = pSettings->r_float(section,"wm_size"); // HUD :: Anims R_ASSERT (m_pHUD); animGet (mhud_idle, pSettings->r_string(*hud_sect,"anim_idle")); animGet (mhud_hide, pSettings->r_string(*hud_sect,"anim_hide")); animGet (mhud_show, pSettings->r_string(*hud_sect,"anim_draw")); animGet (mhud_attack, pSettings->r_string(*hud_sect,"anim_shoot1_start")); animGet (mhud_attack2, pSettings->r_string(*hud_sect,"anim_shoot2_start")); animGet (mhud_attack_e, pSettings->r_string(*hud_sect,"anim_shoot1_end")); animGet (mhud_attack2_e,pSettings->r_string(*hud_sect,"anim_shoot2_end")); HUD_SOUND::LoadSound(section,"snd_shoot" , m_sndShot , ESoundTypes(SOUND_TYPE_WEAPON_SHOOTING) ); knife_material_idx = GMLib.GetMaterialIdx(KNIFE_MATERIAL_NAME); } void CWeaponKnife::OnStateSwitch (u32 S) { inherited::OnStateSwitch(S); switch (S) { case eIdle: switch2_Idle (); break; case eShowing: switch2_Showing (); break; case eHiding: switch2_Hiding (); break; case eHidden: switch2_Hidden (); break; case eFire: { //------------------------------------------- m_eHitType = m_eHitType_1; fHitPower = fHitPower_1; fHitImpulse = fHitImpulse_1; //------------------------------------------- switch2_Attacking (S); }break; case eFire2: { //------------------------------------------- m_eHitType = m_eHitType_2; fHitPower = fHitPower_2; fHitImpulse = fHitImpulse_2; //------------------------------------------- switch2_Attacking (S); }break; } } void CWeaponKnife::KnifeStrike(const Fvector& pos, const Fvector& dir) { CCartridge cartridge; cartridge.m_buckShot = 1; cartridge.m_impair = 1; cartridge.m_kDisp = 1; cartridge.m_kHit = 1; cartridge.m_kImpulse = 1; cartridge.m_kPierce = 1; cartridge.m_flags.set (CCartridge::cfTracer, FALSE); cartridge.m_flags.set (CCartridge::cfRicochet, FALSE); cartridge.fWallmarkSize = fWallmarkSize; cartridge.bullet_material_idx = knife_material_idx; while(m_magazine.size() < 2) m_magazine.push_back(cartridge); iAmmoElapsed = m_magazine.size(); bool SendHit = SendHitAllowed(H_Parent()); PlaySound (m_sndShot,pos); Level().BulletManager().AddBullet( pos, dir, m_fStartBulletSpeed, fHitPower, fHitImpulse, H_Parent()->ID(), ID(), m_eHitType, fireDistance, cartridge, SendHit); } void CWeaponKnife::OnAnimationEnd(u32 state) { switch (state) { case eHiding: SwitchState(eHidden); break; case eFire: case eFire2: { if(m_attackStart) { m_attackStart = false; if(GetState()==eFire) m_pHUD->animPlay(random_anim(mhud_attack_e), TRUE, this, GetState()); else m_pHUD->animPlay(random_anim(mhud_attack2_e), TRUE, this, GetState()); Fvector p1, d; p1.set(get_LastFP()); d.set(get_LastFD()); if(H_Parent()) smart_cast<CEntity*>(H_Parent())->g_fireParams(this, p1,d); else break; KnifeStrike(p1,d); } else SwitchState(eIdle); }break; case eShowing: case eIdle: SwitchState(eIdle); break; } } void CWeaponKnife::state_Attacking (float) { } void CWeaponKnife::switch2_Attacking (u32 state) { if(m_bPending) return; if(state==eFire) m_pHUD->animPlay(random_anim(mhud_attack), FALSE, this, state); else //eFire2 m_pHUD->animPlay(random_anim(mhud_attack2), FALSE, this, state); m_attackStart = true; m_bPending = true; } void CWeaponKnife::switch2_Idle () { VERIFY(GetState()==eIdle); m_pHUD->animPlay(random_anim(mhud_idle), TRUE, this, GetState()); m_bPending = false; } void CWeaponKnife::switch2_Hiding () { FireEnd (); VERIFY(GetState()==eHiding); m_pHUD->animPlay (random_anim(mhud_hide), TRUE, this, GetState()); // m_bPending = true; } void CWeaponKnife::switch2_Hidden() { signal_HideComplete (); } void CWeaponKnife::switch2_Showing () { VERIFY(GetState()==eShowing); m_pHUD->animPlay (random_anim(mhud_show), FALSE, this, GetState()); // m_bPending = true; } void CWeaponKnife::FireStart() { inherited::FireStart(); SwitchState (eFire); } void CWeaponKnife::Fire2Start () { inherited::Fire2Start(); SwitchState(eFire2); } bool CWeaponKnife::Action(s32 cmd, u32 flags) { if(inherited::Action(cmd, flags)) return true; switch(cmd) { case kWPN_ZOOM : if(flags&CMD_START) Fire2Start(); else Fire2End(); return true; } return false; } void CWeaponKnife::LoadFireParams(LPCSTR section, LPCSTR prefix) { inherited::LoadFireParams(section, prefix); string256 full_name; fHitPower_1 = fHitPower; fHitImpulse_1 = fHitImpulse; m_eHitType_1 = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type")); fHitPower_2 = pSettings->r_float (section,strconcat(full_name, prefix, "hit_power_2")); fHitImpulse_2 = pSettings->r_float (section,strconcat(full_name, prefix, "hit_impulse_2")); m_eHitType_2 = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type_2")); } void CWeaponKnife::StartIdleAnim() { m_pHUD->animDisplay(mhud_idle[Random.randI(mhud_idle.size())], TRUE); } void CWeaponKnife::GetBriefInfo(xr_string& str_name, xr_string& icon_sect_name, xr_string& str_count) { str_name = NameShort(); str_count = ""; icon_sect_name = *cNameSect(); } #include "script_space.h" using namespace luabind; #pragma optimize("s",on) void CWeaponKnife::script_register (lua_State *L) { module(L) [ class_<CWeaponKnife,CGameObject>("CWeaponKnife") .def(constructor<>()) ]; }
24.209559
102
0.646773
ixray-team
36bcb60be3238f2450f2728f16905b857754c02b
31,539
cpp
C++
examples/Chapter-16/Chapter-16.cpp
kamarianakis/glGA-edu
17f0b33c3ea8efcfa8be01d41343862ea4e6fae0
[ "BSD-4-Clause-UC" ]
4
2018-08-22T03:43:30.000Z
2021-03-11T18:20:27.000Z
examples/Chapter-16/Chapter-16.cpp
kamarianakis/glGA-edu
17f0b33c3ea8efcfa8be01d41343862ea4e6fae0
[ "BSD-4-Clause-UC" ]
7
2020-10-06T16:34:12.000Z
2020-12-06T17:29:22.000Z
examples/Chapter-16/Chapter-16.cpp
kamarianakis/glGA-edu
17f0b33c3ea8efcfa8be01d41343862ea4e6fae0
[ "BSD-4-Clause-UC" ]
71
2015-03-26T10:28:04.000Z
2021-11-07T10:09:12.000Z
// basic STL streams #include <iostream> #include <sstream> // GLEW lib // http://glew.sourceforge.net/basic.html #include <GL/glew.h> // Update 05/08/16 #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <ImGUI/imgui.h> #include <ImGUI/imgui_impl_sdl.h> #include <ImGUI/imgui_impl_opengl3.h> // Here we decide which of the two versions we want to use // If your systems supports both, choose to uncomment USE_OPENGL32 // otherwise choose to uncomment USE_OPENGL21 // GLView cna also help you decide before running this program: // // FOR MACOSX only, please use OPENGL32 for AntTweakBar to work properly // #define USE_OPENGL32 #include <glGA/glGARigMesh.h> // GLM lib // http://glm.g-truc.net/api/modules.html #define GLM_SWIZZLE #define GLM_FORCE_INLINE #include <glm/glm.hpp> #include <glm/gtx/string_cast.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/random.hpp> #include <fstream> //local #include "glGA/glGAHelper.h" #include "glGA/glGAMesh.h" // number of Squares for Plane #define NumOfSQ 20 // update globals SDL_Window *gWindow = NULL; SDL_GLContext gContext; float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f }; double FPS; // global variables int windowWidth=1024, windowHeight=768; GLuint programPlane, programPS; GLuint vao, vaoPlane, vaoPS; GLuint bufferPlane, bufferPS; GLuint MV_uniformPlane , MVP_uniformPlane , Normal_uniformPlane; GLuint MV_uniform3D , MVP_uniformPS , Normal_uniform3D; GLuint TextureMatrix_Uniform; int timesc = 0; GLuint gSampler1,gSampler; Texture *pTexture = NULL; Mesh *m = NULL; const int NumVerticesSQ = ( (NumOfSQ) * (NumOfSQ)) * (2) * (3) + (1); const int NumVerticesCube = 36; //(6 faces)(2 triangles/face)(3 vertices/triangle) bool wireFrame = false; bool camera = false; bool SYNC = true; typedef glm::vec4 color4; typedef glm::vec4 point4; int IndexSQ = 0,IndexSQ1 = 0,IndexCube = 0; //Modelling arrays point4 pointsq[NumVerticesSQ]; color4 colorsq[NumVerticesSQ]; glm::vec3 normalsq[NumVerticesSQ]; glm::vec4 tex_coords[NumVerticesSQ]; glm::vec3 pos = glm::vec3( 0.0f, 0.0f , 30.0f ); float horizAngle = 3.14f; float verticAngle = 0.0f; float speedo = 3.0f; float mouseSpeedo = 0.005f; int xpos = 0,ypos = 0; float zNear; float zFar; float FOV; float initialFoV = 45.0f; int divideFactor = 2; float m10 = -15.0f,m101 = -15.0f; int go2 = 0; // Scene orientation (stored as a quaternion) float Rotation[] = { 0.0f, 0.0f, 0.0f, 1.0f }; //Plane point4 planeVertices[NumVerticesSQ]; color4 planeColor[NumVerticesSQ]; // Update function prototypes bool initSDL(); bool event_handler(SDL_Event* event); void close(); void resize_window(int width, int height); bool initImGui(); void displayGui(); // Update functions bool initSDL() { //Init flag bool success = true; //Basic Setup if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { std::cout << std::endl << "Yay! Initialized SDL succesfully!" << std::endl; //Use OpenGL Core 3.2 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16); #ifdef __APPLE__ SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1"); #endif //Create Window SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, &current); #ifdef __APPLE__ gWindow = SDL_CreateWindow("Chapter16", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI ); divideFactor = 4; #else gWindow = SDL_CreateWindow("Chapter16", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); #endif if (gWindow == NULL) { std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { std::cout << std::endl << "Yay! Created window sucessfully!" << std::endl << std::endl; //Create context gContext = SDL_GL_CreateContext(gWindow); if (gContext == NULL) { std::cout << "OpenGL context could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { //Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { std::cout << "Error initializing GLEW! " << glewGetErrorString(glewError) << std::endl; } //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { std::cout << "Warning: Unable to set Vsync! SDL Error: " << SDL_GetError() << std::endl; } //Initializes ImGui if (!initImGui()) { std::cout << "Error initializing ImGui! " << std::endl; success = false; } //Init glViewport first time; resize_window(windowWidth, windowHeight); } } } return success; } bool event_handler(SDL_Event* event) { switch (event->type) { case SDL_WINDOWEVENT: { if (event->window.event == SDL_WINDOWEVENT_RESIZED) { resize_window(event->window.data1, event->window.data2); } } case SDL_MOUSEWHEEL: { return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) if (event->button.button == SDL_BUTTON_RIGHT) if (event->button.button == SDL_BUTTON_MIDDLE) return true; } case SDL_TEXTINPUT: { return true; } case SDL_KEYDOWN: { if (event->key.keysym.sym == SDLK_w) { if (wireFrame) { wireFrame = false; } else { wireFrame = true; } return true; } if (event->key.keysym.sym == SDLK_SPACE) { if (camera == false) { camera = true; SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); SDL_ShowCursor(0); } else { camera = false; SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); SDL_ShowCursor(1); } return true; } return true; } case SDL_KEYUP: { return true; } case SDL_MOUSEMOTION: { return true; } } return false; } void close() { //Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gContext); SDL_DestroyWindow(gWindow); SDL_Quit(); } void resize_window(int width, int height) { // Set OpenGL viewport and default camera glViewport(0, 0, width, height); float aspect = (GLfloat)width / (GLfloat)height; windowWidth = width; windowHeight = height; } bool initImGui() { // Setup ImGui binding IMGUI_CHECKVERSION(); ImGui::SetCurrentContext(ImGui::CreateContext()); // Setup ImGui binding if (!ImGui_ImplOpenGL3_Init("#version 150")) { return false; } if (!ImGui_ImplSDL2_InitForOpenGL(gWindow, gContext)) { return false; } // Load Fonts // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details) // Marios -> in order to use custom Fonts, //there is a file named extra_fonts inside /_thirdPartyLibs/include/ImGUI/extra_fonts //Uncomment the next line -> ImGui::GetIO() and one of the others -> io.Fonts->AddFontFromFileTTF("", 15.0f). //Important : Make sure to check the first parameter is the correct file path of the .ttf or you get an assertion. //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../_thirdPartyLibs/include/ImGUI/extra_fonts/Karla-Regular.ttf", 14.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); return true; } void displayGui(){ ImGui::Begin("Main Editor"); ImGui::SetWindowSize(ImVec2(200, 200), ImGuiSetCond_Once); ImGui::SetWindowPos(ImVec2(10, 10), ImGuiSetCond_Once); static bool checkbox = false; if (ImGui::Checkbox("Wireframe", &checkbox)) { if (checkbox) wireFrame = true; else wireFrame = false; } ImGui::Separator(); ImGui::ColorEdit3("bgColor", bgColor); ImGui::Separator(); if (ImGui::TreeNode("Scene Rotation")) { ImGui::InputFloat4("SceneRotation", (float*)&Rotation, 2); ImGui::Separator(); ImGui::SliderFloat("X", (float*)&Rotation[0], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("Y", (float*)&Rotation[1], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("Z", (float*)&Rotation[2], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("W", (float*)&Rotation[3], -1.0f, 1.0f, "%.2f"); ImGui::TreePop(); } ImGui::Separator(); if (ImGui::Button("Reset View", ImVec2(100, 20))) { Rotation[0] = 0.0f; Rotation[1] = 0.0f; Rotation[2] = 0.0f; Rotation[3] = 1.0f; pos = glm::vec3(5.0f, 3.0f, 18.0f); zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; horizAngle = 3.14f; verticAngle = 0.0f; } ImGui::Separator(); if (ImGui::TreeNode("Projection Properties")) { ImGui::SliderFloat("Near Clip Plane", &zNear, 0.5, 100.0, "%.2f"); ImGui::Separator(); ImGui::SliderFloat("Far Clip Plane", &zFar, 0.5, 1000.0, "%.2f"); ImGui::Separator(); ImGui::SliderFloat("Field of View", &FOV, 0.0f, 100.0f, "%.2f"); ImGui::TreePop(); } ImGui::Separator(); if (ImGui::TreeNode("Frame Rate")) { ImGui::BulletText("MS per 1 Frame %.2f", FPS); ImGui::NewLine(); ImGui::BulletText("Frames Per Second %.2f", ImGui::GetIO().Framerate); ImGui::NewLine(); ImGui::BulletText("vSYNC %d", SYNC); ImGui::TreePop(); } ImGui::End(); } #if !defined(__APPLE__) /*void setVSync(bool sync) { // Function pointer for the wgl extention function we need to enable/disable // vsync typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALPROC)( int ); PFNWGLSWAPINTERVALPROC wglSwapIntervalEXT = 0; //const char *extensions = (char*)glGetString( GL_EXTENSIONS ); //if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 ) //if(glewIsSupported("WGL_EXT_swap_control")) //{ // std::cout<<"\nWGL_EXT_swap_control Extension is not supported.\n"; // return; //} //else //{ wglSwapIntervalEXT = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress( "wglSwapIntervalEXT" ); if( wglSwapIntervalEXT ) wglSwapIntervalEXT(sync); std::cout<<"\nDONE :: "<<sync<<"\n"; //} }*/ #endif static GLint arrayWidth, arrayHeight; static GLfloat *verts = NULL; static GLfloat *colors = NULL; static GLfloat *velocities = NULL; static GLfloat *startTimes = NULL; GLfloat Time = 0.0f,Time1 = 0.0f; glm::vec4 Background = glm::vec4(0.0,0.0,0.0,1.0); // Routine to convert a quaternion to a 4x4 matrix glm::mat4 ConvertQuaternionToMatrix(float *quat,glm::mat4 &mat) { float yy2 = 2.0f * quat[1] * quat[1]; float xy2 = 2.0f * quat[0] * quat[1]; float xz2 = 2.0f * quat[0] * quat[2]; float yz2 = 2.0f * quat[1] * quat[2]; float zz2 = 2.0f * quat[2] * quat[2]; float wz2 = 2.0f * quat[3] * quat[2]; float wy2 = 2.0f * quat[3] * quat[1]; float wx2 = 2.0f * quat[3] * quat[0]; float xx2 = 2.0f * quat[0] * quat[0]; mat[0][0] = - yy2 - zz2 + 1.0f; mat[0][1] = xy2 + wz2; mat[0][2] = xz2 - wy2; mat[0][3] = 0; mat[1][0] = xy2 - wz2; mat[1][1] = - xx2 - zz2 + 1.0f; mat[1][2] = yz2 + wx2; mat[1][3] = 0; mat[2][0] = xz2 + wy2; mat[2][1] = yz2 - wx2; mat[2][2] = - xx2 - yy2 + 1.0f; mat[2][3] = 0; mat[3][0] = mat[3][1] = mat[3][2] = 0; mat[3][3] = 1; return mat; } float ax = (0.0f/NumOfSQ),ay = (0.0f/NumOfSQ); // { 0.0 , 0.0 } float bx = (0.0f/NumOfSQ),by = (1.0f/NumOfSQ); // { 0.0 , 1.0 } float cx = (1.0f/NumOfSQ),cy = (1.0f/NumOfSQ); // { 1.0 , 1.0 } float dx = (1.0f/NumOfSQ),dy = (0.0f/NumOfSQ); // { 1.0 , 0.0 } int counter2 = 0,counter3 = 1; void quadSQ( int a, int b, int c, int d ) { // 0, 3, 2, 1 //specify temporary vectors along each quad's edge in order to compute the face // normal using the cross product rule glm::vec3 u = (planeVertices[b]-planeVertices[a]).xyz(); glm::vec3 v = (planeVertices[c]-planeVertices[b]).xyz(); glm::vec3 norm = glm::cross(u, v); glm::vec3 normal= glm::normalize(norm); normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[b]; pointsq[IndexSQ] = planeVertices[b];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[d]; pointsq[IndexSQ] = planeVertices[d];IndexSQ++; // Texture Coordinate Generation for the Plane if(counter2 != NumOfSQ) { tex_coords[IndexSQ1] = glm::vec4((bx) + (counter2 * (1.0/NumOfSQ)),(by),0.0,0.0);IndexSQ1++; // { 0.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((cx) + (counter2 * (1.0/NumOfSQ)),(cy),0.0,0.0);IndexSQ1++; // { 1.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((dx) + (counter2 * (1.0/NumOfSQ)),(dy),0.0,0.0);IndexSQ1++; // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4((bx) + (counter2 * (1.0/NumOfSQ)),(by),0.0,0.0);IndexSQ1++; // { 0.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((dx) + (counter2 * (1.0/NumOfSQ)),(dy),0.0,0.0);IndexSQ1++; // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4((ax) + (counter2 * (1.0/NumOfSQ)),(ay),0.0,0.0);IndexSQ1++; // { 0.0 , 0.0 } counter2++; } else { ax = (ax);ay = (ay) + (counter3 * (1.0/NumOfSQ)); // { 0.0 , 0.0 } bx = (bx);by = (by) + (counter3 * (1.0/NumOfSQ)); // { 0.0 , 1.0 } cx = (cx);cy = (cy) + (counter3 * (1.0/NumOfSQ)); // { 1.0 , 1.0 } dx = (dx);dy = (dy) + (counter3 * (1.0/NumOfSQ)); // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4(bx,by,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(cx,cy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(dx,dy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(bx,by,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(dx,dy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(ax,ay,0.0,0.0);IndexSQ1++; counter2 = 1; } } void initPlane() { float numX = 0.0f,numX1 = 0.5f; float numZ = 0.0f,numZ1 = 0.5f; planeVertices[0] = point4 ( numX, 0.0, numZ1, 1.0); planeColor[0] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 0 a planeVertices[1] = point4 ( numX, 0.0, numZ, 1.0); planeColor[1] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 1 d planeVertices[2] = point4 ( numX1, 0.0, numZ, 1.0); planeColor[2] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 2 c planeVertices[3] = point4 ( numX1, 0.0, numZ1, 1.0); planeColor[3] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 3 b int k = 4; int counter = 0; for(k=4;k<NumVerticesSQ;k=k+4) { numX+=0.5f; numX1+=0.5f; counter++; planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0); if( counter == (NumOfSQ - 1) ) { numX = 0.0f;numX1 = 0.5f;k+=4; counter = 0; numZ+=0.5f;numZ1+=0.5f; planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0); } } //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vaoPlane); glBindVertexArray(vaoPlane); pTexture = new Texture(GL_TEXTURE_2D,"./Textures/nvidia_logo.jpg"); //pTexture = new Texture(GL_TEXTURE_2D,"./Textures/NVIDIA.jpg"); if (!pTexture->loadTexture()) { exit(EXIT_FAILURE); } int lp = 0,a,b,c,d; a=0,b=3,c=2,d=1; for(lp = 0;lp < (NumOfSQ * NumOfSQ);lp++) { quadSQ(a,b,c,d); a+=4;b+=4;c+=4;d+=4; } // Load shaders and use the resulting shader program programPlane = LoadShaders( "./Shaders/vPlaneShader.vert", "./Shaders/fPlaneShader.frag" ); glUseProgram( programPlane ); // Create and initialize a buffer object on the server side (GPU) //GLuint buffer; glGenBuffers( 1, &bufferPlane ); glBindBuffer( GL_ARRAY_BUFFER, bufferPlane ); glBufferData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) + sizeof(tex_coords),NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(pointsq), pointsq ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq), sizeof(colorsq), colorsq ); glBufferSubData( GL_ARRAY_BUFFER,sizeof(pointsq) + sizeof(colorsq),sizeof(normalsq),normalsq ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) ,sizeof(tex_coords) , tex_coords ); // set up vertex arrays GLuint vPosition = glGetAttribLocation( programPlane, "MCvertex" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); GLuint vColor = glGetAttribLocation( programPlane, "vColor" ); glEnableVertexAttribArray( vColor ); glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq)) ); GLuint vNormal = glGetAttribLocation( programPlane, "vNormal" ); glEnableVertexAttribArray( vNormal ); glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq)) ); GLuint vText = glGetAttribLocation( programPlane, "MultiTexCoord0" ); glEnableVertexAttribArray( vText ); glVertexAttribPointer( vText, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq)) ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void initParticleSystem() { m = new Mesh(); m->loadMesh("./Models/sphere.dae"); float *speed = NULL; float *lifetime = NULL; speed = (float *)malloc(m->numIndices * sizeof(float)); lifetime = (float *)malloc(m->numIndices * sizeof(float)); for(int i = 0; i < m->numIndices ; i++) { speed[i] = ((float)rand() / RAND_MAX ) / 10; lifetime[i] = 75.0 + (float)rand()/((float)RAND_MAX/(120.0-75.0)); } //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vaoPS); glBindVertexArray(vaoPS); // Load shaders and use the resulting shader program programPS = LoadShaders( "./Shaders/vParticleShader.vert", "./Shaders/fParticleShader.frag" ); glUseProgram( programPS ); // Create and initialize a buffer object on the server side (GPU) //GLuint buffer; glGenBuffers( 1, &bufferPS ); glBindBuffer( GL_ARRAY_BUFFER, bufferPS ); glBufferData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + 2*(m->numIndices * sizeof(float)),NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, (sizeof(m->Positions[0]) * m->Positions.size()), &m->Positions[0] ); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()),(sizeof(m->Normals[0]) * m->Normals.size()),&m->Normals[0] ); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()),(m->numIndices * sizeof(float)),speed); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + (m->numIndices * sizeof(float)),(m->numIndices * sizeof(float)),lifetime); // set up vertex arrays GLuint vPosition = glGetAttribLocation( programPS, "MCVertex" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); GLuint vVelocity = glGetAttribLocation( programPS, "Velocity" ); glEnableVertexAttribArray( vVelocity ); glVertexAttribPointer( vVelocity, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size())) ); GLuint vSpeed = glGetAttribLocation( programPS, "Speed" ); glEnableVertexAttribArray( vSpeed ); glVertexAttribPointer( vSpeed, 1, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size())) ); GLuint vLifeTime = glGetAttribLocation( programPS, "LifeTime" ); glEnableVertexAttribArray( vLifeTime ); glVertexAttribPointer( vLifeTime, 1, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + (m->numIndices * sizeof(float))) ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void checkActiveUniforms() { GLint nUniforms, maxLen; glGetProgramiv( programPS, GL_ACTIVE_UNIFORM_MAX_LENGTH,&maxLen); glGetProgramiv( programPS, GL_ACTIVE_UNIFORMS,&nUniforms); GLchar * name = (GLchar *) malloc( maxLen ); GLint size, location; GLsizei written; GLenum type; printf(" Location | Name\n"); printf("------------------------------------------------\n"); for( int i = 0; i < nUniforms; ++i ) { glGetActiveUniform( programPS, i, maxLen, &written,&size, &type, name ); location = glGetUniformLocation(programPS, name); printf(" %-8d | %s\n", location, name); } free(name); } void displayPlane(glm::mat4 &md,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv) { glUseProgram(programPlane); glBindVertexArray(vaoPlane); glDisable(GL_CULL_FACE); glPushAttrib(GL_ALL_ATTRIB_BITS); if (wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); MV_uniformPlane = glGetUniformLocation(programPlane, "MV_mat"); MVP_uniformPlane = glGetUniformLocation(programPlane, "MVP_mat"); Normal_uniformPlane = glGetUniformLocation(programPlane, "Normal_mat"); TextureMatrix_Uniform = glGetUniformLocation(programPlane, "TextureMatrix"); glm::mat4 TexMat = glm::mat4(); glUniformMatrix4fv(TextureMatrix_Uniform,1,GL_FALSE,glm::value_ptr(TexMat)); // Calculation of ModelView Matrix glm::mat4 model_mat_plane = md; glm::mat4 view_mat_plane = glm::lookAt(positionv,positionv + directionv,upv); glm::mat4 MV_mat_plane = view_mat_plane * model_mat_plane; glUniformMatrix4fv(MV_uniformPlane,1, GL_FALSE, glm::value_ptr(MV_mat_plane)); // Calculation of Normal Matrix glm::mat3 Normal_mat_plane = glm::transpose(glm::inverse(glm::mat3(MV_mat_plane))); glUniformMatrix3fv(Normal_uniformPlane,1, GL_FALSE, glm::value_ptr(Normal_mat_plane)); // Calculation of ModelViewProjection Matrix float aspect_plane = (GLfloat)windowWidth / (GLfloat)windowHeight; glm::mat4 projection_mat_plane = glm::perspective(FOV, aspect_plane,zNear,zFar); glm::mat4 MVP_mat_plane = projection_mat_plane * MV_mat_plane; glUniformMatrix4fv(MVP_uniformPlane, 1, GL_FALSE, glm::value_ptr(MVP_mat_plane)); gSampler = glGetUniformLocationARB(programPlane, "gSampler"); glUniform1iARB(gSampler, 0); pTexture->bindTexture(GL_TEXTURE0); glDrawArrays( GL_TRIANGLES, 0, NumVerticesSQ ); glPopAttrib(); glBindVertexArray(0); //glUseProgram(0); } int flagP = 0,flagP1 = 0; void displayParticleSystem(glm::mat4 &md,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv,int firew) { glUseProgram(programPS); glBindVertexArray(vaoPS); glDisable(GL_CULL_FACE); glPushAttrib(GL_ALL_ATTRIB_BITS); glPointSize(1.5); if (wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); MVP_uniformPS = glGetUniformLocation(programPS, "MVPMatrix"); // Calculation of ModelView Matrix glm::mat4 model_matx; if(firew == 1) { model_matx = glm::translate(md,glm::vec3(0.0,m10,0.0)); glUniform1i(glGetUniformLocation(programPS,"firew"),firew); } else { model_matx = glm::translate(md,glm::vec3(-5.0,m101,4.0)); glUniform1i(glGetUniformLocation(programPS,"firew"),firew); } glm::mat4 view_matx = glm::lookAt(positionv,positionv + directionv,upv); glm::mat4 MV_matx = view_matx * model_matx; // Calculation of ModelViewProjection Matrix float aspectx = (GLfloat)windowWidth / (GLfloat)windowHeight; glm::mat4 projection_matx = glm::perspective(45.0f, aspectx,0.1f,100.0f); glm::mat4 MVP_matx = projection_matx * MV_matx; glUniformMatrix4fv(MVP_uniformPS, 1, GL_FALSE, glm::value_ptr(MVP_matx)); glUniform4fv(glGetUniformLocation(programPS,"Background"),1,glm::value_ptr(Background)); if(Time <= 30.009 && Time >= 0) { m10 += 0.1; Time += 0.15f; } else if(Time >= 30.009) { flagP = 1; } if(flagP == 1) { Time += 0.2f; if(Time >= 0.009 && Time <= 4.00) { Time += 0.29f; } else if(Time >= 4.00 && Time <= 9.00) { Time += 0.4f; } } std::cout<<"CurrentTIME: "<<Time<<"\n"; glUniform1f(glGetUniformLocation(programPS,"Time"),Time); if(go2 == 1 && firew == 2) { if(Time1 <= 30.009 && Time1 >= 0) { m101 += 0.1; Time1 += 0.15f; } else if(Time1 >= 30.009) { flagP1 = 1; } if(flagP1 == 1) { Time1 += 0.2f; if(Time1 >= 0.009 && Time1 <= 4.00) { Time1 += 0.29f; } else if(Time1 >= 4.00 && Time1 <= 9.00) { Time1 += 0.4f; } } glUniform1f(glGetUniformLocation(programPS,"Time"),Time1); } glDrawArrays( GL_POINTS, 0, m->numVertices ); glPopAttrib(); glBindVertexArray(0); //glUseProgram(0); } int main (int argc, char * argv[]) { glm::mat4 mat; float axis[] = { 0.7f, 0.7f, 0.7f }; // initial model rotation float angle = 0.8f; double FT = 0; double starting = 0.0; double ending = 0.0; int rate = 0; int fr = 0; zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; // Current time double time = 0; // initialise GLFW int running = GL_TRUE; if (!initSDL()) { exit(EXIT_FAILURE); } std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; std::ostringstream stream1,stream2; stream1 << glGetString(GL_VENDOR); stream2 << glGetString(GL_RENDERER); std::string vendor ="Title : Chapter-16 Vendor : " + stream1.str() + " Renderer : " +stream2.str(); const char *tit = vendor.c_str(); SDL_SetWindowTitle(gWindow, tit); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); initPlane(); //initialize Plane initParticleSystem(); GLfloat rat = 0.001f; if(SYNC == false) { rat = 0.001f; } else { rat = 0.01f; } // Initialize time time = SDL_GetTicks() / 1000.0f; uint32 currentTime; uint32 lastTime = 0U; int Frames = 0; double LT = SDL_GetTicks() / 1000.0f; starting = SDL_GetTicks() / 1000.0f; int play = 0; #if !defined (__APPLE__) if(SDL_GL_SetSwapInterval(1) == 0) SYNC = true; //setVSync(SYNC); #endif FOV = initialFoV; #ifdef __APPLE__ int *w = (int*)malloc(sizeof(int)); int *h = (int*)malloc(sizeof(int)); #endif while (running) { glm::vec3 direction(cos(verticAngle) * sin(horizAngle), sin(verticAngle), cos(verticAngle) * cos(horizAngle)); glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f / 2.0f), 0, cos(horizAngle - 3.14f / 2.0f)); glm::vec3 up = glm::cross(right, direction); currentTime = SDL_GetTicks(); float dTime = float(currentTime - lastTime) / 1000.0f; lastTime = currentTime; SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); event_handler(&event); if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_UP) pos += direction * dTime * speedo; if (event.key.keysym.sym == SDLK_DOWN) pos -= direction * dTime * speedo; if (event.key.keysym.sym == SDLK_RIGHT) pos += right * dTime * speedo; if (event.key.keysym.sym == SDLK_LEFT) pos -= right * dTime * speedo; if (event.key.keysym.sym == SDLK_RETURN) { if (play == 0) play = 1; else play = 0; } } if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) { running = GL_FALSE; } if (event.type == SDL_QUIT) running = GL_FALSE; } ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(gWindow); ImGui::NewFrame(); glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color if(camera == true) { SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); horizAngle += mouseSpeedo * float(windowWidth/divideFactor - xpos ); verticAngle += mouseSpeedo * float( windowHeight/divideFactor - ypos ); } mat = ConvertQuaternionToMatrix(Rotation, mat); if(play == 1) { displayParticleSystem(mat,pos,direction,up,1); if(Time >= 40) { go2 = 1; } if(go2 == 1) { displayParticleSystem(mat,pos,direction,up,2); } if(Time >= 350) { mat = glm::mat4(); flagP = 0; flagP1 = 0; Time=0; Time1=0; go2=0; m10 = -15.0f; m101 = -15.0f; } } fr++; ending = SDL_GetTicks() / 1000.0f; if(ending - starting >= 1) { rate = fr; fr = 0; starting = SDL_GetTicks() / 1000.0f; } double CT = SDL_GetTicks() / 1000.0f; Frames++; if(CT -LT >= 1.0) { FPS = 1000.0 / (double)Frames; Frames = 0; LT += 1.0f; } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); displayGui(); ImGui::Render(); SDL_GL_MakeCurrent(gWindow, gContext); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(gWindow); #ifdef __APPLE__ if(w!=NULL && h!=NULL){ SDL_GL_GetDrawableSize(gWindow, w, h); resize_window(*w, *h); } #endif } //close OpenGL window and terminate ImGui and SDL2 close(); exit(EXIT_SUCCESS); }
28.724044
208
0.658645
kamarianakis
36bcb83a85750fe14f9e9c24b01732fb4e79ed37
488
cpp
C++
framework/platform/bpl/uci/cfg/bpl_cfg_extra.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
null
null
null
framework/platform/bpl/uci/cfg/bpl_cfg_extra.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
null
null
null
framework/platform/bpl/uci/cfg/bpl_cfg_extra.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
1
2022-02-01T20:52:12.000Z
2022-02-01T20:52:12.000Z
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * Copyright (c) 2016-2019 Intel Corporation * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include "../../common/utils/utils.h" #include <bpl/bpl_cfg.h> #include "bpl_cfg_helper.h" #include "bpl_cfg_uci.h" #include "mapf/common/logger.h" namespace beerocks { namespace bpl { int cfg_set_onboarding(int enable) { return 0; } } // namespace bpl } // namespace beerocks
20.333333
63
0.715164
ydx-coder
36bccc26957afceea2334910837427fffb054d04
18
hpp
C++
src/color/LabCH/trait/index/index.hpp
3l0w/color
e42d0933b6b88564807bcd5f49e9c7f66e24990a
[ "Apache-2.0" ]
120
2015-12-31T22:30:14.000Z
2022-03-29T15:08:01.000Z
src/color/LabCH/trait/index/index.hpp
3l0w/color
e42d0933b6b88564807bcd5f49e9c7f66e24990a
[ "Apache-2.0" ]
6
2016-08-22T02:14:56.000Z
2021-11-06T22:39:52.000Z
src/color/LabCH/trait/index/index.hpp
3l0w/color
e42d0933b6b88564807bcd5f49e9c7f66e24990a
[ "Apache-2.0" ]
23
2016-02-03T01:56:26.000Z
2021-09-28T16:36:27.000Z
// Use default !!!
18
18
0.555556
3l0w
36bf61d242ffb5ca97f4578297884555bdbdf857
1,827
cpp
C++
sound/SoundLoader.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
2
2017-03-31T19:01:22.000Z
2017-05-18T08:14:37.000Z
sound/SoundLoader.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
null
null
null
sound/SoundLoader.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2013, Mathias Hällman. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sound/SoundLoader.h" #include "sound/SoundResource.h" std::shared_ptr<Resource> SoundLoader::Load( const ResourceKey& key, const FileManager& fileManager) const { File file; fileManager.Open(key.GetFilePath(), file); SoundFileFormat format = SoundFileFormatUnknown; if (ExtractFileEnding(key.GetFilePath()).compare(".ogg") == 0) { format = SoundFileFormatOGG; } return std::make_shared<SoundResource>(file.ReadAll(), format); }
39.717391
79
0.763547
mathall
36c00318268ef72413a57bb5d1a43004c2df9ed9
1,166
cpp
C++
dynamic_programming/longest_common_subsequence.cpp
ShiyuSky/Algorithms
a2255ae55e0efb248d40ed02f86517252d66b6a3
[ "MIT" ]
null
null
null
dynamic_programming/longest_common_subsequence.cpp
ShiyuSky/Algorithms
a2255ae55e0efb248d40ed02f86517252d66b6a3
[ "MIT" ]
null
null
null
dynamic_programming/longest_common_subsequence.cpp
ShiyuSky/Algorithms
a2255ae55e0efb248d40ed02f86517252d66b6a3
[ "MIT" ]
null
null
null
/* A DP solution for solving LCS problem */ #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void printArray(vector<vector<int>> arr) { for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < arr[i].size(); j++) { cout << arr[i][j] << " "; } cout << endl; } } int findLCS(string s1, string s2) { int m = s1.size(); int n = s2.size(); vector<vector<int>> L(m, vector<int>(n)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { L[i][j] = (s1[i] == s2[j]) ? 1 : 0; } else if (s1[i] == s2[j]) { L[i][j] = 1 + L[i - 1][j - 1]; } else { L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } //cout << "L" << endl; //printArray(L); } // return last element in L return L[m - 1][n - 1]; } int main() { string s1("AGGTAB"); string s2("GXTXAYB"); int ans = findLCS(s1, s2); cout << ans << endl; std::cin.ignore(); return 0; }
22.862745
56
0.418525
ShiyuSky
36c6594f3268cf5af00e9a1138aa720568ed77d4
1,149
hpp
C++
include/flexlib/reflect/ReflectAST.hpp
blockspacer/flexlib
92c957d4cf8f172769c204962733dafbdfc71bd9
[ "Apache-2.0", "MIT" ]
1
2021-03-25T16:32:53.000Z
2021-03-25T16:32:53.000Z
include/flexlib/reflect/ReflectAST.hpp
blockspacer/flexlib
92c957d4cf8f172769c204962733dafbdfc71bd9
[ "Apache-2.0", "MIT" ]
null
null
null
include/flexlib/reflect/ReflectAST.hpp
blockspacer/flexlib
92c957d4cf8f172769c204962733dafbdfc71bd9
[ "Apache-2.0", "MIT" ]
1
2020-05-19T01:00:50.000Z
2020-05-19T01:00:50.000Z
#pragma once #include "flexlib/reflect/ReflTypes.hpp" /// \todo improve based on p1240r1 /// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2019/p1240r1.pdf namespace reflection { using namespace clang; class AstReflector { public: explicit AstReflector(const clang::ASTContext* context) : m_astContext(context) { } EnumInfoPtr ReflectEnum(const clang::EnumDecl* decl, NamespacesTree* nsTree); TypedefInfoPtr ReflectTypedef(const clang::TypedefNameDecl* decl, NamespacesTree* nsTree); ClassInfoPtr ReflectClass(const clang::CXXRecordDecl* decl, NamespacesTree* nsTree, bool recursive = true); MethodInfoPtr ReflectMethod(const clang::FunctionDecl* decl, NamespacesTree* nsTree); static void SetupNamedDeclInfo(const clang::NamedDecl* decl, NamedDeclInfo* info, const clang::ASTContext* astContext); private: const clang::NamedDecl* FindEnclosingOpaqueDecl(const clang::DeclContext* decl); void ReflectImplicitSpecialMembers(const clang::CXXRecordDecl* decl, ClassInfo* classInfo, NamespacesTree* nsTree); private: const clang::ASTContext* m_astContext; }; } // namespace reflection
31.054054
123
0.763272
blockspacer
36c66a485241128197440c641fe991ff3f27d266
921
cpp
C++
QRDemo/src/AppResourceId.cpp
NetBUG/qrbus-tizen
56e34a4dc5e36b538a184fea3494ed3f1d9e4fe3
[ "MIT" ]
1
2015-02-28T20:48:32.000Z
2015-02-28T20:48:32.000Z
QRDemo/src/AppResourceId.cpp
NetBUG/qrbus-tizen
56e34a4dc5e36b538a184fea3494ed3f1d9e4fe3
[ "MIT" ]
null
null
null
QRDemo/src/AppResourceId.cpp
NetBUG/qrbus-tizen
56e34a4dc5e36b538a184fea3494ed3f1d9e4fe3
[ "MIT" ]
null
null
null
// // Tizen C++ SDK // Copyright (c) 2012 Samsung Electronics Co., Ltd. // // Licensed under the Flora License, Version 1.1 (the License); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://floralicense.org/license // // 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 "AppResourceId.h" const wchar_t* IDF_FORM = L"IDF_FORM"; const wchar_t* IDC_INFO_LABEL = L"IDC_INFO_LABEL"; const wchar_t* ID_POPUP = L"ID_POPUP"; const wchar_t* IDC_BUTTON_YES = L"IDC_BUTTON_YES"; const wchar_t* IDC_BUTTON_NO = L"IDC_BUTTON_NO"; const wchar_t* IDC_TEXTBOX = L"IDC_TEXTBOX";
34.111111
75
0.7481
NetBUG
36c8dbd0d882712a284c6fa1bab1cf9471a95ed3
11,573
hh
C++
harfbuzz/src/hb-ot-shape-complex.hh
ebraminio/rustybuzz
07d9419d04d956d3f588b547dcd2b36576504c6e
[ "MIT" ]
null
null
null
harfbuzz/src/hb-ot-shape-complex.hh
ebraminio/rustybuzz
07d9419d04d956d3f588b547dcd2b36576504c6e
[ "MIT" ]
null
null
null
harfbuzz/src/hb-ot-shape-complex.hh
ebraminio/rustybuzz
07d9419d04d956d3f588b547dcd2b36576504c6e
[ "MIT" ]
null
null
null
/* * Copyright © 2010,2011,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #pragma once #include "hb.hh" #include "hb-ot-layout.hh" #include "hb-ot-shape-normalize.hh" #include "hb-ot-shape.hh" /* buffer var allocations, used by complex shapers */ #define complex_var_u8_0() var2.u8[2] #define complex_var_u8_1() var2.u8[3] #define HB_OT_SHAPE_COMPLEX_MAX_COMBINING_MARKS 32 extern "C" { void rb_preprocess_text_vowel_constraints(rb_buffer_t *buffer); } enum hb_ot_shape_zero_width_marks_type_t { HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE, HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_EARLY, HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE }; typedef struct hb_ot_complex_shaper_t hb_ot_complex_shaper_t; extern "C" { void hb_ot_complex_shaper_collect_features(const hb_ot_complex_shaper_t *shaper, hb_ot_shape_planner_t *planner); void hb_ot_complex_shaper_override_features(const hb_ot_complex_shaper_t *shaper, hb_ot_shape_planner_t *planner); void *hb_ot_complex_shaper_data_create(const hb_ot_complex_shaper_t *shaper, hb_shape_plan_t *plan); void hb_ot_complex_shaper_data_destroy(const hb_ot_complex_shaper_t *shaper, void *data); void hb_ot_complex_shaper_preprocess_text(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font); void hb_ot_complex_shaper_postprocess_glyphs(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font); hb_ot_shape_normalization_mode_t hb_ot_complex_shaper_normalization_preference(const hb_ot_complex_shaper_t *shaper); bool hb_ot_complex_shaper_decompose(const hb_ot_complex_shaper_t *shaper, const hb_ot_shape_normalize_context_t *c, hb_codepoint_t ab, hb_codepoint_t *a, hb_codepoint_t *b); bool hb_ot_complex_shaper_compose(const hb_ot_complex_shaper_t *shaper, const hb_ot_shape_normalize_context_t *c, hb_codepoint_t a, hb_codepoint_t b, hb_codepoint_t *ab); void hb_ot_complex_shaper_setup_masks(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font); hb_tag_t hb_ot_complex_shaper_gpos_tag(const hb_ot_complex_shaper_t *shaper); void hb_ot_complex_shaper_reorder_marks(const hb_ot_complex_shaper_t *shaper, const hb_shape_plan_t *plan, rb_buffer_t *buffer, unsigned int start, unsigned int end); hb_ot_shape_zero_width_marks_type_t hb_ot_complex_shaper_zero_width_marks(const hb_ot_complex_shaper_t *shaper); bool hb_ot_complex_shaper_fallback_position(const hb_ot_complex_shaper_t *shaper); } extern "C" { hb_ot_complex_shaper_t *rb_create_default_shaper(); hb_ot_complex_shaper_t *rb_create_arabic_shaper(); hb_ot_complex_shaper_t *rb_create_hangul_shaper(); hb_ot_complex_shaper_t *rb_create_hebrew_shaper(); hb_ot_complex_shaper_t *rb_create_indic_shaper(); hb_ot_complex_shaper_t *rb_create_khmer_shaper(); hb_ot_complex_shaper_t *rb_create_myanmar_shaper(); hb_ot_complex_shaper_t *rb_create_myanmar_zawgyi_shaper(); hb_ot_complex_shaper_t *rb_create_thai_shaper(); hb_ot_complex_shaper_t *rb_create_use_shaper(); } inline const hb_ot_complex_shaper_t *hb_ot_shape_complex_categorize(const hb_ot_shape_planner_t *planner) { switch ((hb_tag_t)planner->props.script) { default: return rb_create_default_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_ARABIC: /* Unicode-3.0 additions */ case HB_SCRIPT_MONGOLIAN: case HB_SCRIPT_SYRIAC: /* Unicode-5.0 additions */ case HB_SCRIPT_NKO: case HB_SCRIPT_PHAGS_PA: /* Unicode-6.0 additions */ case HB_SCRIPT_MANDAIC: /* Unicode-7.0 additions */ case HB_SCRIPT_MANICHAEAN: case HB_SCRIPT_PSALTER_PAHLAVI: /* Unicode-9.0 additions */ case HB_SCRIPT_ADLAM: /* Unicode-11.0 additions */ case HB_SCRIPT_HANIFI_ROHINGYA: case HB_SCRIPT_SOGDIAN: /* For Arabic script, use the Arabic shaper even if no OT script tag was found. * This is because we do fallback shaping for Arabic script (and not others). * But note that Arabic shaping is applicable only to horizontal layout; for * vertical text, just use the generic shaper instead. */ if ((rb_ot_map_builder_chosen_script(planner->map, 0) != HB_OT_TAG_DEFAULT_SCRIPT || planner->props.script == HB_SCRIPT_ARABIC) && HB_DIRECTION_IS_HORIZONTAL(planner->props.direction)) return rb_create_arabic_shaper(); else return rb_create_default_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_THAI: case HB_SCRIPT_LAO: return rb_create_thai_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_HANGUL: return rb_create_hangul_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_HEBREW: return rb_create_hebrew_shaper(); /* Unicode-1.1 additions */ case HB_SCRIPT_BENGALI: case HB_SCRIPT_DEVANAGARI: case HB_SCRIPT_GUJARATI: case HB_SCRIPT_GURMUKHI: case HB_SCRIPT_KANNADA: case HB_SCRIPT_MALAYALAM: case HB_SCRIPT_ORIYA: case HB_SCRIPT_TAMIL: case HB_SCRIPT_TELUGU: /* Unicode-3.0 additions */ case HB_SCRIPT_SINHALA: /* If the designer designed the font for the 'DFLT' script, * (or we ended up arbitrarily pick 'latn'), use the default shaper. * Otherwise, use the specific shaper. * * If it's indy3 tag, send to USE. */ if (rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('D', 'F', 'L', 'T') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('l', 'a', 't', 'n')) return rb_create_default_shaper(); else if ((rb_ot_map_builder_chosen_script(planner->map, 0) & 0x000000FF) == '3') return rb_create_use_shaper(); else return rb_create_indic_shaper(); case HB_SCRIPT_KHMER: return rb_create_khmer_shaper(); case HB_SCRIPT_MYANMAR: /* If the designer designed the font for the 'DFLT' script, * (or we ended up arbitrarily pick 'latn'), use the default shaper. * Otherwise, use the specific shaper. * * If designer designed for 'mymr' tag, also send to default * shaper. That's tag used from before Myanmar shaping spec * was developed. The shaping spec uses 'mym2' tag. */ if (rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('D', 'F', 'L', 'T') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('l', 'a', 't', 'n') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('m', 'y', 'm', 'r')) return rb_create_default_shaper(); else return rb_create_myanmar_shaper(); /* https://github.com/harfbuzz/harfbuzz/issues/1162 */ case HB_SCRIPT_MYANMAR_ZAWGYI: return rb_create_myanmar_zawgyi_shaper(); /* Unicode-2.0 additions */ case HB_SCRIPT_TIBETAN: /* Unicode-3.0 additions */ // case HB_SCRIPT_MONGOLIAN: // case HB_SCRIPT_SINHALA: /* Unicode-3.2 additions */ case HB_SCRIPT_BUHID: case HB_SCRIPT_HANUNOO: case HB_SCRIPT_TAGALOG: case HB_SCRIPT_TAGBANWA: /* Unicode-4.0 additions */ case HB_SCRIPT_LIMBU: case HB_SCRIPT_TAI_LE: /* Unicode-4.1 additions */ case HB_SCRIPT_BUGINESE: case HB_SCRIPT_KHAROSHTHI: case HB_SCRIPT_SYLOTI_NAGRI: case HB_SCRIPT_TIFINAGH: /* Unicode-5.0 additions */ case HB_SCRIPT_BALINESE: // case HB_SCRIPT_NKO: // case HB_SCRIPT_PHAGS_PA: /* Unicode-5.1 additions */ case HB_SCRIPT_CHAM: case HB_SCRIPT_KAYAH_LI: case HB_SCRIPT_LEPCHA: case HB_SCRIPT_REJANG: case HB_SCRIPT_SAURASHTRA: case HB_SCRIPT_SUNDANESE: /* Unicode-5.2 additions */ case HB_SCRIPT_EGYPTIAN_HIEROGLYPHS: case HB_SCRIPT_JAVANESE: case HB_SCRIPT_KAITHI: case HB_SCRIPT_MEETEI_MAYEK: case HB_SCRIPT_TAI_THAM: case HB_SCRIPT_TAI_VIET: /* Unicode-6.0 additions */ case HB_SCRIPT_BATAK: case HB_SCRIPT_BRAHMI: // case HB_SCRIPT_MANDAIC: /* Unicode-6.1 additions */ case HB_SCRIPT_CHAKMA: case HB_SCRIPT_SHARADA: case HB_SCRIPT_TAKRI: /* Unicode-7.0 additions */ case HB_SCRIPT_DUPLOYAN: case HB_SCRIPT_GRANTHA: case HB_SCRIPT_KHOJKI: case HB_SCRIPT_KHUDAWADI: case HB_SCRIPT_MAHAJANI: // case HB_SCRIPT_MANICHAEAN: case HB_SCRIPT_MODI: case HB_SCRIPT_PAHAWH_HMONG: // case HB_SCRIPT_PSALTER_PAHLAVI: case HB_SCRIPT_SIDDHAM: case HB_SCRIPT_TIRHUTA: /* Unicode-8.0 additions */ case HB_SCRIPT_AHOM: /* Unicode-9.0 additions */ // case HB_SCRIPT_ADLAM: case HB_SCRIPT_BHAIKSUKI: case HB_SCRIPT_MARCHEN: case HB_SCRIPT_NEWA: /* Unicode-10.0 additions */ case HB_SCRIPT_MASARAM_GONDI: case HB_SCRIPT_SOYOMBO: case HB_SCRIPT_ZANABAZAR_SQUARE: /* Unicode-11.0 additions */ case HB_SCRIPT_DOGRA: case HB_SCRIPT_GUNJALA_GONDI: // case HB_SCRIPT_HANIFI_ROHINGYA: case HB_SCRIPT_MAKASAR: // case HB_SCRIPT_SOGDIAN: /* Unicode-12.0 additions */ case HB_SCRIPT_NANDINAGARI: /* If the designer designed the font for the 'DFLT' script, * (or we ended up arbitrarily pick 'latn'), use the default shaper. * Otherwise, use the specific shaper. * Note that for some simple scripts, there may not be *any* * GSUB/GPOS needed, so there may be no scripts found! */ if (rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('D', 'F', 'L', 'T') || rb_ot_map_builder_chosen_script(planner->map, 0) == HB_TAG('l', 'a', 't', 'n')) return rb_create_default_shaper(); else return rb_create_use_shaper(); } }
36.739683
117
0.674847
ebraminio
36c98c01f0c20fba89bc0feaf240e9a76625de58
625
hpp
C++
math/float-binomial.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
math/float-binomial.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
math/float-binomial.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#pragma once struct FloatBinomial { vector<long double> f; static constexpr long double LOGZERO = -1e10; FloatBinomial(int MAX) { f.resize(MAX + 1, 0.0); f[0] = 0.0; for (int i = 1; i <= MAX; i++) { f[i] = f[i - 1] + logl(i); } } long double logfac(int n) const { return f[n]; } long double logfinv(int n) const { return -f[n]; } long double logC(int n, int k) const { if (n < k || k < 0 || n < 0) return LOGZERO; return f[n] - f[n - k] - f[k]; } long double logP(int n, int k) const { if (n < k || k < 0 || n < 0) return LOGZERO; return f[n] - f[n - k]; } };
20.833333
52
0.5248
NachiaVivias
36cbdaa2b0d941a4c7ea550331381399cb1cd38b
809
hpp
C++
libmuscle/cpp/src/libmuscle/tests/mocks/mock_post_office.hpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
11
2018-03-12T10:43:46.000Z
2020-06-01T10:58:56.000Z
libmuscle/cpp/src/libmuscle/tests/mocks/mock_post_office.hpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
85
2018-03-03T15:10:56.000Z
2022-03-18T14:05:14.000Z
libmuscle/cpp/src/libmuscle/tests/mocks/mock_post_office.hpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
6
2018-03-12T10:47:11.000Z
2022-02-03T13:44:07.000Z
#pragma once #include <ymmsl/ymmsl.hpp> #include <libmuscle/data.hpp> #include <libmuscle/mcp/message.hpp> #include <libmuscle/outbox.hpp> namespace libmuscle { namespace impl { class MockPostOffice { public: MockPostOffice() = default; bool has_message(ymmsl::Reference const & receiver); std::unique_ptr<DataConstRef> get_message( ymmsl::Reference const & receiver); void deposit( ymmsl::Reference const & receiver, std::unique_ptr<DataConstRef> message); void wait_for_receivers() const; // Mock control variables static void reset(); static ymmsl::Reference last_receiver; static std::unique_ptr<mcp::Message> last_message; }; using PostOffice = MockPostOffice; } }
20.74359
60
0.647713
DongweiYe
36ccd20b1e19181f9dbd163524824989c7a25fa6
4,640
cc
C++
scripts/MPM/extractTaylor.cc
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
3
2020-06-10T08:21:31.000Z
2020-06-23T18:33:16.000Z
scripts/MPM/extractTaylor.cc
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
null
null
null
scripts/MPM/extractTaylor.cc
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
2
2019-12-30T05:48:30.000Z
2020-02-12T16:24:16.000Z
/* * The MIT License * * Copyright (c) 1997-2019 The University of Utah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <cstdlib> #include <cstdio> #include <iostream> #include <fstream> #include <cmath> #include <string> #include <vector> // Find the current location of a set of points whose initial // position is known (from puda) (for the Taylor impact test) using namespace std; bool inbox(double px, double py, double pz, double xmin, double xmax, double ymin, double ymax, double zmin, double zmax) { if (px > xmin && py > ymin && pz > zmin && px < xmax && py < ymax && pz < zmax) return true; return false; } int main(int argc, char** argv) { // Check if the number of arguments is correct if (argc != 3) { cerr << "Usage: extractTaylor <int_pos_file> <final_pos_file>" << endl; exit(0); } // Parse arguments string posFileName = argv[1]; string finposFileName = argv[2]; // Open the files ifstream posFile(posFileName.c_str()); if(!posFile) { cerr << "File " << posFileName << " can't be opened." << endl; exit(0); } string pidFileName = posFileName+".pid"; ofstream pidFile(pidFileName.c_str()); // Read in the initial particle location double rad, height; cout << "\n Enter radius and height "; cin >> rad >> height; cout << rad << " " << height << endl; double dx; cout << "\n Enter width of search box "; cin >> dx; cout << dx << endl; // Create an array for storing the PIDs vector<int64_t> pidVec; // Read the header posFile.ignore(1000,'\n'); int64_t pID; int patch, mat; double time, x, y, z; double xmin, ymin, xmax, ymax, zmin, zmax; while (posFile >> time >> patch >> mat >> pID >> x >> y >> z){ // Create the width box (top) xmin = -dx; ymin = height - dx; zmin = -dx; xmax = rad + dx; ymax = height + dx; zmax = dx; if (inbox(x, y, z, xmin, xmax, ymin, ymax, zmin, zmax)){ //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; pidFile << pID << " " << x << " " << y << " " << z << endl; pidVec.push_back(pID); } // Create the height box xmin = rad - dx; ymin = -dx; zmin = -dx; xmax = rad + dx; ymax = height + dx; zmax = dx; if (inbox(x, y, z, xmin, xmax, ymin, ymax, zmin, zmax)){ //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; pidFile << pID << " " << x << " " << y << " " << z << endl; pidVec.push_back(pID); } // Create the width box (bottom) xmin = -dx; ymin = - dx; zmin = -dx; xmax = rad + dx; ymax = dx; zmax = dx; if (inbox(x, y, z, xmin, xmax, ymin, ymax, zmin, zmax)){ //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; pidFile << pID << " " << x << " " << y << " " << z << endl; pidVec.push_back(pID); } } posFile.close(); // Open the files ifstream finposFile(finposFileName.c_str()); if(!finposFile) { cerr << "File " << finposFileName << " can't be opened." << endl; exit(0); } string finpidFileName = finposFileName+".pid"; ofstream finpidFile(finpidFileName.c_str()); // Read the header finposFile.ignore(1000,'\n'); int numPID = pidVec.size(); while (finposFile >> time >> patch >> mat >> pID >> x >> y >> z){ for (int ii = 0; ii < numPID; ++ii) { if (pID == pidVec[ii]) //cout << " pID = " << pID << " [" << x <<","<<y<<","<<z<<"]\n"; finpidFile << pID << " " << x << " " << y << " " << z << endl; } } finposFile.close(); }
32.907801
79
0.581466
QuocAnh90
36cf1e47419932fcf550e9faa181b2c3cebdc745
2,865
cpp
C++
p16_3Sum_Closest/p16.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p16_3Sum_Closest/p16.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p16_3Sum_Closest/p16.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> using namespace std; class VectorTools{ public: void sorted(vector<int>::iterator first, vector<int>::iterator last) { if (first == last || first + 1 == last) return; vector<int>::iterator pivot = first; int temp; for (vector<int>::iterator it = first+1; it != last; it ++) { if (*it<*pivot) { temp = *it; *it = *(pivot+1); *(pivot+1) = *pivot; *pivot = temp; pivot ++; } } sorted(first, pivot); sorted(pivot+1, last); } int binary_search(vector<int>::iterator first, int size, bool have_sorted, int tar) { int l = 0; int r = size - 1; int mid = (l+r)/2; if (size==0) return -1; else if (size==1) return 0; if (!have_sorted) sorted(first, first+size); if (*(first+l)>=tar) return l; if (*(first+r)<=tar) return r; while (l < r - 1) { mid = (l+r)/2; if (*(first+mid) < tar) l = mid; else if (*(first+mid) == tar) { int i = 0; while((mid - i)>=0 && *(first+mid-i) == tar) i ++; return *(first+mid-i)==tar?(mid-i):(mid-i+1); } else r = mid; } return (tar-*(first+l) >= *(first+r) - tar)?r:l; } void vector_display(vector<int>& v) { for (vector<int>:: iterator it = v.begin(); it != v.end(); it ++) { printf("%d ",*it); }printf("\n"); } }; class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int result,temp_result, distance; distance = INT_MAX; if (nums.size()<3) return result; VectorTools V; V.sorted(nums.begin(), nums.end()); for (int i = 0; i < nums.size()-2; i ++) { if(i>0 && nums[i]==nums[i-1]) continue; for (int j = i+1; j < nums.size()-1; j ++) { if(j>i+1 && nums[j] == nums[j-1]) continue; int l,r; l = nums[i]; r = nums[j]; int tar = target - (l + r); temp_result = nums[j+1+V.binary_search(nums.begin()+j+1,nums.size()-j-1,true,tar)]; //printf("%d: %d %d %d\n",tar,l,r,temp_result); temp_result += (l+r); if(abs(temp_result-target)<distance){ result = temp_result; distance = abs(temp_result-target); } } } return result; } }; int main () { int intList[] = {-1, 0, 1, 1, 55}; vector<int> v(intList, intList + sizeof(intList)/sizeof(int)); Solution s; VectorTools V; int result = s.threeSumClosest(v,3); printf("%d\n",result); }
31.483516
99
0.456545
Song1996
36d0ab4c2efd30629b6ebebe34477a232522789d
1,675
hh
C++
example/TerrainTestPlugin.hh
osrf/swarm
1a2e4040b12b686ed7a13e32301d538b1c7d0b1d
[ "ECL-2.0", "Apache-2.0" ]
1
2021-04-20T20:03:18.000Z
2021-04-20T20:03:18.000Z
example/TerrainTestPlugin.hh
osrf/swarm
1a2e4040b12b686ed7a13e32301d538b1c7d0b1d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
example/TerrainTestPlugin.hh
osrf/swarm
1a2e4040b12b686ed7a13e32301d538b1c7d0b1d
[ "ECL-2.0", "Apache-2.0" ]
1
2021-03-16T14:38:38.000Z
2021-03-16T14:38:38.000Z
/* * * Copyright (C) 2015 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /// \file TerrainTestPlugin.hh /// \brief A plugin that outputs an elevation.csv and a terrain.csv file. /// The elevation.csv file contains elevation information within the search /// area. The terrain.csv files contains terrain type informaiton within the /// search area. These csv files can be used in conjunction with terrain.py /// to produce png file respresentations of the raw data. #ifndef __SWARM_TERRAIN_DEBUG_PLUGIN_HH__ #define __SWARM_TERRAIN_DEBUG_PLUGIN_HH__ #include "swarm/RobotPlugin.hh" namespace swarm { /// \brief A plugin useful for testing terrain elevation and terrain type. /// Refere to the following tutorial for more information: class TerrainTestPlugin : public swarm::RobotPlugin { /// \brief constructor public: TerrainTestPlugin(); /// \brief destructor public: virtual ~TerrainTestPlugin() = default; /// \brief Produces the elevation.csv and terrain.csv files. /// \param[in] _sdf Pointer the sdf information. public: virtual void Load(sdf::ElementPtr _sdf); }; } #endif
34.183673
76
0.740896
osrf
36d1cff0cf64b80c3b49d8d78a787821d90d250d
4,635
cpp
C++
dev/src/BicycleFrontPanel/model/cwheelitemmodel.cpp
CountrySideEngineer/BicycleFrontPanel
de13a984f726d282f1703f9096dd61ef287806e9
[ "MIT" ]
null
null
null
dev/src/BicycleFrontPanel/model/cwheelitemmodel.cpp
CountrySideEngineer/BicycleFrontPanel
de13a984f726d282f1703f9096dd61ef287806e9
[ "MIT" ]
null
null
null
dev/src/BicycleFrontPanel/model/cwheelitemmodel.cpp
CountrySideEngineer/BicycleFrontPanel
de13a984f726d282f1703f9096dd61ef287806e9
[ "MIT" ]
null
null
null
#include <QString> #include "cwheelitemmodel.h" /** * @brief CWheelItemModel::VelocityValueConverter::Value2String Convert velocity value * in uint32_t data type into QString. * The format is xxxx.yyy, the decade part * has 3 number. * @param value Value to convert. * @return Convert value in QString data type. */ QString CWheelItemModel::VelocityValueConverter::Value2String(uint32_t value) { uint32_t integerPart = value / 1000; uint32_t decadePart = value % 1000; QString valueString = QString::number(integerPart) + QString(".") + QString::number(decadePart).rightJustified(3, '0') + this->getUnit(); return valueString; } /** * @brief CWheelItemModel::VelocityValueConverter::getUnit Returns the unit of velocity. * @return Unit of velocity. */ QString CWheelItemModel::VelocityValueConverter::getUnit() { return QString("[km/h]"); } /** * @brief CWheelItemModel::RotateValueConverter::Value2String Convert the number of rotation value * in uint32_t data type into QString. * @param value Rotation value to be converted. * @return Converted value in QStirng data type. */ QString CWheelItemModel::RotateValueConverter::Value2String(uint32_t value) { QString valueString = QString::number(value) + this->getUnit(); return valueString; } /** * @brief CWheelItemModel::RotateValueConverter::getUnit Returns teh unit of rotation. * @return Unit of rotation. */ QString CWheelItemModel::RotateValueConverter::getUnit() { return QString("[RPM]"); } /** * @brief CWheelItemModel::CWheelItemModel Constructs a CWheelItemModel object * with given parent. * @param parent Pointer to parent. */ CWheelItemModel::CWheelItemModel(QObject* parent) : CBicycleItemModel (parent) {} /** * @brief CWheelItemModel::setPinData Set data of wheel, velocity and rotate into model. * @param pin GPIO pin number. * @param velocity Velocity of wheel to set * @param rotate */ void CWheelItemModel::setData(const int pin, const uint32_t rotate, const uint32_t velocity) { int rowIndex = this->Pin2RowIndex(pin); RotateValueConverter rotateConverter; VelocityValueConverter velocityConverter; this->setData(rowIndex, MODEL_COLUMN_INDEX_ROTATE, rotate, rotateConverter); this->setData(rowIndex, MODEL_COLUMN_INDEX_VELOCITY, velocity, velocityConverter); } /** * @brief CWheelItemModel::setData Set data into model specified by index of row, rowIndex, and column, columnIndex. * The value is set both in raw number and string with format. * @param rowIndex Index of row of model the value to be set. * @param columnIndex Index of column of model the value to be set. * @param value The value to be set to model. * @param converter Instance of IValueConverter's subclass to be used convert value into string. */ void CWheelItemModel::setData( const int rowIndex, const int columnIndex, const uint32_t value, IValueConverter &converter) { QModelIndex modelIndex = this->index(rowIndex, columnIndex); CBicycleItemModel::setData(modelIndex, QVariant(value), false); this->setData(columnIndex, converter); } #define AVERAGE(value1, value2) (((value1) >> 1) + (value2 >> 1)) /** * @brief CWheelItemModel::updateData * @param columnIndex * @param converter */ void CWheelItemModel::setData(const int columnIndex, IValueConverter &converter) { QModelIndex frontModelIndex = this->index(MODEL_ROW_INDEX_FRONT_WHEEL_MODEL, columnIndex); QVariant frontVariant = this->data(frontModelIndex); uint32_t frontValue = frontVariant.toUInt(); QModelIndex rearModelIndex = this->index(MODEL_ROW_INDEX_REAR_WHEEL_MODEL, columnIndex); QVariant rearVariant = this->data(rearModelIndex); uint32_t rearValue = rearVariant.toUInt(); uint32_t average = AVERAGE(frontValue, rearValue); QModelIndex averageModelIndex = this->index(MODEL_ROW_INDEX_INTEGRATED_WHEEL_MODEL, columnIndex); CBicycleItemModel::setData(averageModelIndex, QVariant(average), false); averageModelIndex = this->index(MODEL_ROW_INDEX_INTEGRATED_WHEEL_MODEL, columnIndex + 2); QString stringAverage = converter.Value2String(average); CBicycleItemModel::setData(averageModelIndex, QVariant(stringAverage)); }
38.625
117
0.683927
CountrySideEngineer
36d4d03b69b7060acc9e7e8f7f471f686cd66552
9,866
cc
C++
src/media/vnext/lib/stream_sink/stream_queue_unittests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/media/vnext/lib/stream_sink/stream_queue_unittests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/media/vnext/lib/stream_sink/stream_queue_unittests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/async/cpp/executor.h> #include <lib/async/cpp/task.h> #include <gtest/gtest.h> #include "src/media/vnext/lib/stream_sink/stream_queue.h" namespace fmlib::test { // Tests the |pull| method. TEST(StreamQueueTest, Pull) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } loop.RunUntilIdle(); // Expect the tasks actually ran. EXPECT_EQ(kElements, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(kElements, element.packet()); ++exec_count; })); // Expect the task hasn't run yet. EXPECT_EQ(kElements, exec_count); // Push one more element. under_test.push(kElements); loop.RunUntilIdle(); // Expect the task ran once more. EXPECT_EQ(kElements + 1, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); } // Tests the |pull| method when the stream is ended. TEST(StreamQueueTest, PullEnded) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // End the stream. under_test.end(); // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect |kEnded|. executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_ended()); ++exec_count; })); loop.RunUntilIdle(); // Expect the tasks actually ran. EXPECT_EQ(kElements + 1, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); } // Tests the |pull| method when the stream is ended asynchronously. TEST(StreamQueueTest, PullEndedAsync) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect |kEnded|. executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_ended()); ++exec_count; })); loop.RunUntilIdle(); // Expect the initial tasks actually ran. EXPECT_EQ(kElements, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // End the stream. under_test.end(); loop.RunUntilIdle(); // Expect the final task actually ran. EXPECT_EQ(kElements + 1, exec_count); } // Tests the |pull| method when the stream is drained. TEST(StreamQueueTest, PullDrained) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Drain the stream. under_test.drain(); // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect drained. executor.schedule_task( under_test.pull().then([&exec_count](StreamQueue<size_t, float>::PullResult& result) { EXPECT_TRUE(result.is_error()); EXPECT_EQ(StreamQueueError::kDrained, result.error()); ++exec_count; })); loop.RunUntilIdle(); // Expect the tasks actually ran. EXPECT_EQ(kElements + 1, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); } // Tests the |pull| method when the stream is drained asynchronously. TEST(StreamQueueTest, PullDrainedAsync) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; static const size_t kElements = 10; // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Push some elements. for (size_t i = 0; i < kElements; ++i) { under_test.push(i); EXPECT_FALSE(under_test.empty()); EXPECT_EQ(i + 1, under_test.size()); } // Pull those elements. size_t exec_count = 0; for (size_t i = 0; i < kElements; ++i) { executor.schedule_task( under_test.pull().and_then([i, &exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_packet()); EXPECT_EQ(i, element.packet()); ++exec_count; })); } // Attempt to pull one more...expect drained. executor.schedule_task( under_test.pull().then([&exec_count](StreamQueue<size_t, float>::PullResult& result) { EXPECT_TRUE(result.is_error()); EXPECT_EQ(StreamQueueError::kDrained, result.error()); ++exec_count; })); loop.RunUntilIdle(); // Expect the initial tasks actually ran. EXPECT_EQ(kElements, exec_count); // Expect the queue is empty. EXPECT_TRUE(under_test.empty()); EXPECT_EQ(0u, under_test.size()); // Drain the stream. under_test.drain(); loop.RunUntilIdle(); // Expect the final task actually ran. EXPECT_EQ(kElements + 1, exec_count); } // Tests the |pull| method when the queue is cleared. TEST(StreamQueueTest, PullClear) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; // Try to pull an element. size_t exec_count = 0; executor.schedule_task( under_test.pull().and_then([&exec_count](StreamQueue<size_t, float>::Element& element) { EXPECT_TRUE(element.is_clear_request()); EXPECT_EQ(0.0f, element.clear_request()); ++exec_count; })); loop.RunUntilIdle(); // Expect the task hasn't run yet. EXPECT_EQ(0u, exec_count); // Clear the queue. under_test.clear(0.0f); loop.RunUntilIdle(); // Expect the task ran once. EXPECT_EQ(1u, exec_count); } // Tests the |cancel_pull| method. TEST(StreamQueueTest, CancelPull) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); async::Executor executor(loop.dispatcher()); StreamQueue<size_t, float> under_test; // Expect |cancel_pull| to return false, because there's no |pull| pending. EXPECT_FALSE(under_test.cancel_pull()); // Attempt to pull. bool task_ran = false; executor.schedule_task( under_test.pull().then([&task_ran](StreamQueue<size_t, float>::PullResult& result) { EXPECT_TRUE(result.is_error()); EXPECT_EQ(StreamQueueError::kCanceled, result.error()); task_ran = true; })); loop.RunUntilIdle(); // Expect that the task didn't run. EXPECT_FALSE(task_ran); // Abandon the pull. Expect |cancel_pull| to return true, because there's a |pull| pending. EXPECT_TRUE(under_test.cancel_pull()); loop.RunUntilIdle(); // Expect that the task ran (returning StreamQueueError::kCanceled). EXPECT_TRUE(task_ran); } } // namespace fmlib::test
28.188571
99
0.673018
allansrc
36d5c9692803b4dfe7ba391eb9d26a999f31bd75
5,141
cc
C++
Source/BladeDevice/source/graphics/RenderTarget.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeDevice/source/graphics/RenderTarget.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeDevice/source/graphics/RenderTarget.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2010/04/10 filename: RenderTarget.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <graphics/RenderTarget.h> #include <interface/public/graphics/IRenderDevice.h> #include <graphics/Texture.h> namespace Blade { ////////////////////////////////////////////////////////////////////////// RenderTarget::RenderTarget(const TString& name,IRenderDevice* device, size_t viewWidth, size_t viewHeight) :mName(name) ,mDevice(device) ,mListener(NULL) ,mViewWidth(viewWidth) ,mViewHeight(viewHeight) { } ////////////////////////////////////////////////////////////////////////// RenderTarget::~RenderTarget() { } /************************************************************************/ /* IRenderTarget interface */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// const TString& RenderTarget::getName() const { return mName; } ////////////////////////////////////////////////////////////////////////// const HTEXTURE& RenderTarget::getDepthBuffer() const { return mDepthBuffer; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setDepthBuffer(const HTEXTURE& hDethBuffer) { if( hDethBuffer != NULL && !hDethBuffer->getPixelFormat().isDepth() && !hDethBuffer->getPixelFormat().isDepthStencil() ) { assert(false); return false; } mDepthBuffer = hDethBuffer; return true; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setColorBuffer(index_t index, const HTEXTURE& buffer) { if( index >= mDevice->getDeviceCaps().mMaxMRT ) { assert(false); return false; } assert( index == 0 || buffer == NULL || buffer->getWidth() == this->getWidth() ); assert( index == 0 || buffer == NULL || buffer->getHeight() == this->getHeight() ); if( index < mOutputBuffers.size() ) mOutputBuffers[index] = buffer; else if( index == mOutputBuffers.size() ) mOutputBuffers.push_back(buffer); else { assert(false); return false; } return true; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setColorBufferCount(index_t count) { if( count <= mDevice->getDeviceCaps().mMaxMRT ) { mOutputBuffers.resize(count); return true; } assert(false); return false; } ////////////////////////////////////////////////////////////////////////// const HTEXTURE& RenderTarget::getColorBuffer(index_t index) const { if( index < mOutputBuffers.size() ) return mOutputBuffers[index]; else return HTEXTURE::EMPTY; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setViewRect(int32 left, int32 top, int32 width, int32 height) { bool ret = false; for (size_t i = 0; i < mOutputBuffers.size(); ++i) { Texture* tex = static_cast<Texture*>(mOutputBuffers[i]); if (tex != NULL) { scalar fwidth = (scalar)tex->getWidth(); scalar fheight = (scalar)tex->getHeight(); ret |= tex->setViewRect((scalar)left/fwidth, (scalar)top/fheight, std::min<scalar>(1.0f, width / fwidth), std::min<scalar>(1.0f, (scalar)height / fheight)); } } if (mDepthBuffer != NULL) { Texture* tex = static_cast<Texture*>(mDepthBuffer); if (tex != NULL) { scalar fwidth = (scalar)tex->getWidth(); scalar fheight = (scalar)tex->getHeight(); ret |= tex->setViewRect((scalar)left / fwidth, (scalar)top / fheight, std::min<scalar>(1.0f, width / fwidth), std::min<scalar>(1.0f, (scalar)height / fheight)); } } return ret; } ////////////////////////////////////////////////////////////////////////// size_t RenderTarget::getColorBufferCount() const { return mOutputBuffers.size(); } ////////////////////////////////////////////////////////////////////////// RenderTarget::IListener*RenderTarget::setListener(IListener* listener) { IListener* old = mListener; mListener = listener; return old; } RenderTarget::IListener*RenderTarget::getListener() const { return mListener; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::isReady() const { return this->getColorBuffer(0) != NULL; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::swapBuffers() { return true; } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void RenderTarget::notifySizeChange(IRenderTarget* target) { if( mListener != NULL ) mListener->onTargetSizeChange(target); } }//namespace Blade
28.72067
164
0.458277
OscarGame
36d6aac80fcc8785b501d16a86751f3957c96025
14,101
cpp
C++
moments/PointCloudIO.cpp
mlangbe/moments
167ab1e77e4e9732396418f38dfec0bad75724ac
[ "MTLL" ]
null
null
null
moments/PointCloudIO.cpp
mlangbe/moments
167ab1e77e4e9732396418f38dfec0bad75724ac
[ "MTLL" ]
null
null
null
moments/PointCloudIO.cpp
mlangbe/moments
167ab1e77e4e9732396418f38dfec0bad75724ac
[ "MTLL" ]
null
null
null
/* I/O of pointclouds to/from different formats This file is part of the source code used for the calculation of the moment invariants as described in the dissertation of Max Langbein https://nbn-resolving.org/urn:nbn:de:hbz:386-kluedo-38558 Copyright (C) 2020 TU Kaiserslautern, Prof.Dr. Hans Hagen (AG Computergraphik und HCI) (hagen@cs.uni-kl.de) Author: Max Langbein (m_langbe@cs.uni-kl.de) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include<iostream> #include<fstream> #include<cassert> #include<stdlib.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #ifndef GNUCC #include<io.h> #else #include<errno.h> #include<unistd.h> #endif #include "PointCloudIO.h" #include "equaldist.h" #include "osgio.h" #ifndef OLD_VC #include<string.h> #include<stdexcept> #define _EXCEPTION_ std::runtime_error #else #define _EXCEPTION_ exception #endif using namespace std; PointCloudIO::PointCloudIO(void) { } PointCloudIO::~PointCloudIO(void) { } bool PointCloudIO::accept(const char *name, const char *format) { if(format) return strcmp(format,this->format())==0; const char*s=strstr(name,ext()); if(!s)return false; if(strlen(s)!=strlen(ext())) return false; return true; } PointCloudIO::Factory* PointCloudIO::instance=0; PointCloudIO* PointCloudIO::Factory::getIO(const char *name, const char *format) { for(int i=0;i<instances.size();++i) if(instances[i]->accept(name,format)) return instances[i]; cerr<<"no appropriate reader or writer for "<<name<<" found"; throw; } //-------------------------------------------------------------------------- //now instances of reader/writers: struct pcio_raw : public PointCloudIO { void read_(vector<mynum> & points ,const char*fname) { struct stat s; if(stat(fname,&s)<0) {throw _EXCEPTION_("couldn't read");} points.resize(s.st_size/sizeof(mynum)); FILE*f=fopen(fname,"rb"); fread(&points[0],sizeof(points[0]),points.size(),f); fclose(f); } void write_(const vector<mynum> & points ,const char*fname) { /* struct stat s; errno=0; int fd=open(fname,O_CREAT|O_RDWR,S_IWRITE|S_IREAD); if(fd<0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw exception("couldn't write");} else { ::write(fd,&points[0],sizeof(points[0])*points.size()); close(fd); } */ FILE *f=fopen(fname,"wb"); if(f==0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw _EXCEPTION_("couldn't write");} else { //Achtung: Dateigroesse bei 64-bit-Version ist groesser als die geschriebenen Daten size_t num=fwrite(&points[0],sizeof(points[0]),points.size(),f); fclose(f); } } const char *ext(){return ".raw";} pcio_raw() { reg(); } } pcio_1; struct pcio_rw2 : public PointCloudIO { //typedef unsigned __int64 tlen; typedef u_int64_t tlen; void read_(vector<mynum> & points ,const char*fname) { FILE*f=fopen(fname,"rb"); if(f==0) { cerr<<"could not open "<<fname<<endl; throw _EXCEPTION_("could not read"); } tlen len; tlen x; fread(&x,sizeof(x),1,f); fread(&len,sizeof(len),1,f); if(x!=sizeof(mynum)){ printf("\n%s: number size=%d bytes != read size=%d bytes\n",fname,(int)x,(int)sizeof(mynum)); throw _EXCEPTION_("number format does not match"); } points.resize(len); size_t nread=fread(&points[0],x,len,f); if(nread!=len){ printf("\n%s: length=%d != read=%d \n",fname,(int)len,(int)nread); throw _EXCEPTION_("could not read full length"); } fclose(f); } void write_(const vector<mynum> & points ,const char*fname) { FILE *f=fopen(fname,"wb"); if(f==0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw _EXCEPTION_("couldn't write");} tlen x=sizeof(mynum); fwrite(&x,sizeof(x),1,f); tlen len=points.size(); fwrite(&len,sizeof(len),1,f); //Achtung: Dateigroesse bei 64-bit-Version ist groesser als die geschriebenen Daten size_t num=fwrite(&points[0],sizeof(points[0]),len,f); fclose(f); } const char *ext(){return ".rw2";} pcio_rw2() { reg(); } } pcio_1_1; struct pcio_asc:public PointCloudIO { void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname); vector<mynum>::const_iterator i; for(i=points.begin();i<points.end();) out <<*(i++)<<' ' <<*(i++)<<' ' <<*(i++)<<endl; } const char*ext(){ return ".asc"; } pcio_asc(){reg();} } pcio_2; struct pcio_gavabvrml:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { char buf[80]; ifstream in(fname); for(;;){ in.getline(buf,79); if(strstr(buf,"point [")!=0) break; if(in.eof())return; } mynum x,y,z; char cc; in.clear(); points.clear(); for(;;){ in>>x>>y>>z; if(in.fail())break; in>>cc; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } const char*ext(){ return ".wrl"; } pcio_gavabvrml(){reg();} } pcio_3; //create the points eually distributed over the surface. struct pcio_gavabvrml_equaldist:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { equaldist eq; char buf[80]; ifstream in(fname); for(;;){ in.getline(buf,79); if(strstr(buf,"point [")!=0) break; if(in.eof())return; } mynum x,y,z; char cc; in.clear(); eq.points.clear(); for(;;){ in>>x>>y>>z; if(in.fail())break; in>>cc; eq.points.push_back(x); eq.points.push_back(y); eq.points.push_back(z); } vector<int> bufidx; in.clear(); for(;;){ in.getline(buf,79); if(strstr(buf,"coordIndex [")!=0) break; if(in.eof())return; } int vidx; for(;;){ in>>vidx; if(in.fail())break; if(vidx>=0) bufidx.push_back(vidx); else { if(bufidx.size()==3) { eq.tris.resize(eq.tris.size()+3); copy(bufidx.begin(),bufidx.end(),eq.tris.end()-3); bufidx.clear(); } else if(bufidx.size()==4) { eq.quads.resize(eq.quads.size()+4); copy(bufidx.begin(),bufidx.end(),eq.quads.end()-4); bufidx.clear(); } else { eq.polygons.push_back(bufidx); bufidx.clear(); } } in>>cc; } in.close(); eq.createEqualDist(points,eq.points.size()/3); } const char*ext(){ return ".wrl"; } const char*format(){ return "equaldist"; } pcio_gavabvrml_equaldist(){reg();} } pcio_3_1; struct pcio_3drma:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname,ios::binary); points.clear(); short int n; assert(sizeof(short int)==2); assert(strstr(fname,".xyz")!=0); assert(sizeof(mynum)>=2); while(!in.eof()) { n=0; in.read((char*)&n,2); if(n==0)continue; int onpt=points.size(); points.resize(points.size()+n*3); //use output vector as read buffer short int*buf=(short int*)&points[onpt]; in.read((char*)buf,n*3*sizeof(short int)); //assign backwards, so you don't overwrite values that are still to be converted for(int i=n*3-1;i>=0;--i) { points[onpt+i]=buf[i]; } } } void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname,ios::binary); short int n; assert(sizeof(short int)==2); static const int nmax=((1<<15)-1); short int buf[1+3*nmax]; buf[0]=(short int)nmax; vector<mynum>::const_iterator it; for(it=points.begin(); points.end()-it >=nmax*3; ) { short int*pts=buf+1, *ptsend=pts+nmax*3; for(;pts!=ptsend;++pts,++it) *pts=(short int)*it; out.write((const char*)buf,sizeof(buf)); } buf[0] = (short int) ((points.end()-it)/3); for(short int*pts=buf+1;it!=points.end();++pts,++it) *pts=(short int)*it; out.write((const char*)&n,sizeof(n)); out.write((const char*)buf,(int(buf[0])*3+1)*sizeof(buf[0])); } const char*ext(){ return ".xyz"; } pcio_3drma(){reg();} } pcio_4; struct pcio_scandump_denker:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); while(!in.eof()) { buf[0]=0; in.getline(buf,80,'\n'); if('A'<=buf[0] && buf[0] <='Z' || buf[0]==0) continue; size_t ps=points.size(); points.resize(points.size()+3); #ifdef GNUCC const char*formatstr="%Lf,%Lf,%Lf"; #else const char*formatstr="%lf,%lf,%lf"; #endif if( sscanf(buf,formatstr, &points[ps],&points[ps+1],&points[ps+2])!=3 ) {cout<<"sth wrong at pos:"<<ps<<":"<<buf<<endl;} } in.close(); } const char*ext(){return ".dump";} pcio_scandump_denker() {reg();} } pcio_5; /* point cloud from zaman with 4 values per row: x,y,z,intensity */ struct pcio_zaman:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x,y,z,v; while(!in.eof()) { in>>x>>y>>z>>v; if(in.fail()) break; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } const char*ext(){ return ".txt"; } const char*format() {return "xyzi";} pcio_zaman(){reg();} } pcio_6; /* point cloud from zaman with 3 values per row: x,y,z */ struct pcio_csv:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x,y,z; while(!in.eof()) { in>>x; in.ignore(1,','); in>>y; in.ignore(1,','); in>>z; if(in.fail()) break; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname); vector<mynum>::const_iterator it; for(it=points.begin(); it!=points.end(); it+=3 ) { out<<it[0]<<','<<it[1]<<','<<it[2]<<'\n'; } } const char*ext(){ return ".csv"; } pcio_csv(){reg();} } pcio_7; /* point cloud from zaman with 4 values per row: x,y,z,intensity */ struct pcio_csv28:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x; while(!in.eof()) { in>>x; if(in.fail()) break; in.ignore(1,','); points.push_back(x); } in.close(); } void write_(const vector<mynum> & points , const char*fname,int n) { ofstream out(fname); assert(points.size()%n==0); out.precision(sizeof(mynum)*2); vector<mynum>::const_iterator it; for(it=points.begin(); it!=points.end(); it+=n ) { out<<it[0]; for(int i=1;i<n;++i) out<<','<<it[i]; out<<"\r\n"; } } void write_(const vector<mynum> & points , const char*fname) { write_(points,fname,28); } const char*ext(){ return ".csv"; } const char*format(){ return "csv28"; } pcio_csv28(){reg();} }pcio_8; //create the points eually distributed over the surface. struct pcio_off_equaldist:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { equaldist eq; char buf[80]; ifstream in(fname); in>>buf; int nverts,nfaces,nedges; in>>nverts>>nfaces>>nedges; mynum x,y,z; char cc; in.clear(); eq.points.clear(); for(int i=0;i<nverts;++i){ in>>x>>y>>z; if(in.fail())break; eq.points.push_back(x); eq.points.push_back(y); eq.points.push_back(z); } in.clear(); int vertsperface; for(int i=0;i<nfaces;++i){ in>>vertsperface; if(vertsperface==3) { int a,b,c; in>>a>>b>>c; eq.tris.push_back(a); eq.tris.push_back(b); eq.tris.push_back(c); } else if(vertsperface==4) { int a,b,c,d; in>>a>>b>>c>>d; eq.tris.push_back(a); eq.tris.push_back(b); eq.tris.push_back(c); eq.tris.push_back(d); } else { eq.polygons.resize(eq.polygons.size()+1); vector<int> &last=eq.polygons.back(); last.resize(vertsperface); for(int i=0;i<vertsperface;++i) { in>>last[i]; } } } in.close(); int npoints=(eq.points.size()/3) *10; if(npoints <1000)npoints= 1000; if(npoints>50000)npoints=50000; eq.createEqualDist(points,npoints); } const char*ext(){ return ".off"; } const char*format(){ return "offequaldist"; } pcio_off_equaldist(){reg();} } pcio_9_1; struct pcio_osg:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { std::ifstream in(fname); osgreadpoints(points,in); in.close(); } void write_(const vector<mynum> & points , const char*fname) { std::ofstream of(fname); osgpointcloud(of ,points); of.close(); } const char*ext(){ return ".osg"; } pcio_osg(){reg();} } pcio_10; #undef _EXCEPTION_
18.101412
108
0.593575
mlangbe
36d7aaf76585cc36ae40b39321d159d3c9ea741f
1,410
cpp
C++
src/icebox/icebox/symbols/map.cpp
IMULMUL/icebox
60586590472d7816645fa1f087b45c1ed08d794b
[ "MIT" ]
null
null
null
src/icebox/icebox/symbols/map.cpp
IMULMUL/icebox
60586590472d7816645fa1f087b45c1ed08d794b
[ "MIT" ]
null
null
null
src/icebox/icebox/symbols/map.cpp
IMULMUL/icebox
60586590472d7816645fa1f087b45c1ed08d794b
[ "MIT" ]
null
null
null
#include "symbols.hpp" #define FDP_MODULE "map" #include "indexer.hpp" #include "interfaces/if_symbols.hpp" #include "log.hpp" #include <fstream> #include <sstream> namespace { bool setup(symbols::Indexer& indexer, const fs::path& filename) { auto filestream = std::ifstream(filename); if(!filestream) return FAIL(false, "unable to open %s", filename.generic_string().data()); auto row = std::string{}; auto offset = uint64_t{}; auto type = char{}; auto symbol = std::string{}; while(std::getline(filestream, row)) { const auto ok = !!(std::istringstream{row} >> std::hex >> offset >> std::dec >> type >> symbol); if(!ok) return FAIL(false, "unable to parse row '%s' in file %s", row.data(), filename.generic_string().data()); indexer.add_symbol(symbol, offset); } return true; } } std::shared_ptr<symbols::Module> symbols::make_map(const std::string& module, const std::string& guid) { const auto* path = getenv("_LINUX_SYMBOL_PATH"); if(!path) return nullptr; const auto indexer = symbols::make_indexer(guid); if(!indexer) return nullptr; const auto ok = setup(*indexer, fs::path(path) / module / guid / "System.map"); if(!ok) return nullptr; indexer->finalize(); return indexer; }
27.115385
120
0.595745
IMULMUL
36d8b3c3a14b9dd41c049f40863c11dad7d88bdf
5,195
cc
C++
slib_physics/source/physx/handler/physx_character_handler.cc
KarlJansson/ecs_game_engine
c76b7379d8ff913cd7773d0a9f55535996abdf35
[ "MIT" ]
1
2018-05-18T10:42:35.000Z
2018-05-18T10:42:35.000Z
slib_physics/source/physx/handler/physx_character_handler.cc
KarlJansson/ecs_game_engine
c76b7379d8ff913cd7773d0a9f55535996abdf35
[ "MIT" ]
null
null
null
slib_physics/source/physx/handler/physx_character_handler.cc
KarlJansson/ecs_game_engine
c76b7379d8ff913cd7773d0a9f55535996abdf35
[ "MIT" ]
null
null
null
#include "physx_character_handler.h" #include "actor.h" #include "camera.h" #include "character.h" #include "entity_manager.h" #include "gui_text.h" #include "transform.h" namespace lib_physics { PhysxCharacterHandler::PhysxCharacterHandler(physx::PxPhysics* phys, physx::PxScene* scene) : physics_(phys) { controller_manager_ = PxCreateControllerManager(*scene); report_callback = std::make_unique<PhysxReportCallback>(); add_callback_ = g_ent_mgr.RegisterAddComponentCallback<Character>( [&](lib_core::Entity ent) { add_character_.push_back(ent); }); remove_callback_ = g_ent_mgr.RegisterRemoveComponentCallback<Character>( [&](lib_core::Entity ent) { remove_character_.push_back(ent); }); } PhysxCharacterHandler::~PhysxCharacterHandler() { controller_manager_->release(); g_ent_mgr.UnregisterAddComponentCallback<Character>(add_callback_); g_ent_mgr.UnregisterRemoveComponentCallback<Character>(remove_callback_); } void PhysxCharacterHandler::UpdateCharacters(float dt) { for (auto& e : add_character_) CreateCharacterController(e); add_character_.clear(); for (auto& e : remove_character_) RemoveCharacterController(e); remove_character_.clear(); auto characters = g_ent_mgr.GetNewCbt<Character>(); if (characters) { float gravity_acc = -9.82f * dt; auto old_characters = g_ent_mgr.GetOldCbt<Character>(); auto char_ents = g_ent_mgr.GetEbt<Character>(); auto char_update = g_ent_mgr.GetNewUbt<Character>(); for (int i = 0; i < char_update->size(); ++i) { if (!(*char_update)[i]) continue; g_ent_mgr.MarkForUpdate<lib_graphics::Camera>(char_ents->at(i)); g_ent_mgr.MarkForUpdate<lib_graphics::Transform>(char_ents->at(i)); auto& c = characters->at(i); auto& old_c = old_characters->at(i); auto character = controllers_[char_ents->at(i)]; if (c.teleport) { character->setPosition( physx::PxExtendedVec3(c.port_loc[0], c.port_loc[1], c.port_loc[2])); c.teleport = false; g_ent_mgr.MarkForUpdate<lib_physics::Character>(char_ents->at(i)); } if (c.resize) { character->resize(c.height); old_c.height = c.height; c.resize = false; } c.vert_velocity = old_c.vert_velocity; c.vert_velocity += gravity_acc * 3.f; if (c.vert_velocity < 0.2f) c.vert_velocity += gravity_acc * 2.5f; c.vert_velocity += c.disp[1]; auto add_position = dt * c.vert_velocity; auto filter = physx::PxControllerFilters(); auto flags = character->move(physx::PxVec3(c.disp[0], add_position, c.disp[2]), 0.001f, dt, filter); c.disp.ZeroMem(); if (flags & physx::PxControllerCollisionFlag::eCOLLISION_UP && c.vert_velocity > 0.f) c.vert_velocity = 0.f; if (flags & physx::PxControllerCollisionFlag::eCOLLISION_DOWN) { c.vert_velocity = 0.f; c.grounded = true; } else { c.grounded = false; } auto pos = character->getPosition(); pos += (character->getPosition() - character->getFootPosition()) * 0.9f; lib_core::Vector3 pos_vec = {float(pos.x), float(pos.y), float(pos.z)}; c.pos = pos_vec; if (c.pos[0] == old_c.pos[0] && c.pos[1] == old_c.pos[1] && c.pos[2] == old_c.pos[2] && c.vert_velocity == old_c.vert_velocity && c.vert_velocity == 0.f) (*char_update)[i] = false; } } } void PhysxCharacterHandler::CreateCharacterController(lib_core::Entity ent) { RemoveCharacterController(ent); auto ent_ptr = g_ent_mgr.GetNewCbeR<Character>(ent); physx::PxCapsuleControllerDesc desc; desc.contactOffset = 0.2f; desc.density = ent_ptr->density; desc.position.x = ent_ptr->pos[0]; desc.position.y = ent_ptr->pos[1]; desc.position.z = ent_ptr->pos[2]; desc.height = ent_ptr->height; desc.radius = ent_ptr->radius; physx::PxMaterial* material = physics_->createMaterial(1.5, 1.5, 1.5); desc.material = material; desc.reportCallback = report_callback.get(); auto controller = controller_manager_->createController(desc); controllers_[ent] = controller; material->release(); } void PhysxCharacterHandler::RemoveCharacterController(lib_core::Entity ent) { if (controllers_.find(ent) != controllers_.end()) { controllers_[ent]->release(); controllers_.erase(ent); } } void PhysxCharacterHandler::PhysxReportCallback::onShapeHit( const physx::PxControllerShapeHit& hit) { auto type = hit.actor->getType(); if (type == physx::PxActorType::eRIGID_DYNAMIC) { auto rigid_dynamic = static_cast<physx::PxRigidDynamic*>(hit.actor); if (rigid_dynamic->getRigidBodyFlags() & physx::PxRigidBodyFlag::eKINEMATIC) return; if (hit.dir.y > -0.5) rigid_dynamic->addForce(hit.dir * hit.length * 10, physx::PxForceMode::eIMPULSE); } } void PhysxCharacterHandler::PhysxReportCallback::onControllerHit( const physx::PxControllersHit& hit) {} void PhysxCharacterHandler::PhysxReportCallback::onObstacleHit( const physx::PxControllerObstacleHit& hit) {} } // namespace lib_physics
34.865772
80
0.673147
KarlJansson
36d90a9d2f205f7dd6d81a633cf19adc4a370e0f
3,217
cpp
C++
inst/tmbTCSAM/src/tmbTCSAM.cpp
wStockhausen/tmbTCSAM02
258a3e28f4a8e26acde34e6bf4c68ccae71a541d
[ "MIT" ]
1
2020-09-12T17:48:09.000Z
2020-09-12T17:48:09.000Z
inst/tmbTCSAM/src/tmbTCSAM.cpp
wStockhausen/tmbTCSAM02
258a3e28f4a8e26acde34e6bf4c68ccae71a541d
[ "MIT" ]
null
null
null
inst/tmbTCSAM/src/tmbTCSAM.cpp
wStockhausen/tmbTCSAM02
258a3e28f4a8e26acde34e6bf4c68ccae71a541d
[ "MIT" ]
null
null
null
#include <TMB.hpp> #include <string> const int DEBUG = 0; #include "../include/tmbTCSAM.hpp" template<class Type> Type objective_function<Type>::operator() () { //get data objects DATA_INTEGER(debug); //flag to print debugging info wtsPRINTSTR_DEBUG("Printing debugging information") DATA_STRUCT(stMC,structModelConfig); if (debug>2) wtsPRINTSTR_DEBUG("structModelConfig:") if (debug>2) wtsPRINTSTRUCT_DEBUG("mc = ",stMC) ModelConfig<Type>* pMC = ModelConfig<Type>::getInstance(stMC); if (debug>3) wtsPRINTSTR_DEBUG("class ModelConfig (testing local pointer):") if (debug>3) std::cout<<(*pMC)<<std::endl; if (debug>4) wtsPRINTSTR_DEBUG("class ModelConfig (testing static instance):") if (debug>4) std::cout<<(*(ModelConfig<Type>::getInstance()))<<std::endl; //for testing if (debug>2) wtsPRINTSTR_DEBUG("Printing testArray_zsmxray information") DATA_ARRAY(testArray_zsmxray); if (debug>2) wtsPRINTVAR_DEBUG("array dim = ",testArray_zsmxray.dim); if (debug>2) wtsPRINTVAR_DEBUG("array mlt = ",testArray_zsmxray.mult); if (debug>2) wtsPRINTVAR_DEBUG("ncols = ",testArray_zsmxray.cols()); if (debug>2) wtsPRINTVAR_DEBUG("nrows = ",testArray_zsmxray.rows()); //for testing vector<int> idx(7);//zsmxray { idx << 0,0,0,0,0,0,0; std::string str = "idx("; str += "0,0,0,0,0,0,0"; str +=")"; int res = calcIndex(idx,ModelConfig<Type>::getInstance()->dims); wtsPRINTVAR_DEBUG(str+" = ",res); Type t = testArray_zsmxray(res); wtsPRINTVAR_DEBUG("t = ",t); } { idx << 0,1,0,0,0,0,0; std::string str = "idx("; str +="0,1,0,0,0,0,0"; str +=")"; int res = calcIndex(idx,ModelConfig<Type>::getInstance()->dims); wtsPRINTVAR_DEBUG(str+" = ",res); Type t = testArray_zsmxray(res); wtsPRINTVAR_DEBUG("t = ",t); } { int idy = pMC->dims[con::iY]-1; idx << 0,0,0,0,0,0,idy; std::string str = "idx(";str+=+"0,0,0,0,0,0,"; str+=std::to_string(idy); str+=")"; int res = calcIndex(idx,ModelConfig<Type>::getInstance()->dims); wtsPRINTVAR_DEBUG(str+" = ",res); Type t = testArray_zsmxray(res); wtsPRINTVAR_DEBUG("t = ",t); } if (debug>20) { wtsPRINTSTR_DEBUG("Printing testArray_zsmxra information"); array<Type> testArray_zsmxra = testArray_zsmxray.col(0); wtsPRINTVAR_DEBUG("array dim = ",testArray_zsmxra.dim); wtsPRINTVAR_DEBUG("array mlt = ",testArray_zsmxra.mult); wtsPRINTVAR_DEBUG("ncols = ",testArray_zsmxra.cols()); wtsPRINTVAR_DEBUG("nrows = ",testArray_zsmxra.rows()); } //get parameter objects PARAMETER(pZ50); //selectivity parameter vector if (debug>1) wtsPRINTVAR_DEBUG("pZ50 = ",pZ50) PARAMETER(pSlp); //selectivity parameter vector if (debug>1) wtsPRINTVAR_DEBUG("pSlp = ",pSlp) //define objective function Type f = 0; //calculate selectivity curve double fZ = 100.0; vector<Type> p(2); p(0) = pZ50; p(1) = pSlp; vector<Type> s = asclogistic(stMC.zBs_z,p,fZ); //report s REPORT(s); //return objective function return f; }
36.146067
90
0.625427
wStockhausen
36da1e360ce0da410eb20da9549f2a2066be0d6d
1,095
cpp
C++
archive/3/metody_nauczania_50.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
archive/3/metody_nauczania_50.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
archive/3/metody_nauczania_50.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef intmax_t I; typedef pair<I, I> II; int main() { cout.sync_with_stdio(false); cin.tie(0); I n, k; cin >> n >> k; vector<I> t(n); for(I i = 0; i < n; ++i) { t[i] = i * 2; //cin >> t[i]; } sort(t.begin(), t.end()); vector<map<I, I>> u(3); for(I i = 0; i < n; ++i) { ++u[0][t[i]]; } for(I j = 1; j < 3; ++j) { for(auto it = u[j - 1].rbegin(); it != u[j - 1].rend(); ++it) { //cout << "'" << it->first << " " << it->second << '\n'; for(I i = 0; i < n; ++i) { u[j][it->first + t[i]] += it->second; } } } /*for(I i = 0; i < 3; ++i) { cout << i << ": "; for(II j : u[i]) { for(I l = 0; l < j.second; ++l) { cout << j.first << ' '; } } cout << '\n'; }*/ I c = 0; for(II p : u[2]) { c += p.second; if(c >= k) { cout << p.first << '\n'; break; } } return 0; }
18.87931
71
0.32968
Aleshkev
36de9c6f31259b37b89d8aecb81b0d5fffcd87c3
1,646
cc
C++
doc/examples/point_index.cc
ClickHouse/s2geometry
471fe9dc931a4bb560333545186e9b5da168ac83
[ "Apache-2.0" ]
null
null
null
doc/examples/point_index.cc
ClickHouse/s2geometry
471fe9dc931a4bb560333545186e9b5da168ac83
[ "Apache-2.0" ]
null
null
null
doc/examples/point_index.cc
ClickHouse/s2geometry
471fe9dc931a4bb560333545186e9b5da168ac83
[ "Apache-2.0" ]
2
2021-08-30T02:45:09.000Z
2022-01-10T11:19:01.000Z
// Copyright 2017 Google Inc. All Rights Reserved. // Author: ericv@google.com (Eric Veach) // // This example shows how to build and query an in-memory index of points // using S2PointIndex. #include <cinttypes> #include <cstdint> #include <cstdio> #include "s2/base/commandlineflags.h" #include "s2/s2earth.h" #include "absl/flags/flag.h" #include "s2/s1chord_angle.h" #include "s2/s2closest_point_query.h" #include "s2/s2point_index.h" #include "s2/s2testing.h" S2_DEFINE_int32(num_index_points, 10000, "Number of points to index"); S2_DEFINE_int32(num_queries, 10000, "Number of queries"); S2_DEFINE_double(query_radius_km, 100, "Query radius in kilometers"); int main(int argc, char **argv) { // Build an index containing random points anywhere on the Earth. S2PointIndex<int> index; for (int i = 0; i < absl::GetFlag(FLAGS_num_index_points); ++i) { index.Add(S2Testing::RandomPoint(), i); } // Create a query to search within the given radius of a target point. S2ClosestPointQuery<int> query(&index); query.mutable_options()->set_max_distance(S1Angle::Radians( S2Earth::KmToRadians(absl::GetFlag(FLAGS_query_radius_km)))); // Repeatedly choose a random target point, and count how many index points // are within the given radius of that point. int64_t num_found = 0; for (int i = 0; i < absl::GetFlag(FLAGS_num_queries); ++i) { S2ClosestPointQuery<int>::PointTarget target(S2Testing::RandomPoint()); num_found += query.FindClosestPoints(&target).size(); } std::printf("Found %" PRId64 " points in %d queries\n", num_found, absl::GetFlag(FLAGS_num_queries)); return 0; }
35.021277
77
0.723572
ClickHouse
36dfdd8a5da413cff936a6d8378abeee3c0d05bc
40,347
cpp
C++
lib/src/payload_adapter_db.cpp
dmarkh/cdbnpp
9f008e348851e7aa3f2a9b53bd4b0e620006909f
[ "MIT" ]
null
null
null
lib/src/payload_adapter_db.cpp
dmarkh/cdbnpp
9f008e348851e7aa3f2a9b53bd4b0e620006909f
[ "MIT" ]
null
null
null
lib/src/payload_adapter_db.cpp
dmarkh/cdbnpp
9f008e348851e7aa3f2a9b53bd4b0e620006909f
[ "MIT" ]
null
null
null
#include "npp/cdb/payload_adapter_db.h" #include <mutex> #include "npp/util/base64.h" #include "npp/util/json_schema.h" #include "npp/util/log.h" #include "npp/util/rng.h" #include "npp/util/util.h" #include "npp/util/uuid.h" #include "npp/cdb/http_client.h" namespace NPP { namespace CDB { using namespace soci; using namespace NPP::Util; std::mutex cdbnpp_db_access_mutex; // protects db calls, as SOCI is not thread-safe PayloadAdapterDb::PayloadAdapterDb() : IPayloadAdapter("db") {} PayloadResults_t PayloadAdapterDb::getPayloads( const std::set<std::string>& paths, const std::vector<std::string>& flavors, const PathToTimeMap_t& maxEntryTimeOverrides, int64_t maxEntryTime, int64_t eventTime, int64_t run, int64_t seq ) { PayloadResults_t res; if ( !ensureMetadata() ) { return res; } std::set<std::string> unfolded_paths{}; for ( const auto& path : paths ) { std::vector<std::string> parts = explode( path, ":" ); std::string flavor = parts.size() == 2 ? parts[0] : ""; std::string unflavored_path = parts.size() == 2 ? parts[1] : parts[0]; if ( mPaths.count(unflavored_path) == 0 ) { for ( const auto& [ key, value ] : mPaths ) { if ( string_starts_with( key, unflavored_path ) && value->mode() > 0 ) { unfolded_paths.insert( ( flavor.size() ? ( flavor + ":" ) : "" ) + key ); } } } else { unfolded_paths.insert( path ); } } for ( const auto& path : unfolded_paths ) { Result<SPayloadPtr_t> rc = getPayload( path, flavors, maxEntryTimeOverrides, maxEntryTime, eventTime, run, seq ); if ( rc.valid() ) { SPayloadPtr_t p = rc.get(); res.insert({ p->directory() + "/" + p->structName(), p }); } } return res; } Result<SPayloadPtr_t> PayloadAdapterDb::getPayload( const std::string& path, const std::vector<std::string>& service_flavors, const PathToTimeMap_t& maxEntryTimeOverrides, int64_t maxEntryTime, int64_t eventTime, int64_t eventRun, int64_t eventSeq ) { Result<SPayloadPtr_t> res; if ( !ensureMetadata() ) { res.setMsg("cannot get metadata"); return res; } if ( !setAccessMode("get") ) { res.setMsg( "cannot switch to GET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure database connection"); return res; } auto [ flavors, directory, structName, is_path_valid ] = Payload::decodePath( path ); if ( !is_path_valid ) { res.setMsg( "request path has not been decoded, path: " + path ); return res; } if ( !service_flavors.size() && !flavors.size() ) { res.setMsg( "no flavor specified, path: " + path ); return res; } if ( !directory.size() ) { res.setMsg( "request does not specify directory, path: " + path ); return res; } if ( !structName.size() ) { res.setMsg( "request does not specify structName, path: " + path ); return res; } std::string dirpath = directory + "/" + structName; // check for path-specific maxEntryTime overrides if ( maxEntryTimeOverrides.size() ) { for ( const auto& [ opath, otime ] : maxEntryTimeOverrides ) { if ( string_starts_with( dirpath, opath ) ) { maxEntryTime = otime; break; } } } // get tag auto tagit = mPaths.find( dirpath ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag for the " + dirpath ); return res; } // get tbname from tag std::string tbname = tagit->second->tbname(), pid = tagit->second->id(); if ( !tbname.size() ) { res.setMsg( "requested path points to the directory, need struct: " + dirpath ); return res; } for ( const auto& flavor : ( flavors.size() ? flavors : service_flavors ) ) { std::string id{""}, uri{""}, fmt{""}; uint64_t bt = 0, et = 0, ct = 0, dt = 0, run = 0, seq = 0, mode = tagit->second->mode(); if ( mode == 2 ) { // fetch id, run, seq { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT id, uri, bt, et, ct, dt, run, seq, fmt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND run = :run " + "AND seq = :seq " + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY ct DESC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventRun, "run" ), use( eventSeq, "seq" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventRun, "run" ), use( eventSeq, "seq" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !id.size() ) { continue; } // nothing found } else if ( mode == 1 ) { // fetch id, bt, et { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT id, uri, bt, et, ct, dt, run, seq, fmt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND bt <= :et AND ( et = 0 OR et > :et ) " + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY bt DESC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventTime, "et" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventTime, "et" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !id.size() ) { continue; } // nothing found if ( et == 0 ) { // if no endTime, do another query to establish endTime { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT bt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND bt >= :et " + "AND ( et = 0 OR et < :et )" + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY bt ASC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(et), use( flavor, "flavor"), use( eventTime, "et" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(et), use( flavor, "flavor"), use( eventTime, "et" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !et ) { et = std::numeric_limits<uint64_t>::max(); } } } // create payload ptr, populate with data auto p = std::make_shared<Payload>( id, pid, flavor, structName, directory, ct, bt, et, dt, run, seq ); p->setURI( uri ); res = p; return res; } return res; } Result<std::string> PayloadAdapterDb::setPayload( const SPayloadPtr_t& payload ) { Result<std::string> res; if ( !payload->ready() ) { res.setMsg( "payload is not ready to be stored" ); return res; } if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata"); return res; } if ( payload->dataSize() && payload->format() != "dat" ) { // validate json against schema if exists Result<std::string> schema = getTagSchema( payload->directory() + "/" + payload->structName() ); if ( schema.valid() ) { Result<bool> rc = validate_json_using_schema( payload->dataAsJson(), schema.get() ); if ( rc.invalid() ) { res.setMsg( "schema validation failed" ); return res; } } } // get tag, fetch tbname auto tagit = mPaths.find( payload->directory() + "/" + payload->structName() ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find payload tag in the database: " + payload->directory() + "/" + payload->structName() ); return res; } std::string tbname = tagit->second->tbname(); sanitize_alnumuscore(tbname); // unpack values for SOCI std::string id = payload->id(), pid = payload->pid(), flavor = payload->flavor(), fmt = payload->format(); int64_t ct = std::time(nullptr), bt = payload->beginTime(), et = payload->endTime(), run = payload->run(), seq = payload->seq(); if ( !setAccessMode("set") ) { res.setMsg( "cannot switch to SET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("db adapter cannot connect to the database"); return res; } // insert iov into cdb_iov_<table-name>, data into cdb_data_<table-name> { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { int64_t dt = 0; transaction tr( *mSession.get() ); if ( !payload->URI().size() && payload->dataSize() ) { // if uri is empty and data is not empty, store data locally to the database size_t data_size = payload->dataSize(); std::string data = base64::encode( payload->data() ); mSession->once << ( "INSERT INTO cdb_data_" + tbname + " ( id, pid, ct, dt, data, size ) VALUES ( :id, :pid, :ct, :dt, :data, :size )" ) ,use(id), use(pid), use(ct), use(dt), use(data), use(data_size); payload->setURI( "db://" + tbname + "/" + id ); } std::string uri = payload->URI(); mSession->once << ( "INSERT INTO cdb_iov_" + tbname + " ( id, pid, flavor, ct, bt, et, dt, run, seq, uri, fmt ) VALUES ( :id, :pid, :flavor, :ct, :bt, :et, :dt, :run, :seq, :uri, :bin )" ) ,use(id), use(pid), use(flavor), use(ct), use(bt), use(et), use(dt), use(run), use(seq), use(uri), use(fmt); tr.commit(); res = id; } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex return res; } Result<std::string> PayloadAdapterDb::deactivatePayload( const SPayloadPtr_t& payload, int64_t deactiveTime ) { Result<std::string> res; if ( !payload->ready() ) { res.setMsg( "payload is not ready to be used for deactivation" ); return res; } if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("db adapter cannot connect to the database"); return res; } // get tag, fetch tbname auto tagit = mPaths.find( payload->directory() + "/" + payload->structName() ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find payload tag in the database: " + payload->directory() + "/" + payload->structName() ); return res; } std::string tbname = tagit->second->tbname(); sanitize_alnumuscore(tbname); std::string id = payload->id(); sanitize_alnumdash(id); { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "UPDATE cdb_iov_" + tbname + " SET dt = :dt WHERE id = :id", use(deactiveTime), use( id ); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } res = id; return res; } Result<SPayloadPtr_t> PayloadAdapterDb::prepareUpload( const std::string& path ) { Result<SPayloadPtr_t> res; // check if Db Adapter is configured for writes if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } auto [ flavors, directory, structName, is_path_valid ] = Payload::decodePath( path ); if ( !flavors.size() ) { res.setMsg( "no flavor provided: " + path ); return res; } if ( !is_path_valid ) { res.setMsg( "bad path provided: " + path ); return res; } // see if path exists in the known tags map auto tagit = mPaths.find( directory + "/" + structName ); if ( tagit == mPaths.end() ) { res.setMsg( "path does not exist in the db. path: " + path ); return res; } // check if path is really a struct if ( !tagit->second->tbname().size() ) { res.setMsg( "cannot upload to the folder, need struct. path: " + path ); return res; } SPayloadPtr_t p = std::make_shared<Payload>(); p->setId( generate_uuid() ); p->setPid( tagit->second->id() ); p->setFlavor( flavors[0] ); p->setDirectory( directory ); p->setStructName( structName ); p->setMode( tagit->second->mode() ); res = p; return res; } Result<bool> PayloadAdapterDb::dropTagSchema( const std::string& tag_path ) { Result<bool> res; if ( !ensureMetadata() ) { res.setMsg("cannot ensure metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg("cannot set ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } // make sure tag_path exists and is a struct std::string sanitized_path = tag_path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != tag_path ) { res.setMsg( "sanitized tag path != input tag path... path: " + sanitized_path ); return res; } std::string tag_pid = ""; auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag path in the database... path: " + sanitized_path ); return res; } tag_pid = (tagit->second)->id(); // find tbname and id for the tag std::string tbname = (tagit->second)->tbname(); if ( !tbname.size() ) { res.setMsg( "tag is not a struct... path: " + sanitized_path ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "DELETE FROM cdb_schemas WHERE pid = :pid", use(tag_pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } res = true; return res; } Result<bool> PayloadAdapterDb::createDatabaseTables() { Result<bool> res; if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "cannot connect to the database" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { transaction tr( *mSession.get() ); // cdb_tags { soci::ddl_type ddl = mSession->create_table("cdb_tags"); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("name", soci::dt_string, 128 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("mode", soci::dt_unsigned_long_long )("not null default 0"); // 0 = tag, 1 = struct bt,et; 2 = struct run,seq ddl.column("tbname", soci::dt_string, 512 )("not null"); ddl.primary_key("cdb_tags_pk", "pid,name,dt"); ddl.unique("cdb_tags_id", "id"); } // cdb_schemas { soci::ddl_type ddl = mSession->create_table("cdb_schemas"); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("null default 0"); ddl.column("data", soci::dt_string )("not null"); ddl.primary_key("cdb_schemas_pk", "pid,dt"); ddl.unique("cdb_schemas_id", "id"); } tr.commit(); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } Result<bool> PayloadAdapterDb::createIOVDataTables( const std::string& tablename, bool create_storage ) { Result<bool> res; if ( !setAccessMode("admin") ) { res.setMsg("cannot get ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } { //RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { transaction tr( *mSession.get() ); // cdb_iov_<tablename> { soci::ddl_type ddl = mSession->create_table("cdb_iov_"+tablename); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("flavor", soci::dt_string, 128 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("bt", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 0 ddl.column("et", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 0 ddl.column("run", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 1 ddl.column("seq", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 1 ddl.column("fmt", soci::dt_string, 36 )("not null"); // see Service::formats() ddl.column("uri", soci::dt_string, 2048 )("not null"); ddl.primary_key("cdb_iov_"+tablename+"_pk", "pid,bt,run,seq,dt,flavor"); ddl.unique("cdb_iov_"+tablename+"_id", "id"); } mSession->once << "CREATE INDEX cdb_iov_" + tablename + "_ct ON cdb_iov_" + tablename + " (ct)"; if ( create_storage ) { // cdb_data_<tablename> { soci::ddl_type ddl = mSession->create_table("cdb_data_"+tablename); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("data", soci::dt_string )("not null"); ddl.column("size", soci::dt_unsigned_long_long )("not null default 0"); ddl.primary_key("cdb_data_"+tablename+"_pk", "id,pid,dt"); ddl.unique("cdb_data_"+tablename+"_id", "id"); } mSession->once << "CREATE INDEX cdb_data_" + tablename + "_pid ON cdb_data_" + tablename + " (pid)"; mSession->once << "CREATE INDEX cdb_data_" + tablename + "_ct ON cdb_data_" + tablename + " (ct)"; } tr.commit(); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } std::vector<std::string> PayloadAdapterDb::listDatabaseTables() { std::vector<std::string> tables; if ( !setAccessMode("admin") ) { return tables; } if ( !ensureConnection() ) { return tables; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string name; soci::statement st = (mSession->prepare_table_names(), into(name)); st.execute(); while (st.fetch()) { tables.push_back( name ); } } catch( std::exception const & e ) { // database exception: " << e.what() tables.clear(); } } // RAII scope block for the db access mutex return tables; } Result<bool> PayloadAdapterDb::dropDatabaseTables() { Result<bool> res; std::vector<std::string> tables = listDatabaseTables(); if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "cannot connect to the database" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { for ( const auto& tbname : tables ) { mSession->drop_table( tbname ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } res = true; } // RAII scope block for the db access mutex return res; } bool PayloadAdapterDb::setAccessMode( const std::string& mode ) { if ( !hasAccess(mode) ) { // cannot set access mode return false; } if ( mAccessMode == mode ) { return true; } mAccessMode = mode; if ( isConnected() ) { return reconnect(); } return true; } void PayloadAdapterDb::disconnect() { if ( !isConnected() ) { return; } { // RAII block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->close(); mIsConnected = false; mDbType = ""; } catch ( std::exception const & e ) { // database exception, e.what() } } // RAII block for the db access mutex } bool PayloadAdapterDb::connect( const std::string& dbtype, const std::string& host, int port, const std::string& user, const std::string& pass, const std::string& dbname, const std::string& options ) { if ( isConnected() ) { disconnect(); } { // RAII block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); if ( mSession == nullptr ) { mSession = std::make_shared<soci::session>(); } std::string connect_string{ dbtype + "://" + ( host.size() ? "host=" + host : "") + ( port > 0 ? " port=" + std::to_string(port) : "" ) + ( user.size() ? " user=" + user : "" ) + ( pass.size() ? " password=" + pass : "" ) + ( dbname.size() ? " dbname=" + dbname : "" ) + ( options.size() ? " " + options : "" ) }; try { mSession->open( connect_string ); } catch ( std::exception const & e ) { // database exception: " << e.what() return false; } mIsConnected = true; mDbType = dbtype; } // RAII scope block for the db access mutex return true; } bool PayloadAdapterDb::reconnect() { if ( !hasAccess( mAccessMode ) ) { return false; } if ( isConnected() ) { disconnect(); } int port{0}; std::string dbtype{}, host{}, user{}, pass{}, dbname{}, options{}; nlohmann::json node; size_t idx = RngS::Instance().random_inclusive<size_t>( 0, mConfig["adapters"]["db"][ mAccessMode ].size() - 1 ); node = mConfig["adapters"]["db"][ mAccessMode ][ idx ]; if ( node.contains("dbtype") ) { dbtype = node["dbtype"]; } if ( node.contains("host") ) { host = node["host"]; } if ( node.contains("port") ) { port = node["port"]; } if ( node.contains("user") ) { user = node["user"]; } if ( node.contains("pass") ) { pass = node["pass"]; } if ( node.contains("dbname") ) { dbname = node["dbname"]; } if ( node.contains("options") ) { options = node["options"]; } return connect( dbtype, host, port, user, pass, dbname, options ); } bool PayloadAdapterDb::ensureMetadata() { return mMetadataAvailable ? true : downloadMetadata(); } bool PayloadAdapterDb::downloadMetadata() { if ( !ensureConnection() ) { return false; } const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); if ( mMetadataAvailable ) { return true; } mTags.clear(); mPaths.clear(); // download tags and populate lookup map: tag ID => Tag obj try { std::string id, name, pid, tbname, schema_id; int64_t ct, dt, mode; soci::indicator ind; statement st = ( mSession->prepare << "SELECT t.id, t.name, t.pid, t.tbname, t.ct, t.dt, t.mode, COALESCE(s.id,'') as schema_id FROM cdb_tags t LEFT JOIN cdb_schemas s ON t.id = s.pid", into(id), into(name), into(pid), into(tbname), into(ct), into(dt), into(mode), into(schema_id, ind) ); st.execute(); while (st.fetch()) { mTags.insert({ id, std::make_shared<Tag>( id, name, pid, tbname, ct, dt, mode, ind == i_ok ? schema_id : "" ) }); } } catch ( std::exception const & e ) { // database exception: " << e.what() return false; } if ( mTags.size() ) { // erase tags that have parent id but no parent exists => side-effect of tag deactivation and/or maxEntryTime // unfortunately, std::erase_if is C++20 container_erase_if( mTags, [this]( const auto item ) { return ( item.second->pid().size() && mTags.find( item.second->pid() ) == mTags.end() ); }); } // parent-child: assign children and parents if ( mTags.size() ) { for ( auto& tag : mTags ) { if ( !(tag.second)->pid().size() ) { continue; } auto rc = mTags.find( ( tag.second )->pid() ); if ( rc == mTags.end() ) { continue; } ( tag.second )->setParent( rc->second ); ( rc->second )->addChild( tag.second ); } // populate lookup map: path => Tag obj for ( const auto& tag : mTags ) { mPaths.insert({ ( tag.second )->path(), tag.second }); } } // TODO: filter mTags and mPaths based on maxEntryTime return true; } Result<std::string> PayloadAdapterDb::createTag( const STagPtr_t& tag ) { return createTag( tag->id(), tag->name(), tag->pid(), tag->tbname(), tag->ct(), tag->dt(), tag->mode() ); } Result<std::string> PayloadAdapterDb::createTag( const std::string& path, int64_t tag_mode ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to database"); return res; } std::string sanitized_path = path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != path ) { res.setMsg( "path contains unwanted characters, path: " + path ); return res; } // check for existing tag if ( mPaths.find( sanitized_path ) != mPaths.end() ) { res.setMsg( "attempt to create an existing tag " + sanitized_path ); return res; } std::string tag_id = uuid_from_str( sanitized_path ), tag_name = "", tag_tbname = "", tag_pid = ""; if ( !tag_id.size() ) { res.setMsg( "new tag uuid generation failed" ); return res; } long long tag_ct = time(0), tag_dt = 0; Tag* parent_tag = nullptr; std::vector<std::string> parts = explode( sanitized_path, '/' ); tag_name = parts.back(); parts.pop_back(); sanitized_path = parts.size() ? implode( parts, "/" ) : ""; if ( sanitized_path.size() ) { auto ptagit = mPaths.find( sanitized_path ); if ( ptagit != mPaths.end() ) { parent_tag = (ptagit->second).get(); tag_pid = parent_tag->id(); } else { res.setMsg( "parent tag does not exist: " + sanitized_path ); return res; } } if ( tag_mode > 0 ) { tag_tbname = ( parent_tag ? parent_tag->path() + "/" + tag_name : tag_name ); std::replace( tag_tbname.begin(), tag_tbname.end(), '/', '_'); string_to_lower_case( tag_tbname ); } return createTag( tag_id, tag_name, tag_pid, tag_tbname, tag_ct, tag_dt, tag_mode ); } Result<std::string> PayloadAdapterDb::deactivateTag( const std::string& path, int64_t deactiveTime ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "db adapter is not configured for writes" ); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to database"); return res; } std::string sanitized_path = path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != path ) { res.setMsg( "path contains unwanted characters, path: " + path ); return res; } // check for existing tag auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find path in the database, path: " + path ); return res; } std::string tag_id = tagit->second->id(); if ( !tag_id.size() ) { res.setMsg( "empty tag id found" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "UPDATE cdb_tags SET dt = :dt WHERE id = :id", use(deactiveTime), use(tag_id); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } res = tag_id; } // RAII scope block for the db access mutex return res; } Result<std::string> PayloadAdapterDb::createTag( const std::string& tag_id, const std::string& tag_name, const std::string& tag_pid, const std::string& tag_tbname, int64_t tag_ct, int64_t tag_dt, int64_t tag_mode ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !tag_id.size() ) { res.setMsg( "cannot create new tag: empty tag id provided" ); return res; } if ( !tag_name.size() ) { res.setMsg( "cannot create new tag: empty tag name provided" ); return res; } if ( tag_pid.size() && mTags.find( tag_pid ) == mTags.end() ) { res.setMsg( "parent tag provided but not found in the map" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "db adapter cannot ensure connection" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); // insert new tag into the database try { mSession->once << "INSERT INTO cdb_tags ( id, name, pid, tbname, ct, dt, mode ) VALUES ( :id, :name, :pid, :tbname, :ct, :dt, :mode ) ", use(tag_id), use(tag_name), use(tag_pid), use(tag_tbname), use(tag_ct), use(tag_dt), use(tag_mode); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex // if it is a struct, create IOV + Data tables if ( tag_tbname.size() ) { Result<bool> rc = createIOVDataTables( tag_tbname ); if ( rc.invalid() ) { res.setMsg( "failed to create IOV Data Tables for tag: " + tag_name + ", tbname: " + tag_tbname ); return res; } } // create new tag object and set parent-child relationship STagPtr_t new_tag = std::make_shared<Tag>( tag_id, tag_name, tag_pid, tag_tbname, tag_ct, tag_dt ); if ( tag_pid.size() ) { STagPtr_t parent_tag = ( mTags.find( tag_pid ) )->second; new_tag->setParent( parent_tag ); parent_tag->addChild( new_tag ); } // add new tag to maps mTags.insert({ tag_id, new_tag }); mPaths.insert({ new_tag->path(), new_tag }); res = tag_id; return res; } std::vector<std::string> PayloadAdapterDb::getTags( bool skipStructs ) { std::vector<std::string> tags; if ( !ensureMetadata() ) { return tags; } if ( !setAccessMode("get") ) { return tags; } if ( !ensureConnection() ) { return tags; } tags.reserve( mPaths.size() ); for ( const auto& [key, value] : mPaths ) { if ( value->mode() == 0 ) { const auto& children = value->children(); if ( children.size() == 0 ) { tags.push_back( "[-] " + key ); } else { bool has_folders = std::find_if( children.begin(), children.end(), []( auto& child ) { return child.second->tbname().size() == 0; } ) != children.end(); if ( has_folders ) { tags.push_back( "[+] " + key ); } else { tags.push_back( "[-] " + key ); } } } else if ( !skipStructs ) { std::string schema = "-"; if ( value->schema().size() ) { schema = "s"; } tags.push_back( "[s/" + schema + "/" + std::to_string( value->mode() ) + "] " + key ); } } return tags; } Result<std::string> PayloadAdapterDb::downloadData( const std::string& uri ) { Result<std::string> res; if ( !uri.size() ) { res.setMsg("empty uri"); return res; } // uri = db://<tablename>/<item-uuid> auto parts = explode( uri, "://" ); if ( parts.size() != 2 || parts[0] != "db" ) { res.setMsg("bad uri"); return res; } if ( !setAccessMode("get") ) { res.setMsg( "db adapter is not configured" ); } if ( !ensureConnection() ) { res.setMsg("cannot ensure database connection"); return res; } auto tbparts = explode( parts[1], "/" ); if ( tbparts.size() != 2 ) { res.setMsg("bad uri tbname"); return res; } std::string storage_name = tbparts[0], id = tbparts[1], data; { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << ("SELECT data FROM cdb_data_" + storage_name + " WHERE id = :id"), into(data), use( id ); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope lock for the db access mutex if ( !data.size() ) { res.setMsg("no data"); return res; } res = base64::decode(data); return res; } Result<std::string> PayloadAdapterDb::getTagSchema( const std::string& tag_path ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg("cannot download metadata"); return res; } if ( !setAccessMode("get") ) { res.setMsg("cannot switch to GET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to the database"); return res; } auto tagit = mPaths.find( tag_path ); if ( tagit == mPaths.end() ) { res.setMsg("cannot find path"); return res; } std::string pid = tagit->second->id(); std::string schema{""}; { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "SELECT data FROM cdb_schemas WHERE pid = :pid ", into(schema), use(pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( schema.size() ) { res = schema; } else { res.setMsg("no schema"); } return res; } Result<std::string> PayloadAdapterDb::exportTagsSchemas( bool tags, bool schemas ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg("cannot download metadata"); return res; } if ( !mTags.size() || !mPaths.size() ) { res.setMsg("no tags, cannot export"); return res; } if ( !tags && !schemas ) { res.setMsg( "neither tags nor schemas were requested for export"); return res; } nlohmann::json output; output["export_type"] = "cdbnpp_tags_schemas"; output["export_timestamp"] = std::time(nullptr); if ( tags ) { output["tags"] = nlohmann::json::array(); } if ( schemas ) { output["schemas"] = nlohmann::json::array(); } for ( const auto& [ key, value ] : mPaths ) { if ( tags ) { output["tags"].push_back( value->toJson() ); } if ( schemas && value->schema().size() ) { Result<std::string> schema_str = getTagSchema( key ); if ( schema_str.valid() ) { output["schemas"].push_back({ { "id", value->schema() }, { "pid", value->id() }, { "path", value->path() }, {"data", schema_str.get() } }); } // cannot get schema for a tag, contact db admin :( } } res = output.dump(2); return res; } Result<bool> PayloadAdapterDb::importTagsSchemas(const std::string& stringified_json ) { Result<bool> res; if ( !stringified_json.size() ) { res.setMsg("empty tag/schema data provided"); return res; } nlohmann::json data = nlohmann::json::parse( stringified_json.begin(), stringified_json.end(), nullptr, false, true ); if ( data.empty() || data.is_discarded() || data.is_null() ) { res.setMsg( "bad input data" ); return res; } bool tag_import_errors = false, schema_import_errors = false; if ( data.contains("tags") ) { for ( const auto& [ key, tag ] : data["tags"].items() ) { Result<std::string> rc = createTag( tag["id"].get<std::string>(), tag["name"].get<std::string>(), tag["pid"].get<std::string>(), tag["tbname"].get<std::string>(), tag["ct"].get<uint64_t>(), tag["dt"].get<uint64_t>(), tag["mode"].get<uint64_t>() ); if ( rc.invalid() ) { tag_import_errors = true; } } } if ( data.contains("schemas") ) { for ( const auto& [ key, schema ] : data["schemas"].items() ) { Result<bool> rc = setTagSchema( schema["path"].get<std::string>(), schema["data"].get<std::string>() ); if ( rc.invalid() ) { schema_import_errors = true; } } } res = !tag_import_errors && !schema_import_errors; return res; } Result<bool> PayloadAdapterDb::setTagSchema( const std::string& tag_path, const std::string& schema_json ) { Result<bool> res; if ( !schema_json.size() ) { res.setMsg( "empty tag schema provided" ); return res; } if ( !ensureMetadata() ) { res.setMsg("cannot ensure metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg("cannot set ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } // make sure tag_path exists and is a struct std::string sanitized_path = tag_path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != tag_path ) { res.setMsg("sanitized tag path != input tag path... path: " + sanitized_path ); return res; } std::string tag_pid = ""; auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag path in the database... path: " + sanitized_path ); return res; } tag_pid = (tagit->second)->id(); // find tbname and id for the tag std::string tbname = (tagit->second)->tbname(); if ( !tbname.size() ) { res.setMsg( "tag is not a struct... path: " + sanitized_path ); return res; } std::string existing_id = ""; { // RAII scope block for the db access schema const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "SELECT id FROM cdb_schemas WHERE pid = :pid ", into(existing_id), use(tag_pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access schema if ( existing_id.size() ) { res.setMsg( "cannot set schema as it already exists for " + sanitized_path ); return res; } // validate schema against schema std::string schema = R"({ "$id": "file://.cdbnpp_config.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "CDBNPP Config File", "type": "object", "required": [ "$id", "$schema", "properties", "required" ], "properties": { "$id": { "type": "string" }, "$schema": { "type": "string" }, "properties": { "type": "object" }, "required": { "type": "array", "items": { "type": "string" } } } })"; Result<bool> rc = validate_json_using_schema( schema_json, schema ); if ( rc.invalid() ) { res.setMsg( "proposed schema is invalid" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); // insert schema into cdb_schemas table try { std::string schema_id = generate_uuid(), data = schema_json; long long ct = 0, dt = 0; mSession->once << "INSERT INTO cdb_schemas ( id, pid, data, ct, dt ) VALUES( :schema_id, :pid, :data, :ct, :dt )", use(schema_id), use(tag_pid), use(data), use(ct), use(dt); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } } // namespace CDB } // namespace NPP
29.493421
192
0.607678
dmarkh
36e01df1d46b2bddb7d044aa15d81da88b418584
20,216
cpp
C++
test/performance-regression/full-apps/graph500-2.1.4/mpi-tuned-2d/mpi/main.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
55
2015-07-28T01:32:58.000Z
2022-02-27T16:27:46.000Z
test/performance-regression/full-apps/graph500-2.1.4/mpi-tuned-2d/mpi/main.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
66
2015-06-15T20:38:19.000Z
2020-08-26T00:11:43.000Z
test/performance-regression/full-apps/graph500-2.1.4/mpi-tuned-2d/mpi/main.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
26
2015-10-26T22:11:51.000Z
2021-03-02T22:09:15.000Z
/* Copyright (C) 2010-2013 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ /* These need to be before any possible inclusions of stdint.h or inttypes.h. * */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include "../generator/make_graph.h" #include "../generator/utils.h" // #include "/home/jewillco/mpe-install/include/mpe.h" #include "common.hpp" #include "bitmap.hpp" #include "onesided.hpp" #include <math.h> #include <mpi.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <stdarg.h> #include <limits.h> #include <stdint.h> #include <inttypes.h> #include <algorithm> #include <execinfo.h> #include <unistd.h> #include <iostream> #include <iomanip> #if defined(CRAYPAT) && 0 #include <pat_api.h> #warning "CrayPAT on" #endif static int compare_doubles(const void* a, const void* b) { double aa = *(const double*)a; double bb = *(const double*)b; return (aa < bb) ? -1 : (aa == bb) ? 0 : 1; } enum {s_minimum, s_firstquartile, s_median, s_thirdquartile, s_maximum, s_mean, s_std, s_LAST}; static void get_statistics(const double x[], int n, double r[s_LAST]) { double temp; /* Compute mean. */ temp = 0.; for (int i = 0; i < n; ++i) temp += x[i]; temp /= n; r[s_mean] = temp; /* Compute std. dev. */ temp = 0.; for (int i = 0; i < n; ++i) temp += (x[i] - r[s_mean]) * (x[i] - r[s_mean]); temp /= double(n - 1); r[s_std] = sqrt(temp); /* Sort x. */ double* xx = (double*)xmalloc(n * sizeof(double)); memcpy(xx, x, n * sizeof(double)); qsort(xx, n, sizeof(double), compare_doubles); /* Get order statistics. */ r[s_minimum] = xx[0]; r[s_firstquartile] = (xx[(n - 1) / 4] + xx[n / 4]) * .5; r[s_median] = (xx[(n - 1) / 2] + xx[n / 2]) * .5; r[s_thirdquartile] = (xx[n - 1 - (n - 1) / 4] + xx[n - 1 - n / 4]) * .5; r[s_maximum] = xx[n - 1]; /* Clean up. */ xfree(xx); } void do_trace(const char* fmt, ...) __attribute__((format(printf, 1, 2))); void do_trace(const char* fmt, ...) { (void)fmt; #if 0 if (rank != 0) return; va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fflush(stderr); void* trace[20]; int len = backtrace(trace, 20), i; fprintf(stderr, "Trace length %d\n", len); for (i = 0; i < len; ++i) fprintf(stderr, "%d: %p\n", i, trace[i]); backtrace_symbols_fd(trace, len, 2); fsync(2); #endif } std::ostream& operator<<(std::ostream& os, const bfs_settings& s) { os << "compression=" << s.compression_level << " nbfs=" << s.nbfs << " keep_queue_stats=" << std::boolalpha << s.keep_queue_stats << " keep_average_level_times=" << s.keep_average_level_times << " official_results=" << s.official_results << " bcast_step_size=" << s.bcast_step_size; return os; } uint_fast32_t seed[5]; // These two are used in common.hpp for graph regen int SCALE; int main(int argc, char** argv) { #ifdef _OPENMP int thr_wanted; #if 0 MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &thr_wanted); if (!(thr_wanted >= MPI_THREAD_SERIALIZED)) { if (rank == 0) { fprintf(stderr, "When compiled with OpenMP, this code requires MPI_THREAD_SERIALIZED\n"); } MPI_Abort(MPI_COMM_WORLD, 50); } #endif MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &thr_wanted); if (!(thr_wanted >= MPI_THREAD_MULTIPLE)) { if (rank == 0) { fprintf(stderr, "When compiled with OpenMP, this code requires MPI_THREAD_MULTIPLE\n"); } MPI_Abort(MPI_COMM_WORLD, 50); } #else MPI_Init(&argc, &argv); #endif #ifdef _OPENMP #pragma omp parallel fprintf(stderr, "%s", ""); // Make sure threads run #endif // MPE_Stop_log(); #if defined(CRAYPAT) && 0 PAT_record(PAT_STATE_OFF); #endif setup_globals(); /* Parse arguments. */ SCALE = 26; int edgefactor = 16; /* nedges / nvertices, i.e., 2*avg. degree */ if (argc >= 2) SCALE = atoi(argv[1]); if (argc >= 3) edgefactor = atoi(argv[2]); if (argc <= 1 || argc >= 4 || SCALE == 0 || edgefactor == 0) { if (rank == 0) { fprintf(stderr, "Usage: %s SCALE edgefactor\n SCALE = log_2(# vertices) [integer, required]\n edgefactor = (# edges) / (# vertices) = .5 * (average vertex degree) [integer, defaults to 16]\n(Random number seed and Kronecker initiator are in main.c)\n", argv[0]); } MPI_Abort(MPI_COMM_WORLD, 1); } uint64_t seed1 = 2, seed2 = 3; tuple_graph tg; tg.nglobaledges = (uint64_t)(edgefactor) << SCALE; uint64_t nglobalverts = (uint64_t)(1) << SCALE; /* Make the raw graph edges. */ /* Get roots for BFS runs, plus maximum vertex with non-zero degree (used by * validator). */ // unsigned int num_bfs_roots = 64; unsigned int num_bfs_roots = 3; do_trace("Before graph_generation\n"); double make_graph_start = MPI_Wtime(); scoped_array<uint64_t> bfs_roots; uint64_t max_used_vertex = 0; { /* Spread the two 64-bit numbers into five nonzero values in the correct * range. */ make_mrg_seed(seed1, seed2, seed); /* Generate the graph. */ size_t block_limit = size_t(DIV_SIZE((tg.nglobaledges + size * FILE_CHUNKSIZE - 1) / FILE_CHUNKSIZE)); tg.edgememory.reset_to_new(block_limit); for (size_t block_idx = 0; block_idx < block_limit; ++block_idx) { if (rank == 0) fprintf(stderr, "%d: Generating block %d of %d\n", rank, (int)block_idx, (int)block_limit); uint64_t start_edge_index = (std::min)(uint64_t(FILE_CHUNKSIZE) * (MUL_SIZE(block_idx) + rank), tg.nglobaledges); size_t edge_count = size_t((std::min)(tg.nglobaledges - start_edge_index, uint64_t(FILE_CHUNKSIZE))); assert (start_edge_index <= tg.nglobaledges); assert (edge_count <= size_t(FILE_CHUNKSIZE)); scoped_array<packed_edge>& buf = tg.edgememory[block_idx]; buf.reset_to_new(edge_count); generate_kronecker_range(seed, SCALE, start_edge_index, start_edge_index + edge_count, buf.get(0, edge_count)); } /* Find root vertices and the largest vertex number with incident edges. * We first generate a larger number of candidate roots, then scan the * edges to find which of them have incident edges. Hopefully enough do; * otherwise, we need to iterate until we find them. */ do_trace("Before finding roots\n"); { const unsigned int candidates_to_scan_per_iter = 4 * num_bfs_roots; bfs_roots.reset_to_new(num_bfs_roots); unsigned int bfs_root_idx = 0; scoped_array<uint64_t> candidate_roots; candidate_roots.reset_to_new(candidates_to_scan_per_iter); scoped_array<int> candidate_root_marks; candidate_root_marks.reset_to_new(candidates_to_scan_per_iter); unsigned int pass_num = 0; while (bfs_root_idx < (unsigned int)(num_bfs_roots)) { ++pass_num; if (rank == 0) fprintf(stderr, "Finding roots, pass %u\n", pass_num); for (unsigned int i = 0; i < candidates_to_scan_per_iter; ++i) { double d[2]; make_random_numbers(2, seed1, seed2, 2 * (pass_num * candidates_to_scan_per_iter + i), d); uint64_t root = uint64_t((d[0] + d[1]) * double(nglobalverts)) % nglobalverts; assert (root < nglobalverts); candidate_roots[i] = root; candidate_root_marks[i] = 0; } ITERATE_TUPLE_GRAPH_BEGIN(&tg, edgebuf, edgebuf_size) { if (rank == 0) fprintf(stderr, "Block %zu of %zu\n", size_t(ITERATE_TUPLE_GRAPH_BLOCK_NUMBER), size_t(ITERATE_TUPLE_GRAPH_BLOCK_COUNT(&tg))); // Global max code from http://www.openmp.org/pipermail/omp/2005/000257.html #pragma omp parallel { uint64_t my_max_used_vertex = max_used_vertex; #pragma omp for for (ptrdiff_t i = 0; i < edgebuf_size; ++i) { uint64_t src = uint64_t(get_v0_from_edge(&edgebuf[i])); uint64_t tgt = uint64_t(get_v1_from_edge(&edgebuf[i])); if (src == tgt) continue; for (unsigned int j = 0; j < candidates_to_scan_per_iter; ++j) { if (candidate_roots[j] == src || candidate_roots[j] == tgt) { #pragma omp atomic candidate_root_marks[j] |= true; } if (src > my_max_used_vertex) { my_max_used_vertex = src; } if (tgt > my_max_used_vertex) { my_max_used_vertex = tgt; } } } #pragma omp critical { if (my_max_used_vertex > max_used_vertex) max_used_vertex = my_max_used_vertex; } } } ITERATE_TUPLE_GRAPH_END; MPI_Allreduce(MPI_IN_PLACE, candidate_root_marks.get(0, candidates_to_scan_per_iter), candidates_to_scan_per_iter, MPI_INT, MPI_LOR, MPI_COMM_WORLD); MPI_Allreduce(MPI_IN_PLACE, &max_used_vertex, 1, MPI_UINT64_T, MPI_MAX, MPI_COMM_WORLD); /* This control flow is common to all nodes. */ for (unsigned int i = 0; i < candidates_to_scan_per_iter; ++i) { if (candidate_root_marks[i] == 1) { bool is_duplicate = false; for (unsigned int j = 0; j < bfs_root_idx; ++j) { if (candidate_roots[i] == bfs_roots[j]) { is_duplicate = true; break; } } if (!is_duplicate) { bfs_roots[bfs_root_idx++] = candidate_roots[i]; if (bfs_root_idx >= (unsigned int)(num_bfs_roots)) break; } } } } } } double make_graph_stop = MPI_Wtime(); double make_graph_time = make_graph_stop - make_graph_start; if (rank == 0) { /* Not an official part of the results */ fprintf(stderr, "graph_generation: %f s\n", make_graph_time); } do_trace("After graph_generation\n"); // int begin_bfs_event = MPE_Log_get_event_number(); // int end_bfs_event = MPE_Log_get_event_number(); // if (rank == 0) MPE_Describe_state(begin_bfs_event, end_bfs_event, "BFS", "red"); /* Make user's graph data structure. */ double data_struct_start = MPI_Wtime(); make_graph_data_structure(&tg); double data_struct_stop = MPI_Wtime(); double data_struct_time = data_struct_stop - data_struct_start; if (rank == 0) { /* Not an official part of the results */ fprintf(stderr, "construction_time: %f s\n", data_struct_time); } do_trace("After user graph data structure construction\n"); tg.edgememory.reset(); do_trace("After cleanup\n"); /* Number of edges visited in each BFS; a double so get_statistics can be * used directly. */ double* edge_counts = (double*)xmalloc(num_bfs_roots * sizeof(double)); /* Run BFS. */ int validation_passed = 1; double* bfs_times = (double*)xmalloc(num_bfs_roots * sizeof(double)); double* validate_times = (double*)xmalloc(num_bfs_roots * sizeof(double)); uint64_t nlocalverts = get_nlocalverts_for_pred(); assert (nlocalverts * sizeof(int64_t) <= SIZE_MAX); memalloc("pred", size_t(nlocalverts) * sizeof(int64_t)); int64_t* pred = (int64_t*)xMPI_Alloc_mem(size_t(nlocalverts) * sizeof(int64_t)); // const int default_bcast_step_size = 8; const bfs_settings settings[] = { // {2, num_bfs_roots, false, false, true, default_bcast_step_size}, {3, num_bfs_roots, false, true, false, 4} /* , {3, 1, false, true, false, 6}, {3, 1, false, true, false, 8}, {3, 1, false, true, false, 12}, {3, 1, false, true, false, 16}, {3, 1, false, true, false, 24}, {3, 1, false, true, false, 32}, {3, 1, false, true, false, 48}, {3, 1, false, true, false, 64}, {3, 1, false, true, false, 96}, {3, 1, false, true, false, 128}, {3, 1, false, true, false, 192}, {3, 1, false, true, false, 256}, {3, num_bfs_roots, false, false, true, -1}, {3, 1, true, true, false, -1}, */ // {2, 1, false, false, false, -1}, // {1, 1, false, true, false, -1}, // {0, 1, false, true, false, -1}, }; bfs_settings best_settings = settings[0]; double best_teps = 0.; for (size_t i = 0; i < sizeof(settings) / sizeof(*settings); ++i) { bfs_settings s = settings[i]; if (s.nbfs > (size_t)num_bfs_roots) { if (rank == 0) fprintf(stderr, "Root count %zu in settings too large for %u generated roots\n", s.nbfs, num_bfs_roots); MPI_Abort(MPI_COMM_WORLD, 1); } if (s.bcast_step_size == -1) s.bcast_step_size = best_settings.bcast_step_size; for (int bfs_root_idx = 0; bfs_root_idx < (int)s.nbfs; ++bfs_root_idx) { int64_t root = bfs_roots[bfs_root_idx]; if (rank == 0) fprintf(stderr, "Running settings %d BFS %d\n", (int)i, bfs_root_idx); /* Clear the pred array. */ memset(pred, 0, size_t(nlocalverts) * sizeof(int64_t)); do_trace("Before BFS %d\n", bfs_root_idx); /* Do the actual BFS. */ // MPE_Start_log(); // MPE_Log_event(begin_bfs_event, 0, "Start of BFS"); MPI_Barrier(MPI_COMM_WORLD); #if defined(CRAYPAT) && 0 if (s.official_results) PAT_record(PAT_STATE_ON); #endif double bfs_start = MPI_Wtime(); run_bfs(root, &pred[0], s); MPI_Barrier(MPI_COMM_WORLD); // MPE_Stop_log(); // MPE_Log_event(end_bfs_event, 0, "End of BFS"); double bfs_stop = MPI_Wtime(); #if defined(CRAYPAT) && 0 if (s.official_results) PAT_record(PAT_STATE_OFF); #endif bfs_times[bfs_root_idx] = bfs_stop - bfs_start; if (rank == 0) fprintf(stderr, "Time for BFS %d is %f\n", bfs_root_idx, bfs_times[bfs_root_idx]); do_trace("After BFS %d\n", bfs_root_idx); #if 1 /* Validate result. */ if (rank == 0) fprintf(stderr, "Validating BFS %d\n", bfs_root_idx); double validate_start = MPI_Wtime(); int64_t edge_visit_count; // fprintf(stderr, "%d: validate_bfs_result(nglobalverts = %" PRId64 ", nlocalverts = %" PRIu64 ", root = %" PRId64 ")\n", rank, max_used_vertex + 1, nlocalverts, root); int validation_passed_one = validate_bfs_result(&tg, max_used_vertex + 1, size_t(nlocalverts), root, pred, &edge_visit_count); double validate_stop = MPI_Wtime(); do_trace("After validating BFS %d\n", bfs_root_idx); validate_times[bfs_root_idx] = validate_stop - validate_start; if (rank == 0) fprintf(stderr, "Validate time for BFS %d is %f\n", bfs_root_idx, validate_times[bfs_root_idx]); edge_counts[bfs_root_idx] = (double)edge_visit_count; if (rank == 0) { std::cerr << "Settings: " << s << std::endl; fprintf(stderr, "TEPS for BFS %d is %g\n", bfs_root_idx, double(edge_visit_count) / bfs_times[bfs_root_idx]); } if (!validation_passed_one) { validation_passed = 0; if (rank == 0) fprintf(stderr, "Validation failed for this BFS root; aborting.\n"); abort(); } #endif if (double(edge_visit_count) / bfs_times[bfs_root_idx] > best_teps) { best_settings = s; best_teps = double(edge_visit_count) / bfs_times[bfs_root_idx]; } } /* Print results. */ if (rank == 0 && s.official_results) { if (!validation_passed) { fprintf(stdout, "No results printed for invalid run.\n"); } else { fprintf(stdout, "compression_level: %d\n", (int)s.compression_level); fprintf(stdout, "SCALE: %d\n", SCALE); fprintf(stdout, "edgefactor: %d\n", edgefactor); fprintf(stdout, "NBFS: %zu\n", s.nbfs); fprintf(stdout, "graph_generation: %g\n", make_graph_time); fprintf(stdout, "num_mpi_processes: %d\n", size); fprintf(stdout, "construction_time: %g\n", data_struct_time); double stats[s_LAST]; get_statistics(bfs_times, s.nbfs, stats); fprintf(stdout, "min_time: %g\n", stats[s_minimum]); fprintf(stdout, "firstquartile_time: %g\n", stats[s_firstquartile]); fprintf(stdout, "median_time: %g\n", stats[s_median]); fprintf(stdout, "thirdquartile_time: %g\n", stats[s_thirdquartile]); fprintf(stdout, "max_time: %g\n", stats[s_maximum]); fprintf(stdout, "mean_time: %g\n", stats[s_mean]); fprintf(stdout, "stddev_time: %g\n", stats[s_std]); get_statistics(edge_counts, s.nbfs, stats); fprintf(stdout, "min_nedge: %.11g\n", stats[s_minimum]); fprintf(stdout, "firstquartile_nedge: %.11g\n", stats[s_firstquartile]); fprintf(stdout, "median_nedge: %.11g\n", stats[s_median]); fprintf(stdout, "thirdquartile_nedge: %.11g\n", stats[s_thirdquartile]); fprintf(stdout, "max_nedge: %.11g\n", stats[s_maximum]); fprintf(stdout, "mean_nedge: %.11g\n", stats[s_mean]); fprintf(stdout, "stddev_nedge: %.11g\n", stats[s_std]); double* secs_per_edge = (double*)xmalloc(s.nbfs * sizeof(double)); for (size_t i = 0; i < s.nbfs; ++i) secs_per_edge[i] = bfs_times[i] / edge_counts[i]; get_statistics(secs_per_edge, s.nbfs, stats); fprintf(stdout, "min_TEPS: %g\n", 1. / stats[s_maximum]); fprintf(stdout, "firstquartile_TEPS: %g\n", 1. / stats[s_thirdquartile]); fprintf(stdout, "median_TEPS: %g\n", 1. / stats[s_median]); fprintf(stdout, "thirdquartile_TEPS: %g\n", 1. / stats[s_firstquartile]); fprintf(stdout, "max_TEPS: %g\n", 1. / stats[s_minimum]); fprintf(stdout, "harmonic_mean_TEPS: %g\n", 1. / stats[s_mean]); /* Formula from: * Title: The Standard Errors of the Geometric and Harmonic Means and * Their Application to Index Numbers * Author(s): Nilan Norris * Source: The Annals of Mathematical Statistics, Vol. 11, No. 4 (Dec., 1940), pp. 445-448 * Publisher(s): Institute of Mathematical Statistics * Stable URL: http://www.jstor.org/stable/2235723 * (same source as in specification). */ fprintf(stdout, "harmonic_stddev_TEPS: %g\n", stats[s_std] / (stats[s_mean] * stats[s_mean] * sqrt(s.nbfs - 1))); xfree(secs_per_edge); secs_per_edge = NULL; get_statistics(validate_times, s.nbfs, stats); fprintf(stdout, "min_validate: %g\n", stats[s_minimum]); fprintf(stdout, "firstquartile_validate: %g\n", stats[s_firstquartile]); fprintf(stdout, "median_validate: %g\n", stats[s_median]); fprintf(stdout, "thirdquartile_validate: %g\n", stats[s_thirdquartile]); fprintf(stdout, "max_validate: %g\n", stats[s_maximum]); fprintf(stdout, "mean_validate: %g\n", stats[s_mean]); fprintf(stdout, "stddev_validate: %g\n", stats[s_std]); #if 0 for (int i = 0; i < s.nbfs; ++i) { fprintf(stdout, "Run %3d: %g s, validation %g s\n", i + 1, bfs_times[i], validate_times[i]); } #endif fprintf(stdout, "\n"); } } } memfree("pred", size_t(nlocalverts) * sizeof(int64_t)); xfree(edge_counts); edge_counts = NULL; xMPI_Free_mem(pred); bfs_roots.reset(); free_graph_data_structure(); xfree(bfs_times); xfree(validate_times); cleanup_globals(); MPI_Finalize(); return 0; }
41.596708
284
0.608281
JKChenFZ
36e06e4f6d47893031c9ff684f6b947afa6c7565
6,808
cc
C++
CalibTracker/SiStripCommon/plugins/ShallowSimhitClustersProducer.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2020-05-09T16:03:43.000Z
2020-05-09T16:03:50.000Z
CalibTracker/SiStripCommon/plugins/ShallowSimhitClustersProducer.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
26
2018-10-30T12:47:58.000Z
2022-03-29T08:39:00.000Z
CalibTracker/SiStripCommon/plugins/ShallowSimhitClustersProducer.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
3
2019-03-09T13:06:43.000Z
2020-07-03T00:47:30.000Z
#include "CalibTracker/SiStripCommon/interface/ShallowSimhitClustersProducer.h" #include "CalibTracker/SiStripCommon/interface/ShallowTools.h" #include "DataFormats/SiStripCluster/interface/SiStripCluster.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "CondFormats/SiStripObjects/interface/SiStripLorentzAngle.h" #include "CondFormats/DataRecord/interface/SiStripLorentzAngleRcd.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" #include "Geometry/CommonTopologies/interface/StripTopology.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" ShallowSimhitClustersProducer::ShallowSimhitClustersProducer(const edm::ParameterSet& iConfig) : clusters_token_(consumes<edmNew::DetSetVector<SiStripCluster>>(iConfig.getParameter<edm::InputTag>("Clusters"))), Prefix(iConfig.getParameter<std::string>("Prefix")), runningmode_(iConfig.getParameter<std::string>("runningMode")) { std::vector<edm::InputTag> simhits_tags = iConfig.getParameter<std::vector<edm::InputTag>>("InputTags"); for (auto itag : simhits_tags) { simhits_tokens_.push_back(consumes<std::vector<PSimHit>>(itag)); } produces<std::vector<unsigned>>(Prefix + "hits"); produces<std::vector<float>>(Prefix + "strip"); produces<std::vector<float>>(Prefix + "localtheta"); produces<std::vector<float>>(Prefix + "localphi"); produces<std::vector<float>>(Prefix + "localx"); produces<std::vector<float>>(Prefix + "localy"); produces<std::vector<float>>(Prefix + "localz"); produces<std::vector<float>>(Prefix + "momentum"); produces<std::vector<float>>(Prefix + "energyloss"); produces<std::vector<float>>(Prefix + "time"); produces<std::vector<int>>(Prefix + "particle"); produces<std::vector<unsigned short>>(Prefix + "process"); } void ShallowSimhitClustersProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { shallow::CLUSTERMAP clustermap = shallow::make_cluster_map(iEvent, clusters_token_); int size = clustermap.size(); auto hits = std::make_unique<std::vector<unsigned>>(size, 0); auto strip = std::make_unique<std::vector<float>>(size, -100); auto localtheta = std::make_unique<std::vector<float>>(size, -100); auto localphi = std::make_unique<std::vector<float>>(size, -100); auto localx = std::make_unique<std::vector<float>>(size, -100); auto localy = std::make_unique<std::vector<float>>(size, -100); auto localz = std::make_unique<std::vector<float>>(size, -100); auto momentum = std::make_unique<std::vector<float>>(size, 0); auto energyloss = std::make_unique<std::vector<float>>(size, -1); auto time = std::make_unique<std::vector<float>>(size, -1); auto particle = std::make_unique<std::vector<int>>(size, -500); auto process = std::make_unique<std::vector<unsigned short>>(size, 0); edm::ESHandle<TrackerGeometry> theTrackerGeometry; iSetup.get<TrackerDigiGeometryRecord>().get(theTrackerGeometry); edm::ESHandle<MagneticField> magfield; iSetup.get<IdealMagneticFieldRecord>().get(magfield); edm::ESHandle<SiStripLorentzAngle> SiStripLorentzAngle; iSetup.get<SiStripLorentzAngleRcd>().get(runningmode_, SiStripLorentzAngle); edm::Handle<edmNew::DetSetVector<SiStripCluster>> clusters; iEvent.getByLabel("siStripClusters", "", clusters); for (auto& simhit_token : simhits_tokens_) { edm::Handle<std::vector<PSimHit>> simhits; iEvent.getByToken(simhit_token, simhits); for (auto const& hit : *simhits) { const uint32_t id = hit.detUnitId(); const StripGeomDetUnit* theStripDet = dynamic_cast<const StripGeomDetUnit*>(theTrackerGeometry->idToDet(id)); const LocalVector drift = shallow::drift(theStripDet, *magfield, *SiStripLorentzAngle); const float driftedstrip_ = theStripDet->specificTopology().strip(hit.localPosition() + 0.5 * drift); const float hitstrip_ = theStripDet->specificTopology().strip(hit.localPosition()); shallow::CLUSTERMAP::const_iterator cluster = match_cluster(id, driftedstrip_, clustermap, *clusters); if (cluster != clustermap.end()) { unsigned i = cluster->second; hits->at(i) += 1; if (hits->at(i) == 1) { strip->at(i) = hitstrip_; localtheta->at(i) = hit.thetaAtEntry(); localphi->at(i) = hit.phiAtEntry(); localx->at(i) = hit.localPosition().x(); localy->at(i) = hit.localPosition().y(); localz->at(i) = hit.localPosition().z(); momentum->at(i) = hit.pabs(); energyloss->at(i) = hit.energyLoss(); time->at(i) = hit.timeOfFlight(); particle->at(i) = hit.particleType(); process->at(i) = hit.processType(); } } } } iEvent.put(std::move(hits), Prefix + "hits"); iEvent.put(std::move(strip), Prefix + "strip"); iEvent.put(std::move(localtheta), Prefix + "localtheta"); iEvent.put(std::move(localphi), Prefix + "localphi"); iEvent.put(std::move(localx), Prefix + "localx"); iEvent.put(std::move(localy), Prefix + "localy"); iEvent.put(std::move(localz), Prefix + "localz"); iEvent.put(std::move(momentum), Prefix + "momentum"); iEvent.put(std::move(energyloss), Prefix + "energyloss"); iEvent.put(std::move(time), Prefix + "time"); iEvent.put(std::move(particle), Prefix + "particle"); iEvent.put(std::move(process), Prefix + "process"); } shallow::CLUSTERMAP::const_iterator ShallowSimhitClustersProducer::match_cluster( const unsigned& id, const float& strip_, const shallow::CLUSTERMAP& clustermap, const edmNew::DetSetVector<SiStripCluster>& clusters) const { shallow::CLUSTERMAP::const_iterator cluster = clustermap.end(); edmNew::DetSetVector<SiStripCluster>::const_iterator clustersDetSet = clusters.find(id); if (clustersDetSet != clusters.end()) { edmNew::DetSet<SiStripCluster>::const_iterator left, right = clustersDetSet->begin(); while (right != clustersDetSet->end() && strip_ > right->barycenter()) right++; left = right - 1; if (right != clustersDetSet->end() && right != clustersDetSet->begin()) { unsigned firstStrip = (right->barycenter() - strip_) < (strip_ - left->barycenter()) ? right->firstStrip() : left->firstStrip(); cluster = clustermap.find(std::make_pair(id, firstStrip)); } else if (right != clustersDetSet->begin()) cluster = clustermap.find(std::make_pair(id, left->firstStrip())); else cluster = clustermap.find(std::make_pair(id, right->firstStrip())); } return cluster; }
50.058824
119
0.706522
NTrevisani
36e620388180ad0ab7afe89498544e17c16012a9
24,455
cc
C++
src/hooks/dhcp/high_availability/tests/query_filter_unittest.cc
mcr/kea
7fbbfde2a0742a3d579d51ec94fc9b91687fb901
[ "Apache-2.0" ]
1
2019-08-10T21:52:58.000Z
2019-08-10T21:52:58.000Z
src/hooks/dhcp/high_availability/tests/query_filter_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
null
null
null
src/hooks/dhcp/high_availability/tests/query_filter_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <ha_test.h> #include <ha_config.h> #include <ha_config_parser.h> #include <query_filter.h> #include <cc/data.h> #include <exceptions/exceptions.h> #include <dhcp/dhcp4.h> #include <dhcp/dhcp6.h> #include <dhcp/hwaddr.h> #include <cstdint> #include <string> using namespace isc; using namespace isc::data; using namespace isc::dhcp; using namespace isc::ha; using namespace isc::ha::test; namespace { /// @brief Test fixture class for @c QueryFilter class. using QueryFilterTest = HATest; // This test verifies the case when load balancing is enabled and // this server is primary. TEST_F(QueryFilterTest, loadBalancingThisPrimary) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // By default the server1 should serve its own scope only. The // server2 should serve its scope. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query4, scope_class)) { ASSERT_EQ("HA_server1", scope_class); ASSERT_NE(scope_class, "HA_server2"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In the failover case, the server1 should also take responsibility for // the server2's queries. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query mist be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } // However, the one that lacks HW address and client id should be out of // scope. Pkt4Ptr query4(new Pkt4(DHCPDISCOVER, 1234)); EXPECT_FALSE(filter.inScope(query4, scope_class)); } // This test verifies that client identifier is used for load balancing. TEST_F(QueryFilterTest, loadBalancingClientIdThisPrimary) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // By default the server1 should serve its own scope only. The // server2 should serve its scope. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Fixed HW address used in tests. std::vector<uint8_t> hw_address(HWAddr::ETHERNET_HWADDR_LEN); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random client identifier. Pkt4Ptr query4 = createQuery4(hw_address, randomKey(8)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query4, scope_class)) { ASSERT_EQ("HA_server1", scope_class); ASSERT_NE(scope_class, "HA_server2"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In the failover case, the server1 should also take responsibility for // the server2's queries. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random client identifier. Pkt4Ptr query4 = createQuery4(hw_address, randomKey(8)); // Every single query mist be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } } // This test verifies the case when load balancing is enabled and // this server is secondary. TEST_F(QueryFilterTest, loadBalancingThisSecondary) { HAConfigPtr config = createValidConfiguration(); // We're now a secondary server. config->setThisServerName("server2"); QueryFilter filter(config); // By default the server2 should serve its own scope only. The // server1 should serve its scope. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query4, scope_class)) { ASSERT_EQ("HA_server2", scope_class); ASSERT_NE(scope_class, "HA_server1"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In this scenario, the server1 died, so the server2 should now serve // both scopes. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } } // This test verifies the case when load balancing is enabled and // this server is backup. /// @todo Expand these tests once we implement the actual load balancing to /// verify which packets are in scope. TEST_F(QueryFilterTest, loadBalancingThisBackup) { HAConfigPtr config = createValidConfiguration(); config->setThisServerName("server3"); QueryFilter filter(config); // The backup server doesn't handle any DHCP traffic by default. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // None of the packets should be handlded by the backup server. ASSERT_FALSE(filter.inScope(query4, scope_class)); } // Simulate failover. Although, backup server never starts handling // other server's traffic automatically, it can be manually instructed // to do so. This simulates such scenario. filter.serveFailoverScopes(); // The backup server now handles traffic of server 1 and server 2. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } } // This test verifies the case when hot-standby is enabled and this // server is primary. TEST_F(QueryFilterTest, hotStandbyThisPrimary) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); QueryFilter filter(config); Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66"); // By default, only the primary server is active. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; // It should process its queries. EXPECT_TRUE(filter.inScope(query4, scope_class)); // Simulate failover scenario, in which the active server detects a // failure of the standby server. This doesn't change anything in how // the traffic is distributed. filter.serveFailoverScopes(); // The server1 continues to process its own traffic. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query4, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies the case when hot-standby is enabled and this // server is standby. TEST_F(QueryFilterTest, hotStandbyThisSecondary) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); config->setThisServerName("server2"); QueryFilter filter(config); Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66"); // The server2 doesn't process any queries by default. The whole // traffic is processed by the server1. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; EXPECT_FALSE(filter.inScope(query4, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); // Simulate failover case whereby the standby server detects a // failure of the active server. filter.serveFailoverScopes(); // The server2 now handles the traffic normally handled by the // server1. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query4, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies the case when hot-standby is enabled and this // server is backup. TEST_F(QueryFilterTest, hotStandbyThisBackup) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); config->setThisServerName("server3"); QueryFilter filter(config); Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66"); // By default the backup server doesn't process any traffic. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; EXPECT_FALSE(filter.inScope(query4, scope_class)); // Simulate failover. Although, backup server never starts handling // other server's traffic automatically, it can be manually instructed // to do so. This simulates such scenario. filter.serveFailoverScopes(); // The backup server now handles the entire traffic, i.e. the traffic // that the primary server handles. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query4, scope_class)); } // This test verifies the case when load balancing is enabled and // this DHCPv6 server is primary. TEST_F(QueryFilterTest, loadBalancingThisPrimary6) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // By default the server1 should serve its own scope only. The // server2 should serve its scope. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random DUID. Pkt6Ptr query6 = createQuery6(randomKey(10)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query6, scope_class)) { ASSERT_EQ("HA_server1", scope_class); ASSERT_NE(scope_class, "HA_server2"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In the failover case, the server1 should also take responsibility for // the server2's queries. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // Every single query mist be in scope. ASSERT_TRUE(filter.inScope(query6, scope_class)); } // However, the one that lacks DUID should be out of scope. Pkt6Ptr query6(new Pkt6(DHCPV6_SOLICIT, 1234)); EXPECT_FALSE(filter.inScope(query6, scope_class)); } // This test verifies the case when load balancing is enabled and // this server is secondary. TEST_F(QueryFilterTest, loadBalancingThisSecondary6) { HAConfigPtr config = createValidConfiguration(); // We're now a secondary server. config->setThisServerName("server2"); QueryFilter filter(config); // By default the server2 should serve its own scope only. The // server1 should serve its scope. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query6, scope_class)) { ASSERT_EQ("HA_server2", scope_class); ASSERT_NE(scope_class, "HA_server1"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In this scenario, the server1 died, so the server2 should now serve // both scopes. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query6, scope_class)); } } // This test verifies the case when load balancing is enabled and // this server is backup. /// @todo Expand these tests once we implement the actual load balancing to /// verify which packets are in scope. TEST_F(QueryFilterTest, loadBalancingThisBackup6) { HAConfigPtr config = createValidConfiguration(); config->setThisServerName("server3"); QueryFilter filter(config); // The backup server doesn't handle any DHCP traffic by default. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // None of the packets should be handlded by the backup server. ASSERT_FALSE(filter.inScope(query6, scope_class)); } // Simulate failover. Although, backup server never starts handling // other server's traffic automatically, it can be manually instructed // to do so. This simulates such scenario. filter.serveFailoverScopes(); // The backup server now handles traffic of server 1 and server 2. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query6, scope_class)); } } // This test verifies the case when hot-standby is enabled and this // server is primary. TEST_F(QueryFilterTest, hotStandbyThisPrimary6) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); QueryFilter filter(config); Pkt6Ptr query6 = createQuery6("01:02:11:22:33:44:55:66"); // By default, only the primary server is active. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; // It should process its queries. EXPECT_TRUE(filter.inScope(query6, scope_class)); // Simulate failover scenario, in which the active server detects a // failure of the standby server. This doesn't change anything in how // the traffic is distributed. filter.serveFailoverScopes(); // The server1 continues to process its own traffic. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query6, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies the case when hot-standby is enabled and this // server is standby. TEST_F(QueryFilterTest, hotStandbyThisSecondary6) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); config->setThisServerName("server2"); QueryFilter filter(config); Pkt6Ptr query6 = createQuery6("01:02:11:22:33:44:55:66"); // The server2 doesn't process any queries by default. The whole // traffic is processed by the server1. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; EXPECT_FALSE(filter.inScope(query6, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); // Simulate failover case whereby the standby server detects a // failure of the active server. filter.serveFailoverScopes(); // The server2 now handles the traffic normally handled by the // server1. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query6, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies that it is possible to explicitly enable and // disable certain scopes. TEST_F(QueryFilterTest, explicitlyServeScopes) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // Initially, the scopes should be set according to the load // balancing configuration. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Enable "server2" scope. ASSERT_NO_THROW(filter.serveScope("server2")); EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Enable only "server2" scope. ASSERT_NO_THROW(filter.serveScopeOnly("server2")); EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Explicitly enable selected scopes. ASSERT_NO_THROW(filter.serveScopes({ "server1", "server3" })); EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_TRUE(filter.amServingScope("server3")); // Revert to defaults. ASSERT_NO_THROW(filter.serveDefaultScopes()); EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Disable all scopes. ASSERT_NO_THROW(filter.serveNoScopes()); EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Test negative cases. EXPECT_THROW(filter.serveScope("unsupported"), BadValue); EXPECT_THROW(filter.serveScopeOnly("unsupported"), BadValue); EXPECT_THROW(filter.serveScopes({ "server1", "unsupported" }), BadValue); } }
38.0919
80
0.702678
mcr
36e8b5bf3ef22888bb6e6902762aa3c7ca325007
651
cpp
C++
tests/src/test_FeatureKey.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
null
null
null
tests/src/test_FeatureKey.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
2
2019-04-23T17:24:04.000Z
2019-04-23T17:28:46.000Z
tests/src/test_FeatureKey.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
null
null
null
#include <lowletorfeats/base/FeatureKey.hpp> int main() { // Test constructors lowletorfeats::base::FeatureKey fKey; fKey = lowletorfeats::base::FeatureKey(fKey); fKey = lowletorfeats::base::FeatureKey("invalid.invalid.invalid"); fKey = lowletorfeats::base::FeatureKey("invalid", "invalid", "invalid"); fKey = lowletorfeats::base::FeatureKey("tfidf", "tfidf", "full"); // Test public methods fKey.changeKey("okapi.bm25.body"); fKey.toString(); fKey.toHash(); fKey.getFType(); fKey.getFName(); fKey.getFSection(); fKey.getVType(); fKey.getVName(); fKey.getVSection(); return 0; }
25.038462
76
0.652842
paddy74
36ec61a33a3fde0b7b74289192ccf13c8e08b6cb
507
hpp
C++
src/base/LogHandler.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
3
2019-08-09T10:44:51.000Z
2019-11-06T00:21:23.000Z
src/base/LogHandler.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
null
null
null
src/base/LogHandler.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
2
2019-09-22T12:58:00.000Z
2019-10-02T13:25:01.000Z
#ifndef __ET_LOG_HANDLER__ #define __ET_LOG_HANDLER__ #include "Headers.hpp" namespace et { class LogHandler { public: static el::Configurations setupLogHandler(int *argc, char ***argv); static void setupLogFile(el::Configurations *defaultConf, string filename, string maxlogsize = "20971520"); static void rolloutHandler(const char *filename, std::size_t size); static string stderrToFile(const string &pathPrefix); }; } // namespace et #endif // __ET_LOG_HANDLER__
29.823529
76
0.727811
coderkd10
36ecb1a36b187e2f45679edef94a3cec564c5769
2,929
cpp
C++
src/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
4,816
2017-12-12T18:07:09.000Z
2019-04-17T02:01:04.000Z
src/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
514
2017-12-12T18:22:52.000Z
2019-04-16T16:07:11.000Z
src/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
579
2017-12-12T18:38:02.000Z
2019-04-11T13:32:53.000Z
/** * @file src/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.cpp * @brief Implementation of VarUseCFGTraversal. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include "retdec/llvmir2hll/analysis/value_analysis.h" #include "retdec/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.h" #include "retdec/llvmir2hll/ir/statement.h" #include "retdec/llvmir2hll/support/debug.h" namespace retdec { namespace llvmir2hll { /** * @brief Constructs a new traverser. * * See the description of isDefinedPriorToEveryAccess() for information on the * parameters. */ VarUseCFGTraversal::VarUseCFGTraversal(ShPtr<Variable> var, ShPtr<CFG> cfg, ShPtr<ValueAnalysis> va): CFGTraversal(cfg, true), var(var), va(va) {} /** * @brief Returns @c true if the given variable @a var is defined/modified prior * to every read access to it in @a cfg. * * @param[in] var Variable whose definition/modification is looked for. * @param[in] cfg CFG that should be traversed. * @param[in] va Analysis of values. * * @par Preconditions * - @a var, @a cfg, and @a va are non-null * - @a va is in a valid state * * This function leaves @a va in a valid state. */ bool VarUseCFGTraversal::isDefinedPriorToEveryAccess(ShPtr<Variable> var, ShPtr<CFG> cfg, ShPtr<ValueAnalysis> va) { PRECONDITION_NON_NULL(var); PRECONDITION_NON_NULL(cfg); PRECONDITION_NON_NULL(va); PRECONDITION(va->isInValidState(), "it is not in a valid state"); ShPtr<VarUseCFGTraversal> traverser(new VarUseCFGTraversal(var, cfg, va)); // Obtain the first statement of the function. We have to skip the entry // node because there are no statements corresponding to the VarDefStmts // for function parameters. ShPtr<CFG::Node> funcBodyNode((*cfg->getEntryNode()->succ_begin())->getDst()); ShPtr<Statement> firstStmt(*funcBodyNode->stmt_begin()); return traverser->performTraversal(firstStmt); } bool VarUseCFGTraversal::visitStmt(ShPtr<Statement> stmt) { ShPtr<ValueData> stmtData(va->getValueData(stmt)); /* TODO Include the following restriction? // There should not be any function calls. if (stmtData->hasCalls()) { return false; } */ // Check whether the variable is read prior modifying; if so, we are done. if (stmtData->isDirRead(var) || stmtData->mayBeIndirRead(var) || stmtData->mustBeIndirRead(var)) { currRetVal = false; return false; } // Check whether we are modifying the variable. Here, it doesn't suffice // that the variable may be read -- it either has to be read directly or // must be read indirectly. if (stmtData->isDirWritten(var) || stmtData->mustBeIndirWritten(var)) { currRetVal = true; return false; } return true; } bool VarUseCFGTraversal::getEndRetVal() const { return true; } bool VarUseCFGTraversal::combineRetVals(bool origRetVal, bool newRetVal) const { return origRetVal ? newRetVal : false; } } // namespace llvmir2hll } // namespace retdec
30.831579
80
0.742916
mehrdad-shokri
36edc45801b2a8d45231f91a54027d633c065ded
1,686
cpp
C++
Mystring.cpp
hahafeijidawang/MyString
9a519e6f13f96d0a7f6dac962e465f9fc7f833d9
[ "MIT" ]
null
null
null
Mystring.cpp
hahafeijidawang/MyString
9a519e6f13f96d0a7f6dac962e465f9fc7f833d9
[ "MIT" ]
null
null
null
Mystring.cpp
hahafeijidawang/MyString
9a519e6f13f96d0a7f6dac962e465f9fc7f833d9
[ "MIT" ]
null
null
null
#include<iostream> #include<Mystring.h> #include<string.h> #include<stdio.h> using namespace std; MyString::MyString(){ //无参构成一个空串 m_len=0; m_p=new char[m_len+1]; strcpy(m_p,""); } MyString::MyString(const char *p){ if(p==NULL){ m_len=0; m_p=new char[m_len+1]; strcpy(m_p,""); }else{ m_len=strlen(p); m_p=new char[m_len+1]; strcpy(m_p,p); } } //拷贝构造函数。 MyString::MyString(const MyString& s){ m_len=s.m_len; m_p=new char[m_len+1]; strcpy(m_p,s.m_p); } MyString::~MyString(){ if(m_p!=NULL){ delete [] m_p; m_p = NULL; m_len = 0; } } void MyString::printCom(){ cout<<"m_len:"<<m_len<<endl; cout<<"m_p:"<<endl; cout<< m_p<<endl; } MyString& MyString::operator=(const char *p){ if(p!=NULL){ m_len =strlen(p); cout<<"hhhh"<<endl; m_p = new char[strlen(p)+1]; strcpy(m_p,p); } else{ m_len=0; m_p =new char[strlen(p)+1]; strcpy(m_p,""); } return *this; } MyString& MyString::operator=(const MyString& s){ m_len = s.m_len; cout<<"dhdhfh"<<endl; m_p = new char[strlen(s.m_p)+1]; strcpy(m_p,s.m_p); return *this; } char& MyString:: operator[]( int i){ return m_p[i]; } ostream& operator <<(ostream& out, MyString& s){ out<<"m_len:"<<s.m_len<<endl; out<<"*m_p:"<<s.m_p<<endl; return out; } istream& operator >>(istream& in, MyString& s){ in>>s.m_len; return in; }
11.315436
51
0.488731
hahafeijidawang
36eed8568f8ce1627f33bdda4a73d34ac068ec98
11,454
hpp
C++
stapl_release/stapl/views/filter_view.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/filter_view.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/filter_view.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_VIEWS_FILTER_VIEW_HPP #define STAPL_VIEWS_FILTER_VIEW_HPP #include <stapl/views/core_view.hpp> #include <stapl/views/operations/sequence.hpp> #include <stapl/views/operations/view_iterator.hpp> #include <stapl/algorithms/algorithm.hpp> #include <iostream> #define INFINITE std::numeric_limits<size_type>::max() namespace stapl { ////////////////////////////////////////////////////////////////////// /// @brief Default functor that accepts everything ////////////////////////////////////////////////////////////////////// struct tautology { typedef bool result_type; template <typename T> bool operator()(T) { return true; } }; ////////////////////////////////////////////////////////////////////// /// @brief Defines a filter view over the specified @p View. /// /// This view provides a selective traversal over the elements /// referenced for the specified view. /// @ingroup filter_view ////////////////////////////////////////////////////////////////////// template <typename View, typename Pred> class filter_view : public core_view<typename View::view_container_type, typename View::domain_type, typename View::map_func_type> { typedef core_view<typename View::view_container_type, typename View::domain_type, typename View::map_func_type> base_type; protected: Pred m_pred; mutable typename base_type::size_type m_size; public: typedef typename View::view_container_type view_container_type; typedef view_container_type container_type; typedef typename view_container_type::reference reference; typedef typename view_container_type::const_reference const_reference; typedef typename View::domain_type domain_type; typedef typename View::map_func_type map_func_type; typedef map_func_type map_function; typedef typename view_container_type::value_type value_type; typedef typename domain_type::index_type index_type; typedef typename base_type::size_type size_type; typedef index_iterator<filter_view> iterator; typedef const_index_iterator<filter_view> const_iterator; ////////////////////////////////////////////////////////////////////// /// @brief Constructs a filter view over the given @p view. /// /// @param view View to filter /// @param pred Functor used to filter elements ////////////////////////////////////////////////////////////////////// filter_view(View const& view, Pred const& pred) : base_type(view.container(), view.domain(), view.mapfunc()), m_pred(pred), m_size(INFINITE) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructor used to pass ownership of the container to the view. /// /// @param vcont Pointer to the container used to forward the operations. /// @param dom Domain to be used by the view. /// @param mfunc Mapping function to transform view indices to container /// gids. /// @param pred Functor used to filter elements ////////////////////////////////////////////////////////////////////// filter_view(view_container_type* vcont, domain_type const& dom, map_func_type mfunc=map_func_type(), Pred const& pred=Pred()) : base_type(vcont, dom, mfunc), m_pred(pred), m_size(INFINITE) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructor that does not takes ownership over the passed /// container. /// /// @param vcont Reference to the container used to forward the operations. /// @param dom Domain to be used by the view. /// @param mfunc Mapping function to transform view indices to container /// gids. /// @param pred Functor used to filter elements ////////////////////////////////////////////////////////////////////// filter_view(view_container_type const& vcont, domain_type const& dom, map_func_type mfunc=map_func_type(), Pred const& pred=Pred()) : base_type(vcont, dom, mfunc), m_pred(pred), m_size(INFINITE) { } filter_view(view_container_type const& vcont, domain_type const& dom, map_func_type mfunc, filter_view const& other) : base_type(vcont, dom, mfunc), m_pred(other.m_pred), m_size(other.m_size) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructor that does not takes ownership over the passed /// container. /// /// @param other View to copy from. ////////////////////////////////////////////////////////////////////// filter_view(filter_view const& other) : base_type(other), m_pred(other.m_pred), m_size(other.m_size) { } /// @name Sequence Iterator /// @warning Methods in the Sequence Iterator group should only be used /// inside a work function which is processing a segmented view. /// These functions will perform a read operation on the data, /// which is not how iterators normally work /// @{ ////////////////////////////////////////////////////////////////////// /// @brief Return an iterator over the element whose GID is the /// first valid index, based on applying the predicate /// to the element value ////////////////////////////////////////////////////////////////////// iterator begin(void) { index_type index = this->domain().first(); if (m_pred(this->container().get_element(this->mapfunc()(index)))) return iterator(*this,index); else return iterator(*this,this->next(index)); } ////////////////////////////////////////////////////////////////////// /// @brief Return an iterator over the element whose GID is the /// first valid index, based on applying the predicate /// to the element value ////////////////////////////////////////////////////////////////////// const_iterator begin(void) const { index_type index = this->domain().first(); if (m_pred(this->container().get_element(this->mapfunc()(index)))) return const_iterator(*this,index); else return const_iterator(*this,this->next(index)); } ////////////////////////////////////////////////////////////////////// /// @brief Return an iterator over the element whose GID is the /// last valid index, based on applying the predicate /// to the element value ////////////////////////////////////////////////////////////////////// iterator end(void) { index_type index = this->domain().advance(this->domain().last(),1); return iterator(*this,index); } ////////////////////////////////////////////////////////////////////// /// @brief Return an iterator over the element whose GID is the /// last valid index, based on applying the predicate /// to the element value ////////////////////////////////////////////////////////////////////// const_iterator end(void) const { index_type index = this->domain().advance(this->domain().last(),1); return const_iterator(*this,index); } ////////////////////////////////////////////////////////////////////// /// @brief Return an iterator over the element whose GID is the /// next valid index, based on applying the predicate /// to the element value ////////////////////////////////////////////////////////////////////// index_type next(index_type index) const { index_type next_index = this->domain().advance(index,1); while (!m_pred(this->container().get_element(this->mapfunc()(next_index))) && this->domain().contains(next_index)) { next_index = this->domain().advance(next_index,1); } return next_index; } /// @} ////////////////////////////////////////////////////////////////////// /// @brief Returns value at the specified @p index. ////////////////////////////////////////////////////////////////////// value_type get_element(index_type index) { return this->container().get_element(this->mapfunc()(index)); } ////////////////////////////////////////////////////////////////////// /// @brief Returns the predicate used to filter the values. ////////////////////////////////////////////////////////////////////// Pred const& predicate(void) const { return m_pred; } ////////////////////////////////////////////////////////////////////// /// @brief Return the number of elements referenced for the view. ////////////////////////////////////////////////////////////////////// size_type size(void) const { if (m_size==INFINITE) { View orig(this->container(), this->domain(), this->mapfunc()); m_size = count_if(orig, m_pred); } return m_size; } ////////////////////////////////////////////////////////////////////// /// @internal /// @brief use to examine this class /// @param msg your message (to provide context) ////////////////////////////////////////////////////////////////////// void debug(char *msg=0) { std::cerr << "FILTER_VIEW " << this << " : "; if (msg) { std::cerr << msg; } std::cerr << std::endl; base_type::debug(); } }; //class filter_view template<typename View, typename Pred> struct view_traits<filter_view<View,Pred> > { typedef typename view_traits<View>::value_type value_type; typedef typename view_traits<View>::reference reference; typedef typename view_traits<View>::container container; typedef typename view_traits<View>::map_function map_function; typedef typename view_traits<View>::domain_type domain_type; typedef typename domain_type::index_type index_type; }; template<typename View, typename Pred, typename Info, typename CID> struct localized_view<mix_view<filter_view<View,Pred>,Info,CID>> : public filter_view<typename cast_container_view<View, typename mix_view<filter_view<View,Pred>, Info, CID>::component_type>::type,Pred> { typedef mix_view<filter_view<View,Pred>,Info,CID> view_base_type; typedef typename mix_view<filter_view<View,Pred>, Info,CID>::component_type component_type; typedef typename cast_container_view<View, component_type>::type casted_view_type; typedef filter_view<casted_view_type,Pred> base_type; localized_view(view_base_type const& v) : base_type(casted_view_type(*(v.get_component()), v.domain(), v.mapfunc()), v.predicate()) { } }; template<typename View, typename Pred> filter_view<View,Pred> filter(View const& view, Pred const& pred) { return filter_view<View,Pred>(view, pred); } } // namespace stapl #undef INFINITE #endif /* STAPL_VIEWS_FILTER_VIEW_HPP */
37.309446
80
0.535359
parasol-ppl
36ef7a08ca71c7c28ceef8b7c12e8fecad20c317
8,008
cpp
C++
KDIS/DataTypes/GED_EnhancedGroundCombatSoldier.cpp
TangramFlex/KDIS_Fork
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
[ "BSD-2-Clause" ]
null
null
null
KDIS/DataTypes/GED_EnhancedGroundCombatSoldier.cpp
TangramFlex/KDIS_Fork
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
[ "BSD-2-Clause" ]
null
null
null
KDIS/DataTypes/GED_EnhancedGroundCombatSoldier.cpp
TangramFlex/KDIS_Fork
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************* Copyright 2013 Karl Jones All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. For Further Information Please Contact me at Karljj1@yahoo.com http://p.sf.net/kdis/UserGuide *********************************************************************/ #include "./GED_EnhancedGroundCombatSoldier.h" using namespace KDIS; using namespace DATA_TYPE; using namespace ENUMS; ////////////////////////////////////////////////////////////////////////// // Public: ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier() : m_ui8WaterStatus( 0 ), m_ui8RestStatus( 0 ), m_ui8PriAmmun( 0 ), m_ui8SecAmmun( 0 ) { } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( KDataStream & stream ) { Decode( stream ); } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( KUINT16 ID, KINT16 XOffset, KINT16 YOffset, KINT16 ZOffset, const EntityAppearance & EA, KINT8 Psi, KINT8 Theta, KINT8 Phi, KINT8 Speed, KINT8 HeadAzimuth, KINT8 HeadElevation, KINT8 HeadScanRate, KINT8 HeadElevationRate, KUINT8 WaterStatus, RestStatus R, KUINT8 PrimaryAmmunition, KUINT8 SecondaryAmmunition ) : GED_BasicGroundCombatSoldier( ID, XOffset, YOffset, ZOffset, EA, Psi, Theta, Phi, Speed, HeadAzimuth, HeadElevation, HeadScanRate, HeadElevationRate ), m_ui8WaterStatus( WaterStatus ), m_ui8RestStatus( R ), m_ui8PriAmmun( PrimaryAmmunition ), m_ui8SecAmmun( SecondaryAmmunition ) { } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( const GED_BasicGroundCombatSoldier & BGCS, KUINT8 WaterStatus, RestStatus R, KUINT8 PrimaryAmmunition, KUINT8 SecondaryAmmunition ) : GED_BasicGroundCombatSoldier( BGCS ), m_ui8WaterStatus( WaterStatus ), m_ui8RestStatus( R ), m_ui8PriAmmun( PrimaryAmmunition ), m_ui8SecAmmun( SecondaryAmmunition ) { } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::~GED_EnhancedGroundCombatSoldier() { } ////////////////////////////////////////////////////////////////////////// GroupedEntityCategory GED_EnhancedGroundCombatSoldier::GetGroupedEntityCategory() const { return EnhancedGroundCombatSoldierGEC; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetLength() const { return GED_ENHANCED_GROUND_COMBAT_SOLDIER_SIZE; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetWaterStatus( KUINT8 W ) { m_ui8WaterStatus = W; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetWaterStatus() const { return m_ui8WaterStatus; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetRestStatus( RestStatus R ) { m_ui8RestStatus = R; } ////////////////////////////////////////////////////////////////////////// RestStatus GED_EnhancedGroundCombatSoldier::GetRestStatus() const { return ( RestStatus )m_ui8RestStatus; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetPrimaryAmmunition( KUINT8 P ) { m_ui8PriAmmun = P; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetPrimaryAmmunition() const { return m_ui8PriAmmun; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetSecondaryAmmunition( KUINT8 S ) { m_ui8SecAmmun = S; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetSecondaryAmmunition() const { return m_ui8SecAmmun; } ////////////////////////////////////////////////////////////////////////// KString GED_EnhancedGroundCombatSoldier::GetAsString() const { KStringStream ss; ss << GED_BasicGroundCombatSoldier::GetAsString(); ss << "GED Enhanced Ground Combat Vehicle\n" << "\tWater Status: " << ( KUINT16 )m_ui8WaterStatus << " ounce/s\n" << "\tRest Status: " << GetEnumAsStringRestStatus( m_ui8RestStatus ) << "\n" << "\tPrimary Ammunition: " << ( KUINT16 )m_ui8PriAmmun << "\n" << "\tSecondary Ammunition: " << ( KUINT16 )m_ui8SecAmmun << "\n"; return ss.str(); } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::Decode( KDataStream & stream ) { if( stream.GetBufferSize() < GED_ENHANCED_GROUND_COMBAT_SOLDIER_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER ); GED_BasicGroundCombatSoldier::Decode( stream ); stream >> m_ui8WaterStatus >> m_ui8RestStatus >> m_ui8PriAmmun >> m_ui8SecAmmun; } ////////////////////////////////////////////////////////////////////////// KDataStream GED_EnhancedGroundCombatSoldier::Encode() const { KDataStream stream; GED_EnhancedGroundCombatSoldier::Encode( stream ); return stream; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::Encode( KDataStream & stream ) const { GED_BasicGroundCombatSoldier::Encode( stream ); stream << m_ui8WaterStatus << m_ui8RestStatus << m_ui8PriAmmun << m_ui8SecAmmun; } ////////////////////////////////////////////////////////////////////////// KBOOL GED_EnhancedGroundCombatSoldier::operator == ( const GED_EnhancedGroundCombatSoldier & Value ) const { if( GED_BasicGroundCombatSoldier::operator!=( Value ) ) return false; if( m_ui8WaterStatus != Value.m_ui8WaterStatus ) return false; if( m_ui8RestStatus != Value.m_ui8RestStatus ) return false; if( m_ui8PriAmmun != Value.m_ui8PriAmmun ) return false; if( m_ui8SecAmmun != Value.m_ui8SecAmmun ) return false; return true; } ////////////////////////////////////////////////////////////////////////// KBOOL GED_EnhancedGroundCombatSoldier::operator != ( const GED_EnhancedGroundCombatSoldier & Value ) const { return !( *this == Value ); } //////////////////////////////////////////////////////////////////////////
34.222222
154
0.567932
TangramFlex
36ef9e7917fb0a0d32dacf6edecf22c33551d246
13,358
cpp
C++
Cappuccino/src/Cappuccino/Mesh.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
5
2019-10-25T11:51:08.000Z
2020-01-09T00:56:24.000Z
Cappuccino/src/Cappuccino/Mesh.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
145
2019-09-10T18:33:49.000Z
2020-02-02T09:59:23.000Z
Cappuccino/src/Cappuccino/Mesh.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
null
null
null
#include "Cappuccino/Mesh.h" #include "Cappuccino/CappMacros.h" #include "Cappuccino/ResourceManager.h" #include <glad/glad.h> #include <glm/glm.hpp> #include <algorithm> #include <fstream> #include <iostream> #include <sstream> using string = std::string; namespace Cappuccino { struct FaceData { unsigned vertexData[3]{}; unsigned textureData[3]{}; unsigned normalData[3]{}; }; std::string Mesh::_meshDirectory = "./Assets/Meshes/"; Mesh::Mesh(const std::string& name, const std::string& path) : _path(path), _name(name) {} Mesh::~Mesh() { glDeleteVertexArrays(1, &_VAO); } Mesh::Mesh(const std::vector<float>& VERTS, const std::vector<float>& TEXTS, const std::vector<float>& NORMS, const std::vector<float>& TANGS) { verts = VERTS; texts = TEXTS; norms = NORMS; tangs = TANGS; } Mesh::Mesh(Mesh& other) { verts = other.verts; texts = other.texts; norms = other.norms; tangs = other.tangs; _numVerts = other._numVerts; _numFaces = other._numFaces; } bool Mesh::loadMesh() { if (loaded) return true; char inputString[128]; std::vector<glm::vec3> vertexData{}; std::vector<glm::vec2> textureData{}; std::vector<glm::vec3> normalData{}; std::vector<FaceData> faces{}; std::vector<float> unPvertexData{}; std::vector<float> unPtextureData{}; std::vector<float> unPnormalData{}; //load the file std::ifstream input{}; input.open(_meshDirectory + _path); if (!input.good()) { std::cout << "Problem loading file: " << _path << "\n"; return false; } //import data while (!input.eof()) { input.getline(inputString, 128); //vertex data if (inputString[0] == 'v' && inputString[1] == ' ') { glm::vec3 vertData{ 0,0,0 }; std::sscanf(inputString, "v %f %f %f", &vertData.x, &vertData.y, &vertData.z); vertexData.push_back(vertData); }//texture data else if (inputString[0] == 'v' && inputString[1] == 't') { glm::vec2 texCoord{ 0,0 }; std::sscanf(inputString, "vt %f %f", &texCoord.x, &texCoord.y); textureData.push_back(texCoord); }//normal data else if (inputString[0] == 'v' && inputString[1] == 'n') { glm::vec3 normData{ 0,0,0 }; std::sscanf(inputString, "vn %f %f %f", &normData.x, &normData.y, &normData.z); normalData.push_back(normData); }//face data else if (inputString[0] == 'f' && inputString[1] == ' ') { faces.emplace_back(); std::sscanf(inputString, "f %u/%u/%u %u/%u/%u %u/%u/%u", &faces.back().vertexData[0], &faces.back().textureData[0], &faces.back().normalData[0], &faces.back().vertexData[1], &faces.back().textureData[1], &faces.back().normalData[1], &faces.back().vertexData[2], &faces.back().textureData[2], &faces.back().normalData[2]); } else continue; } //add the data to the vectors for (unsigned i = 0; i < faces.size(); i++) { for (unsigned j = 0; j < 3; j++) { unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].x); unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].y); unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].z); if (!textureData.empty()) { unPtextureData.push_back(textureData[faces[i].textureData[j] - 1].x); unPtextureData.push_back(textureData[faces[i].textureData[j] - 1].y); } if (!normalData.empty()) { unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].x); unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].y); unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].z); } } } _numFaces = faces.size(); _numVerts = _numFaces * 3; //https://learnopengl.com/Advanced-Lighting/Normal-Mapping //https://gitlab.com/ShawnM427/florp/blob/master/src/florp/graphics/MeshBuilder.cpp //it works! std::vector<glm::vec3> tangs; for (unsigned i = 0; i < _numFaces; i++) { std::vector<glm::vec3> tCalcPos; std::vector<glm::vec2> tCalcUV; for (unsigned j = 0; j < 3; j++) { tCalcPos.push_back(vertexData[faces[i].vertexData[j] - 1]); tCalcUV.push_back(textureData[faces[i].textureData[j] - 1]); } glm::vec3 deltaPos = tCalcPos[1] - tCalcPos[0]; glm::vec3 deltaPos2 = tCalcPos[2] - tCalcPos[0]; glm::vec2 deltaUV = tCalcUV[1] - tCalcUV[0]; glm::vec2 deltaUV2 = tCalcUV[2] - tCalcUV[0]; float f = 1.0f / (deltaUV.x * deltaUV2.y - deltaUV.y * deltaUV2.x); glm::vec3 tang = (deltaPos * deltaUV2.y - deltaPos2 * deltaUV.y) * f; for (unsigned j = 0; j < 3; j++) { tangs.push_back(tang); } } for (unsigned i = 0; i < unPvertexData.size(); i++) { master.push_back(unPvertexData[i]); verts.push_back(unPvertexData[i]); } for (unsigned i = 0; i < unPtextureData.size(); i++) { master.push_back(unPtextureData[i]); texts.push_back(unPtextureData[i]); } for (unsigned i = 0; i < unPnormalData.size(); i++) { master.push_back(unPnormalData[i]); norms.push_back(unPnormalData[i]); } for (unsigned i = 0; i < tangs.size(); i++) { master.push_back(tangs[i].x); master.push_back(tangs[i].y); master.push_back(tangs[i].z); this->tangs.push_back(tangs[i].x); this->tangs.push_back(tangs[i].y); this->tangs.push_back(tangs[i].z); } glGenVertexArrays(1, &_VAO); glGenBuffers(1, &_VBO); //binding the vao glBindVertexArray(_VAO); //enable slots glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); //vertex glBufferData(GL_ARRAY_BUFFER, master.size() * sizeof(float), &master[0], GL_STATIC_DRAW); //verts glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); //texts glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(unPvertexData.size() * sizeof(float))); //norms glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size()) * sizeof(float))); //tangents glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size() + unPnormalData.size()) * sizeof(float))); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size() + unPnormalData.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); input.close(); return loaded = true; } void Mesh::loadFromData() { master.clear(); for (unsigned i = 0; i < verts.size(); i++) master.push_back(verts[i]); for (unsigned i = 0; i < texts.size(); i++) master.push_back(texts[i]); for (unsigned i = 0; i < norms.size(); i++) master.push_back(norms[i]); for (unsigned i = 0; i < tangs.size(); i++) master.push_back(tangs[i]); glGenVertexArrays(1, &_VAO); glGenBuffers(1, &_VBO); glBindVertexArray(_VAO); //enable slots glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); //vertex glBufferData(GL_ARRAY_BUFFER, master.size() * sizeof(float), &master[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); loaded = true; } void Mesh::animationFunction(Mesh& other, bool shouldPlay) { glBindVertexArray(_VAO); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, other._VBO); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Mesh::resetVertAttribPointers() { glBindVertexArray(_VAO); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Mesh::reload(const std::vector<float>& VERTS, const std::vector<float>& NORMS, const std::vector<float>& TANGS) { master.clear(); verts.clear(); norms.clear(); tangs.clear(); for (unsigned i = 0; i < VERTS.size(); i++) { master.push_back(VERTS[i]); verts.push_back(VERTS[i]); } for (unsigned i = 0; i < texts.size(); i++) { master.push_back(texts[i]); } for (unsigned i = 0; i < NORMS.size(); i++) { master.push_back(NORMS[i]); norms.push_back(NORMS[i]); } for (unsigned i = 0; i < TANGS.size(); i++) { master.push_back(TANGS[i]); tangs.push_back(TANGS[i]); } glBindVertexArray(_VAO); //enable slots glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, _VBO); //vertex glBufferSubData(GL_ARRAY_BUFFER, 0, master.size() * sizeof(float), &master[0]); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Mesh::unload() { //empty the buffers glDeleteBuffers(1, &_VBO); glDeleteVertexArrays(1, &_VAO); _VBO = 0; _VAO = 0; //_numFaces = 0;//reset all numbers //_numVerts = 0; } void Mesh::draw() { glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLES, 0, _numVerts); } void Mesh::setDefaultPath(const std::string& directory) { string dir = directory; std::transform(dir.begin(), dir.end(), dir.begin(), ::tolower); if (dir == "default") _meshDirectory = "./Assets/Meshes/"; else _meshDirectory = directory; } }
32.501217
166
0.647477
Promethaes
36f12182c28662271f907f14b30cbef66baaeefe
1,586
hh
C++
util/id-types.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
util/id-types.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
util/id-types.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2013 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #ifndef FAINT_ID_TYPES_HH #define FAINT_ID_TYPES_HH namespace faint{ template<int group> class FaintID{ public: FaintID(){ static int max_id = 1007; m_rawId = max_id++; } static FaintID Invalid(){ return FaintID(-1); } static FaintID DefaultID(){ return FaintID<group>(0); } bool operator==(const FaintID<group>& other) const{ return other.m_rawId == m_rawId; } bool operator!=(const FaintID<group>& other) const{ return !operator==(other); } bool operator<(const FaintID<group>& other) const{ return m_rawId < other.m_rawId; } bool operator>(const FaintID<group>& other) const{ return m_rawId > other.m_rawId; } int Raw() const{ return m_rawId; } private: explicit FaintID(int id){ m_rawId = id; } int m_rawId; }; using CanvasId = FaintID<107>; using ObjectId = FaintID<108>; using CommandId = FaintID<109>; // 110 reserved using FrameId = FaintID<111>; } // namespace #endif
22.027778
70
0.69483
lukas-ke
36f5f1cfe35ad2bc9d0cfbf58e334d7983ec3147
4,801
cc
C++
src/theia/sfm/view_graph/view_graph_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-01-17T17:37:37.000Z
2021-03-26T09:21:38.000Z
src/theia/sfm/view_graph/view_graph_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
null
null
null
src/theia/sfm/view_graph/view_graph_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-09-09T03:34:20.000Z
2020-05-21T06:00:50.000Z
// Copyright (C) 2014 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest.h" #include "theia/util/hash.h" #include "theia/util/map_util.h" #include "theia/sfm/twoview_info.h" #include "theia/sfm/types.h" #include "theia/sfm/view_graph/view_graph.h" namespace theia { // This is needed for EXPECT_EQ(TwoViewInfo, TwoViewInfo); bool operator==(const TwoViewInfo& lhs, const TwoViewInfo& rhs) { return lhs.position_2 == rhs.position_2 && lhs.rotation_2 == rhs.rotation_2 && lhs.num_verified_matches == rhs.num_verified_matches; } TEST(ViewGraph, Constructor) { ViewGraph view_graph; EXPECT_EQ(view_graph.NumViews(), 0); EXPECT_EQ(view_graph.NumEdges(), 0); } TEST(ViewGraph, RemoveView) { ViewGraph graph; const ViewId view_one = 0; const ViewId view_two = 1; const TwoViewInfo edge; graph.AddEdge(view_one, view_two, edge); EXPECT_TRUE(graph.HasView(view_one)); EXPECT_TRUE(graph.HasView(view_two)); EXPECT_EQ(graph.NumEdges(), 1); graph.RemoveView(view_one); EXPECT_TRUE(!graph.HasView(view_one)); EXPECT_EQ(graph.NumViews(), 1); EXPECT_EQ(graph.NumEdges(), 0); } TEST(ViewGraph, AddEdge) { TwoViewInfo info1; info1.num_verified_matches = 1; TwoViewInfo info2; info2.num_verified_matches = 2; ViewGraph graph; graph.AddEdge(0, 1, info1); graph.AddEdge(0, 2, info2); EXPECT_EQ(graph.NumViews(), 3); EXPECT_EQ(graph.NumEdges(), 2); const std::vector<int> expected_ids = {0, 1, 2}; std::unordered_set<ViewId> view_ids = graph.ViewIds(); const auto* edge_0_1 = graph.GetEdge(0, 1); const auto* edge_0_2 = graph.GetEdge(0, 2); EXPECT_TRUE(edge_0_1 != nullptr); EXPECT_EQ(*edge_0_1, info1); EXPECT_TRUE(edge_0_2 != nullptr); EXPECT_EQ(*edge_0_2, info2); EXPECT_TRUE(graph.GetEdge(1, 2) == nullptr); const auto* edge_1_0 = graph.GetEdge(1, 0); const auto* edge_2_0 = graph.GetEdge(2, 0); EXPECT_TRUE(edge_1_0 != nullptr); EXPECT_EQ(*edge_1_0, info1); EXPECT_EQ(*edge_2_0, info2); EXPECT_TRUE(graph.GetEdge(2, 1) == nullptr); const std::unordered_set<ViewId> edge_ids = *graph.GetNeighborIdsForView(0); EXPECT_TRUE(ContainsKey(edge_ids, 1)); EXPECT_TRUE(ContainsKey(edge_ids, 2)); TwoViewInfo info3; info3.num_verified_matches = 3; graph.AddEdge(1, 2, info3); EXPECT_EQ(graph.NumViews(), 3); EXPECT_EQ(graph.NumEdges(), 3); EXPECT_TRUE(graph.GetEdge(1, 2) != nullptr); EXPECT_EQ(*graph.GetEdge(1, 2), info3); } TEST(ViewGraph, RemoveEdge) { TwoViewInfo info1; info1.num_verified_matches = 1; TwoViewInfo info2; info2.num_verified_matches = 2; ViewGraph graph; graph.AddEdge(0, 1, info1); graph.AddEdge(0, 2, info2); EXPECT_TRUE(graph.GetEdge(0, 1) != nullptr); EXPECT_TRUE(graph.GetEdge(0, 2) != nullptr); EXPECT_EQ(graph.NumViews(), 3); EXPECT_EQ(graph.NumEdges(), 2); EXPECT_TRUE(graph.RemoveEdge(0, 2)); EXPECT_EQ(graph.NumEdges(), 1); EXPECT_TRUE(graph.GetEdge(0, 2) == nullptr); } } // namespace theia
32.659864
78
0.725057
LEON-MING
36f6067521e6947e4595e9989ec5213cd4420d67
10,370
cpp
C++
Mary/Game/StyleSwitcher.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Mary/Game/StyleSwitcher.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Mary/Game/StyleSwitcher.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
#include "StyleSwitcher.h" uint64 Game_StyleSwitcher_counter = 0; PrivateStart; byte8 * StyleControllerProxy = 0; byte8 * GunslingerGetStyleLevel = 0; byte8 * VergilDynamicStyle = 0; void UpdateStyle(byte8 * baseAddr, uint32 index) { auto actor = System_Actor_GetActorId(baseAddr); auto & character = *(uint8 *)(baseAddr + 0x78); auto & style = *(uint32 *)(baseAddr + 0x6338); auto & level = *(uint32 *)(baseAddr + 0x6358); auto & experience = *(float32 *)(baseAddr + 0x6364); auto session = *(byte **)(appBaseAddr + 0xC90E30); if (!session) { return; } auto sessionLevel = (uint32 *)(session + 0x11C); auto sessionExperience = (float32 *)(session + 0x134); if (!((character == CHAR_DANTE) || (character == CHAR_VERGIL))) { return; } if (character == CHAR_VERGIL) { switch (index) { case STYLE_SWORDMASTER: case STYLE_GUNSLINGER: case STYLE_ROYALGUARD: index = STYLE_DARK_SLAYER; break; } } if (style == index) { if (Config.Game.StyleSwitcher.noDoubleTap) { return; } index = STYLE_QUICKSILVER; } if ((index == STYLE_QUICKSILVER) && (actor != ACTOR_ONE)) { return; } if ((index == STYLE_DOPPELGANGER) && Config.System.Actor.forceSingleActor) { return; } // @Todo: Check if array for unlocked styles. if (character == CHAR_DANTE) { if (index == STYLE_QUICKSILVER) { auto & unlock = *(bool *)(session + 0x5E); if (!unlock) { return; } } else if (index == STYLE_DOPPELGANGER) { auto & unlock = *(bool *)(session + 0x5F); if (!unlock) { return; } } } if (actor == ACTOR_ONE) { sessionLevel [style] = level; sessionExperience[style] = experience; } level = sessionLevel [index]; experience = sessionExperience[index]; style = index; if ((index == STYLE_SWORDMASTER) || (index == STYLE_GUNSLINGER)) { System_Weapon_Dante_UpdateExpertise(baseAddr); } UpdateActor2Start: { auto & baseAddr2 = System_Actor_actorBaseAddr[ACTOR_TWO]; if (!baseAddr2) { goto UpdateActor2End; } auto & character2 = *(uint8 *)(baseAddr2 + 0x78 ); auto & style2 = *(uint32 *)(baseAddr2 + 0x6338); auto & isControlledByPlayer2 = *(bool *)(baseAddr2 + 0x6480); if (Config.System.Actor.forceSingleActor) { goto UpdateActor2End; } if (actor != ACTOR_ONE) { goto UpdateActor2End; } if (character != character2) { goto UpdateActor2End; } if ((index == STYLE_QUICKSILVER) /*|| (index == STYLE_DOPPELGANGER)*/) { goto UpdateActor2End; } if (!isControlledByPlayer2) { style2 = index; if ((index == STYLE_SWORDMASTER) || (index == STYLE_GUNSLINGER)) { System_Weapon_Dante_UpdateExpertise(baseAddr2); } } } UpdateActor2End: if (actor == ACTOR_ONE) { System_HUD_updateStyleIcon = true; } Game_StyleSwitcher_counter++; } PrivateEnd; void Game_StyleSwitcher_Controller() { //uint8 actorCount = System_Actor_GetActorCount(); //if (actorCount < 1) //{ // return; //} // @Todo: Change to bindings. uint8 commandId[] = { CMD_MAP_SCREEN, CMD_FILE_SCREEN, CMD_ITEM_SCREEN, CMD_EQUIP_SCREEN, }; static bool execute[MAX_ACTOR][5] = {}; // @Fix: GetButtonState or loop is broken. Style is updated for other actors as well even if only actor one initiates the switch. // @Todo: Create helper; auto count = System_Actor_GetActorCount(); for (uint8 actor = 0; actor < count; actor++) { for (uint8 style = 0; style < 4; style++) { if (System_Input_GetButtonState(actor) & System_Input_GetBinding(commandId[style])) { if (execute[actor][style]) { UpdateStyle(System_Actor_actorBaseAddr[actor], style); execute[actor][style] = false; } } else { execute[actor][style] = true; } } if (Config.Game.Multiplayer.enable) { continue; } if ((System_Input_GetButtonState(actor) & System_Input_GetBinding(CMD_CHANGE_TARGET)) && (System_Input_GetButtonState(actor) & System_Input_GetBinding(CMD_DEFAULT_CAMERA))) { if (execute[actor][4]) { UpdateStyle(System_Actor_actorBaseAddr[actor], STYLE_DOPPELGANGER); execute[actor][4] = false; } } else { execute[actor][4] = true; } } } void Game_StyleSwitcher_Init() { LogFunction(); { byte8 sect0[] = { 0x48, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00, //mov rcx,[dmc3.exe+C90E30] 0x48, 0x85, 0xC9, //test rcx,rcx 0x74, 0x07, //je short 0x8B, 0x8B, 0x58, 0x63, 0x00, 0x00, //mov ecx,[rbx+00006358] 0xC3, //ret 0x8B, 0x89, 0x00, 0x00, 0x00, 0x00, //mov ecx,[rcx+00000000] 0xC3, //ret }; FUNC func = CreateFunction(0, 0, false, true, sizeof(sect0)); memcpy(func.sect0, sect0, sizeof(sect0)); WriteAddress(func.sect0, (appBaseAddr + 0xC90E30), 7); *(dword *)(func.sect0 + 0x15) = (0x11C + (STYLE_GUNSLINGER * 4)); GunslingerGetStyleLevel = func.addr; } { byte8 sect0[] = { 0x50, //push rax 0x56, //push rsi 0x48, 0x8B, 0x35, 0x00, 0x00, 0x00, 0x00, //mov rsi,[dmc3.exe+C90E30] 0x48, 0x85, 0xF6, //test rsi,rsi 0x74, 0x0C, //je short 0x8B, 0x86, 0xA4, 0x01, 0x00, 0x00, //mov eax,[rsi+000001A4] 0x89, 0x81, 0x38, 0x63, 0x00, 0x00, //mov [rcx+00006338],eax 0x5E, //pop rsi 0x58, //pop rax }; FUNC func = CreateFunction(0, (appBaseAddr + 0x223D81), false, true, sizeof(sect0)); memcpy(func.sect0, sect0, sizeof(sect0)); WriteAddress((func.sect0 + 2), (appBaseAddr + 0xC90E30), 7); VergilDynamicStyle = func.addr; } } // @Todo: Update. void Game_StyleSwitcher_Toggle(bool enable) { Log("%s %u", FUNC_NAME, enable); if (enable) { Write<byte>((appBaseAddr + 0x1E8F98), 0xEB); // Bypass Character Check //WriteJump((appBaseAddr + 0x23D4B2), StyleControllerProxy); Write<byte>((appBaseAddr + 0x23B111), 0); Write<byte>((appBaseAddr + 0x23B15E), 0); Write<byte>((appBaseAddr + 0x23B1A2), 0); Write<byte>((appBaseAddr + 0x23B1E6), 0); // Gunslinger Fixes WriteCall((appBaseAddr + 0x204E38), GunslingerGetStyleLevel, 1); WriteCall((appBaseAddr + 0x205586), GunslingerGetStyleLevel, 1); WriteCall((appBaseAddr + 0x208A90), GunslingerGetStyleLevel, 1); WriteCall((appBaseAddr + 0x208F13), GunslingerGetStyleLevel, 1); WriteAddress((appBaseAddr + 0x1E6AAD), (appBaseAddr + 0x1E6AB3), 6 ); // Allow Charged Shot Write<byte>((appBaseAddr + 0x1E7F5F), 0xEB); // Allow Wild Stomp WriteAddress((appBaseAddr + 0x21607C), (appBaseAddr + 0x216082), 6 ); // Allow Charging // Force Style Updates WriteAddress((appBaseAddr + 0x1F87BB), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F87C4), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F87CD), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F87D6), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F880B), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F8852), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F8862), (appBaseAddr + 0x1F8A00), 5); WriteAddress((appBaseAddr + 0x1F886E), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F89E1), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F89FB), (appBaseAddr + 0x1F8A00), 5); WriteAddress((appBaseAddr + 0x1F8A07), (appBaseAddr + 0x1F8AAC), 6); WriteAddress((appBaseAddr + 0x1F8A7D), (appBaseAddr + 0x1F8AAC), 2); WriteAddress((appBaseAddr + 0x1F8AAA), (appBaseAddr + 0x1F8AAC), 2); WriteAddress((appBaseAddr + 0x1F8AC4), (appBaseAddr + 0x1F8AC6), 2); // Vergil Fixes WriteJump((appBaseAddr + 0x223D77), VergilDynamicStyle, 5); // Force dynamic style // @Audit: Should this go to Actor.cpp? Yup, Doppelganger fix. vp_memset((appBaseAddr + 0x221E50), 0x90, 8); // Update Actor Vergil; Disable linked actor base address reset. } else { Write<byte>((appBaseAddr + 0x1E8F98), 0x74); //WriteCall((appBaseAddr + 0x23D4B2), (appBaseAddr + 0x23B060)); Write<byte>((appBaseAddr + 0x23B111), 1); Write<byte>((appBaseAddr + 0x23B15E), 1); Write<byte>((appBaseAddr + 0x23B1A2), 1); Write<byte>((appBaseAddr + 0x23B1E6), 1); { byte buffer[] = { 0x8B, 0x8B, 0x58, 0x63, 0x00, 0x00, //mov ecx,[rbx+00006358] }; vp_memcpy((appBaseAddr + 0x204E38), buffer, sizeof(buffer)); vp_memcpy((appBaseAddr + 0x205586), buffer, sizeof(buffer)); vp_memcpy((appBaseAddr + 0x208A90), buffer, sizeof(buffer)); vp_memcpy((appBaseAddr + 0x208F13), buffer, sizeof(buffer)); } WriteAddress((appBaseAddr + 0x1E6AAD), (appBaseAddr + 0x1E64A9), 6); Write<byte>((appBaseAddr + 0x1E7F5F), 0x74); WriteAddress((appBaseAddr + 0x21607C), (appBaseAddr + 0x216572), 6); WriteAddress((appBaseAddr + 0x1F87BB), (appBaseAddr + 0x1F8AC6), 6); WriteAddress((appBaseAddr + 0x1F87C4), (appBaseAddr + 0x1F8AAC), 6); WriteAddress((appBaseAddr + 0x1F87CD), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F87D6), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F880B), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F8852), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F8862), (appBaseAddr + 0x1F8AF8), 5); WriteAddress((appBaseAddr + 0x1F886E), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F89E1), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F89FB), (appBaseAddr + 0x1F8AF8), 5); WriteAddress((appBaseAddr + 0x1F8A07), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F8A7D), (appBaseAddr + 0x1F8AF8), 2); WriteAddress((appBaseAddr + 0x1F8AAA), (appBaseAddr + 0x1F8AF8), 2); WriteAddress((appBaseAddr + 0x1F8AC4), (appBaseAddr + 0x1F8AF8), 2); { byte buffer[] = { 0xC7, 0x81, 0x38, 0x63, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, //mov [rcx+00006338],00000002 }; vp_memcpy((appBaseAddr + 0x223D77), buffer, sizeof(buffer)); } { byte buffer[] = { 0x4D, 0x89, 0xB4, 0x24, 0x78, 0x64, 0x00, 0x00, //mov [r12+00006478],r14 }; vp_memcpy((appBaseAddr + 0x221E50), buffer, sizeof(buffer)); } } }
29.047619
174
0.643684
wangxh1007
36f6f960413fd520167a2834a398d3f7fc80fb31
2,451
cpp
C++
testrunner/main.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
39
2018-08-26T05:53:19.000Z
2021-12-11T07:47:24.000Z
testrunner/main.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
1
2018-06-21T00:40:41.000Z
2018-06-21T00:40:46.000Z
testrunner/main.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
8
2018-08-27T00:34:23.000Z
2020-09-27T12:51:22.000Z
#include "/Users/duc/github/ContestNeko/CodeForces/TaskD.cpp" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <cctype> #include <ctime> namespace jhelper { struct Test { std::string input; std::string output; bool active; bool has_output; }; bool check(std::string expected, std::string actual) { while(!expected.empty() && isspace(*--expected.end())) expected.erase(--expected.end()); while(!actual.empty() && isspace(*--actual.end())) actual.erase(--actual.end()); return expected == actual; } } // namespace jhelper int main() { std::vector<jhelper::Test> tests = { {"5\n11 2 3 5 7\n4\n11 7 3 7\n", "3\n", true, true},{"2\n1 2\n1\n100\n", "-1\n", true, true},{"3\n1 2 3\n3\n1 2 3\n", "3\n", true, true},{"5\n1 2 3 4 5\n3 \n5 7 3", "", true, true}, }; bool allOK = true; int testID = 0; std::cout << std::fixed; double maxTime = 0.0; for(const jhelper::Test& test: tests ) { std::cout << "Test #" << ++testID << std::endl; std::cout << "Input: \n" << test.input << std::endl; if (test.has_output) { std::cout << "Expected output: \n" << test.output << std::endl; } else { std::cout << "Expected output: \n" << "N/A" << std::endl; } if (test.active) { std::stringstream in(test.input); std::ostringstream out; std::clock_t start = std::clock(); TaskD solver; solver.solve(in, out); std::clock_t finish = std::clock(); double currentTime = double(finish - start) / CLOCKS_PER_SEC; maxTime = std::max(currentTime, maxTime); std::cout << "Actual output: \n" << out.str() << std::endl; if (test.has_output) { bool result = jhelper::check(test.output, out.str()); allOK = allOK && result; std::cout << "Result: " << (result ? "OK" : "Wrong answer") << std::endl; } std::cout << "Time: " << currentTime << std::endl; } else { std::cout << "SKIPPED\n"; } std::cout << std::endl; } if(allOK) { std::cout << "All OK" << std::endl; } else { std::cout << "Some cases failed" << std::endl; } std::cout << "Maximal time: " << maxTime << "s." << std::endl; return 0; }
31.025316
189
0.518972
ducaddepar
36f82dba5adb44908ab284b453ade94d0325c5af
25,405
cpp
C++
tmc3/TMC3.cpp
jokerld/TMC13v5-Cluster
aa8d8d8be31f1723f8909abe73673fc160d2f837
[ "BSD-3-Clause" ]
null
null
null
tmc3/TMC3.cpp
jokerld/TMC13v5-Cluster
aa8d8d8be31f1723f8909abe73673fc160d2f837
[ "BSD-3-Clause" ]
null
null
null
tmc3/TMC3.cpp
jokerld/TMC13v5-Cluster
aa8d8d8be31f1723f8909abe73673fc160d2f837
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * 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 ISO/IEC nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "TMC3.h" #include <memory> #include "PCCTMC3Encoder.h" #include "PCCTMC3Decoder.h" #include "constants.h" #include "program_options_lite.h" #include "io_tlv.h" #include "version.h" using namespace std; using namespace pcc; //============================================================================ struct Parameters { bool isDecoder; // command line parsing should adjust dist2 values according to PQS bool positionQuantizationScaleAdjustsDist2; // output mode for ply writing (binary or ascii) bool outputBinaryPly; // when true, configure the encoder as if no attributes are specified bool disableAttributeCoding; std::string uncompressedDataPath; std::string compressedStreamPath; std::string reconstructedDataPath; // Filename for saving pre inverse scaled point cloud. std::string preInvScalePath; pcc::EncoderParams encoder; pcc::DecoderParams decoder; // todo(df): this should be per-attribute ColorTransform colorTransform; // todo(df): this should be per-attribute int reflectanceScale; }; //============================================================================ int main(int argc, char* argv[]) { cout << "MPEG PCC tmc3 version " << ::pcc::version << endl; Parameters params; if (!ParseParameters(argc, argv, params)) { return -1; } // Timers to count elapsed wall/user time pcc::chrono::Stopwatch<std::chrono::steady_clock> clock_wall; pcc::chrono::Stopwatch<pcc::chrono::utime_inc_children_clock> clock_user; clock_wall.start(); int ret = 0; if (params.isDecoder) { ret = Decompress(params, clock_user); } else { ret = Compress(params, clock_user); } clock_wall.stop(); using namespace std::chrono; auto total_wall = duration_cast<milliseconds>(clock_wall.count()).count(); auto total_user = duration_cast<milliseconds>(clock_user.count()).count(); std::cout << "Processing time (wall): " << total_wall / 1000.0 << " s\n"; std::cout << "Processing time (user): " << total_user / 1000.0 << " s\n"; return ret; } //--------------------------------------------------------------------------- // :: Command line / config parsing helpers template<typename T> static std::istream& readUInt(std::istream& in, T& val) { unsigned int tmp; in >> tmp; val = T(tmp); return in; } static std::istream& operator>>(std::istream& in, ColorTransform& val) { return readUInt(in, val); } namespace pcc { static std::istream& operator>>(std::istream& in, AttributeEncoding& val) { return readUInt(in, val); } } // namespace pcc namespace pcc { static std::istream& operator>>(std::istream& in, PartitionMethod& val) { return readUInt(in, val); } } // namespace pcc namespace pcc { static std::ostream& operator<<(std::ostream& out, const AttributeEncoding& val) { switch (val) { case AttributeEncoding::kPredictingTransform: out << "0 (Pred)"; break; case AttributeEncoding::kRAHTransform: out << "1 (RAHT)"; break; case AttributeEncoding::kLiftingTransform: out << "2 (Lift)"; break; } return out; } } // namespace pcc namespace pcc { static std::ostream& operator<<(std::ostream& out, const PartitionMethod& val) { switch (val) { case PartitionMethod::kNone: out << "0 (None)"; break; case PartitionMethod::kUniformGeom: out << "0 (UniformGeom)"; break; case PartitionMethod::kOctreeUniform: out << "0 (UniformOctree)"; break; default: out << int(val) << " (Unknown)"; break; } return out; } } // namespace pcc namespace df { namespace program_options_lite { template<typename T> struct option_detail<pcc::PCCVector3<T>> { static constexpr bool is_container = true; static constexpr bool is_fixed_size = true; typedef T* output_iterator; static void clear(pcc::PCCVector3<T>& container){}; static output_iterator make_output_iterator(pcc::PCCVector3<T>& container) { return &container[0]; } }; } // namespace program_options_lite } // namespace df //--------------------------------------------------------------------------- // :: Command line / config parsing bool ParseParameters(int argc, char* argv[], Parameters& params) { namespace po = df::program_options_lite; struct { AttributeDescription desc; AttributeParameterSet aps; } params_attr; bool print_help = false; // a helper to set the attribute std::function<po::OptionFunc::Func> attribute_setter = [&](po::Options&, const std::string& name, po::ErrorReporter) { // copy the current state of parsed attribute parameters // // NB: this does not cause the default values of attr to be restored // for the next attribute block. A side-effect of this is that the // following is allowed leading to attribute foo having both X=1 and // Y=2: // "--attr.X=1 --attribute foo --attr.Y=2 --attribute foo" // // NB: insert returns any existing element const auto& it = params.encoder.attributeIdxMap.insert( {name, int(params.encoder.attributeIdxMap.size())}); if (it.second) { params.encoder.sps.attributeSets.push_back(params_attr.desc); params.encoder.aps.push_back(params_attr.aps); return; } // update existing entry params.encoder.sps.attributeSets[it.first->second] = params_attr.desc; params.encoder.aps[it.first->second] = params_attr.aps; }; /* clang-format off */ // The definition of the program/config options, along with default values. // // NB: when updating the following tables: // (a) please keep to 80-columns for easier reading at a glance, // (b) do not vertically align values -- it breaks quickly // po::Options opts; opts.addOptions() ("help", print_help, false, "this help text") ("config,c", po::parseConfigFile, "configuration file name") (po::Section("General")) ("mode", params.isDecoder, false, "The encoding/decoding mode:\n" " 0: encode\n" " 1: decode") // i/o parameters ("reconstructedDataPath", params.reconstructedDataPath, {}, "The ouput reconstructed pointcloud file path (decoder only)") ("uncompressedDataPath", params.uncompressedDataPath, {}, "The input pointcloud file path") ("compressedStreamPath", params.compressedStreamPath, {}, "The compressed bitstream path (encoder=output, decoder=input)") ("postRecolorPath", params.encoder.postRecolorPath, {}, "Recolored pointcloud file path (encoder only)") ("preInvScalePath", params.preInvScalePath, {}, "Pre inverse scaled pointcloud file path (decoder only)") ("outputBinaryPly", params.outputBinaryPly, false, "Output ply files using binary (or otherwise ascii) format") // general // todo(df): this should be per-attribute ("colorTransform", params.colorTransform, COLOR_TRANSFORM_RGB_TO_YCBCR, "The colour transform to be applied:\n" " 0: none\n" " 1: RGB to YCbCr (Rec.709)") // todo(df): this should be per-attribute ("hack.reflectanceScale", params.reflectanceScale, 1, "scale factor to be applied to reflectance " "pre encoding / post reconstruction") // NB: if adding decoder options, uncomment the Decoder section marker // (po::Section("Decoder")) (po::Section("Encoder")) ("seq_bounding_box_xyz0", params.encoder.sps.seq_bounding_box_xyz0, {0}, "seq_bounding_box_xyz0. NB: seq_bounding_box_whd must be set for this " "parameter to have an effect") ("seq_bounding_box_whd", params.encoder.sps.seq_bounding_box_whd, {0}, "seq_bounding_box_whd") ("positionQuantizationScale", params.encoder.sps.seq_source_geom_scale_factor, 1.f, "Scale factor to be applied to point positions during quantization process") ("positionQuantizationScaleAdjustsDist2", params.positionQuantizationScaleAdjustsDist2, false, "Scale dist2 values by squared positionQuantizationScale") ("mergeDuplicatedPoints", params.encoder.gps.geom_unique_points_flag, true, "Enables removal of duplicated points") ("partitionMethod", params.encoder.partitionMethod, PartitionMethod::kNone, "Method used to partition input point cloud into slices/tiles:\n" " 0: none\n" " 1: none (deprecated)\n" " 2: n Uniform-Geometry partition bins along the longest edge\n" " 3: Uniform Geometry partition at n octree depth") ("partitionNumUniformGeom", params.encoder.partitionNumUniformGeom, 0, "Number of bins for partitionMethod=2:\n" " 0: slice partition with adaptive-defined bins\n" " >=1: slice partition with user-defined bins\n") ("partitionOctreeDepth", params.encoder.partitionOctreeDepth, 2, "Depth of octree partition for partitionMethod=3") ("disableAttributeCoding", params.disableAttributeCoding, false, "Ignore attribute coding configuration") (po::Section("Geometry")) // tools ("bitwiseOccupancyCoding", params.encoder.gps.bitwise_occupancy_coding_flag, true, "Selects between bitwise and bytewise occupancy coding:\n" " 0: bytewise\n" " 1: bitwise") ("neighbourContextRestriction", params.encoder.gps.neighbour_context_restriction_flag, false, "Limit geometry octree occupancy contextualisation to sibling nodes") ("neighbourAvailBoundaryLog2", params.encoder.gps.neighbour_avail_boundary_log2, 0, "Defines the avaliability volume for neighbour occupancy lookups." " 0: unconstrained") ("inferredDirectCodingMode", params.encoder.gps.inferred_direct_coding_mode_enabled_flag, true, "Permits early termination of the geometry octree for isolated points") ("intra_pred_max_node_size_log2", params.encoder.gps.intra_pred_max_node_size_log2, 0, "octree nodesizes eligible for occupancy intra prediction") ("ctxOccupancyReductionFactor", params.encoder.gps.geom_occupancy_ctx_reduction_factor, 3, "Adjusts the number of contexts used in occupancy coding") ("trisoup_node_size_log2", params.encoder.gps.trisoup_node_size_log2, 0, "Size of nodes for surface triangulation.\n" " 0: disabled\n") (po::Section("Attributes")) // attribute processing // NB: Attribute options are special in the way they are applied (see above) ("attribute", attribute_setter, "Encode the given attribute (NB, must appear after the" "following attribute parameters)") ("bitdepth", params_attr.desc.attr_bitdepth, 8, "Attribute bitdepth") ("transformType", params_attr.aps.attr_encoding, AttributeEncoding::kPredictingTransform, "Coding method to use for attribute:\n" " 0: Hierarchical neighbourhood prediction\n" " 1: Region Adaptive Hierarchical Transform (RAHT)\n" " 2: Hierarichical neighbourhood prediction as lifting transform") ("rahtLeafDecimationDepth", params_attr.aps.raht_binary_level_threshold, 3, "Sets coefficients to zero in the bottom n levels of RAHT tree. " "Used for chroma-subsampling in attribute=color only.") ("rahtQuantizationStep", params_attr.aps.quant_step_size_luma, 0, "deprecated -- use quantizationStepsLuma") ("rahtDepth", params_attr.aps.raht_depth, 21, "Number of bits for morton representation of an RAHT co-ordinate" "component") ("numberOfNearestNeighborsInPrediction", params_attr.aps.num_pred_nearest_neighbours, 3, "Attribute's maximum number of nearest neighbors to be used for prediction") ("adaptivePredictionThreshold", params_attr.aps.adaptive_prediction_threshold, -1, "Neighbouring attribute value difference that enables choice of " "single|multi predictors. Applies to transformType=2 only.\n" " -1: auto = 2**(bitdepth-2)") ("attributeSearchRange", params_attr.aps.search_range, 128, "Range for nearest neighbor search") ("lodBinaryTree", params_attr.aps.lod_binary_tree_enabled_flag, false, "Controls LoD generation method:\n" " 0: distance based subsampling\n" " 1: binary tree") ("max_num_direct_predictors", params_attr.aps.max_num_direct_predictors, 3, "Maximum number of nearest neighbour candidates used in direct" "attribute prediction") ("levelOfDetailCount", params_attr.aps.num_detail_levels, 1, "Attribute's number of levels of detail") ("quantizationStepLuma", params_attr.aps.quant_step_size_luma, 0, "Attribute's luma quantization step size") ("quantizationStepChroma", params_attr.aps.quant_step_size_chroma, 0, "Attribute's chroma quantization step size") ("dist2", params_attr.aps.dist2, {}, "Attribute's list of squared distances, or initial value for automatic" "derivation") ; /* clang-format on */ po::setDefaults(opts); po::ErrorReporter err; const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**)argv, err); for (const auto arg : argv_unhandled) { err.warn() << "Unhandled argument ignored: " << arg << "\n"; } if (argc == 1 || print_help) { po::doHelp(std::cout, opts, 78); return false; } // Certain coding modes are not available when trisoup is enabled. // Disable them, and warn if set (they may be set as defaults). if (params.encoder.gps.trisoup_node_size_log2 > 0) { if (!params.encoder.gps.geom_unique_points_flag) err.warn() << "TriSoup geometry does not preserve duplicated points\n"; if (params.encoder.gps.inferred_direct_coding_mode_enabled_flag) err.warn() << "TriSoup geometry is incompatable with IDCM\n"; params.encoder.gps.geom_unique_points_flag = true; params.encoder.gps.inferred_direct_coding_mode_enabled_flag = false; } // support disabling attribute coding (simplifies configuration) if (params.disableAttributeCoding) { params.encoder.attributeIdxMap.clear(); params.encoder.sps.attributeSets.clear(); params.encoder.aps.clear(); } // fixup any per-attribute settings for (const auto& it : params.encoder.attributeIdxMap) { auto& attr_sps = params.encoder.sps.attributeSets[it.second]; auto& attr_aps = params.encoder.aps[it.second]; // Avoid wasting bits signalling chroma quant step size for reflectance if (it.first == "reflectance") { attr_aps.quant_step_size_chroma = 0; } bool isLifting = attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform || attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform; // derive the dist2 values based on an initial value if (isLifting) { if (attr_aps.dist2.size() > attr_aps.num_detail_levels) { attr_aps.dist2.resize(attr_aps.num_detail_levels); } else if ( attr_aps.dist2.size() < attr_aps.num_detail_levels && !attr_aps.dist2.empty()) { if (attr_aps.dist2.size() < attr_aps.num_detail_levels) { attr_aps.dist2.resize(attr_aps.num_detail_levels); const double distRatio = 4.0; uint64_t d2 = attr_aps.dist2[0]; for (int i = 0; i < attr_aps.num_detail_levels; ++i) { attr_aps.dist2[i] = d2; d2 = uint64_t(std::round(distRatio * d2)); } } } } // In order to simplify specification of dist2 values, which are // depending on the scale of the coded point cloud, the following // adjust the dist2 values according to PQS. The user need only // specify the unquantised PQS value. if (params.positionQuantizationScaleAdjustsDist2) { double pqs = params.encoder.sps.seq_source_geom_scale_factor; double pqs2 = pqs * pqs; for (auto& dist2 : attr_aps.dist2) dist2 = int64_t(std::round(pqs2 * dist2)); } // Set default threshold based on bitdepth if (attr_aps.adaptive_prediction_threshold == -1) { attr_aps.adaptive_prediction_threshold = 1 << (attr_sps.attr_bitdepth - 2); } if (attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform) { attr_aps.adaptive_prediction_threshold = 0; } // For RAHT, ensure that the unused lod count = 0 (prevents mishaps) if (attr_aps.attr_encoding == AttributeEncoding::kRAHTransform) { attr_aps.num_detail_levels = 0; attr_aps.adaptive_prediction_threshold = 0; // todo(df): suggest chroma quant_step_size for raht attr_aps.quant_step_size_chroma = 0; } } // sanity checks if (params.encoder.gps.intra_pred_max_node_size_log2) if (!params.encoder.gps.neighbour_avail_boundary_log2) err.error() << "Geometry intra prediction requires finite" "neighbour_avail_boundary_log2\n"; for (const auto& it : params.encoder.attributeIdxMap) { const auto& attr_sps = params.encoder.sps.attributeSets[it.second]; const auto& attr_aps = params.encoder.aps[it.second]; bool isLifting = attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform || attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform; if (it.first == "color") { // todo(??): permit relaxing of the following constraint if (attr_sps.attr_bitdepth > 8) err.error() << it.first << ".bitdepth must be less than 9\n"; } if (it.first == "reflectance") { if (attr_sps.attr_bitdepth > 16) err.error() << it.first << ".bitdepth must be less than 17\n"; } if (isLifting) { int lod = attr_aps.num_detail_levels; if (lod > 255 || lod < 0) { err.error() << it.first << ".levelOfDetailCount must be in the range [0,255]\n"; } if (attr_aps.dist2.size() != lod) { err.error() << it.first << ".dist2 does not have " << lod << " entries\n"; } if (attr_aps.adaptive_prediction_threshold < 0) { err.error() << it.first << ".adaptivePredictionThreshold must be positive\n"; } if ( attr_aps.num_pred_nearest_neighbours > kAttributePredictionMaxNeighbourCount) { err.error() << it.first << ".numberOfNearestNeighborsInPrediction must be <= " << kAttributePredictionMaxNeighbourCount << "\n"; } } } // check required arguments are specified if (!params.isDecoder && params.uncompressedDataPath.empty()) err.error() << "uncompressedDataPath not set\n"; if (params.isDecoder && params.reconstructedDataPath.empty()) err.error() << "reconstructedDataPath not set\n"; if (params.compressedStreamPath.empty()) err.error() << "compressedStreamPath not set\n"; // report the current configuration (only in the absence of errors so // that errors/warnings are more obvious and in the same place). if (err.is_errored) return false; // Dump the complete derived configuration cout << "+ Effective configuration parameters\n"; po::dumpCfg(cout, opts, "General", 4); if (params.isDecoder) { po::dumpCfg(cout, opts, "Decoder", 4); } else { po::dumpCfg(cout, opts, "Encoder", 4); po::dumpCfg(cout, opts, "Geometry", 4); for (const auto& it : params.encoder.attributeIdxMap) { // NB: when dumping the config, opts references params_attr params_attr.desc = params.encoder.sps.attributeSets[it.second]; params_attr.aps = params.encoder.aps[it.second]; cout << " " << it.first << "\n"; po::dumpCfg(cout, opts, "Attributes", 8); } } cout << endl; return true; } int Compress(Parameters& params, Stopwatch& clock) { PCCPointSet3 pointCloud; if ( !pointCloud.read(params.uncompressedDataPath) || pointCloud.getPointCount() == 0) { cout << "Error: can't open input file!" << endl; return -1; } // Sanitise the input point cloud // todo(df): remove the following with generic handling of properties bool codeColour = params.encoder.attributeIdxMap.count("color"); if (!codeColour) pointCloud.removeColors(); assert(codeColour == pointCloud.hasColors()); bool codeReflectance = params.encoder.attributeIdxMap.count("reflectance"); if (!codeReflectance) pointCloud.removeReflectances(); assert(codeReflectance == pointCloud.hasReflectances()); ofstream fout(params.compressedStreamPath, ios::binary); if (!fout.is_open()) { return -1; } clock.start(); if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) { pointCloud.convertRGBToYUV(); } if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) { const auto pointCount = pointCloud.getPointCount(); for (size_t i = 0; i < pointCount; ++i) { int val = pointCloud.getReflectance(i) / params.reflectanceScale; pointCloud.setReflectance(i, val); } } PCCTMC3Encoder3 encoder; // The reconstructed point cloud std::unique_ptr<PCCPointSet3> reconPointCloud; if (!params.reconstructedDataPath.empty()) { reconPointCloud.reset(new PCCPointSet3); } int ret = encoder.compress( pointCloud, &params.encoder, [&](const PayloadBuffer& buf) { writeTlv(buf, fout); }, reconPointCloud.get()); if (ret) { cout << "Error: can't compress point cloud!" << endl; return -1; } std::cout << "Total bitstream size " << fout.tellp() << " B" << std::endl; fout.close(); clock.stop(); if (!params.reconstructedDataPath.empty()) { if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) { reconPointCloud->convertYUVToRGB(); } if (params.reflectanceScale > 1 && reconPointCloud->hasReflectances()) { const auto pointCount = reconPointCloud->getPointCount(); for (size_t i = 0; i < pointCount; ++i) { int val = reconPointCloud->getReflectance(i) * params.reflectanceScale; reconPointCloud->setReflectance(i, val); } } reconPointCloud->write( params.reconstructedDataPath, !params.outputBinaryPly); } return 0; } int Decompress(Parameters& params, Stopwatch& clock) { ifstream fin(params.compressedStreamPath, ios::binary); if (!fin.is_open()) { return -1; } clock.start(); PayloadBuffer buf; PCCTMC3Decoder3 decoder; while (true) { PayloadBuffer* buf_ptr = &buf; readTlv(fin, &buf); // at end of file (or other error), flush decoder if (!fin) buf_ptr = nullptr; int ret = decoder.decompress( params.decoder, buf_ptr, [&](const PCCPointSet3& decodedPointCloud) { PCCPointSet3 pointCloud(decodedPointCloud); if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) { pointCloud.convertYUVToRGB(); } if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) { const auto pointCount = pointCloud.getPointCount(); for (size_t i = 0; i < pointCount; ++i) { int val = pointCloud.getReflectance(i) * params.reflectanceScale; pointCloud.setReflectance(i, val); } } // Dump the decoded colour using the pre inverse scaled geometry if (!params.preInvScalePath.empty()) { pointCloud.write(params.preInvScalePath, !params.outputBinaryPly); } decoder.inverseQuantization(pointCloud); clock.stop(); if (!pointCloud.write( params.reconstructedDataPath, !params.outputBinaryPly)) { cout << "Error: can't open output file!" << endl; } clock.start(); }); if (ret) { cout << "Error: can't decompress point cloud!" << endl; return -1; } if (!buf_ptr) break; } fin.clear(); fin.seekg(0, ios_base::end); std::cout << "Total bitstream size " << fin.tellg() << " B" << std::endl; clock.stop(); return 0; }
31.83584
80
0.678331
jokerld
36fb2647450aa8082f242d7f72b1c37d058c5fae
15,885
cc
C++
components/autofill/core/browser/ui/label_formatter_utils.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/ui/label_formatter_utils.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/ui/label_formatter_utils.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/ui/label_formatter_utils.h" #include <algorithm> #include <iterator> #include <memory> #include "base/bind.h" #include "base/callback.h" #include "base/ranges/algorithm.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/geo/address_i18n.h" #include "components/autofill/core/browser/geo/phone_number_i18n.h" #include "components/autofill/core/browser/validation.h" #include "components/grit/components_scaled_resources.h" #include "components/strings/grit/components_strings.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h" #include "ui/base/l10n/l10n_util.h" namespace autofill { using data_util::ContainsAddress; using data_util::ContainsEmail; using data_util::ContainsName; using data_util::ContainsPhone; namespace { // Returns true if all |profiles| have the same value for the data retrieved by // |get_data|. bool HaveSameData( const std::vector<AutofillProfile*>& profiles, const std::string& app_locale, base::RepeatingCallback<base::string16(const AutofillProfile&, const std::string&)> get_data, base::RepeatingCallback<bool(const base::string16& str1, const base::string16& str2)> matches) { if (profiles.size() <= 1) { return true; } const base::string16 first_profile_data = get_data.Run(*profiles[0], app_locale); for (size_t i = 1; i < profiles.size(); ++i) { const base::string16 current_profile_data = get_data.Run(*profiles[i], app_locale); if (!matches.Run(first_profile_data, current_profile_data)) { return false; } } return true; } // Used to avoid having the same lambda in HaveSameEmailAddresses, // HaveSameFirstNames, HaveSameStreetAddresses. bool Equals(const base::string16& str1, const base::string16& str2) { return str1 == str2; } } // namespace void AddLabelPartIfNotEmpty(const base::string16& part, std::vector<base::string16>* parts) { if (!part.empty()) { parts->push_back(part); } } base::string16 ConstructLabelLine(const std::vector<base::string16>& parts) { return base::JoinString(parts, l10n_util::GetStringUTF16( IDS_AUTOFILL_SUGGESTION_LABEL_SEPARATOR)); } base::string16 ConstructMobileLabelLine( const std::vector<base::string16>& parts) { return base::JoinString( parts, l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_SUMMARY_SEPARATOR)); } bool IsNonStreetAddressPart(ServerFieldType type) { switch (type) { case ADDRESS_HOME_CITY: case ADDRESS_BILLING_CITY: case ADDRESS_HOME_ZIP: case ADDRESS_BILLING_ZIP: case ADDRESS_HOME_STATE: case ADDRESS_BILLING_STATE: case ADDRESS_HOME_COUNTRY: case ADDRESS_BILLING_COUNTRY: case ADDRESS_HOME_SORTING_CODE: case ADDRESS_BILLING_SORTING_CODE: case ADDRESS_HOME_DEPENDENT_LOCALITY: case ADDRESS_BILLING_DEPENDENT_LOCALITY: return true; default: return false; } } bool IsStreetAddressPart(ServerFieldType type) { switch (type) { case ADDRESS_HOME_LINE1: case ADDRESS_HOME_LINE2: case ADDRESS_HOME_APT_NUM: case ADDRESS_BILLING_LINE1: case ADDRESS_BILLING_LINE2: case ADDRESS_BILLING_APT_NUM: case ADDRESS_HOME_STREET_ADDRESS: case ADDRESS_BILLING_STREET_ADDRESS: case ADDRESS_HOME_LINE3: case ADDRESS_BILLING_LINE3: return true; default: return false; } } bool HasNonStreetAddress(const std::vector<ServerFieldType>& types) { return base::ranges::any_of(types, IsNonStreetAddressPart); } bool HasStreetAddress(const std::vector<ServerFieldType>& types) { return base::ranges::any_of(types, IsStreetAddressPart); } std::vector<ServerFieldType> ExtractSpecifiedAddressFieldTypes( bool extract_street_address_types, const std::vector<ServerFieldType>& types) { auto should_be_extracted = [&extract_street_address_types](ServerFieldType type) -> bool { return AutofillType(AutofillType(type).GetStorableType()).group() == FieldTypeGroup::kAddressHome && (extract_street_address_types ? IsStreetAddressPart(type) : !IsStreetAddressPart(type)); }; std::vector<ServerFieldType> extracted_address_types; std::copy_if(types.begin(), types.end(), std::back_inserter(extracted_address_types), should_be_extracted); return extracted_address_types; } std::vector<ServerFieldType> TypesWithoutFocusedField( const std::vector<ServerFieldType>& types, ServerFieldType field_type_to_remove) { std::vector<ServerFieldType> types_without_field; std::copy_if(types.begin(), types.end(), std::back_inserter(types_without_field), [&field_type_to_remove](ServerFieldType type) -> bool { return type != field_type_to_remove; }); return types_without_field; } AutofillProfile MakeTrimmedProfile(const AutofillProfile& profile, const std::string& app_locale, const std::vector<ServerFieldType>& types) { AutofillProfile trimmed_profile(profile.guid(), profile.origin()); trimmed_profile.set_language_code(profile.language_code()); const AutofillType country_code_type(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE); const base::string16 country_code = profile.GetInfo(country_code_type, app_locale); trimmed_profile.SetInfo(country_code_type, country_code, app_locale); for (const ServerFieldType& type : types) { trimmed_profile.SetInfo(type, profile.GetInfo(type, app_locale), app_locale); } return trimmed_profile; } base::string16 GetLabelForFocusedAddress( ServerFieldType focused_field_type, bool form_has_street_address, const AutofillProfile& profile, const std::string& app_locale, const std::vector<ServerFieldType>& types) { return GetLabelAddress( form_has_street_address && !IsStreetAddressPart(focused_field_type), profile, app_locale, types); } base::string16 GetLabelAddress(bool use_street_address, const AutofillProfile& profile, const std::string& app_locale, const std::vector<ServerFieldType>& types) { return use_street_address ? GetLabelStreetAddress( ExtractSpecifiedAddressFieldTypes(use_street_address, types), profile, app_locale) : GetLabelNationalAddress( ExtractSpecifiedAddressFieldTypes(use_street_address, types), profile, app_locale); } base::string16 GetLabelNationalAddress( const std::vector<ServerFieldType>& types, const AutofillProfile& profile, const std::string& app_locale) { std::unique_ptr<::i18n::addressinput::AddressData> address_data = i18n::CreateAddressDataFromAutofillProfile( MakeTrimmedProfile(profile, app_locale, types), app_locale); std::string address_line; ::i18n::addressinput::GetFormattedNationalAddressLine(*address_data, &address_line); return base::UTF8ToUTF16(address_line); } base::string16 GetLabelStreetAddress(const std::vector<ServerFieldType>& types, const AutofillProfile& profile, const std::string& app_locale) { std::unique_ptr<::i18n::addressinput::AddressData> address_data = i18n::CreateAddressDataFromAutofillProfile( MakeTrimmedProfile(profile, app_locale, types), app_locale); std::string address_line; ::i18n::addressinput::GetStreetAddressLinesAsSingleLine(*address_data, &address_line); return base::UTF8ToUTF16(address_line); } base::string16 GetLabelForProfileOnFocusedNonStreetAddress( bool form_has_street_address, const AutofillProfile& profile, const std::string& app_locale, const std::vector<ServerFieldType>& types, const base::string16& contact_info) { std::vector<base::string16> label_parts; AddLabelPartIfNotEmpty( GetLabelAddress(form_has_street_address, profile, app_locale, types), &label_parts); AddLabelPartIfNotEmpty(contact_info, &label_parts); return ConstructLabelLine(label_parts); } base::string16 GetLabelName(const std::vector<ServerFieldType>& types, const AutofillProfile& profile, const std::string& app_locale) { bool has_first_name = false; bool has_last_name = false; bool has_full_name = false; for (const ServerFieldType type : types) { if (type == NAME_FULL) { has_full_name = true; break; } if (type == NAME_FIRST) { has_first_name = true; } if (type == NAME_LAST) { has_last_name = true; } } if (has_full_name) { return profile.GetInfo(AutofillType(NAME_FULL), app_locale); } if (has_first_name && has_last_name) { std::vector<base::string16> name_parts; AddLabelPartIfNotEmpty(GetLabelFirstName(profile, app_locale), &name_parts); AddLabelPartIfNotEmpty(profile.GetInfo(AutofillType(NAME_LAST), app_locale), &name_parts); return base::JoinString(name_parts, base::ASCIIToUTF16(" ")); } if (has_first_name) { return GetLabelFirstName(profile, app_locale); } if (has_last_name) { return profile.GetInfo(AutofillType(NAME_LAST), app_locale); } // The form contains neither a full name field nor a first name field, // so choose some name field in the form and make it the label text. for (const ServerFieldType type : types) { if (AutofillType(AutofillType(type).GetStorableType()).group() == FieldTypeGroup::kName) { return profile.GetInfo(AutofillType(type), app_locale); } } return base::string16(); } base::string16 GetLabelFirstName(const AutofillProfile& profile, const std::string& app_locale) { return profile.GetInfo(AutofillType(NAME_FIRST), app_locale); } base::string16 GetLabelEmail(const AutofillProfile& profile, const std::string& app_locale) { const base::string16 email = profile.GetInfo(AutofillType(EMAIL_ADDRESS), app_locale); return IsValidEmailAddress(email) ? email : base::string16(); } base::string16 GetLabelPhone(const AutofillProfile& profile, const std::string& app_locale) { const std::string unformatted_phone = base::UTF16ToUTF8( profile.GetInfo(AutofillType(PHONE_HOME_WHOLE_NUMBER), app_locale)); return unformatted_phone.empty() ? base::string16() : base::UTF8ToUTF16(i18n::FormatPhoneNationallyForDisplay( unformatted_phone, data_util::GetCountryCodeWithFallback(profile, app_locale))); } bool HaveSameEmailAddresses(const std::vector<AutofillProfile*>& profiles, const std::string& app_locale) { return HaveSameData(profiles, app_locale, base::BindRepeating(&GetLabelEmail), base::BindRepeating(base::BindRepeating(&Equals))); } bool HaveSameFirstNames(const std::vector<AutofillProfile*>& profiles, const std::string& app_locale) { return HaveSameData(profiles, app_locale, base::BindRepeating(&GetLabelFirstName), base::BindRepeating(base::BindRepeating(&Equals))); } bool HaveSameNonStreetAddresses(const std::vector<AutofillProfile*>& profiles, const std::string& app_locale, const std::vector<ServerFieldType>& types) { // In general, comparing non street addresses with Equals, which uses ==, is // not ideal since Düsseldorf and Dusseldorf will be considered distinct. It's // okay to use it here because near-duplicate non street addresses like this // are filtered out before a LabelFormatter is created. return HaveSameData(profiles, app_locale, base::BindRepeating(&GetLabelNationalAddress, types), base::BindRepeating(&Equals)); } bool HaveSamePhoneNumbers(const std::vector<AutofillProfile*>& profiles, const std::string& app_locale) { // Note that the same country code is used in all comparisons. auto equals = [](const std::string& country_code, const std::string& app_locale, const base::string16& phone1, const base::string16& phone2) -> bool { return (phone1.empty() && phone2.empty()) || i18n::PhoneNumbersMatch(phone1, phone2, country_code, app_locale); }; return profiles.size() <= 1 ? true : HaveSameData( profiles, app_locale, base::BindRepeating(&GetLabelPhone), base::BindRepeating(equals, base::UTF16ToASCII(profiles[0]->GetInfo( ADDRESS_HOME_COUNTRY, app_locale)), app_locale)); } bool HaveSameStreetAddresses(const std::vector<AutofillProfile*>& profiles, const std::string& app_locale, const std::vector<ServerFieldType>& types) { // In general, comparing street addresses with Equals, which uses ==, is not // ideal since 3 Elm St and 3 Elm St. will be considered distinct. It's okay // to use it here because near-duplicate addresses like this are filtered // out before a LabelFormatter is created. return HaveSameData(profiles, app_locale, base::BindRepeating(&GetLabelStreetAddress, types), base::BindRepeating(&Equals)); } bool HasUnfocusedEmailField(FieldTypeGroup focused_group, uint32_t form_groups) { return ContainsEmail(form_groups) && focused_group != FieldTypeGroup::kEmail; } bool HasUnfocusedNameField(FieldTypeGroup focused_group, uint32_t form_groups) { return ContainsName(form_groups) && focused_group != FieldTypeGroup::kName; } bool HasUnfocusedNonStreetAddressField( ServerFieldType focused_field, FieldTypeGroup focused_group, const std::vector<ServerFieldType>& types) { return HasNonStreetAddress(types) && (focused_group != FieldTypeGroup::kAddressHome || !IsNonStreetAddressPart(focused_field)); } bool HasUnfocusedPhoneField(FieldTypeGroup focused_group, uint32_t form_groups) { return ContainsPhone(form_groups) && focused_group != FieldTypeGroup::kPhoneHome; } bool HasUnfocusedStreetAddressField(ServerFieldType focused_field, FieldTypeGroup focused_group, const std::vector<ServerFieldType>& types) { return HasStreetAddress(types) && (focused_group != FieldTypeGroup::kAddressHome || !IsStreetAddressPart(focused_field)); } bool FormHasOnlyNonStreetAddressFields( const std::vector<ServerFieldType>& types, uint32_t form_groups) { return ContainsAddress(form_groups) && !HasStreetAddress(types) && !(ContainsName(form_groups) || ContainsPhone(form_groups) || ContainsEmail(form_groups)); } } // namespace autofill
38.002392
90
0.678691
Ron423c
36fc1c809ad5a96ab02b25419f5d245897616720
241
cpp
C++
c02/2_8.cpp
brynhayder/accelerated-cpp
e26796486ba410db566c0f8acc392f32f20330a9
[ "MIT" ]
null
null
null
c02/2_8.cpp
brynhayder/accelerated-cpp
e26796486ba410db566c0f8acc392f32f20330a9
[ "MIT" ]
null
null
null
c02/2_8.cpp
brynhayder/accelerated-cpp
e26796486ba410db566c0f8acc392f32f20330a9
[ "MIT" ]
null
null
null
// Compute product of numbers in [1, 10) #include <iostream> int main(){ int sup = 10; int start = 1; int j = start; for (int i = 1; i != sup; i++){ j *= i; } std::cout << j << std::endl; return 0; }
17.214286
40
0.46888
brynhayder
36fcb56badb878b9545909bde5a5f58231e658df
1,004
cpp
C++
prime.cpp
Ki-Seki/codes-algorithm
8bb2204a700e489927276cec3506cd748cf8867f
[ "MIT" ]
null
null
null
prime.cpp
Ki-Seki/codes-algorithm
8bb2204a700e489927276cec3506cd748cf8867f
[ "MIT" ]
null
null
null
prime.cpp
Ki-Seki/codes-algorithm
8bb2204a700e489927276cec3506cd748cf8867f
[ "MIT" ]
null
null
null
/* * hint: * 素数相关的算法,包括: * 使用 sqrt 来优化的素数判断函数 * 使用平方技巧来优化的素数判断函数 * 求素数表:埃氏筛法,Eratosthenes 筛法 */ #include <iostream> #include <cmath> // 使用 sqrt 来优化的素数判断函数 // 需要 <cmath> bool is_prime(int n) { for (int i = 2; i <= (int) sqrt(n * 1.0); i++) if (n % i == 0) return false; return true; } // 使用平方技巧来优化的素数判断函数 // 缺点是若 n 较大,易产生溢出 bool is_prime_vice(int n) { for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } // 求素数表:埃氏筛法,Eratosthenes 筛法 // 时间复杂度 O(nloglogn) #define MAXN 100 // 素数表大小 int prime[MAXN + 5], p_len = 0; bool not_prime[MAXN * 20] = {}; // 找到 [2, n] 范围内的素数,保存至 prime[] void find_prime(int n) { for (int i = 2; i <= n; i++) if (not_prime[i] == false) { prime[p_len++] = i; for (int j = i + i; j <= n; j += i) not_prime[j] = true; } } int main() { find_prime(MAXN); for (int i = 0; i < p_len; i++) printf(" %d", prime[i]); }
18.943396
50
0.506972
Ki-Seki
36fdd20bb432b6609c99f6890af33f354a7f1bc4
30,332
cpp
C++
mainwindow.cpp
LaudateCorpus1/testcad
fd3fd325070d1e29732625b1e5b791f696a8dcd7
[ "MIT" ]
2
2018-11-15T12:51:38.000Z
2021-03-18T09:38:10.000Z
mainwindow.cpp
LaudateCorpus1/testcad
fd3fd325070d1e29732625b1e5b791f696a8dcd7
[ "MIT" ]
null
null
null
mainwindow.cpp
LaudateCorpus1/testcad
fd3fd325070d1e29732625b1e5b791f696a8dcd7
[ "MIT" ]
3
2021-03-18T09:38:30.000Z
2022-03-25T10:38:24.000Z
#include <QtWidgets> #include <QScreen> #include "mainwindow.h" MainWindow::MainWindow() { this->setWindowIcon(QIcon(":/icons/testCADIcon.png")); QStringList labels; labels << tr(STRING_COMPONENTS) << " ≠" << tr(STRING_COMMENTS); treeWidget = new QTreeWidget; treeWidget->setHeaderLabels(labels); treeWidget->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents); treeWidget->header()->setSectionResizeMode(1,QHeaderView::ResizeToContents); treeWidget->setContextMenuPolicy(Qt::CustomContextMenu); setCentralWidget(treeWidget); editor = new treeEditor(treeWidget); analyzer = new treeAnalyzer(treeWidget); icons = new iconsCatalog; collector = 0; combiner = 0; sequencer = 0; crossChecker = 0; connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), editor, SLOT(preventDiffColumnEdition(QTreeWidgetItem*,int))); connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(trackUnsavedChanges(QTreeWidgetItem*,int))); connect(treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); connect(treeWidget, SIGNAL(itemPressed(QTreeWidgetItem*,int)),this,SLOT(trackClicks(QTreeWidgetItem*))); createActions(); createMenus(); createToolbars(); statusBar()->showMessage(QObject::tr(STRING_READY)); setWindowTitle(QObject::tr(STRING_TESTCAD)); QScreen *screen = QGuiApplication::primaryScreen(); QSize newSize = screen->availableSize(); newSize.setHeight(newSize.height()*0.8); newSize.setWidth(newSize.width()*0.8); resize(newSize); hasChanges = false; historyFilePath = QDir::currentPath() + "/" + STRING_HISTORY_FILE; reloadOpenHistory(); } //---------------------------------------------------------------------------------------------------- void MainWindow::addToOpenHistory(QString filePath) { QFile hFile (historyFilePath); QTextStream history(&hFile); QString hLine; QStringList recentFiles; if (hFile.exists()){ hFile.open(QFile::ReadWrite | QFile::Text ); hLine = history.readLine(); while (hLine.length() > 0){ recentFiles.append(hLine + '\n'); hLine = history.readLine(); } hFile.remove(); } hFile.open(QFile::WriteOnly | QFile::Text ); if (!recentFiles.contains(filePath + '\n')){ recentFiles.prepend(filePath + '\n'); } for (int n = 0; n < recentFiles.length(); n++){ history << recentFiles.at(n); if (n > 5) break; } hFile.close();; } //---------------------------------------------------------------------------------------------------- void MainWindow::reloadOpenHistory() { QFile hFile (historyFilePath); QTextStream history(&hFile); QString hLine; recentFiles.clear(); if (hFile.exists()){ hFile.open(QFile::ReadOnly | QFile::Text ); hLine = history.readLine(); while (hLine.length() > 0){ recentFiles.append(hLine); hLine = history.readLine(); } } hFile.close(); historyMenu->clear(); for (int n = 0; n < recentFiles.length(); n++){ QAction *actBuff = historyMenu->addAction(recentFiles.at(n)); connect(actBuff, SIGNAL(triggered()), this, SLOT(openRecent())); actBuff->setCheckable(true); actBuff->setChecked(false); } } //---------------------------------------------------------------------------------------------------- void MainWindow::openRecent() { for (int n = 0; n < historyMenu->actions().count(); n++){ QAction *actBuff = historyMenu->actions().at(n); if (actBuff->isChecked()){ int decision = notSavedWarningResponse(); if(QMessageBox::Save == decision) { save(); treeWidget->clear(); openFromArgument(recentFiles.at(n)); hasChanges=false; }else if(QMessageBox::Ignore == decision){ treeWidget->clear(); openFromArgument(recentFiles.at(n)); hasChanges=false; } } actBuff->setChecked(false); } } //---------------------------------------------------------------------------------------------------- void MainWindow::openFromArgument(QString filePathParam) { treeOpener opener(treeWidget, this); opener.filePath = filePathParam; if (opener.openSelected(treeOpener::toLoad)){ filePath = opener.filePath; addToOpenHistory(filePath); setWindowTitleToFileName(); statusBar()->showMessage(QObject::tr(STRING_FILE_LOADED),2000); }else{ statusBar()->showMessage(QObject::tr(STRING_NO_FILE_LOADED),2000); } } //---------------------------------------------------------------------------------------------------- void MainWindow::openTreeFor(int editionType) { if (editionType == editing){ treeWidget->clear(); } treeOpener opener(treeWidget, this); if (opener.fileOpened()){ if (editionType != appending){ filePath = opener.filePath; addToOpenHistory(filePath); setWindowTitleToFileName(); } reloadOpenHistory(); statusBar()->showMessage(QObject::tr(STRING_FILE_LOADED),2000); }else{ statusBar()->showMessage(QObject::tr(STRING_NO_FILE_LOADED),2000); } } //---------------------------------------------------------------------------------------------------- void MainWindow::showSplashWindow() { splashWindow *spW = new splashWindow(this); spW->show(); } //---------------------------------------------------------------------------------------------------- void MainWindow::openDesignerWindow() { if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_COLLECTION){ if (collectorWindow::instance == 0){ collector = new collectorWindow(this, clickedItem); connect(collector, SIGNAL(saved()), this, SLOT(save())); collector->show(); } }else if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_COMBINATION){ if (combinerWindow::instance == 0){ combiner = new combinerWindow(this, clickedItem); connect(combiner, SIGNAL(saved()), this, SLOT(save())); combiner->show(); } }else if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_SEQUENCE){ if (sequencerWindow::instance == 0){ sequencer = new sequencerWindow(this, clickedItem); connect(sequencer, SIGNAL(saved()), this, SLOT(save())); sequencer->show(); } }else if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_CROSSCHECK){ if (crossCheckerWindow::instance == 0){ crossChecker = new crossCheckerWindow(this, clickedItem); connect(crossChecker, SIGNAL(saved()), this, SLOT(save())); crossChecker->show(); } } } //---------------------------------------------------------------------------------------------------- void MainWindow::trackClicks(QTreeWidgetItem *item) { clickedItem = item; editor->setClickedItem(item); analyzer->setClickedItem(item); if (collector != 0){ collectorWindow::clickedItem = item; } if (combiner != 0){ combinerWindow::clickedItem = item; } if (crossChecker != 0){ crossCheckerWindow::clickedItem = item; } } //---------------------------------------------------------------------------------------------------- void MainWindow::showContextMenu(QPoint point) { Q_UNUSED(point); QMenu contextMenu; if ((editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_GROUP) && (editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_COLLECTION) && (editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_COMBINATION) && (editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_SEQUENCE) && (editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_CROSSCHECK)){ contextMenu.addAction(markPlannedAct); contextMenu.addAction(markValidatedAct); contextMenu.addAction(markReviewAct); contextMenu.addAction(markPendingAct); contextMenu.addAction(markFailed); contextMenu.addAction(markUnsupported); contextMenu.addSeparator(); contextMenu.addAction(copyPathClipAct); contextMenu.addAction(copyBranchClipAct); contextMenu.addSeparator(); contextMenu.addAction(collapseAct); contextMenu.addAction(expandAct); contextMenu.addSeparator(); contextMenu.addAction(addMultipleAct); contextMenu.addSeparator(); contextMenu.addAction(copyVariableStats); contextMenu.addSeparator(); contextMenu.addAction(copyAct); contextMenu.addAction(cutAct); contextMenu.addAction(pasteAct); }else if (editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_GROUP){ contextMenu.addAction(addTestCollectionAct); contextMenu.addAction(addTestCombinationAct); contextMenu.addAction(addTestSequenceAct); contextMenu.addAction(addTestCrossCheckerAct); contextMenu.addSeparator(); contextMenu.addAction(collapseAct); contextMenu.addAction(expandAct); contextMenu.addSeparator(); contextMenu.addAction(pasteAct); }else if ((editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_COLLECTION) || (editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_COMBINATION)|| (editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_SEQUENCE)|| (editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_CROSSCHECK)){ contextMenu.addAction(openTestDesignerAct); contextMenu.addSeparator(); contextMenu.addAction(copyAct); contextMenu.addAction(cutAct); } contextMenu.exec(QCursor::pos()); } //---------------------------------------------------------------------------------------------------- void MainWindow::createToolbars() { QToolBar *tb = this->addToolBar(tr(STRING_MENU_TOOLS)); tb->setMovable(false); tb->addAction(openAct); tb->addAction(saveAct); tb->addAction(saveAsAct); tb->addSeparator(); tb->addAction(addComponentAct); tb->addSeparator(); tb->addAction(copyAct); tb->addAction(cutAct); tb->addAction(pasteAct); tb->addAction(deleteAct); tb->addAction(undoAct); tb->addAction(moveUpAct); tb->addAction(moveDownAct); tb->addSeparator(); tb->addAction(searchAct); tb->addAction(findFailedAct); tb->addAction(findReviewAct); tb->addAction(findUnsupportedAct); tb->addAction(findPendingAct); tb->addAction(findPlannedAct); tb->addAction(findPassedAct); tb->addAction(showStatsAct); tb->addSeparator(); tb->addAction(addTestGroupAct); tb->addAction(addTestCollectionAct); tb->addAction(addTestCombinationAct); tb->addAction(addTestSequenceAct); tb->addAction(addTestCrossCheckerAct); tb->addSeparator(); tb->addAction(clearHighlightsAct); } //---------------------------------------------------------------------------------------------------- void MainWindow::closeEvent(QCloseEvent *event) { int decision = notSavedWarningResponse(); bool deleteChildren = false; if(QMessageBox::Save == decision) { save(); deleteChildren = true; }else if(QMessageBox::Ignore == decision) { deleteChildren = true; }else if(QMessageBox::Cancel == decision) { event->ignore(); } if (deleteChildren){ if (collectorWindow::instance != 0) delete(collector); if (combinerWindow::instance != 0) delete(combiner); if (crossCheckerWindow::instance != 0) delete(crossChecker); if (sequencerWindow::instance != 0) delete(sequencer); event->accept(); } } //---------------------------------------------------------------------------------------------------- void MainWindow::exportImage() { treeSaver saver(treeWidget, this); saver.exportTreeToImage(); } //---------------------------------------------------------------------------------------------------- void MainWindow::clearHighlights() { treeEditor::clearHighlightsIn(treeWidget); clearHighlightsAct->setVisible(false); } //---------------------------------------------------------------------------------------------------- void MainWindow::trackUnsavedChanges(QTreeWidgetItem *item, int column) { Q_UNUSED(item); Q_UNUSED(column); hasChanges = true; } //---------------------------------------------------------------------------------------------------- void MainWindow::compare() { treeOpener opener(treeWidget, this); opener.selectToCompare(); analyzer->showDiffWith(opener.diffHashTable); } //---------------------------------------------------------------------------------------------------- void MainWindow::setWindowTitleToFileName() { if(!filePath.isEmpty()){ QFileInfo details; details.setFile(filePath); setWindowTitle(details.fileName()); }else{ setWindowTitle(QObject::tr(STRING_TESTCAD)); } } //---------------------------------------------------------------------------------------------------- int MainWindow::notSavedWarningResponse() { QMessageBox msgBox; msgBox.setText(STRING_UNSAVEDCHANGES_DIALOG_TITLE); msgBox.setInformativeText(STRING_SAVE_BEFORE); msgBox.setIcon(QMessageBox::Warning); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Ignore); msgBox.setDefaultButton(QMessageBox::Save); int decision = QMessageBox::Ignore; if(hasChanges) { decision = msgBox.exec(); } return decision; } //---------------------------------------------------------------------------------------------------- void MainWindow::show() { QMainWindow::show(); showSplashWindow(); } //---------------------------------------------------------------------------------------------------- void MainWindow::open() { int decision = notSavedWarningResponse(); if(QMessageBox::Save == decision) { save(); hasChanges=false; }else if(QMessageBox::Ignore == decision){ openTreeFor(editing); hasChanges=false; } } //---------------------------------------------------------------------------------------------------- void MainWindow::append() { openTreeFor(appending); hasChanges=true; } //---------------------------------------------------------------------------------------------------- void MainWindow::save() { treeSaver saver(treeWidget, this); if (!filePath.isEmpty()){ if(saver.saveTreeTo(filePath)){ statusBar()->showMessage(QObject::tr(STRING_FILE_SAVED),2000); hasChanges = false; }else{ statusBar()->showMessage(QObject::tr(STRING_FILE_NOT_SAVED),2000); } }else{ saveAs(); } } //---------------------------------------------------------------------------------------------------- void MainWindow::saveAs() { treeSaver saver(treeWidget, this); if(saver.saveTreeAs()){ filePath = saver.filePath; setWindowTitleToFileName(); statusBar()->showMessage(QObject::tr(STRING_FILE_SAVED),2000); hasChanges = false; }else{ statusBar()->showMessage(QObject::tr(STRING_FILE_NOT_SAVED),2000); } } //---------------------------------------------------------------------------------------------------- void MainWindow::closeTree() { int decision = notSavedWarningResponse(); if(QMessageBox::Save == decision) { save(); hasChanges = false; }else if(QMessageBox::Ignore == decision) { treeWidget->clear(); hasChanges = false; } } //---------------------------------------------------------------------------------------------------- void MainWindow::about() { QMessageBox::about(this, tr(STRING_ABOUT_TESTCAD), tr(ABOUT_TEXT) + tr("Version:") + " " + tr(STRING_VERSION_NUMBER)); } //---------------------------------------------------------------------------------------------------- void MainWindow::createActions() { createFileActions(); createInsertActions(); createEditActions(); createViewActions(); createToolsActions(); createTestActions(); createHelpActions(); } //---------------------------------------------------------------------------------------------------- void MainWindow::createFileActions() { openAct = new QAction(icons->openIcon,tr(STRING_ACTION_OPEN), this); openAct->setShortcuts(QKeySequence::Open); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); saveAct = new QAction(tr(STRING_ACTION_SAVE), this); saveAct->setIcon(icons->saveIcon); saveAct->setShortcuts(QKeySequence::Save); connect(saveAct, SIGNAL(triggered()), this, SLOT(save())); saveAsAct = new QAction(tr(STRING_ACTION_SAVE_AS), this); saveAsAct->setShortcuts(QKeySequence::SaveAs); saveAsAct->setIcon(icons->saveAsIcon); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); appendAct = new QAction(QIcon(":/icons/appendIcon.png"),tr(STRING_ACTION_APPEND), this); connect(appendAct, SIGNAL(triggered()), this, SLOT(append())); closeTreeAct = new QAction(tr("Close"), this); connect(closeTreeAct, SIGNAL(triggered()), this, SLOT(closeTree())); exitAct = new QAction(tr(STRING_ACTION_EXIT), this); exitAct->setShortcuts(QKeySequence::Quit); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); } //---------------------------------------------------------------------------------------------------- void MainWindow::createEditActions() { markPendingAct = new QAction(tr(STRING_ACTION_MARK_PENDING), this); markPendingAct->setIcon(icons->pendingIcon); markPendingAct->setShortcut(QKeySequence(tr("Ctrl+E"))); connect(markPendingAct, SIGNAL(triggered()), editor, SLOT(markAsPending())); markPlannedAct = new QAction(tr(STRING_ACTION_MARK_PLANNED), this); markPlannedAct->setIcon(icons->plannedIcon); markPlannedAct->setShortcut(QKeySequence(tr("Ctrl+A"))); connect(markPlannedAct, SIGNAL(triggered()), editor, SLOT(markAsPlanned())); markValidatedAct = new QAction(tr(STRING_ACTION_MARK_VALIDATED), this); markValidatedAct->setIcon(icons->validatedIcon); markValidatedAct->setShortcut(QKeySequence(tr("Ctrl+P"))); connect(markValidatedAct, SIGNAL(triggered()), editor, SLOT(markAsValidated())); markReviewAct = new QAction(tr(STRING_ACTION_MARK_REVIEW), this); markReviewAct->setIcon(icons->reviewIcon); markReviewAct->setShortcut(QKeySequence(tr("Ctrl+R"))); connect(markReviewAct, SIGNAL(triggered()), editor, SLOT(markAsReview())); markFailed = new QAction(tr(STRING_ACTION_MARK_FAILED), this); markFailed->setIcon(icons->failedIcon); markFailed->setShortcut(QKeySequence(tr("Ctrl+L"))); connect(markFailed, SIGNAL(triggered()), editor, SLOT(markAsFailed())); markUnsupported = new QAction(tr(STRING_ACTION_MARK_UNSUPPORTED), this); markUnsupported->setIcon(icons->unsupportedIcon); connect(markUnsupported, SIGNAL(triggered()), editor, SLOT(markAsUnsupported())); deleteAct = new QAction(tr(STRING_ACTION_DELETE), this); deleteAct->setIcon(icons->deleteIcon); deleteAct->setShortcut(QKeySequence::Delete); connect(deleteAct, SIGNAL(triggered()), editor, SLOT(removeItem())); undoAct = new QAction(tr(STRING_ACTION_UNDO), this); undoAct->setIcon(icons->undoIcon); undoAct->setShortcut(QKeySequence::Undo); connect(undoAct, SIGNAL(triggered()), editor, SLOT(undo())); copyAct = new QAction(tr(STRING_ACTION_COPY), this); copyAct->setIcon(icons->copyIcon); copyAct->setShortcut(QKeySequence::Copy); connect(copyAct, SIGNAL(triggered()), editor, SLOT(copy())); cutAct = new QAction(tr(STRING_ACTION_CUT), this); cutAct->setIcon(icons->cutIcon); cutAct->setShortcut(QKeySequence::Cut); connect(cutAct, SIGNAL(triggered()), editor, SLOT(cut())); pasteAct = new QAction(tr(STRING_ACTION_PASTE), this); pasteAct->setIcon(icons->pasteIcon); pasteAct->setShortcut(QKeySequence::Paste); connect(pasteAct, SIGNAL(triggered()), editor, SLOT(paste())); moveUpAct = new QAction(tr(STRING_ACTION_MOVE_UP), this); moveUpAct->setIcon(icons->upIcon); moveUpAct->setShortcut(QKeySequence(tr("Ctrl+U"))); connect(moveUpAct, SIGNAL(triggered()), editor, SLOT(moveUp())); moveDownAct = new QAction(tr(STRING_ACTION_MOVE_DOWN), this); moveDownAct->setIcon(icons->downIcon); moveDownAct->setShortcut(QKeySequence(tr("Ctrl+D"))); connect(moveDownAct, SIGNAL(triggered()), editor, SLOT(moveDown())); } //---------------------------------------------------------------------------------------------------- void MainWindow::createInsertActions() { addComponentAct = new QAction(tr(STRING_ACTION_ADD_COMPONENT), this); addComponentAct->setIcon(icons->addTopIcon); connect(addComponentAct, SIGNAL(triggered()), editor, SLOT(addComponent())); addMultipleAct = new QAction(tr(STRING_ACTION_ADD), this); addMultipleAct->setIcon(icons->addIcon); connect(addMultipleAct, SIGNAL(triggered()), editor, SLOT(addMultiple())); } //---------------------------------------------------------------------------------------------------- void MainWindow::createViewActions() { findFailedAct = new QAction(tr(STRING_ACTION_SHOW_FAILED), this); findFailedAct->setIcon(icons->findFailedIcon); connect(findFailedAct, SIGNAL(triggered()), editor, SLOT(showMissing())); findReviewAct = new QAction(tr(STRING_ACTION_SHOW_REVIEW), this); findReviewAct->setIcon(icons->findReviewIcon); connect(findReviewAct, SIGNAL(triggered()), editor, SLOT(showReview())); findPlannedAct = new QAction(tr(STRING_ACTION_SHOW_PLANNED), this); findPlannedAct->setIcon(icons->findPlannedIcon); connect(findPlannedAct, SIGNAL(triggered()), editor, SLOT(showPlanned())); findPendingAct = new QAction(tr(STRING_ACTION_SHOW_PENDING), this); findPendingAct->setIcon(icons->findPendingIcon); connect(findPendingAct, SIGNAL(triggered()), editor, SLOT(showPending())); findPassedAct = new QAction(tr(STRING_ACTION_SHOW_VALIDATED), this); findPassedAct->setIcon(icons->findPassedIcon); connect(findPassedAct, SIGNAL(triggered()), editor, SLOT(showValidated())); findUnsupportedAct = new QAction(tr(STRING_ACTION_SHOW_UNSUPPORTED), this); findUnsupportedAct->setIcon(icons->findUnsupportedIcon); connect(findUnsupportedAct, SIGNAL(triggered()), editor, SLOT(showUnsupported())); collapseAct = new QAction(tr(STRING_ACTION_COLLAPSE), this); connect(collapseAct, SIGNAL(triggered()), editor, SLOT(collapseSelected())); expandAct = new QAction(tr(STRING_ACTION_EXPAND), this); connect(expandAct, SIGNAL(triggered()), editor, SLOT(expandSelected())); collapseAllAct = new QAction(tr(STRING_ACTION_COLLAPSE_ALL), this); connect(collapseAllAct, SIGNAL(triggered()), editor, SLOT(collapseAll())); expandAllAct = new QAction(tr(STRING_ACTION_EXPAND_ALL), this); connect(expandAllAct, SIGNAL(triggered()), editor, SLOT(expandAll())); } //---------------------------------------------------------------------------------------------------- void MainWindow::search() { editor->search(); clearHighlightsAct->setVisible(true); } //---------------------------------------------------------------------------------------------------- void MainWindow::createToolsActions() { searchAct = new QAction(tr(STRING_ACTION_SEARCH), this); searchAct->setIcon(icons->searchIcon); searchAct->setShortcut(QKeySequence::Find); connect(searchAct, SIGNAL(triggered()), this, SLOT(search())); copyPathClipAct = new QAction(QObject::tr(STRING_ACTION_COPY_PATH_TO_CLIPBOARD), this); copyPathClipAct->setIcon(icons->pathIcon); connect(copyPathClipAct, SIGNAL(triggered()), analyzer, SLOT(copyPathToClipBoard())); copyBranchClipAct= new QAction(QObject::tr(STRING_ACTION_COPY_BRANCH_TO_CLIPBOARD), this); copyBranchClipAct->setIcon(icons->copyBranchIcon); connect(copyBranchClipAct, SIGNAL(triggered()), analyzer, SLOT(copyBranchToClipboard())); showStatsAct = new QAction(QObject::tr(STRING_ACTION_SHOW_STATISTICS), this); showStatsAct->setIcon(icons->statsIcon); connect(showStatsAct, SIGNAL(triggered()), analyzer, SLOT(showStatistics())); showDiffAct = new QAction(QObject::tr(STRING_ACTION_COMPARE), this); connect(showDiffAct, SIGNAL(triggered()), this, SLOT(compare())); exportImageAct = new QAction(icons->pictureIcon, QObject::tr(STRING_ACTION_EXPORT_IMAGE), this); connect(exportImageAct, SIGNAL(triggered()), this, SLOT(exportImage())); clearHighlightsAct = new QAction(QObject::tr(STRING_ACTION_CLEAR_HIGHLIGHTS), this); clearHighlightsAct->setShortcut(QKeySequence(tr("Ctrl+H"))); clearHighlightsAct->setIcon(icons->clearHighlightsIcon); clearHighlightsAct->setVisible(false); connect(clearHighlightsAct, SIGNAL(triggered()), this, SLOT(clearHighlights())); copyVariableStats = new QAction(QIcon(":/icons/statsIcon.png"),QObject::tr("Copy variable statistics"), this); connect(copyVariableStats, SIGNAL(triggered()), analyzer, SLOT(copyVariableStatisticsToClipboard())); } //---------------------------------------------------------------------------------------------------- void MainWindow::createTestActions() { addTestGroupAct = new QAction(tr("Add a test group"), this); addTestGroupAct->setIcon(icons->testGroupIcon); connect(addTestGroupAct, SIGNAL(triggered()), editor, SLOT(addTestGroup())); addTestCollectionAct = new QAction(tr("Add a collection"), this); addTestCollectionAct->setIcon(icons->testCollectionIcon); connect(addTestCollectionAct, SIGNAL(triggered()), editor, SLOT(addTestCollection())); addTestCombinationAct = new QAction(tr("Add a combination"), this); addTestCombinationAct->setIcon(icons->testCombinationIcon); connect(addTestCombinationAct, SIGNAL(triggered()), editor, SLOT(addTestCombination())); addTestSequenceAct = new QAction(tr("Add a sequence"), this); addTestSequenceAct->setIcon(icons->testSequenceIcon); connect(addTestSequenceAct, SIGNAL(triggered()), editor, SLOT(addTestSequence())); openTestDesignerAct = new QAction(icons->designerIcon,tr("Open designer"), this); connect(openTestDesignerAct, SIGNAL(triggered()), this, SLOT(openDesignerWindow())); addTestCrossCheckerAct = new QAction(tr("Add a cross checker"), this); addTestCrossCheckerAct->setIcon(icons->testCrossCheckerIcon); connect(addTestCrossCheckerAct, SIGNAL(triggered()), editor, SLOT(addTestCrossChecker())); } //---------------------------------------------------------------------------------------------------- void MainWindow::createHelpActions() { aboutAct = new QAction(tr("About..."), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } //---------------------------------------------------------------------------------------------------- void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(openAct); fileMenu->addAction(saveAsAct); fileMenu->addAction(saveAct); fileMenu->addSeparator(); fileMenu->addAction(appendAct); fileMenu->addSeparator(); fileMenu->addAction(closeTreeAct); fileMenu->addAction(exitAct); fileMenu->addSeparator(); historyMenu = new QMenu("Recent files..."); fileMenu->addMenu(historyMenu); menuBar()->addSeparator(); editMenu = menuBar()->addMenu(tr("Edit")); editMenu->addAction(addComponentAct); editMenu->addSeparator(); editMenu->addAction(searchAct); editMenu->addAction(moveUpAct); editMenu->addAction(moveDownAct); editMenu->addSeparator(); editMenu->addAction(markPlannedAct); editMenu->addAction(markValidatedAct); editMenu->addAction(markReviewAct); editMenu->addAction(markPendingAct); editMenu->addAction(markFailed); editMenu->addAction(markUnsupported); editMenu->addSeparator(); editMenu->addAction(copyAct); editMenu->addAction(cutAct); editMenu->addAction(pasteAct); editMenu->addSeparator(); editMenu->addAction(deleteAct); editMenu->addSeparator(); editMenu->addAction(undoAct); menuBar()->addSeparator(); viewMenu = menuBar()->addMenu(tr("View")); viewMenu->addAction(clearHighlightsAct); editMenu->addSeparator(); viewMenu->addAction(findFailedAct); viewMenu->addAction(findReviewAct); viewMenu->addAction(findUnsupportedAct); viewMenu->addAction(findPendingAct); viewMenu->addAction(findPlannedAct); viewMenu->addAction(findPassedAct); viewMenu->addSeparator(); viewMenu->addAction(expandAllAct); viewMenu->addAction(collapseAllAct); viewMenu->addSeparator(); viewMenu->addAction(expandAct); viewMenu->addAction(collapseAct); menuBar()->addSeparator(); toolsMenu = menuBar()->addMenu(tr("Tools")); toolsMenu->addAction(showStatsAct); toolsMenu->addSeparator(); toolsMenu->addAction(exportImageAct); toolsMenu->addSeparator(); toolsMenu->addAction(showDiffAct); menuBar()->addSeparator(); testMenu = menuBar()->addMenu(tr("Test")); testMenu->addAction(addTestGroupAct); testMenu->addAction(addTestCollectionAct); testMenu->addAction(addTestCombinationAct); testMenu->addAction(addTestSequenceAct); testMenu->addAction(addTestCrossCheckerAct); testMenu->addSeparator(); menuBar()->addSeparator(); helpMenu = menuBar()->addMenu(tr("Help")); helpMenu->addAction(aboutAct); }
33.553097
129
0.603356
LaudateCorpus1
3c03e17ef65317f049b8248ef42a63996158f3fd
2,903
hpp
C++
src/ucx/endpoint.hpp
biddisco/oomph
df6d2251b9ce49da9394bb8c06de65bbb034cdff
[ "BSD-3-Clause" ]
null
null
null
src/ucx/endpoint.hpp
biddisco/oomph
df6d2251b9ce49da9394bb8c06de65bbb034cdff
[ "BSD-3-Clause" ]
null
null
null
src/ucx/endpoint.hpp
biddisco/oomph
df6d2251b9ce49da9394bb8c06de65bbb034cdff
[ "BSD-3-Clause" ]
null
null
null
/* * GridTools * * Copyright (c) 2014-2021, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause * */ #pragma once #include <oomph/communicator.hpp> #include <oomph/util/moved_bit.hpp> #include "./address.hpp" #include <chrono> #ifndef NDEBUG #include <iostream> #endif namespace oomph { #define OOMPH_ANY_SOURCE (int)-1 struct endpoint_t { using rank_type = communicator::rank_type; rank_type m_rank; ucp_ep_h m_ep; ucp_worker_h m_worker; util::moved_bit m_moved; endpoint_t() noexcept : m_moved(true) { } endpoint_t(rank_type rank, ucp_worker_h local_worker, const address_t& remote_worker_address) : m_rank(rank) , m_worker{local_worker} { ucp_ep_params_t ep_params; ep_params.field_mask = UCP_EP_PARAM_FIELD_REMOTE_ADDRESS; ep_params.address = remote_worker_address.get(); OOMPH_CHECK_UCX_RESULT(ucp_ep_create(local_worker, &ep_params, &(m_ep))); } endpoint_t(const endpoint_t&) = delete; endpoint_t& operator=(const endpoint_t&) = delete; endpoint_t(endpoint_t&& other) noexcept = default; endpoint_t& operator=(endpoint_t&& other) noexcept { destroy(); m_ep.~ucp_ep_h(); ::new ((void*)(&m_ep)) ucp_ep_h{other.m_ep}; m_rank = other.m_rank; m_worker = other.m_worker; m_moved = std::move(other.m_moved); return *this; } ~endpoint_t() { destroy(); } void destroy() { if (!m_moved) { ucs_status_ptr_t ret = ucp_ep_close_nb(m_ep, UCP_EP_CLOSE_MODE_FLUSH); if (UCS_OK == reinterpret_cast<std::uintptr_t>(ret)) return; if (UCS_PTR_IS_ERR(ret)) return; // wait untile the ep is destroyed, free the request const auto t0 = std::chrono::system_clock::now(); double elapsed = 0.0; static constexpr double t_timeout = 2000; while (UCS_OK != ucp_request_check_status(ret)) { elapsed = std::chrono::duration<double, std::milli>(std::chrono::system_clock::now() - t0) .count(); if (elapsed > t_timeout) break; ucp_worker_progress(m_worker); } #ifndef NDEBUG if (elapsed > t_timeout) std::cerr << "WARNING: timeout waiting for UCX endpoint close" << std::endl; #endif ucp_request_free(ret); } } //operator bool() const noexcept { return m_moved; } operator ucp_ep_h() const noexcept { return m_ep; } rank_type rank() const noexcept { return m_rank; } ucp_ep_h& get() noexcept { return m_ep; } const ucp_ep_h& get() const noexcept { return m_ep; } }; } // namespace oomph
28.460784
100
0.605236
biddisco
3c04b9ae8784aaee3a69e010701e3c2c96eb94a6
379
cpp
C++
cpp_analysis/bin/example.cpp
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
[ "BSD-3-Clause" ]
null
null
null
cpp_analysis/bin/example.cpp
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
[ "BSD-3-Clause" ]
null
null
null
cpp_analysis/bin/example.cpp
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
[ "BSD-3-Clause" ]
null
null
null
#include "TString.h" #include "friendTreeInjector.h" #include <iostream> int main(int argc, char* argv[]){ if(argc<2) return -1; TString infile = argv[1]; friendTreeInjector intree; intree.addFromFile(infile); intree.setSourceTreeName("tree"); intree.createChain(); auto c = intree.getChain(); std::cout << c->GetEntries() <<std::endl; }
16.478261
45
0.646438
shahrukhqasim
3c05633c545f47b9d3e23b1d3bc6f5a6bc1702e6
1,318
cpp
C++
src/cpp/DP/dp_minimus_path_sum.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
src/cpp/DP/dp_minimus_path_sum.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
1
2018-10-24T05:48:27.000Z
2018-10-24T05:52:14.000Z
src/cpp/DP/dp_minimus_path_sum.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
/* Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example: Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum. */ #include <iostream> #include <vector> using namespace std; class Solution { public: int minPathSum(vector<vector<int>> & grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = grid[0][0]; for (int j = 1; j < n; ++j) dp[0][j] = grid[0][j] + dp[0][j-1]; for (int i = 1; i < m; ++i) { dp[i][0] = grid[i][0] + dp[i-1][0]; for (int j = 1; j < n; ++j) { dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; } } return dp[m-1][n-1]; } }; int main() { Solution sol = Solution(); freopen("data.in", "r", stdin); int m, n, t; cin >> m >> n; vector<vector<int>> grid(m, vector<int>(n, 0)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { cin >> t; grid[i][j] = t; } cout << sol.minPathSum(grid) << endl; return 0; }
23.535714
149
0.492413
spurscoder
3c077ea42a66e002809b23be1a8b2645f6657c2b
2,980
cpp
C++
SierraChart2/Time.cpp
AndrewAMD/SierraChartZorroPlugin
43d3645e17a8349fb6d3dffa541c91d0a51222d7
[ "MIT" ]
26
2018-11-09T07:43:49.000Z
2021-09-10T06:15:47.000Z
SierraChart2/Time.cpp
AndrewAMD/SierraChartZorroPlugin
43d3645e17a8349fb6d3dffa541c91d0a51222d7
[ "MIT" ]
1
2021-02-02T11:50:42.000Z
2021-02-02T13:58:08.000Z
SierraChart2/Time.cpp
AndrewAMD/SierraChartZorroPlugin
43d3645e17a8349fb6d3dffa541c91d0a51222d7
[ "MIT" ]
10
2019-01-03T08:38:30.000Z
2022-03-30T02:26:57.000Z
#include "pch.h" #include "framework.h" #include <Windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "Time.h" #include "StrBufs.h" #include "client.h" #include "banned.h" //must include last int g_RequestRateLimit_ms = 100; namespace cro = std::chrono; cro::steady_clock::time_point g_NextRequestTp = cro::steady_clock::now(); bool can_request_now() { return cro::steady_clock::now() > g_NextRequestTp; } bool delay_request(bool double_delay) { auto limit_ms = g_RequestRateLimit_ms; if (double_delay) limit_ms *= 2; while (!can_request_now()) { cl_drain(); if (!refresh()) return false; cl_loiter(); } g_NextRequestTp = cro::steady_clock::now() + cro::milliseconds(limit_ms); return true; } DATE vEpochSeconds_to_date(double vEpochSeconds){ return vEpochSeconds / (24ll * 60ll * 60ll) + 25569ll; // 25569. = DATE(1.1.1970 00:00) } DATE llEpochMicroseconds_to_date(long long llEpochMicroseconds) { return ((double)llEpochMicroseconds) / (1000000ll * (24ll * 60ll * 60ll)) + 25569ll; // 25569. = DATE(1.1.1970 00:00) } double date_to_vEpochSeconds(DATE date){ return (double)((date - 25569ll) * (24ll * 60ll * 60ll)); } void set_time_zone(const char* sTZ) { _putenv_s("TZ", sTZ); _tzset(); return; } int epochmilli_str_to_yyyymmdd(const char* emilli) { __time32_t t32 = (__time32_t)(strtod(emilli, NULL) / 1000); if (!t32) return 0; // parse failure struct tm tm1 = { 0 }; set_time_zone("UTC0"); if (_localtime32_s(&tm1, &t32)) { return 0;// error } int y = tm1.tm_year + 1900; int m = tm1.tm_mon + 1; int d = tm1.tm_mday; return y * 10000 + m * 100 + d; } int get_todays_date_yyyymmdd() { __time32_t t32 = 0; struct tm tm1 = { 0 }; _time32(&t32); set_time_zone("UTC0"); _localtime32_s(&tm1, &t32); int y = tm1.tm_year + 1900; int m = tm1.tm_mon + 1; int d = tm1.tm_mday; return y * 10000 + m * 100 + d; } int vEpochSeconds_to_todays_date_yyyymmdd(double vEpochSeconds) { __time32_t t32 = lround(vEpochSeconds); struct tm tm1 = { 0 }; set_time_zone("UTC0"); _localtime32_s(&tm1, &t32); int y = tm1.tm_year + 1900; int m = tm1.tm_mon + 1; int d = tm1.tm_mday; return y * 10000 + m * 100 + d; } char get_monthchar(int monthnum) { //0=jan, 1=feb ... 11=dec. switch (monthnum) { case 0: return 'F';//jan case 1: return 'G';//feb case 2: return 'H'; case 3: return 'J'; case 4: return 'K'; case 5: return 'M'; case 6: return 'N'; case 7: return 'Q'; case 8: return 'U'; case 9: return 'V'; case 10: return 'X'; case 11: return 'Z'; //dec default: return '_'; //fail } } const char* get_monthcode_string(int month_flags) { static char out[13]; memset(out, 0, 13); int i = 0; char ch[2] = { 0,0 }; for (i = 0; i < 12; i++) { if ((1 << i) & month_flags) { ch[0] = get_monthchar(i); strcat_s(out,13, ch); } } return out; }
25.042017
119
0.632215
AndrewAMD
3c0b3cd97beaebbf482b79a10e1560101192cf5f
423
cpp
C++
src/libs/router_db/Constants.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/libs/router_db/Constants.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/libs/router_db/Constants.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "keto/router_db/Constants.hpp" namespace keto { namespace router_db { const char* Constants::ROUTER_INDEX = "routes"; const std::vector<std::string> Constants::DB_LIST = {Constants::ROUTER_INDEX}; } }
16.92
79
0.699764
burntjam
3c0cd3ea765a310ea68a85662f4612d06c3e8a03
117
cpp
C++
tests/Issue182.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
1,853
2018-05-13T21:49:17.000Z
2022-03-30T10:34:45.000Z
tests/Issue182.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
398
2018-05-15T14:48:51.000Z
2022-03-24T12:14:33.000Z
tests/Issue182.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
104
2018-05-15T04:00:59.000Z
2022-03-17T02:04:15.000Z
typedef int my_cb(int dst, int len, int dat); int f(my_cb cb, void *dat); int f(my_cb cb, void *dat) { return 0; }
14.625
45
0.649573
galorojo
3c0d3bbd4140c391ef55f48e7426fd4b2ea3e05c
6,289
cpp
C++
lib/CIndexStoreDB/CIndexStoreDB.cpp
gmittert/indexstore-db
31ff487bd8d10531a9af761e4ecc1c929ccee2ff
[ "Apache-2.0" ]
1
2021-07-07T15:38:50.000Z
2021-07-07T15:38:50.000Z
lib/CIndexStoreDB/CIndexStoreDB.cpp
DalavanCloud/indexstore-db
b1258a6827e988a4d9988e5fddf4d4e95cbd59bb
[ "Apache-2.0" ]
null
null
null
lib/CIndexStoreDB/CIndexStoreDB.cpp
DalavanCloud/indexstore-db
b1258a6827e988a4d9988e5fddf4d4e95cbd59bb
[ "Apache-2.0" ]
null
null
null
//===--- CIndexStoreDB.cpp ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "CIndexStoreDB/CIndexStoreDB.h" #include "IndexStoreDB/Index/IndexStoreLibraryProvider.h" #include "IndexStoreDB/Index/IndexSystem.h" #include "IndexStoreDB/Index/IndexSystemDelegate.h" #include "IndexStoreDB/Core/Symbol.h" #include "indexstore/IndexStoreCXX.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include <Block.h> using namespace IndexStoreDB; using namespace index; class IndexStoreDBObjectBase : public llvm::ThreadSafeRefCountedBase<IndexStoreDBObjectBase> { public: virtual ~IndexStoreDBObjectBase() {} }; template <typename T> class IndexStoreDBObject: public IndexStoreDBObjectBase { public: T value; IndexStoreDBObject(T value) : value(std::move(value)) {} }; template <typename T> static IndexStoreDBObject<T> *make_object(const T &value) { auto obj = new IndexStoreDBObject<T>(value); obj->Retain(); return obj; } struct IndexStoreDBError { std::string message; IndexStoreDBError(StringRef message) : message(message.str()) {} }; class BlockIndexStoreLibraryProvider : public IndexStoreLibraryProvider { indexstore_library_provider_t callback; public: BlockIndexStoreLibraryProvider(indexstore_library_provider_t callback) : callback(Block_copy(callback)) {} ~BlockIndexStoreLibraryProvider() { Block_release(callback); } IndexStoreLibraryRef getLibraryForStorePath(StringRef storePath) override { indexstore_functions_t api; if (auto lib = callback(storePath.str().c_str())) { auto *obj = (IndexStoreDBObject<IndexStoreLibraryRef> *)lib; return obj->value; } else { return nullptr; } } }; indexstoredb_index_t indexstoredb_index_create(const char *storePath, const char *databasePath, indexstore_library_provider_t libProvider, // delegate, bool readonly, indexstoredb_error_t *error) { auto delegate = std::make_shared<IndexSystemDelegate>(); auto libProviderObj = std::make_shared<BlockIndexStoreLibraryProvider>(libProvider); std::string errMsg; if (auto index = IndexSystem::create(storePath, databasePath, libProviderObj, delegate, readonly, llvm::None, errMsg)) { return make_object(index); } else if (error) { *error = (indexstoredb_error_t)new IndexStoreDBError(errMsg); } return nullptr; } indexstoredb_indexstore_library_t indexstoredb_load_indexstore_library(const char *dylibPath, indexstoredb_error_t *error) { std::string errMsg; if (auto lib = loadIndexStoreLibrary(dylibPath, errMsg)) { return make_object(lib); } else if (error) { *error = (indexstoredb_error_t)new IndexStoreDBError(errMsg); } return nullptr; } bool indexstoredb_index_symbol_occurrences_by_usr( indexstoredb_index_t index, const char *usr, uint64_t roles, indexstoredb_symbol_occurrence_receiver_t receiver) { auto obj = (IndexStoreDBObject<std::shared_ptr<IndexSystem>> *)index; return obj->value->foreachSymbolOccurrenceByUSR(usr, (SymbolRoleSet)roles, [&](SymbolOccurrenceRef Occur) -> bool { return receiver(make_object(Occur)); }); } bool indexstoredb_index_related_symbol_occurrences_by_usr( indexstoredb_index_t index, const char *usr, uint64_t roles, indexstoredb_symbol_occurrence_receiver_t receiver) { auto obj = (IndexStoreDBObject<std::shared_ptr<IndexSystem>> *)index; return obj->value->foreachRelatedSymbolOccurrenceByUSR(usr, (SymbolRoleSet)roles, [&](SymbolOccurrenceRef Occur) -> bool { return receiver(make_object(Occur)); }); } const char * indexstoredb_symbol_usr(indexstoredb_symbol_t symbol) { auto obj = (IndexStoreDBObject<std::shared_ptr<Symbol>> *)symbol; return obj->value->getUSR().c_str(); } const char * indexstoredb_symbol_name(indexstoredb_symbol_t symbol) { auto obj = (IndexStoreDBObject<std::shared_ptr<Symbol>> *)symbol; return obj->value->getName().c_str(); } indexstoredb_symbol_t indexstoredb_symbol_occurrence_symbol(indexstoredb_symbol_occurrence_t occur) { auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur; return make_object(obj->value->getSymbol()); } uint64_t indexstoredb_symbol_occurrence_roles(indexstoredb_symbol_occurrence_t occur) { auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur; return (uint64_t)obj->value->getRoles(); } indexstoredb_symbol_location_t indexstoredb_symbol_occurrence_location( indexstoredb_symbol_occurrence_t occur) { auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur; return (indexstoredb_symbol_location_t)&obj->value->getLocation(); } const char * indexstoredb_symbol_location_path(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->getPath().getPathString().c_str(); } bool indexstoredb_symbol_location_is_system(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->isSystem(); } int indexstoredb_symbol_location_line(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->getLine(); } int indexstoredb_symbol_location_column_utf8(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->getColumn(); } indexstoredb_object_t indexstoredb_retain(indexstoredb_object_t obj) { if (obj) ((IndexStoreDBObjectBase *)obj)->Retain(); return obj; } void indexstoredb_release(indexstoredb_object_t obj) { if (obj) ((IndexStoreDBObjectBase *)obj)->Release(); } const char * indexstoredb_error_get_description(indexstoredb_error_t error) { return ((IndexStoreDBError *)error)->message.c_str(); } void indexstoredb_error_dispose(indexstoredb_error_t error) { if (error) delete (IndexStoreDBError *)error; }
29.805687
86
0.732231
gmittert
3c0ddf64227cf33b25892c86a24f34c8c134766c
219,191
cpp
C++
multimedia/directx/dsound/dsound/dsbuf.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/dsound/dsound/dsbuf.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/dsound/dsound/dsbuf.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*************************************************************************** * * Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved. * * File: dsbuf.cpp * Content: DirectSound Buffer object * History: * Date By Reason * ==== == ====== * 12/27/96 dereks Created * 1999-2001 duganp Many changes, fixes and updates * ***************************************************************************/ #include "dsoundi.h" inline DWORD DSBCAPStoDSBPLAY(DWORD dwCaps) {return (dwCaps >> 1) & DSBPLAY_LOCMASK;} inline DWORD DSBCAPStoDSBSTATUS(DWORD dwCaps) {return (dwCaps << 1) & DSBSTATUS_LOCMASK;} inline DWORD DSBPLAYtoDSBCAPS(DWORD dwPlay) {return (dwPlay << 1) & DSBCAPS_LOCMASK;} inline DWORD DSBPLAYtoDSBSTATUS(DWORD dwPlay) {return (dwPlay << 2) & DSBSTATUS_LOCMASK;} inline DWORD DSBSTATUStoDSBCAPS(DWORD dwStatus) {return (dwStatus >> 1) & DSBCAPS_LOCMASK;} inline DWORD DSBSTATUStoDSBPLAY(DWORD dwStatus) {return (dwStatus >> 2) & DSBPLAY_LOCMASK;} /*************************************************************************** * * CDirectSoundBuffer * * Description: * DirectSound buffer object constructor. * * Arguments: * CDirectSound * [in]: parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundBuffer::CDirectSoundBuffer" CDirectSoundBuffer::CDirectSoundBuffer(CDirectSound *pDirectSound) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSoundBuffer); // Initialize defaults m_pDirectSound = pDirectSound; m_dwStatus = 0; InitStruct(&m_dsbd, sizeof(m_dsbd)); DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSoundBuffer * * Description: * DirectSound buffer object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundBuffer::~CDirectSoundBuffer" CDirectSoundBuffer::~CDirectSoundBuffer(void) { DPF_ENTER(); DPF_DESTRUCT(CDirectSoundBuffer); // Free memory MEMFREE(m_dsbd.lpwfxFormat); DPF_LEAVE_VOID(); } /*************************************************************************** * * UpdateBufferStatusFlags * * Description: * Converts a set of VAD_BUFFERSTATE_* flags to DSBSTATUS_* flags. * * Arguments: * DWORD [in]: VAD_BUFFERSTATE_* flags. * LPDWORD [in/out]: current buffer flags. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundBuffer::UpdateBufferStatusFlags" void CDirectSoundBuffer::UpdateBufferStatusFlags(DWORD dwState, LPDWORD pdwStatus) { const DWORD dwStateMask = VAD_BUFFERSTATE_STARTED | VAD_BUFFERSTATE_LOOPING; DPF_ENTER(); dwState &= dwStateMask; if(!(dwState & VAD_BUFFERSTATE_STARTED)) { ASSERT(!(dwState & VAD_BUFFERSTATE_LOOPING)); dwState &= ~VAD_BUFFERSTATE_LOOPING; } if(dwState & VAD_BUFFERSTATE_STARTED) { *pdwStatus |= DSBSTATUS_PLAYING; } else { *pdwStatus &= ~DSBSTATUS_PLAYING; } if(dwState & VAD_BUFFERSTATE_LOOPING) { *pdwStatus |= DSBSTATUS_LOOPING; } else { *pdwStatus &= ~DSBSTATUS_LOOPING; } DPF_LEAVE_VOID(); } /*************************************************************************** * * CDirectSoundPrimaryBuffer * * Description: * DirectSound primary buffer object constructor. * * Arguments: * CDirectSound * [in]: pointer to the parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::CDirectSoundPrimaryBuffer" CDirectSoundPrimaryBuffer::CDirectSoundPrimaryBuffer(CDirectSound *pDirectSound) : CDirectSoundBuffer(pDirectSound) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSoundPrimaryBuffer); // Initialize defaults m_pImpDirectSoundBuffer = NULL; m_pDeviceBuffer = NULL; m_p3dListener = NULL; m_pPropertySet = NULL; m_dwRestoreState = VAD_BUFFERSTATE_STOPPED | VAD_BUFFERSTATE_WHENIDLE; m_fWritePrimary = FALSE; m_ulUserRefCount = 0; m_hrInit = DSERR_UNINITIALIZED; m_bDataLocked = FALSE; DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSoundPrimaryBuffer * * Description: * DirectSound primary buffer object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::~CDirectSoundPrimaryBuffer" CDirectSoundPrimaryBuffer::~CDirectSoundPrimaryBuffer(void) { DPF_ENTER(); DPF_DESTRUCT(CDirectSoundBuffer); // Make sure to give up WRITEPRIMARY access if(m_pDeviceBuffer) { SetPriority(DSSCL_NONE); } // Free all interfaces DELETE(m_pImpDirectSoundBuffer); // Free owned objects ABSOLUTE_RELEASE(m_p3dListener); ABSOLUTE_RELEASE(m_pPropertySet); // Free the device buffer RELEASE(m_pDeviceBuffer); // The owning DirectSound object is responsible for updating the global // focus state. DPF_LEAVE_VOID(); } /*************************************************************************** * * Initialize * * Description: * Initializes a buffer object. If this function fails, the object * should be immediately deleted. * * Arguments: * LPDSBUFFERDESC [in]: buffer description. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Initialize" HRESULT CDirectSoundPrimaryBuffer::Initialize(LPCDSBUFFERDESC pDesc) { VADRBUFFERCAPS vrbc; HRESULT hr; DPF_ENTER(); ASSERT(IsInit() == DSERR_UNINITIALIZED); ASSERT(pDesc); // Create the device buffer hr = m_pDirectSound->m_pDevice->CreatePrimaryBuffer(pDesc->dwFlags, m_pDirectSound, &m_pDeviceBuffer); // Attempt to create the property set object if(SUCCEEDED(hr)) { m_pPropertySet = NEW(CDirectSoundPropertySet(this)); hr = HRFROMP(m_pPropertySet); if(SUCCEEDED(hr)) { hr = m_pPropertySet->Initialize(); } if(SUCCEEDED(hr)) { // We don't care if this fails m_pPropertySet->AcquireResources(m_pDeviceBuffer); } } // Attempt to create the 3D listener if(SUCCEEDED(hr) && (pDesc->dwFlags & DSBCAPS_CTRL3D)) { m_p3dListener = NEW(CDirectSound3dListener(this)); hr = HRFROMP(m_p3dListener); if(SUCCEEDED(hr)) { hr = m_p3dListener->Initialize(m_pDeviceBuffer); } } // Register the standard buffer interface with the interface manager if(SUCCEEDED(hr)) { hr = CreateAndRegisterInterface(this, IID_IDirectSoundBuffer, this, &m_pImpDirectSoundBuffer); } // Build the local buffer description if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->GetCaps(&vrbc); } if(SUCCEEDED(hr)) { m_dsbd.dwFlags = (vrbc.dwFlags & DSBCAPS_LOCMASK); m_dsbd.dwBufferBytes = vrbc.dwBufferBytes; m_dsbd.lpwfxFormat = AllocDefWfx(); hr = HRFROMP(m_dsbd.lpwfxFormat); } // If the 3D listener has been created, he's already registered the // 3D listener interface. if(SUCCEEDED(hr) && m_p3dListener) { m_dsbd.dwFlags |= DSBCAPS_CTRL3D; } // Handle buffer caps flags change if(SUCCEEDED(hr)) { hr = SetBufferFlags(pDesc->dwFlags); } // Handle priority change if(SUCCEEDED(hr)) { hr = SetPriority(m_pDirectSound->m_dsclCooperativeLevel.dwPriority); } // The DirectSound object creating this buffer is responsible for updating // the global focus state. // Success if(SUCCEEDED(hr)) { m_hrInit = DS_OK; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetCaps * * Description: * Queries capabilities for the buffer. * * Arguments: * LPDSBCAPS [out]: receives caps. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetCaps" HRESULT CDirectSoundPrimaryBuffer::GetCaps(LPDSBCAPS pDsbCaps) { DPF_ENTER(); ASSERT(LXOR(m_dsbd.dwFlags & DSBCAPS_LOCSOFTWARE, m_dsbd.dwFlags & DSBCAPS_LOCHARDWARE)); pDsbCaps->dwFlags = m_dsbd.dwFlags; pDsbCaps->dwBufferBytes = m_dsbd.dwBufferBytes; pDsbCaps->dwUnlockTransferRate = 0; pDsbCaps->dwPlayCpuOverhead = 0; DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * OnCreateSoundBuffer * * Description: * Called in response to an application calling * CreateSoundBuffer(DSBCAPS_PRIMARYBUFFER). * * Arguments: * DWORD [in]: new buffer flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::OnCreateSoundBuffer" HRESULT CDirectSoundPrimaryBuffer::OnCreateSoundBuffer(DWORD dwFlags) { HRESULT hr = DS_OK; DPF_ENTER(); // COMPATCOMPAT: in previous versions of DirectSound, calling // CreateSoundBuffer(PRIMARYBUFFER) once would change the buffer flags, // but calling it twice would just return a pointer to the same, // unmodified buffer. I've introduced new behavior in this version // that would allow an app to modify the capabilities of the primary // buffer on-the-fly by calling CreateSoundBuffer(PRIMARYBUFFER) more // than once. This could potentially free interfaces that the app // will later try to use. One way to fix this would be to add a data // member to the DirectSound or primary buffer object that stores // whether or not the application has created a primary buffer already. // The steps outlined above are now implemented here: if(m_ulUserRefCount) { RPF((dwFlags == m_dsbd.dwFlags) ? DPFLVL_WARNING : DPFLVL_ERROR, "The primary buffer already exists. Any changes made to the buffer description will be ignored."); } else { hr = SetBufferFlags(dwFlags); } if(SUCCEEDED(hr)) { AddRef(); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetBufferFlags * * Description: * Changes capabilities for the buffer. This function is also * responsible for creating and freeing interfaces. * * Arguments: * DWORD [in]: new buffer flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetBufferFlags" HRESULT CDirectSoundPrimaryBuffer::SetBufferFlags(DWORD dwFlags) { HRESULT hr = DS_OK; DWORD dwVolPanCaps; DPF_ENTER(); // Make sure we can handle the requested flags if((dwFlags & DSBCAPS_CTRL3D) && !m_p3dListener) { RPF(DPFLVL_ERROR, "No 3D listener support"); hr = DSERR_CONTROLUNAVAIL; } // Not all capabilities of the DirectSound primary buffer map to the // methods of the device primary buffer. Specifically, attenuation is // handled by the render device. Let's check these flags before // proceeding. if(SUCCEEDED(hr) && (dwFlags & DSBCAPS_CTRLATTENUATION)) { hr = m_pDirectSound->m_pDevice->GetVolumePanCaps(&dwVolPanCaps); if(SUCCEEDED(hr) && (dwFlags & DSBCAPS_CTRLVOLUME) && !(dwVolPanCaps & DSBCAPS_CTRLVOLUME)) { RPF(DPFLVL_ERROR, "The device does not support CTRLVOLUME"); hr = DSERR_CONTROLUNAVAIL; } if(SUCCEEDED(hr) && (dwFlags & DSBCAPS_CTRLPAN) && !(dwVolPanCaps & DSBCAPS_CTRLPAN)) { RPF(DPFLVL_ERROR, "The device does not support CTRLPAN"); hr = DSERR_CONTROLUNAVAIL; } } // Fix up the 3D listener interface if(SUCCEEDED(hr) && ((m_dsbd.dwFlags & DSBCAPS_CTRL3D) != (dwFlags & DSBCAPS_CTRL3D))) { if(dwFlags & DSBCAPS_CTRL3D) { DPF(DPFLVL_INFO, "Primary buffer becoming CTRL3D. Registering IID_IDirectSound3DListener"); hr = RegisterInterface(IID_IDirectSound3DListener, m_p3dListener->m_pImpDirectSound3dListener, m_p3dListener->m_pImpDirectSound3dListener); } else { DPF(DPFLVL_INFO, "Primary buffer becoming ~CTRL3D. Unregistering IID_IDirectSound3DListener"); hr = UnregisterInterface(IID_IDirectSound3DListener); } } // Save buffer flags. We're assuming that the buffer location has // already been saved to m_dsbd.dwFlags at this point. if(SUCCEEDED(hr)) { m_dsbd.dwFlags = (dwFlags & ~DSBCAPS_LOCMASK) | (m_dsbd.dwFlags & DSBCAPS_LOCMASK); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetFormat * * Description: * Retrieves the format for the given buffer. * * Arguments: * LPWAVEFORMATEX [out]: receives the format. * LPDWORD [in/out]: size of the format structure. On entry, this * must be initialized to the size of the structure. * On exit, this will be filled with the size that * was required. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetFormat" HRESULT CDirectSoundPrimaryBuffer::GetFormat(LPWAVEFORMATEX pwfxFormat, LPDWORD pdwSize) { HRESULT hr; DPF_ENTER(); hr = CopyWfxApi(m_dsbd.lpwfxFormat, pwfxFormat, pdwSize); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetFormat * * Description: * Sets the format for a given buffer. * * Arguments: * LPWAVEFORMATEX [in]: new format. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetFormat" HRESULT CDirectSoundPrimaryBuffer::SetFormat(LPCWAVEFORMATEX pwfxFormat) { LPWAVEFORMATEX pwfxLocal = NULL; BOOL fActive = MAKEBOOL(m_dwStatus & DSBSTATUS_ACTIVE); HRESULT hr = DS_OK; CNode<CDirectSound *> * pNode; BOOL bRewriteStartupSilence = FALSE; DPF_ENTER(); // Check access rights if(m_pDirectSound->m_dsclCooperativeLevel.dwPriority < DSSCL_PRIORITY) { RPF(DPFLVL_ERROR, "Cooperative level is not PRIORITY"); hr = DSERR_PRIOLEVELNEEDED; } // Save a local copy of the format if(SUCCEEDED(hr)) { pwfxLocal = CopyWfxAlloc(pwfxFormat); hr = HRFROMP(pwfxLocal); } // We can only change the format if we're active if(SUCCEEDED(hr) && !fActive) { // The Administrator says we're out of focus. If there's not really anyone // else in focus, we're going to cheat and set the format anyway. // DuganP: This is weird - presumably done so fewer apps will break when the // user switches focus away from them temporarily. There's the problem that // if multiple apps are in this state, whoever's last to set the format wins. // However, app-compat probably means we can't touch this code any more, so... for(pNode = g_pDsAdmin->m_lstDirectSound.GetListHead(); pNode; pNode = pNode->m_pNext) { if(pNode->m_data && SUCCEEDED(pNode->m_data->IsInit())) { if(pNode->m_data->m_pPrimaryBuffer && this != pNode->m_data->m_pPrimaryBuffer && SUCCEEDED(pNode->m_data->m_pPrimaryBuffer->IsInit())) { if(DSBUFFERFOCUS_INFOCUS == g_pDsAdmin->GetBufferFocusState(pNode->m_data->m_pPrimaryBuffer)) { // NOTE: We added a "&& pNode->m_data->GetOwnerProcessId() != GetOwnerProcessId())" // clause to fix WinME bug 120317, and we removed it again to fix DX8 bug 40627. // We found an in-focus primary buffer [in another app], so fail. break; } } } } if(!pNode) { fActive = TRUE; } } // Apply the format to the device if(SUCCEEDED(hr)) { if( m_fWritePrimary ) { // // See if this a WRITEPRIMARY app that's about to change to a new sample size. // If so, silence will need to be re-written for the new sample size // (providing the app hasn't locked any data yet). // LPWAVEFORMATEX pwfxOld; DWORD dwSize; HRESULT hrTmp = m_pDirectSound->m_pDevice->GetGlobalFormat(NULL, &dwSize); if(SUCCEEDED(hrTmp)) { pwfxOld = (LPWAVEFORMATEX)MEMALLOC_A(BYTE, dwSize); if( pwfxOld ) { hrTmp = m_pDirectSound->m_pDevice->GetGlobalFormat(pwfxOld, &dwSize); if( SUCCEEDED( hr ) ) { if( pwfxLocal->wBitsPerSample != pwfxOld->wBitsPerSample ) { bRewriteStartupSilence = TRUE; } } MEMFREE(pwfxOld); } } } if(fActive) { DPF(DPFLVL_INFO, "Setting the format on device " DPF_GUID_STRING, DPF_GUID_VAL(m_pDirectSound->m_pDevice->m_pDeviceDescription->m_guidDeviceId)); // If we're WRITEPRIMARY, the format needs to be exact. Otherwise, // we'll try to set the next closest format. We're checking the // actual focus priority instead of our local writeprimary flag // in case the buffer is lost. if(DSSCL_WRITEPRIMARY == m_pDirectSound->m_dsclCooperativeLevel.dwPriority) { hr = m_pDirectSound->SetDeviceFormatExact(pwfxLocal); } else { hr = m_pDirectSound->SetDeviceFormat(pwfxLocal); } } else { DPF(DPFLVL_INFO, "NOT setting the format on device " DPF_GUID_STRING, DPF_GUID_VAL(m_pDirectSound->m_pDevice->m_pDeviceDescription->m_guidDeviceId)); } } // Update the stored format if(SUCCEEDED(hr)) { MEMFREE(m_dsbd.lpwfxFormat); m_dsbd.lpwfxFormat = pwfxLocal; if( bRewriteStartupSilence && !m_bDataLocked ) { // Refill the buffer with silence in the new sample size format, // only if the primary buffer was started playing before Locking any data. DSBUFFERFOCUS bfFocus = g_pDsAdmin->GetBufferFocusState(this); if( bfFocus == DSBUFFERFOCUS_INFOCUS) { ASSERT( m_fWritePrimary ); // Request write access first HRESULT hrTmp = m_pDeviceBuffer->RequestWriteAccess(TRUE); if(SUCCEEDED(hrTmp)) { // Fill the buffer with silence. At this point, we MUST be WRITEPRIMARY. ::FillSilence(m_pDeviceBuffer->m_pSysMemBuffer->GetPlayBuffer(), m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat->wBitsPerSample); hrTmp = m_pDeviceBuffer->CommitToDevice(0, m_pDeviceBuffer->m_pSysMemBuffer->GetSize()); #ifdef DEBUG if(FAILED( hrTmp ) ) { // Not a catastrophic failure if we fail this DPF(DPFLVL_WARNING, "CommitToDevice for buffer at 0x%p failed (%ld) ", this, hrTmp); } #endif } #ifdef DEBUG else { // again, not a catastrophic failure DPF(DPFLVL_WARNING, "RequestWriteAccess failed for buffer at 0x%p failed with %ld", this, hrTmp ); } #endif } } } else { MEMFREE(pwfxLocal); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetFrequency * * Description: * Retrieves frequency for the given buffer. * * Arguments: * LPDWORD [out]: receives the frequency. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetFrequency" HRESULT CDirectSoundPrimaryBuffer::GetFrequency(LPDWORD pdwFrequency) { DPF_ENTER(); RPF(DPFLVL_ERROR, "Primary buffers don't support CTRLFREQUENCY"); DPF_LEAVE_HRESULT(DSERR_CONTROLUNAVAIL); return DSERR_CONTROLUNAVAIL; } /*************************************************************************** * * SetFrequency * * Description: * Retrieves frequency for the given buffer. * * Arguments: * DWORD [in]: frequency. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetFrequency" HRESULT CDirectSoundPrimaryBuffer::SetFrequency(DWORD dwFrequency) { DPF_ENTER(); RPF(DPFLVL_ERROR, "Primary buffers don't support CTRLFREQUENCY"); DPF_LEAVE_HRESULT(DSERR_CONTROLUNAVAIL); return DSERR_CONTROLUNAVAIL; } /*************************************************************************** * * GetPan * * Description: * Retrieves pan for the given buffer. * * Arguments: * LPLONG [out]: receives the pan. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetPan" HRESULT CDirectSoundPrimaryBuffer::GetPan(LPLONG plPan) { HRESULT hr = DS_OK; DSVOLUMEPAN dsvp; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN"); hr = DSERR_CONTROLUNAVAIL; } // Ask the device for global attenuation and convert to pan if(SUCCEEDED(hr)) { hr = m_pDirectSound->m_pDevice->GetGlobalAttenuation(&dsvp); } if(SUCCEEDED(hr)) { *plPan = dsvp.lPan; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetPan * * Description: * Sets the pan for a given buffer. * * Arguments: * LONG [in]: new pan. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetPan" HRESULT CDirectSoundPrimaryBuffer::SetPan(LONG lPan) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN"); hr = DSERR_CONTROLUNAVAIL; } // Set device pan if(SUCCEEDED(hr)) { hr = m_pDirectSound->SetDevicePan(lPan); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetVolume * * Description: * Retrieves volume for the given buffer. * * Arguments: * LPLONG [out]: receives the volume. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetVolume" HRESULT CDirectSoundPrimaryBuffer::GetVolume(LPLONG plVolume) { HRESULT hr = DS_OK; DSVOLUMEPAN dsvp; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME"); hr = DSERR_CONTROLUNAVAIL; } // Ask the device for global attenuation and convert to volume if(SUCCEEDED(hr)) { hr = m_pDirectSound->m_pDevice->GetGlobalAttenuation(&dsvp); } if(SUCCEEDED(hr)) { *plVolume = dsvp.lVolume; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetVolume * * Description: * Sets the volume for a given buffer. * * Arguments: * LONG [in]: new volume. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetVolume" HRESULT CDirectSoundPrimaryBuffer::SetVolume(LONG lVolume) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME"); hr = DSERR_CONTROLUNAVAIL; } // Set device volume if(SUCCEEDED(hr)) { hr = m_pDirectSound->SetDeviceVolume(lVolume); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetNotificationPositions * * Description: * Sets buffer notification positions. * * Arguments: * DWORD [in]: DSBPOSITIONNOTIFY structure count. * LPDSBPOSITIONNOTIFY [in]: offsets and events. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetNotificationPositions" HRESULT CDirectSoundPrimaryBuffer::SetNotificationPositions(DWORD dwCount, LPCDSBPOSITIONNOTIFY paNotes) { DPF_ENTER(); RPF(DPFLVL_ERROR, "Primary buffers don't support CTRLPOSITIONNOTIFY"); DPF_LEAVE_HRESULT(DSERR_CONTROLUNAVAIL); return DSERR_CONTROLUNAVAIL; } /*************************************************************************** * * GetCurrentPosition * * Description: * Gets the current play/write positions for the given buffer. * * Arguments: * LPDWORD [out]: receives play cursor position. * LPDWORD [out]: receives write cursor position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetCurrentPosition" HRESULT CDirectSoundPrimaryBuffer::GetCurrentPosition(LPDWORD pdwPlay, LPDWORD pdwWrite) { HRESULT hr = DS_OK; DWORD dwPlay; DWORD dwWrite; DPF_ENTER(); // Check for BUFFERLOST if(m_dwStatus & DSBSTATUS_BUFFERLOST) { hr = DSERR_BUFFERLOST; } // Check access rights if(SUCCEEDED(hr) && !m_fWritePrimary) { RPF(DPFLVL_ERROR, "Cooperative level is not WRITEPRIMARY"); hr = DSERR_PRIOLEVELNEEDED; } // We save the position to local variables so that the object we're // calling into doesn't have to worry about whether one or both of // the arguments are NULL. if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->GetCursorPosition(&dwPlay, &dwWrite); } // Block-align the positions if(SUCCEEDED(hr)) { dwPlay = BLOCKALIGN(dwPlay, m_dsbd.lpwfxFormat->nBlockAlign); dwWrite = BLOCKALIGN(dwWrite, m_dsbd.lpwfxFormat->nBlockAlign); } // Apply app-hacks if(SUCCEEDED(hr) && m_pDirectSound->m_ahAppHacks.lCursorPad) { dwPlay = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad); dwWrite = PadCursor(dwWrite, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad); } if(SUCCEEDED(hr) && (m_pDirectSound->m_ahAppHacks.vdtReturnWritePos & m_pDirectSound->m_pDevice->m_vdtDeviceType)) { dwPlay = dwWrite; } if(SUCCEEDED(hr) && m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.fEnable) { dwWrite = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.lCursorPad); } // Success if(SUCCEEDED(hr) && pdwPlay) { *pdwPlay = dwPlay; } if(SUCCEEDED(hr) && pdwWrite) { *pdwWrite = dwWrite; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetCurrentPosition * * Description: * Sets the current play position for a given buffer. * * Arguments: * DWORD [in]: new play position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetCurrentPosition" HRESULT CDirectSoundPrimaryBuffer::SetCurrentPosition(DWORD dwPlayCursor) { DPF_ENTER(); RPF(DPFLVL_ERROR, "Primary buffers don't support SetCurrentPosition"); DPF_LEAVE_HRESULT(DSERR_INVALIDCALL); return DSERR_INVALIDCALL; } /*************************************************************************** * * GetStatus * * Description: * Retrieves status for the given buffer. * * Arguments: * LPDWORD [out]: receives the status. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetStatus" HRESULT CDirectSoundPrimaryBuffer::GetStatus(LPDWORD pdwStatus) { HRESULT hr = DS_OK; DWORD dwStatus; DWORD dwState; DPF_ENTER(); // Update the buffer status. If we're lost, that's the only state we // care about if(m_dwStatus & DSBSTATUS_BUFFERLOST) { dwStatus = DSBSTATUS_BUFFERLOST; } else { // Get the current device buffer state hr = m_pDeviceBuffer->GetState(&dwState); if(SUCCEEDED(hr)) { dwStatus = m_dwStatus; UpdateBufferStatusFlags(dwState, &m_dwStatus); } // Fill in the buffer location if(SUCCEEDED(hr)) { m_dwStatus |= DSBCAPStoDSBSTATUS(m_dsbd.dwFlags); } if(SUCCEEDED(hr)) { dwStatus = m_dwStatus; } } // Mask off bits that shouldn't get back to the app if(SUCCEEDED(hr)) { dwStatus &= DSBSTATUS_USERMASK; } if(SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { dwStatus &= ~DSBSTATUS_LOCDEFERMASK; } if(SUCCEEDED(hr) && pdwStatus) { *pdwStatus = dwStatus; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Play * * Description: * Starts the buffer playing. * * Arguments: * DWORD [in]: priority. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Play" HRESULT CDirectSoundPrimaryBuffer::Play(DWORD dwPriority, DWORD dwFlags) { HRESULT hr = DS_OK; DPF_ENTER(); // Validate flags if(dwFlags != DSBPLAY_LOOPING) { RPF(DPFLVL_ERROR, "The only valid flag for primary buffers is LOOPING, which must always be set"); hr = DSERR_INVALIDPARAM; } if(SUCCEEDED(hr) && dwPriority) { RPF(DPFLVL_ERROR, "Priority is not valid for primary buffers"); hr = DSERR_INVALIDPARAM; } // Check for BUFFERLOST if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { hr = DSERR_BUFFERLOST; } // Set the buffer state if(SUCCEEDED(hr)) { hr = SetBufferState(VAD_BUFFERSTATE_STARTED | VAD_BUFFERSTATE_LOOPING); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Stop * * Description: * Stops playing the given buffer. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Stop" HRESULT CDirectSoundPrimaryBuffer::Stop(void) { HRESULT hr = DS_OK; DPF_ENTER(); // Check for BUFFERLOST if(m_dwStatus & DSBSTATUS_BUFFERLOST) { hr = DSERR_BUFFERLOST; } // Set the buffer state if(SUCCEEDED(hr)) { hr = SetBufferState(VAD_BUFFERSTATE_STOPPED); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetBufferState * * Description: * Sets the buffer play/stop state. * * Arguments: * DWORD [in]: buffer state flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetBufferState" HRESULT CDirectSoundPrimaryBuffer::SetBufferState(DWORD dwNewState) { DWORD dwOldState; HRESULT hr; DPF_ENTER(); if(m_fWritePrimary) { dwNewState &= ~VAD_BUFFERSTATE_WHENIDLE; } else { dwNewState |= VAD_BUFFERSTATE_WHENIDLE; } hr = m_pDeviceBuffer->GetState(&dwOldState); if(SUCCEEDED(hr) && dwNewState != dwOldState) { hr = m_pDeviceBuffer->SetState(dwNewState); } if(SUCCEEDED(hr)) { m_dwRestoreState = dwNewState; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Activate * * Description: * Activates or deactivates the buffer object. * * Arguments: * BOOL [in]: Activation state. TRUE to activate, FALSE to deactivate. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Activate" HRESULT CDirectSoundPrimaryBuffer::Activate(BOOL fActive) { HRESULT hr; DPF_ENTER(); // Apply cached properties. If we fail while doing this, hard luck, // but there's nothing we can do about it. We should never return // failure from Activate. if(MAKEBOOL(m_dwStatus & DSBSTATUS_ACTIVE) != fActive) { if(fActive) { m_dwStatus |= DSBSTATUS_ACTIVE; // Restore cached format hr = m_pDirectSound->SetDeviceFormatExact(m_dsbd.lpwfxFormat); if(FAILED(hr)) { RPF(DPFLVL_WARNING, "Unable to restore cached primary buffer format"); } // Restore primary buffer state hr = SetBufferState(m_dwRestoreState); if(FAILED(hr)) { RPF(DPFLVL_WARNING, "Unable to restore cached primary buffer state"); } } else { m_dwStatus &= ~DSBSTATUS_ACTIVE; } } DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * SetPriority * * Description: * Sets buffer priority. * * Arguments: * DWORD [in]: new priority. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::SetPriority" HRESULT CDirectSoundPrimaryBuffer::SetPriority(DWORD dwPriority) { const BOOL fCurrent = m_fWritePrimary; const BOOL fNew = (DSSCL_WRITEPRIMARY == dwPriority); HRESULT hr = DS_OK; const DSBUFFERFOCUS bfFocus = g_pDsAdmin->GetBufferFocusState(this); DPF_ENTER(); // Update our copy of the priority m_fWritePrimary = fNew; // If we're becoming WRITEPRIMARY but are out of focus, become immediately // lost. if (fNew && !fCurrent && bfFocus != DSBUFFERFOCUS_INFOCUS) { // Give up WRITEPRIMARY access m_fWritePrimary = FALSE; // Deactivate the buffer Activate(FALSE); // Flag the buffer as lost m_dwStatus |= DSBSTATUS_BUFFERLOST; hr = DSERR_OTHERAPPHASPRIO; } // Make sure the WRITEPRIMARY state has actually changed if(SUCCEEDED(hr) && fNew != fCurrent) { // If we're becoming WRITEPRIMARY, we need to request primary // access to the device. if(fNew) { // Request write access hr = m_pDeviceBuffer->RequestWriteAccess(TRUE); if(SUCCEEDED(hr)) { DPF(DPFLVL_INFO, "Buffer at 0x%p has become WRITEPRIMARY", this); } } // Fill the buffer with silence. At this point, we MUST be WRITEPRIMARY. if(SUCCEEDED(hr)) { ::FillSilence(m_pDeviceBuffer->m_pSysMemBuffer->GetPlayBuffer(), m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat->wBitsPerSample); hr = m_pDeviceBuffer->CommitToDevice(0, m_pDeviceBuffer->m_pSysMemBuffer->GetSize()); } // If we're leaving WRITEPRIMARY, we need to relinquish primary // access to the device. if(!fNew) { // Free any open locks on the buffer m_pDeviceBuffer->OverrideLocks(); // Give up write access hr = m_pDeviceBuffer->RequestWriteAccess(FALSE); if(SUCCEEDED(hr)) { DPF(DPFLVL_INFO, "Buffer at 0x%p is no longer WRITEPRIMARY", this); } } // Reset the buffer state if(SUCCEEDED(hr)) { SetBufferState(VAD_BUFFERSTATE_STOPPED); } } // If we're currently lost, but the cooperative level has changed to // something other than WRITEPRIMARY, we'll go ahead and restore the // buffer for the app. Only WRITEPRIMARY buffers can be lost. if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST) && !fNew) { m_dwStatus &= ~DSBSTATUS_BUFFERLOST; } // Recover from any errors if(FAILED(hr)) { m_fWritePrimary = fCurrent; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Lock * * Description: * Locks the buffer memory to allow for writing. * * Arguments: * DWORD [in]: offset, in bytes, from the start of the buffer to where * the lock begins. This parameter is ignored if * DSBLOCK_FROMWRITECURSOR is specified in the dwFlags * parameter. * DWORD [in]: size, in bytes, of the portion of the buffer to lock. * Note that the sound buffer is conceptually circular. * LPVOID * [out]: address for a pointer to contain the first block of * the sound buffer to be locked. * LPDWORD [out]: address for a variable to contain the number of bytes * pointed to by the ppvAudioPtr1 parameter. If this * value is less than the dwWriteBytes parameter, * ppvAudioPtr2 will point to a second block of sound * data. * LPVOID * [out]: address for a pointer to contain the second block of * the sound buffer to be locked. If the value of this * parameter is NULL, the ppvAudioPtr1 parameter * points to the entire locked portion of the sound * buffer. * LPDWORD [out]: address of a variable to contain the number of bytes * pointed to by the ppvAudioPtr2 parameter. If * ppvAudioPtr2 is NULL, this value will be 0. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Lock" HRESULT CDirectSoundPrimaryBuffer::Lock(DWORD dwWriteCursor, DWORD dwWriteBytes, LPVOID *ppvAudioPtr1, LPDWORD pdwAudioBytes1, LPVOID *ppvAudioPtr2, LPDWORD pdwAudioBytes2, DWORD dwFlags) { HRESULT hr = DS_OK; DPF_ENTER(); // Check for BUFFERLOST if(m_dwStatus & DSBSTATUS_BUFFERLOST) { hr = DSERR_BUFFERLOST; } // Check access rights if(SUCCEEDED(hr) && !m_fWritePrimary) { RPF(DPFLVL_ERROR, "Cooperative level is not WRITEPRIMARY"); hr = DSERR_PRIOLEVELNEEDED; } // Handle flags if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_FROMWRITECURSOR)) { hr = GetCurrentPosition(NULL, &dwWriteCursor); } if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_ENTIREBUFFER)) { dwWriteBytes = m_dsbd.dwBufferBytes; } // Cursor validation if(SUCCEEDED(hr) && dwWriteCursor >= m_dsbd.dwBufferBytes) { ASSERT(!(dwFlags & DSBLOCK_FROMWRITECURSOR)); RPF(DPFLVL_ERROR, "Write cursor past buffer end"); hr = DSERR_INVALIDPARAM; } if(SUCCEEDED(hr) && dwWriteBytes > m_dsbd.dwBufferBytes) { ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER)); RPF(DPFLVL_ERROR, "Lock size larger than buffer size"); hr = DSERR_INVALIDPARAM; } if(SUCCEEDED(hr) && !dwWriteBytes) { ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER)); RPF(DPFLVL_ERROR, "Lock size must be > 0"); hr = DSERR_INVALIDPARAM; } // Lock the device buffer if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->Lock(dwWriteCursor, dwWriteBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2); } m_bDataLocked = TRUE; // used to signal that app has written data (reset only required 1 per buffer creation) DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Unlock * * Description: * Unlocks the given buffer. * * Arguments: * LPVOID [in]: pointer to the first block. * DWORD [in]: size of the first block. * LPVOID [in]: pointer to the second block. * DWORD [in]: size of the second block. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Unlock" HRESULT CDirectSoundPrimaryBuffer::Unlock(LPVOID pvAudioPtr1, DWORD dwAudioBytes1, LPVOID pvAudioPtr2, DWORD dwAudioBytes2) { HRESULT hr = DS_OK; DPF_ENTER(); // Check for BUFFERLOST if(m_dwStatus & DSBSTATUS_BUFFERLOST) { hr = DSERR_BUFFERLOST; } // Check access rights if(SUCCEEDED(hr) && !m_fWritePrimary) { RPF(DPFLVL_ERROR, "Cooperative level is not WRITEPRIMARY"); hr = DSERR_PRIOLEVELNEEDED; } // Unlock the device buffer. Because we fail the call when the buffer is // lost (or out of focus), there's no need to notify the device buffer of // any state change. if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->Unlock(pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Lose * * Description: * Flags the buffer as lost. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Lose" HRESULT CDirectSoundPrimaryBuffer::Lose(void) { DPF_ENTER(); // We can only be lost if we're WRITEPRIMARY if(!(m_dwStatus & DSBSTATUS_BUFFERLOST) && m_fWritePrimary) { // Stop the buffer. All lost buffers are stopped by definition. SetBufferState(VAD_BUFFERSTATE_STOPPED); // Give up WRITEPRIMARY access SetPriority(DSSCL_NONE); // Deactivate the buffer Activate(FALSE); // Flag the buffer as lost m_dwStatus |= DSBSTATUS_BUFFERLOST; } DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * Restore * * Description: * Attempts to restore a lost bufer. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::Restore" HRESULT CDirectSoundPrimaryBuffer::Restore(void) { HRESULT hr = DS_OK; DPF_ENTER(); if(m_dwStatus & DSBSTATUS_BUFFERLOST) { // Are we still lost? if(DSBUFFERFOCUS_LOST == g_pDsAdmin->GetBufferFocusState(this)) { hr = DSERR_BUFFERLOST; } // Remove the lost flag if(SUCCEEDED(hr)) { m_dwStatus &= ~DSBSTATUS_BUFFERLOST; } // Reset the focus priority if(SUCCEEDED(hr)) { hr = SetPriority(m_pDirectSound->m_dsclCooperativeLevel.dwPriority); } // Clean up if(FAILED(hr)) { m_dwStatus |= DSBSTATUS_BUFFERLOST; } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * CDirectSoundSecondaryBuffer * * Description: * DirectSound secondary buffer object constructor. * * Arguments: * CDirectSound * [in]: pointer to the parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::CDirectSoundSecondaryBuffer" CDirectSoundSecondaryBuffer::CDirectSoundSecondaryBuffer(CDirectSound *pDirectSound) : CDirectSoundBuffer(pDirectSound) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSoundSecondaryBuffer); // Initialize/check defaults ASSERT(m_pImpDirectSoundBuffer == NULL); ASSERT(m_pImpDirectSoundNotify == NULL); ASSERT(m_pOwningSink == NULL); ASSERT(m_pDeviceBuffer == NULL); ASSERT(m_p3dBuffer == NULL); ASSERT(m_pPropertySet == NULL); ASSERT(m_fxChain == NULL); ASSERT(m_dwPriority == 0); ASSERT(m_dwVmPriority == 0); ASSERT(m_fMute == FALSE); #ifdef FUTURE_MULTIPAN_SUPPORT ASSERT(m_dwChannelCount == 0); ASSERT(m_pdwChannels == NULL); ASSERT(m_plChannelVolumes == NULL); #endif ASSERT(m_guidBufferID == GUID_NULL); ASSERT(m_dwAHLastGetPosTime == 0); ASSERT(m_dwAHCachedPlayPos == 0); ASSERT(m_dwAHCachedWritePos == 0); m_fCanStealResources = TRUE; m_hrInit = DSERR_UNINITIALIZED; m_hrPlay = DS_OK; m_playState = Stopped; m_dwSliceBegin = MAX_DWORD; m_dwSliceEnd = MAX_DWORD; #ifdef ENABLE_PERFLOG // Initialize performance state if logging is enabled m_pPerfState = NULL; if (PerflogTracingEnabled()) { m_pPerfState = NEW(BufferPerfState(this)); // We don't mind if this allocation fails } #endif DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSoundSecondaryBuffer * * Description: * DirectSound secondary buffer object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::~CDirectSoundSecondaryBuffer" CDirectSoundSecondaryBuffer::~CDirectSoundSecondaryBuffer(void) { HRESULT hr; DPF_ENTER(); DPF_DESTRUCT(CDirectSoundBuffer); // If we're a MIXIN buffer, inform all our senders that we're going // away, and unregister with the streaming thread if ((m_dsbd.dwFlags & DSBCAPS_MIXIN) && SUCCEEDED(m_hrInit)) { CNode<CDirectSoundSecondaryBuffer*>* pDsbNode; for (pDsbNode = m_pDirectSound->m_lstSecondaryBuffers.GetListHead(); pDsbNode; pDsbNode = pDsbNode->m_pNext) if (pDsbNode->m_data->HasFX()) pDsbNode->m_data->m_fxChain->NotifyRelease(this); m_pStreamingThread->UnregisterMixBuffer(this); } // If we're a SINKIN buffer, unregister with our owning sink if (m_pOwningSink) { hr = m_pOwningSink->RemoveBuffer(this); ASSERT(SUCCEEDED(hr)); RELEASE(m_pOwningSink); } // Release our FX chain, if we have one RELEASE(m_fxChain); // Make sure the buffer is stopped if(m_pDeviceBuffer) { hr = SetBufferState(VAD_BUFFERSTATE_STOPPED); ASSERT(SUCCEEDED(hr) || hr == DSERR_NODRIVER); } // Unregister with the parent object m_pDirectSound->m_lstSecondaryBuffers.RemoveDataFromList(this); // Free all interfaces DELETE(m_pImpDirectSoundNotify); DELETE(m_pImpDirectSoundBuffer); // Free owned objects ABSOLUTE_RELEASE(m_p3dBuffer); ABSOLUTE_RELEASE(m_pPropertySet); // Release the device buffer RELEASE(m_pDeviceBuffer); // Clean up memory #ifdef FUTURE_MULTIPAN_SUPPORT MEMFREE(m_pdwChannels); MEMFREE(m_plChannelVolumes); #endif #ifdef ENABLE_PERFLOG DELETE(m_pPerfState); #endif DPF_LEAVE_VOID(); } /*************************************************************************** * * Initialize * * Description: * Initializes a buffer object. If this function fails, the object * should be immediately deleted. * * Arguments: * LPDSBUFFERDESC [in]: buffer description. * CDirectSoundBuffer * [in]: source buffer to duplicate from, or NULL * to create a new buffer object. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Initialize" HRESULT CDirectSoundSecondaryBuffer::Initialize(LPCDSBUFFERDESC pDesc, CDirectSoundSecondaryBuffer *pSource) { #ifdef DEBUG const ULONG ulKsIoctlCount = g_ulKsIoctlCount; #endif // DEBUG DSBUFFERFOCUS bfFocus; VADRBUFFERCAPS vrbc; HRESULT hr; DPF_ENTER(); ASSERT(IsInit() == DSERR_UNINITIALIZED); ASSERT(LXOR(pSource, pDesc)); if(pDesc) { DPF(DPFLVL_MOREINFO, "dwFlags: 0x%8.8lX", pDesc->dwFlags); DPF(DPFLVL_MOREINFO, "dwBufferBytes: %lu", pDesc->dwBufferBytes); DPF(DPFLVL_MOREINFO, "dwReserved: %lu", pDesc->dwReserved); if(pDesc->lpwfxFormat) { DPF(DPFLVL_MOREINFO, "lpwfxFormat->wFormatTag: %u", pDesc->lpwfxFormat->wFormatTag); DPF(DPFLVL_MOREINFO, "lpwfxFormat->nChannels: %u", pDesc->lpwfxFormat->nChannels); DPF(DPFLVL_MOREINFO, "lpwfxFormat->nSamplesPerSec: %lu", pDesc->lpwfxFormat->nSamplesPerSec); DPF(DPFLVL_MOREINFO, "lpwfxFormat->nAvgBytesPerSec: %lu", pDesc->lpwfxFormat->nAvgBytesPerSec); DPF(DPFLVL_MOREINFO, "lpwfxFormat->nBlockAlign: %u", pDesc->lpwfxFormat->nBlockAlign); DPF(DPFLVL_MOREINFO, "lpwfxFormat->wBitsPerSample: %u", pDesc->lpwfxFormat->wBitsPerSample); if(WAVE_FORMAT_PCM != pDesc->lpwfxFormat->wFormatTag) { DPF(DPFLVL_MOREINFO, "lpwfxFormat->cbSize: %u", pDesc->lpwfxFormat->cbSize); } } DPF(DPFLVL_MOREINFO, "guid3DAlgorithm: " DPF_GUID_STRING, DPF_GUID_VAL(pDesc->guid3DAlgorithm)); } // Initialize the buffer hr = InitializeEmpty(pDesc, pSource); // Register with the parent object if(SUCCEEDED(hr)) { hr = HRFROMP(m_pDirectSound->m_lstSecondaryBuffers.AddNodeToList(this)); } // Set default properties if(SUCCEEDED(hr)) { if(pSource && (m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME) && DSBVOLUME_MAX != pSource->m_lVolume) { SetVolume(pSource->m_lVolume); } else { m_lVolume = DSBVOLUME_MAX; } } if(SUCCEEDED(hr)) { if(pSource && (m_dsbd.dwFlags & DSBCAPS_CTRLPAN) && DSBPAN_CENTER != pSource->m_lPan) { SetPan(pSource->m_lPan); } else { m_lPan = DSBPAN_CENTER; } } if(SUCCEEDED(hr)) { if(pSource && (m_dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY) && m_dsbd.lpwfxFormat->nSamplesPerSec != pSource->m_dwFrequency) { SetFrequency(pSource->m_dwFrequency); } else { m_dwFrequency = m_dsbd.lpwfxFormat->nSamplesPerSec; } } // Attempt to create the property set object if(SUCCEEDED(hr)) { m_pPropertySet = NEW(CDirectSoundSecondaryBufferPropertySet(this)); hr = HRFROMP(m_pPropertySet); if(SUCCEEDED(hr)) { hr = m_pPropertySet->Initialize(); } } // Attempt to create the 3D buffer if(SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_CTRL3D)) { m_p3dBuffer = NEW(CDirectSound3dBuffer(this)); hr = HRFROMP(m_p3dBuffer); if(SUCCEEDED(hr)) { hr = m_p3dBuffer->Initialize(m_dsbd.guid3DAlgorithm, m_dsbd.dwFlags, m_dwFrequency, m_pDirectSound->m_pPrimaryBuffer->m_p3dListener, pSource ? pSource->m_p3dBuffer : NULL); } } // Handle any possible resource acquisitions if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->GetCaps(&vrbc); } // Manbug 36422: CEmSecondaryRenderWaveBuffer objects can return LOCSOFTWARE|LOCDEFER, // in which case we incorrectly acquired resources here for deferred emulated buffers. // Hence the "&& !(vrbc.dwFlags & DSBCAPS_LOCDEFER)" below. if(SUCCEEDED(hr) && (vrbc.dwFlags & DSBCAPS_LOCMASK) && !(vrbc.dwFlags & DSBCAPS_LOCDEFER)) { hr = HandleResourceAcquisition(vrbc.dwFlags & DSBCAPS_LOCMASK); } // Register the interfaces with the interface manager if(SUCCEEDED(hr)) { hr = CreateAndRegisterInterface(this, IID_IDirectSoundBuffer, this, &m_pImpDirectSoundBuffer); } if(SUCCEEDED(hr) && GetDsVersion() >= DSVERSION_DX8) { hr = RegisterInterface(IID_IDirectSoundBuffer8, m_pImpDirectSoundBuffer, m_pImpDirectSoundBuffer); } if(SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)) { hr = CreateAndRegisterInterface(this, IID_IDirectSoundNotify, this, &m_pImpDirectSoundNotify); } // Initialize focus state if(SUCCEEDED(hr)) { bfFocus = g_pDsAdmin->GetBufferFocusState(this); switch(bfFocus) { case DSBUFFERFOCUS_INFOCUS: hr = Activate(TRUE); break; case DSBUFFERFOCUS_OUTOFFOCUS: hr = Activate(FALSE); break; case DSBUFFERFOCUS_LOST: hr = Lose(); break; } } // If this is a MIXIN buffer, register it with the streaming thread if (SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_MIXIN)) { m_pStreamingThread = GetStreamingThread(); hr = HRFROMP(m_pStreamingThread); if (SUCCEEDED(hr)) { hr = m_pStreamingThread->RegisterMixBuffer(this); } } // Success if(SUCCEEDED(hr)) { #ifdef DEBUG if(IS_KS_VAD(m_pDirectSound->m_pDevice->m_vdtDeviceType)) { DPF(DPFLVL_MOREINFO, "%s used %lu IOCTLs", TEXT(DPF_FNAME), g_ulKsIoctlCount - ulKsIoctlCount); } #endif // DEBUG m_hrInit = DS_OK; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * InitializeEmpty * * Description: * Initializes a buffer object. * * Arguments: * LPDSBUFFERDESC [in]: buffer description. * CDirectSoundBuffer * [in]: source buffer to duplicate from, or NULL * to create a new buffer object. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::InitializeEmpty" HRESULT CDirectSoundSecondaryBuffer::InitializeEmpty(LPCDSBUFFERDESC pDesc, CDirectSoundSecondaryBuffer *pSource) { BOOL fRealDuplicate = FALSE; VADRBUFFERDESC vrbd; HRESULT hr; DPF_ENTER(); // Save buffer description if(pSource) { m_dwOriginalFlags = pSource->m_dwOriginalFlags; hr = CopyDsBufferDesc(&pSource->m_dsbd, &m_dsbd); // We're going to reset the flags back to those originally passed to // CreateSoundBuffer so that the duplicate buffer is created with // the same *requested* capabilities as the original. // COMPATCOMPAT: one side effect of doing this is that if the source buffer // is in hardware, but no location flags were specified when creating it, // any number of its duplicates may potentially live in software. This // is new behavior as of version 5.0a. if(SUCCEEDED(hr)) { m_dsbd.dwFlags = m_dwOriginalFlags; } } else { m_dwOriginalFlags = pDesc->dwFlags; hr = CopyDsBufferDesc(pDesc, &m_dsbd); } // Fill in any missing pieces if(SUCCEEDED(hr) && !pSource) { m_dsbd.dwBufferBytes = GetAlignedBufferSize(m_dsbd.lpwfxFormat, m_dsbd.dwBufferBytes); } // Include legacy Voice Manager stuff if(SUCCEEDED(hr) && DSPROPERTY_VMANAGER_MODE_DEFAULT != m_pDirectSound->m_vmmMode) { m_dsbd.dwFlags |= DSBCAPS_LOCDEFER; } // Attempt to duplicate the device buffer if(SUCCEEDED(hr) && pSource) { hr = pSource->m_pDeviceBuffer->Duplicate(&m_pDeviceBuffer); // If we failed to duplicate the buffer, and the source buffer's // original flags don't specify a location, fall back on software. fRealDuplicate = SUCCEEDED(hr); if(FAILED(hr) && !(pSource->m_dwOriginalFlags & DSBCAPS_LOCHARDWARE)) { hr = DS_OK; } } // Attempt to create the device buffer if(SUCCEEDED(hr) && !m_pDeviceBuffer) { vrbd.dwFlags = m_dsbd.dwFlags; vrbd.dwBufferBytes = m_dsbd.dwBufferBytes; vrbd.pwfxFormat = m_dsbd.lpwfxFormat; vrbd.guid3dAlgorithm = m_dsbd.guid3DAlgorithm; hr = m_pDirectSound->m_pDevice->CreateSecondaryBuffer(&vrbd, m_pDirectSound, &m_pDeviceBuffer); } // Initialize the buffer data if(SUCCEEDED(hr)) { if(pSource) { if(!fRealDuplicate) { ASSERT(m_pDeviceBuffer->m_pSysMemBuffer->GetSize() == m_dsbd.dwBufferBytes); ASSERT(pSource->m_pDeviceBuffer->m_pSysMemBuffer->GetSize() == m_dsbd.dwBufferBytes); CopyMemory(GetWriteBuffer(), pSource->GetWriteBuffer(), m_dsbd.dwBufferBytes); } } else if(GetBufferType()) // If true, buffer is MIXIN or SINKIN (FIXME - does this simplify the sink?) { ClearWriteBuffer(); } else { #ifdef RDEBUG // Write some ugly noise into the buffer to catch remiss apps ::FillNoise(GetWriteBuffer(), m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat->wBitsPerSample); #else // RDEBUG if(GetDsVersion() < DSVERSION_DX8) { // For apps written for DirectX 8 or later, we decided not to // waste time initializing all secondary buffers with silence. // They'll still be zeroed out by our memory allocator, though ;-) ClearWriteBuffer(); } #endif // RDEBUG } if(!pSource || !fRealDuplicate) { hr = CommitToDevice(0, m_dsbd.dwBufferBytes); } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * AttemptResourceAcquisition * * Description: * Acquires hardware resources. * * Arguments: * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::AttemptResourceAcquisition" HRESULT CDirectSoundSecondaryBuffer::AttemptResourceAcquisition(DWORD dwFlags) { HRESULT hr = DSERR_INVALIDPARAM; CList<CDirectSoundSecondaryBuffer *> lstBuffers; CNode<CDirectSoundSecondaryBuffer *> * pNode; HRESULT hrTemp; DPF_ENTER(); ASSERT(m_pDeviceBuffer); if (m_dwStatus & DSBSTATUS_RESOURCESACQUIRED) { hr = DS_OK; } else { // Include legacy Voice Manager stuff if(DSPROPERTY_VMANAGER_MODE_DEFAULT != m_pDirectSound->m_vmmMode) { ASSERT(m_dsbd.dwFlags & DSBCAPS_LOCDEFER); ASSERT(!(dwFlags & DSBPLAY_LOCDEFERMASK)); dwFlags &= ~DSBPLAY_LOCDEFERMASK; dwFlags |= DSBCAPStoDSBPLAY(m_dsbd.dwFlags); switch(m_pDirectSound->m_vmmMode) { case DSPROPERTY_VMANAGER_MODE_AUTO: dwFlags |= DSBPLAY_TERMINATEBY_TIME; break; case DSPROPERTY_VMANAGER_MODE_USER: dwFlags |= DSBPLAY_TERMINATEBY_PRIORITY; break; } } // Try to acquire resources. If any of the TERMINATEBY flags were specified, // we'll need to try to explicitly acquire hardware resources, then attempt // to steal, then fall back on software. if(!(dwFlags & DSBPLAY_LOCSOFTWARE)) { hr = AcquireResources(DSBCAPS_LOCHARDWARE); if(FAILED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_MASK)) { hrTemp = GetResourceTheftCandidates(dwFlags & DSBPLAY_TERMINATEBY_MASK, &lstBuffers); if(SUCCEEDED(hrTemp)) { if(pNode = lstBuffers.GetListHead()) hr = StealResources(pNode->m_data); } else { hr = hrTemp; } } } if(FAILED(hr) && !(dwFlags & DSBPLAY_LOCHARDWARE)) { hr = AcquireResources(DSBCAPS_LOCSOFTWARE); } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * AcquireResources * * Description: * Acquires hardware resources. * * Arguments: * DWORD [in]: buffer location flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::AcquireResources" HRESULT CDirectSoundSecondaryBuffer::AcquireResources(DWORD dwFlags) { VADRBUFFERCAPS vrbc; HRESULT hr; DPF_ENTER(); ASSERT(m_pDeviceBuffer); ASSERT(!(m_dwStatus & DSBSTATUS_RESOURCESACQUIRED)); hr = m_pDeviceBuffer->GetCaps(&vrbc); if(SUCCEEDED(hr)) { if(!(vrbc.dwFlags & DSBCAPS_LOCMASK)) { // Try to acquire the device buffer hr = m_pDeviceBuffer->AcquireResources(dwFlags); } else if((dwFlags & DSBCAPS_LOCMASK) != (vrbc.dwFlags & DSBCAPS_LOCMASK)) { hr = DSERR_INVALIDCALL; } } if(SUCCEEDED(hr)) { DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has acquired resources at 0x%p", this, m_pDeviceBuffer); hr = CommitToDevice(0, m_dsbd.dwBufferBytes); // Handle the resource acquisition if(SUCCEEDED(hr)) { hr = HandleResourceAcquisition(vrbc.dwFlags & DSBCAPS_LOCMASK); } if (FAILED(hr)) { // Free any resources acquired so far HRESULT hrTemp = FreeResources(FALSE); ASSERT(SUCCEEDED(hrTemp)); // Not much we can do if this fails } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * StealResources * * Description: * Steals hardware resources from another buffer. * * Arguments: * CDirectSoundSecondaryBuffer * [in]: buffer to steal from. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::StealResources" HRESULT CDirectSoundSecondaryBuffer::StealResources(CDirectSoundSecondaryBuffer *pSource) { VADRBUFFERCAPS vrbc; HRESULT hrTemp; HRESULT hr; DPF_ENTER(); ASSERT(m_pDeviceBuffer); ASSERT(!(m_dwStatus & DSBSTATUS_RESOURCESACQUIRED)); DPF(DPFLVL_INFO, "Stealing resources from buffer at 0x%p", pSource); ASSERT(pSource->m_dwStatus & DSBSTATUS_RESOURCESACQUIRED); // Get the buffer location hr = pSource->m_pDeviceBuffer->GetCaps(&vrbc); if(SUCCEEDED(hr)) { ASSERT(vrbc.dwFlags & DSBCAPS_LOCHARDWARE); } // Steal hardware resources if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->StealResources(pSource->m_pDeviceBuffer); } if(SUCCEEDED(hr)) { // Free the source buffer's resources (since they're now our resources). hr = pSource->FreeResources(TRUE); if(SUCCEEDED(hr)) { hr = CommitToDevice(0, m_dsbd.dwBufferBytes); } // Handle the resource acquisition if(SUCCEEDED(hr)) { hr = HandleResourceAcquisition(vrbc.dwFlags & DSBCAPS_LOCMASK); } } else if(DSERR_UNSUPPORTED == hr) { // The device buffer doesn't support resource theft. Free the // source buffer's resources and try to acquire our own. hr = pSource->FreeResources(TRUE); if(SUCCEEDED(hr)) { hr = AcquireResources(DSBCAPS_LOCHARDWARE); // Try to reacquire the source buffer's resources if(FAILED(hr)) { hrTemp = pSource->AcquireResources(DSBCAPS_LOCHARDWARE); if(FAILED(hrTemp)) { RPF(DPFLVL_ERROR, "Unable to reacquire hardware resources!"); } } } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetResourceTheftCandidates * * Description: * Finds objects that are available to have their resources stolen. * * Arguments: * CList * [out]: destination list. * DWORD [in]: TERMINATEBY flags. If none are specified, all * compatible buffers are added to the list. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetResourceTheftCandidates" HRESULT CDirectSoundSecondaryBuffer::GetResourceTheftCandidates(DWORD dwFlags, CList<CDirectSoundSecondaryBuffer *> *plstDest) { HRESULT hr = DS_OK; CNode<CDirectSoundSecondaryBuffer *> * pNode; CNode<CDirectSoundSecondaryBuffer *> * pNext; CDirectSoundSecondaryBuffer * pTimeBuffer; DWORD dwStatus; DWORD dwMinPriority; DWORD dwPriority; DWORD cbMinRemain; DWORD cbRemain; COMPAREBUFFER cmp[2]; DPF_ENTER(); ASSERT(m_pDeviceBuffer); // First, find all compatible buffers for(pNode = m_pDirectSound->m_lstSecondaryBuffers.GetListHead(); pNode; pNode = pNode->m_pNext) { // We never want to look at ourselves. It's just sick. if(this == pNode->m_data) { continue; } // We can only steal from LOCDEFER buffers if(!(pNode->m_data->m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { continue; } // This flag prevents us from stealing resources from buffers that have // just called UserAcquireResources() and haven't called Play() yet if(!pNode->m_data->m_fCanStealResources) { continue; } // Make sure the object actually has some hardware resources hr = pNode->m_data->GetStatus(&dwStatus); if(FAILED(hr)) { break; } if(!(dwStatus & DSBSTATUS_LOCHARDWARE)) { continue; } // Compare the buffer properties cmp[0].dwFlags = m_dsbd.dwFlags; cmp[0].pwfxFormat = m_dsbd.lpwfxFormat; cmp[0].guid3dAlgorithm = m_dsbd.guid3DAlgorithm; cmp[1].dwFlags = pNode->m_data->m_dsbd.dwFlags; cmp[1].pwfxFormat = pNode->m_data->m_dsbd.lpwfxFormat; cmp[1].guid3dAlgorithm = pNode->m_data->m_dsbd.guid3DAlgorithm; if(!CompareBufferProperties(&cmp[0], &cmp[1])) { continue; } hr = HRFROMP(plstDest->AddNodeToList(pNode->m_data)); if (FAILED(hr)) { break; } } if(SUCCEEDED(hr)) { DPF(DPFLVL_MOREINFO, "Found %lu compatible buffers", plstDest->GetNodeCount()); } // Remove all buffers that are > the lowest priority if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_PRIORITY)) { dwMinPriority = GetBufferPriority(); for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext) { dwPriority = pNode->m_data->GetBufferPriority(); if(dwPriority < dwMinPriority) { dwMinPriority = dwPriority; } } pNode = plstDest->GetListHead(); while(pNode) { pNext = pNode->m_pNext; dwPriority = pNode->m_data->GetBufferPriority(); if(dwPriority > dwMinPriority) { plstDest->RemoveNodeFromList(pNode); } pNode = pNext; } #ifdef DEBUG DPF(DPFLVL_MOREINFO, "%lu buffers passed the priority test", plstDest->GetNodeCount()); for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext) { DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has priority %lu", pNode->m_data, pNode->m_data->GetBufferPriority()); } #endif // DEBUG } // Remove any buffers that aren't at max distance if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_DISTANCE)) { pNode = plstDest->GetListHead(); while(pNode) { pNext = pNode->m_pNext; if(!pNode->m_data->m_p3dBuffer || !pNode->m_data->m_p3dBuffer->m_pWrapper3dObject->IsAtMaxDistance()) { plstDest->RemoveNodeFromList(pNode); } pNode = pNext; } #ifdef DEBUG DPF(DPFLVL_MOREINFO, "%lu buffers passed the distance test", plstDest->GetNodeCount()); for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext) { DPF(DPFLVL_MOREINFO, "Buffer at 0x%p is at max distance", pNode->m_data); } #endif // DEBUG } // Find the buffer with the least amount of time remaining if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_TIME)) { cbMinRemain = MAX_DWORD; pTimeBuffer = NULL; for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext) { hr = pNode->m_data->GetPlayTimeRemaining(&cbRemain); if(FAILED(hr)) { break; } DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has %lu bytes remaining", pNode->m_data, cbRemain); if(cbRemain < cbMinRemain) { cbMinRemain = cbRemain; pTimeBuffer = pNode->m_data; } } if(SUCCEEDED(hr)) { plstDest->RemoveAllNodesFromList(); if(pTimeBuffer) { hr = HRFROMP(plstDest->AddNodeToList(pTimeBuffer)); } DPF(DPFLVL_MOREINFO, "%lu buffers passed the time test", plstDest->GetNodeCount()); } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetPlayTimeRemaining * * Description: * Gets the amount of time the buffer has remaining before stopping. * * Arguments: * LPDWORD [out]: receives time (in bytes). * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetPlayTimeRemaining" HRESULT CDirectSoundSecondaryBuffer::GetPlayTimeRemaining(LPDWORD pdwRemain) { DWORD dwRemain = MAX_DWORD; HRESULT hr = DS_OK; DWORD dwPlay; DPF_ENTER(); if(!(m_dwStatus & DSBSTATUS_LOOPING)) { hr = GetCurrentPosition(&dwPlay, NULL); if(SUCCEEDED(hr)) { dwRemain = m_dsbd.dwBufferBytes - dwPlay; } } if(SUCCEEDED(hr)) { *pdwRemain = dwRemain; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * FreeResources * * Description: * Frees hardware resources. * * Arguments: * BOOL [in]: TRUE if the buffer has been terminated as a result of * resources being stolen. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::FreeResources" HRESULT CDirectSoundSecondaryBuffer::FreeResources(BOOL fTerminate) { HRESULT hr; DPF_ENTER(); ASSERT(m_pDeviceBuffer); // Make sure the buffer is stopped hr = SetBufferState(VAD_BUFFERSTATE_STOPPED); // Free owned objects' resources if(SUCCEEDED(hr) && m_p3dBuffer) { hr = m_p3dBuffer->FreeResources(); } if(SUCCEEDED(hr) && m_pPropertySet) { hr = m_pPropertySet->FreeResources(); } // Free the device buffer's resources if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->FreeResources(); } // Resources have been freed if(SUCCEEDED(hr)) { DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has freed its resources", this); m_dwStatus &= ~DSBSTATUS_RESOURCESACQUIRED; } // If resources were freed as a result of a termination, update // the status. if(SUCCEEDED(hr) && fTerminate) { m_dwStatus |= DSBSTATUS_TERMINATED; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * HandleResourceAcquisition * * Description: * Handles acquisition of hardware resources. * * Arguments: * DWORD [in]: location flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::HandleResourceAcquisition" HRESULT CDirectSoundSecondaryBuffer::HandleResourceAcquisition(DWORD dwFlags) { HRESULT hr = S_OK; DPF_ENTER(); ASSERT(m_pDeviceBuffer); // Acquire 3D resources if(SUCCEEDED(hr) && m_p3dBuffer) { hr = m_p3dBuffer->AcquireResources(m_pDeviceBuffer); } // Acquire property set resources. It's OK if this fails. if(SUCCEEDED(hr) && m_pPropertySet) { m_pPropertySet->AcquireResources(m_pDeviceBuffer); } // Acquire effect handling resources if necessary if(SUCCEEDED(hr) && HasFX()) { hr = m_fxChain->AcquireFxResources(); } // Resources have been acquired if(SUCCEEDED(hr)) { m_dwStatus |= DSBSTATUS_RESOURCESACQUIRED; } // If the buffer was created *without* LOCDEFER, the caps must reflect // the location. If the buffer was create *with* LOCDEFER, the caps // will never reflect anything other than that; call GetStatus instead. if(SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { m_dsbd.dwFlags |= dwFlags & DSBCAPS_LOCMASK; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetCaps * * Description: * Queries capabilities for the buffer. * * Arguments: * LPDSBCAPS [out]: receives caps. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetCaps" HRESULT CDirectSoundSecondaryBuffer::GetCaps(LPDSBCAPS pDsbCaps) { DPF_ENTER(); ASSERT(sizeof(DSBCAPS) == pDsbCaps->dwSize); if(m_dsbd.dwFlags & DSBCAPS_LOCDEFER) { ASSERT(!(m_dsbd.dwFlags & DSBCAPS_LOCMASK)); } else { ASSERT(LXOR(m_dsbd.dwFlags & DSBCAPS_LOCSOFTWARE, m_dsbd.dwFlags & DSBCAPS_LOCHARDWARE)); } pDsbCaps->dwFlags = m_dsbd.dwFlags & DSBCAPS_VALIDFLAGS; // Remove any special internal flags (e.g. DSBCAPS_SINKIN) pDsbCaps->dwBufferBytes = GetBufferType() ? 0 : m_dsbd.dwBufferBytes; // Shouldn't report internal size of sink/MIXIN buffers pDsbCaps->dwUnlockTransferRate = 0; pDsbCaps->dwPlayCpuOverhead = 0; DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * GetFormat * * Description: * Retrieves the format for the given buffer. * * Arguments: * LPWAVEFORMATEX [out]: receives the format. * LPDWORD [in/out]: size of the format structure. On entry, this * must be initialized to the size of the structure. * On exit, this will be filled with the size that * was required. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetFormat" HRESULT CDirectSoundSecondaryBuffer::GetFormat(LPWAVEFORMATEX pwfxFormat, LPDWORD pdwSize) { HRESULT hr = DS_OK; DPF_ENTER(); hr = CopyWfxApi(m_dsbd.lpwfxFormat, pwfxFormat, pdwSize); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetFormat * * Description: * Sets the format for a given buffer. * * Arguments: * LPWAVEFORMATEX [in]: new format. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFormat" HRESULT CDirectSoundSecondaryBuffer::SetFormat(LPCWAVEFORMATEX pwfxFormat) { DPF_ENTER(); RPF(DPFLVL_ERROR, "Secondary buffers don't support SetFormat"); DPF_LEAVE_HRESULT(DSERR_INVALIDCALL); return DSERR_INVALIDCALL; } /*************************************************************************** * * GetFrequency * * Description: * Retrieves frequency for the given buffer. * * Arguments: * LPDWORD [out]: receives the frequency. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPrimaryBuffer::GetFrequency" HRESULT CDirectSoundSecondaryBuffer::GetFrequency(LPDWORD pdwFrequency) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLFREQUENCY"); hr = DSERR_CONTROLUNAVAIL; } if(SUCCEEDED(hr)) { *pdwFrequency = m_dwFrequency; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetFrequency * * Description: * Sets the frequency for the given buffer. * * Arguments: * DWORD [in]: frequency. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFrequency" HRESULT CDirectSoundSecondaryBuffer::SetFrequency(DWORD dwFrequency) { BOOL fContinue = TRUE; HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLFREQUENCY"); hr = DSERR_CONTROLUNAVAIL; } // Handle default frequency if(SUCCEEDED(hr) && DSBFREQUENCY_ORIGINAL == dwFrequency) { dwFrequency = m_dsbd.lpwfxFormat->nSamplesPerSec; } // Validate the frequency if(SUCCEEDED(hr) && (dwFrequency < DSBFREQUENCY_MIN || dwFrequency > DSBFREQUENCY_MAX)) { RPF(DPFLVL_ERROR, "Specified invalid frequency %lu (valid range is %lu to %lu)", dwFrequency, DSBFREQUENCY_MIN, DSBFREQUENCY_MAX); hr = DSERR_INVALIDPARAM; } // Only set the frequency if it's changed if(SUCCEEDED(hr) && dwFrequency == m_dwFrequency) { fContinue = FALSE; } // Update the 3D object if(SUCCEEDED(hr) && m_p3dBuffer && fContinue) { hr = m_p3dBuffer->SetFrequency(dwFrequency, &fContinue); } // Update the device buffer if(SUCCEEDED(hr) && fContinue) { hr = m_pDeviceBuffer->SetBufferFrequency(dwFrequency); } // Update our local copy if(SUCCEEDED(hr)) { m_dwFrequency = dwFrequency; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetPan * * Description: * Retrieves pan for the given buffer. * * Arguments: * LPLONG [out]: receives the pan. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetPan" HRESULT CDirectSoundSecondaryBuffer::GetPan(LPLONG plPan) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN"); hr = DSERR_CONTROLUNAVAIL; } if(SUCCEEDED(hr)) { *plPan = m_lPan; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetPan * * Description: * Sets the pan for a given buffer. * * Arguments: * LONG [in]: new pan. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetPan" HRESULT CDirectSoundSecondaryBuffer::SetPan(LONG lPan) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN"); hr = DSERR_CONTROLUNAVAIL; } // Set the pan if it has changed if(SUCCEEDED(hr) && lPan != m_lPan) { hr = SetAttenuation(m_lVolume, lPan); // Update our local copy if(SUCCEEDED(hr)) { m_lPan = lPan; } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetVolume * * Description: * Retrieves volume for the given buffer. * * Arguments: * LPLONG [out]: receives the volume. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVolume" HRESULT CDirectSoundSecondaryBuffer::GetVolume(LPLONG plVolume) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME"); hr = DSERR_CONTROLUNAVAIL; } if(SUCCEEDED(hr)) { *plVolume = m_lVolume; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetVolume * * Description: * Sets the volume for a given buffer. * * Arguments: * LONG [in]: new volume. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetVolume" HRESULT CDirectSoundSecondaryBuffer::SetVolume(LONG lVolume) { HRESULT hr = DS_OK; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME"); hr = DSERR_CONTROLUNAVAIL; } // Set the volume if it has changed if(SUCCEEDED(hr) && lVolume != m_lVolume) { #ifdef FUTURE_MULTIPAN_SUPPORT if (m_dsbd.dwFlags & DSBCAPS_CTRLCHANNELVOLUME) { hr = m_pDeviceBuffer->SetChannelAttenuations(lVolume, m_dwChannelCount, m_pdwChannels, m_plChannelVolumes); } else #endif { hr = SetAttenuation(lVolume, m_lPan); } // Update our local copy if(SUCCEEDED(hr)) { m_lVolume = lVolume; } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetAttenuation * * Description: * Obtains the buffer's true current attenuation, after 3D processing * (unlike GetVolume, which returns the last volume set by the app). * * Arguments: * FLOAT* [out]: attenuation in millibels. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetAttenuation" HRESULT CDirectSoundSecondaryBuffer::GetAttenuation(FLOAT* pfAttenuation) { DPF_ENTER(); // FIXME: this function needs to obtain the buffer's true attenuation // (i.e. the attenuation set via SetVolume() plus the extra attenuation // caused by DS3D processing). Unfortunately we don't have a method in // our device buffer class hierarchy (vad.h - CRenderWaveBuffer et al) // to obtain a buffer's attenuation. And the code in ds3d.cpp doesn't // explicitly save this info either (it just passes it along to the 3D // object implemenation - which in some cases is external to dsound, // e.g. ks3d.cpp). // // So we have two options: // // - Add a GetVolume() to the CSecondaryRenderWaveBuffer hierarchy; // In some cases it can read the volume directly off the buffer // (e.g. for KS buffers); in others (e.g. VxD buffers) the DDI // doesn't provide for that, so we'd have to remember the last // successfully set volume and return that (this last may be the // best implementation; in fact it may be possibly to do it just // once, in the base class). // // - Make the C3dObject hierarchy do attenuation calculations for // all 3d objects (even KS ones that don't require it), and save // the result. // // The first option looks much easier. // (MANBUG 39130 - POSTPONED TO DX8.1) HRESULT hr = DS_OK; *pfAttenuation = 0.0f; DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetAttenuation * * Description: * Sets the volume and pan for a given buffer. * * Arguments: * LONG [in]: new volume. * LONG [in]: new pan. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetAttenuation" HRESULT CDirectSoundSecondaryBuffer::SetAttenuation(LONG lVolume, LONG lPan) { BOOL fContinue = TRUE; HRESULT hr = DS_OK; DSVOLUMEPAN dsvp; DPF_ENTER(); // Calculate the attenuation based on the volume and pan if(SUCCEEDED(hr) && fContinue) { FillDsVolumePan(lVolume, lPan, &dsvp); } // Update the 3D object if(SUCCEEDED(hr) && m_p3dBuffer && fContinue) { hr = m_p3dBuffer->SetAttenuation(&dsvp, &fContinue); } // Update the device buffer if(SUCCEEDED(hr) && fContinue) { hr = m_pDeviceBuffer->SetAttenuation(&dsvp); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetNotificationPositions * * Description: * Sets buffer notification positions. * * Arguments: * DWORD [in]: DSBPOSITIONNOTIFY structure count. * LPDSBPOSITIONNOTIFY [in]: offsets and events. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetNotificationPositions" HRESULT CDirectSoundSecondaryBuffer::SetNotificationPositions(DWORD dwCount, LPCDSBPOSITIONNOTIFY paNotes) { HRESULT hr = DS_OK; LPDSBPOSITIONNOTIFY paNotesOrdered = NULL; DWORD dwState; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLPOSITIONNOTIFY"); hr = DSERR_CONTROLUNAVAIL; } // Validate notifications if(SUCCEEDED(hr)) { hr = ValidateNotificationPositions(m_dsbd.dwBufferBytes, dwCount, paNotes, m_dsbd.lpwfxFormat->nBlockAlign, &paNotesOrdered); } // We must be stopped in order to set notification positions if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->GetState(&dwState); if(SUCCEEDED(hr) && dwState & VAD_BUFFERSTATE_STARTED) { RPF(DPFLVL_ERROR, "Buffer must be stopped before setting notification positions"); hr = DSERR_INVALIDCALL; } } // Set notifications if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->SetNotificationPositions(dwCount, paNotesOrdered); } MEMFREE(paNotesOrdered); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetOwningSink * * Description: * Sets the owning CDirectSoundSink object for this buffer. * * Arguments: * CDirectSoundSink * [in]: The new the owning sink object. * * Returns: * void * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetOwningSink" void CDirectSoundSecondaryBuffer::SetOwningSink(CDirectSoundSink* pOwningSink) { DPF_ENTER(); ASSERT(m_dsbd.dwFlags & DSBCAPS_SINKIN); ASSERT(m_pOwningSink == NULL); CHECK_WRITE_PTR(pOwningSink); m_pOwningSink = pOwningSink; m_pOwningSink->AddRef(); m_pDeviceBuffer->SetOwningSink(pOwningSink); DPF_LEAVE_VOID(); } /*************************************************************************** * * GetCurrentPosition * * Description: * Gets the current play/write positions for the given buffer. * * Arguments: * LPDWORD [out]: receives play cursor position. * LPDWORD [out]: receives write cursor position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetCurrentPosition" HRESULT CDirectSoundSecondaryBuffer::GetCurrentPosition(LPDWORD pdwPlay, LPDWORD pdwWrite) { HRESULT hr = DS_OK; DWORD dwPlay; DWORD dwWrite; DPF_ENTER(); // Forbid certain calls for MIXIN and SINKIN buffers if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN)) { RPF(DPFLVL_ERROR, "GetCurrentPosition() not valid for MIXIN/sink buffers"); hr = DSERR_INVALIDCALL; } // Check for BUFFERLOST if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { hr = DSERR_BUFFERLOST; } // We save the position to local variables so that the object we're // calling into doesn't have to worry about whether one or both of // the arguments are NULL. if(SUCCEEDED(hr)) { if( m_pDirectSound->m_ahAppHacks.vdtCachePositions & m_pDirectSound->m_pDevice->m_vdtDeviceType ) { // App hack for Furby calling GetCurrentPosition every .5ms on multiple buffers which stresses NT/WDM systems DWORD dwNow = timeGetTime(); if( m_dwAHLastGetPosTime > 0 && dwNow >= m_dwAHLastGetPosTime && // catch unlikely wrap-around and '=' because of 5ms accuracy of timeGetTime() dwNow - m_dwAHLastGetPosTime < 5 ) // 5ms tolerance { dwPlay = m_dwAHCachedPlayPos; dwWrite = m_dwAHCachedWritePos; } else { hr = m_pDeviceBuffer->GetCursorPosition(&dwPlay, &dwWrite); m_dwAHCachedPlayPos = dwPlay; m_dwAHCachedWritePos = dwWrite; } m_dwAHLastGetPosTime = dwNow; } else { hr = m_pDeviceBuffer->GetCursorPosition(&dwPlay, &dwWrite); } } // Block-align the positions if(SUCCEEDED(hr)) { dwPlay = BLOCKALIGN(dwPlay, m_dsbd.lpwfxFormat->nBlockAlign); dwWrite = BLOCKALIGN(dwWrite, m_dsbd.lpwfxFormat->nBlockAlign); } // Apply app-hacks and cursor adjustments if(SUCCEEDED(hr)) { // If the buffer has effects, we return the FX cursor as the write cursor if(HasFX()) { DWORD dwDistance = BytesToMs(DISTANCE(dwWrite, m_dwSliceEnd, GetBufferSize()), Format()); if (dwDistance > 200) DPF(DPFLVL_WARNING, "FX cursor suspiciously far ahead of write cursor (%ld ms)", dwDistance); else dwWrite = m_dwSliceEnd; // FIXME: may not always be valid } if (m_pDirectSound->m_ahAppHacks.lCursorPad) { dwPlay = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad); dwWrite = PadCursor(dwWrite, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad); } if(m_pDirectSound->m_ahAppHacks.vdtReturnWritePos & m_pDirectSound->m_pDevice->m_vdtDeviceType) { dwPlay = dwWrite; } if(m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.fEnable) { dwWrite = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.lCursorPad); } } // Success if(SUCCEEDED(hr) && pdwPlay) { *pdwPlay = dwPlay; } if(SUCCEEDED(hr) && pdwWrite) { *pdwWrite = dwWrite; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetCurrentPosition * * Description: * Sets the current play position for a given buffer. * * Arguments: * DWORD [in]: new play position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetCurrentPosition" HRESULT CDirectSoundSecondaryBuffer::SetCurrentPosition(DWORD dwPlay) { HRESULT hr = DS_OK; DPF_ENTER(); // Forbid certain calls for MIXIN and SINKIN buffers if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN)) { RPF(DPFLVL_ERROR, "SetCurrentPosition() not valid for MIXIN/sink buffers"); hr = DSERR_INVALIDCALL; } // Check for BUFFERLOST if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { hr = DSERR_BUFFERLOST; } // Check the cursor position if(SUCCEEDED(hr) && dwPlay >= m_dsbd.dwBufferBytes) { RPF(DPFLVL_ERROR, "Cursor position out of bounds"); hr = DSERR_INVALIDPARAM; } // Make sure dwPlay is block-aligned if(SUCCEEDED(hr)) { dwPlay = BLOCKALIGN(dwPlay, m_dsbd.lpwfxFormat->nBlockAlign); } // Prime the effects chain for the new play position if(SUCCEEDED(hr) && HasFX()) { hr = m_fxChain->PreRollFx(dwPlay); } if(SUCCEEDED(hr)) { hr = m_pDeviceBuffer->SetCursorPosition(dwPlay); } // Mark the play state as stopped to force the streaming thread // to react to our new cursor position if(SUCCEEDED(hr)) { m_playState = Stopped; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetStatus * * Description: * Retrieves status for the given buffer. * * Arguments: * LPDWORD [out]: receives the status. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetStatus" HRESULT CDirectSoundSecondaryBuffer::GetStatus(LPDWORD pdwStatus) { HRESULT hr = DS_OK; DWORD dwStatus; DWORD dwState; VADRBUFFERCAPS vrbc; DPF_ENTER(); // Update the buffer status. If we're lost, that's the only state we care about if(m_dwStatus & DSBSTATUS_BUFFERLOST) { dwStatus = DSBSTATUS_BUFFERLOST; } else { // Get the current device buffer state hr = m_pDeviceBuffer->GetState(&dwState); if(SUCCEEDED(hr)) { dwStatus = m_dwStatus; UpdateBufferStatusFlags(dwState, &m_dwStatus); // If we thought we were playing, but now we're stopped, handle // the transition. if((dwStatus & DSBSTATUS_PLAYING) && !(m_dwStatus & DSBSTATUS_PLAYING)) { hr = Stop(); } } // Fill in the buffer location if(SUCCEEDED(hr)) { m_dwStatus &= ~DSBSTATUS_LOCMASK; if(m_dwStatus & DSBSTATUS_RESOURCESACQUIRED) { hr = m_pDeviceBuffer->GetCaps(&vrbc); if(SUCCEEDED(hr)) { m_dwStatus |= DSBCAPStoDSBSTATUS(vrbc.dwFlags); } } } if(SUCCEEDED(hr)) { dwStatus = m_dwStatus; } } // Mask off bits that shouldn't get back to the app if(SUCCEEDED(hr)) { dwStatus &= DSBSTATUS_USERMASK; } if(SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { dwStatus &= ~DSBSTATUS_LOCDEFERMASK; } if(SUCCEEDED(hr) && pdwStatus) { *pdwStatus = dwStatus; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Play * * Description: * Starts the buffer playing. * * Arguments: * DWORD [in]: priority. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Play" HRESULT CDirectSoundSecondaryBuffer::Play(DWORD dwPriority, DWORD dwFlags) { #ifdef DEBUG const ULONG ulKsIoctlCount = g_ulKsIoctlCount; #endif // DEBUG DWORD dwState = VAD_BUFFERSTATE_STARTED; HRESULT hr = DS_OK; DPF_ENTER(); // Make sure cooperative level has been set if(SUCCEEDED(hr) && (!m_pDirectSound->m_dsclCooperativeLevel.dwThreadId || DSSCL_NONE == m_pDirectSound->m_dsclCooperativeLevel.dwPriority)) { RPF(DPFLVL_ERROR, "Cooperative level must be set before calling Play"); hr = DSERR_PRIOLEVELNEEDED; } // Priority is only valid if we're LOCDEFER if(SUCCEEDED(hr) && dwPriority && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { RPF(DPFLVL_ERROR, "Priority is only valid on LOCDEFER buffers"); hr = DSERR_INVALIDPARAM; } // Validate flags if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_LOCDEFERMASK) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { RPF(DPFLVL_ERROR, "Specified a flag that is only valid on LOCDEFER buffers"); hr = DSERR_INVALIDPARAM; } // For MIXIN/sink buffers, the DSBPLAY_LOOPING flag is mandatory if(SUCCEEDED(hr) && GetBufferType() && !(dwFlags & DSBPLAY_LOOPING)) { RPF(DPFLVL_ERROR, "The LOOPING flag must always be set for MIXIN/sink buffers"); hr = DSERR_INVALIDPARAM; } // Check for BUFFERLOST if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { hr = DSERR_BUFFERLOST; } // Refresh the current buffer status if(SUCCEEDED(hr)) { hr = GetStatus(NULL); } // Set buffer priority if(SUCCEEDED(hr)) { m_dwPriority = dwPriority; } // Reset the special success code m_pDeviceBuffer->m_hrSuccessCode = DS_OK; // Make sure resources have been acquired if(SUCCEEDED(hr)) { hr = AttemptResourceAcquisition(dwFlags); } // Set the buffer state if(SUCCEEDED(hr)) { if(dwFlags & DSBPLAY_LOOPING) { dwState |= VAD_BUFFERSTATE_LOOPING; } hr = SetBufferState(dwState); } if(SUCCEEDED(hr)) { // If the buffer was previously terminated, remove the flag from the status m_dwStatus &= ~DSBSTATUS_TERMINATED; // Make it possible to steal this buffer's resources m_fCanStealResources = TRUE; } // Save the result code m_hrPlay = hr; #ifdef DEBUG if(IS_KS_VAD(m_pDirectSound->m_pDevice->m_vdtDeviceType)) { DPF(DPFLVL_INFO, "%s used %lu IOCTLs", TEXT(DPF_FNAME), g_ulKsIoctlCount - ulKsIoctlCount); } #endif // DEBUG DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Stop * * Description: * Stops playing the given buffer. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Stop" HRESULT CDirectSoundSecondaryBuffer::Stop(void) { #ifdef DEBUG const ULONG ulKsIoctlCount = g_ulKsIoctlCount; #endif // DEBUG HRESULT hr = DS_OK; DPF_ENTER(); #ifdef ENABLE_PERFLOG // Check if there were any glitches if (m_pPerfState) { m_pPerfState->OnUnlockBuffer(0, GetBufferSize()); } #endif // Check for BUFFERLOST if(m_dwStatus & DSBSTATUS_BUFFERLOST) { hr = DSERR_BUFFERLOST; } // Set the buffer state if(SUCCEEDED(hr)) { hr = SetBufferState(VAD_BUFFERSTATE_STOPPED); } // If we're LOCDEFER and the buffer is stopped, resources can be freed if(SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_LOCDEFER) && (m_dwStatus & DSBSTATUS_RESOURCESACQUIRED)) { hr = FreeResources(FALSE); } #ifdef DEBUG if(IS_KS_VAD(m_pDirectSound->m_pDevice->m_vdtDeviceType)) { DPF(DPFLVL_MOREINFO, "%s used %lu IOCTLs", TEXT(DPF_FNAME), g_ulKsIoctlCount - ulKsIoctlCount); } #endif // DEBUG DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetBufferState * * Description: * Sets the buffer play/stop state. * * Arguments: * DWORD [in]: buffer state flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetBufferState" HRESULT CDirectSoundSecondaryBuffer::SetBufferState(DWORD dwNewState) { DWORD dwOldState; HRESULT hr; DPF_ENTER(); hr = m_pDeviceBuffer->GetState(&dwOldState); if(SUCCEEDED(hr) && dwNewState != dwOldState) { // Our state is changing; reset the performance tracing state #ifdef ENABLE_PERFLOG if (PerflogTracingEnabled()) { if (!m_pPerfState) m_pPerfState = NEW(BufferPerfState(this)); if (m_pPerfState) m_pPerfState->Reset(); } #endif DPF(DPFLVL_MOREINFO, "Buffer at 0x%p going from %s to %s", this, StateName(dwOldState), StateName(dwNewState)); hr = m_pDeviceBuffer->SetState(dwNewState); if (SUCCEEDED(hr) && HasSink()) { #ifdef FUTURE_WAVE_SUPPORT if ((m_dsbd.dwFlags & DSBCAPS_FROMWAVEOBJECT) && (dwNewState & VAD_BUFFERSTATE_STARTED)) hr = m_pOwningSink->Activate(TRUE); // FIXME: maybe this activation should be handled by the sink // itself in SetBufferState() below, so it can also take care // of deactivation when it runs out of active clients if (SUCCEEDED(hr)) #endif // FUTURE_WAVE_SUPPORT hr = m_pOwningSink->SetBufferState(this, dwNewState, dwOldState); } if (SUCCEEDED(hr) && HasFX()) hr = m_fxChain->NotifyState(dwNewState); // If a MIXIN or SINKIN buffer is stopping, clear it and set its position to 0 if (SUCCEEDED(hr) && GetBufferType() && !(dwNewState & VAD_BUFFERSTATE_STARTED)) { ClearWriteBuffer(); // FIXME - does this simplify the sink? ClearPlayBuffer(); m_pDeviceBuffer->SetCursorPosition(0); m_playState = Stopped; // This stops FX processing on this buffer, // and forces the streaming thread to reset // our current slice next time it wakes up m_dwSliceBegin = m_dwSliceEnd = MAX_DWORD; } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Activate * * Description: * Activates or deactivates the buffer object. * * Arguments: * BOOL [in]: Activation state. TRUE to activate, FALSE to deactivate. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Activate" HRESULT CDirectSoundSecondaryBuffer::Activate(BOOL fActive) { HRESULT hr; DPF_ENTER(); hr = SetMute(!fActive); if(SUCCEEDED(hr)) { if(fActive) { m_dwStatus |= DSBSTATUS_ACTIVE; // If we're a MIXIN or SINKIN buffer, we have to clear our lost // status (since the app can't call Restore() to do it for us) if (GetBufferType()) { // If the buffer was playing before it got lost, restart it if (m_dwStatus & DSBSTATUS_STOPPEDBYFOCUS) hr = SetBufferState(VAD_BUFFERSTATE_STARTED | VAD_BUFFERSTATE_LOOPING); // Clear our BUFFERLOST and STOPPEDBYFOCUS status flags m_dwStatus &= ~(DSBSTATUS_BUFFERLOST | DSBSTATUS_STOPPEDBYFOCUS); } } else { m_dwStatus &= ~DSBSTATUS_ACTIVE; } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetMute * * Description: * Mutes or unmutes the buffer. * * Arguments: * BOOL [in]: Mute state. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetMute" HRESULT CDirectSoundSecondaryBuffer::SetMute(BOOL fMute) { BOOL fContinue = TRUE; HRESULT hr = DS_OK; DPF_ENTER(); // Only set the mute status if it's changed if(SUCCEEDED(hr) && fMute == m_fMute) { fContinue = FALSE; } // Update the 3D object if(SUCCEEDED(hr) && m_p3dBuffer && fContinue) { hr = m_p3dBuffer->SetMute(fMute, &fContinue); } // Update the device buffer if(SUCCEEDED(hr) && fContinue) { hr = m_pDeviceBuffer->SetMute(fMute); } // Update our local copy if(SUCCEEDED(hr)) { m_fMute = fMute; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Lock * * Description: * Locks the buffer memory to allow for writing. * * Arguments: * DWORD [in]: offset, in bytes, from the start of the buffer to where * the lock begins. This parameter is ignored if * DSBLOCK_FROMWRITECURSOR is specified in the dwFlags * parameter. * DWORD [in]: size, in bytes, of the portion of the buffer to lock. * Note that the sound buffer is conceptually circular. * LPVOID * [out]: address for a pointer to contain the first block of * the sound buffer to be locked. * LPDWORD [out]: address for a variable to contain the number of bytes * pointed to by the ppvAudioPtr1 parameter. If this * value is less than the dwWriteBytes parameter, * ppvAudioPtr2 will point to a second block of sound * data. * LPVOID * [out]: address for a pointer to contain the second block of * the sound buffer to be locked. If the value of this * parameter is NULL, the ppvAudioPtr1 parameter * points to the entire locked portion of the sound * buffer. * LPDWORD [out]: address of a variable to contain the number of bytes * pointed to by the ppvAudioPtr2 parameter. If * ppvAudioPtr2 is NULL, this value will be 0. * DWORD [in]: locking flags * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Lock" HRESULT CDirectSoundSecondaryBuffer::Lock(DWORD dwWriteCursor, DWORD dwWriteBytes, LPVOID *ppvAudioPtr1, LPDWORD pdwAudioBytes1, LPVOID *ppvAudioPtr2, LPDWORD pdwAudioBytes2, DWORD dwFlags) { HRESULT hr = DS_OK; DPF_ENTER(); // Forbid certain calls for MIXIN and SINKIN buffers if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN)) { RPF(DPFLVL_ERROR, "Lock() not valid for MIXIN/sink buffers"); hr = DSERR_INVALIDCALL; } // Check for BUFFERLOST if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { hr = DSERR_BUFFERLOST; } // Handle flags if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_FROMWRITECURSOR)) { hr = GetCurrentPosition(NULL, &dwWriteCursor); } if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_ENTIREBUFFER)) { dwWriteBytes = m_dsbd.dwBufferBytes; } // Cursor validation if(SUCCEEDED(hr) && dwWriteCursor >= m_dsbd.dwBufferBytes) { ASSERT(!(dwFlags & DSBLOCK_FROMWRITECURSOR)); RPF(DPFLVL_ERROR, "Write cursor past buffer end"); hr = DSERR_INVALIDPARAM; } if(SUCCEEDED(hr) && dwWriteBytes > m_dsbd.dwBufferBytes) { ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER)); RPF(DPFLVL_ERROR, "Lock size larger than buffer size"); hr = DSERR_INVALIDPARAM; } if(SUCCEEDED(hr) && !dwWriteBytes) { ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER)); RPF(DPFLVL_ERROR, "Lock size must be > 0"); hr = DSERR_INVALIDPARAM; } // Lock the device buffer if(SUCCEEDED(hr)) { if (GetDsVersion() >= DSVERSION_DX8) { // DX8 removes support for apps that lock their buffers // and never bother to unlock them again (see the comment // in CVxdSecondaryRenderWaveBuffer::Lock for explanation) hr = DirectLock(dwWriteCursor, dwWriteBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2); } else { hr = m_pDeviceBuffer->Lock(dwWriteCursor, dwWriteBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2); } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Unlock * * Description: * Unlocks the given buffer. * * Arguments: * LPVOID [in]: pointer to the first block. * DWORD [in]: size of the first block. * LPVOID [in]: pointer to the second block. * DWORD [in]: size of the second block. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Unlock" HRESULT CDirectSoundSecondaryBuffer::Unlock(LPVOID pvAudioPtr1, DWORD dwAudioBytes1, LPVOID pvAudioPtr2, DWORD dwAudioBytes2) { HRESULT hr = DS_OK; DPF_ENTER(); // Forbid certain calls for MIXIN and SINKIN buffers if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN)) { RPF(DPFLVL_ERROR, "Unlock() not valid for MIXIN/sink buffers"); hr = DSERR_INVALIDCALL; } // Check for BUFFERLOST if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { hr = DSERR_BUFFERLOST; } // Unlock the device buffer if(SUCCEEDED(hr)) { if (GetDsVersion() >= DSVERSION_DX8) { // DX8 removes support for apps that lock their buffers // and never bother to unlock them again (see the comment // in CVxdSecondaryRenderWaveBuffer::Lock for explanation) hr = DirectUnlock(pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2); } else { hr = m_pDeviceBuffer->Unlock(pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2); } } // Update the processed FX buffer if necessary if(SUCCEEDED(hr) && HasFX()) { m_fxChain->UpdateFx(pvAudioPtr1, dwAudioBytes1); if (pvAudioPtr2 && dwAudioBytes2) m_fxChain->UpdateFx(pvAudioPtr2, dwAudioBytes2); } #ifdef ENABLE_PERFLOG // Check if there were any glitches if (m_pPerfState) { if (pvAudioPtr1) m_pPerfState->OnUnlockBuffer(PtrDiffToUlong(LPBYTE(pvAudioPtr1) - GetPlayBuffer()), dwAudioBytes1); if (pvAudioPtr2) m_pPerfState->OnUnlockBuffer(PtrDiffToUlong(LPBYTE(pvAudioPtr2) - GetPlayBuffer()), dwAudioBytes2); } #endif DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * Lose * * Description: * Flags the buffer as lost. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Lose" HRESULT CDirectSoundSecondaryBuffer::Lose(void) { DPF_ENTER(); if(!(m_dwStatus & DSBSTATUS_BUFFERLOST)) { // If the buffer is MIXIN or SINKIN, and is currently playing, // flag it as stopped due to a focus change if (GetBufferType()) { DWORD dwState = 0; m_pDeviceBuffer->GetState(&dwState); if (dwState & VAD_BUFFERSTATE_STARTED) m_dwStatus |= DSBSTATUS_STOPPEDBYFOCUS; } // Stop the buffer. All lost buffers are stopped by definition. SetBufferState(VAD_BUFFERSTATE_STOPPED); // Flag the buffer as lost m_dwStatus |= DSBSTATUS_BUFFERLOST; // Deactivate the buffer Activate(FALSE); // Free any open locks on the buffer m_pDeviceBuffer->OverrideLocks(); } DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * Restore * * Description: * Attempts to restore a lost bufer. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::Restore" HRESULT CDirectSoundSecondaryBuffer::Restore(void) { HRESULT hr = DS_OK; DPF_ENTER(); // Forbid certain calls for MIXIN and SINKIN buffers if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN)) { RPF(DPFLVL_ERROR, "Restore() not valid for MIXIN/sink buffers"); hr = DSERR_INVALIDCALL; } if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST)) { // Are we still lost? if(DSBUFFERFOCUS_LOST == g_pDsAdmin->GetBufferFocusState(this)) { hr = DSERR_BUFFERLOST; } else { m_dwStatus &= ~DSBSTATUS_BUFFERLOST; } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetVoiceManagerMode * * Description: * Gets the current voice manager mode. * * Arguments: * VmMode * [out]: receives voice manager mode. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVoiceManagerMode" HRESULT CDirectSoundSecondaryBuffer::GetVoiceManagerMode(VmMode *pvmmMode) { DPF_ENTER(); *pvmmMode = m_pDirectSound->m_vmmMode; DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * SetVoiceManagerMode * * Description: * Sets the current voice manager mode. * * Arguments: * VmMode [in]: voice manager mode. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetVoiceManagerMode" HRESULT CDirectSoundSecondaryBuffer::SetVoiceManagerMode(VmMode vmmMode) { HRESULT hr = DS_OK; DPF_ENTER(); if(vmmMode < DSPROPERTY_VMANAGER_MODE_FIRST || vmmMode > DSPROPERTY_VMANAGER_MODE_LAST) { RPF(DPFLVL_ERROR, "Invalid Voice Manager mode"); hr = DSERR_INVALIDPARAM; } if(SUCCEEDED(hr)) { m_pDirectSound->m_vmmMode = vmmMode; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetVoiceManagerPriority * * Description: * Gets the current voice manager priority. * * Arguments: * LPDWORD [out]: receives voice manager priority. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVoiceManagerPriority" HRESULT CDirectSoundSecondaryBuffer::GetVoiceManagerPriority(LPDWORD pdwPriority) { DPF_ENTER(); *pdwPriority = m_dwVmPriority; DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } /*************************************************************************** * * SetVoiceManagerPriority * * Description: * Sets the current voice manager priority. * * Arguments: * DWORD [in]: voice manager priority. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetVoiceManagerPriority" HRESULT CDirectSoundSecondaryBuffer::SetVoiceManagerPriority(DWORD dwPriority) { DPF_ENTER(); m_dwVmPriority = dwPriority; DPF_LEAVE_HRESULT(DS_OK); return DS_OK; } #ifdef DEAD_CODE /*************************************************************************** * * GetVoiceManagerState * * Description: * Gets the current voice manager state. * * Arguments: * VmState * [out]: receives voice manager state. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVoiceManagerState" HRESULT CDirectSoundSecondaryBuffer::GetVoiceManagerState(VmState *pvmsState) { DWORD dwStatus; HRESULT hr; DPF_ENTER(); hr = GetStatus(&dwStatus); if(SUCCEEDED(hr)) { if(dwStatus & DSBSTATUS_PLAYING) { *pvmsState = DSPROPERTY_VMANAGER_STATE_PLAYING3DHW; } else if(FAILED(m_hrPlay)) { *pvmsState = DSPROPERTY_VMANAGER_STATE_PLAYFAILED; } else if(dwStatus & DSBSTATUS_TERMINATED) { *pvmsState = DSPROPERTY_VMANAGER_STATE_BUMPED; } else { ASSERT(!dwStatus); *pvmsState = DSPROPERTY_VMANAGER_STATE_SILENT; } } DPF_LEAVE_HRESULT(hr); return hr; } #endif // DEAD_CODE /*************************************************************************** * * SetFX * * Description: * Sets a chain of effects on this buffer, replacing any previous * effect chain and, if necessary, allocating or deallocating the * shadow buffer used to hold unprocessed audio . * * Arguments: * DWORD [in]: Number of effects. 0 to remove current FX chain. * DSEFFECTDESC * [in]: Array of effect descriptor structures. * DWORD * [out]: Receives the creation statuses of the effects. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFX" HRESULT CDirectSoundSecondaryBuffer::SetFX(DWORD dwFxCount, LPDSEFFECTDESC pDSFXDesc, LPDWORD pdwResultCodes) { DWORD dwStatus; HRESULT hr = DS_OK; DPF_ENTER(); ASSERT(IS_VALID_READ_PTR(pDSFXDesc, dwFxCount * sizeof *pDSFXDesc)); ASSERT(!pdwResultCodes || IS_VALID_WRITE_PTR(pdwResultCodes, dwFxCount * sizeof *pdwResultCodes)); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFX)) { RPF(DPFLVL_ERROR, "Buffer was not created with DSBCAPS_CTRLFX flag"); hr = DSERR_CONTROLUNAVAIL; } // Check the buffer is inactive if(SUCCEEDED(hr)) { hr = GetStatus(&dwStatus); if(SUCCEEDED(hr) && (dwStatus & DSBSTATUS_PLAYING)) { RPF(DPFLVL_ERROR, "Cannot change effects, because buffer is playing"); hr = DSERR_INVALIDCALL; } } // Check there are no pending locks on the buffer if(SUCCEEDED(hr) && m_pDeviceBuffer->m_pSysMemBuffer->GetLockCount()) { RPF(DPFLVL_ERROR, "Cannot change effects, because buffer has pending locks"); hr = DSERR_INVALIDCALL; } if(SUCCEEDED(hr)) { // Release the old FX chain, if necessary RELEASE(m_fxChain); // If the effects count is 0, we can free up associated resources if (dwFxCount == 0) { m_pDeviceBuffer->m_pSysMemBuffer->FreeFxBuffer(); } else // Allocate the pre-FX buffer and create the FX chain requested { hr = m_pDeviceBuffer->m_pSysMemBuffer->AllocateFxBuffer(); if (SUCCEEDED(hr)) { m_fxChain = NEW(CEffectChain(this)); hr = HRFROMP(m_fxChain); } if (SUCCEEDED(hr)) { hr = m_fxChain->Initialize(dwFxCount, pDSFXDesc, pdwResultCodes); } if (SUCCEEDED(hr)) { if (!(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { hr = m_fxChain->AcquireFxResources(); } // We need to preserve the return code from AcquireFxResources, in case it's // DS_INCOMPLETE, so we omit "hr=" from GetFxStatus (which always succeeds): if (pdwResultCodes) { m_fxChain->GetFxStatus(pdwResultCodes); } } if (FAILED(hr)) { RELEASE(m_fxChain); m_pDeviceBuffer->m_pSysMemBuffer->FreeFxBuffer(); } } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetFXBufferConfig * * Description: * Sets a chain of effects described in a CDirectSoundBufferConfig * object, which represents a buffer description previously loaded * from a file (or other IStream provider). * * Arguments: * CDirectSoundBufferConfig * [in]: describes the effects to be set. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFXBufferConfig" HRESULT CDirectSoundSecondaryBuffer::SetFXBufferConfig(CDirectSoundBufferConfig* pDSBConfigObj) { DWORD dwStatus; HRESULT hr; DPF_ENTER(); CHECK_READ_PTR(pDSBConfigObj); ASSERT(m_dsbd.dwFlags & DSBCAPS_CTRLFX); hr = GetStatus(&dwStatus); if(SUCCEEDED(hr) && (dwStatus & DSBSTATUS_PLAYING)) { DPF(DPFLVL_ERROR, "Cannot change effects, because buffer is playing"); hr = DSERR_GENERIC; } if(SUCCEEDED(hr)) { // Release the old FX chain, if necessary RELEASE(m_fxChain); // Allocate the pre-FX buffer and create the FX chain requested hr = m_pDeviceBuffer->m_pSysMemBuffer->AllocateFxBuffer(); if (SUCCEEDED(hr)) { m_fxChain = NEW(CEffectChain(this)); hr = HRFROMP(m_fxChain); } if (SUCCEEDED(hr)) { hr = m_fxChain->Clone(pDSBConfigObj); } if (SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { hr = m_fxChain->AcquireFxResources(); } if (FAILED(hr)) { RELEASE(m_fxChain); m_pDeviceBuffer->m_pSysMemBuffer->FreeFxBuffer(); } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * UserAcquireResources * * Description: * Acquires hardware resources, and reports on FX creation status. * The "User" means this is called only from the app (via dsimp.cpp). * * Arguments: * DWORD [in]: count of FX status flags to be returned. * LPDWORD [out]: pointer to array of FX status flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::UserAcquireResources" HRESULT CDirectSoundSecondaryBuffer::UserAcquireResources(DWORD dwFlags, DWORD dwFxCount, LPDWORD pdwResultCodes) { HRESULT hr = DS_OK; DPF_ENTER(); // Check that buffer is LOCDEFER if(!(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)) { RPF(DPFLVL_ERROR, "AcquireResources() is only valid for buffers created with DSBCAPS_LOCDEFER"); hr = DSERR_INVALIDCALL; } if (SUCCEEDED(hr) && pdwResultCodes && (!HasFX() || dwFxCount != m_fxChain->GetFxCount())) { RPF(DPFLVL_ERROR, "Specified an incorrect effect count"); hr = DSERR_INVALIDPARAM; } if (SUCCEEDED(hr)) hr = AttemptResourceAcquisition(dwFlags); // We need to preserve the return code from AttemptResourceAcquisition, in case it's // DS_INCOMPLETE, so we omit the "hr=" from GetFxStatus (which always succeeds): if (HasFX() && pdwResultCodes) m_fxChain->GetFxStatus(pdwResultCodes); // If successful, prevent this buffer from having its resources stolen before it's played if (SUCCEEDED(hr)) m_fCanStealResources = FALSE; DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetObjectInPath * * Description: * Obtains a given interface on a given effect on this buffer. * * Arguments: * REFGUID [in]: Class ID of the effect that is being searched for, * or GUID_ALL_OBJECTS to search for any effect. * DWORD [in]: Index of the effect, in case there is more than one * effect with this CLSID on this buffer. * REFGUID [in]: IID of the interface requested. The selected effect * will be queried for this interface. * LPVOID * [out]: Receives the interface requested. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetObjectInPath" HRESULT CDirectSoundSecondaryBuffer::GetObjectInPath(REFGUID guidObject, DWORD dwIndex, REFGUID iidInterface, LPVOID *ppObject) { HRESULT hr; DPF_ENTER(); if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFX)) { RPF(DPFLVL_ERROR, "Buffer was not created with DSBCAPS_CTRLFX flag"); hr = DSERR_CONTROLUNAVAIL; } if (!HasFX()) { hr = DSERR_OBJECTNOTFOUND; } else { hr = m_fxChain->GetEffectInterface(guidObject, dwIndex, iidInterface, ppObject); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetInternalCursors * * Description: * This method is used by streamer.cpp and effects.cpp (new in DX8). * It obtains the current play and write cursors from our contained * m_pDeviceBuffer object, and aligns them on sample block boundaries. * * Arguments: * LPDWORD [out]: receives the play position. * LPDWORD [out]: receives the write position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetInternalCursors" HRESULT CDirectSoundSecondaryBuffer::GetInternalCursors(LPDWORD pdwPlay, LPDWORD pdwWrite) { DPF_ENTER(); HRESULT hr = m_pDeviceBuffer->GetCursorPosition(pdwPlay, pdwWrite); // ASSERT(SUCCEEDED(hr)); // Removed this ASSERT because the device will // sometimes mysteriously disappear out from under us - which is a pity, // because we depend utterly on GetCursorPosition() being reliable. if (SUCCEEDED(hr)) { // If our device is emulated, add EMULATION_LATENCY_BOOST ms to the write cursor // FIXME: this code should be in m_pDeviceBuffer->GetCursorPosition() once we've // figured out what's up with cursor reporting on emulation. For now, let's just // avoid regressions! This method is only used by effects.cpp and dssink.cpp... // DISABLED UNTIL DX8.1: // if (pdwWrite && IsEmulated()) // *pdwWrite = PadCursor(*pdwWrite, GetBufferSize(), Format(), EMULATION_LATENCY_BOOST); // OR: // if (IsEmulated()) // { // if (pdwPlay) // *pdwPlay = PadCursor(*pdwPlay, GetBufferSize(), Format(), EMULATION_LATENCY_BOOST); // if (pdwWrite) // *pdwWrite = PadCursor(*pdwWrite, GetBufferSize(), Format(), EMULATION_LATENCY_BOOST); // } // The cursors aren't guaranteed to be on block boundaries - fix them: if (pdwPlay) *pdwPlay = BLOCKALIGN(*pdwPlay, Format()->nBlockAlign); if (pdwWrite) *pdwWrite = BLOCKALIGN(*pdwWrite, Format()->nBlockAlign); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetCurrentSlice * * Description: * Obtains the part of the audio buffer that is being processed * during the streaming thread's current pass. * * The "slice" terminology is whimsical but makes it easy to search * for the slice-handling code in an editor. It's better than yet * another overloaded usage of "buffer". * * Arguments: * LPDWORD [out]: receives buffer slice start (as byte offset). * LPDWORD [out]: receives buffer slice end (as byte offset). * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::GetCurrentSlice" void CDirectSoundSecondaryBuffer::GetCurrentSlice(LPDWORD pdwSliceBegin, LPDWORD pdwSliceEnd) { DPF_ENTER(); // Make sure the slice endpoints have been initialized and are within range if (!(m_dsbd.dwFlags & DSBCAPS_SINKIN)) { // NB: Sink buffers can be uninitialized if the sink is starting, // or if it decided not to advance its play position on this run. ASSERT(m_dwSliceBegin != MAX_DWORD && m_dwSliceEnd != MAX_DWORD); ASSERT(m_dwSliceBegin < GetBufferSize() && m_dwSliceEnd < GetBufferSize()); } if (pdwSliceBegin) *pdwSliceBegin = m_dwSliceBegin; if (pdwSliceEnd) *pdwSliceEnd = m_dwSliceEnd; DPF_LEAVE_VOID(); } /*************************************************************************** * * SetCurrentSlice * * Description: * Establishes the part of this audio buffer that is being processed * during the streaming thread's current pass. * * Arguments: * DWORD [in]: Slice start (as byte offset from audio buffer start), * or the special argument CURRENT_WRITE_POS which means * "make the slice start at our current write position". * DWORD [in]: Slice size in bytes. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetCurrentSlice" void CDirectSoundSecondaryBuffer::SetCurrentSlice(DWORD dwSliceBegin, DWORD dwBytes) { HRESULT hr = DS_OK; DPF_ENTER(); DPF_TIMING(DPFLVL_MOREINFO, "begin=%lu size=%lu (%s%s%sbuffer%s at 0x%p)", dwSliceBegin, dwBytes, m_dsbd.dwFlags & DSBCAPS_MIXIN ? TEXT("MIXIN ") : TEXT(""), m_dsbd.dwFlags & DSBCAPS_SINKIN ? TEXT("SINKIN ") : TEXT(""), !(m_dsbd.dwFlags & (DSBCAPS_MIXIN|DSBCAPS_SINKIN)) ? TEXT("regular ") : TEXT(""), HasFX() ? TEXT(" w/effects") : TEXT(""), this); ASSERT(dwBytes > 0 && dwBytes < GetBufferSize()); if (dwSliceBegin == CURRENT_WRITE_POS) { hr = GetInternalCursors(NULL, &dwSliceBegin); if (SUCCEEDED(hr)) { m_dwSliceBegin = PadCursor(dwSliceBegin, GetBufferSize(), Format(), INITIAL_WRITEAHEAD); DPF_TIMING(DPFLVL_MOREINFO, "CURRENT_WRITE_POS is %lu; setting slice start to %lu", dwSliceBegin, m_dwSliceBegin); } else // GetInternalCursors failed; stop FX processing and force the { // streaming thread to reset our slice next time it wakes up m_playState = Stopped; m_dwSliceBegin = m_dwSliceEnd = MAX_DWORD; } } else // dwSliceBegin != CURRENT_WRITE_POS { // Normal case: set the new slice begin position explicitly m_dwSliceBegin = dwSliceBegin; } if (SUCCEEDED(hr)) { ASSERT(m_dwSliceBegin < GetBufferSize()); if (HasFX() && m_dwSliceBegin != m_dwSliceEnd) // Discontinuous buffer slices m_fxChain->FxDiscontinuity(); // Inform effects of break in their input data m_dwSliceEnd = (m_dwSliceBegin + dwBytes) % GetBufferSize(); // If this is a MIXIN buffer, write silence to the new slice if (m_dsbd.dwFlags & DSBCAPS_MIXIN) m_pDeviceBuffer->m_pSysMemBuffer->WriteSilence(m_dsbd.lpwfxFormat->wBitsPerSample, m_dwSliceBegin, m_dwSliceEnd); } DPF_LEAVE_VOID(); } /*************************************************************************** * * MoveCurrentSlice * * Description: * Shifts forward the audio buffer slice that is being processed. * * Arguments: * DWORD [in]: Size in bytes for the new buffer slice. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::MoveCurrentSlice" void CDirectSoundSecondaryBuffer::MoveCurrentSlice(DWORD dwBytes) { DPF_ENTER(); DPF_TIMING(DPFLVL_MOREINFO, "dwBytes=%lu (%s%s%sbuffer%s at 0x%p)", dwBytes, m_dsbd.dwFlags & DSBCAPS_MIXIN ? TEXT("MIXIN ") : TEXT(""), m_dsbd.dwFlags & DSBCAPS_SINKIN ? TEXT("SINKIN ") : TEXT(""), !(m_dsbd.dwFlags & (DSBCAPS_MIXIN|DSBCAPS_SINKIN)) ? TEXT("regular ") : TEXT(""), HasFX() ? TEXT(" w/effects") : TEXT(""), this); ASSERT(dwBytes > 0 && dwBytes < GetBufferSize()); // Slide the current slice forwards and make it dwBytes wide if (m_dwSliceBegin == MAX_DWORD) // FIXME: for debugging only { ASSERT(!"Unset processing slice detected"); m_playState = Stopped; m_dwSliceBegin = m_dwSliceEnd = MAX_DWORD; // FIXME: this code can disappear once all bugs are ironed out } else { m_dwSliceBegin = m_dwSliceEnd; } ASSERT(m_dwSliceBegin < GetBufferSize()); m_dwSliceEnd = (m_dwSliceBegin + dwBytes) % GetBufferSize(); // If this is a MIXIN buffer, write silence to the new slice if (m_dsbd.dwFlags & DSBCAPS_MIXIN) m_pDeviceBuffer->m_pSysMemBuffer->WriteSilence(m_dsbd.lpwfxFormat->wBitsPerSample, m_dwSliceBegin, m_dwSliceEnd); DPF_LEAVE_VOID(); } /*************************************************************************** * * DirectLock * * Description: * An abbreviation for the frequent operation of locking a region of * our contained audio buffer. * * Arguments: * DWORD [in]: Byte offset to where the lock begins in the buffer. * DWORD [in]: Size, in bytes, of the portion of the buffer to lock. * LPVOID* [out]: Returns the first part of the locked region. * LPDWORD [out]: Returns the size in bytes of the first part. * LPVOID* [out]: Returns the second part of the locked region. * LPDWORD [out]: Returns the size in bytes of the second part. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::DirectLock" HRESULT CDirectSoundSecondaryBuffer::DirectLock(DWORD dwPosition, DWORD dwSize, LPVOID* ppvPtr1, LPDWORD pdwSize1, LPVOID* ppvPtr2, LPDWORD pdwSize2) { DPF_ENTER(); ASSERT(m_pDeviceBuffer != NULL); HRESULT hr = m_pDeviceBuffer->CRenderWaveBuffer::Lock(dwPosition, dwSize, ppvPtr1, pdwSize1, ppvPtr2, pdwSize2); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * DirectUnlock * * Description: * An abbreviation for the frequent operation of unlocking a region of * our contained audio buffer. * * Arguments: * LPVOID [in]: pointer to the first block. * DWORD [in]: size of the first block. * LPVOID [in]: pointer to the second block. * DWORD [in]: size of the second block. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::DirectUnlock" HRESULT CDirectSoundSecondaryBuffer::DirectUnlock(LPVOID pvPtr1, DWORD dwSize1, LPVOID pvPtr2, DWORD dwSize2) { DPF_ENTER(); ASSERT(m_pDeviceBuffer != NULL); HRESULT hr = m_pDeviceBuffer->CRenderWaveBuffer::Unlock(pvPtr1, dwSize1, pvPtr2, dwSize2); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * FindSendLoop * * Description: * Auxiliary function used in effects.cpp to detect send loops. * Returns DSERR_SENDLOOP if a send effect pointing to this buffer * is detected anywhere in the send graph rooted at pCurBuffer. * * Arguments: * CDirectSoundSecondaryBuffer* [in]: Current buffer in graph traversal. * * Returns: * HRESULT: DirectSound/COM result code; DSERR_SENDLOOP if a send loop * is found, otherwise DS_OK. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::FindSendLoop" HRESULT CDirectSoundSecondaryBuffer::FindSendLoop(CDirectSoundSecondaryBuffer* pCurBuffer) { HRESULT hr = DS_OK; DPF_ENTER(); CHECK_WRITE_PTR(pCurBuffer); if (pCurBuffer == this) { RPF(DPFLVL_ERROR, "Send loop detected from buffer at 0x%p to itself", this); hr = DSERR_SENDLOOP; } else if (pCurBuffer->HasFX()) { // Buffer has effects - look for send effects and call ourself recursively. for (CNode<CEffect*>* pFxNode = pCurBuffer->m_fxChain->m_fxList.GetListHead(); pFxNode && SUCCEEDED(hr); pFxNode = pFxNode->m_pNext) { CDirectSoundSecondaryBuffer* pDstBuffer = pFxNode->m_data->GetDestBuffer(); if (pDstBuffer) hr = FindSendLoop(pDstBuffer); } } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * CalculateOffset * * Description: * Given a CDirectSoundSecondaryBuffer and a byte offset into that * buffer, calculates the "corresponding" byte offset in this buffer * such that both buffers' play cursors will reach their respective * offsets at the same time. To do this we need to know the exact * difference between the buffers' play positions, which we obtain * using a voting heuristic, since our underlying driver models * (VxD, WDM) don't support this operation directly. * * Arguments: * CDirectSoundSecondaryBuffer* [in]: Buffer to get offset from. * DWORD [in]: Position in the buffer to which to synchronize. * DWORD* [out]: Returns the corresponding position in this buffer. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::CalculateOffset" // Our compiler doesn't allow this POSOFFSET type to be local to // the function below, because it is used as a template argument. struct POSOFFSET {LONG offset; int count; POSOFFSET(LONG _o =0) {offset=_o; count=1;}}; HRESULT CDirectSoundSecondaryBuffer::CalculateOffset(CDirectSoundSecondaryBuffer* pDsBuffer, DWORD dwTargetPos, DWORD* pdwSyncPos) { const int nMaxAttempts = 7; // Getting the cursor positions takes a surprisingly long time const int nQuorum = 3; // How many "votes" are required to determine the offset // Note: these arbitrary constants were found to result in an accurate // offset calculation "almost always". An out-of-sync send is very easy // to hear (it sound phasy and flangy); if we ever detect this problem in // testing, this code should be revisited. // Sanity checks CHECK_WRITE_PTR(pDsBuffer); CHECK_WRITE_PTR(pdwSyncPos); ASSERT(dwTargetPos < pDsBuffer->GetBufferSize()); CList<POSOFFSET> lstOffsets; // List of cursor offsets found CNode<POSOFFSET>* pCheckNode; // Used to check AddNoteToList failures DWORD dwFirstPos1 = 0, dwFirstPos2 = 0; // First cursor positions found DWORD dwPos1, dwPos2; // Current cursor positions found LONG lOffset; // Current offset BOOL fOffsetFound = FALSE; // Found the best offset? int nOurBlockSize = Format()->nBlockAlign; // Used for brevity below int nBufferBlockSize = pDsBuffer->Format()->nBlockAlign; // Ditto HRESULT hr = DS_OK; DPF_ENTER(); // Uncomment this to see how long this function takes to run // DWORD dwTimeBefore = timeGetTime(); for (int i=0; i<nMaxAttempts && SUCCEEDED(hr); ++i) { hr = GetInternalCursors(&dwPos1, NULL); if (SUCCEEDED(hr)) hr = pDsBuffer->GetInternalCursors(&dwPos2, NULL); if (SUCCEEDED(hr)) { // Save the first buffer positions found if (i == 0) dwFirstPos1 = dwPos1, dwFirstPos2 = dwPos2; // If we detect a cursor wraparound, start all over again [??] if (dwPos1 < dwFirstPos1 || dwPos2 < dwFirstPos2) { #ifdef ENABLE_SENDS // Debug output for later debugging for (int j=0; j<5; ++j) { DPF(DPFLVL_INFO, "Take %d: dwPos1=%d < dwFirstPos1=%d || dwPos2=%d < dwFirstPos2=%d", i, dwPos1, dwFirstPos1, dwPos2, dwFirstPos2); Sleep(10); GetInternalCursors(&dwPos1, NULL); pDsBuffer->GetInternalCursors(&dwPos2, NULL); } #endif break; } // Convert dwPos2 from pDsBuffer's sample block units into ours dwPos2 = dwPos2 * nOurBlockSize / nBufferBlockSize; LONG lNewOffset = dwPos2 - dwPos1; DPF_TIMING(DPFLVL_INFO, "Play offset #%d = %ld", i, lNewOffset); for (CNode<POSOFFSET>* pOff = lstOffsets.GetListHead(); pOff; pOff = pOff->m_pNext) if (pOff->m_data.offset >= lNewOffset - nOurBlockSize && pOff->m_data.offset <= lNewOffset + nOurBlockSize) { // I.e. if the offsets are equal or only off by 1 sample block ++pOff->m_data.count; break; } if (pOff == NULL) // A new offset was found - add it to the list { pCheckNode = lstOffsets.AddNodeToList(POSOFFSET(lNewOffset)); ASSERT(pCheckNode != NULL); } else if (pOff->m_data.count == nQuorum) // We have a winner! { lOffset = pOff->m_data.offset; fOffsetFound = TRUE; #ifdef ENABLE_SENDS // Debug output for later debugging DPF(DPFLVL_INFO, "QUORUM REACHED"); #endif break; } } } if (SUCCEEDED(hr) && !fOffsetFound) // Didn't get enough votes for any one offset { // Just pick the one with the most "votes" int nBestSoFar = 0; for (CNode<POSOFFSET>* pOff = lstOffsets.GetListHead(); pOff; pOff = pOff->m_pNext) if (pOff->m_data.count > nBestSoFar) { lOffset = pOff->m_data.offset; nBestSoFar = pOff->m_data.count; } ASSERT(nBestSoFar > 0); } if (SUCCEEDED(hr)) { // If dwTargetPos is smaller than the play position on pDsBuffer, it must have // wrapped around, so we put it back where it would be if it hadn't wrapped if (dwTargetPos < dwFirstPos2) dwTargetPos += pDsBuffer->GetBufferSize(); // Convert dwTargetPos from pDsBuffer's sample block units into ours dwTargetPos = dwTargetPos * nOurBlockSize / nBufferBlockSize; #ifdef DEBUG_TIMING if (dwTargetPos - dwFirstPos2*nOurBlockSize/nBufferBlockSize > GetBufferSize()) ASSERT(!"Sync buffer's target and play positions are further apart than our buffer size"); #endif // And finally... *pdwSyncPos = dwTargetPos - lOffset; if (*pdwSyncPos >= GetBufferSize()) { *pdwSyncPos -= GetBufferSize(); ASSERT(*pdwSyncPos < GetBufferSize()); } DPF_TIMING(DPFLVL_INFO, "Target buffer size=%lu, play pos=%lu, target pos=%lu", pDsBuffer->GetBufferSize(), dwFirstPos2, dwTargetPos); DPF_TIMING(DPFLVL_INFO, "Source buffer size=%lu, play pos=%lu, sync pos=%lu", GetBufferSize(), dwFirstPos1, *pdwSyncPos); } // Uncomment this to see how long this function takes to run // DWORD dwTimeAfter = timeGetTime(); // DPF(DPFLVL_MOREINFO, "Calculations took %ld ms", dwTimeAfter-dwTimeBefore); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SynchronizeToBuffer * * Description: * Synchronizes this buffer's current processing slice to that of the * buffer passed in as an argument. * * Arguments: * CDirectSoundSecondaryBuffer* [in]: Buffer to synchronize to. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SynchronizeToBuffer" void CDirectSoundSecondaryBuffer::SynchronizeToBuffer(CDirectSoundSecondaryBuffer* pSyncBuffer) { DPF_ENTER(); DWORD dwSliceBegin, dwSliceEnd, dwSliceSize; pSyncBuffer->GetCurrentSlice(&dwSliceBegin, &dwSliceEnd); dwSliceSize = DISTANCE(dwSliceBegin, dwSliceEnd, pSyncBuffer->GetBufferSize()); // Convert dwSliceSize from pSyncBuffer's sample block units into ours dwSliceSize = dwSliceSize * Format()->nBlockAlign / pSyncBuffer->Format()->nBlockAlign; // Convert dwSliceBegin into an offset into our buffer (taking into // account the relative play cursors of our buffer and pSyncBuffer) CalculateOffset(pSyncBuffer, dwSliceBegin, &dwSliceBegin); // Establish our new processing slice SetCurrentSlice(dwSliceBegin, dwSliceSize); // No point propagating an error to our caller, which is the streaming thread; // CalculateOffset() can only fail if GetCurrentPosition() fails, in which case // everything will come to a grinding halt soon enough anyway. DPF_LEAVE_VOID(); } /*************************************************************************** * * UpdatePlayState * * Description: * Auxiliary function used by the streaming thread to update this * buffer's playing state. This is called once per buffer when the * effects/streaming thread begins a processing pass; then for the * rest of the pass, individual effects can query our state using * GetPlayState(), without needing to call GetState() repeatedly * on our device buffer. * * Arguments: * (void) * * Returns: * (void) - If GetState() fails, we simply set our state to FALSE. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::UpdatePlayState" DSPLAYSTATE CDirectSoundSecondaryBuffer::UpdatePlayState(void) { DSPLAYSTATE oldPlayState = m_playState; DWORD dwState; DPF_ENTER(); if (SUCCEEDED(m_pDeviceBuffer->GetState(&dwState))) { if (dwState & VAD_BUFFERSTATE_STARTED) if (m_playState <= Playing) m_playState = Playing; else m_playState = Starting; else if (m_playState >= Stopping) m_playState = Stopped; else m_playState = Stopping; } else { DPF(DPFLVL_ERROR, "Cataclysmic GetState() failure"); m_playState = Stopped; } if (oldPlayState != m_playState) { static TCHAR* szStates[] = {TEXT("Starting"), TEXT("Playing"), TEXT("Stopping"), TEXT("Stopped")}; DPF(DPFLVL_MOREINFO, "Buffer at 0x%p went from %s to %s", this, szStates[oldPlayState], szStates[m_playState]); } DPF_LEAVE(m_playState); return m_playState; } /*************************************************************************** * * SetInitialSlice * * Description: * Auxiliary function used by the streaming thread to establish an * initial processing slice for this buffer when it starts playing. * We try to synchronize with an active buffer that is sending to us, * and if none are available we start at our current write cursor. * * Arguments: * REFERENCE_TIME [in]: Size of processing slice to be established. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetInitialSlice" void CDirectSoundSecondaryBuffer::SetInitialSlice(REFERENCE_TIME rtSliceSize) { DPF_ENTER(); if (GetPlayState() == Starting && !(GetBufferType() & DSBCAPS_SINKIN)) { CNode<CDirectSoundSecondaryBuffer*>* pSender; for (pSender = m_lstSenders.GetListHead(); pSender; pSender = pSender->m_pNext) if (pSender->m_data->IsPlaying()) { // Found an active buffer sending to us DPF_TIMING(DPFLVL_INFO, "Synchronizing MIXIN buffer at 0x%p with send buffer at 0x%p", this, pSender->m_data); SynchronizeToBuffer(pSender->m_data); break; } if (pSender == NULL) { DPF_TIMING(DPFLVL_INFO, "No active buffers found sending to MIXIN buffer at 0x%p", this); SetCurrentSlice(CURRENT_WRITE_POS, RefTimeToBytes(rtSliceSize, Format())); } } DPF_LEAVE_VOID(); } #ifdef FUTURE_MULTIPAN_SUPPORT /*************************************************************************** * * SetChannelVolume * * Description: * Sets the volume on a set of output channels for a given mono buffer. * * Arguments: * [MISSING] * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBuffer::SetChannelVolume" HRESULT CDirectSoundSecondaryBuffer::SetChannelVolume(DWORD dwChannelCount, LPDWORD pdwChannels, LPLONG plVolumes) { HRESULT hr = DS_OK; BOOL fChanged = FALSE; DPF_ENTER(); // Check access rights if(!(m_dsbd.dwFlags & DSBCAPS_CTRLCHANNELVOLUME)) { RPF(DPFLVL_ERROR, "Buffer does not have CTRLCHANNELVOLUME"); hr = DSERR_CONTROLUNAVAIL; } // Check if channel levels have changed if(SUCCEEDED(hr)) { if (dwChannelCount != m_dwChannelCount) fChanged = TRUE; else for (DWORD i=0; i<dwChannelCount && !fChanged; ++i) if (pdwChannels[i] != m_pdwChannels[i] || plVolumes[i] != m_plChannelVolumes[i]) fChanged = TRUE; } // Set channel volumes if they've changed if(SUCCEEDED(hr) && fChanged) { hr = m_pDeviceBuffer->SetChannelAttenuations(m_lVolume, dwChannelCount, pdwChannels, plVolumes); // Update our local copy if successful if(SUCCEEDED(hr)) { MEMFREE(m_pdwChannels); MEMFREE(m_plChannelVolumes); m_pdwChannels = MEMALLOC_A(DWORD, dwChannelCount); hr = HRFROMP(m_pdwChannels); } if (SUCCEEDED(hr)) { m_plChannelVolumes = MEMALLOC_A(LONG, dwChannelCount); hr = HRFROMP(m_plChannelVolumes); } if (SUCCEEDED(hr)) { CopyMemory(m_pdwChannels, pdwChannels, sizeof(DWORD) * dwChannelCount); CopyMemory(m_plChannelVolumes, plVolumes, sizeof(LONG) * dwChannelCount); m_dwChannelCount = dwChannelCount; } } DPF_LEAVE_HRESULT(hr); return hr; } #endif // FUTURE_MULTIPAN_SUPPORT /*************************************************************************** * * CDirectSound3dListener * * Description: * Object constructor. * * Arguments: * CUnknown * [in]: parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::CDirectSound3dListener" CDirectSound3dListener::CDirectSound3dListener(CDirectSoundPrimaryBuffer *pParent) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSound3dListener); // Initialize defaults m_pParent = pParent; m_pImpDirectSound3dListener = NULL; m_pDevice3dListener = NULL; m_hrInit = DSERR_UNINITIALIZED; DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSound3dListener * * Description: * Object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::~CDirectSound3dListener" CDirectSound3dListener::~CDirectSound3dListener(void) { DPF_ENTER(); DPF_DESTRUCT(CDirectSound3dListener); // Free 3D listener object RELEASE(m_pDevice3dListener); // Free interface(s) DELETE(m_pImpDirectSound3dListener); DPF_LEAVE_VOID(); } /*************************************************************************** * * Initialize * * Description: * Initializes the object. If this function fails, the object should * be immediately deleted. * * Arguments: * CPrimaryRenderWaveBuffer * [in]: device buffer. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::Initialize" HRESULT CDirectSound3dListener::Initialize(CPrimaryRenderWaveBuffer *pDeviceBuffer) { HRESULT hr; DPF_ENTER(); // Create the device 3D listener hr = pDeviceBuffer->Create3dListener(&m_pDevice3dListener); // Create the 3D listener interfaces if(SUCCEEDED(hr)) { hr = CreateAndRegisterInterface(m_pParent, IID_IDirectSound3DListener, this, &m_pImpDirectSound3dListener); } // Success if(SUCCEEDED(hr)) { m_hrInit = DS_OK; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetAllParameters * * Description: * Gets all listener properties. * * Arguments: * LPDS3DLISTENER [out]: receives properties. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetAllParameters" HRESULT CDirectSound3dListener::GetAllParameters(LPDS3DLISTENER pParam) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetAllParameters(pParam); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetDistanceFactor * * Description: * Gets the world's distance factor. * * Arguments: * D3DVALUE* [out]: receives distance factor. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetDistanceFactor" HRESULT CDirectSound3dListener::GetDistanceFactor(D3DVALUE* pflDistanceFactor) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetDistanceFactor(pflDistanceFactor); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetDopplerFactor * * Description: * Gets the world's doppler factor. * * Arguments: * D3DVALUE* [out]: receives doppler factor. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetDopplerFactor" HRESULT CDirectSound3dListener::GetDopplerFactor(D3DVALUE* pflDopplerFactor) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetDopplerFactor(pflDopplerFactor); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetOrientation * * Description: * Gets the listener's orientation. * * Arguments: * D3DVECTOR* [out]: receives front orientation. * D3DVECTOR* [out]: receives top orientation. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetOrientation" HRESULT CDirectSound3dListener::GetOrientation(D3DVECTOR* pvrOrientationFront, D3DVECTOR* pvrOrientationTop) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetOrientation(pvrOrientationFront, pvrOrientationTop); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetPosition * * Description: * Gets the listener's position. * * Arguments: * D3DVECTOR* [out]: receives position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetPosition" HRESULT CDirectSound3dListener::GetPosition(D3DVECTOR* pvrPosition) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetPosition(pvrPosition); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetRolloffFactor * * Description: * Gets the world's rolloff factor. * * Arguments: * D3DVALUE* [out]: receives rolloff factor. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetRolloffFactor" HRESULT CDirectSound3dListener::GetRolloffFactor(D3DVALUE* pflRolloffFactor) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetRolloffFactor(pflRolloffFactor); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetVelocity * * Description: * Gets the listener's velocity. * * Arguments: * D3DVECTOR* [out]: receives velocity. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::GetVelocity" HRESULT CDirectSound3dListener::GetVelocity(D3DVECTOR* pvrVelocity) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->GetVelocity(pvrVelocity); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetAllParameters * * Description: * Sets all listener properties. * * Arguments: * LPDS3DLISTENER [in]: properties. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetAllParameters" HRESULT CDirectSound3dListener::SetAllParameters(LPCDS3DLISTENER pParam, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetAllParameters(pParam, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetDistanceFactor * * Description: * Sets the world's distance factor. * * Arguments: * D3DVALUE [in]: distance factor. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetDistanceFactor" HRESULT CDirectSound3dListener::SetDistanceFactor(D3DVALUE flDistanceFactor, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetDistanceFactor(flDistanceFactor, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetDopplerFactor * * Description: * Sets the world's Doppler factor. * * Arguments: * D3DVALUE [in]: Doppler factor. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetDopplerFactor" HRESULT CDirectSound3dListener::SetDopplerFactor(D3DVALUE flDopplerFactor, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetDopplerFactor(flDopplerFactor, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetOrientation * * Description: * Sets the listener's orientation. * * Arguments: * REFD3DVECTOR [in]: front orientation. * REFD3DVECTOR [in]: top orientation. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetOrientation" HRESULT CDirectSound3dListener::SetOrientation(REFD3DVECTOR vrOrientationFront, REFD3DVECTOR vrOrientationTop, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetOrientation(vrOrientationFront, vrOrientationTop, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetPosition * * Description: * Sets the listener's position. * * Arguments: * REFD3DVECTOR [in]: position. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetPosition" HRESULT CDirectSound3dListener::SetPosition(REFD3DVECTOR vrPosition, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetPosition(vrPosition, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetRolloffFactor * * Description: * Sets the world's rolloff factor. * * Arguments: * D3DVALUE [in]: rolloff factor. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetRolloffFactor" HRESULT CDirectSound3dListener::SetRolloffFactor(D3DVALUE flRolloffFactor, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetRolloffFactor(flRolloffFactor, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetVelocity * * Description: * Sets the listener's velocity. * * Arguments: * REFD3DVECTOR [in]: velocity. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetVelocity" HRESULT CDirectSound3dListener::SetVelocity(REFD3DVECTOR vrVelocity, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetVelocity(vrVelocity, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * CommitDeferredSettings * * Description: * Commits deferred settings. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::CommitDeferredSettings" HRESULT CDirectSound3dListener::CommitDeferredSettings(void) { HRESULT hr; DPF_ENTER(); // Commit all listener settings hr = m_pDevice3dListener->CommitDeferred(); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetSpeakerConfig * * Description: * Sets device speaker configuration. * * Arguments: * DWORD [in]: speaker configuration. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dListener::SetSpeakerConfig" HRESULT CDirectSound3dListener::SetSpeakerConfig(DWORD dwSpeakerConfig) { HRESULT hr; DPF_ENTER(); hr = m_pDevice3dListener->SetSpeakerConfig(dwSpeakerConfig); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * CDirectSound3dBuffer * * Description: * Object constructor. * * Arguments: * CUnknown * [in]: parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::CDirectSound3dBuffer" CDirectSound3dBuffer::CDirectSound3dBuffer(CDirectSoundSecondaryBuffer *pParent) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSound3dBuffer); // Initialize defaults m_pParent = pParent; m_pImpDirectSound3dBuffer = NULL; m_pWrapper3dObject = NULL; m_pDevice3dObject = NULL; m_hrInit = DSERR_UNINITIALIZED; DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSound3dBuffer * * Description: * Object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::~CDirectSound3dBuffer" CDirectSound3dBuffer::~CDirectSound3dBuffer(void) { DPF_ENTER(); DPF_DESTRUCT(CDirectSound3dBuffer); // Free 3D buffer objects RELEASE(m_pWrapper3dObject); RELEASE(m_pDevice3dObject); // Free all interfaces DELETE(m_pImpDirectSound3dBuffer); DPF_LEAVE_VOID(); } /*************************************************************************** * * Initialize * * Description: * Initializes a buffer object. If this function fails, the object * should be immediately deleted. * * Arguments: * REFGUID [in]: 3D algorithm identifier. * DWORD [in]: buffer creation flags. * DWORD [in]: buffer frequency. * CDirectSound3dListener * [in]: listener object. * CDirectSound3dBuffer * [in]: source object to duplicate from. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::Initialize" HRESULT CDirectSound3dBuffer::Initialize(REFGUID guid3dAlgorithm, DWORD dwFlags, DWORD dwFrequency, CDirectSound3dListener *pListener, CDirectSound3dBuffer *pSource) { const BOOL fMute3dAtMaxDistance = MAKEBOOL(dwFlags & DSBCAPS_MUTE3DATMAXDISTANCE); const BOOL fDopplerEnabled = !MAKEBOOL((dwFlags & DSBCAPS_CTRLFX) && !(dwFlags & DSBCAPS_SINKIN)); DS3DBUFFER param; HRESULT hr; DPF_ENTER(); // Create the wrapper 3D object m_pWrapper3dObject = NEW(CWrapper3dObject(pListener->m_pDevice3dListener, guid3dAlgorithm, fMute3dAtMaxDistance, fDopplerEnabled, dwFrequency)); hr = HRFROMP(m_pWrapper3dObject); // Copy the source buffer's 3D properties if(SUCCEEDED(hr) && pSource) { InitStruct(&param, sizeof(param)); hr = pSource->GetAllParameters(&param); if(SUCCEEDED(hr)) { hr = SetAllParameters(&param, 0); } } // Register the 3D buffer interfaces if(SUCCEEDED(hr)) { hr = CreateAndRegisterInterface(m_pParent, IID_IDirectSound3DBuffer, this, &m_pImpDirectSound3dBuffer); } if(SUCCEEDED(hr)) { hr = m_pParent->RegisterInterface(IID_IDirectSound3DBufferPrivate, m_pImpDirectSound3dBuffer, (IDirectSound3DBufferPrivate*)m_pImpDirectSound3dBuffer); } // Success if(SUCCEEDED(hr)) { m_hrInit = DS_OK; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * AcquireResources * * Description: * Acquires hardware resources. * * Arguments: * CSecondaryRenderWaveBuffer * [in]: device buffer. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::AcquireResources" HRESULT CDirectSound3dBuffer::AcquireResources(CSecondaryRenderWaveBuffer *pDeviceBuffer) { HRESULT hr; DPF_ENTER(); // Create the device 3D object hr = pDeviceBuffer->Create3dObject(m_pWrapper3dObject->GetListener(), &m_pDevice3dObject); if(SUCCEEDED(hr)) { hr = m_pWrapper3dObject->SetObjectPointer(m_pDevice3dObject); } if(SUCCEEDED(hr)) { DPF(DPFLVL_MOREINFO, "3D buffer at 0x%p has acquired resources at 0x%p", this, m_pDevice3dObject); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * FreeResources * * Description: * Frees hardware resources. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::FreeResources" HRESULT CDirectSound3dBuffer::FreeResources(void) { HRESULT hr; DPF_ENTER(); // Free the device 3D object hr = m_pWrapper3dObject->SetObjectPointer(NULL); if(SUCCEEDED(hr)) { RELEASE(m_pDevice3dObject); DPF(DPFLVL_MOREINFO, "3D buffer at 0x%p has freed its resources", this); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetAttenuation * * Description: * Sets the attenuation for a given buffer. This function is * overridden in the 3D buffer because the 3D object may need * notification. * * Arguments: * PDSVOLUMEPAN [in]: new attenuation. * LPBOOL [out]: receives TRUE if the device buffer should be notified * of the change. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetAttenuation" HRESULT CDirectSound3dBuffer::SetAttenuation(PDSVOLUMEPAN pdsvp, LPBOOL pfContinue) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetAttenuation(pdsvp, pfContinue); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetFrequency * * Description: * Sets the frequency for a given buffer. This function is * overridden in the 3D buffer because the 3D object may need * notification. * * Arguments: * DWORD [in]: new frequency. * LPBOOL [out]: receives TRUE if the device buffer should be notified * of the change. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetFrequency" HRESULT CDirectSound3dBuffer::SetFrequency(DWORD dwFrequency, LPBOOL pfContinue) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetFrequency(dwFrequency, pfContinue); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetMute * * Description: * Sets the mute status for a given buffer. This function is * overridden in the 3D buffer because the 3D object may need * notification. * * Arguments: * BOOL [in]: new mute status. * LPBOOL [out]: receives TRUE if the device buffer should be notified * of the change. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetMute" HRESULT CDirectSound3dBuffer::SetMute(BOOL fMute, LPBOOL pfContinue) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetMute(fMute, pfContinue); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetAllParameters * * Description: * Retrieves all 3D properties for the buffer. * * Arguments: * LPDS3DBUFFER [out]: recieves properties. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetAllParameters" HRESULT CDirectSound3dBuffer::GetAllParameters(LPDS3DBUFFER pParam) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetAllParameters(pParam); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetConeAngles * * Description: * Gets inside and outside cone angles. * * Arguments: * LPDWORD [out]: receives inside cone angle. * LPDWORD [out]: receives outside cone angle. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetConeAngles" HRESULT CDirectSound3dBuffer::GetConeAngles(LPDWORD pdwInside, LPDWORD pdwOutside) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetConeAngles(pdwInside, pdwOutside); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetConeOrientation * * Description: * Gets cone orienation. * * Arguments: * D3DVECTOR* [out]: receives cone orientation. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetConeOrientation" HRESULT CDirectSound3dBuffer::GetConeOrientation(D3DVECTOR* pvrConeOrientation) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetConeOrientation(pvrConeOrientation); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetConeOutsideVolume * * Description: * Gets cone orienation. * * Arguments: * LPLONG [out]: receives volume. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetConeOutsideVolume" HRESULT CDirectSound3dBuffer::GetConeOutsideVolume(LPLONG plVolume) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetConeOutsideVolume(plVolume); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetMaxDistance * * Description: * Gets the object's maximum distance from the listener. * * Arguments: * D3DVALUE* [out]: receives max distance. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetMaxDistance" HRESULT CDirectSound3dBuffer::GetMaxDistance(D3DVALUE* pflMaxDistance) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetMaxDistance(pflMaxDistance); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetMinDistance * * Description: * Gets the object's minimim distance from the listener. * * Arguments: * D3DVALUE* [out]: receives min distance. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetMinDistance" HRESULT CDirectSound3dBuffer::GetMinDistance(D3DVALUE* pflMinDistance) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetMinDistance(pflMinDistance); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetMode * * Description: * Gets the object's mode. * * Arguments: * LPDWORD [out]: receives mode. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetMode" HRESULT CDirectSound3dBuffer::GetMode(LPDWORD pdwMode) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetMode(pdwMode); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetPosition * * Description: * Gets the object's position. * * Arguments: * D3DVECTOR* [out]: receives position. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetPosition" HRESULT CDirectSound3dBuffer::GetPosition(D3DVECTOR* pvrPosition) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetPosition(pvrPosition); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetVelocity * * Description: * Gets the object's velocity. * * Arguments: * D3DVECTOR* [out]: receives velocity. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetVelocity" HRESULT CDirectSound3dBuffer::GetVelocity(D3DVECTOR* pvrVelocity) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->GetVelocity(pvrVelocity); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetAllParameters * * Description: * Sets all object properties. * * Arguments: * LPDS3DBUFFER [in]: object parameters. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetAllParameters" HRESULT CDirectSound3dBuffer::SetAllParameters(LPCDS3DBUFFER pParam, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetAllParameters(pParam, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetConeAngles * * Description: * Sets the sound cone's angles. * * Arguments: * DWORD [in]: inside angle. * DWORD [in]: outside angle. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetConeAngles" HRESULT CDirectSound3dBuffer::SetConeAngles(DWORD dwInside, DWORD dwOutside, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetConeAngles(dwInside, dwOutside, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetConeOrientation * * Description: * Sets the sound cone's orientation. * * Arguments: * REFD3DVECTOR [in]: orientation. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetConeOrientation" HRESULT CDirectSound3dBuffer::SetConeOrientation(REFD3DVECTOR vrOrientation, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetConeOrientation(vrOrientation, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetConeOutsideVolume * * Description: * Sets the sound cone's outside volume. * * Arguments: * LONG [in]: volume. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetConeOutsideVolume" HRESULT CDirectSound3dBuffer::SetConeOutsideVolume(LONG lVolume, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetConeOutsideVolume(lVolume, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetMaxDistance * * Description: * Sets the objects maximum distance from the listener. * * Arguments: * D3DVALUE [in]: maximum distance. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetMaxDistance" HRESULT CDirectSound3dBuffer::SetMaxDistance(D3DVALUE flMaxDistance, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetMaxDistance(flMaxDistance, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetMinDistance * * Description: * Sets the objects minimum distance from the listener. * * Arguments: * D3DVALUE [in]: minimum distance. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetMinDistance" HRESULT CDirectSound3dBuffer::SetMinDistance(D3DVALUE flMinDistance, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetMinDistance(flMinDistance, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetMode * * Description: * Sets the objects mode. * * Arguments: * DWORD [in]: mode. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetMode" HRESULT CDirectSound3dBuffer::SetMode(DWORD dwMode, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetMode(dwMode, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetPosition * * Description: * Sets the objects position. * * Arguments: * REFD3DVECTOR [in]: position. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetPosition" HRESULT CDirectSound3dBuffer::SetPosition(REFD3DVECTOR vrPosition, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetPosition(vrPosition, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetVelocity * * Description: * Sets the objects velocity. * * Arguments: * REFD3DVECTOR [in]: velocity. * DWORD [in]: flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::SetVelocity" HRESULT CDirectSound3dBuffer::SetVelocity(REFD3DVECTOR vrVelocity, DWORD dwFlags) { HRESULT hr; DPF_ENTER(); hr = m_pWrapper3dObject->SetVelocity(vrVelocity, !(dwFlags & DS3D_DEFERRED)); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetAttenuation * * Description: * Obtains the buffer's current true attenuation (as opposed to * GetVolume, which just returns the last volume set by the app). * * Arguments: * FLOAT* [out]: attenuation in millibels. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSound3dBuffer::GetAttenuation" HRESULT CDirectSound3dBuffer::GetAttenuation(FLOAT* pfAttenuation) { DPF_ENTER(); HRESULT hr = m_pParent->GetAttenuation(pfAttenuation); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * CDirectSoundPropertySet * * Description: * Object constructor. * * Arguments: * CUnknown * [in]: parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::CDirectSoundPropertySet" CDirectSoundPropertySet::CDirectSoundPropertySet(CUnknown *pParent) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSoundPropertySet); // Set defaults m_pParent = pParent; m_pImpKsPropertySet = NULL; m_pWrapperPropertySet = NULL; m_pDevicePropertySet = NULL; m_hrInit = DSERR_UNINITIALIZED; DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSoundPropertySet * * Description: * Object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::~CDirectSoundPropertySet" CDirectSoundPropertySet::~CDirectSoundPropertySet(void) { DPF_ENTER(); DPF_DESTRUCT(CDirectSoundPropertySet); // Free property set objects RELEASE(m_pWrapperPropertySet); RELEASE(m_pDevicePropertySet); // Free interface(s) DELETE(m_pImpKsPropertySet); DPF_LEAVE_VOID(); } /*************************************************************************** * * Initialize * * Description: * Initializes the object. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::Initialize" HRESULT CDirectSoundPropertySet::Initialize(void) { HRESULT hr; DPF_ENTER(); // Create the wrapper property set object m_pWrapperPropertySet = NEW(CWrapperPropertySet); hr = HRFROMP(m_pWrapperPropertySet); // Register interface if(SUCCEEDED(hr)) { hr = CreateAndRegisterInterface(m_pParent, IID_IKsPropertySet, this, &m_pImpKsPropertySet); } // Success if(SUCCEEDED(hr)) { m_hrInit = DS_OK; } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * AcquireResources * * Description: * Acquires hardware resources. * * Arguments: * CRenderWaveBuffer * [in]: device buffer. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::AcquireResources" HRESULT CDirectSoundPropertySet::AcquireResources(CRenderWaveBuffer *pDeviceBuffer) { HRESULT hr; DPF_ENTER(); // Create the device property set object ASSERT(m_pDevicePropertySet == NULL); hr = pDeviceBuffer->CreatePropertySet(&m_pDevicePropertySet); if(SUCCEEDED(hr)) { hr = m_pWrapperPropertySet->SetObjectPointer(m_pDevicePropertySet); } if(SUCCEEDED(hr)) { DPF(DPFLVL_MOREINFO, "Property set at 0x%p has acquired resources at 0x%p", this, m_pDevicePropertySet); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * FreeResources * * Description: * Frees hardware resources. * * Arguments: * (void) * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::FreeResources" HRESULT CDirectSoundPropertySet::FreeResources(void) { HRESULT hr; DPF_ENTER(); // Free the device property set object hr = m_pWrapperPropertySet->SetObjectPointer(NULL); if(SUCCEEDED(hr)) { RELEASE(m_pDevicePropertySet); DPF(DPFLVL_MOREINFO, "Property set at 0x%p has freed its resources", this); } DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * QuerySupport * * Description: * Queries for support of a given property set or property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id, or 0 to query for support of the property * set as a whole. * PULONG [out]: receives support flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::QuerySupport" HRESULT CDirectSoundPropertySet::QuerySupport(REFGUID guidPropertySetId, ULONG ulPropertyId, PULONG pulSupport) { HRESULT hr; DPF_ENTER(); hr = m_pWrapperPropertySet->QuerySupport(guidPropertySetId, ulPropertyId, pulSupport); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetProperty * * Description: * Gets data for a given property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id. * LPVOID [in]: property parameters. * ULONG [in]: size of property parameters. * LPVOID [out]: receives property data. * PULONG [in/out]: size of property data. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::GetProperty" HRESULT CDirectSoundPropertySet::GetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, PULONG pcbPropertyData) { HRESULT hr; DPF_ENTER(); hr = m_pWrapperPropertySet->GetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, pcbPropertyData); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetProperty * * Description: * Sets data for a given property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id. * LPVOID [in]: property parameters. * ULONG [in]: size of property parameters. * LPVOID [in]: property data. * ULONG [in]: size of property data. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundPropertySet::SetProperty" HRESULT CDirectSoundPropertySet::SetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, ULONG cbPropertyData) { HRESULT hr; DPF_ENTER(); hr = m_pWrapperPropertySet->SetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, cbPropertyData); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * CDirectSoundSecondaryBufferPropertySet * * Description: * Object constructor. * * Arguments: * CDirectSoundSecondaryBuffer * [in]: parent object. * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::CDirectSoundSecondaryBufferPropertySet" CDirectSoundSecondaryBufferPropertySet::CDirectSoundSecondaryBufferPropertySet(CDirectSoundSecondaryBuffer *pParent) : CDirectSoundPropertySet(pParent) { DPF_ENTER(); DPF_CONSTRUCT(CDirectSoundSecondaryBufferPropertySet); DPF_LEAVE_VOID(); } /*************************************************************************** * * ~CDirectSoundSecondaryBufferPropertySet * * Description: * Object destructor. * * Arguments: * (void) * * Returns: * (void) * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::~CDirectSoundSecondaryBufferPropertySet" CDirectSoundSecondaryBufferPropertySet::~CDirectSoundSecondaryBufferPropertySet(void) { DPF_ENTER(); DPF_DESTRUCT(CDirectSoundSecondaryBufferPropertySet); DPF_LEAVE_VOID(); } /*************************************************************************** * * QuerySupport * * Description: * Queries for support of a given property set or property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id, or 0 to query for support of the property * set as a whole. * PULONG [out]: receives support flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::QuerySupport" HRESULT CDirectSoundSecondaryBufferPropertySet::QuerySupport(REFGUID guidPropertySetId, ULONG ulPropertyId, PULONG pulSupport) { HRESULT hr; DPF_ENTER(); hr = CPropertySetHandler::QuerySupport(guidPropertySetId, ulPropertyId, pulSupport); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * GetProperty * * Description: * Gets data for a given property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id. * LPVOID [in]: property parameters. * ULONG [in]: size of property parameters. * LPVOID [out]: receives property data. * PULONG [in/out]: size of property data. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::GetProperty" HRESULT CDirectSoundSecondaryBufferPropertySet::GetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, PULONG pcbPropertyData) { HRESULT hr; DPF_ENTER(); hr = CPropertySetHandler::GetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, pcbPropertyData); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * SetProperty * * Description: * Sets data for a given property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id. * LPVOID [in]: property parameters. * ULONG [in]: size of property parameters. * LPVOID [in]: property data. * ULONG [in]: size of property data. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::SetProperty" HRESULT CDirectSoundSecondaryBufferPropertySet::SetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, ULONG cbPropertyData) { HRESULT hr; DPF_ENTER(); hr = CPropertySetHandler::SetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, cbPropertyData); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * UnsupportedQueryHandler * * Description: * Queries for support of a given property set or property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id, or 0 to query for support of the property * set as a whole. * PULONG [out]: receives support flags. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::UnsupportedQueryHandler" HRESULT CDirectSoundSecondaryBufferPropertySet::UnsupportedQueryHandler(REFGUID guidPropertySetId, ULONG ulPropertyId, PULONG pulSupport) { HRESULT hr; DPF_ENTER(); hr = CDirectSoundPropertySet::QuerySupport(guidPropertySetId, ulPropertyId, pulSupport); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * UnsupportedGetHandler * * Description: * Gets data for a given property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id. * LPVOID [in]: property parameters. * ULONG [in]: size of property parameters. * LPVOID [out]: receives property data. * PULONG [in/out]: size of property data. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::UnsupportedGetHandler" HRESULT CDirectSoundSecondaryBufferPropertySet::UnsupportedGetHandler(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, PULONG pcbPropertyData) { HRESULT hr; DPF_ENTER(); hr = CDirectSoundPropertySet::GetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, pcbPropertyData); DPF_LEAVE_HRESULT(hr); return hr; } /*************************************************************************** * * UnsupportedSetHandler * * Description: * Sets data for a given property. * * Arguments: * REFGUID [in]: property set id. * ULONG [in]: property id. * LPVOID [in]: property parameters. * ULONG [in]: size of property parameters. * LPVOID [in]: property data. * ULONG [in]: size of property data. * * Returns: * HRESULT: DirectSound/COM result code. * ***************************************************************************/ #undef DPF_FNAME #define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::UnsupportedSetHandler" HRESULT CDirectSoundSecondaryBufferPropertySet::UnsupportedSetHandler(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, ULONG cbPropertyData) { HRESULT hr; DPF_ENTER(); hr = CDirectSoundPropertySet::SetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, cbPropertyData); DPF_LEAVE_HRESULT(hr); return hr; }
27.787906
213
0.542276
npocmaka
3c0f3a82dccea0a7b94e19dc5d8f525af56dc64c
5,882
hpp
C++
src/lib/nas/storage.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
16
2020-04-16T02:07:37.000Z
2020-07-23T10:48:27.000Z
src/lib/nas/storage.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
8
2020-07-13T17:11:35.000Z
2020-08-03T16:46:31.000Z
src/lib/nas/storage.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
9
2020-03-04T15:05:08.000Z
2020-07-30T06:18:18.000Z
// // This file is a part of UERANSIM open source project. // Copyright (c) 2021 ALİ GÜNGÖR. // // The software and all associated files are licensed under GPL-3.0 // and subject to the terms and conditions defined in LICENSE file. // #include <array> #include <functional> #include <optional> #include <type_traits> #include <vector> #include <utils/common.hpp> #include <utils/json.hpp> namespace nas { // TODO: Periodun sonuna geldiğinde erişilmezse, (autoClearIfNecessary çağrılmazsa) delete yapılmaz backup çalışmaz /* * - Items are unique, if already exists, deletes the previous one * - List have fixed size, if capacity is full, oldest item is deleted * - Automatically cleared after specified period * - The list is NOT thread safe */ template <typename T> class NasList { public: using backup_functor_type = std::function<void(const std::vector<T> &buffer, size_t count)>; private: const size_t m_sizeLimit; const int64_t m_autoClearingPeriod; const std::optional<backup_functor_type> m_backupFunctor; std::vector<T> m_data; size_t m_size; int64_t m_lastAutoCleared; public: NasList(size_t sizeLimit, int64_t autoClearingPeriod, std::optional<backup_functor_type> backupFunctor) : m_sizeLimit{sizeLimit}, m_autoClearingPeriod{autoClearingPeriod}, m_backupFunctor{backupFunctor}, m_data{sizeLimit}, m_size{}, m_lastAutoCleared{::utils::CurrentTimeMillis()} { } NasList(const NasList &) = delete; NasList(NasList &&) = delete; public: void add(const T &item) { autoClearIfNecessary(); remove(item); makeSlotForNewItem(); m_data[m_size] = item; m_size++; touch(); } void add(T &&item) { autoClearIfNecessary(); remove(item); makeSlotForNewItem(); m_data[m_size] = std::move(item); m_size++; touch(); } void remove(const T &item) { autoClearIfNecessary(); size_t index = ~0u; for (size_t i = 0; i < m_size; i++) { if (m_data[i] == item) { index = i; break; } } if (index != ~0u) removeAt(index); } bool contains(const T &item) { autoClearIfNecessary(); for (size_t i = 0; i < m_size; i++) if (m_data[i] == item) return true; return false; } template <typename Functor> void forEach(Functor &&fun) { autoClearIfNecessary(); for (size_t i = 0; i < m_size; i++) fun((const T &)m_data[i]); } template <typename Functor> void mutateForEach(Functor &&fun) { autoClearIfNecessary(); for (size_t i = 0; i < m_size; i++) fun(m_data[i]); touch(); } void clear() { int64_t currentTime = ::utils::CurrentTimeMillis(); if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod) m_lastAutoCleared = currentTime; m_data.clear(); m_size = 0; touch(); } [[nodiscard]] size_t size() const { autoClearIfNecessary(); return m_data.size(); } private: void autoClearIfNecessary() { if (m_autoClearingPeriod <= 0) return; int64_t currentTime = ::utils::CurrentTimeMillis(); if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod) { m_lastAutoCleared = currentTime; clear(); } } void makeSlotForNewItem() { if (m_size >= m_sizeLimit) removeAt(0); } void removeAt(size_t index) { for (size_t i = index; i < m_size; ++i) m_data[i] = i + 1 < m_sizeLimit ? m_data[i + 1] : T{}; m_size--; touch(); } void touch() { if (m_backupFunctor) (*m_backupFunctor)(m_data, m_size); } }; template <typename T> class NasSlot { public: using backup_functor_type = std::function<void(const T &value)>; private: const int64_t m_autoClearingPeriod; const std::optional<backup_functor_type> m_backupFunctor; T m_value; int64_t m_lastAutoCleared; static_assert(!std::is_reference<T>::value); public: NasSlot(int64_t autoClearingPeriod, std::optional<backup_functor_type> backupFunctor) : m_autoClearingPeriod{autoClearingPeriod}, m_backupFunctor{backupFunctor}, m_value{}, m_lastAutoCleared{::utils::CurrentTimeMillis()} { } const T &get() { autoClearIfNecessary(); return m_value; } const T &getPure() const { return m_value; } void clear() { set(T{}); } void set(const T &value) { autoClearIfNecessary(); m_value = value; touch(); } void set(T &&value) { autoClearIfNecessary(); m_value = std::move(value); touch(); } template <typename Functor> void access(Functor fun) { autoClearIfNecessary(); fun((const T &)m_value); } template <typename Functor> void mutate(Functor fun) { autoClearIfNecessary(); fun((T &)m_value); touch(); } private: void autoClearIfNecessary() { if (m_autoClearingPeriod <= 0) return; int64_t currentTime = ::utils::CurrentTimeMillis(); if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod) { m_lastAutoCleared = currentTime; m_value = {}; } } void touch() { if (m_backupFunctor) (*m_backupFunctor)(m_value); } }; } // namespace nas template <typename T> inline Json ToJson(const nas::NasSlot<T> &v) { return ToJson(v.getPure()); }
20.858156
118
0.579735
aligungr
3c0f7ba66ef17898cc749620c5aade0186243f97
2,048
hpp
C++
ux/uxsysvipc.hpp
bachue/AUPv2
97ea014fc6619f6355174bbd1ee68a9a1ae19a0d
[ "Unlicense" ]
null
null
null
ux/uxsysvipc.hpp
bachue/AUPv2
97ea014fc6619f6355174bbd1ee68a9a1ae19a0d
[ "Unlicense" ]
null
null
null
ux/uxsysvipc.hpp
bachue/AUPv2
97ea014fc6619f6355174bbd1ee68a9a1ae19a0d
[ "Unlicense" ]
null
null
null
/* Copyright 2003 by Marc J. Rochkind. All rights reserved. May be copied only for purposes and under conditions described on the Web page www.basepath.com/aup/copyright.htm. The Example Files are provided "as is," without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. The author and his publisher are not responsible for any damages, direct or incidental, resulting from the use or non-use of these Example Files. The Example Files may contain defects, and some contain deliberate coding mistakes that were included for educational reasons. You are responsible for determining if and how the Example Files are to be used. */ #ifndef _UXSYSVIPC_HPP_ #define _UXSYSVIPC_HPP_ #include <sys/ipc.h> #include <sys/msg.h> #include <sys/shm.h> #include <sys/sem.h> namespace Ux { /** \ingroup Ux */ class SysVIPC : public Base { protected: int id; public: SysVIPC(int n = -1) : id(n) { } static key_t ftok(const char *path, int id); operator int() { return id; } }; /** \ingroup Ux */ class SysVMsg : public SysVIPC { public: void get(key_t key, int flags = IPC_CREAT | PERM_FILE); void ctl(int cmd, struct msqid_ds *data = NULL); void snd(const void *msgp, size_t msgsize, int flags = 0); ssize_t rcv(void *msgp, size_t mtextsize, long msgtype = 0, int flags = 0); }; /** \ingroup Ux */ class SysVShm : public SysVIPC { public: void get(key_t key, size_t size, int flags = IPC_CREAT | PERM_FILE); void ctl(int cmd, struct shmid_ds *data = NULL); void * at(const void *shmaddr = NULL, int flags = 0); void dt(const void *shmaddr); }; /** \ingroup Ux Union defined by SUS, but not in any standard header. */ union semun { int val; struct semid_ds *buf; unsigned short *array; }; /** \ingroup Ux */ class SysVSem : public SysVIPC { public: void get(key_t key, int nsems, int flags = IPC_CREAT | PERM_FILE); int ctl(int semnum, int cmd, union semun arg); void op(struct sembuf *sops, size_t nsops); }; } // namespace #endif // _UXSYSVIPC_HPP_
23.011236
76
0.713867
bachue
3c10e19edcf66eac67ca39fb40ce1ee7359ac99c
3,550
cpp
C++
DigitalPlayprint/lib/common/src/DPPType/DppScalarArray.cpp
magic-lantern-studio/mle-core-dpp
ec901206b718c57163d8ac62afab7a1e1d6371d9
[ "MIT" ]
null
null
null
DigitalPlayprint/lib/common/src/DPPType/DppScalarArray.cpp
magic-lantern-studio/mle-core-dpp
ec901206b718c57163d8ac62afab7a1e1d6371d9
[ "MIT" ]
null
null
null
DigitalPlayprint/lib/common/src/DPPType/DppScalarArray.cpp
magic-lantern-studio/mle-core-dpp
ec901206b718c57163d8ac62afab7a1e1d6371d9
[ "MIT" ]
null
null
null
/** @defgroup MleDPPType Magic Lantern Digital Playprint Library API - Type */ /** * @file DppScalarArray.h * @ingroup MleDPPType * * This file implements the scalar array data type used by the Magic Lantern Digital * Playprint Library API. * * @author Mark S. Millard * @created February 6, 2004 */ // COPYRIGHT_BEGIN // // Copyright (c) 2015 Wizzer Works // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // For information concerning this source file, contact Mark S. Millard, // of Wizzer Works at msm@wizzerworks.com. // // More information concerning Wizzer Works may be found at // // http://www.wizzerworks.com // // COPYRIGHT_END // Include Magic Lantern header files. #include "mle/mlMalloc.h" // Include Digital Playprint header files. #include "mle/DppScalar.h" #include "mle/DppScalarArray.h" // // int array class // MLE_DWP_DATATYPE_SOURCE(MleDppScalarArray,"ScalarArray",MleDppArray); // // The MlScalar type might be a float or a long 16.16 fixed point // number. Or it might be a class encapsulating one of those. // Read/write the thing as a floating point number for the sake // of numerics and having a fixed interchange format (esp if we // go to 16.16 AND 20.12 fixed point numbers). // // Read into the data union as a float, then convert to fixed/float // scalar type on the get()/set(). int MleDppScalarArray::readElement(MleDwpInput *in,void *data) const { return in->readFloat((float *)data); } int MleDppScalarArray::writeElement(MleDwpOutput *out,void *data) const { return out->writeFloat(*(float *)data); } int MleDppScalarArray::writeElement(MleDppActorGroupOutput *out,void *data) const { return out->writeScalar(*(float *)data); } int MleDppScalarArray::getElementSize(void) const { return sizeof(MlScalar); } void MleDppScalarArray::setElement(MleDwpDataUnion *data,void *src) const { SET_FLOAT_FROM_SCALAR(*(float *)(data->m_u.v),src); } void MleDppScalarArray::getElement(MleDwpDataUnion *data,void *dst) const { SET_SCALAR_FROM_FLOAT(dst,*(float *)(data->m_u.v)); } void MleDppScalarArray::set(MleDwpDataUnion *data,void *src) const { data->setDatatype(this); data->m_u.v = new MleArray<MlScalar> ( *(MleArray<MlScalar> *)src ); } void MleDppScalarArray::get(MleDwpDataUnion *data,void *dst) const { *(MleArray<MlScalar> *)dst = *(MleArray<MlScalar> *)data->m_u.v; } void * MleDppScalarArray::operator new(size_t tSize) { void *p = mlMalloc(tSize); return p; } void MleDppScalarArray::operator delete(void *p) { mlFree(p); }
27.51938
84
0.738592
magic-lantern-studio
3c10fb00d9bc967b0e278f171ba3e607debedeeb
7,330
cpp
C++
src/V8Snapshot.cpp
pengwei1024/V8Study.x86
7d82da573b57f8d1d00b85778e2a3853d21c28e9
[ "Apache-2.0" ]
2
2021-05-26T08:12:17.000Z
2022-01-22T07:07:04.000Z
src/V8Snapshot.cpp
pengwei1024/V8Study.x86
7d82da573b57f8d1d00b85778e2a3853d21c28e9
[ "Apache-2.0" ]
null
null
null
src/V8Snapshot.cpp
pengwei1024/V8Study.x86
7d82da573b57f8d1d00b85778e2a3853d21c28e9
[ "Apache-2.0" ]
null
null
null
// // Created by Peng,Wei(BAMRD) on 2021/4/2. // https://github.com/tosone/bundleNode/blob/aaf04fd200a56f3f5b60c1c691877c192c6448af/deps/v8/src/startup-data-util.cc // #include <v8.h> #include "V8Snapshot.h" #include "V8Engine.h" #include "GlobalObject.h" #include "Utils.hpp" #ifdef WIN32 #include <io.h> #include <direct.h> #else #include <unistd.h> #include <sys/stat.h> #endif #include <stdint.h> #include <string> #define MAX_PATH_LEN 256 #ifdef WIN32 #define ACCESS(fileName,accessMode) _access(fileName,accessMode) #define MKDIR(path) _mkdir(path) #else #define ACCESS(fileName, accessMode) access(fileName,accessMode) #define MKDIR(path) mkdir(path,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) #endif #define MAX_PATH_LEN 256 using namespace v8; v8::StartupData V8Snapshot::makeSnapshot() { auto external_references = createExtRef(); V8Engine v8Engine(external_references); v8::StartupData data{nullptr, 0}; v8::SnapshotCreator creator(v8Engine.isolate, external_references.data(), nullptr); { v8::HandleScope scope(v8Engine.isolate); v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(v8Engine.isolate); global->SetAccessor(String::NewFromUtf8(v8Engine.isolate, "x").ToLocalChecked(), GlobalObject::XGetter, GlobalObject::XSetter); printf("GlobalObject::Version point=%p\n", &GlobalObject::Version); Local<FunctionTemplate> fun = v8::FunctionTemplate::New(v8Engine.isolate, GlobalObject::Version); global->Set(v8Engine.isolate, "version", fun); v8::Local<v8::Context> context = v8::Context::New(v8Engine.isolate, nullptr, global); v8::Context::Scope context_scope(context); { v8::Local<v8::String> source = v8::String::NewFromUtf8(v8Engine.isolate, "if(typeof x == 'undefined'){x = 0}x++;function add(a,b) {return a+b;}var kk='##@';(typeof version === 'function'? version(): 'None')+ add(0.1,x);").ToLocalChecked(); v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked(); v8::Local<v8::Value> result = script->Run(context).ToLocalChecked(); v8::String::Utf8Value value(v8Engine.isolate, result); printf("result = %s\n", *value); // 必须要调用 AddContext creator.AddContext(context); creator.SetDefaultContext(context); } } data = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kKeep); // 立即从 snapshot 恢复 context restoreSnapshot(data, false); return data; } // 从左到右依次判断文件夹是否存在,不存在就创建 // example: /home/root/mkdir/1/2/3/4/ // 注意:最后一个如果是文件夹的话,需要加上 '\' 或者 '/' int32_t createDirectory(const std::string &directoryPath) { uint32_t dirPathLen = directoryPath.length(); if (dirPathLen > MAX_PATH_LEN) { return -1; } char tmpDirPath[MAX_PATH_LEN] = {0}; for (uint32_t i = 0; i < dirPathLen; ++i) { tmpDirPath[i] = directoryPath[i]; if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/') { if (ACCESS(tmpDirPath, 0) != 0) { int32_t ret = MKDIR(tmpDirPath); if (ret != 0) { return ret; } } } } return 0; } void V8Snapshot::restoreSnapshot(v8::StartupData &data, const bool createPlatform) { printf("## restoreSnapshot ##\n"); if (createPlatform) { v8::V8::InitializeICU(); v8::V8::InitializeExternalStartupDataFromFile(__FILE__); platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); printf("version=%s\n", v8::V8::GetVersion()); } // Create a new Isolate and make it the current one. createParams = v8::Isolate::CreateParams(); createParams.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); createParams.snapshot_blob = &data; createParams.external_references = createExtRef().data(); v8::Isolate *isolate = v8::Isolate::New(createParams); { v8::HandleScope handle_scope(isolate); v8::TryCatch tryCatch(isolate); // Create a new context. v8::Local<v8::Context> context = v8::Context::New(isolate); // v8::Local<v8::Context> context = v8::Context::FromSnapshot(isolate, 0).ToLocalChecked(); // Enter the context for compiling and running the hello world script. v8::Context::Scope context_scope(context); { v8::Local<v8::String> source = v8::String::NewFromUtf8Literal(isolate, "(typeof version === 'function')? x + version():'not found version()'"); // Compile the source code. v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked(); v8::MaybeLocal<v8::Value> localResult = script->Run(context); if (tryCatch.HasCaught() || localResult.IsEmpty()) { Local<String> msg = tryCatch.Message()->Get(); v8::String::Utf8Value msgVal(isolate, msg); printf("HasCaught => %s\n", *msgVal); } else { v8::Local<v8::Value> result = localResult.ToLocalChecked(); // Convert the result to an UTF8 string and print it. v8::String::Utf8Value utf8(isolate, result); printf("restore add() = %s\n", *utf8); } } } if (createPlatform) { isolate->Dispose(); v8::V8::Dispose(); v8::V8::ShutdownPlatform(); delete createParams.array_buffer_allocator; } } void V8Snapshot::writeFile(v8::StartupData data) { char currentPath[MAX_PATH_LEN]; getcwd(currentPath, MAX_PATH_LEN); printf("current path =%s\n", currentPath); std::string path = currentPath; FILE *file = fopen((path + "/a.blob").c_str(), "w"); fseek(file, 0, SEEK_END); rewind(file); int writeSize = fwrite(data.data, data.raw_size, 1, file); printf("write size=%d\n", writeSize); fclose(file); } void V8Snapshot::readFile(v8::StartupData &data) { char currentPath[MAX_PATH_LEN]; getcwd(currentPath, MAX_PATH_LEN); printf("current path =%s\n", currentPath); std::string path = currentPath; FILE *file = fopen((path + "/a.blob").c_str(), "rb"); fseek(file, 0, SEEK_END); data.raw_size = static_cast<int>(ftell(file)); rewind(file); data.data = new char[data.raw_size]; int read_size = static_cast<int>(fread(const_cast<char *>(data.data), 1, data.raw_size, file)); fclose(file); printf("readFile ## raw_size =%d, IsValid=%d, CanBeRehashed=%d, read_size=%d\n", data.raw_size, data.IsValid(), data.CanBeRehashed(), read_size); } std::vector<intptr_t> V8Snapshot::createExtRef() { std::vector<intptr_t> external_references; external_references.reserve(3); external_references.push_back((intptr_t) &GlobalObject::Version); external_references.push_back((intptr_t) &GlobalObject::XGetter); external_references.push_back((intptr_t) &GlobalObject::XSetter); return external_references; }
38.783069
210
0.619645
pengwei1024
3c11133c5185b8e7beeab83e5b639d2086a62ca1
154
cpp
C++
lib/AsciiArtParsers/LinesParser/LinesParser.cpp
dodikk/AsciiBresenheim
e107d1e8773826868edb83e0f56a8052ce73a264
[ "BSD-4-Clause" ]
1
2022-03-13T00:42:02.000Z
2022-03-13T00:42:02.000Z
lib/AsciiArtParsers/LinesParser/LinesParser.cpp
dodikk/AsciiBresenheim
e107d1e8773826868edb83e0f56a8052ce73a264
[ "BSD-4-Clause" ]
null
null
null
lib/AsciiArtParsers/LinesParser/LinesParser.cpp
dodikk/AsciiBresenheim
e107d1e8773826868edb83e0f56a8052ce73a264
[ "BSD-4-Clause" ]
null
null
null
#include "StdAfx.h" #include "LinesParser.h" using namespace AsciiArt::Parser; LinesParser::LinesParser(void) { } LinesParser::~LinesParser(void) { }
11
33
0.733766
dodikk
3c12e06c7798ed0b2fa2dd80f7b1ff2bbf2c6118
4,037
cpp
C++
05-Map/src/Sokoban.cpp
eXpl0it3r/SFML-Workshop
0a42acc8a4aa48d44f3191b7472ea1f666381dee
[ "Unlicense" ]
9
2019-06-11T16:55:25.000Z
2020-05-06T14:59:28.000Z
05-Map/src/Sokoban.cpp
eXpl0it3r/SFML-Workshop
0a42acc8a4aa48d44f3191b7472ea1f666381dee
[ "Unlicense" ]
null
null
null
05-Map/src/Sokoban.cpp
eXpl0it3r/SFML-Workshop
0a42acc8a4aa48d44f3191b7472ea1f666381dee
[ "Unlicense" ]
null
null
null
#include "Sokoban.hpp" Sokoban::Sokoban() : m_window_size{ 640u, 640u }, m_distance{ 64.f }, m_tile_size{ m_distance, m_distance }, m_window{ sf::VideoMode{ m_window_size.x, m_window_size.y }, "05 - Map - SFML Workshop" } { m_window.setFramerateLimit(60); m_texture_holder.load("tilesheet", "assets/tilesheet.png"); init_player(); init_map(); } void Sokoban::run() { while (m_window.isOpen()) { handle_events(); update(); render(); } } void Sokoban::handle_events() { for (auto event = sf::Event{}; m_window.pollEvent(event);) { if (event.type == sf::Event::Closed) { m_window.close(); } handle_keyboard_input(event); } } void Sokoban::update() { const auto next_position = m_player.getPosition() + (sf::Vector2f{ m_direction } * m_distance); m_direction = sf::Vector2i{}; if (check_window_bounds(next_position) && !m_map.check_collision(next_position, { 0, 85, 90 })) { m_player.setPosition(next_position); } } void Sokoban::render() { m_window.clear(sf::Color{ 0xAA733CFF }); m_window.draw(m_map); m_window.draw(m_player); m_window.display(); } void Sokoban::init_player() { m_player.setTexture(m_texture_holder.get("tilesheet")); m_player.setPosition(m_tile_size * 2.f); m_player.setTextureRect({ 0, 5 * static_cast<int>(m_tile_size.y), static_cast<int>(m_tile_size.x), static_cast<int>(m_tile_size.y) }); } void Sokoban::init_map() { std::vector<int> data = { 90, 90, 90, 85, 85, 85, 85, 85, 90, 90, 90, 85, 85, 85, 89, 89, 89, 85, 90, 90, 90, 85, 102, 89, 89, 89, 89, 85, 90, 90, 90, 85, 85, 85, 89, 89, 102, 85, 90, 90, 90, 85, 102, 85, 85, 89, 89, 85, 90, 90, 90, 85, 89, 85, 89, 102, 89, 85, 85, 90, 90, 85, 89, 89, 102, 89, 89, 102, 85, 90, 90, 85, 89, 89, 89, 102, 89, 89, 85, 90, 90, 85, 85, 85, 85, 85, 85, 85, 85, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, }; m_map.load(m_texture_holder.get("tilesheet"), { 64u, 64u }, data.data(), { 10u, 10u }); } void Sokoban::handle_keyboard_input(const sf::Event event) { if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Left && !m_key_states[sf::Keyboard::Left]) { m_direction.x = -1; m_key_states[sf::Keyboard::Left] = true; } else if (event.key.code == sf::Keyboard::Right && !m_key_states[sf::Keyboard::Right]) { m_direction.x = 1; m_key_states[sf::Keyboard::Right] = true; } else if (event.key.code == sf::Keyboard::Up && !m_key_states[sf::Keyboard::Up]) { m_direction.y = -1; m_key_states[sf::Keyboard::Up] = true; } else if (event.key.code == sf::Keyboard::Down && !m_key_states[sf::Keyboard::Down]) { m_direction.y = 1; m_key_states[sf::Keyboard::Down] = true; } } else if (event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Left) { m_direction.x = 0; m_key_states[sf::Keyboard::Left] = false; } else if (event.key.code == sf::Keyboard::Right) { m_direction.x = 0; m_key_states[sf::Keyboard::Right] = false; } else if (event.key.code == sf::Keyboard::Up) { m_direction.y = 0; m_key_states[sf::Keyboard::Up] = false; } else if (event.key.code == sf::Keyboard::Down) { m_direction.y = 0; m_key_states[sf::Keyboard::Down] = false; } } } bool Sokoban::check_window_bounds(const sf::Vector2<float> next_position) const { return next_position.x >= 0.f && next_position.x <= m_window_size.x - m_distance && next_position.y >= 0.f && next_position.y <= m_window_size.y - m_distance; }
28.230769
99
0.55462
eXpl0it3r
3c18d01176bba72ebd3e73829eec458c78ec502c
1,762
hpp
C++
src/jngl/shapes.hpp
jhasse/jngl
1aab1bb5b9712eca50786418d44e9559373441a8
[ "Zlib" ]
61
2015-09-30T14:42:38.000Z
2022-03-30T13:56:54.000Z
src/jngl/shapes.hpp
jhasse/jngl
1aab1bb5b9712eca50786418d44e9559373441a8
[ "Zlib" ]
57
2016-08-10T19:28:36.000Z
2022-03-15T07:18:00.000Z
src/jngl/shapes.hpp
jhasse/jngl
1aab1bb5b9712eca50786418d44e9559373441a8
[ "Zlib" ]
3
2021-12-14T18:08:56.000Z
2022-02-23T08:29:19.000Z
// Copyright 2012-2020 Jan Niklas Hasse <jhasse@bixense.com> // For conditions of distribution and use, see copyright notice in LICENSE.txt /// Functions for drawing shapes /// @file #pragma once #include "Color.hpp" #include "Vec2.hpp" namespace jngl { /// Sets the color which should be used to draw primitives /// /// Doesn't change the alpha value currently set by setAlpha() void setColor(jngl::Color rgb); void setColor(jngl::Color, unsigned char alpha); void setColor(unsigned char red, unsigned char green, unsigned char blue); void setColor(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha); /// Sets the alpha value which should be used to draw primitives (0 = fully transparent, 255 = fully /// opaque) void setAlpha(uint8_t alpha); void pushAlpha(unsigned char alpha); void popAlpha(); void setLineWidth(float width); void drawLine(Vec2 start, Vec2 end); void drawLine(double xstart, double ystart, double xend, double yend); void drawEllipse(float xmid, float ymid, float width, float height, float startAngle = 0); void drawEllipse(Vec2, float width, float height, float startAngle = 0); void drawCircle(Vec2, float radius, float startAngle = 0); void drawPoint(double x, double y); void drawTriangle(Vec2 a, Vec2 b, Vec2 c); void drawTriangle(double A_x, double A_y, double B_x, double B_y, double C_x, double C_y); void drawRect(double xposition, double yposition, double width, double height); /// Draws a rectangle at \a position /// /// Use setColor(Color) to change the color and setAlpha(uint8_t) to change the translucency. void drawRect(Vec2 position, Vec2 size); template <class Vect> void drawRect(Vect pos, Vect size) { drawRect(pos.x, pos.y, size.x, size.y); } } // namespace jngl
28.885246
100
0.747446
jhasse
3c1a076c7a89670cc4eab31bc9a78b6a04661ccf
91
cc
C++
kythe/cxx/indexer/cxx/testdata/basic/inline_namespace.cc
bowlofstew/kythe
23a3524de3924901ffaba4b8bcab8abe96de6f3a
[ "Apache-2.0" ]
1
2021-04-24T08:18:15.000Z
2021-04-24T08:18:15.000Z
kythe/cxx/indexer/cxx/testdata/basic/inline_namespace.cc
bowlofstew/kythe
23a3524de3924901ffaba4b8bcab8abe96de6f3a
[ "Apache-2.0" ]
3
2020-12-31T09:08:34.000Z
2021-09-28T05:42:02.000Z
kythe/cxx/indexer/cxx/testdata/basic/inline_namespace.cc
moul/kythe
2e198cc818981fc6cffa14d8263fda3a33da6429
[ "Apache-2.0" ]
null
null
null
// We index inline namespaces. //- @ns defines/binding NamespaceNS inline namespace ns { }
18.2
35
0.736264
bowlofstew
3c1a841992e6b972b684dae30d628b652f4f73b6
3,101
cpp
C++
src/org/apache/poi/ss/formula/function/FunctionMetadata.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/function/FunctionMetadata.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/function/FunctionMetadata.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/function/FunctionMetadata.java #include <org/apache/poi/ss/formula/function/FunctionMetadata.hpp> #include <java/lang/Class.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <Array.hpp> template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::formula::function::FunctionMetadata::FunctionMetadata(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::formula::function::FunctionMetadata::FunctionMetadata(int32_t index, ::java::lang::String* name, int32_t minParams, int32_t maxParams, int8_t returnClassCode, ::int8_tArray* parameterClassCodes) : FunctionMetadata(*static_cast< ::default_init_tag* >(0)) { ctor(index,name,minParams,maxParams,returnClassCode,parameterClassCodes); } constexpr int16_t poi::ss::formula::function::FunctionMetadata::FUNCTION_MAX_PARAMS; void poi::ss::formula::function::FunctionMetadata::ctor(int32_t index, ::java::lang::String* name, int32_t minParams, int32_t maxParams, int8_t returnClassCode, ::int8_tArray* parameterClassCodes) { super::ctor(); _index = index; _name = name; _minParams = minParams; _maxParams = maxParams; _returnClassCode = returnClassCode; _parameterClassCodes = (parameterClassCodes == nullptr) ? static_cast< ::int8_tArray* >(nullptr) : npc(parameterClassCodes)->clone(); } int32_t poi::ss::formula::function::FunctionMetadata::getIndex() { return _index; } java::lang::String* poi::ss::formula::function::FunctionMetadata::getName() { return _name; } int32_t poi::ss::formula::function::FunctionMetadata::getMinParams() { return _minParams; } int32_t poi::ss::formula::function::FunctionMetadata::getMaxParams() { return _maxParams; } bool poi::ss::formula::function::FunctionMetadata::hasFixedArgsLength() { return _minParams == _maxParams; } int8_t poi::ss::formula::function::FunctionMetadata::getReturnClassCode() { return _returnClassCode; } int8_tArray* poi::ss::formula::function::FunctionMetadata::getParameterClassCodes() { return npc(_parameterClassCodes)->clone(); } bool poi::ss::formula::function::FunctionMetadata::hasUnlimitedVarags() { return FUNCTION_MAX_PARAMS == _maxParams; } java::lang::String* poi::ss::formula::function::FunctionMetadata::toString() { auto sb = new ::java::lang::StringBuffer(int32_t(64)); npc(npc(sb)->append(npc(getClass())->getName()))->append(u" ["_j); npc(npc(npc(sb)->append(_index))->append(u" "_j))->append(_name); npc(sb)->append(u"]"_j); return npc(sb)->toString(); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::formula::function::FunctionMetadata::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.function.FunctionMetadata", 51); return c; } java::lang::Class* poi::ss::formula::function::FunctionMetadata::getClass0() { return class_(); }
29.817308
204
0.722348
pebble2015
3c1d5e34e805702a010f50bccd41ab7061c3b41e
4,952
cc
C++
tests/unit/features/StreamingHashedDocDotFeatures_unittest.cc
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
2
2021-08-12T18:11:06.000Z
2021-11-17T10:56:49.000Z
tests/unit/features/StreamingHashedDocDotFeatures_unittest.cc
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
null
null
null
tests/unit/features/StreamingHashedDocDotFeatures_unittest.cc
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
null
null
null
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Evangelos Anagnostopoulos, Soeren Sonnenburg, Bjoern Esser */ #include <gtest/gtest.h> #include <shogun/features/streaming/StreamingHashedDocDotFeatures.h> #include <shogun/lib/SGString.h> #include <shogun/lib/SGStringList.h> #include <shogun/lib/DelimiterTokenizer.h> #include <shogun/converter/HashedDocConverter.h> using namespace shogun; TEST(StreamingHashedDocFeaturesTest, example_reading) { const char* doc_1 = "You're never too old to rock and roll, if you're too young to die"; const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam"; const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven"; SGString<char> string_1(65); for (index_t i=0; i<65; i++) string_1.string[i] = doc_1[i]; SGString<char> string_2(72); for (index_t i=0; i<72; i++) string_2.string[i] = doc_2[i]; SGString<char> string_3(85); for (index_t i=0; i<85; i++) string_3.string[i] = doc_3[i]; SGStringList<char> list(3,85); list.strings[0] = string_1; list.strings[1] = string_2; list.strings[2] = string_3; CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer(); tokenizer->delimiters[' '] = 1; tokenizer->delimiters['\''] = 1; tokenizer->delimiters[','] = 1; CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, true); CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE); CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection, tokenizer, 5); index_t i = 0; feats->start_parser(); while (feats->get_next_example()) { SGSparseVector<float64_t> example = feats->get_vector(); SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false); tmp.vector = list.strings[i].string; SGSparseVector<float64_t> converted_doc = converter->apply(tmp); EXPECT_EQ(example.num_feat_entries, converted_doc.num_feat_entries); for (index_t j=0; j<example.num_feat_entries; j++) { EXPECT_EQ(example.features[j].feat_index, converted_doc.features[j].feat_index); EXPECT_EQ(example.features[j].entry, converted_doc.features[j].entry); } feats->release_example(); i++; } feats->end_parser(); SG_UNREF(feats); SG_UNREF(doc_collection); SG_UNREF(converter); } TEST(StreamingHashedDocFeaturesTest, dot_tests) { const char* doc_1 = "You're never too old to rock and roll, if you're too young to die"; const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam"; const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven"; SGString<char> string_1(65); for (index_t i=0; i<65; i++) string_1.string[i] = doc_1[i]; SGString<char> string_2(72); for (index_t i=0; i<72; i++) string_2.string[i] = doc_2[i]; SGString<char> string_3(85); for (index_t i=0; i<85; i++) string_3.string[i] = doc_3[i]; SGStringList<char> list(3,85); list.strings[0] = string_1; list.strings[1] = string_2; list.strings[2] = string_3; CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer(); tokenizer->delimiters[' '] = 1; tokenizer->delimiters['\''] = 1; tokenizer->delimiters[','] = 1; CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, true); CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE); CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection, tokenizer, 5); feats->start_parser(); SGVector<float32_t> dense_vec(32); for (index_t j=0; j<32; j++) dense_vec[j] = CMath::random(0.0, 1.0); index_t i = 0; while (feats->get_next_example()) { /** Dense dot test */ SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false); tmp.vector = list.strings[i].string; SGSparseVector<float64_t> converted_doc = converter->apply(tmp); float32_t tmp_res = 0; for (index_t j=0; j<converted_doc.num_feat_entries; j++) tmp_res += dense_vec[converted_doc.features[j].feat_index] * converted_doc.features[j].entry; EXPECT_NEAR(tmp_res, feats->dense_dot(dense_vec.vector, dense_vec.vlen), 1e-7); /** Add to dense test */ SGSparseVector<float64_t> example = feats->get_vector(); SGVector<float32_t> dense_vec2(32); for (index_t j=0; j<32; j++) dense_vec2[j] = dense_vec[j]; feats->add_to_dense_vec(1, dense_vec2.vector, dense_vec2.vlen); index_t sparse_idx = 0; for (index_t j=0; j<32; j++) { if ( (sparse_idx < example.num_feat_entries) && (example.features[sparse_idx].feat_index == j) ) { EXPECT_NEAR(dense_vec2[j], dense_vec[j] + example.features[sparse_idx].entry, 1e-7); sparse_idx++; } else EXPECT_NEAR(dense_vec2[j], dense_vec[j], 1e-7); } feats->release_example(); i++; } feats->end_parser(); SG_UNREF(feats); SG_UNREF(doc_collection); SG_UNREF(converter); }
31.541401
109
0.715468
cloner1984
3c1d63800364e0bf556edb34acb28747baf5219b
1,336
cpp
C++
src/DiscreteDynamicsWorldMultiThreaded.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
245
2015-01-02T14:11:26.000Z
2022-03-18T08:56:36.000Z
src/DiscreteDynamicsWorldMultiThreaded.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
50
2015-01-04T22:32:21.000Z
2021-06-08T20:26:24.000Z
src/DiscreteDynamicsWorldMultiThreaded.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
69
2015-04-03T15:38:44.000Z
2022-01-20T14:27:30.000Z
#include "StdAfx.h" #ifndef DISABLE_UNCOMMON #include "BroadphaseInterface.h" #include "CollisionConfiguration.h" #include "DiscreteDynamicsWorldMultiThreaded.h" #include "Dispatcher.h" #include "SequentialImpulseConstraintSolver.h" ConstraintSolverPoolMultiThreaded::ConstraintSolverPoolMultiThreaded(int numSolvers) : ConstraintSolver(ALIGNED_NEW(btConstraintSolverPoolMt)(numSolvers)) { } DiscreteDynamicsWorldMultiThreaded::DiscreteDynamicsWorldMultiThreaded(BulletSharp::Dispatcher^ dispatcher, BroadphaseInterface^ pairCache, ConstraintSolverPoolMultiThreaded^ constraintSolver, BulletSharp::ConstraintSolver^ constraintSolverMultiThreaded, CollisionConfiguration^ collisionConfiguration) { if (!dispatcher) { throw gcnew ArgumentNullException("dispatcher"); } if (!pairCache) { throw gcnew ArgumentNullException("pairCache"); } if (!constraintSolver) { throw gcnew ArgumentNullException("constraintSolver"); } auto native = new btDiscreteDynamicsWorldMt(dispatcher->_native, pairCache->_native, (btConstraintSolverPoolMt*)constraintSolver->_native, GetUnmanagedNullable(constraintSolverMultiThreaded), GetUnmanagedNullable(collisionConfiguration)); _constraintSolver = constraintSolver; SetInternalReferences(native, dispatcher, pairCache); } #endif
30.363636
111
0.802395
AndresTraks
3c212a879e77cb386fd32337d492e15ca6ab8a88
5,170
cpp
C++
include/shacl/optional/Type/test/value_or.test.cpp
shacl/optional
02dc7ed2b923e3afb223817c47c239e2fab45c8f
[ "BSD-3-Clause" ]
null
null
null
include/shacl/optional/Type/test/value_or.test.cpp
shacl/optional
02dc7ed2b923e3afb223817c47c239e2fab45c8f
[ "BSD-3-Clause" ]
null
null
null
include/shacl/optional/Type/test/value_or.test.cpp
shacl/optional
02dc7ed2b923e3afb223817c47c239e2fab45c8f
[ "BSD-3-Clause" ]
null
null
null
#include "shacl/optional.hpp" #include "catch2/catch.hpp" SCENARIO("value_or"){ struct U { mutable bool copiedFrom = false; mutable bool movedFrom = false; }; struct T { mutable bool copiedFrom = false; mutable bool movedFrom = false; T() = default; T(T&& that) { that.movedFrom = true; } T& operator=(T&&) { return *this; } T(const T& that) { that.copiedFrom = true; } T(U&& that) { that.movedFrom = true; } T(const U& that) { that.copiedFrom = true; } }; auto ignore = [](auto&&){}; shacl::Optional<T> o; GIVEN("an optional const lvalue"){ const auto& co = o; GIVEN("the optional is engaged"){ o = T{}; GIVEN("an argument of the optional parameter type"){ auto arg = T{}; THEN("the value_or method should copy the stored value"){ auto t = co.value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE(co.value().copiedFrom); REQUIRE_FALSE(co.value().movedFrom); } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; THEN("the value_or method should copy the stored value"){ auto t = co.value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE(co.value().copiedFrom); REQUIRE_FALSE(co.value().movedFrom); } } } GIVEN("the optional is disengaged"){ GIVEN("an argument of the optional parameter type"){ auto arg = T{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = co.value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = co.value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = co.value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = co.value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } } } GIVEN("an optional mutable rvalue"){ GIVEN("the optional is engaged"){ o = T{}; GIVEN("an argument of the optional parameter type"){ auto arg = T{}; THEN("the value_or method should move the stored value"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE_FALSE(o.value().copiedFrom); REQUIRE(o.value().movedFrom); } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; THEN("the value_or method should move the stored value"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE_FALSE(o.value().copiedFrom); REQUIRE(o.value().movedFrom); } } } GIVEN("the optional is disengaged"){ GIVEN("an argument of the optional parameter type"){ auto arg = T{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = std::move(o).value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = std::move(o).value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } } } }
27.945946
70
0.543327
shacl
3c240845a9bb3630bf9d4c90d20c950b8293124f
2,283
cpp
C++
lib/duden/LdFile.cpp
nonwill/lsd2dsl
00e2a9832666dff03667b07815d73fab3fa8378e
[ "MIT" ]
66
2015-01-17T16:57:38.000Z
2022-02-06T15:29:54.000Z
lib/duden/LdFile.cpp
nonwill/lsd2dsl
00e2a9832666dff03667b07815d73fab3fa8378e
[ "MIT" ]
19
2015-02-08T15:35:12.000Z
2022-01-26T10:46:11.000Z
lib/duden/LdFile.cpp
nongeneric/lsd2dsl
4bf92b42b1ae47eee8e0b71bc04224dc037bd549
[ "MIT" ]
18
2015-03-23T07:06:07.000Z
2022-01-15T21:03:04.000Z
#include "LdFile.h" #include "Duden.h" #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> namespace duden { LdFile parseLdFile(dictlsd::IRandomAccessStream* stream) { LdFile ld; ld.references.push_back({"WEB", "Web", "W"}); std::string line; while (readLine(stream, line)) { boost::algorithm::trim(line); if (line.empty()) continue; line = win1252toUtf8(line); if (line[0] == 'G' || line[0] == 'g') { boost::smatch m; if (!boost::regex_match(line, m, boost::regex("^.(.*?)\\|(.*?)\\|(.*?)$"))) throw std::runtime_error("LD parsing error"); ld.references.push_back({m[1], m[2], m[3]}); } else if (line[0] == 'B') { ld.name = line.substr(1); } else if (line[0] == 'S') { ld.sourceLanguage = line.substr(1); } else if (line[0] == 'K') { ld.baseFileName = line.substr(1); } else if (line[0] == 'D') { boost::smatch m; if (!boost::regex_match(line, m, boost::regex("^D(.+?) (\\d+) (\\d+).*$"))) throw std::runtime_error("LD parsing error"); ld.ranges.push_back({m[1], static_cast<uint32_t>(std::stoul(m[2])), static_cast<uint32_t>(std::stoul(m[3]))}); } } return ld; } int dudenLangToCode(const std::string& lang) { if (lang == "deu") return 1031; if (lang == "enu") return 1033; if (lang == "fra") return 1036; if (lang == "esn") return 1034; if (lang == "ita") return 1040; if (lang == "rus") return 1049; return 0; } void updateLanguageCodes(std::vector<LdFile*> lds) { auto first = lds.at(0); auto second = lds.size() > 1 ? lds.at(1) : nullptr; auto firstSource = first->sourceLanguage; auto secondSource = second ? second->sourceLanguage : "deu"; first->sourceLanguageCode = dudenLangToCode(firstSource); first->targetLanguageCode = dudenLangToCode(secondSource); if (second) { second->sourceLanguageCode = dudenLangToCode(secondSource); second->targetLanguageCode = dudenLangToCode(firstSource); } } } // namespace duden
30.851351
87
0.536575
nonwill
3c2597efb9131b6c7f0c3995ad59971d945792c9
12,202
cpp
C++
Sources/Tools/EPI/Document/Properties/PtySky.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
Sources/Tools/EPI/Document/Properties/PtySky.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
Sources/Tools/EPI/Document/Properties/PtySky.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * 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. */ #include "PtySky.h" #include <QtToolbox/CollapsibleWidget.moc.h> #include <QtToolbox/SingleSlidingValue.moc.h> #include <QtToolbox/ColorPicker/QuickColorPicker.moc.h> #include <QtToolbox/ComboBox.moc.h> #include <Universe/World.h> #include <QGridLayout> #include <QCheckBox> #include <EPI/GUI/Widget/CustomLine.moc.h> namespace EPI { //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- PtySky::PtySky(const Ptr<Universe::World>& pWorld, const Core::String& title): PropertyNode(title, true, false, CONTENT), _skyTexture(pWorld->getSkyTexture()), _color(pWorld->getSkyColor()), _glow(pWorld->getSkyGlow()), _horizon(pWorld->getSkyHorizon()), _angle(pWorld->getSkyAngle()), _roof(pWorld->getSkyRoof()), _sphericity(pWorld->getSkySphericity()), _atInfinity(pWorld->getSkyAtInfinity()), _isProcedural(pWorld->isSkyProcedural()), _model(pWorld->getSkyModel()), _skyColor(pWorld->getSkyBackColor()), _sunColor(pWorld->getSkySunColor()), _intensity(pWorld->getSkySunIntensity()), _pWorld(pWorld) { updateProperty(); } //----------------------------------------------------------------------------- PtySky::~PtySky() { } //----------------------------------------------------------------------------- Ptr<PropertyWidget> PtySky::internalCreatePropertyWidget(const Ptr<PropertyWidgetDataProxy>& pDataProxy, QWidget * parent) { Ptr<PtyWidgetSky> pPW (new PtyWidgetSky(pDataProxy, parent)); return pPW; } //----------------------------------------------------------------------------- void PtySky::updateProperty() { _skyTexture = _pWorld->getSkyTexture(); _color = _pWorld->getSkyColor(); _glow = _pWorld->getSkyGlow(); _horizon = _pWorld->getSkyHorizon(); _angle = _pWorld->getSkyAngle(); _roof = _pWorld->getSkyRoof(); _sphericity = _pWorld->getSkySphericity(); _atInfinity = _pWorld->getSkyAtInfinity(); _isProcedural = _pWorld->isSkyProcedural(); _model = _pWorld->getSkyModel(); _skyColor = _pWorld->getSkyBackColor(); _sunColor = _pWorld->getSkySunColor(); _intensity = _pWorld->getSkySunIntensity(); } //----------------------------------------------------------------------------- void PtySky::updateData() { _pWorld->setSkyTexture(_skyTexture); _pWorld->setSkyColor(_color); _pWorld->setSkyGlow(_glow); _pWorld->setSkyHorizon(_horizon); _pWorld->setSkyAngle(_angle); _pWorld->setSkyRoof(_roof); _pWorld->setSkySphericity(_sphericity); _pWorld->setSkyAtInfinity(_atInfinity); _pWorld->setSkyProcedural(_isProcedural); _pWorld->setSkyModel(_model); _pWorld->setSkyBackColor(_skyColor); _pWorld->setSkySunColor(_sunColor); _pWorld->setSkySunIntensity(_intensity); } //----------------------------------------------------------------------------- Ptr<Property> PtySky::clone() const { return Ptr<Property>(new PtySky( *this )); } //----------------------------------------------------------------------------- void PtySky::internalCopy(const Ptr<Property>& pSrc) { Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(pSrc); _skyTexture = pPtySky->_skyTexture; _color = pPtySky->_color; _glow = pPtySky->_glow; _horizon = pPtySky->_horizon; _angle = pPtySky->_angle; _roof = pPtySky->_roof; _sphericity = pPtySky->_sphericity; _atInfinity = pPtySky->_atInfinity; _isProcedural = pPtySky->_isProcedural; _pWorld = pPtySky->_pWorld; _model = pPtySky->_model; _skyColor = pPtySky->_skyColor; _sunColor = pPtySky->_sunColor; _intensity = pPtySky->_intensity; updateData(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- PtyWidgetSky::PtyWidgetSky(const Ptr<PropertyWidgetDataProxy>& data, QWidget * parent): PropertyWidget(data, parent) { setupUi(); } //----------------------------------------------------------------------------- PtyWidgetSky::~PtyWidgetSky() { } //----------------------------------------------------------------------------- void PtyWidgetSky::setupUi() { _layout = new QGridLayout(this); _layout->setContentsMargins(0, 0, 0, 0); _layout->setAlignment(Qt::AlignTop | Qt::AlignLeft); _groupBox = new QtToolbox::CollapsibleWidget(this, "Sky", false); _groupBox->setStyle(QtToolbox::CW_TITLE_1); _groupBox->setAlignmentTitle(Qt::AlignCenter); QGridLayout* layoutGroupBox = new QGridLayout(NULL); layoutGroupBox->setContentsMargins(0, 0, 0, 0); _groupBox->setLayout(layoutGroupBox); _skyTexture = new CustomLine(_groupBox, "Texture"); _skyTexture->pushAuthorizedDropMimeData("asset/texture"); _skyTexture->setReadOnly(true); _color = new QtToolbox::QuickColorPicker(_groupBox, "Color", Qt::white, false); _glow = new QtToolbox::QuickColorPicker(_groupBox, "Glow", Qt::white, false); _horizon = new QtToolbox::SingleSlidingDouble(_groupBox, "Horizon", -1.0, 0.99); _angle = new QtToolbox::SingleSlidingDouble(_groupBox, "Angle", 0, Core::rad2deg(d_PI_MUL_2)); _roof = new QtToolbox::SingleSlidingDouble(_groupBox, "Roof", 0.0, 5000.0); _sphericity = new QtToolbox::SingleSlidingDouble(_groupBox, "Sphericity", 0.0, 1.0); _atInfinity = new QCheckBox("At infinity", _groupBox); _atInfinity->setChecked(true); _isProcedural = new QCheckBox("Is procedural", _groupBox); _isProcedural->setChecked(true); _model = new QtToolbox::ComboBox(_groupBox, "Model"); _skyColor = new QtToolbox::QuickColorPicker(_groupBox, "Sky color", Qt::white, false); _sunColor = new QtToolbox::QuickColorPicker(_groupBox, "Sun color", Qt::white, false); _intensity = new QtToolbox::SingleSlidingDouble(_groupBox, "Intensity", 1.0, 4.0); _model->addItem("Foggy"); _model->addItem("Cloudy"); _model->addItem("Clear sky"); layoutGroupBox->addWidget(_skyTexture, 0, 0, Qt::AlignCenter); layoutGroupBox->addWidget(_color, 1, 0, Qt::AlignCenter); layoutGroupBox->addWidget(_glow, 2, 0, Qt::AlignCenter); layoutGroupBox->addWidget(_horizon, 3, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_angle, 4, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_roof, 5, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_sphericity, 6, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_atInfinity, 7, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_isProcedural,8, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_model, 9, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_skyColor, 10, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_sunColor, 11, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_intensity, 12, 0, Qt::AlignLeft); _layout->addWidget(_groupBox); getWidgetsForUndoRedo().push_back(_skyTexture); getWidgetsForUndoRedo().push_back(_color); getWidgetsForUndoRedo().push_back(_glow); getWidgetsForUndoRedo().push_back(_horizon); getWidgetsForUndoRedo().push_back(_angle); getWidgetsForUndoRedo().push_back(_roof); getWidgetsForUndoRedo().push_back(_sphericity); getWidgetsForUndoRedo().push_back(_atInfinity); getWidgetsForUndoRedo().push_back(_isProcedural); getWidgetsForUndoRedo().push_back(_model); getWidgetsForUndoRedo().push_back(_skyColor); getWidgetsForUndoRedo().push_back(_sunColor); getWidgetsForUndoRedo().push_back(_intensity); PropertyWidget::setupUi(); } //----------------------------------------------------------------------------- void PtyWidgetSky::readProperty() { Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty()); _skyTexture->setText(Core::String8(pPtySky->_skyTexture).c_str()); _color->setColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a); _glow->setColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a); _horizon->setSingleValue(pPtySky->_horizon); _angle->setSingleValue(Core::rad2deg(pPtySky->_angle)); _roof->setSingleValue(pPtySky->_roof); _sphericity->setSingleValue(pPtySky->_sphericity); _atInfinity->setChecked(pPtySky->_atInfinity); _isProcedural->setChecked(pPtySky->_isProcedural); _skyColor->setColorLinear(pPtySky->_skyColor); _sunColor->setColorLinear(pPtySky->_sunColor); _model->selectIndex(int(pPtySky->_model)); _intensity->setSingleValue(pPtySky->_intensity); } //----------------------------------------------------------------------------- void PtyWidgetSky::writeProperty(QWidget* pWidget) { Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty()); pPtySky->_skyTexture = Core::String(_skyTexture->text().toStdString().c_str()); _color->getColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a); _glow->getColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a); _horizon->getSingleValue(pPtySky->_horizon); double angle = 0.0; _angle->getSingleValue(angle); pPtySky->_angle = Core::deg2rad(angle); _roof->getSingleValue(pPtySky->_roof); _sphericity->getSingleValue(pPtySky->_sphericity); pPtySky->_atInfinity = _atInfinity->isChecked(); pPtySky->_isProcedural = _isProcedural->isChecked(); _skyColor->getColorLinear(pPtySky->_skyColor); _sunColor->getColorLinear(pPtySky->_sunColor); pPtySky->_model = Renderer::ELightingModel(_model->selectedIndex()); _intensity->getSingleValue(pPtySky->_intensity); } //----------------------------------------------------------------------------- } // namespace EPI
46.572519
128
0.612523
benkaraban
3c27f69dfe490a67babef9a7a7bac0cf785a8b47
7,263
cpp
C++
GameItself/game.cpp
hcim38/PROJECT
7e4b4e2d8d2783b0c452463ccae00ff35d3594d5
[ "MIT" ]
null
null
null
GameItself/game.cpp
hcim38/PROJECT
7e4b4e2d8d2783b0c452463ccae00ff35d3594d5
[ "MIT" ]
null
null
null
GameItself/game.cpp
hcim38/PROJECT
7e4b4e2d8d2783b0c452463ccae00ff35d3594d5
[ "MIT" ]
null
null
null
#include "game.h" Game::Game() { qrTexturePtr = new QResource(":/Textures/Resources/hex-tex.png"); qrFontPtr = new QResource(":/Fonts/Resources/Lato-Regular.ttf"); texture.loadFromMemory(qrTexturePtr->data(), qrTexturePtr->size()); //lading resources font.loadFromMemory(qrFontPtr->data(), qrFontPtr->size()); delete qrTexturePtr; delete qrFontPtr; generateTemplate(); clickedAt = Tile(); } Game::Game(bool) : Game() { banner = Banner(sf::Vector2f(0, 640 - 32), sf::Vector2f(640, 32), font); } void Game::clicked(sf::Vector2i pos, std::vector<Player> &players, Tile &clickedAt) { for (auto &player : players) { for (auto &val : player.ownership()) { if (val.getGlobalBounds().contains(pos.x, pos.y)) { clickedAt = val; break; } } } } void Game::generateTemplate(sf::Vector2i tileSize, unsigned int mapSize) { std::vector<Tile> m_objects; for (int i = 0; i < mapSize; ++i) for (int j = 0; j < mapSize; ++j) { if (j % 2 == 0) { Tile temp(texture, tileSize, sf::Vector2f(i * tileSize.x * 2, 2 * j * tileSize.y)); temp.setUpTile(tileSize, sf::Vector2i(i, j), 0); m_objects.emplace_back(temp); } else { Tile temp(texture, tileSize, sf::Vector2f(i * tileSize.x * 2 + tileSize.x, 2 * j * tileSize.y)); temp.setUpTile(tileSize, sf::Vector2i(i, j), 1); m_objects.emplace_back(temp); } } for (auto &obj : m_objects) { obj.move(tileSize.x / 2, tileSize.y / 2); } MAP = m_objects; } std::vector<sf::VertexArray> Game::createLines(std::vector<Player> &players) { sf::VertexArray temp(sf::Lines, 2); std::vector<sf::VertexArray> vec; for (auto &playerM : players) { for (auto &tileOne : playerM.ownership()) { for (auto &player : players) { for (auto &tileTwo : player.ownership()) { if (tileOne.movePossible(tileTwo)) { temp[0].color = sf::Color(100, 100, 100, 50); temp[0].position = sf::Vector2f(tileOne.getGlobalBounds().left + (tileOne.getGlobalBounds().width / 2), tileOne.getGlobalBounds().top + (tileOne.getGlobalBounds().height / 2)); temp[1].color = sf::Color(100, 100, 100, 50); temp[1].position = sf::Vector2f(tileTwo.getGlobalBounds().left + (tileTwo.getGlobalBounds().width / 2), tileTwo.getGlobalBounds().top + (tileTwo.getGlobalBounds().height / 2)); vec.emplace_back(temp); } } } } } return vec; } void Game::nextTurn(unsigned long long &turn, std::vector<Player> &players) { turn++; if (turn >= players.size()) { turn = 1; } while (players[turn].ownership().size() == 0) { turn++; if (turn >= players.size()) { turn = 1; } } } void Game::gameLoop() { Lines = createLines(players); TilesOnScreen = MAP.size(); sf::RenderWindow window(sf::VideoMode(640, 640), "Tile Conqueror"); window.setFramerateLimit(60); window.setVerticalSyncEnabled(1); while (window.isOpen()) { //config complete, window created, game starts sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } if (event.type == event.MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left) { clicked(sf::Mouse::getPosition(window), players, clickedAt); } if (event.type == event.KeyReleased && event.key.code == sf::Keyboard::Space && !players[turn].AI()) { if (pointsGiveAway) { nextTurn(turn, players); pointsGiveAway = 0; //TODO if points left add 1 point from the remaining to every tile IF possible continue; } players[turn].clearOrigin(); pointsGiveAway = 1; pointsLeft = players[turn].ownership().size(); } //TODO add full value on PPM } window.clear(sf::Color::Black); for (auto &line : Lines) { window.draw(line); } for (auto &player : players) { player.textCorrection(); player.colorCorrection(); } if (!pointsGiveAway) { Turnmanager(players, clickedAt, turn); } else { players[turn].addPointsToTiles(clickedAt, pointsLeft); } players[turn].hilightOrigin(); clickedAt = Tile(); //// for (auto player : players) { for (auto val : player.ownership()) { val.drawMe(window, font); } } banner.refreshBanner(pointsLeft, players[turn], pointsGiveAway); banner.drawMe(window); window.display(); //koniec for (auto &player : players) { if (player.ownership().empty() && player.nickname() != "MAP") { playersEmpty++; } } if (TilesOnScreen == players[turn].ownership().size() || playersEmpty == players.size() - 2) //win condition winCondition++; if (winCondition >= 2) break; playersEmpty = 0; } ///Game ended window.close(); for (auto &player : players) { if (!player.ownership().empty() && player.nickname() != "MAP" && winCondition >= 2) { QMessageBox msg; msg.setText(QString::fromStdString(player.nickname()) + " has won the game"); msg.exec(); } } return; } void Game::loadMap(QString path, std::vector<Player> &NewPlayers) { players = NewPlayers; QFile file(path); file.open(QFile::ReadOnly); if (file.isOpen()) { std::vector<sf::Vector2i> deleted; QDataStream in(&file); QString str; int x, y; while (!in.atEnd()) { in >> x >> y; deleted.emplace_back(sf::Vector2i(x, y)); } file.close(); for (auto const &pos : deleted) { for (auto tile = MAP.begin(); tile != MAP.end(); tile++) { if (*tile == pos) { tile->setColor(sf::Color(255, 0, 0, 100)); MAP.erase(tile); tile--; continue; } } } } captureRandomTiles(MAP, players); } Game::~Game() {}
31.578261
100
0.480793
hcim38
3c286fa71809c84a909ccf9dd6e4c6cc960d524a
1,086
cpp
C++
Online Judges/SPOJ/RPLN - Negative Score/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/SPOJ/RPLN - Negative Score/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/SPOJ/RPLN - Negative Score/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> using namespace std; int v[100001], st[512345]; inline int goleft(int n) {return n << 1;} inline int goright(int n) {return (n << 1) + 1;} void build(int n, int s, int e) { if (s == e) { st[n] = v[s]; } else { int m = (s + e) >> 1; build(goleft(n), s, m); build(goright(n), m + 1, e); st[n] = min(st[goleft(n)], st[goright(n)]); } } int query(int n, int s, int e, int i, int j) { if (s > j || e < i) return 0x3f3f3f3f; if (i <= s && e <= j) return st[n]; int m = (s + e) >> 1; int l = query(goleft(n), s, m, i, j); int d = query(goright(n), m + 1, e, i, j); return min(l, d); } int main() { int t, n, q, a, b, x = 1; cin >> t; while(t--) { cin >> n >> q; for (int i = 0; i < n; i++) { cin >> v[i]; } build(1, 0, n - 1); cout << "Scenario #" << x++ << ":\n"; while(q--) { cin >> a >> b; cout << query(1, 0, n - 1, a - 1, b - 1) << endl; } } return 0; }
20.111111
61
0.402394
AnneLivia
3c293f244f4de113c85546bfd196752d3c6e8249
533
cpp
C++
Chapter 3. Strings, Vectors, and Arrays/Codes/3.35.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 3. Strings, Vectors, and Arrays/Codes/3.35.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 3. Strings, Vectors, and Arrays/Codes/3.35.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
1
2021-09-30T14:08:03.000Z
2021-09-30T14:08:03.000Z
#include <iostream> using std::cin; using std::cout; using std::iterator; using std::begin; using std::end; /** * Using pointers, write a program to set the elements in an array to zero. */ int main() { //Initialize a 10-length array. int arr[10]; //Use pointer to assign each value to zero. for (auto ptr = begin(arr); ptr != end(arr); ptr++) *ptr = 0; //Output each element's value. for (auto ptr = begin(arr); ptr != end(arr); ptr++) cout << *ptr << ' '; return 0; }
13.666667
75
0.577861
Yunxiang-Li
3c2b5e9d1e60c07c19c55545055d7daa9f6fd4dd
9,042
cpp
C++
NOLF/ClientShellDLL/LightningFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ClientShellDLL/LightningFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ClientShellDLL/LightningFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// ----------------------------------------------------------------------- // // // MODULE : LightningFX.cpp // // PURPOSE : Lightning special FX - Implementation // // CREATED : 4/15/99 // // (c) 1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "LightningFX.h" #include "iltclient.h" #include "SFXMgr.h" #include "iltcustomdraw.h" #include "GameClientShell.h" #include "DynamicLightFX.h" #include "GameButes.h" #include "VarTrack.h" // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Init // // PURPOSE: Init the lightning fx // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage) { if (!CSpecialFX::Init(hServObj, hMessage)) return LTFALSE; if (!hMessage) return LTFALSE; // Read in the init info from the message... LFXCREATESTRUCT lcs; lcs.hServerObj = hServObj; lcs.lfx.hServerObj = hServObj; g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vStartPos)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vEndPos)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.vLightColor)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vInnerColorStart)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vInnerColorEnd)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vOuterColorStart)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vOuterColorEnd)); lcs.lfx.fAlphaStart = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fAlphaEnd = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fMinWidth = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fMaxWidth = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fLifeTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fAlphaLifeTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fMinDelayTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fMaxDelayTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fPerturb = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fLightRadius = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fSoundRadius = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.nWidthStyle = g_pLTClient->ReadFromMessageByte(hMessage); lcs.lfx.nNumSegments = g_pLTClient->ReadFromMessageByte(hMessage); lcs.bOneTimeOnly = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.bDynamicLight = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.bPlaySound = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.lfx.bAdditive = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.lfx.bMultiply = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); m_hstrTexture = g_pLTClient->ReadFromMessageHString(hMessage); return Init(&lcs); } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Init // // PURPOSE: Init the lightning fx // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE; LFXCREATESTRUCT* pLFX = (LFXCREATESTRUCT*)psfxCreateStruct; m_cs = *pLFX; if (m_hstrTexture) { m_cs.lfx.pTexture = g_pLTClient->GetStringData(m_hstrTexture); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::CreateObject // // PURPOSE: Create object associated the object // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::CreateObject(ILTClient *pClientDE) { if (!CSpecialFX::CreateObject(pClientDE)) return LTFALSE; // Validate our init info... if (m_cs.lfx.nNumSegments < 1) return LTFALSE; // Get the thunder sound path if we need to play the sound... if (m_cs.bPlaySound) { m_csThunderStr = g_pClientButeMgr->GetWeatherAttributeString(WEATHER_BUTE_THUNDERSOUND); } // Set up the lightning... return Setup(); } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Setup // // PURPOSE: Setup the line used to draw lightning // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Setup() { // Figure out the position based on the object's current pos... if (m_hServerObject) { LTVector vPos; g_pLTClient->GetObjectPos(m_hServerObject, &vPos); m_cs.lfx.vStartPos = vPos; } // Create our poly-line for the lightning... if (m_Line.HasBeenDrawn()) { m_Line.ReInit(&m_cs.lfx); } else { m_Line.Init(&m_cs.lfx); m_Line.CreateObject(g_pLTClient); } // Figure out when to start/stop... LTFLOAT fTime = g_pLTClient->GetTime(); m_fStartTime = fTime + GetRandom(m_cs.fMinDelayTime, m_cs.fMaxDelayTime); m_fEndTime = m_fStartTime + m_cs.lfx.fLifeTime; // Calculate our mid point... LTVector vPos = m_cs.lfx.vStartPos; LTVector vDir = (m_cs.lfx.vEndPos - m_cs.lfx.vStartPos); float fDist = vDir.Mag(); float fTotalDist = fDist; vDir.Norm(); m_vMidPos = (m_cs.lfx.vStartPos + (vDir * fDist/2.0f)); // Create the dynamic light if necessary... if (m_cs.bDynamicLight && !m_hLight) { ObjectCreateStruct createStruct; INIT_OBJECTCREATESTRUCT(createStruct); createStruct.m_ObjectType = OT_LIGHT; createStruct.m_Flags = FLAG_DONTLIGHTBACKFACING; createStruct.m_Pos = m_vMidPos; m_hLight = m_pClientDE->CreateObject(&createStruct); if (!m_hLight) return LTFALSE; m_pClientDE->SetLightColor(m_hLight, m_cs.vLightColor.x/255.0f, m_cs.vLightColor.y/255.0f, m_cs.vLightColor.z/255.0f); m_pClientDE->SetLightRadius(m_hLight, m_cs.fLightRadius); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::HandleFirstTime // // PURPOSE: Handle the first time drawing... // // ----------------------------------------------------------------------- // void CLightningFX::HandleFirstTime() { if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags | FLAG_VISIBLE); } if (m_cs.bPlaySound) { float fWaitTime = 0.0f; m_fPlaySoundTime = g_pLTClient->GetTime() + fWaitTime; m_bPlayedSound = LTFALSE; } } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::UpdateSound // // PURPOSE: Handle playing the sound // // ----------------------------------------------------------------------- // void CLightningFX::UpdateSound() { if (m_bPlayedSound || !m_cs.bPlaySound || (m_csThunderStr.GetLength() < 1)) return; if (m_fPlaySoundTime <= g_pLTClient->GetTime()) { m_bPlayedSound = LTTRUE; g_pClientSoundMgr->PlaySoundFromPos(m_vMidPos, (char *)(LPCSTR)m_csThunderStr, m_cs.fSoundRadius, SOUNDPRIORITY_MISC_MEDIUM); } } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Update // // PURPOSE: Update the lightning // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Update() { if (m_bWantRemove) return LTFALSE; LTFLOAT fTime = g_pLTClient->GetTime(); // Hide/show lightning if necessary... if (m_hServerObject) { uint32 dwUserFlags; g_pLTClient->GetObjectUserFlags(m_hServerObject, &dwUserFlags); if (!(dwUserFlags & USRFLG_VISIBLE)) { m_Line.SetFlags(m_Line.GetFlags() & ~FLAG_VISIBLE); if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE); } return LTTRUE; } else { m_Line.SetFlags(m_Line.GetFlags() | FLAG_VISIBLE); } } m_Line.Update(); // See if it is time to act... if (fTime > m_fEndTime) { if (m_cs.bOneTimeOnly) { return LTFALSE; } else { Setup(); m_bFirstTime = LTTRUE; } } if (fTime < m_fStartTime) { m_Line.SetFlags(m_Line.GetFlags() & ~FLAG_VISIBLE); if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE); } return LTTRUE; // not yet... } else { m_Line.SetFlags(m_Line.GetFlags() | FLAG_VISIBLE); } // Do first time stuff... if (m_bFirstTime) { m_bFirstTime = LTFALSE; HandleFirstTime(); } else { if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE); } } // Update playing the sound... UpdateSound(); return LTTRUE; }
25.908309
90
0.603185
haekb
3c32c44ec2ae71806881e0bed2134d4330619d30
9,670
hpp
C++
security/L1/include/xf_security/msgpack.hpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-09-11T01:05:01.000Z
2021-09-11T01:05:01.000Z
security/L1/include/xf_security/msgpack.hpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
security/L1/include/xf_security/msgpack.hpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file aes.hpp * @brief header file for Advanced Encryption Standard relate function. * This file part of Vitis Security Library. * * @detail Currently we have Aes256_Encryption for AES256 standard. */ #ifndef _XF_SECURITY_MSG_PACK_HPP_ #define _XF_SECURITY_MSG_PACK_HPP_ #include <ap_int.h> #include <stdint.h> #include <hls_stream.h> #ifndef __SYNTHESIS__ #include <iostream> #endif namespace xf { namespace security { namespace internal { /** * @brief Base class of msg packer * * @tparam W Bit width of one row. Support 64, 128, 256, 512. */ template <int W> class packBase { public: int64_t msg_num; int64_t curr_ptr; // not in bytes, in rows int64_t buffer_size; // in bytes int64_t total_row; unsigned char* buffer_ptr; bool isReset; bool isMemAlloced; packBase() { #pragma HLS inline #ifndef __SYNTHESIS__ isReset = false; isMemAlloced = false; #endif } /** * @brief Reset records for packBase, need to be called each time a new pack to be process. reset function won't * release any alloced memory. Should only be used on host side. */ void reset() { msg_num = 0; if (W == 64) { curr_ptr = 2; } else if (W == 128) { curr_ptr = 1; } else if (W == 256) { curr_ptr = 1; } else if (W == 512) { curr_ptr = 1; } else { #ifndef __SYNTHESIS__ std::cout << W << " bits width of row is not supported. Only 64 / 128 / 256 / 512 is allowed." << std::endl; #endif } buffer_size = 0; buffer_ptr = nullptr; isReset = true; isMemAlloced = false; } /** * @brief Assign alloced memory to packBase to process. Should only be used on host side. * * @param ptr Pointer to allocated memory. * @size Size of allocated memory. */ void setPtr(unsigned char* ptr, int64_t size) { buffer_ptr = ptr; buffer_size = size; total_row = buffer_size / (W / 8); isMemAlloced = true; } /** * @brief Finish a pack by adding number of message and effective rows of pack. This funciton need to be called once * before send the package for processing. Should only be used on host side. * * @param ptr Pointer to allocated memory. * @size Size of allocated memory. */ void finishPack() { int64_t* header = (int64_t*)buffer_ptr; header[0] = msg_num; header[1] = curr_ptr; } }; /** * @brief Base class of msg packer. Bit width of one row is 128. * * @tparam KeyW Bit width of key, only support 128, 192, 256 */ template <int KeyW> class aesCbcPack : public packBase<128> { private: void scanRaw(ap_uint<128>* ddr, ap_uint<64> row_num, hls::stream<ap_uint<128> >& rawStrm) { for (ap_uint<64> i = 1; i < row_num; i++) { #pragma HLS pipeline II = 1 ap_uint<128> tmp = ddr[i]; rawStrm.write(tmp); } } void parsePack(ap_uint<64> msg_num, hls::stream<ap_uint<128> >& rawStrm, hls::stream<ap_uint<128> >& textStrm, hls::stream<bool>& endTextStrm, hls::stream<ap_uint<KeyW> >& keyStrm, hls::stream<ap_uint<128> >& IVStrm, hls::stream<ap_uint<64> >& lenStrm) { for (ap_uint<64> i = 0; i < msg_num; i++) { ap_uint<64> len = rawStrm.read(); ap_uint<128> iv = rawStrm.read(); ap_uint<128> keyL = rawStrm.read(); ap_uint<128> keyH = 0; ap_uint<KeyW> key = 0; if (KeyW > 128) { keyH = rawStrm.read(); } key.range(127, 0) = keyL; key.range(KeyW - 1, 128) = keyH.range(KeyW - 129, 0); keyStrm.write(key); IVStrm.write(iv); lenStrm.write(len); for (ap_uint<64> i = 0; i < len; i += 16) { #pragma HLS pipeline II = 1 textStrm.write(rawStrm.read()); endTextStrm.write(false); } endTextStrm.write(true); } } void writeRaw(ap_uint<128>* ddr, hls::stream<ap_uint<128> >& rawStrm, hls::stream<ap_uint<16> >& numRawStrm) { ap_uint<64> addr = 0; ap_uint<16> numRaw = numRawStrm.read(); while (numRaw != 0) { for (ap_uint<16> i = 0; i < numRaw; i++) { #pragma HLS pipeline II = 1 ddr[addr + i] = rawStrm.read(); } addr += numRaw; numRaw = numRawStrm.read(); } } void preparePack(ap_uint<64> msg_num, hls::stream<ap_uint<128> >& textStrm, hls::stream<bool>& endTextStrm, hls::stream<ap_uint<64> >& lenStrm, hls::stream<ap_uint<128> >& rawStrm, hls::stream<ap_uint<16> >& numRawStrm) { ap_uint<16> numRaw = 0; rawStrm.write(ap_uint<128>(msg_num)); numRaw++; for (ap_uint<64> i = 0; i < msg_num; i++) { rawStrm.write(ap_uint<128>(lenStrm.read())); numRaw++; if (numRaw == 64) { numRaw = 0; numRawStrm.write(ap_uint<16>(64)); } while (!endTextStrm.read()) { rawStrm.write(textStrm.read()); numRaw++; if (numRaw == 64) { numRaw = 0; numRawStrm.write(ap_uint<16>(64)); } } } if (numRaw != 0) { numRawStrm.write(numRaw); } numRawStrm.write(0); } public: aesCbcPack() { #pragma HLS inline } #ifndef __SYNTHESIS__ /** * @brief Add one message. * * @msg Pointer of message to be added. * @len Length of message to be added. * @iv Initialization vector of this message. * @key Encryption key * @return return true if successfully add message, other wise false. */ bool addOneMsg(unsigned char* msg, int64_t len, unsigned char* iv, unsigned char* key) { if (!isReset) { std::cout << "Not reset yet, please call reset()" << std::endl; return false; } if (!isMemAlloced) { std::cout << "Memory not alloced yet, please call setPtr()" << std::endl; return false; } int64_t row_inc = 1 + 1 + (len + 15) / 16; // 1 for len, 1 for iv, 1 or 2 for key, (len + 15) / 16 for msg; if (KeyW > 128) { row_inc += 2; } else { row_inc += 1; } if (curr_ptr + row_inc > total_row) { std::cout << "Memory left not enough to add one message" << std::endl; return false; } memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 16); *(int64_t*)(buffer_ptr + (curr_ptr * 16)) = len; curr_ptr++; memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 16); memcpy((void*)(buffer_ptr + (curr_ptr * 16)), (void*)iv, 16); curr_ptr++; if (KeyW > 128) { memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 32); } else { memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 16); } memcpy((void*)(buffer_ptr + (curr_ptr * 16)), (void*)key, KeyW / 8); if (KeyW > 128) { curr_ptr += 2; } else { curr_ptr += 1; } memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, (len + 15) / 16 * 16); memcpy((void*)(buffer_ptr + (curr_ptr * 16)), (void*)msg, len); curr_ptr += (len + 15) / 16; msg_num++; return true; } #endif void scanPack(ap_uint<128>* ddr, ap_uint<64> msg_num, ap_uint<64> row_num, hls::stream<ap_uint<128> >& textStrm, hls::stream<bool>& endTextStrm, hls::stream<ap_uint<KeyW> >& keyStrm, hls::stream<ap_uint<128> >& IVStrm, hls::stream<ap_uint<64> >& lenStrm) { #pragma HLS dataflow hls::stream<ap_uint<128> > rawStrm; #pragma HLS stream variable = rawStrm depth = 128 scanRaw(ddr, row_num, rawStrm); parsePack(msg_num, rawStrm, textStrm, endTextStrm, keyStrm, IVStrm, lenStrm); } void writeOutMsgPack(ap_uint<128>* ddr, ap_uint<64> msg_num, hls::stream<ap_uint<128> >& textStrm, hls::stream<bool>& endTextStrm, hls::stream<ap_uint<64> >& lenStrm) { #pragma HLS dataflow hls::stream<ap_uint<128> > rawStrm; #pragma HLS stream variable = rawStrm depth = 128 hls::stream<ap_uint<16> > numRawStrm; #pragma HLS stream variable = numRawStrm depth = 4 preparePack(msg_num, textStrm, endTextStrm, lenStrm, rawStrm, numRawStrm); writeRaw(ddr, rawStrm, numRawStrm); } }; } // namespace internal } // namespace security } // namespace xf #endif
31.396104
120
0.543744
vmayoral
3c332ee44712746f8ef25ff3dee54d2f18cec212
7,589
cpp
C++
.sandbox/hybrid-daes/dae-drumboiler/src/laws.cpp
vacary/siconos-tutorials
93c0158321077a313692ed52fed69ff3c256ae32
[ "Apache-2.0" ]
6
2017-01-12T23:09:28.000Z
2021-03-20T17:03:58.000Z
.sandbox/hybrid-daes/dae-drumboiler/src/laws.cpp
vacary/siconos-tutorials
93c0158321077a313692ed52fed69ff3c256ae32
[ "Apache-2.0" ]
3
2019-01-14T13:44:51.000Z
2021-05-17T13:57:27.000Z
.sandbox/hybrid-daes/dae-drumboiler/src/laws.cpp
vacary/siconos-tutorials
93c0158321077a313692ed52fed69ff3c256ae32
[ "Apache-2.0" ]
2
2019-10-22T13:30:39.000Z
2020-10-06T10:19:57.000Z
#include "laws_cst.hpp" #include "laws.hpp" double rhov(const double &P_, const double &T_) { return P_/(R*T_); } double rhovdP(const double &P_, const double &T_) { return 1/(R*T_); } double rhovdT(const double &P_, const double &T_) { return -P_/(R*pow(T_,2.0)); } /* Volumic mass of water -- */ double rhol(const double &P_, const double &T_) { return (-0.0025*(T_-273.156) - 0.1992)*(T_-273.156) + 1004.4; } double rholdP(const double &P_, const double &T_) { return 0; } double rholdT(const double &P_, const double &T_) { return (-2*0.0025*(T_-273.156) - 0.1992); } /* Specific enthalpy of vapor (J/kg) in fonction of Pressure (Pa) and Temperature (K) */ double h_v(const double &P_, const double &T_) { double c00 = 1.778741e+06; double c10 = -6.997339e-02; double c01 = 2.423675e+03; double c20 = 1.958603e-10; double c11 = 8.100784e-05; double c02 = -3.747139e-01; double c30 = -1.016123e-19; double c21 = -1.234548e-13; double c12 = -2.324528e-08; double c03 = 1.891004e-04; return c00 + c10*P_ + c01*T_ + c20*pow(P_,2.0) + c11*P_*T_ + c02*pow(T_,2.0) + c30*pow(P_,3.0) + c21*pow(P_,2.0)*T_ + c12*P_*pow(T_,2.0) + c03*pow(T_,3.0); } double h_vdP(const double &P_, const double &T_) { double c00 = 1.778741e+06; double c10 = -6.997339e-02; double c01 = 2.423675e+03; double c20 = 1.958603e-10; double c11 = 8.100784e-05; double c02 = -3.747139e-01; double c30 = -1.016123e-19; double c21 = -1.234548e-13; double c12 = -2.324528e-08; double c03 = 1.891004e-04; return c10 + c20*2.0*P_ + c11*T_ + c30*3.0*pow(P_,2.0) + c21*2.0*P_*T_ + c12*pow(T_,2.0); } double h_vdT(const double &P_, const double &T_) { double c00 = 1.778741e+06; double c10 = -6.997339e-02; double c01 = 2.423675e+03; double c20 = 1.958603e-10; double c11 = 8.100784e-05; double c02 = -3.747139e-01; double c30 = -1.016123e-19; double c21 = -1.234548e-13; double c12 = -2.324528e-08; double c03 = 1.891004e-04; return c01 + c11*P_ + c02*2.0*T_ + c21*pow(P_,2.0) + c12*P_*2.0*T_ + c03*3.0*pow(T_,2.0); } /* Specific enthalpy of liquid (J/kg) in fonction of Pressure (Pa) and Temperature (K) */ double h_l(const double &P_, const double &T_) { double c00 = -1.210342e+07; double c10 = 3.932901e-02; double c01 = 1.310565e+05; double c20 = -3.425284e-10; double c11 = -2.572281e-04; double c02 = -5.801243e+02; double c30 = 1.974339e-19; double c21 = 2.427381e-12; double c12 = 4.966543e-07; double c03 = 1.314839e+00; double c40 = -4.256626e-27; double c31 = 1.512868e-21; double c22 = -6.054694e-15; double c13 = -8.389491e-11; double c04 = -1.484055e-03; double c50 = 1.597043e-35; double c41 = 1.356624e-31; double c32 = -2.492294e-24; double c23 = 5.082575e-18; double c14 = -3.822957e-13; double c05 = 6.712484e-07; return c00 + c10*P_ + c01*T_ + c20*pow(P_,2.0) + c11*P_*T_ + c02*pow(T_,2.0) + c30*pow(P_,3.0) + c21*pow(P_,2.0)*T_ + c12*P_*pow(T_,2.0) + c03*pow(T_,3.0) + c40*pow(P_,4.0) + c31*pow(P_,3.0)*T_ + c22*pow(P_,2.0)*pow(T_,2.0) + c13*P_*pow(T_,3.0) + c04*pow(T_,4.0) + c50*pow(P_,5.0) + c41*pow(P_,4.0)*T_ + c32*pow(P_,3.0)*pow(T_,2.0) + c23*pow(P_,2.0)*pow(T_,3.0) + c14*P_*pow(T_,4.0) + c05*pow(T_,5.0); } double h_ldP(const double &P_, const double &T_) { double c00 = -1.210342e+07; double c10 = 3.932901e-02; double c01 = 1.310565e+05; double c20 = -3.425284e-10; double c11 = -2.572281e-04; double c02 = -5.801243e+02; double c30 = 1.974339e-19; double c21 = 2.427381e-12; double c12 = 4.966543e-07; double c03 = 1.314839e+00; double c40 = -4.256626e-27; double c31 = 1.512868e-21; double c22 = -6.054694e-15; double c13 = -8.389491e-11; double c04 = -1.484055e-03; double c50 = 1.597043e-35; double c41 = 1.356624e-31; double c32 = -2.492294e-24; double c23 = 5.082575e-18; double c14 = -3.822957e-13; double c05 = 6.712484e-07; return c10 + c20*2.0*P_ + c11*T_ + c30*3.0*pow(P_,2.0) + c21*2.0*P_*T_ + c12*pow(T_,2.0) + c40*4.0*pow(P_,3.0) + c31*3.0*pow(P_,2.0)*T_ + c22*2.0*P_*pow(T_,2.0) + c13*pow(T_,3.0) + c50*5.0*pow(P_,4.0) + c41*4.0*pow(P_,3.0)*T_ + c32*3.0*pow(P_,2.0)*pow(T_,2.0) + c23*2.0*P_*pow(T_,3.0) + c14*pow(T_,4.0); } double h_ldT(const double &P_, const double &T_) { double c00 = -1.210342e+07; double c10 = 3.932901e-02; double c01 = 1.310565e+05; double c20 = -3.425284e-10; double c11 = -2.572281e-04; double c02 = -5.801243e+02; double c30 = 1.974339e-19; double c21 = 2.427381e-12; double c12 = 4.966543e-07; double c03 = 1.314839e+00; double c40 = -4.256626e-27; double c31 = 1.512868e-21; double c22 = -6.054694e-15; double c13 = -8.389491e-11; double c04 = -1.484055e-03; double c50 = 1.597043e-35; double c41 = 1.356624e-31; double c32 = -2.492294e-24; double c23 = 5.082575e-18; double c14 = -3.822957e-13; double c05 = 6.712484e-07; return c01 + c11*P_ + c02*2.0*T_ + c21*pow(P_,2.0) + c12*P_*2.0*T_ + c03*3.0*pow(T_,2.0) + c31*pow(P_,3.0) + c22*pow(P_,2.0)*2.0*T_ + c13*P_*3.0*pow(T_,2.0) + c04*4.0*pow(T_,3.0) + c41*pow(P_,4.0) + c32*pow(P_,3.0)*2.0*T_ + c23*pow(P_,2.0)*3.0*pow(T_,2.0) + c14*P_*4.0*pow(T_,3.0) + c05*5.0*pow(T_,4.0); } /* Saturation pressure (Pa) in fonction of Temperature (K)*/ double psat(const double &T_) { double c7 = 7.677448367806697e-11; double c6 = -2.327974895639335e-07; double c5 = 2.984399245658974e-04; double c4 = -2.081210501212062e-01; double c3 = 8.527291155079814e+01; double c2 = -2.055993982138471e+04; double c1 = 2.704822454027627e+06; double c0 = -1.499284498173245e+08; return c0 + c1*T_ + c2*pow(T_,2.0) + c3*pow(T_,3.0) + c4*pow(T_,4.0) + c5*pow(T_,5.0) + c6*pow(T_,6.0) + c7*pow(T_,7.0); } double psatdT(const double &T_) { double c7=7.677448367806697e-11; double c6=-2.327974895639335e-07; double c5=2.984399245658974e-04; double c4=-2.081210501212062e-01; double c3=8.527291155079814e+01; double c2=-2.055993982138471e+04; double c1=2.704822454027627e+06; double c0=-1.499284498173245e+08; return c1 + 2.0*c2*T_ + 3.0*c3*pow(T_,2.0) + 4.0*c4*pow(T_,3.0) + 5.0*c5*pow(T_,4.0) + 6.0*c6*pow(T_,5.0) + 7.0*c7*pow(T_,6.0); } /* specific internal energy equation*/ double u(const double &P_, const double &h_, const double &r_) { return h_- P_/r_; } double udP(const double &P_, const double &h_, const double &r_){ return -1.0/r_; } double udh(const double &P_, const double &h_, const double &r_){ return 1.0; } double udr(const double &P_, const double &h_, const double &r_){ return P_/pow(r_,2.0); } /* volume equation */ double vol(const double &r_, const double &M_){ return M_/r_; } double voldr(const double &r_, const double &M_){ return -1.0*M_/pow(r_,2.0); } double voldM(const double &r_, const double &M_){ return 1.0/r_; }
29.877953
89
0.572012
vacary
3c33bdec27a201db0f4d26fab96d506c6bb9ea87
1,254
hpp
C++
libTupl/src/tupl/LargeKeyError.hpp
cojen/TuplNative
4a8fa2b90825fdfe8f563e910fa188f1ed851404
[ "Apache-2.0" ]
1
2016-07-15T14:50:58.000Z
2016-07-15T14:50:58.000Z
libTupl/src/tupl/LargeKeyError.hpp
cojen/TuplNative
4a8fa2b90825fdfe8f563e910fa188f1ed851404
[ "Apache-2.0" ]
null
null
null
libTupl/src/tupl/LargeKeyError.hpp
cojen/TuplNative
4a8fa2b90825fdfe8f563e910fa188f1ed851404
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2014 Brian S O'Neill * Copyright (C) 2014 Vishal Parakh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _TUPL_LARGEKEYEXCEPTION_HPP #define _TUPL_LARGEKEYEXCEPTION_HPP #include "DatabaseError.hpp" namespace tupl { /** * Thrown when a key is too large to fit into a page. Maximum key size is * defined as: {@code min(16383, (pageSize / 2) - 22)}. When using the default * page size of 4096 bytes, the maximum key size is 2026 bytes. * * @author Brian S O'Neill * @author Vishal Parakh */ class LargeKeyError: public DatabaseError { public: LargeKeyError(const size_t /* length */) { // FIXME: bubble up // super("Key is too large: " + length); } }; } #endif
28.5
78
0.699362
cojen
3c344f5483b92d3d53a547e37442984aaa53c74f
611
cpp
C++
UUT/Video/Image.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
UUT/Video/Image.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
UUT/Video/Image.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
#include "Image.h" namespace uut { UUT_OBJECT_IMPLEMENT(Image) {} Image::Image() : _data(nullptr) { } Image::~Image() { Destroy(); } bool Image::Create(const Vector2i& size) { if (_size == size) return true; Destroy(); _data = SDL_CreateRGBSurface(0, _size.x, _size.y, 32, 0, 0, 0, 0); return IsCreated(); } void Image::Destroy() { if (!IsCreated()) return; SDL_FreeSurface(_data); _data = nullptr; } bool Image::IsCreated() const { return _data != nullptr; } uintptr_t Image::GetInternalHandle() const { return reinterpret_cast<uintptr_t>(_data); } }
13
44
0.631751
kolyden
3c35a958121c6917278c070b6a48f025cdc27e77
1,559
cpp
C++
kernel/drivers/pic8042contr.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
4
2021-07-14T20:24:24.000Z
2021-07-16T06:49:48.000Z
kernel/drivers/pic8042contr.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
null
null
null
kernel/drivers/pic8042contr.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
null
null
null
#include "pic8042contr.hpp" #include "asm/asmstubs.hpp" #include "gloxor/modules.hpp" #include "system/logging.hpp" // everything is masked on startup static glox::picContext picCtx{0xFF, 0xFF}; namespace glox::pic { void sendEoiSlave() { outb(PIC2_COMMAND, PIC_EOI); } void sendEoiMaster() { outb(PIC1_COMMAND, PIC_EOI); } void remap(u8 offset1, u8 offset2) { unsigned char a1, a2; a1 = inb(PIC1_DATA); // save masks a2 = inb(PIC2_DATA); outb(PIC1_COMMAND, ICW1_INIT | ICW1_ICW4); // starts the initialization sequence (in cascade mode) ioWait(); outb(PIC2_COMMAND, ICW1_INIT | ICW1_ICW4); ioWait(); outb(PIC1_DATA, offset1); // ICW2: Master PIC vector offset ioWait(); outb(PIC2_DATA, offset2); // ICW2: Slave PIC vector offset ioWait(); outb(PIC1_DATA, 4); // ICW3: tell Master PIC that there is a slave PIC at IRQ2 (0000 0100) ioWait(); outb(PIC2_DATA, 2); // ICW3: tell Slave PIC its cascade identity (0000 0010) ioWait(); outb(PIC1_DATA, ICW4_8086); ioWait(); outb(PIC2_DATA, ICW4_8086); ioWait(); outb(PIC1_DATA, a1); // restore saved masks. outb(PIC2_DATA, a2); } void setMasterMask(u8 mask) { picCtx.masterMask &= mask; outb(PIC1_DATA, picCtx.masterMask); } void setSlaveMask(u8 mask) { picCtx.slaveMask &= mask; outb(PIC1_DATA, picCtx.slaveMask); } } // namespace glox::pic static void initPic() { glox::pic::remap(0x20, 0x28); gloxDebugLog("Initializing PIC\n"); // Mask all devices outb(PIC1_DATA, 0xFF); outb(PIC2_DATA, 0xFF); } initDriverCentralModule(initPic);
22.926471
100
0.6966
CarboSauce
3c3693c493f420216094c6039949a40685fac446
7,418
cpp
C++
src/effect/explosion.cpp
FreeAllegiance/AllegianceDX7
3955756dffea8e7e31d3a55fcf6184232b792195
[ "MIT" ]
76
2015-08-18T19:18:40.000Z
2022-01-08T12:47:22.000Z
src/effect/explosion.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
37
2015-08-14T22:44:12.000Z
2020-01-21T01:03:06.000Z
src/effect/explosion.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
42
2015-08-13T23:31:35.000Z
2022-03-17T02:20:26.000Z
#include "explosion.h" ////////////////////////////////////////////////////////////////////////////// // // ExplosionGeo // ////////////////////////////////////////////////////////////////////////////// class ExplosionGeoImpl : public ExplosionGeo { private: ////////////////////////////////////////////////////////////////////////////// // // Types // ////////////////////////////////////////////////////////////////////////////// class ExplosionData : IObject { public: TRef<AnimatedImage> m_pimage; Vector m_position; Vector m_dposition; float m_angle; float m_timeStart; float m_scale; }; class ShockwaveData : IObject { public: TRef<Image> m_pimageShockwave; Vector m_position; Vector m_dposition; Vector m_forward; Vector m_right; Color m_color; float m_timeStart; float m_scale; }; typedef TList<ExplosionData> ExplosionDataList; ////////////////////////////////////////////////////////////////////////////// // // Members // ////////////////////////////////////////////////////////////////////////////// TList<ShockwaveData> m_listShockwave; TVector<ExplosionDataList> m_vlistExplosion; ////////////////////////////////////////////////////////////////////////////// // // Value Members // ////////////////////////////////////////////////////////////////////////////// Number* GetTime() { return Number::Cast(GetChild(0)); } public: ExplosionGeoImpl(Number* ptime) : ExplosionGeo(ptime), m_vlistExplosion(24) { } ////////////////////////////////////////////////////////////////////////////// // // Methods // ////////////////////////////////////////////////////////////////////////////// void AddExplosion( const Vector& position, const Vector& forward, const Vector& right, const Vector& dposition, float radiusExplosion, float radiusShockWave, const Color& color, int countDecals, TVector<TRef<AnimatedImage> > vpimage, Image* pimageShockwave ) { // // Add the shockwave // if (pimageShockwave != NULL) { m_listShockwave.PushFront(); ShockwaveData& sdata = m_listShockwave.GetFront(); sdata.m_timeStart = GetTime()->GetValue(); sdata.m_pimageShockwave = pimageShockwave; sdata.m_color = color; sdata.m_position = position; sdata.m_dposition = dposition; sdata.m_scale = radiusShockWave; sdata.m_forward = forward; sdata.m_right = right; } // // Add the little explosions // int countImage = vpimage.GetCount(); int indexImage = 0; for (int index = 0; index < countDecals; index++) { ExplosionDataList& list = m_vlistExplosion.Get(index); list.PushFront(); ExplosionData& edata = list.GetFront(); edata.m_timeStart = GetTime()->GetValue() + index * 0.25f; edata.m_pimage = vpimage[indexImage]; edata.m_position = position + Vector::RandomPosition(radiusExplosion * 0.5f); edata.m_dposition = dposition; edata.m_angle = random(0, 2 * pi); edata.m_scale = radiusExplosion; indexImage++; if (indexImage >= countImage) { indexImage = 0; } } } ////////////////////////////////////////////////////////////////////////////// // // Value Methods // ////////////////////////////////////////////////////////////////////////////// ZString GetFunctionName() { return "ExplosionGeo"; } ////////////////////////////////////////////////////////////////////////////// // // Geometry Methods // ////////////////////////////////////////////////////////////////////////////// float RenderShockwaves(Context* pcontext) { float fill = 0; TList<ShockwaveData>::Iterator iter(m_listShockwave); while (!iter.End()) { ShockwaveData& sdata = iter.Value(); float time = GetTime()->GetValue() - sdata.m_timeStart; float bright = 1.0f - time * time; if (bright <= 0) { iter.Remove(); } else { float scale = time * sdata.m_scale; fill += pcontext->DrawDecal( sdata.m_pimageShockwave->GetSurface(), bright * sdata.m_color, sdata.m_position + time * sdata.m_dposition, scale * sdata.m_forward, scale * sdata.m_right, 0, 0 ); iter.Next(); } }; return fill; } float RenderExplosions( Context* pcontext, ExplosionDataList& list ) { float fill = 0; ExplosionDataList::Iterator iter(list); while (!iter.End()) { ExplosionData& edata = iter.Value(); float time = GetTime()->GetValue() - edata.m_timeStart; if (time >= 0) { int frame = (int)(time * 20.0f); if (frame >= edata.m_pimage->GetCount()) { iter.Remove(); continue; } else { fill += pcontext->DrawDecal( edata.m_pimage->GetSurface(frame), Color::White(), edata.m_position + time * edata.m_dposition, Vector::GetZero(), Vector::GetZero(), edata.m_scale, edata.m_angle ); } } iter.Next(); } return fill; } void Render(Context* pcontext) { float fill = 0; fill += RenderShockwaves(pcontext); int count = m_vlistExplosion.GetCount(); for (int index = 0; index < count; index++) { fill += RenderExplosions(pcontext, m_vlistExplosion.Get(index)); // // If we have passed the fill limit throw away the rest of the explosions // if (fill > 2.0f) { for (int index2 = index + 1; index2 < count; index2++) { m_vlistExplosion.Get(index2).SetEmpty(); } return; } } } }; ////////////////////////////////////////////////////////////////////////////// // // ExplosionGeo Factory // ////////////////////////////////////////////////////////////////////////////// TRef<ExplosionGeo> CreateExplosionGeo(Number* ptime) { return new ExplosionGeoImpl(ptime); }
29.553785
90
0.384201
FreeAllegiance
3c38182a5e9abea64fa191de9bb0c7e1b42dadfd
3,813
cc
C++
mediapipe/framework/deps/file_helpers.cc
dwayne45/mediapipe
731d2b95363d58f12acb29a6f8435ec33fe548d9
[ "Apache-2.0" ]
14
2020-01-23T15:21:28.000Z
2022-01-15T16:22:40.000Z
mediapipe/framework/deps/file_helpers.cc
dwayne45/mediapipe
731d2b95363d58f12acb29a6f8435ec33fe548d9
[ "Apache-2.0" ]
3
2020-06-04T13:17:46.000Z
2021-09-14T15:28:23.000Z
mediapipe/framework/deps/file_helpers.cc
dwayne45/mediapipe
731d2b95363d58f12acb29a6f8435ec33fe548d9
[ "Apache-2.0" ]
6
2019-11-21T02:16:23.000Z
2020-04-05T16:19:59.000Z
// Copyright 2019 The MediaPipe Authors. // // 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 "mediapipe/framework/deps/file_helpers.h" #include <dirent.h> #include <stdio.h> #include <sys/stat.h> #include <cerrno> #include "mediapipe/framework/deps/canonical_errors.h" #include "mediapipe/framework/deps/file_path.h" #include "mediapipe/framework/deps/status_builder.h" namespace mediapipe { namespace file { ::mediapipe::Status GetContents(absl::string_view file_name, std::string* output) { FILE* fp = fopen(file_name.data(), "r"); if (fp == NULL) { return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC) << "Can't find file: " << file_name; } output->clear(); while (!feof(fp)) { char buf[4096]; size_t ret = fread(buf, 1, 4096, fp); if (ret == 0 && ferror(fp)) { return ::mediapipe::InternalErrorBuilder(MEDIAPIPE_LOC) << "Error while reading file: " << file_name; } output->append(std::string(buf, ret)); } fclose(fp); return ::mediapipe::OkStatus(); } ::mediapipe::Status SetContents(absl::string_view file_name, absl::string_view content) { FILE* fp = fopen(file_name.data(), "w"); if (fp == NULL) { return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC) << "Can't open file: " << file_name; } fwrite(content.data(), sizeof(char), content.size(), fp); size_t ret = fclose(fp); if (ret == 0 && ferror(fp)) { return ::mediapipe::InternalErrorBuilder(MEDIAPIPE_LOC) << "Error while writing file: " << file_name; } return ::mediapipe::OkStatus(); } ::mediapipe::Status MatchInTopSubdirectories( const std::string& parent_directory, const std::string& file_name, std::vector<std::string>* results) { DIR* dir = opendir(parent_directory.c_str()); CHECK(dir); // Iterates through the parent direcotry. while (true) { struct dirent* dir_ent = readdir(dir); if (dir_ent == nullptr) { break; } if (std::string(dir_ent->d_name) == "." || std::string(dir_ent->d_name) == "..") { continue; } std::string subpath = JoinPath(parent_directory, std::string(dir_ent->d_name)); DIR* sub_dir = opendir(subpath.c_str()); // Iterates through the subdirecotry to find file matches. while (true) { struct dirent* dir_ent_2 = readdir(sub_dir); if (dir_ent_2 == nullptr) { break; } if (std::string(dir_ent_2->d_name) == "." || std::string(dir_ent_2->d_name) == "..") { continue; } if (absl::EndsWith(std::string(dir_ent_2->d_name), file_name)) { results->push_back(JoinPath(subpath, std::string(dir_ent_2->d_name))); } } closedir(sub_dir); } closedir(dir); return ::mediapipe::OkStatus(); } ::mediapipe::Status Exists(absl::string_view file_name) { struct stat buffer; int status; status = stat(file_name.data(), &buffer); if (status == 0) { return ::mediapipe::OkStatus(); } switch (errno) { case EACCES: return ::mediapipe::PermissionDeniedError("Insufficient permissions."); default: return ::mediapipe::NotFoundError("The path does not exist."); } } } // namespace file } // namespace mediapipe
31
78
0.643588
dwayne45
3c391e37b3ccae6920d4150b7551e4a237718801
1,664
hpp
C++
typed_python/PyPythonSubclassInstance.hpp
braxtonmckee/nativepython
5c64e91eb959fcd1c2c42655b40c7cceb3436f1d
[ "Apache-2.0" ]
7
2018-08-07T15:41:54.000Z
2019-02-19T12:47:57.000Z
typed_python/PyPythonSubclassInstance.hpp
braxtonmckee/nativepython
5c64e91eb959fcd1c2c42655b40c7cceb3436f1d
[ "Apache-2.0" ]
38
2018-10-17T13:37:46.000Z
2019-04-11T20:50:14.000Z
typed_python/PyPythonSubclassInstance.hpp
braxtonmckee/nativepython
5c64e91eb959fcd1c2c42655b40c7cceb3436f1d
[ "Apache-2.0" ]
4
2019-02-11T17:44:55.000Z
2019-03-20T07:38:18.000Z
#pragma once #include "PyInstance.hpp" class PyPythonSubclassInstance : public PyInstance { public: typedef PythonSubclass modeled_type; static void copyConstructFromPythonInstanceConcrete(PythonSubclass* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) { Type* argType = extractTypeFrom(pyRepresentation->ob_type); if (argType && argType == eltType) { eltType->getBaseType()->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr()); return; } if (argType && argType == eltType->getBaseType()) { eltType->getBaseType()->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr()); return; } PyInstance::copyConstructFromPythonInstanceConcrete(eltType, tgt, pyRepresentation, isExplicit); } PyObject* tp_getattr_concrete(PyObject* pyAttrName, const char* attrName) { return specializeForType((PyObject*)this, [&](auto& subtype) { return subtype.tp_getattr_concrete(pyAttrName, attrName); }, type()->getBaseType()); } static bool pyValCouldBeOfTypeConcrete(modeled_type* type, PyObject* pyRepresentation) { return true; } static void constructFromPythonArgumentsConcrete(Type* t, uint8_t* data, PyObject* args, PyObject* kwargs) { constructFromPythonArguments(data, (Type*)t->getBaseType(), args, kwargs); } Py_ssize_t mp_and_sq_length_concrete() { return specializeForTypeReturningSizeT((PyObject*)this, [&](auto& subtype) { return subtype.mp_and_sq_length_concrete(); }, type()->getBaseType()); } };
34.666667
145
0.680889
braxtonmckee
3c392fead2c793a0203aaeda00408eef499e15ab
1,623
cpp
C++
decoders/cpp/usage_inherited_types.cpp
lpsandaruwan/schema
1ee5cca5fa2733b216ed3fbd6ad5a59e8820565c
[ "MIT" ]
79
2019-02-19T10:16:04.000Z
2022-03-29T00:37:13.000Z
decoders/cpp/usage_inherited_types.cpp
lpsandaruwan/schema
1ee5cca5fa2733b216ed3fbd6ad5a59e8820565c
[ "MIT" ]
104
2019-03-31T20:01:02.000Z
2022-03-18T06:28:05.000Z
decoders/cpp/usage_inherited_types.cpp
lpsandaruwan/schema
1ee5cca5fa2733b216ed3fbd6ad5a59e8820565c
[ "MIT" ]
39
2019-04-01T02:24:59.000Z
2022-03-23T02:40:06.000Z
#include <iostream> #include "schema.h" #include "InheritedTypes.hpp" int main() { // const unsigned char encodedState[] = { 0, 0, 205, 244, 1, 1, 205, 32, 3, 193, 1, 0, 204, 200, 1, 205, 44, 1, 2, 166, 80, 108, 97, 121, 101, 114, 193, 2, 0, 100, 1, 204, 150, 2, 163, 66, 111, 116, 3, 204, 200, 193, 3, 213, 2, 3, 100, 193 }; const unsigned char encodedState[] = { 0, 0, 205, 244, 1, 1, 205, 32, 3, 193, 1, 0, 204, 200, 1, 205, 44, 1, 2, 166, 80, 108, 97, 121, 101, 114, 193, 2, 0, 100, 1, 204, 150, 2, 163, 66, 111, 116, 3, 204, 200, 193 }; InheritedTypes *p = new InheritedTypes(); std::cerr << "============ about to decode\n"; p->decode(encodedState, sizeof(encodedState) / sizeof(unsigned char)); std::cerr << "============ decoded ================================================================ \n"; std::cout << "state.entity.x = " << p->entity->x << std::endl; std::cout << "state.entity.y = " << p->entity->y << std::endl; std::cout << std::endl; std::cout << "state.player.name = " << p->player->name << std::endl; std::cout << "state.player.x = " << p->player->x << std::endl; std::cout << "state.player.y = " << p->player->y << std::endl; std::cout << std::endl; std::cout << "state.bot.name = " << p->bot->name << std::endl; std::cout << "state.bot.x = " << p->bot->x << std::endl; std::cout << "state.bot.y = " << p->bot->y << std::endl; std::cout << "state.bot.power = " << p->bot->power << std::endl; std::cout << std::endl; // std::cout << "state.any.power = " << p->any->power << std::endl; delete p; return 0; }
46.371429
246
0.510783
lpsandaruwan
3c3973b1261e81f56c154ba2a5ce46a351f7103b
8,561
cpp
C++
exa_test/test/buffered_stream_test.cpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
exa_test/test/buffered_stream_test.cpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
exa_test/test/buffered_stream_test.cpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
#include <pch.h> #include <exa/buffered_stream.hpp> #include <exa/memory_stream.hpp> #include <exa/concepts.hpp> using namespace exa; using namespace testing; using namespace std::chrono_literals; namespace { auto create_stream(std::shared_ptr<stream> s = std::make_shared<memory_stream>(), std::streamsize bs = 4096) { return std::make_shared<buffered_stream>(s, bs); } auto create_data(size_t size = 1000) { std::vector<uint8_t> v(size, 0); for (size_t i = 0; i < size; ++i) { v[i] = static_cast<uint8_t>(i); } return v; } struct test_stream : public memory_stream { bool seekable = true; bool writable = true; bool readable = true; virtual bool can_seek() const override { return seekable; } virtual bool can_write() const override { return writable; } virtual bool can_read() const override { return readable; } }; struct concurrent_stream : public memory_stream, public lockable<std::mutex> { virtual void write(gsl::span<const uint8_t> b) override { exa::lock(*this, [&] { memory_stream::write(b); }); } virtual std::streamsize read(gsl::span<uint8_t> b) override { std::streamsize r = 0; exa::lock(*this, [&] { r = memory_stream::read(b); }); return r; } }; struct throw_stream : public memory_stream { virtual void write(gsl::span<const uint8_t> b) override { throw std::runtime_error("Operation not allowed."); } virtual std::streamsize read(gsl::span<uint8_t> b) override { throw std::runtime_error("Operation not allowed."); } virtual void flush() override { throw std::runtime_error("Operation not allowed."); } virtual std::streamoff seek(std::streamoff offset, seek_origin origin) override { throw std::runtime_error("Operation not allowed."); } }; struct tracking_stream : public stream { virtual ~tracking_stream() = default; mutable struct { int can_read = 0; int can_seek = 0; int can_write = 0; int size = 0; int position = 0; int flush = 0; int read = 0; int seek = 0; int write = 0; } called; std::shared_ptr<stream> stream; tracking_stream(std::shared_ptr<exa::stream> s) { stream = s; } // Inherited via stream virtual bool can_read() const override { called.can_read += 1; return stream->can_read(); } virtual bool can_seek() const override { called.can_seek += 1; return stream->can_seek(); } virtual bool can_write() const override { called.can_write += 1; return stream->can_write(); } virtual std::streamsize size() const override { called.size += 1; return stream->size(); } virtual void size(std::streamsize value) override { called.size += 1; stream->size(); } virtual std::streamoff position() const override { called.position += 1; return stream->position(); } virtual void position(std::streamoff value) override { called.position += 1; stream->position(); } virtual void flush() override { called.flush += 1; stream->flush(); } virtual std::streamsize read(gsl::span<uint8_t> buffer) override { called.read += 1; return stream->read(buffer); } virtual std::streamoff seek(std::streamoff offset, seek_origin origin) override { called.seek += 1; return stream->seek(offset, origin); } virtual void write(gsl::span<const uint8_t> buffer) override { called.write += 1; stream->write(buffer); } }; } TEST(buffered_stream_test, concurrent_operations_are_serialized) { auto v = create_data(); auto inner = std::make_shared<concurrent_stream>(); auto s = create_stream(inner, 1); std::array<std::future<void>, 4> tasks; for (size_t i = 0; i < tasks.size(); ++i) { tasks[i] = s->write_async(gsl::span<uint8_t>(v.data() + 250 * i, 250)); } for (auto& t : tasks) { ASSERT_NO_THROW(t.get()); } s->position(0); for (size_t i = 0; i < tasks.size(); ++i) { auto b = s->read_byte(); ASSERT_TRUE(b == i || b == static_cast<uint8_t>(i + 250) || b == static_cast<uint8_t>(i + 500) || b == static_cast<uint8_t>(i + 750)); } } TEST(buffered_stream_test, underlying_stream_throws_exception) { auto s = create_stream(std::make_shared<throw_stream>()); std::vector<uint8_t> v1(1); std::vector<uint8_t> v2(10000); ASSERT_THROW(s->read_async(v1).get(), std::runtime_error); ASSERT_THROW(s->write_async(v2).get(), std::runtime_error); s->write_byte(1); ASSERT_THROW(s->flush_async().get(), std::runtime_error); } TEST(buffered_stream_test, copy_to_requires_flushing_of_writes) { for (auto async : {false, true}) { auto s = create_stream(); auto v = create_data(); auto d = std::make_shared<memory_stream>(); s->write(v); s->position(0); v[0] = 42; s->write_byte(42); d->write_byte(42); if (async) { s->copy_to_async(d).get(); } else { s->copy_to(d); } auto r = d->to_array(); ASSERT_THAT(r, ContainerEq(v)); } } TEST(buffered_stream_test, copy_to_read_before_copy_copies_all_data) { std::vector<std::pair<bool, bool>> data = {{false, false}, {false, true}, {true, false}, {true, true}}; for (auto input : data) { auto v = create_data(); auto ts = std::make_shared<test_stream>(); ts->write(v); ts->position(0); ts->seekable = input.first; auto src = create_stream(ts, 100); src->read_byte(); auto dst = std::make_shared<memory_stream>(); if (input.second) { src->copy_to_async(dst).get(); } else { src->copy_to(dst); } std::vector<uint8_t> expected(v.size() - 1); std::copy(std::next(std::begin(v), 1), std::end(v), std::begin(expected)); auto array = dst->to_array(); ASSERT_THAT(array, ContainerEq(expected)); } } TEST(buffered_stream_test, should_not_flush_underyling_stream_if_readonly) { for (auto can_seek : {true, false}) { auto underlying = std::make_shared<test_stream>(); underlying->write(create_data(123)); underlying->position(0); underlying->seekable = can_seek; underlying->writable = false; auto tracker = std::make_shared<tracking_stream>(underlying); auto s = create_stream(tracker); s->read_byte(); s->flush(); ASSERT_THAT(tracker->called.flush, Eq(0)); s->flush_async().get(); ASSERT_THAT(tracker->called.flush, Eq(0)); } } TEST(buffered_stream_test, should_always_flush_underlying_stream_if_writable) { std::vector<std::pair<bool, bool>> v = {{true, true}, {true, false}, {false, true}, {false, false}}; for (auto input : v) { auto underlying = std::make_shared<test_stream>(); underlying->write(create_data(123)); underlying->position(0); underlying->readable = input.first; underlying->seekable = input.second; underlying->writable = true; auto tracker = std::make_shared<tracking_stream>(underlying); auto s = create_stream(tracker); s->flush(); ASSERT_THAT(tracker->called.flush, Eq(1)); s->flush_async().get(); ASSERT_THAT(tracker->called.flush, Eq(2)); s->write_byte(42); s->flush(); ASSERT_THAT(tracker->called.flush, Eq(3)); s->flush_async().get(); ASSERT_THAT(tracker->called.flush, Eq(4)); } }
25.479167
112
0.546665
chronos38
3c3a1262bdaffaba4318e26b3970727e030dc12e
22,108
cpp
C++
samples/utils/CommandLineUtils.cpp
awslabs/aws-iot-device-sdk-cpp-v2
b90ff7d9d324508f789bbce855e12787aec3ff6b
[ "Apache-2.0" ]
11
2019-03-14T06:20:44.000Z
2019-10-14T21:55:17.000Z
samples/utils/CommandLineUtils.cpp
awslabs/aws-iot-device-sdk-cpp-v2
b90ff7d9d324508f789bbce855e12787aec3ff6b
[ "Apache-2.0" ]
50
2019-02-22T08:34:49.000Z
2019-11-21T03:44:11.000Z
samples/utils/CommandLineUtils.cpp
awslabs/aws-iot-device-sdk-cpp-v2
b90ff7d9d324508f789bbce855e12787aec3ff6b
[ "Apache-2.0" ]
7
2019-02-28T17:32:18.000Z
2019-09-27T18:02:46.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include "CommandLineUtils.h" #include <aws/crt/Api.h> #include <aws/crt/Types.h> #include <aws/crt/auth/Credentials.h> #include <aws/crt/io/Pkcs11.h> #include <iostream> namespace Utils { CommandLineUtils::CommandLineUtils() { // Automatically register the help command RegisterCommand(m_cmd_help, "", "Prints this message"); } void CommandLineUtils::RegisterProgramName(Aws::Crt::String newProgramName) { m_programName = std::move(newProgramName); } void CommandLineUtils::RegisterCommand(CommandLineOption option) { if (m_registeredCommands.count(option.m_commandName)) { fprintf(stdout, "Cannot register command: %s: Command already registered!", option.m_commandName.c_str()); return; } m_registeredCommands.insert({option.m_commandName, option}); } void CommandLineUtils::RegisterCommand( Aws::Crt::String commandName, Aws::Crt::String exampleInput, Aws::Crt::String helpOutput) { RegisterCommand(CommandLineOption(commandName, exampleInput, helpOutput)); } void CommandLineUtils::RemoveCommand(Aws::Crt::String commandName) { if (m_registeredCommands.count(commandName)) { m_registeredCommands.erase(commandName); } } void CommandLineUtils::UpdateCommandHelp(Aws::Crt::String commandName, Aws::Crt::String newCommandHelp) { if (m_registeredCommands.count(commandName)) { m_registeredCommands.at(commandName).m_helpOutput = std::move(newCommandHelp); } } void CommandLineUtils::SendArguments(const char **argv, const char **argc) { if (m_beginPosition != nullptr || m_endPosition != nullptr) { fprintf(stdout, "Arguments already sent!"); return; } m_beginPosition = argv; m_endPosition = argc; // Automatically check and print the help message if the help command is present if (HasCommand(m_cmd_help)) { PrintHelp(); exit(-1); } } bool CommandLineUtils::HasCommand(Aws::Crt::String command) { return std::find(m_beginPosition, m_endPosition, "--" + command) != m_endPosition; } Aws::Crt::String CommandLineUtils::GetCommand(Aws::Crt::String command) { const char **itr = std::find(m_beginPosition, m_endPosition, "--" + command); if (itr != m_endPosition && ++itr != m_endPosition) { return Aws::Crt::String(*itr); } return ""; } Aws::Crt::String CommandLineUtils::GetCommandOrDefault(Aws::Crt::String command, Aws::Crt::String commandDefault) { if (HasCommand(command)) { return Aws::Crt::String(GetCommand(command)); } return commandDefault; } Aws::Crt::String CommandLineUtils::GetCommandRequired( Aws::Crt::String command, Aws::Crt::String optionalAdditionalMessage) { if (HasCommand(command)) { return GetCommand(command); } PrintHelp(); fprintf(stderr, "Missing required argument: --%s\n", command.c_str()); if (optionalAdditionalMessage != "") { fprintf(stderr, "%s\n", optionalAdditionalMessage.c_str()); } exit(-1); } void CommandLineUtils::PrintHelp() { fprintf(stdout, "Usage:\n"); fprintf(stdout, "%s", m_programName.c_str()); for (auto const &pair : m_registeredCommands) { fprintf(stdout, " --%s %s", pair.first.c_str(), pair.second.m_exampleInput.c_str()); } fprintf(stdout, "\n\n"); for (auto const &pair : m_registeredCommands) { fprintf(stdout, "* %s:\t\t%s\n", pair.first.c_str(), pair.second.m_helpOutput.c_str()); } fprintf(stdout, "\n"); } void CommandLineUtils::AddCommonMQTTCommands() { RegisterCommand(m_cmd_endpoint, "<str>", "The endpoint of the mqtt server not including a port."); RegisterCommand( m_cmd_ca_file, "<path>", "Path to AmazonRootCA1.pem (optional, system trust store used by default)."); } void CommandLineUtils::AddCommonProxyCommands() { RegisterCommand(m_cmd_proxy_host, "<str>", "Host name of the proxy server to connect through (optional)"); RegisterCommand( m_cmd_proxy_port, "<int>", "Port of the proxy server to connect through (optional, default='8080'"); } void CommandLineUtils::AddCommonX509Commands() { RegisterCommand( m_cmd_x509_role, "<str>", "Role alias to use with the x509 credentials provider (required for x509)"); RegisterCommand(m_cmd_x509_endpoint, "<str>", "Endpoint to fetch x509 credentials from (required for x509)"); RegisterCommand( m_cmd_x509_thing_name, "<str>", "Thing name to fetch x509 credentials on behalf of (required for x509)"); RegisterCommand( m_cmd_x509_cert_file, "<path>", "Path to the IoT thing certificate used in fetching x509 credentials (required for x509)"); RegisterCommand( m_cmd_x509_key_file, "<path>", "Path to the IoT thing private key used in fetching x509 credentials (required for x509)"); RegisterCommand( m_cmd_x509_ca_file, "<path>", "Path to the root certificate used in fetching x509 credentials (required for x509)"); } void CommandLineUtils::AddCommonTopicMessageCommands() { RegisterCommand( m_cmd_message, "<str>", "The message to send in the payload (optional, default='Hello world!')"); RegisterCommand(m_cmd_topic, "<str>", "Topic to publish, subscribe to. (optional, default='test/topic')"); } void CommandLineUtils::AddCommonCustomAuthorizerCommands() { RegisterCommand( m_cmd_custom_auth_username, "<str>", "The name to send when connecting through the custom authorizer (optional)"); RegisterCommand( m_cmd_custom_auth_authorizer_name, "<str>", "The name of the custom authorizer to connect to (optional but required for everything but custom " "domains)"); RegisterCommand( m_cmd_custom_auth_authorizer_signature, "<str>", "The signature to send when connecting through a custom authorizer (optional)"); RegisterCommand( m_cmd_custom_auth_password, "<str>", "The password to send when connecting through a custom authorizer (optional)"); } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildPKCS11MQTTConnection( Aws::Iot::MqttClient *client) { std::shared_ptr<Aws::Crt::Io::Pkcs11Lib> pkcs11Lib = Aws::Crt::Io::Pkcs11Lib::Create(GetCommandRequired(m_cmd_pkcs11_lib)); if (!pkcs11Lib) { fprintf(stderr, "Pkcs11Lib failed: %s\n", Aws::Crt::ErrorDebugString(Aws::Crt::LastError())); exit(-1); } Aws::Crt::Io::TlsContextPkcs11Options pkcs11Options(pkcs11Lib); pkcs11Options.SetCertificateFilePath(GetCommandRequired(m_cmd_cert_file)); pkcs11Options.SetUserPin(GetCommandRequired(m_cmd_pkcs11_pin)); if (HasCommand(m_cmd_pkcs11_token)) { pkcs11Options.SetTokenLabel(GetCommand(m_cmd_pkcs11_token)); } if (HasCommand(m_cmd_pkcs11_slot)) { uint64_t slotId = std::stoull(GetCommand(m_cmd_pkcs11_slot).c_str()); pkcs11Options.SetSlotId(slotId); } if (HasCommand(m_cmd_pkcs11_key)) { pkcs11Options.SetPrivateKeyObjectLabel(GetCommand(m_cmd_pkcs11_key)); } Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder(pkcs11Options); if (!clientConfigBuilder) { fprintf( stderr, "MqttClientConnectionConfigBuilder failed: %s\n", Aws::Crt::ErrorDebugString(Aws::Crt::LastError())); exit(-1); } if (HasCommand(m_cmd_ca_file)) { clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str()); } if (HasCommand(m_cmd_port_override)) { int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str()); if (tmp_port > 0 && tmp_port < UINT16_MAX) { clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port)); } } clientConfigBuilder.WithEndpoint(GetCommandRequired(m_cmd_endpoint)); return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder); } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildWebsocketX509MQTTConnection( Aws::Iot::MqttClient *client) { Aws::Crt::Io::TlsContext x509TlsCtx; Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder; std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider> provider = nullptr; Aws::Crt::Io::TlsContextOptions tlsCtxOptions = Aws::Crt::Io::TlsContextOptions::InitClientWithMtls( GetCommandRequired(m_cmd_x509_cert_file).c_str(), GetCommandRequired(m_cmd_x509_key_file).c_str()); if (!tlsCtxOptions) { fprintf( stderr, "Unable to initialize tls context options, error: %s!\n", Aws::Crt::ErrorDebugString(tlsCtxOptions.LastError())); exit(-1); } if (HasCommand(m_cmd_x509_ca_file)) { tlsCtxOptions.OverrideDefaultTrustStore(nullptr, GetCommand(m_cmd_x509_ca_file).c_str()); } x509TlsCtx = Aws::Crt::Io::TlsContext(tlsCtxOptions, Aws::Crt::Io::TlsMode::CLIENT); if (!x509TlsCtx) { fprintf( stderr, "Unable to create tls context, error: %s!\n", Aws::Crt::ErrorDebugString(x509TlsCtx.GetInitializationError())); exit(-1); } Aws::Crt::Auth::CredentialsProviderX509Config x509Config; x509Config.TlsOptions = x509TlsCtx.NewConnectionOptions(); if (!x509Config.TlsOptions) { fprintf( stderr, "Unable to create tls options from tls context, error: %s!\n", Aws::Crt::ErrorDebugString(x509Config.TlsOptions.LastError())); exit(-1); } x509Config.Endpoint = GetCommandRequired(m_cmd_x509_endpoint); x509Config.RoleAlias = GetCommandRequired(m_cmd_x509_role); x509Config.ThingName = GetCommandRequired(m_cmd_x509_thing_name); Aws::Crt::Http::HttpClientConnectionProxyOptions proxyOptions; if (HasCommand(m_cmd_proxy_host)) { proxyOptions = GetProxyOptionsForMQTTConnection(); x509Config.ProxyOptions = proxyOptions; } provider = Aws::Crt::Auth::CredentialsProvider::CreateCredentialsProviderX509(x509Config); if (!provider) { fprintf(stderr, "Failure to create credentials provider!\n"); exit(-1); } Aws::Iot::WebsocketConfig config(GetCommandRequired(m_cmd_signing_region), provider); clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder(config); if (HasCommand(m_cmd_ca_file)) { clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str()); } if (HasCommand(m_cmd_proxy_host)) { clientConfigBuilder.WithHttpProxyOptions(proxyOptions); } if (HasCommand(m_cmd_port_override)) { int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str()); if (tmp_port > 0 && tmp_port < UINT16_MAX) { clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port)); } } clientConfigBuilder.WithEndpoint(GetCommandRequired(m_cmd_endpoint)); return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder); } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildWebsocketMQTTConnection( Aws::Iot::MqttClient *client) { Aws::Crt::Io::TlsContext x509TlsCtx; Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder; std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider> provider = nullptr; Aws::Crt::Auth::CredentialsProviderChainDefaultConfig defaultConfig; provider = Aws::Crt::Auth::CredentialsProvider::CreateCredentialsProviderChainDefault(defaultConfig); if (!provider) { fprintf(stderr, "Failure to create credentials provider!\n"); exit(-1); } Aws::Iot::WebsocketConfig config(GetCommandRequired(m_cmd_signing_region), provider); clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder(config); if (HasCommand(m_cmd_ca_file)) { clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str()); } if (HasCommand(m_cmd_proxy_host)) { clientConfigBuilder.WithHttpProxyOptions(GetProxyOptionsForMQTTConnection()); } if (HasCommand(m_cmd_port_override)) { int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str()); if (tmp_port > 0 && tmp_port < UINT16_MAX) { clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port)); } } clientConfigBuilder.WithEndpoint(GetCommandRequired(m_cmd_endpoint)); return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder); } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildDirectMQTTConnection( Aws::Iot::MqttClient *client) { Aws::Crt::String certificatePath = GetCommandRequired(m_cmd_cert_file); Aws::Crt::String keyPath = GetCommandRequired(m_cmd_key_file); Aws::Crt::String endpoint = GetCommandRequired(m_cmd_endpoint); auto clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder(certificatePath.c_str(), keyPath.c_str()); clientConfigBuilder.WithEndpoint(endpoint); if (HasCommand(m_cmd_ca_file)) { clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str()); } if (HasCommand(m_cmd_proxy_host)) { clientConfigBuilder.WithHttpProxyOptions(GetProxyOptionsForMQTTConnection()); } if (HasCommand(m_cmd_port_override)) { int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str()); if (tmp_port > 0 && tmp_port < UINT16_MAX) { clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port)); } } return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder); } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildDirectMQTTConnectionWithCustomAuthorizer( Aws::Iot::MqttClient *client) { Aws::Crt::String auth_username = GetCommandOrDefault(m_cmd_custom_auth_username, ""); Aws::Crt::String auth_authorizer_name = GetCommandOrDefault(m_cmd_custom_auth_authorizer_name, ""); Aws::Crt::String auth_authorizer_signature = GetCommandOrDefault(m_cmd_custom_auth_authorizer_signature, ""); Aws::Crt::String auth_password = GetCommandOrDefault(m_cmd_custom_auth_password, ""); Aws::Crt::String endpoint = GetCommandRequired(m_cmd_endpoint); auto clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder::NewDefaultBuilder(); clientConfigBuilder.WithEndpoint(endpoint); clientConfigBuilder.WithCustomAuthorizer( auth_username, auth_authorizer_name, auth_authorizer_signature, auth_password); return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder); } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildMQTTConnection() { if (!m_internal_client) { m_internal_client = Aws::Iot::MqttClient(); if (!m_internal_client) { fprintf( stderr, "MQTT Client Creation failed with error %s\n", Aws::Crt::ErrorDebugString(m_internal_client.LastError())); exit(-1); } } if (HasCommand(m_cmd_pkcs11_lib)) { return BuildPKCS11MQTTConnection(&m_internal_client); } else if (HasCommand(m_cmd_signing_region)) { if (HasCommand(m_cmd_x509_endpoint)) { return BuildWebsocketX509MQTTConnection(&m_internal_client); } else { return BuildWebsocketMQTTConnection(&m_internal_client); } } else if (HasCommand(m_cmd_custom_auth_authorizer_name)) { return BuildDirectMQTTConnectionWithCustomAuthorizer(&m_internal_client); } else { return BuildDirectMQTTConnection(&m_internal_client); } } Aws::Crt::Http::HttpClientConnectionProxyOptions CommandLineUtils::GetProxyOptionsForMQTTConnection() { Aws::Crt::Http::HttpClientConnectionProxyOptions proxyOptions; proxyOptions.HostName = GetCommand(m_cmd_proxy_host); int ProxyPort = atoi(GetCommandOrDefault(m_cmd_proxy_port, "8080").c_str()); if (ProxyPort > 0 && ProxyPort < UINT16_MAX) { proxyOptions.Port = static_cast<uint16_t>(ProxyPort); } else { proxyOptions.Port = 8080; } proxyOptions.AuthType = Aws::Crt::Http::AwsHttpProxyAuthenticationType::None; return proxyOptions; } std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::GetClientConnectionForMQTTConnection( Aws::Iot::MqttClient *client, Aws::Iot::MqttClientConnectionConfigBuilder *clientConfigBuilder) { auto clientConfig = clientConfigBuilder->Build(); if (!clientConfig) { fprintf( stderr, "Client Configuration initialization failed with error %s\n", Aws::Crt::ErrorDebugString(clientConfig.LastError())); exit(-1); } auto connection = client->NewConnection(clientConfig); if (!*connection) { fprintf( stderr, "MQTT Connection Creation failed with error %s\n", Aws::Crt::ErrorDebugString(connection->LastError())); exit(-1); } return connection; } void CommandLineUtils::SampleConnectAndDisconnect( std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> connection, Aws::Crt::String clientId) { /* * In a real world application you probably don't want to enforce synchronous behavior * but this is a sample console application, so we'll just do that with a condition variable. */ std::promise<bool> connectionCompletedPromise; std::promise<void> connectionClosedPromise; /* * This will execute when an mqtt connect has completed or failed. */ auto onConnectionCompleted = [&](Aws::Crt::Mqtt::MqttConnection &, int errorCode, Aws::Crt::Mqtt::ReturnCode returnCode, bool) { if (errorCode) { fprintf(stdout, "Connection failed with error %s\n", Aws::Crt::ErrorDebugString(errorCode)); connectionCompletedPromise.set_value(false); } else { fprintf(stdout, "Connection completed with return code %d\n", returnCode); connectionCompletedPromise.set_value(true); } }; auto onInterrupted = [&](Aws::Crt::Mqtt::MqttConnection &, int error) { fprintf(stdout, "Connection interrupted with error %s\n", Aws::Crt::ErrorDebugString(error)); }; auto onResumed = [&](Aws::Crt::Mqtt::MqttConnection &, Aws::Crt::Mqtt::ReturnCode, bool) { fprintf(stdout, "Connection resumed\n"); }; /* * Invoked when a disconnect message has completed. */ auto onDisconnect = [&](Aws::Crt::Mqtt::MqttConnection &) { fprintf(stdout, "Disconnect completed\n"); connectionClosedPromise.set_value(); }; connection->OnConnectionCompleted = std::move(onConnectionCompleted); connection->OnDisconnect = std::move(onDisconnect); connection->OnConnectionInterrupted = std::move(onInterrupted); connection->OnConnectionResumed = std::move(onResumed); /* * Actually perform the connect dance. */ fprintf(stdout, "Connecting...\n"); if (!connection->Connect(clientId.c_str(), false /*cleanSession*/, 1000 /*keepAliveTimeSecs*/)) { fprintf( stderr, "MQTT Connection failed with error %s\n", Aws::Crt::ErrorDebugString(connection->LastError())); exit(-1); } // wait for the OnConnectionCompleted callback to fire, which sets connectionCompletedPromise... if (connectionCompletedPromise.get_future().get() == false) { fprintf(stderr, "Connection failed\n"); exit(-1); } /* Disconnect */ if (connection->Disconnect()) { connectionClosedPromise.get_future().wait(); } } } // namespace Utils
37.407783
119
0.621766
awslabs
3c3ea285eee4612a46df66a02a478785d4f434aa
6,721
cpp
C++
ccore/tst/utest-pam_build.cpp
JosephChataignon/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
1,013
2015-01-26T19:50:14.000Z
2022-03-31T07:38:48.000Z
ccore/tst/utest-pam_build.cpp
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
542
2015-01-20T16:44:32.000Z
2022-01-29T14:57:20.000Z
ccore/tst/utest-pam_build.cpp
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
262
2015-03-19T07:28:12.000Z
2022-03-30T07:28:24.000Z
/*! @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause */ #include <gtest/gtest.h> #include "answer.hpp" #include "samples.hpp" #include <pyclustering/cluster/pam_build.hpp> #include <pyclustering/utils/metric.hpp> using namespace pyclustering; using namespace pyclustering::clst; using namespace pyclustering::utils::metric; void template_pam_build_medoids(const dataset_ptr & p_data, const std::size_t p_amount, const medoids & p_expected, const data_t p_data_type, const distance_metric<point> & p_metric = distance_metric_factory<point>::euclidean_square()) { dataset data; if (p_data_type == data_t::POINTS) { data = *p_data; } else { distance_matrix(*p_data, data); } medoids medoids; pam_build(p_amount, p_metric).initialize(data, p_data_type, medoids); ASSERT_EQ(p_amount, medoids.size()); ASSERT_EQ(p_expected, medoids); } TEST(utest_pam_build, correct_medoids_simple_01) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_simple_01_distance_matrix) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX); } TEST(utest_pam_build, correct_medoids_simple_01_wrong_amount_1) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1, { 4 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_simple_01_wrong_amount_3) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 3, { 4, 8, 0 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_simple_01_wrong_amount_10) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 10, { 4, 8, 0, 9, 1, 7, 6, 5, 2, 3 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_simple_01_metrics) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::euclidean_square()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::euclidean()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::manhattan()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::chebyshev()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::minkowski(2.0)); } TEST(utest_pam_build, correct_medoids_simple_01_metrics_distance_matrix) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::euclidean_square()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::euclidean()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::manhattan()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::chebyshev()); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::minkowski(2.0)); } TEST(utest_pam_build, correct_medoids_simple_02) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_02), 3, { 3, 20, 14 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_simple_03) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_03), 4, { 28, 56, 5, 34 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_simple_04) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_04), 5, { 44, 7, 64, 25, 55 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_one_dimensional) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 2, { 0, 20 }, data_t::POINTS); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 1, { 0 }, data_t::POINTS); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 3, { 0, 20, 1 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_one_dimensional_distance_matrix) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 2, { 0, 20 }, data_t::DISTANCE_MATRIX); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 1, { 0 }, data_t::DISTANCE_MATRIX); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 3, { 0, 20, 1 }, data_t::DISTANCE_MATRIX); } TEST(utest_pam_build, correct_medoids_three_dimensional) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 2, { 15, 4 }, data_t::POINTS); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 1, { 15 }, data_t::POINTS); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 3, { 15, 4, 14 }, data_t::POINTS); } TEST(utest_pam_build, correct_medoids_three_dimensional_distance_matrix) { template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 2, { 15, 4 }, data_t::DISTANCE_MATRIX); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 1, { 15 }, data_t::DISTANCE_MATRIX); template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 3, { 15, 4, 14 }, data_t::DISTANCE_MATRIX); }
51.305344
193
0.759262
JosephChataignon
3c3f2dde1f8342c3664ec27b6acfdc460b0eb57d
379
cpp
C++
library/Methods/Geometry/distance_ss.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
127
2019-07-22T03:52:01.000Z
2022-03-11T07:20:21.000Z
library/Methods/Geometry/distance_ss.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
39
2019-09-16T12:04:53.000Z
2022-03-29T15:43:35.000Z
library/Methods/Geometry/distance_ss.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
29
2019-08-10T11:27:06.000Z
2022-03-11T07:02:43.000Z
#include "segment.cpp" #include "is_intersect_ss.cpp" #include "distance_sp.cpp" namespace geometry { // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D Real distance_ss(const Segment &a, const Segment &b) { if(is_intersect_ss(a, b)) return 0; return min({distance_sp(a, b.a), distance_sp(a, b.b), distance_sp(b, a.a), distance_sp(b, a.b)}); } }
29.153846
101
0.69657
sarafanshul
3c3f48f5f69d21fe79384a6f66533aee53ece3f7
1,725
inl
C++
AllGames/base/share_data/default_init_zip/shader/tech_textchannel-3.inl
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
4
2019-11-08T00:15:13.000Z
2021-03-26T13:34:50.000Z
AllGames/base/share_data/default_init_zip/shader/tech_textchannel-3.inl
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
4
2021-03-13T10:26:09.000Z
2021-03-13T10:45:35.000Z
AllGames/base/share_data/default_init_zip/shader/tech_textchannel-3.inl
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
3
2020-06-01T01:53:05.000Z
2021-03-21T03:51:33.000Z
/*[DirectX9]*/ matrix MVP; int filterMin = 2; int filterMag = 2; int filterMip = 2; texture texture1; float4 textChannel; sampler sampler1 = sampler_state { Texture = <texture1>; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; }; struct VInput{ float4 Pos : POSITION; float3 Normal : Normal; float4 Color : COLOR0; float2 uv : TEXCOORD0; }; struct VOutput{ float4 Pos : POSITION; float2 uv : TEXCOORD0; float4 Color : TEXCOORD1; float3 channel : TEXCOORD2; }; VOutput Vshader(VInput input) { VOutput output; output.Pos = mul(input.Pos, MVP); output.Color = input.Color; output.uv = input.uv; output.channel = input.Normal; return output; } float4 Pshader(VOutput output) : COLOR0 { float4 ret = output.Color; float3 temp = tex2D(sampler1, output.uv).xyz;// * output.channel; float f = (temp.x + temp.y + temp.z); ret.xyz *= f; ret.a *= f; return ret; } technique main { pass P { VertexShader = compile vs_2_0 Vshader(); PixelShader = compile ps_2_0 Pshader(); } } /*[/DirectX9]*/ /*[OpenglES_Vertex]*/ //attribute in attribute vec4 inPosition; attribute vec2 inTexcoord; attribute vec4 inColor; // uniform mat4 MVP; varying vec2 passCoord; varying vec4 passColor0; void main() { passCoord = inTexcoord; passColor0 = vec4(inColor.b, inColor.g, inColor.r, inColor.a); gl_Position = MVP * inPosition; } /*[/OpenglES_Vertex]*/ /*[OpenglES_Pixel]*/ precision lowp float; varying vec4 passColor0; varying vec2 passCoord; uniform sampler2D texture1; uniform vec3 textChannel; void main() { vec3 v = texture2D(texture1, passCoord).xyz * textChannel; float f = (v.x+v.y+v.z); gl_FragColor = vec4(f*passColor0.xyz, f*passColor0.a*255.0); } /*[/OpenglES_Pixel]*/
19.827586
66
0.70087
DexianZhao
3c40b4a1cf4875babafc9fe982bfa08186acd959
806
cpp
C++
q10082v2.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
1
2018-03-19T05:18:49.000Z
2018-03-19T05:18:49.000Z
q10082v2.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
null
null
null
q10082v2.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
null
null
null
//q10082v2.cpp - 2011/09/09 //10082 - WERTYU //accepted at //run time = 0.012 #include <stdio.h> #include <string.h> using namespace std; int main(){ char ch[]={'`','1','2','3','4','5','6','7','8','9','0','-','=', 'Q','W','E','R','T','Y','U','I','O','P','[',']','\\', 'A','S','D','F','G','H','J','K','L',';','\'', 'Z','X','C','V','B','N','M',',','.','/'}; int maxLeng = 0; char inputChar[10000] = {0}; int i = 0, j = 0; while(gets(inputChar)!=NULL){ maxLeng = strlen(inputChar); for(i=0;i<maxLeng;i++){ if(inputChar[i]==' '){ printf(" "); }else{ for(j=0;j<strlen(ch);j++){ if(inputChar[i]==ch[j]){ printf("%c", ch[j-1]); break; } } } } printf("\n"); } return 0; }
23.028571
70
0.398263
abraxaslee
3c4215beae3902cf23ca9156ad3823a7fb9aec69
12,800
cpp
C++
src/goto-symex/build_goto_trace.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
1
2017-07-25T02:44:56.000Z
2017-07-25T02:44:56.000Z
src/goto-symex/build_goto_trace.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
1
2017-02-22T14:35:19.000Z
2017-02-27T08:49:58.000Z
src/goto-symex/build_goto_trace.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
4
2019-01-19T03:32:21.000Z
2021-12-20T14:25:19.000Z
/*******************************************************************\ Module: Traces of GOTO Programs Author: Daniel Kroening Date: July 2005 \*******************************************************************/ #include <cassert> #include <util/threeval.h> #include <util/simplify_expr.h> #include <util/arith_tools.h> #include <solvers/prop/prop_conv.h> #include <solvers/prop/prop.h> #include "partial_order_concurrency.h" #include "build_goto_trace.h" /*******************************************************************\ Function: build_full_lhs_rec Inputs: Outputs: Purpose: \*******************************************************************/ exprt build_full_lhs_rec( const prop_convt &prop_conv, const namespacet &ns, const exprt &src_original, // original identifiers const exprt &src_ssa) // renamed identifiers { if(src_ssa.id()!=src_original.id()) return src_original; const irep_idt id=src_original.id(); if(id==ID_index) { // get index value from src_ssa exprt index_value=prop_conv.get(to_index_expr(src_ssa).index()); if(index_value.is_not_nil()) { simplify(index_value, ns); index_exprt tmp=to_index_expr(src_original); tmp.index()=index_value; tmp.array()= build_full_lhs_rec(prop_conv, ns, to_index_expr(src_original).array(), to_index_expr(src_ssa).array()); return tmp; } return src_original; } else if(id==ID_member) { member_exprt tmp=to_member_expr(src_original); tmp.struct_op()=build_full_lhs_rec( prop_conv, ns, to_member_expr(src_original).struct_op(), to_member_expr(src_ssa).struct_op()); } else if(id==ID_if) { if_exprt tmp2=to_if_expr(src_original); tmp2.false_case()=build_full_lhs_rec(prop_conv, ns, tmp2.false_case(), to_if_expr(src_ssa).false_case()); tmp2.true_case()=build_full_lhs_rec(prop_conv, ns, tmp2.true_case(), to_if_expr(src_ssa).true_case()); exprt tmp=prop_conv.get(to_if_expr(src_ssa).cond()); if(tmp.is_true()) return tmp2.true_case(); else if(tmp.is_false()) return tmp2.false_case(); else return tmp2; } else if(id==ID_typecast) { typecast_exprt tmp=to_typecast_expr(src_original); tmp.op()=build_full_lhs_rec(prop_conv, ns, to_typecast_expr(src_original).op(), to_typecast_expr(src_ssa).op()); return tmp; } else if(id==ID_byte_extract_little_endian || id==ID_byte_extract_big_endian) { exprt tmp=src_original; assert(tmp.operands().size()==2); tmp.op0()=build_full_lhs_rec(prop_conv, ns, tmp.op0(), src_ssa.op0()); // re-write into big case-split } return src_original; } /*******************************************************************\ Function: adjust_lhs_object Inputs: Outputs: Purpose: \*******************************************************************/ exprt adjust_lhs_object( const prop_convt &prop_conv, const namespacet &ns, const exprt &src) { return nil_exprt(); } /*******************************************************************\ Function: build_goto_trace Inputs: Outputs: Purpose: \*******************************************************************/ void build_goto_trace_backup( const symex_target_equationt &target, const prop_convt &prop_conv, const namespacet &ns, goto_tracet &goto_trace) { // We need to re-sort the steps according to their clock. // Furthermore, read-events need to occur before write // events with the same clock. typedef std::map<mp_integer, goto_tracet::stepst> time_mapt; time_mapt time_map; mp_integer current_time=0; for(symex_target_equationt::SSA_stepst::const_iterator it=target.SSA_steps.begin(); it!=target.SSA_steps.end(); it++) { const symex_target_equationt::SSA_stept &SSA_step=*it; if(prop_conv.l_get(SSA_step.guard_literal)!=tvt(true)) continue; if(it->is_constraint() || it->is_spawn()) continue; else if(it->is_atomic_begin()) { // for atomic sections the timing can only be determined once we see // a shared read or write (if there is none, the time will be // reverted to the time before entering the atomic section); we thus // use a temporary negative time slot to gather all events current_time*=-1; continue; } else if(it->is_shared_read() || it->is_shared_write() || it->is_atomic_end()) { mp_integer time_before=current_time; if(it->is_shared_read() || it->is_shared_write()) { // these are just used to get the time stamp exprt clock_value=prop_conv.get( symbol_exprt(partial_order_concurrencyt::rw_clock_id(it))); to_integer(clock_value, current_time); } else if(it->is_atomic_end() && current_time<0) current_time*=-1; assert(current_time>=0); // move any steps gathered in an atomic section if(time_before<0) { time_mapt::iterator entry= time_map.insert(std::make_pair( current_time, goto_tracet::stepst())).first; entry->second.splice(entry->second.end(), time_map[time_before]); time_map.erase(time_before); } continue; } // drop hidden assignments if(it->is_assignment() && SSA_step.assignment_type!=symex_target_equationt::STATE) continue; goto_tracet::stepst &steps=time_map[current_time]; steps.push_back(goto_trace_stept()); goto_trace_stept &goto_trace_step=steps.back(); goto_trace_step.thread_nr=SSA_step.source.thread_nr; goto_trace_step.pc=SSA_step.source.pc; goto_trace_step.comment=SSA_step.comment; goto_trace_step.lhs_object=SSA_step.original_lhs_object; goto_trace_step.type=SSA_step.type; goto_trace_step.format_string=SSA_step.format_string; goto_trace_step.io_id=SSA_step.io_id; goto_trace_step.formatted=SSA_step.formatted; goto_trace_step.identifier=SSA_step.identifier; if(SSA_step.original_full_lhs.is_not_nil()) goto_trace_step.full_lhs= build_full_lhs_rec( prop_conv, ns, SSA_step.original_full_lhs, SSA_step.ssa_full_lhs); if(SSA_step.ssa_lhs.is_not_nil()) goto_trace_step.lhs_object_value=prop_conv.get(SSA_step.ssa_lhs); if(SSA_step.ssa_full_lhs.is_not_nil()) { goto_trace_step.full_lhs_value=prop_conv.get(SSA_step.ssa_full_lhs); simplify(goto_trace_step.full_lhs_value, ns); } for(std::list<exprt>::const_iterator j=SSA_step.converted_io_args.begin(); j!=SSA_step.converted_io_args.end(); j++) { const exprt &arg=*j; if(arg.is_constant() || arg.id()==ID_string_constant) goto_trace_step.io_args.push_back(arg); else { exprt tmp=prop_conv.get(arg); goto_trace_step.io_args.push_back(tmp); } } if(SSA_step.is_assert() || SSA_step.is_assume()) { goto_trace_step.cond_expr=SSA_step.cond_expr; goto_trace_step.cond_value= prop_conv.l_get(SSA_step.cond_literal).is_true(); } else if(SSA_step.is_location() && SSA_step.source.pc->is_goto()) { goto_trace_step.cond_expr=SSA_step.source.pc->guard; const bool backwards=SSA_step.source.pc->is_backwards_goto(); symex_target_equationt::SSA_stepst::const_iterator next=it; ++next; assert(next!=target.SSA_steps.end()); // goto was taken if backwards and next is enabled or forward // and next is not active; // there is an ambiguity here if a forward goto is to the next // instruction, which we simply ignore for now goto_trace_step.goto_taken= backwards== (prop_conv.l_get(next->guard_literal)==tvt(true)); } } // Now assemble into a single goto_trace. // This expoits sorted-ness of the map. for(time_mapt::iterator t_it=time_map.begin(); t_it!=time_map.end(); t_it++) { goto_trace.steps.splice(goto_trace.steps.end(), t_it->second); } // produce the step numbers unsigned step_nr=0; for(goto_tracet::stepst::iterator s_it=goto_trace.steps.begin(); s_it!=goto_trace.steps.end(); s_it++) s_it->step_nr=++step_nr; // Now delete anything after failed assertion for(goto_tracet::stepst::iterator s_it1=goto_trace.steps.begin(); s_it1!=goto_trace.steps.end(); s_it1++) if(s_it1->is_assert() && !s_it1->cond_value) { s_it1++; for(goto_tracet::stepst::iterator s_it2=s_it1; s_it2!=goto_trace.steps.end(); s_it2=goto_trace.steps.erase(s_it2)); break; } } /*******************************************************************\ Function: build_goto_trace Inputs: Outputs: Purpose: \*******************************************************************/ void build_goto_trace( const symex_target_equationt &target, const prop_convt &prop_conv, const namespacet &ns, goto_tracet &goto_trace) { // We need to re-sort the steps according to their clock. // Furthermore, read-events need to occur before write // events with the same clock. for(symex_target_equationt::SSA_stepst::const_iterator it=target.SSA_steps.begin(); it!=target.SSA_steps.end(); it++) { const symex_target_equationt::SSA_stept &SSA_step=*it; if(prop_conv.l_get(SSA_step.guard_literal)!=tvt(true)) continue; if(it->is_constraint() || it->is_spawn()) continue; // drop hidden assignments if(it->is_assignment() && SSA_step.assignment_type!=symex_target_equationt::STATE) continue; goto_tracet::stepst &steps=goto_trace.steps; steps.push_back(goto_trace_stept()); goto_trace_stept &goto_trace_step=steps.back(); goto_trace_step.thread_nr=SSA_step.source.thread_nr; goto_trace_step.pc=SSA_step.source.pc; goto_trace_step.comment=SSA_step.comment; goto_trace_step.lhs_object=SSA_step.original_lhs_object; goto_trace_step.type=SSA_step.type; goto_trace_step.format_string=SSA_step.format_string; goto_trace_step.io_id=SSA_step.io_id; goto_trace_step.formatted=SSA_step.formatted; goto_trace_step.identifier=SSA_step.identifier; if(SSA_step.original_full_lhs.is_not_nil()) goto_trace_step.full_lhs= build_full_lhs_rec( prop_conv, ns, SSA_step.original_full_lhs, SSA_step.ssa_full_lhs); if(SSA_step.ssa_lhs.is_not_nil()) goto_trace_step.lhs_object_value=prop_conv.get(SSA_step.ssa_lhs); if(SSA_step.ssa_full_lhs.is_not_nil()) { goto_trace_step.full_lhs_value=prop_conv.get(SSA_step.ssa_full_lhs); simplify(goto_trace_step.full_lhs_value, ns); } for(std::list<exprt>::const_iterator j=SSA_step.converted_io_args.begin(); j!=SSA_step.converted_io_args.end(); j++) { const exprt &arg=*j; if(arg.is_constant() || arg.id()==ID_string_constant) goto_trace_step.io_args.push_back(arg); else { exprt tmp=prop_conv.get(arg); goto_trace_step.io_args.push_back(tmp); } } if(SSA_step.is_assert() || SSA_step.is_assume()) { goto_trace_step.cond_expr=SSA_step.cond_expr; goto_trace_step.cond_value= prop_conv.l_get(SSA_step.cond_literal).is_true(); } else if(SSA_step.is_location() && SSA_step.source.pc->is_goto()) { goto_trace_step.cond_expr=SSA_step.source.pc->guard; const bool backwards=SSA_step.source.pc->is_backwards_goto(); symex_target_equationt::SSA_stepst::const_iterator next=it; ++next; assert(next!=target.SSA_steps.end()); // goto was taken if backwards and next is enabled or forward // and next is not active; // there is an ambiguity here if a forward goto is to the next // instruction, which we simply ignore for now goto_trace_step.goto_taken= backwards== (prop_conv.l_get(next->guard_literal)==tvt(true)); } } // produce the step numbers unsigned step_nr=0; for(goto_tracet::stepst::iterator s_it=goto_trace.steps.begin(); s_it!=goto_trace.steps.end(); s_it++) s_it->step_nr=++step_nr; // Now delete anything after failed assertion /* for(goto_tracet::stepst::iterator s_it1=goto_trace.steps.begin(); s_it1!=goto_trace.steps.end(); s_it1++) if(s_it1->is_assert() && !s_it1->cond_value) { s_it1++; for(goto_tracet::stepst::iterator s_it2=s_it1; s_it2!=goto_trace.steps.end(); s_it2=goto_trace.steps.erase(s_it2)); break; }*/ }
27.408994
86
0.634375
dan-blank
3c4480d863b0b441fb0db26e4947dc5bb762da51
7,647
cc
C++
services/prediction/proximity_info_factory.cc
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:10.000Z
2020-04-28T14:35:10.000Z
services/prediction/proximity_info_factory.cc
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
null
null
null
services/prediction/proximity_info_factory.cc
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:11.000Z
2020-04-28T14:35:11.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <cmath> #include <new> #include <vector> #include "services/prediction/proximity_info_factory.h" #include "services/prediction/touch_position_correction.h" // NOTE: This class has been translated to C++ and modified from the Android // Open Source Project. Specifically from some functions of the following file: // https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/ // android-5.1.1_r8/java/src/com/android/inputmethod/keyboard/ProximityInfo.java namespace prediction { const float ProximityInfoFactory::SEARCH_DISTANCE = 1.2f; const float ProximityInfoFactory::DEFAULT_TOUCH_POSITION_CORRECTION_RADIUS = 0.15f; // Hardcoded qwerty keyboard proximity settings ProximityInfoFactory::ProximityInfoFactory() { plocale_ = "en"; pgrid_width_ = 32; pgrid_height_ = 16; pgrid_size_ = pgrid_width_ * pgrid_height_; pcell_width_ = (348 + pgrid_width_ - 1) / pgrid_width_; pcell_height_ = (174 + pgrid_height_ - 1) / pgrid_height_; pkeyboard_min_width_ = 348; pkeyboard_height_ = 174; pmost_common_key_height_ = 29; pmost_common_key_width_ = 58; } ProximityInfoFactory::~ProximityInfoFactory() { } latinime::ProximityInfo* ProximityInfoFactory::GetNativeProximityInfo() { const int default_width = pmost_common_key_width_; const int threshold = (int)(default_width * SEARCH_DISTANCE); const int threshold_squared = threshold * threshold; const int last_pixel_x_coordinate = pgrid_width_ * pcell_width_ - 1; const int last_pixel_y_coordinate = pgrid_height_ * pcell_height_ - 1; std::vector<Key> pgrid_neighbors[32 * 16 /*pgrid_size_*/]; int neighbor_count_per_cell[pgrid_size_]; std::fill_n(neighbor_count_per_cell, pgrid_size_, 0); Key neighbors_flat_buffer[32 * 16 * 26 /*pgrid_size_ * keyset::key_count*/]; const int half_cell_width = pcell_width_ / 2; const int half_cell_height = pcell_height_ / 2; for (int i = 0; i < keyset::key_count; i++) { const Key key = keyset::key_set[i]; const int key_x = key.kx; const int key_y = key.ky; const int top_pixel_within_threshold = key_y - threshold; const int y_delta_to_grid = top_pixel_within_threshold % pcell_height_; const int y_middle_of_top_cell = top_pixel_within_threshold - y_delta_to_grid + half_cell_height; const int y_start = std::max(half_cell_height, y_middle_of_top_cell + (y_delta_to_grid <= half_cell_height ? 0 : pcell_height_)); const int y_end = std::min(last_pixel_y_coordinate, key_y + key.kheight + threshold); const int left_pixel_within_threshold = key_x - threshold; const int x_delta_to_grid = left_pixel_within_threshold % pcell_width_; const int x_middle_of_left_cell = left_pixel_within_threshold - x_delta_to_grid + half_cell_width; const int x_start = std::max(half_cell_width, x_middle_of_left_cell + (x_delta_to_grid <= half_cell_width ? 0 : pcell_width_)); const int x_end = std::min(last_pixel_x_coordinate, key_x + key.kwidth + threshold); int base_index_of_current_row = (y_start / pcell_height_) * pgrid_width_ + (x_start / pcell_width_); for (int center_y = y_start; center_y <= y_end; center_y += pcell_height_) { int index = base_index_of_current_row; for (int center_x = x_start; center_x <= x_end; center_x += pcell_width_) { if (SquaredDistanceToEdge(center_x, center_y, key) < threshold_squared) { neighbors_flat_buffer[index * keyset::key_count + neighbor_count_per_cell[index]] = keyset::key_set[i]; ++neighbor_count_per_cell[index]; } ++index; } base_index_of_current_row += pgrid_width_; } } for (int i = 0; i < pgrid_size_; ++i) { const int index_start = i * keyset::key_count; const int index_end = index_start + neighbor_count_per_cell[i]; for (int index = index_start; index < index_end; index++) { pgrid_neighbors[i].push_back(neighbors_flat_buffer[index]); } } int proximity_chars_array[pgrid_size_ * MAX_PROXIMITY_CHARS_SIZE]; for (int i = 0; i < pgrid_size_; i++) { int info_index = i * MAX_PROXIMITY_CHARS_SIZE; for (int j = 0; j < neighbor_count_per_cell[i]; j++) { Key neighbor_key = pgrid_neighbors[i][j]; proximity_chars_array[info_index] = neighbor_key.kcode; info_index++; } } int key_x_coordinates[keyset::key_count]; int key_y_coordinates[keyset::key_count]; int key_widths[keyset::key_count]; int key_heights[keyset::key_count]; int key_char_codes[keyset::key_count]; float sweet_spot_center_xs[keyset::key_count]; float sweet_spot_center_ys[keyset::key_count]; float sweet_spot_radii[keyset::key_count]; for (int key_index = 0; key_index < keyset::key_count; key_index++) { Key key = keyset::key_set[key_index]; key_x_coordinates[key_index] = key.kx; key_y_coordinates[key_index] = key.ky; key_widths[key_index] = key.kwidth; key_heights[key_index] = key.kheight; key_char_codes[key_index] = key.kcode; } TouchPositionCorrection touch_position_correction; if (touch_position_correction.IsValid()) { const int rows = touch_position_correction.GetRows(); const float default_radius = DEFAULT_TOUCH_POSITION_CORRECTION_RADIUS * (float)std::hypot(pmost_common_key_width_, pmost_common_key_height_); for (int key_index = 0; key_index < keyset::key_count; key_index++) { Key key = keyset::key_set[key_index]; sweet_spot_center_xs[key_index] = (key.khit_box_left + key.khit_box_right) * 0.5f; sweet_spot_center_ys[key_index] = (key.khit_box_top + key.khit_box_bottom) * 0.5f; sweet_spot_radii[key_index] = default_radius; const int row = key.khit_box_top / pmost_common_key_height_; if (row < rows) { const int hit_box_width = key.khit_box_right - key.khit_box_left; const int hit_box_height = key.khit_box_bottom - key.khit_box_top; const float hit_box_diagonal = (float)std::hypot(hit_box_width, hit_box_height); sweet_spot_center_xs[key_index] += touch_position_correction.GetX(row) * hit_box_width; sweet_spot_center_ys[key_index] += touch_position_correction.GetY(row) * hit_box_height; sweet_spot_radii[key_index] = touch_position_correction.GetRadius(row) * hit_box_diagonal; } } } latinime::ProximityInfo* proximity_info = new latinime::ProximityInfo( plocale_, pkeyboard_min_width_, pkeyboard_height_, pgrid_width_, pgrid_height_, pmost_common_key_width_, pmost_common_key_height_, proximity_chars_array, pgrid_size_ * MAX_PROXIMITY_CHARS_SIZE, keyset::key_count, key_x_coordinates, key_y_coordinates, key_widths, key_heights, key_char_codes, sweet_spot_center_xs, sweet_spot_center_ys, sweet_spot_radii); return proximity_info; } int ProximityInfoFactory::SquaredDistanceToEdge(int x, int y, Key k) { const int left = k.kx; const int right = left + k.kwidth; const int top = k.ky; const int bottom = top + k.kheight; const int edge_x = x < left ? left : (x > right ? right : x); const int edge_y = y < top ? top : (y > bottom ? bottom : y); const int dx = x - edge_x; const int dy = y - edge_y; return dx * dx + dy * dy; } } // namespace prediction
40.036649
80
0.707859
zbowling
3c45ec5e49f274755a9e7fb21062c0d7e807763d
2,808
cpp
C++
ch5_openCV_PCL/PCL-jointMap/jointMap.cpp
ClovisChen/slam14
35fad23a491f2dd7666edab55ae849ac937d44c2
[ "MIT" ]
null
null
null
ch5_openCV_PCL/PCL-jointMap/jointMap.cpp
ClovisChen/slam14
35fad23a491f2dd7666edab55ae849ac937d44c2
[ "MIT" ]
null
null
null
ch5_openCV_PCL/PCL-jointMap/jointMap.cpp
ClovisChen/slam14
35fad23a491f2dd7666edab55ae849ac937d44c2
[ "MIT" ]
null
null
null
// // Created by chen-tian on 17-7-19. // #include <iostream> #include <fstream> using namespace std; #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <Eigen/Geometry> #include <boost/format.hpp> //字符串格式化 #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> int main(int argc, char** argv){ vector<cv::Mat> colorImgs, depthImgs; vector<Eigen::Isometry3d> poses; ifstream f("../pose.txt");//f is name if (!f) { cerr<<"please run this program with pose.txt"<<endl; return 1; } for (int i=0; i<5; i++) { //boost::format to format the srting boost::format fmt("../%s/%d.%s");//the format of the image colorImgs.push_back(cv::imread( (fmt%"color"%(i+1)%"png").str() )); depthImgs.push_back(cv::imread( (fmt%"depth"%(i+1)%"pgm").str() ,-1 ));//-1 is used to read initial image double data[7] = {0}; for (auto& d:data ) f>>d; Eigen::Quaterniond q(data[6], data[3], data[4], data[5] );//the last number is the real Eigen::Isometry3d T(q);//euler 4*4 T.pretranslate(Eigen::Vector3d( data[0], data[1], data[2] )); poses.push_back(T); } //K double cx=325.5; double cy=253.5; double fx=518.0; double fy=519.0; double depthScale=100.0; cout<<"transfering image to point clouds..."<<endl; //point clouds typedef: XYZRGB typedef pcl::PointXYZRGB PointT; typedef pcl::PointCloud<PointT> PointCloud; PointCloud::Ptr pointCloud(new PointCloud); for (int i=0; i<5; i++) { cout<<"transfering..."<<i+1<<endl; cv::Mat color = colorImgs[i]; cv::Mat depth = depthImgs[i]; Eigen::Isometry3d T = poses[i]; for(int v=0; v<color.rows;v++) for(int u=0; u<color.cols;u++) { unsigned int d = depth.ptr<unsigned short>(v)[u]; if (d==0)continue; Eigen::Vector3d point; point[2] = double(d)/depthScale; point[0] = (u-cx)*point[2]/fx; point[1] = (v-cy)*point[2]/fy; Eigen::Vector3d pointWorld = T*point; PointT p; p.x = pointWorld[0]; p.y = pointWorld[1]; p.z = pointWorld[2]; p.b = color.data[v*color.step+u*color.channels()]; p.g = color.data[v*color.step+u*color.channels()+1]; p.r = color.data[v*color.step+u*color.channels()+2]; pointCloud->points.push_back(p); } } pointCloud->is_dense = false; cout<<"pointcloud has "<<pointCloud->size()<<" points"<<endl; pcl::io::savePCDFileBinary("map.pcd", *pointCloud); }
29.25
113
0.549858
ClovisChen
3c4a455f6d75898195fe66e4ad6918840f131cb6
2,356
cpp
C++
src/register/SegmentRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
1
2022-01-16T18:24:32.000Z
2022-01-16T18:24:32.000Z
src/register/SegmentRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
src/register/SegmentRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
// // Created by 86759 on 2022-01-14. // #include "SegmentRegister.h" #include "SystemAddressRegister.h" segment_descriptor_t load_descriptor(uint32_t value) { uint32_t descriptor_index = value >> 3; uint32_t offset = descriptor_index * 64/8; const auto address = SystemAddressRegister::GDT + offset; const auto descriptor = (uint64_t)*address; segment_descriptor_t segment_descriptor; segment_descriptor.base = ((descriptor & 0x1111'0000'0000'0000) >> 48 << 0) + ((descriptor & 0x0000'0000'0000'0011) >> 0 << 15) + ((descriptor & 0x0000'0000'1100'0000) >> 24 << 23) + 0; segment_descriptor.limit = ((descriptor & 0x0000'1111'0000'0000) >> 32 << 0) + ((descriptor & 0x0000'0000'0000'0011) >> 16 << 15) + 0; // TODO: set remain bits } uint16_t SegmentRegister::CS_r = 0xF000; uint16_t SegmentRegister::SS_r = 0x0000; uint16_t SegmentRegister::DS_r = 0x0000; uint16_t SegmentRegister::ES_r = 0x0000; uint16_t SegmentRegister::FS_r = 0x0000; uint16_t SegmentRegister::GS_r = 0x0000; segment_descriptor_t SegmentRegister::CS_descriptor; segment_descriptor_t SegmentRegister::SS_descriptor; segment_descriptor_t SegmentRegister::DS_descriptor; segment_descriptor_t SegmentRegister::ES_descriptor; segment_descriptor_t SegmentRegister::FS_descriptor; segment_descriptor_t SegmentRegister::GS_descriptor; uint16_t SegmentRegister::CS() { return CS_r; } uint16_t SegmentRegister::SS() { return SS_r; } uint16_t SegmentRegister::DS() { return DS_r; } uint16_t SegmentRegister::ES() { return ES_r; } uint16_t SegmentRegister::FS() { return FS_r; } uint16_t SegmentRegister::GS() { return GS_r; } void SegmentRegister::CS(uint16_t value) { CS_r = value; CS_descriptor = load_descriptor(value); } void SegmentRegister::SS(uint16_t value) { SS_r = value; SS_descriptor = load_descriptor(value); } void SegmentRegister::DS(uint16_t value) { DS_r = value; DS_descriptor = load_descriptor(value); } void SegmentRegister::ES(uint16_t value) { ES_r = value; ES_descriptor = load_descriptor(value); } void SegmentRegister::FS(uint16_t value) { FS_r = value; FS_descriptor = load_descriptor(value); } void SegmentRegister::GS(uint16_t value) { GS_r = value; GS_descriptor = load_descriptor(value); }
44.45283
99
0.712224
openx86
3c4cef2edac1f22cb082cf3001941ea236bb1a3c
796
cpp
C++
Sources/Folders/ExtraCodes/FishCodes.cpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
52
2020-01-17T08:12:04.000Z
2022-03-19T20:02:57.000Z
Sources/Folders/ExtraCodes/FishCodes.cpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
67
2020-05-06T04:47:27.000Z
2022-03-31T16:25:19.000Z
Sources/Folders/ExtraCodes/FishCodes.cpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
7
2021-01-20T17:42:25.000Z
2022-03-08T09:29:42.000Z
#include "cheats.hpp" #include "Helpers/Address.hpp" namespace CTRPluginFramework { //Fish Byte Always void FishAlwaysBiteRightAway(MenuEntry *entry) { static const Address fishbite(0x1EA844, 0x1EA288, 0x1EA864, 0x1EA864, 0x1EA7A0, 0x1EA7A0, 0x1EA76C, 0x1EA76C); if(entry->WasJustActivated()) Process::Patch(fishbite.addr, 0xE3A0005A); else if(!entry->IsActivated()) Process::Patch(fishbite.addr, 0xE0800100); } //Fish Can't Be Scared void FishCantBeScared(MenuEntry *entry) { static const Address fishscare(0x1EAB14, 0x1EA558, 0x1EAB34, 0x1EAB34, 0x1EAA70, 0x1EAA70, 0x1EAA3C, 0x1EAA3C); if(entry->WasJustActivated()) Process::Patch(fishscare.addr, 0xE3500001); else if(!entry->IsActivated()) Process::Patch(fishscare.addr, 0xE3500000); } }
36.181818
114
0.729899
MirayXS