hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dbfe35824a4ad7a80bc5395d2463867fce2095a1 | 39,264 | cpp | C++ | src/WindowProxy.cpp | ravidavi/OpenFrames | 67cce87f1ccd23df91d6d070d86c06ceb180dadb | [
"Apache-2.0"
] | 26 | 2017-08-16T18:17:50.000Z | 2022-03-11T10:23:52.000Z | src/WindowProxy.cpp | ravidavi/OpenFrames | 67cce87f1ccd23df91d6d070d86c06ceb180dadb | [
"Apache-2.0"
] | 4 | 2018-10-18T12:31:19.000Z | 2020-08-12T08:59:25.000Z | src/WindowProxy.cpp | ravidavi/OpenFrames | 67cce87f1ccd23df91d6d070d86c06ceb180dadb | [
"Apache-2.0"
] | 11 | 2018-09-10T18:29:07.000Z | 2022-03-09T13:53:52.000Z | /***********************************
Copyright 2020 Ravishankar Mathur
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 WindowProxy.cpp
* EmbeddedGraphics, WindowEventHandler and WindowProxy-class function definitions.
*/
#include <OpenFrames/WindowProxy.hpp>
#include <OpenFrames/Utilities.hpp>
#include <osg/GraphicsContext>
#include <osg/PointSprite>
#include <osgGA/GUIEventHandler>
#include <iostream>
#include <limits>
namespace OpenFrames
{
/** This is the GraphicsWindow that is used for embedded graphics */
EmbeddedGraphics::EmbeddedGraphics(int x, int y, int width, int height, WindowProxy *window)
: _gcCallback(nullptr), _makeCurrent(NULL), _swapBuffers(NULL), _updateContext(NULL), _window(window), _realized(false)
{
// Specify traits for this graphics context
_traits = new GraphicsContext::Traits;
setGeometry(x, y, width, height);
}
EmbeddedGraphics::~EmbeddedGraphics() {}
bool EmbeddedGraphics::makeCurrentImplementation()
{
if(_gcCallback == nullptr)
{
if(_makeCurrent == nullptr)
{
OSG_WARN<< "EmbeddedGraphics::makeCurrentImplementation() ERROR: Callback object or makeCurrent() function must be defined." << std::endl;
return false;
}
else if(_window == nullptr)
{
OSG_WARN<< "EmbeddedGraphics::makeCurrentImplementation() ERROR: WindowProxy must be defined if makeCurrent() function is used." << std::endl;
return false;
}
}
// Perform the makeCurrent callback
bool success = false;
if(_gcCallback != nullptr) success = _gcCallback->makeCurrent();
else
{
unsigned int winID = _window->getID();
_makeCurrent(&winID, &success);
}
return success;
}
void EmbeddedGraphics::swapBuffersImplementation()
{
if(_gcCallback == nullptr)
{
if(_swapBuffers == nullptr)
{
OSG_WARN<< "EmbeddedGraphics::swapBuffersImplementation() ERROR: Callback object or swapBuffers() function must be defined." << std::endl;
return;
}
else if(_window == nullptr)
{
OSG_WARN<< "EmbeddedGraphics::swapBuffersImplementation() ERROR: WindowProxy is not defined." << std::endl;
return;
}
}
// Perform the custom SwapBuffers callback
if(_gcCallback != nullptr) _gcCallback->swapBuffers();
else
{
unsigned int winID = _window->getID();
_swapBuffers(&winID);
}
}
void EmbeddedGraphics::setGeometry(int x, int y, int width, int height)
{
_traits->x = x;
_traits->y = y;
_traits->width = width;
_traits->height = height;
}
void EmbeddedGraphics::setGraphicsContextCallback(GraphicsContextCallback *gcCallback)
{
_gcCallback = gcCallback;
}
void EmbeddedGraphics::setMakeCurrentFunction(void (*fcn)(unsigned int *winID, bool *success))
{
_makeCurrent = fcn;
}
void EmbeddedGraphics::setUpdateContextFunction(void (*fcn)(unsigned int *winID, bool *success))
{
_updateContext = fcn;
}
bool EmbeddedGraphics::updateContextImplementation()
{
bool success = false;
if(_gcCallback != nullptr) success = _gcCallback->updateContext();
else if(_updateContext)
{
unsigned int winID = _window->getID();
_updateContext(&winID, &success);
}
return success;
}
void EmbeddedGraphics::setSwapBuffersFunction(void (*fcn)(unsigned int *winID))
{
_swapBuffers = fcn;
}
bool EmbeddedGraphics::realizeImplementation()
{
_realized = true;
return _realized;
}
/** This is the handler for events to a WindowProxy */
WindowEventHandler::WindowEventHandler(WindowProxy *window)
: _window(window)
{
_currentRow = _currentCol = 0;
_keyPressCallback = NULL;
_mouseMotionCallback = NULL;
_buttonPressCallback = NULL;
_buttonReleaseCallback = NULL;
_vrEventCallback = NULL;
}
WindowEventHandler::~WindowEventHandler() {}
// ea is the event, and aa is the osgViewer::View in which the event occured
bool WindowEventHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
bool handled = false;
// Check for different event types
switch(ea.getEventType())
{
// Mouse button was pushed
case(osgGA::GUIEventAdapter::PUSH):
{
// Get the RenderRectangle at the current mouse location
unsigned int row, col;
getRenderRectangle(ea.getX()/ea.getWindowWidth(), ea.getY()/ea.getWindowHeight(), row, col);
selectRenderRectangle(row, col);
// Call the button press callback
if(_buttonPressCallback)
{
// Get normalized (in range [-1, +1]) x and y coordinates of the mouse, within the current sub-window
float xnorm = ea.getXnormalized();
float ynorm = ea.getYnormalized();
unsigned int id = _window->getID(); // Get the window's ID
unsigned int button = ea.getButton(); // Get the ID of the button that was pressed
// Call the user's button press callback
_buttonPressCallback(&id, &_currentRow, &_currentCol, &xnorm, &ynorm, &button);
}
break;
}
// Mouse button was released
case(osgGA::GUIEventAdapter::RELEASE):
{
// Call the button release callback
if(_buttonReleaseCallback)
{
// Get normalized (in range [-1, +1]) x and y coordinates of the mouse, within
// the current sub-window
float xnorm = ea.getXnormalized();
float ynorm = ea.getYnormalized();
unsigned int id = _window->getID(); // Get the window's ID
unsigned int button = ea.getButton(); // Get the ID of the button that was pressed
_buttonReleaseCallback(&id, &_currentRow, &_currentCol, &xnorm, &ynorm, &button);
}
break;
}
// Mouse was moved
case(osgGA::GUIEventAdapter::MOVE):
{
// Call the mouse move callback
if(_mouseMotionCallback)
{
// Get normalized (in range [-1, +1]) x and y coordinates of the mouse, within
// the current sub-window
float xnorm = ea.getXnormalized();
float ynorm = ea.getYnormalized();
unsigned int id = _window->getID(); // Get the window's ID
_mouseMotionCallback(&id, &_currentRow, &_currentCol, &xnorm, &ynorm);
}
break;
}
// A keyboard key was pressed
case(osgGA::GUIEventAdapter::KEYDOWN):
{
int key = ea.getKey();
// 'v' switches to next view
if(key == 'v')
{
_window->getGridPosition(_currentRow, _currentCol)->nextView();
handled = true;
}
// 'V' switches to previous view
else if(key == 'V')
{
_window->getGridPosition(_currentRow, _currentCol)->previousView();
handled = true;
}
// Spacebar resets current view
else if (key == osgGA::GUIEventAdapter::KEY_Space)
{
_window->getGridPosition(_currentRow, _currentCol)->getCurrentView()->resetView();
handled = true;
}
// Scale world if VR is used
else if (key == osgGA::GUIEventAdapter::KEY_Up)
{
if (_window->getUseVR())
{
float scale = _window->getWorldUnitsPerMeter();
scale /= 2.0; // Make world bigger
_window->setWorldUnitsPerMeter(scale);
handled = true;
}
}
else if (key == osgGA::GUIEventAdapter::KEY_Down)
{
if (_window->getUseVR())
{
float scale = _window->getWorldUnitsPerMeter();
scale *= 2.0; // Make world smaller
_window->setWorldUnitsPerMeter(scale);
handled = true;
}
}
// Call the keypress callback
unsigned int id = _window->getID();
if(_keyPressCallback) _keyPressCallback(&id, &_currentRow, &_currentCol, &key);
break;
}
// The window was resized
case(osgGA::GUIEventAdapter::RESIZE):
{
// Get the graphics context that was resized
osg::GraphicsContext *gc = OpenFrames::getMainGraphicsContext(aa.asView());
// If graphics context is EmbeddedGraphics, then call the update context callback
EmbeddedGraphics* eg = dynamic_cast<EmbeddedGraphics*>(gc);
if(eg)
{
bool success = eg->updateContextImplementation();
if(!success) std::cerr<< "WindowEventHandler::handle WARNING: OpenGL context was not properly updated during RESIZE event. Rendering artifacts may occur." << std::endl;
}
// Make sure OpenFrames::View knows about resize and updates its projection matrix
_window->setupGrid(ea.getWindowWidth(), ea.getWindowHeight());
break;
}
// The window was closed or application quit
case(osgGA::GUIEventAdapter::CLOSE_WINDOW):
case(osgGA::GUIEventAdapter::QUIT_APPLICATION):
{
_window->shutdown();
break;
}
// Check for custom events
case(osgGA::GUIEventAdapter::USER):
{
const OpenVREvent *vrEvent = dynamic_cast<const OpenVREvent*>(&ea);
if (vrEvent && _vrEventCallback)
{
unsigned int id = _window->getID();
_vrEventCallback(&id, &_currentRow, &_currentCol, vrEvent);
}
break;
}
default:
break;
}
return handled;
}
void WindowEventHandler::windowModified()
{
unsigned int numRows = _window->getNumRows();
unsigned int numCols = _window->getNumCols();
// Reset the current RenderRectangle
if((_currentRow >= numRows) || (_currentCol >= numCols))
{
_currentRow = _currentCol = 0;
}
// Deselect every RenderRectangle
for(unsigned int i = 0; i < numRows; ++i)
{
for(unsigned int j = 0; j < numCols; ++j)
{
_window->getGridPosition(i, j)->setSelected(false);
}
}
// Now select the current RenderRectangle
_window->getGridPosition(_currentRow, _currentCol)->setSelected(true);
}
/** Get the RenderRectangle at the (x,y) coordinates of the window. Note that
the coordinates must be in the range [0, 1). */
void WindowEventHandler::getRenderRectangle(float x, float y, unsigned int &row, unsigned int &col)
{
unsigned int nRows = _window->getNumRows();
unsigned int nCols = _window->getNumCols();
// (x, y) are out of range, so return an invalid rectangle position
if(x < 0.0 || y < 0.0 || x >= 1.0 || y >= 1.0)
{
row = nRows;
col = nCols;
return;
}
// Compute the column of the specified coordinates
col = (unsigned int)(x*nCols);
// Compute the row of the specified coordinates, noting that the first row is at the
// TOP of the window, whereas y coordinates start at the BOTTOM of the window.
row = (nRows - 1) - (int)(y*nRows);
}
void WindowEventHandler::selectRenderRectangle( unsigned int row, unsigned int col )
{
// Make sure we clicked in a valid rectangle
if((row < _window->getNumRows()) && (col < _window->getNumCols()))
{
// Make sure we aren't clicking on the current rectangle
if(row != _currentRow || col != _currentCol)
{
// Deselect the old rectangle
_window->getGridPosition(_currentRow, _currentCol)->setSelected(false);
// Set the new selected rectangle
_currentRow = row;
_currentCol = col;
// Select the new rectangle
_window->getGridPosition(_currentRow, _currentCol)->setSelected(true);
}
}
else
std::cerr<< "OpenFrames::WindowEventHandler ERROR: invalid grid location (row " << row << ", col " << col << ")" << std::endl;
}
/**
Checks whether certain necessary OpenGL and WindowProxy components exist
*/
class CheckPrerequisites : public osg::Operation
{
public:
CheckPrerequisites(WindowProxy *wp)
: _windowProxy(wp)
{}
/** Do the actual task of this operation.*/
virtual void operator () (osg::Object* obj)
{
// Get the GraphicsContext to be tested
osg::GraphicsContext *gc = dynamic_cast<osg::GraphicsContext*>(obj);
osg::State *state = gc->getState();
osg::GLExtensions *glext = state->get<osg::GLExtensions>();
if(!gc)
{
OSG_WARN<< "OpenFrames::WindowProxy ERROR: GraphicsContext not valid" << std::endl;
return;
}
// Get OpenGL version info
char *glVersionString = (char*)glGetString(GL_VERSION);
if(glVersionString == 0)
OSG_WARN<< "OpenFrames::WindowProxy ERROR in glGetString(GL_VERSION): " << std::endl;
// Get OpenGL renderer info
char *glRendererString = (char*)glGetString(GL_RENDERER);
if(glRendererString == 0)
OSG_WARN<< "OpenFrames::WindowProxy ERROR in glGetString(GL_RENDERER): " << std::endl;
// Report OpenGL version and renderer info
if(glVersionString && glRendererString)
{
OSG_NOTICE<< "OpenFrames renderer: " << glRendererString << ", version: " << glVersionString;
if(gc->getTraits()->samples > 0)
OSG_NOTICE<< " with " << gc->getTraits()->samples << "x MSAA";
OSG_NOTICE<< std::endl;
}
else
{
GLenum err = glGetError();
if(err == GL_INVALID_ENUM)
{
OSG_WARN<< " GL_INVALID_ENUM, please ensure that a valid OpenGL context is current before starting the WindowProxy animation." << std::endl;
}
else if(err == GL_INVALID_OPERATION)
{
OSG_WARN<< " GL_INVALID_OPERATION, please ensure that application is not already using OpenGL elsewhere." << std::endl;
}
else
{
OSG_WARN<< "OpenGL error code " << err << std::endl;
}
return;
}
// Check if PointSprites are supported
osg::ref_ptr<osg::PointSprite> ps = new osg::PointSprite;
if(!ps->checkValidityOfAssociatedModes(*(gc->getState())))
{
std::cerr<< "OpenFrames::WindowProxy ERROR: OpenGL PointSprite extension not supported." << std::endl;
}
// Check for glVertexAttrib
if(!glext->glVertexAttrib3fv)
{
std::cerr<< "OpenFrames::WindowProxy ERROR: OpenGL glVertexAttrib3fv not found." << std::endl;
}
// Check for FrameBuffer Objects (needed for VR support)
if(!glext->isFrameBufferObjectSupported)
{
std::cerr<< "OpenFrames::WindowProxy WARNING: FBOs not supported, VR support disabled." << std::endl;
}
// Check for multisample support
if(_windowProxy->getUseVR() && !glext->isRenderbufferMultisampleSupported())
{
std::cerr<< "OpenFrames::WindowProxy WARNING: Multisample not supported, VR rendering will not be antialiased." << std::endl;
}
// Disable vsync since VR does its own frame synchronization
if (_windowProxy->getUseVR())
{
osgViewer::GraphicsWindow *gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc);
if (gw) gw->setSyncToVBlank(false);
}
// Other OpenGL extension checks can go here
}
protected:
virtual ~CheckPrerequisites() {}
WindowProxy* _windowProxy;
};
WindowProxy::WindowProxy( int x, int y, unsigned int width, unsigned int height,
unsigned int nrow, unsigned int ncol, bool embedded, bool useVR )
: _winID(0), _nRow(0), _nCol(0), _isEmbedded(embedded),
_animationState(IDLE), _pauseAnimation(false),
_timePaused(false), _useVR(useVR)
{
// Input value checks
if(x < 0) x = 0;
if(y < 0) y = 0;
if(width == 0) width = 1;
if(height == 0) height = 1;
if(nrow == 0) nrow = 1;
if(ncol == 0) ncol = 1;
_viewer = new osgViewer::CompositeViewer;
_viewer->setIncrementalCompileOperation(new osgUtil::IncrementalCompileOperation());
_embeddedGraphics = new EmbeddedGraphics(x, y, width, height, this);
_eventHandler = new WindowEventHandler(this);
_statsHandler = new osgViewer::StatsHandler;
_screenCaptureHandler = new osgViewer::ScreenCaptureHandler;
_screenCaptureHandler->setKeyEventToggleContinuousCapture(0); // Disable continuous capture
_windowSizeHandler = new osgViewer::WindowSizeHandler;
_windowSizeHandler->setChangeWindowedResolution(false); // Don't change windowed resolution
setWindowName("OpenFrames Window");
/** Make sure that OpenGL checks are done when the window is created */
_viewer->setRealizeOperation(new CheckPrerequisites(this));
/** We don't want the OpenGL context being made current then released at every frame, because that slows things down and can cause problems with single-context windowing systems such as Winteracter. It's ok to not do this here, because we know that each WindowProxy will only handle one drawing context in its thread. */
_viewer->setReleaseContextAtEndOfFrameHint(false);
// VR can only be enabled for 1x1 windows
if(_useVR)
{
if(nrow*ncol > 1)
{
osg::notify(osg::FATAL)<< "OpenFrames::WindowProxy ERROR: VR only available for 1x1 windows. Disabling VR." << std::endl;
_useVR = false;
}
else
{
// Set up OpenVR
_ovrDevice = new OpenVRDevice(0.001, 0.9144); // 4'6" user height
if(_ovrDevice->initVR())
{
osg::notify(osg::INFO) << "WindowProxy enabling VR" << std::endl;
int vrWidth, vrHeight;
_ovrDevice->getRecommendedTextureSize(vrWidth, vrHeight);
_vrTextureBuffer = new VRTextureBuffer(vrWidth, vrHeight);
_ovrDevice->setWorldUnitsPerMeterLimits(0.001, 1.0e6);
}
else
{
osg::notify(osg::FATAL) << "WindowProxy disabling VR" << std::endl;
_ovrDevice = NULL;
_useVR = false;
}
}
}
// Create the RenderRectangles immediately so that they can be modified as needed
setGridSize(nrow, ncol);
setupGrid(width, height);
// Set time parameters
setTimeRange(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max());
setTime(0.0);
setTimeScale(1.0);
// Set framerate (in fps) based on whether VR is enabled
if(_useVR) _frameThrottle.setDesiredFramerate(0.0); // Don't limit framerate
else _frameThrottle.setDesiredFramerate(30.0);
}
// WindowProxy destructor
// Stop any animations and wait for the thread to join
WindowProxy::~WindowProxy()
{
shutdown();
if (isRunning()) join(); // Only join if thread is running
if (_useVR) _ovrDevice->shutdownVR();
}
void WindowProxy::cancelCleanup()
{
OSG_NOTICE<< "WindowProxy::cancelCleanup()" << std::endl;
shutdown();
}
void WindowProxy::setWindowName(const std::string& name)
{
// If window exists, then directly set its name
if(_window) _window->setWindowName(name);
// Otherwise set the name in the EmbeddedGraphics object, which will be used to initialize
// the window when it is created
else _embeddedGraphics->setWindowName(name);
}
std::string WindowProxy::getWindowName() const
{
if(_window) return _window->getWindowName();
else return _embeddedGraphics->getWindowName();
}
void WindowProxy::setWindowBackgroundColor(const osg::Vec3& color)
{
// If window exists, then directly set its color
if(_window) _window->setClearColor(osg::Vec4(color, 1.0));
// Otherwise set the color in the EmbeddedGraphics object, which will be used to initialize
// the window when it is created
else _embeddedGraphics->setClearColor(osg::Vec4(color, 1.0));
}
osg::Vec3 WindowProxy::getWindowBackgroundColor() const
{
osg::Vec4 clearColor;
if(_window) clearColor = _window->getClearColor();
else clearColor = _embeddedGraphics->getClearColor();
return osg::Vec3(clearColor[0], clearColor[1], clearColor[2]);
}
bool WindowProxy::setupWindow()
{
if(_isEmbedded) // For embedded windows, just set the window to our embedded GraphicsContext
{
osg::State* state = new osg::State; // Tracks current OpenGL state
_embeddedGraphics->setState(state);
state->setGraphicsContext(_embeddedGraphics);
state->setContextID(osg::GraphicsContext::createNewContextID());
_window = _embeddedGraphics.get();
}
else // Otherwise create a new window for OpenGL graphics
{
// Get default window traits that are saved in the EmbeddedGraphics object (even if it is not used)
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
*traits = *(_embeddedGraphics->getTraits());
traits->readDISPLAY(); // Get DISPLAY number for OS's that support it
traits->windowDecoration = true; // We want decorations such as window borders
traits->doubleBuffer = true; // We want double buffered graphics since we're doing animation
if(_useVR)
{
traits->vsync = false; // VR rendering handles its own HMD vblank sync
}
else
{
traits->samples = 4; // Enable 4x MSAA
}
// Try creating graphics context
osg::GraphicsContext* gc = osg::GraphicsContext::createGraphicsContext(traits.get());
// On error, try again without MSAA
if(!gc)
{
OSG_WARN << "Couldn't create 4x MSAA window, trying again without MSAA..." << std::endl;
traits->samples = 0; // Disable MSAA
gc = osg::GraphicsContext::createGraphicsContext(traits.get());
}
_window = dynamic_cast<osgViewer::GraphicsWindow*>(gc);
}
if(_window.valid())
{
// Initialize background color for the window
_window->setClearColor(_embeddedGraphics->getClearColor());
// Specify that we want to clear both color & depth buffers at every frame
_window->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
#ifdef OF_DEBUG
// Check GL errors often in debug builds
_window->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
#else
// Check GL errors sparingly in release builds
_window->getState()->setCheckForGLErrors(osg::State::ONCE_PER_FRAME);
#endif
// Initialize event processing system's input window
_window->getEventQueue()->syncWindowRectangleWithGraphicsContext();
// Allow shaders to access osg_* uniforms
_window->getState()->setUseModelViewAndProjectionUniforms(true);
// Disable swap buffers
if(_useVR) _window->setSwapCallback(new OpenVRSwapBuffers(_ovrDevice, _vrTextureBuffer));
}
else
{
std::cerr<< "WindowProxy ERROR: Graphics Window couldn't be created." << std::endl;
return false;
}
// Set the graphics context for each RenderRectangle
for(unsigned int i = 0; i < _renderList.size(); ++i)
{
_renderList[i]->setGraphicsContext(_window.get());
}
// Compute the positions/sizes of each RenderRectangle
int width = _embeddedGraphics->getTraits()->width;
int height = _embeddedGraphics->getTraits()->height;
setupGrid(width, height);
return true;
}
/** Gather all the displayed scenes, each one being one FrameManager */
void WindowProxy::collectScenes()
{
FrameManager* currScene;
// Clear set of scenes
_scenes.clear();
// Loop over each RenderRectangle
for(unsigned int row = 0; row < _nRow; ++row)
{
for(unsigned int col = 0; col < _nCol; ++col)
{
// Add current RenderRectangle's scene to the set (if the scene exists)
currScene = getScene(row, col);
if(currScene) _scenes.insert(currScene);
}
}
}
/** Get the width of the displayed window */
unsigned int WindowProxy::getWindowWidth() const
{
if(_window.valid()) return _window->getTraits()->width;
else return 0;
}
/** Get the height of the displayed window */
unsigned int WindowProxy::getWindowHeight() const
{
if(_window.valid()) return _window->getTraits()->height;
else return 0;
}
/** Set the key used for fullscreen toggle */
void WindowProxy::setToggleFullscreenKey(int key)
{
if (key == 0)
{
_windowSizeHandler->setToggleFullscreen(false);
}
else
{
_windowSizeHandler->setToggleFullscreen(true);
_windowSizeHandler->setKeyEventToggleFullscreen(key);
}
}
/** Create a key pressed event */
void WindowProxy::keyPress(int key)
{
_window->getEventQueue()->keyPress(key);
}
/** Create a key released event */
void WindowProxy::keyRelease(int key)
{
_window->getEventQueue()->keyRelease(key);
}
/** Create a mouse moved event */
void WindowProxy::mouseMotion(float x, float y)
{
_window->getEventQueue()->mouseMotion(x, y);
}
/** Create a mouse button pressed event */
void WindowProxy::buttonPress(float x, float y, unsigned int button)
{
_window->getEventQueue()->mouseButtonPress(x, y, button);
}
/** Create a mouse button released event */
void WindowProxy::buttonRelease(float x, float y, unsigned int button)
{
_window->getEventQueue()->mouseButtonRelease(x, y, button);
}
/** Create a window resized event */
void WindowProxy::resizeWindow(int x, int y, unsigned int width, unsigned int height)
{
// Input value checks
if(x < 0) x = 0;
if(y < 0) y = 0;
if(width == 0) width = 1;
if(height == 0) height = 1;
if(_window)
{
// Can this be changed to _window->setWindowRectangle()?
_window->resized(x, y, width, height);
_window->getEventQueue()->windowResize(x, y, width, height);
}
else
{
_embeddedGraphics->setGeometry(x, y, width, height);
setupGrid(width, height);
}
}
/** Resize each RenderRectangle's viewport (the on-screen area that it draws to). */
void WindowProxy::setupGrid(unsigned int width, unsigned int height)
{
float rw, rh;
rw = (float)width/(float)_nCol; // Width of each RenderRect
rh = (float)height/(float)_nRow; // Height of each RenderRect
// Loop over each RenderRectangle
RenderRectangle *rect;
for(unsigned int row = 0; row < _nRow; ++row)
{
for(unsigned int col = 0; col < _nCol; ++col)
{
// Get the RenderRectangle at the current (row, col) position
rect = getGridPosition(row, col);
// Set viewport size for this grid position
rect->setViewport((int)(rw*col), (int)(rh*(_nRow-1-row)), (int)rw, (int)rh);
// Reset the projection matrix
rect->applyCurrentViewProjection();
}
}
}
/** Set the current time */
void WindowProxy::setTime(double time)
{
if(_timeSyncWinProxy.valid()) _timeSyncWinProxy->setTime(time);
else
{
if(time < _minTime) time = _minTime;
else if(time > _maxTime) time = _maxTime;
_currTime = _offsetTime = time;
_Tref = osg::Timer::instance()->tick();
}
}
/** Set the time range */
void WindowProxy::setTimeRange(double tMin, double tMax)
{
if(_timeSyncWinProxy.valid()) _timeSyncWinProxy->setTimeRange(tMin, tMax);
else if(tMax >= tMin)
{
_minTime = tMin;
_maxTime = tMax;
}
}
/** Get the time range */
void WindowProxy::getTimeRange(double& tMin, double& tMax) const
{
if(_timeSyncWinProxy.valid()) _timeSyncWinProxy->getTimeRange(tMin, tMax);
else
{
tMin = _minTime;
tMax = _maxTime;
}
}
/** Pause/unpause time */
void WindowProxy::pauseTime(bool pause)
{
if(_timeSyncWinProxy.valid()) _timeSyncWinProxy->pauseTime(pause);
else
{
_timePaused = pause;
setTime(_currTime);
}
}
/** Change time scale */
void WindowProxy::setTimeScale(double tscale)
{
if(_timeSyncWinProxy.valid()) _timeSyncWinProxy->setTimeScale(tscale);
else
{
_timeScale = tscale;
setTime(_currTime);
}
}
/** Synchronize time with specified WindowProxy */
bool WindowProxy::synchronizeTime(WindowProxy *winproxy)
{
// Stop synchronizing time
if((winproxy == NULL) || (winproxy == this))
{
if(_timeSyncWinProxy.valid())
{
// Save currently synchronized window's time parameters
double newTime = _timeSyncWinProxy->getTime();
_timeScale = _timeSyncWinProxy->getTimeScale();
_timePaused = _timeSyncWinProxy->isTimePaused();
_timeSyncWinProxy->getTimeRange(_minTime, _maxTime);
_timeSyncWinProxy = NULL;
setTime(newTime);
}
return true;
}
// Check for circular dependency by traversing full synchronized window chain
// Note that this should never be an infinite loop since there should be no existing circular dependencies
for(WindowProxy* syncWP = winproxy->getTimeSyncWindow(); syncWP != NULL; syncWP = syncWP->getTimeSyncWindow())
{
// Make sure synchronized window isn't this window
if(syncWP == this)
{
OSG_WARN << "WindowProxy::synchronizeTime circular dependency not allowed." << std::endl;
return false;
}
}
// No circular dependency, so set synchronized window
_timeSyncWinProxy = winproxy;
return true;
}
/** Pause the window's animation */
void WindowProxy::pauseAnimation(bool pause)
{
if(pause == _pauseAnimation) return;
_pauseAnimation = pause;
// As long as animation is active, wait until animation state matches the desired state
while(isAnimating() && ((_animationState == PAUSED) != _pauseAnimation)) OpenThreads::Thread::YieldCurrentThread();
}
/** Add or remove RenderRectangles to the grid to make it the right size. */
void WindowProxy::setGridSize(unsigned int row, unsigned int col)
{
// Check for invalid grid size
if(row == 0 || col == 0) return;
_nRow = row;
_nCol = col;
unsigned int newSize = _nRow*_nCol;
unsigned int oldSize = _renderList.size();
if(oldSize == newSize) return;
_renderList.resize(newSize); // Resize the RenderRectangle list
// Set up each new RenderRectangle
osgViewer::View* currView;
for(unsigned int i = oldSize; i < newSize; ++i)
{
// Create the new RenderRectangle
_renderList[i] = new RenderRectangle(_ovrDevice, _vrTextureBuffer);
currView = _renderList[i]->getSceneView();
// Set the event handler for this RenderRectangle
currView->addEventHandler(_eventHandler.get());
// Add the stats handler to this RenderRectangle
currView->addEventHandler(_statsHandler);
// Add the screen capture handler to this RenderRectangle
currView->addEventHandler(_screenCaptureHandler);
// Add the fulscreen handler
if(!_isEmbedded) currView->addEventHandler(_windowSizeHandler);
// Add the RenderRectangle's camera to the viewer
_viewer->addView(currView);
}
// Don't show border if we only have 1 RenderRectangle
if(newSize == 1) _renderList[0]->setShowBorder(false);
else _renderList[0]->setShowBorder(true);
// Tell event handler that this WindowProxy was modified
_eventHandler->windowModified();
collectScenes(); // Make a set containing all unique scenes
}
/** Set the scene contained in the given FrameManager at the given location. */
void WindowProxy::setScene(FrameManager *newfm, unsigned int row, unsigned int col)
{
// Location out of bounds
if(row >= _nRow || col >= _nCol)
{
std::cerr<< "WindowProxy::setScene ERROR: Grid position (" << row << "," << col << ") out of bounds." << std::endl;
return;
}
unsigned int loc = row*_nCol + col;
FrameManager *oldfm = _renderList[loc]->getFrameManager();
if(newfm == oldfm) return; // The same FrameManager is already there
// Set the new FrameManager for the RenderRectangle. If the old
// FrameManager is no longer being used, it will automatically be erased.
_renderList[loc]->setFrameManager(newfm);
collectScenes(); // Make set containing all unique scenes
}
/** Set the scene contained in the given FrameManager at the given location. */
FrameManager* WindowProxy::getScene(unsigned int row, unsigned int col)
{
if(row >= _nRow || col >= _nCol) return NULL; // Location out of bounds
return _renderList[row*_nCol + col]->getFrameManager();
}
/** Get the RenderRectangle used for the given grid position */
RenderRectangle* WindowProxy::getGridPosition(unsigned int row, unsigned int col)
{
if(row >= _nRow || col >= _nCol) return NULL; // Location out of bounds
return _renderList[row*_nCol + col].get();
}
void WindowProxy::setGraphicsContextCallback(GraphicsContextCallback *gcCallback)
{
_embeddedGraphics->setGraphicsContextCallback(gcCallback);
}
void WindowProxy::setMakeCurrentFunction(void (*fcn)(unsigned int *winID, bool *success))
{
_embeddedGraphics->setMakeCurrentFunction(fcn);
}
void WindowProxy::setUpdateContextFunction(void (*fcn)(unsigned int *winID, bool *success))
{
_embeddedGraphics->setUpdateContextFunction(fcn);
}
void WindowProxy::setSwapBuffersFunction(void (*fcn)(unsigned int *winID))
{
_embeddedGraphics->setSwapBuffersFunction(fcn);
}
void WindowProxy::run()
{
_animationState = INITIALIZING;
// Create the window
if(!setupWindow())
{
_animationState = FAILED;
return;
}
// Set up processor affinity for render and database threads
// First let OSG configure affinity
_viewer->configureAffinity();
// Next override this rendering thread's affinity so it doesn't
// suck up time on Proc0
_viewer->setProcessorAffinity(OpenThreads::Affinity());
// Finally set threading model
_viewer->setUseConfigureAffinity(false); // Already called configureAffinity
_viewer->setThreadingModel(osgViewer::ViewerBase::SingleThreaded);
// Set the reference time
_Tref = osg::Timer::instance()->tick();
// Initialize animation state
_animationState = _pauseAnimation ? PAUSED : ANIMATING;
// Loop until the user asks us to quit
while(!_viewer->done())
{
if(_pauseAnimation)
{
_animationState = PAUSED;
OpenThreads::Thread::YieldCurrentThread();
}
else
{
_animationState = ANIMATING;
// Pause to achieve desired framerate
_frameThrottle.frame();
// Do one frame: check events, update objects, render scene
frame();
}
}
// Close the graphics context before exiting this thread. If this is
// not done, then the graphics context will be released when this
// WindowProxy is destroyed. This could result in a seg fault if
// the context is already destroyed before OSG can release it.
_window->close();
// Shutdown OpenVR if needed
if (_useVR) _ovrDevice->shutdownVR();
_animationState = SUCCESS; // Indicate that animation is complete
}
/** Handle one frame of animation, including event handling */
void WindowProxy::frame()
{
// Use simulation time from synchonized WindowProxy
if(_timeSyncWinProxy.valid())
{
_currTime = _timeSyncWinProxy->getTime();
}
// Otherwise compute current simulation time if not paused
else if(!_timePaused)
{
double dt = osg::Timer::instance()->delta_s(_Tref, osg::Timer::instance()->tick());
_currTime = _offsetTime + dt*_timeScale;
if(_currTime < _minTime) _currTime = _minTime;
else if(_currTime > _maxTime) _currTime = _maxTime;
}
// Lock all scenes so that they aren't modified while being drawn
for(SceneSet::iterator sceneIter = _scenes.begin(); sceneIter != _scenes.end(); ++sceneIter)
{
(*sceneIter)->lock(FrameManager::LOW_PRIORITY);
}
// Process events, then update, cull, and draw all scenes
_viewer->frame(_currTime);
// Unlock all scenes so that they can be modified
for(SceneSet::iterator sceneIter = _scenes.begin(); sceneIter != _scenes.end(); ++sceneIter)
{
(*sceneIter)->unlock(FrameManager::LOW_PRIORITY);
}
}
/** Print info about this window to std::cout */
void WindowProxy::printInfo()
{
OSG_NOTICE<< "WindowProxy info:" << std::endl;
OSG_NOTICE<< "\t Window ID: " << _winID << std::endl;
if(_window.valid())
{
OSG_NOTICE<< "\tContext ID: " << _window->getState()->getContextID() << std::endl;
}
else
{
OSG_NOTICE<< "No graphics window created yet" << std::endl;
}
OSG_NOTICE<< "\tGrid size: " << _nRow << " rows, " << _nCol << " columns" << std::endl;
FrameManager *fm;
for(unsigned int i = 0; i < _renderList.size(); ++i)
{
fm = _renderList[i]->getFrameManager();
if(fm == NULL)
{
OSG_NOTICE<< "\tRenderRectangle " << i << " has no FrameManager" << std::endl;
}
else
{
OSG_NOTICE<< "\tRenderRectangle " << i << " has FrameManager " << fm << std::endl;
}
}
}
/** Take a screenshot of this window */
void WindowProxy::captureWindow(bool waitForCapture)
{
_screenCaptureHandler->setFramesToCapture(1);
_screenCaptureHandler->startCapture();
// Wait for capture to finish
while(waitForCapture && (_screenCaptureHandler->getFramesToCapture() > 0))
{
OpenThreads::Thread::YieldCurrentThread();
}
}
/** Set the window capture filename and type */
void WindowProxy::setWindowCaptureFile(const std::string& fname, const std::string& fext)
{
_screenCaptureHandler->setCaptureOperation(new osgViewer::ScreenCaptureHandler::WriteToFile(fname, fext));
}
/** Set a custom window capture operation */
void WindowProxy::setWindowCaptureOperation(osgViewer::ScreenCaptureHandler::CaptureOperation* captureOp)
{
_screenCaptureHandler->setCaptureOperation(captureOp);
}
osgViewer::ScreenCaptureHandler::CaptureOperation* WindowProxy::getWindowCaptureOperation() const
{
return _screenCaptureHandler->getCaptureOperation();
}
}
| 32.53024 | 324 | 0.636843 | ravidavi |
e0003e1c41cde00de6f9fc93e0742f5f3b2c1e13 | 2,039 | cc | C++ | 2838/4454746_AC_1297MS_544K.cc | twilightgod/twilight-poj-solution | 3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82 | [
"Apache-2.0"
] | 21 | 2015-05-26T10:18:12.000Z | 2021-06-01T09:39:47.000Z | 2838/4454746_AC_1297MS_544K.cc | twilightgod/twilight-poj-solution | 3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82 | [
"Apache-2.0"
] | null | null | null | 2838/4454746_AC_1297MS_544K.cc | twilightgod/twilight-poj-solution | 3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82 | [
"Apache-2.0"
] | 8 | 2015-09-30T08:41:15.000Z | 2020-03-11T03:49:42.000Z | /**********************************************************************
* Online Judge : POJ
* Problem Title : Graph Connectivity
* ID : 2838
* Date : 12/4/2008
* Time : 21:28:51
* Computer Name : EVERLASTING-PC
***********************************************************************/
#include<iostream>
using namespace std;
#define MAXN 1001
#define MAXE 40002
struct Edge
{
int v,next;
};
bool used[MAXN];
Edge e[MAXE];
int Link[MAXN];
int n,q;
int ec;
bool got;
void AddEdge(int u,int v)
{
e[ec].next=Link[u];
e[ec].v=v;
Link[u]=ec;
ec++;
}
void RemoveEdge(int u,int v)
{
int pre=-2;
for(int i=Link[u];i!=-1;i=e[i].next)
{
if (e[i].v==v)
{
if (pre==-2)
{
Link[u]=e[i].next;
}
else
{
e[pre].next=e[i].next;
}
}
pre=i;
}
}
// void DFS(int u,int goal)
// {
// if(u==goal)
// {
// got=true;
// return;
// }
// used[u]=true;
// for (int i=Link[u];i!=-1;i=e[i].next)
// {
// int v=e[i].v;
// if(!used[v])
// {
// DFS(v,goal);
// }
// }
// }
//
// bool IsLink(int u,int v)
// {
// memset(used,false,sizeof(used));
// got=false;
// DFS(u,v);
// return got;
// }
bool IsLink(int u,int goal)
{
memset(used,false,sizeof(used));
used[u]=true;
got=false;
int h=-1,t=0;
int q[MAXN];
q[0]=u;
while(h!=t)
{
int x=q[++h];
if (x==goal)
{
got=true;
goto ret;
}
for (int i=Link[x];i!=-1;i=e[i].next)
{
int v=e[i].v;
if(!used[v])
{
q[++t]=v;
used[v]=true;
}
}
}
ret:return got;
}
int main()
{
//freopen("in_2838.txt","r",stdin);
while (scanf("%d%d",&n,&q)!=-1)
{
getchar();
memset(Link,-1,sizeof(int)*(n+1));
ec=0;
for (int i=0;i<q;++i)
{
int u,v;
char cmd;
scanf("%c%d%d",&cmd,&u,&v);
getchar();
switch (cmd)
{
case 'I':
AddEdge(u,v);
AddEdge(v,u);
break;
case 'D':
RemoveEdge(u,v);
RemoveEdge(v,u);
break;
case 'Q':
printf("%c\n",IsLink(u,v)?'Y':'N');
break;
}
}
}
return 0;
}
| 14.359155 | 72 | 0.450221 | twilightgod |
e0034e8ffc83ec90b4e7728fac1ce8fdf2bb4549 | 1,196 | cpp | C++ | codelib/graph_theory/shortest_paths/dijkstra.cpp | TissueRoll/admu-progvar-notebook | efd1c48872d40aeabe2b03af7b986bb831c062b1 | [
"MIT"
] | null | null | null | codelib/graph_theory/shortest_paths/dijkstra.cpp | TissueRoll/admu-progvar-notebook | efd1c48872d40aeabe2b03af7b986bb831c062b1 | [
"MIT"
] | null | null | null | codelib/graph_theory/shortest_paths/dijkstra.cpp | TissueRoll/admu-progvar-notebook | efd1c48872d40aeabe2b03af7b986bb831c062b1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <utility>
#include <vector>
#include <queue>
#define INF 1e9
typedef std::pair<int, int> ii;
typedef std::vector<ii> vii;
struct graph {
int n;
vii *adj;
int *dist;
graph(int n) {
this->n = n;
adj = new vii[n];
dist = new int[n];
}
void add_edge(int u, int v, int w) {
adj[u].push_back({v, w});
// adj[v].push_back({u, w});
}
void dijkstra(int s) {
for (int u = 0; u < n; ++u)
dist[u] = INF;
dist[s] = 0;
std::priority_queue<ii, vii, std::greater<ii> > pq;
pq.push({0, s});
while (!pq.empty()) {
int u = pq.top().second;
int d = pq.top().first;
pq.pop();
if (dist[u] < d)
continue;
dist[u] = d;
for (auto &e : adj[u]) {
int v = e.first;
int w = e.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
}
};
int main() {
int N, M; std::cin>>N>>M;
int s, t; std::cin>>s>>t;
graph g(N);
for (int i = 0; i < M; ++i) {
int u, v, w; std::cin>>u>>v>>w;
g.add_edge(u, v, w);
}
g.dijkstra(s);
std::cout << g.dist[t] << "\n";
return 0;
}
| 18.984127 | 55 | 0.466555 | TissueRoll |
e007c46d5ae5857dd1506e356b9ae259308dfd8e | 7,976 | cpp | C++ | Ouroboros/Source/oConcurrency/tests/TESTthreadpool.cpp | igHunterKiller/ouroboros | 5e2cde7e6365341da297da10d8927b091ecf5559 | [
"MIT"
] | null | null | null | Ouroboros/Source/oConcurrency/tests/TESTthreadpool.cpp | igHunterKiller/ouroboros | 5e2cde7e6365341da297da10d8927b091ecf5559 | [
"MIT"
] | null | null | null | Ouroboros/Source/oConcurrency/tests/TESTthreadpool.cpp | igHunterKiller/ouroboros | 5e2cde7e6365341da297da10d8927b091ecf5559 | [
"MIT"
] | null | null | null | // Copyright (c) 2016 Antony Arciuolo. See License.txt regarding use.
#include <oBase/unit_test.h>
#include <oCore/byte.h>
#include <oCore/timer.h>
#include <oCore/finally.h>
#include <oConcurrency/concurrency.h>
#include <oConcurrency/threadpool.h>
#include <oString/fixed_string.h>
#include <oSystem/thread_traits.h>
#include <atomic>
#include <chrono>
#include "concurrency_tests_common.h"
using namespace ouro;
template<typename ThreadpoolT> void test_basics(unit_test::services& services, ThreadpoolT& t)
{
oCHECK(t.joinable(), "Threadpool is not joinable");
{
std::atomic<int> value(-1);
t.dispatch([&] { value++; });
t.flush();
oCHECK(value == 0, "Threadpool did not execute a single task correctly.");
}
static const int kNumDispatches = 100;
{
std::atomic<int> value(0);
for (int i = 0; i < kNumDispatches; i++)
t.dispatch([&] { value++; });
t.flush();
oCHECK(value == kNumDispatches, "Threadpool did not dispatch correctly, or failed to properly block on flush");
}
}
template<typename TaskGroupT> static void test_task_group(unit_test::services& services, TaskGroupT& g)
{
static const int kNumRuns = 100;
{
std::atomic<int> value = 0;
for (size_t i = 0; i < kNumRuns; i++)
g.run([&] { value++; });
g.wait();
std::atomic_thread_fence(std::memory_order_seq_cst);
oCHECK(value == kNumRuns, "std::function<void()>group either failed to run or failed to block on wait (1st run)");
}
{
std::atomic<int> value = 0;
for (int i = 0; i < kNumRuns; i++)
g.run([&] { value++; });
g.wait();
std::atomic_thread_fence(std::memory_order_seq_cst);
oCHECK(value == kNumRuns, "std::function<void()>group was not able to be reused or either failed to run or failed to block on wait (2nd run)");
}
}
static void set_value(size_t _Index, size_t* _pArray)
{
_pArray[_Index] = 1;
}
template<typename ThreadpoolT> static void test_parallel_for(unit_test::services& services, ThreadpoolT& thdpool)
{
static const size_t kFullRange = 100;
size_t Results[kFullRange];
memset(Results, 0, kFullRange * sizeof(size_t));
ouro::detail::parallel_for<16>(thdpool, 10, kFullRange - 10, std::bind(set_value, std::placeholders::_1, Results));
for (size_t i = 0; i < 10; i++)
oCHECK(Results[i] == 0, "wrote out of range at beginning");
for (size_t i = 10; i < kFullRange-10; i++)
oCHECK(Results[i] == 1, "bad write in main set_value loop");
for (size_t i = kFullRange-10; i < kFullRange; i++)
oCHECK(Results[i] == 0, "wrote out of range at end");
}
template<typename ThreadpoolT> static void TestT(unit_test::services& services)
{
ThreadpoolT t;
oFinally { if (t.joinable()) t.join(); };
test_basics(services, t);
t.join();
oCHECK(!t.joinable(), "Threadpool was joined, but remains joinable()");
}
void TESTthreadpool(unit_test::services& services)
{
TestT<threadpool<core_thread_traits>>(services);
}
void TESTtask_group(unit_test::services& services)
{
threadpool<core_thread_traits> t;
oFinally { if (t.joinable()) t.join(); };
detail::task_group<core_thread_traits> g(t);
test_task_group(services, g);
test_parallel_for(services, t);
}
namespace RatcliffJobSwarm {
#if 1
// Settings used in John Ratcliffe's code
#define FRACTAL_SIZE 2048
#define SWARM_SIZE 8
#define MAX_ITERATIONS 65536
#else
// Super-soak test... thread_pool tests take about ~30 sec each
#define FRACTAL_SIZE 16384
#define SWARM_SIZE 64
#define MAX_ITERATIONS 65536
#endif
#define TILE_SIZE ((FRACTAL_SIZE)/(SWARM_SIZE))
//********************************************************************************
// solves a single point in the mandelbrot set.
//********************************************************************************
static inline unsigned int mandelbrotPoint(unsigned int iterations,double real,double imaginary)
{
double fx,fy,xs,ys;
unsigned int count;
double two(2.0);
fx = real;
fy = imaginary;
count = 0;
do
{
xs = fx*fx;
ys = fy*fy;
fy = (two*fx*fy)+imaginary;
fx = xs-ys+real;
count++;
} while ( xs+ys < 4.0 && count < iterations);
return count;
}
static inline unsigned int solvePoint(unsigned int x,unsigned int y,double x1,double y1,double xscale,double yscale)
{
return mandelbrotPoint(MAX_ITERATIONS,(double)x*xscale+x1,(double)y*yscale+y1);
}
static void MandelbrotTask(size_t _Index, void* _pData, double _FX, double _FY, double _XScale, double _YScale)
{
unsigned int Xs = static_cast<unsigned int>(_Index % TILE_SIZE);
unsigned int Ys = static_cast<unsigned int>(_Index / TILE_SIZE);
const size_t stride = FRACTAL_SIZE * sizeof(unsigned char);
const size_t offset = Ys*stride + Xs*sizeof(unsigned char);
unsigned char* fractal_image = (unsigned char*)_pData + offset;
for (unsigned int y=0; y<SWARM_SIZE; y++)
{
unsigned char* pDest = fractal_image + stride * y;
for (unsigned int x=0; x<SWARM_SIZE; x++)
{
unsigned int v = 0xff & solvePoint(x+Xs,y+Ys,_FX,_FY,_XScale,_YScale);
*pDest++ = (unsigned char)v;
}
}
}
#pragma fenv_access (on)
#ifdef _DEBUG
#define DEBUG_DISCLAIMER "(DEBUG: Non-authoritive) "
#else
#define DEBUG_DISCLAIMER
#endif
} // namespace RatcliffJobSwarm
void ouro::TESTthreadpool_performance(ouro::unit_test::services& services, test_threadpool& thdpool)
{
const unsigned int taskRow = TILE_SIZE;
const unsigned int taskCount = taskRow*taskRow;
const double x1 = -0.56017680903960034334758968;
const double x2 = -0.5540396934395273995800156;
const double y1 = -0.63815211573948702427222672;
const double y2 = y1+(x2-x1);
const double xscale = (x2-x1)/(double)FRACTAL_SIZE;
const double yscale = (y2-y1)/(double)FRACTAL_SIZE;
std::vector<unsigned char> fractal;
fractal.resize(FRACTAL_SIZE*FRACTAL_SIZE);
const char* n = thdpool.name() ? thdpool.name() : "(null)";
services.trace("%s::dispatch()...", n);
timer tm;
for (unsigned int y=0; y<TILE_SIZE; y++)
for (unsigned int x=0; x<TILE_SIZE; x++)
thdpool.dispatch(std::bind(RatcliffJobSwarm::MandelbrotTask
, y*TILE_SIZE + x, fractal.data(), x1, y1, xscale, yscale));
auto scheduling_time = tm.seconds();
thdpool.flush();
auto execution_time = tm.seconds();
services.trace("%s::parallel_for()...", n);
tm.reset();
bool DidParallelFor = thdpool.parallel_for(0, taskCount
, std::bind(RatcliffJobSwarm::MandelbrotTask, std::placeholders::_1, fractal.data(), x1, y1, xscale, yscale));
auto parallel_for_time = tm.seconds();
const char* DebuggerDisclaimer = services.is_debugger_attached() ? "(DEBUGGER ATTACHED: Non-authoritive) " : "";
sstring st, et, pt;
format_duration(st, scheduling_time, true, true);
format_duration(et, execution_time, true, true);
format_duration(pt, parallel_for_time, true, true);
services.trace(DEBUG_DISCLAIMER
"%s%s: dispatch %s (%s sched), parallel_for %s"
, DebuggerDisclaimer, n, et.c_str(), st.c_str(), DidParallelFor ? pt.c_str() : "not supported");
}
struct threadpool_impl : test_threadpool
{
threadpool<threadpool_default_traits> t;
~threadpool_impl() { if (t.joinable()) t.join(); }
const char* name() const override { return "threadpool"; }
void dispatch(const std::function<void()>& _Task) override { return t.dispatch(_Task); }
bool parallel_for(size_t _Begin, size_t _End, const std::function<void(size_t _Index)>& _Task) override
{
ouro::detail::parallel_for<16>(t, _Begin, _End, _Task);
return true;
}
void flush() override { t.flush(); }
void release() override { if (t.joinable()) t.join(); }
};
namespace {
// Implement this inside a TESTMyThreadpool() function.
template<typename test_threadpool_impl_t> void TESTthreadpool_performance_impl1(unit_test::services& services)
{
test_threadpool_impl_t tp;
oFinally { tp.release(); };
TESTthreadpool_performance(services, tp);
}
}
void TESTthreadpool_perf(unit_test::services& services)
{
#ifdef _DEBUG
throw unit_test::skip_test("This is slow in debug, and pointless as a benchmark.");
#else
TESTthreadpool_performance_impl1<threadpool_impl>(services);
#endif
}
| 29.540741 | 145 | 0.698972 | igHunterKiller |
e009cfd0161b185c2a31ba65bc4c073bcace8b5a | 3,502 | hpp | C++ | include/nanorange/algorithm/partial_sort_copy.hpp | paulbendixen/NanoRange | 993dc03ebb2d3de5395648f3c0d112d230127c65 | [
"BSL-1.0"
] | null | null | null | include/nanorange/algorithm/partial_sort_copy.hpp | paulbendixen/NanoRange | 993dc03ebb2d3de5395648f3c0d112d230127c65 | [
"BSL-1.0"
] | null | null | null | include/nanorange/algorithm/partial_sort_copy.hpp | paulbendixen/NanoRange | 993dc03ebb2d3de5395648f3c0d112d230127c65 | [
"BSL-1.0"
] | null | null | null | // nanorange/algorithm/partial_sort_copy.hpp
//
// Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail dot com)
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef NANORANGE_ALGORITHM_PARTIAL_SORT_COPY_HPP_INCLUDED
#define NANORANGE_ALGORITHM_PARTIAL_SORT_COPY_HPP_INCLUDED
#include <nanorange/algorithm/make_heap.hpp>
#include <nanorange/algorithm/sort_heap.hpp>
NANO_BEGIN_NAMESPACE
namespace detail {
struct partial_sort_copy_fn {
private:
template <typename I1, typename S1, typename I2, typename S2,
typename Comp, typename Proj1, typename Proj2>
static constexpr I2 impl(I1 first, S1 last, I2 result_first,
S2 result_last, Comp& comp, Proj1& proj1, Proj2& proj2)
{
I2 r = result_first;
if (r == result_last) {
return r;
}
while (r != result_last && first != last) {
*r = *first;
++r;
++first;
}
nano::make_heap(result_first, r, comp, proj2);
const auto len = nano::distance(result_first, r);
while (first != last) {
iter_reference_t<I1>&& x = *first;
if (nano::invoke(comp, nano::invoke(proj1, x), nano::invoke(proj2, *result_first))) {
*result_first = std::forward<iter_reference_t<I1>>(x);
detail::sift_down_n(result_first, len, result_first, comp, proj2);
}
++first;
}
nano::sort_heap(result_first, r, comp, proj2);
return r;
}
public:
template <typename I1, typename S1, typename I2, typename S2,
typename Comp = ranges::less, typename Proj1 = identity, typename Proj2 = identity>
constexpr std::enable_if_t<
input_iterator<I1> && sentinel_for<S1, I1> &&
random_access_iterator<I2> &&
sentinel_for<S2, I2> &&
indirectly_copyable<I1, I2> && sortable<I2, Comp, Proj2> &&
indirect_strict_weak_order<Comp, projected<I1, Proj1>, projected<I2, Proj2>>,
I2>
operator()(I1 first, S1 last, I2 result_first, S2 result_last, Comp comp = Comp{},
Proj1 proj1 = Proj1{}, Proj2 proj2 = Proj2{}) const
{
return partial_sort_copy_fn::impl(std::move(first), std::move(last),
std::move(result_first), std::move(result_last),
comp, proj1, proj2);
}
template <typename Rng1, typename Rng2, typename Comp = ranges::less,
typename Proj1 = identity, typename Proj2 = identity>
constexpr std::enable_if_t<
input_range<Rng1> && random_access_range<Rng2> &&
indirectly_copyable<iterator_t<Rng1>, iterator_t<Rng2>> &&
sortable<iterator_t<Rng2>, Comp, Proj2> &&
indirect_strict_weak_order<Comp, projected<iterator_t<Rng1>, Proj1>, projected<iterator_t<Rng2>, Proj2>>,
safe_iterator_t<Rng2>>
operator()(Rng1&& rng, Rng2&& result_rng, Comp comp = Comp{},
Proj1 proj1 = Proj1{}, Proj2 proj2 = Proj2{}) const
{
return partial_sort_copy_fn::impl(nano::begin(rng), nano::end(rng),
nano::begin(result_rng), nano::end(result_rng),
comp, proj1, proj2);
}
};
}
NANO_INLINE_VAR(detail::partial_sort_copy_fn, partial_sort_copy)
NANO_END_NAMESPACE
#endif
| 37.255319 | 117 | 0.609937 | paulbendixen |
e00b55480d2577e41ab310aba0df1951acd303f6 | 1,356 | cpp | C++ | src/server/service/journey_service.cpp | neilbu/osrm-backend | 2a8e1f77459fef33ca34c9fe01ec62e88e255452 | [
"BSD-2-Clause"
] | null | null | null | src/server/service/journey_service.cpp | neilbu/osrm-backend | 2a8e1f77459fef33ca34c9fe01ec62e88e255452 | [
"BSD-2-Clause"
] | null | null | null | src/server/service/journey_service.cpp | neilbu/osrm-backend | 2a8e1f77459fef33ca34c9fe01ec62e88e255452 | [
"BSD-2-Clause"
] | 1 | 2021-11-24T14:24:44.000Z | 2021-11-24T14:24:44.000Z | #include "server/service/journey_service.hpp"
#include "server/api/parameters_parser.hpp"
#include "engine/api/journey_parameters.hpp"
#include "util/json_container.hpp"
#include <boost/format.hpp>
namespace osrm
{
namespace server
{
namespace service
{
engine::Status
JourneyService::RunQuery(std::size_t prefix_length, std::string &query, ResultT &result)
{
result = util::json::Object();
auto &json_result = result.get<util::json::Object>();
auto query_iterator = query.begin();
auto parameters =
api::parseParameters<engine::api::JourneyParameters>(query_iterator, query.end());
if (!parameters || query_iterator != query.end())
{
const auto position = std::distance(query.begin(), query_iterator);
json_result.values["code"] = "InvalidQuery";
json_result.values["message"] =
"Query string malformed close to position " + std::to_string(prefix_length + position);
return engine::Status::Error;
}
BOOST_ASSERT(parameters);
if (!parameters->IsValid())
{
json_result.values["code"] = "InvalidOptions";
json_result.values["message"] = "At least two coordinates required";
return engine::Status::Error;
}
BOOST_ASSERT(parameters->IsValid());
return BaseService::routing_machine.Journey(*parameters, json_result);
}
}
}
}
| 27.673469 | 99 | 0.684366 | neilbu |
e011bdf682f26f2f6b240cf77e544150e324d4e4 | 229 | cc | C++ | build/ARM/python/m5/internal/param_RawDiskImage.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | build/ARM/python/m5/internal/param_RawDiskImage.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | build/ARM/python/m5/internal/param_RawDiskImage.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
extern "C" {
void init_param_RawDiskImage();
}
EmbeddedSwig embed_swig_param_RawDiskImage(init_param_RawDiskImage, "m5.internal._param_RawDiskImage");
| 25.444444 | 111 | 0.624454 | Jakgn |
e014dba6929225b4ad46b6cdc6892bd064be55de | 2,249 | cpp | C++ | src/LN_SHORT_ME.cpp | dowdlelt/LAYNII | 8d434da57f3126bcd304577bd41eaa32d504df04 | [
"BSD-3-Clause"
] | 70 | 2018-04-09T13:16:42.000Z | 2022-03-25T11:35:05.000Z | src/LN_SHORT_ME.cpp | dowdlelt/LAYNII | 8d434da57f3126bcd304577bd41eaa32d504df04 | [
"BSD-3-Clause"
] | 48 | 2018-12-06T01:17:48.000Z | 2022-03-31T13:55:28.000Z | src/LN_SHORT_ME.cpp | dowdlelt/LAYNII | 8d434da57f3126bcd304577bd41eaa32d504df04 | [
"BSD-3-Clause"
] | 17 | 2019-04-25T20:57:34.000Z | 2022-03-07T12:20:31.000Z |
#include "../dep/laynii_lib.h"
int show_help(void) {
printf(
"LN_SHORT_ME: Convert nifti datatype to SHORT. \n"
" In order not to loose too much depth resolution for \n"
" floating point values, the nii-header slope is scaled by 1000 \n"
"\n"
"Usage:\n"
" LN_SHORT_ME -input data_file.nii \n"
" LN_SHORT_ME -input data_file.nii -output output_filename.nii \n"
" ../LN_SHORT_ME -input lo_VASO_act.nii -output short.nii\n"
"\n"
"Options:\n"
" -help : Show this help.\n"
" -input : Dataset that should be shorted data.\n"
" -output : (Optional) Output filename, including .nii or\n"
" .nii.gz, and path if needed. Overwrites existing files.\n"
"\n");
return 0;
}
int main(int argc, char *argv[]) {
bool use_outpath = false;
char *fin = NULL, *fout = NULL;
int ac;
if (argc < 3) return show_help();
// Process user options
for (ac = 1; ac < argc; ac++) {
if (!strncmp(argv[ac], "-h", 2)) {
return show_help();
} else if (!strcmp(argv[ac], "-input")) {
if (++ac >= argc) {
fprintf(stderr, "** missing argument for -input\n");
return 1;
}
fin = argv[ac];
fout = fin;
} else if (!strcmp(argv[ac], "-output")) {
if (++ac >= argc) {
fprintf(stderr, "** missing argument for -output\n");
return 2;
}
use_outpath = true;
fout = argv[ac];
} else {
fprintf(stderr, "** invalid option, '%s'\n", argv[ac]);
return 1;
}
}
if (!fin) {
fprintf(stderr, "** missing option '-input'\n");
return 1;
}
// Read input dataset
nifti_image *nii = nifti_image_read(fin, 1);
if (!nii) {
fprintf(stderr, "** failed to read NIfTI from '%s'\n", fin);
return 2;
}
log_welcome("LN_SHORT_ME");
log_nifti_descriptives(nii);
// Cast input data to short (int16)
nifti_image *nii_new = copy_nifti_as_float16(nii);
save_output_nifti(fout, "short", nii_new, true, use_outpath);
cout << " Finished." << endl;
return 0;
}
| 29.207792 | 81 | 0.52779 | dowdlelt |
e01754250c7f71881c4be4dba650ad21f4341f6c | 1,716 | hpp | C++ | include/libtransistor/cpp/ipc.hpp | kgsws/libtransistor | e90d27a52e9471c3978f02413ab226c15e93ca10 | [
"ISC"
] | 4 | 2018-01-07T20:22:39.000Z | 2018-01-11T19:09:40.000Z | include/libtransistor/cpp/ipc.hpp | kgsws/libtransistor | e90d27a52e9471c3978f02413ab226c15e93ca10 | [
"ISC"
] | null | null | null | include/libtransistor/cpp/ipc.hpp | kgsws/libtransistor | e90d27a52e9471c3978f02413ab226c15e93ca10 | [
"ISC"
] | null | null | null | /**
* @file libtransistor/cpp/ipc.hpp
* @brief IPC (C++ header)
*/
#pragma once
#include<libtransistor/cpp/types.hpp>
#include<libtransistor/ipc.h>
#include<type_traits>
namespace trn {
namespace ipc {
class Message {
public:
ipc_message_t msg;
};
template<typename T>
struct OutObject {
OutObject(T &ref) : value(&ref) { }
T *value;
};
template<typename T>
struct InRaw {
InRaw(T value) : value(value) { }
static_assert(std::is_pod<T>::value, "InRaw types must be POD");
T value;
T &operator*() {
return value;
}
};
template<typename T>
struct OutRaw {
OutRaw(T &ref) : value(&ref) { }
static_assert(std::is_pod<T>::value, "OutRaw types must be POD");
OutRaw<T> &operator=(T val) {
*value = val;
return *this;
}
T &operator*() {
return *value;
}
T *value;
};
struct copy {};
struct move {};
template<typename T, typename Transfer>
struct OutHandle;
template<typename Transfer>
struct OutHandle<handle_t, Transfer> {
OutHandle(handle_t &handle) : handle(&handle) {}
OutHandle<handle_t, Transfer> &operator=(handle_t val) {
*handle = val;
return *this;
}
handle_t *handle;
};
template<typename T, typename Transfer>
struct OutHandle {
OutHandle(handle_t &handle) : handle(&handle) {}
OutHandle<T, Transfer> &operator=(T &val) {
*handle = val.handle;
return *this;
}
handle_t *handle;
};
template<typename T, uint32_t type, size_t expected_size = 0>
struct Buffer {
Buffer(std::vector<T> &vec) : Buffer(vec.data(), vec.size() * sizeof(T)) { }
Buffer(T *data, size_t size) : data(data), size(size) { }
T *data;
size_t size;
};
struct InPid {
uint64_t value;
};
struct OutPid {
OutPid(uint64_t &ref) : value(&ref) { }
uint64_t *value;
};
}
}
| 16.342857 | 77 | 0.664918 | kgsws |
e0246ccec6ac054a3398780c0da5d87f0a1732c3 | 1,199 | cpp | C++ | pass.cpp | LakhanShanker/mypage | a2a5791225156be355623ad864c5491d13483a31 | [
"MIT"
] | null | null | null | pass.cpp | LakhanShanker/mypage | a2a5791225156be355623ad864c5491d13483a31 | [
"MIT"
] | null | null | null | pass.cpp | LakhanShanker/mypage | a2a5791225156be355623ad864c5491d13483a31 | [
"MIT"
] | null | null | null |
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
void check(char a[]);
main()
{
int t;
char a[30];
scanf("%d",&t);
while(t--)
{
scanf("%s",a);
check(a);
}
}
void check(char a[])
{
char c;
int len,i,flag5=0,flag1=0,flag2=0,flag3=0,flag4=0;
len=strlen(a);
if(len<10)
flag1=1;
else
{
for(i=0;i<len;i++)
if((a[i]>=48&&a[i]<=58))
{
flag2=0;
break;
}
else
flag2=1;
for(i=1;i<len-1;i++)
if((a[i]>=0&&a[i]<=9))
{
flag5=0;
break;
}
else
flag5=1;
for(i=0;i<len;i++)
if((a[i]>=65&&a[i]<=90))
{
flag3=0;
break;
}
else
flag3=1;
for(i=0;i<len;i++)
if(a[i]=='#'||a[i]=='@'||a[i]=='?'||a[i]=='&'||a[i]=='%')
{
flag4=0;
break;
}
else
flag4=1;
}
if(flag1==1||flag1==5||flag2==1||flag3==1||flag4==1)
printf("NO\n");
else
printf("YES\n");
return;
}
| 15.371795 | 66 | 0.337781 | LakhanShanker |
e024723547d60f76c4e4d885ad5eb487d044abe3 | 1,699 | cpp | C++ | vs2015/realtime_server/realtime_srv/common/RealtimeSrvTiming.cpp | no5ix/realtime-server | c786d5329382c2d1f19673ba3025d516b83e1cc4 | [
"MIT"
] | 465 | 2018-06-21T02:50:56.000Z | 2022-03-27T11:51:46.000Z | vs2015/realtime_server/realtime_srv/common/RealtimeSrvTiming.cpp | no5ix/RealTimeServer | 9e3b690c1d12fe32068bc4637fa1919cd52ce854 | [
"MIT"
] | 8 | 2018-08-09T09:25:00.000Z | 2022-03-10T14:54:51.000Z | vs2015/realtime_server/realtime_srv/common/RealtimeSrvTiming.cpp | no5ix/RealTimeServer | 9e3b690c1d12fe32068bc4637fa1919cd52ce854 | [
"MIT"
] | 113 | 2018-06-25T01:42:20.000Z | 2022-03-23T11:27:56.000Z | #include "realtime_srv/common/RealtimeSrvShared.h"
#ifndef IS_WIN
#include <chrono>
using namespace std::chrono;
#endif // IS_WIN
#ifdef IS_LINUX
using namespace muduo;
#endif // IS_LINUX
using namespace realtime_srv;
RealtimeSrvTiming RealtimeSrvTiming::sInst;
namespace
{
#ifdef IS_WIN
LARGE_INTEGER sStartTime = { 0 };
#else
#ifdef IS_LINUX
//muduo::Timestamp sStartTime;
#else
high_resolution_clock::time_point sStartTime;
#endif // IS_LINUX
#endif
}
RealtimeSrvTiming::RealtimeSrvTiming()
#ifdef IS_LINUX
: sStartTime(muduo::Timestamp::now())
#endif
{
#ifdef IS_WIN
LARGE_INTEGER perfFreq;
QueryPerformanceFrequency(&perfFreq);
perfCountDuration_ = 1.0 / perfFreq.QuadPart;
QueryPerformanceCounter(&sStartTime);
lastFrameStartTime_ = GetGameTimeD();
#else
#ifndef IS_LINUX
sStartTime = high_resolution_clock::now();
#endif
#endif
}
void RealtimeSrvTiming::Update()
{
double currentTime = GetGameTimeD();
deltaTime_ = (float)(currentTime - lastFrameStartTime_);
lastFrameStartTime_ = currentTime;
frameStartTimef_ = static_cast<float> (lastFrameStartTime_);
}
double RealtimeSrvTiming::GetGameTimeD() const
{
#ifdef IS_WIN
LARGE_INTEGER curTime, timeSinceStart;
QueryPerformanceCounter(&curTime);
timeSinceStart.QuadPart = curTime.QuadPart - sStartTime.QuadPart;
return timeSinceStart.QuadPart * perfCountDuration_;
#else
#ifdef IS_LINUX
return muduo::timeDifference(muduo::Timestamp::now(), sStartTime);
#else
auto now = high_resolution_clock::now();
auto ms = duration_cast<milliseconds>(now - sStartTime).count();
//a little uncool to then convert into a double just to go back, but oh well.
return static_cast<double>(ms) / 1000;
#endif
#endif
}
| 18.877778 | 78 | 0.773396 | no5ix |
e02eaba15aadf72b9b4745ef1b182c727e42b8b1 | 326 | hpp | C++ | poo_basic/attributes/ClasseAtributoEstatico/ClasseAtributoEstatico.hpp | stemDaniel/ufmg-pds2 | 4dbb536a0926b617d04d133cbd3f7a5a223e113e | [
"MIT"
] | null | null | null | poo_basic/attributes/ClasseAtributoEstatico/ClasseAtributoEstatico.hpp | stemDaniel/ufmg-pds2 | 4dbb536a0926b617d04d133cbd3f7a5a223e113e | [
"MIT"
] | null | null | null | poo_basic/attributes/ClasseAtributoEstatico/ClasseAtributoEstatico.hpp | stemDaniel/ufmg-pds2 | 4dbb536a0926b617d04d133cbd3f7a5a223e113e | [
"MIT"
] | null | null | null | #ifndef CLASSEATRIBUTOESTATICO
#define CLASSEATRIBUTOESTATICO
#include <iostream>
using namespace std;
class ClasseAtributoEstatico {
public:
static int numero;
ClasseAtributoEstatico() {
ClasseAtributoEstatico::numero++;
}
void imprimirNumero () {
cout << ClasseAtributoEstatico::numero << endl;
}
};
#endif | 14.818182 | 49 | 0.751534 | stemDaniel |
e02f16a086f82a83434454eb547e072d4ff58edd | 5,288 | cc | C++ | test/common/upstream/eds_speed_test.cc | jchorl/envoy | 11c9223aac10834b7d5d2e399b0b4b59e0a3b3a1 | [
"Apache-2.0"
] | 1 | 2021-03-18T07:17:50.000Z | 2021-03-18T07:17:50.000Z | test/common/upstream/eds_speed_test.cc | jchorl/envoy | 11c9223aac10834b7d5d2e399b0b4b59e0a3b3a1 | [
"Apache-2.0"
] | null | null | null | test/common/upstream/eds_speed_test.cc | jchorl/envoy | 11c9223aac10834b7d5d2e399b0b4b59e0a3b3a1 | [
"Apache-2.0"
] | 1 | 2020-09-14T05:29:19.000Z | 2020-09-14T05:29:19.000Z | // Note: this should be run with --compilation_mode=opt, and would benefit from a
// quiescent system with disabled cstate power management.
#include "envoy/config/cluster/v3/cluster.pb.h"
#include "envoy/config/core/v3/health_check.pb.h"
#include "envoy/config/endpoint/v3/endpoint.pb.h"
#include "envoy/config/endpoint/v3/endpoint_components.pb.h"
#include "envoy/service/discovery/v3/discovery.pb.h"
#include "envoy/stats/scope.h"
#include "common/config/utility.h"
#include "common/singleton/manager_impl.h"
#include "common/upstream/eds.h"
#include "server/transport_socket_config_impl.h"
#include "test/common/upstream/utility.h"
#include "test/mocks/local_info/mocks.h"
#include "test/mocks/protobuf/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/ssl/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/utility.h"
#include "benchmark/benchmark.h"
namespace Envoy {
namespace Upstream {
class EdsSpeedTest {
public:
EdsSpeedTest() : api_(Api::createApiForTest(stats_)) {}
void resetCluster(const std::string& yaml_config, Cluster::InitializePhase initialize_phase) {
local_info_.node_.mutable_locality()->set_zone("us-east-1a");
eds_cluster_ = parseClusterFromV2Yaml(yaml_config);
Envoy::Stats::ScopePtr scope = stats_.createScope(fmt::format(
"cluster.{}.",
eds_cluster_.alt_stat_name().empty() ? eds_cluster_.name() : eds_cluster_.alt_stat_name()));
Envoy::Server::Configuration::TransportSocketFactoryContextImpl factory_context(
admin_, ssl_context_manager_, *scope, cm_, local_info_, dispatcher_, random_, stats_,
singleton_manager_, tls_, validation_visitor_, *api_);
cluster_ = std::make_shared<EdsClusterImpl>(eds_cluster_, runtime_, factory_context,
std::move(scope), false);
EXPECT_EQ(initialize_phase, cluster_->initializePhase());
eds_callbacks_ = cm_.subscription_factory_.callbacks_;
}
void initialize() {
EXPECT_CALL(*cm_.subscription_factory_.subscription_, start(_));
cluster_->initialize([this] { initialized_ = true; });
}
// Set up an EDS config with multiple priorities, localities, weights and make sure
// they are loaded and reloaded as expected.
void priorityAndLocalityWeightedHelper(bool ignore_unknown_dynamic_fields, int num_hosts) {
envoy::config::endpoint::v3::ClusterLoadAssignment cluster_load_assignment;
cluster_load_assignment.set_cluster_name("fare");
resetCluster(R"EOF(
name: name
connect_timeout: 0.25s
type: EDS
eds_cluster_config:
service_name: fare
eds_config:
api_config_source:
cluster_names:
- eds
refresh_delay: 1s
)EOF",
Envoy::Upstream::Cluster::InitializePhase::Secondary);
// Add a whole bunch of hosts in a single place:
auto* endpoints = cluster_load_assignment.add_endpoints();
endpoints->set_priority(1);
auto* locality = endpoints->mutable_locality();
locality->set_region("region");
locality->set_zone("zone");
locality->set_sub_zone("sub_zone");
endpoints->mutable_load_balancing_weight()->set_value(1);
uint32_t port = 1000;
for (int i = 0; i < num_hosts; ++i) {
auto* socket_address = endpoints->add_lb_endpoints()
->mutable_endpoint()
->mutable_address()
->mutable_socket_address();
socket_address->set_address("10.0.1." + std::to_string(i / 60000));
socket_address->set_port_value((port + i) % 60000);
}
// this is what we're actually testing:
validation_visitor_.setSkipValidation(ignore_unknown_dynamic_fields);
initialize();
Protobuf::RepeatedPtrField<ProtobufWkt::Any> resources;
resources.Add()->PackFrom(cluster_load_assignment);
eds_callbacks_->onConfigUpdate(resources, "");
ASSERT(initialized_);
}
bool initialized_{};
Stats::IsolatedStoreImpl stats_;
Ssl::MockContextManager ssl_context_manager_;
envoy::config::cluster::v3::Cluster eds_cluster_;
NiceMock<MockClusterManager> cm_;
NiceMock<Event::MockDispatcher> dispatcher_;
std::shared_ptr<EdsClusterImpl> cluster_;
Config::SubscriptionCallbacks* eds_callbacks_{};
NiceMock<Runtime::MockRandomGenerator> random_;
NiceMock<Runtime::MockLoader> runtime_;
NiceMock<LocalInfo::MockLocalInfo> local_info_;
NiceMock<Server::MockAdmin> admin_;
Singleton::ManagerImpl singleton_manager_{Thread::threadFactoryForTest()};
NiceMock<ThreadLocal::MockInstance> tls_;
ProtobufMessage::MockValidationVisitor validation_visitor_;
Api::ApiPtr api_;
};
} // namespace Upstream
} // namespace Envoy
static void priorityAndLocalityWeighted(benchmark::State& state) {
Envoy::Thread::MutexBasicLockable lock;
Envoy::Logger::Context logging_state(spdlog::level::warn,
Envoy::Logger::Logger::DEFAULT_LOG_FORMAT, lock, false);
for (auto _ : state) {
Envoy::Upstream::EdsSpeedTest speed_test;
speed_test.priorityAndLocalityWeightedHelper(state.range(0), state.range(1));
}
}
BENCHMARK(priorityAndLocalityWeighted)->Ranges({{false, true}, {2000, 100000}});
| 39.17037 | 100 | 0.713124 | jchorl |
e030a78353f11d5858d2b35a652a5fbea908114c | 15,695 | cpp | C++ | dev/mosquitto_transport/a_transport_manager.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | 3 | 2020-01-25T12:49:55.000Z | 2021-11-08T10:42:09.000Z | dev/mosquitto_transport/a_transport_manager.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | null | null | null | dev/mosquitto_transport/a_transport_manager.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | null | null | null | /*
* mosquitto_transport-1.0
*/
/*!
* \file
* \brief Main transport manager agent.
*/
#include <mosquitto_transport/a_transport_manager.hpp>
#include <mosquitto_transport/tools.hpp>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <algorithm>
#include <iterator>
namespace mosquitto_transport {
namespace details {
constexpr int qos_to_use = 0;
//
// subscription_info_t
//
subscription_info_t::subscription_info_t()
: m_status{ subscription_status_t::new_subscription }
{}
subscription_status_t
subscription_info_t::status() const
{ return m_status; }
void
subscription_info_t::subscription_created(
const std::string & topic_name )
{
m_status = subscription_status_t::subscribed;
m_failure_description.clear();
for( const auto & p : m_postmans )
p->subscription_available( topic_name );
}
void
subscription_info_t::subscription_lost(
const std::string & topic_name )
{
m_status = subscription_status_t::unsubscribed;
m_failure_description.clear();
for( const auto & p : m_postmans )
p->subscription_unavailable( topic_name );
}
void
subscription_info_t::subscription_failed(
const std::string & topic_name,
const std::string & description )
{
m_status = subscription_status_t::failed;
m_failure_description = description;
for( const auto & p : m_postmans )
p->subscription_failed( topic_name, description );
}
bool
subscription_info_t::has_postmans() const
{
return !m_postmans.empty();
}
void
subscription_info_t::add_postman(
const std::string & topic_name,
const postman_shared_ptr_t & postman )
{
if( subscription_status_t::subscribed == m_status )
postman->subscription_available( topic_name );
else if( subscription_status_t::failed == m_status )
postman->subscription_failed( topic_name, m_failure_description );
// If there is no any exception after status setup the postman
// can be stored in postmans set.
m_postmans.insert( postman );
}
void
subscription_info_t::remove_postman( const postman_shared_ptr_t & postman )
{
m_postmans.erase( postman );
}
void
subscription_info_t::deliver_message(
const std::string & topic,
const std::string & payload )
{
for( const auto & p : m_postmans )
p->post( topic, payload );
}
//
// make_mosq_instance
//
mosquitto_unique_ptr_t
make_mosq_instance(
const std::string & client_id,
a_transport_manager_t * callback_param )
{
auto m = mosquitto_new( client_id.c_str(), true, callback_param );
ensure_with_explblock< ex_t >( m,
[]{ return fmt::format( "mosquitto_new failed, errno: {}", errno ); } );
mosquitto_unique_ptr_t retval{ m, &mosquitto_destroy };
return retval;
}
} /* namespace details */
using namespace details;
//
// a_transport_manager_t
//
a_transport_manager_t::a_transport_manager_t(
context_t ctx,
lib_initializer_t & /*lib_initializer*/,
connection_params_t connection_params,
std::shared_ptr< spdlog::logger > logger )
: so_5::agent_t{ ctx }
, m_connection_params( std::move(connection_params) )
, m_self_mbox{ so_environment().create_mbox() }
, m_logger{ std::move(logger) }
, m_mosq{
make_mosq_instance(
m_connection_params.m_client_id, this ) }
{
setup_mosq_callbacks();
}
void
a_transport_manager_t::so_define_agent()
{
st_working
.event( m_self_mbox, &a_transport_manager_t::on_subscribe_topic )
.event( m_self_mbox, &a_transport_manager_t::on_unsubscribe_topic )
.event( m_self_mbox, &a_transport_manager_t::on_message_received,
so_5::thread_safe );
st_disconnected
.on_enter( [this] {
// Everyone should be informed that connection lost.
so_5::send< broker_disconnected_t >( m_self_mbox );
} )
.event< connected_t >(
m_self_mbox, &a_transport_manager_t::on_connected );
st_connected
.on_enter( [this] {
// Everyone should be informed that connection established.
so_5::send< broker_connected_t >( m_self_mbox );
// All registered subscriptions must be restored.
restore_subscriptions_on_reconnect();
} )
.on_exit( [this] {
// All subscriptions are lost.
drop_subscription_statuses();
// No more pending subscriptions.
m_pending_subscriptions.clear();
} )
.event< disconnected_t >(
m_self_mbox, &a_transport_manager_t::on_disconnected )
.event( m_self_mbox, &a_transport_manager_t::on_subscription_result )
.event( m_self_mbox, &a_transport_manager_t::on_publish_message,
so_5::thread_safe )
.event( &a_transport_manager_t::on_pending_subscriptions_timer );
}
void
a_transport_manager_t::so_evt_start()
{
// mosquitto event loop must be started.
ensure_mosq_success(
mosquitto_loop_start( m_mosq.get() ),
[]{ return "mosquitto_loop_start failed"; } );
this >>= st_disconnected;
// Initiate connection to broker.
ensure_mosq_success(
mosquitto_connect_async(
m_mosq.get(),
m_connection_params.m_host.c_str(),
static_cast< int >(m_connection_params.m_port),
static_cast< int >(m_connection_params.m_keepalive) ),
[&]{ return fmt::format(
"mosquitto_connect_async({}, {}, {}) failed",
m_connection_params.m_host,
m_connection_params.m_port,
m_connection_params.m_keepalive ); } );
m_pending_subscriptions_timer =
so_5::send_periodic< pending_subscriptions_timer_t >( *this,
std::chrono::seconds{1},
std::chrono::seconds{1} );
}
void
a_transport_manager_t::so_evt_finish()
{
// mosquitto event-loop must be stopped here!
if( st_connected == so_current_state() )
// Because there is a connection it must be gracefully closed.
ensure_mosq_success(
mosquitto_disconnect( m_mosq.get() ),
[]{ return "mosquitto_disconnect failed"; } );
ensure_mosq_success(
mosquitto_loop_stop( m_mosq.get(), true ),
[]{ return "mosquitto_loop_stop failed"; } );
}
instance_t
a_transport_manager_t::instance() const
{
return instance_t{ so_environment(), m_self_mbox };
}
void
a_transport_manager_t::mqtt_will_set(
const std::string & topic_name,
const std::string & payload,
int qos,
bool retain )
{
ensure_mosq_success(
mosquitto_will_set( m_mosq.get(),
topic_name.c_str(),
//FIXME: there could be utility class mqtt_payload_size with checking
//the size of payload (this value cannot exces 268,435,455 bytes).
static_cast< int >( payload.size() ),
payload.data(),
qos,
retain ),
[&] { return fmt::format(
"mosquitto_will_set({}, {} bytes) failed",
topic_name,
payload.size() ); } );
}
void
a_transport_manager_t::set_subscription_timeout(
std::chrono::steady_clock::duration timeout )
{
m_subscription_timeout = timeout;
}
void
a_transport_manager_t::setup_mosq_callbacks()
{
mosquitto_log_callback_set(
m_mosq.get(),
&a_transport_manager_t::on_log_callback );
mosquitto_connect_callback_set(
m_mosq.get(),
&a_transport_manager_t::on_connect_callback );
mosquitto_disconnect_callback_set(
m_mosq.get(),
&a_transport_manager_t::on_disconnect_callback );
mosquitto_subscribe_callback_set(
m_mosq.get(),
&a_transport_manager_t::on_subscribe_callback );
mosquitto_message_callback_set(
m_mosq.get(),
&a_transport_manager_t::on_message_callback );
}
void
a_transport_manager_t::on_connect_callback(
mosquitto *,
void * this_object,
int connect_result )
{
auto tm = reinterpret_cast< a_transport_manager_t * >(this_object);
tm->m_logger->info( "on_connect, rc={}/{}",
connect_result,
mosquitto_connack_string( connect_result ) );
if( 0 == connect_result )
so_5::send< connected_t >( tm->m_self_mbox );
}
void
a_transport_manager_t::on_disconnect_callback(
mosquitto *,
void * this_object,
int disconnect_result )
{
auto tm = reinterpret_cast< a_transport_manager_t * >(this_object);
tm->m_logger->info( "on_disconnect, rc={}", disconnect_result );
if( 0 != disconnect_result )
so_5::send< disconnected_t >( tm->m_self_mbox );
}
void
a_transport_manager_t::on_subscribe_callback(
mosquitto *,
void * this_object,
int mid,
int qos_count,
const int * qos_items )
{
auto tm = reinterpret_cast< a_transport_manager_t * >(this_object);
if( qos_count )
{
tm->m_logger->trace( "on_subscribe, mid={}, qos_count={}",
mid, qos_count );
so_5::send< subscription_result_t >( tm->m_self_mbox,
mid,
std::vector< int >( qos_items, qos_items + qos_count ) );
}
else
tm->m_logger->warn( "on_subscribe, qos_count is zero, mid={}", mid );
}
void
a_transport_manager_t::on_message_callback(
mosquitto *,
void * this_object,
const mosquitto_message * msg )
{
auto tm = reinterpret_cast< a_transport_manager_t * >(this_object);
tm->m_logger->trace( "on_message, topic={}, payloadlen={}, qos={}"
", retain={}",
msg->topic, msg->payloadlen, msg->qos, msg->retain );
so_5::send< message_received_t >( tm->m_self_mbox, *msg );
}
void
a_transport_manager_t::on_log_callback(
mosquitto *,
void * this_object,
int log_level,
const char * log_msg )
{
static const char log_line_format[] = "[libmosquitto] {}";
auto tm = reinterpret_cast< a_transport_manager_t * >(this_object);
auto & logger = *(tm->m_logger);
switch( log_level )
{
case MOSQ_LOG_ERR :
logger.error( log_line_format, log_msg ); break;
case MOSQ_LOG_WARNING :
case MOSQ_LOG_NOTICE :
logger.warn( log_line_format, log_msg ); break;
case MOSQ_LOG_INFO :
logger.info( log_line_format, log_msg ); break;
case MOSQ_LOG_DEBUG :
logger.debug( log_line_format, log_msg ); break;
}
}
void
a_transport_manager_t::on_connected()
{
this >>= st_connected;
}
void
a_transport_manager_t::on_disconnected()
{
this >>= st_disconnected;
}
void
a_transport_manager_t::on_subscribe_topic(
const subscribe_topic_t & cmd )
{
m_logger->debug( "add topic postman, topic={}, postman={}",
cmd.m_topic_name, cmd.m_postman );
auto & info = m_registered_subscriptions[ cmd.m_topic_name ];
info.add_postman( cmd.m_topic_name, cmd.m_postman );
if( subscription_status_t::new_subscription == info.status() )
{
m_delivery_map.insert( cmd.m_topic_name, &info );
try_subscribe_topic( cmd.m_topic_name );
}
}
void
a_transport_manager_t::on_unsubscribe_topic(
const unsubscribe_topic_t & cmd )
{
m_logger->debug( "remove topic postman, topic={}, postman={}",
cmd.m_topic_name, cmd.m_postman );
auto ittopic = m_registered_subscriptions.find( cmd.m_topic_name );
if( ittopic != m_registered_subscriptions.end() )
{
ittopic->second.remove_postman( cmd.m_postman );
if( !ittopic->second.has_postmans() )
{
m_delivery_map.erase( cmd.m_topic_name, &(ittopic->second) );
m_registered_subscriptions.erase( ittopic );
m_logger->info( "topic unsubscription, topic={}",
cmd.m_topic_name );
auto r = mosquitto_unsubscribe( m_mosq.get(), 0,
cmd.m_topic_name.c_str() );
// If there is an error we can't do something reasonable.
// Just log it and ignore.
if( r != MOSQ_ERR_SUCCESS )
m_logger->warn( "mosquitto_unsubscribe failed, "
"topic={}, rc={}",
cmd.m_topic_name, r );
}
}
else
m_logger->warn( "topic for unsubscription is not registered, "
"topic={}", cmd.m_topic_name );
}
void
a_transport_manager_t::on_subscription_result(
const subscription_result_t & cmd )
{
auto itpending = m_pending_subscriptions.find( cmd.m_mid );
if( itpending != m_pending_subscriptions.end() )
{
auto ittopic = m_registered_subscriptions.find(
itpending->second.m_topic_name );
if( ittopic != m_registered_subscriptions.end() )
{
m_logger->debug( "subscription_result: mid={}, topic={}, "
"granted_qos={}",
cmd.m_mid,
itpending->second.m_topic_name,
cmd.m_granted_qos.front() );
process_subscription_result(
itpending->second.m_topic_name,
ittopic->second,
cmd.m_granted_qos.front() );
}
else
m_logger->warn( "unknown topic for subscription_result, "
"mid={}, topic={}",
cmd.m_mid,
itpending->second.m_topic_name );
m_pending_subscriptions.erase( itpending );
}
else
m_logger->warn( "unknown mid in subscription_result_t, mid={}",
cmd.m_mid );
}
void
a_transport_manager_t::on_pending_subscriptions_timer(
mhood_t< pending_subscriptions_timer_t > )
{
if( m_pending_subscriptions.empty() )
return;
const auto now = std::chrono::steady_clock::now();
for( auto it = m_pending_subscriptions.begin();
it != m_pending_subscriptions.end(); )
{
auto & pending = it->second;
if( now - pending.m_initiated_at > m_subscription_timeout )
{
auto itdel = it++;
m_logger->error( "subscription timed out, topic={}",
pending.m_topic_name );
auto ittopic = m_registered_subscriptions.find(
pending.m_topic_name );
ittopic->second.subscription_failed(
pending.m_topic_name,
"subscription timed out" );
m_pending_subscriptions.erase( itdel );
}
else
++it;
}
}
void
a_transport_manager_t::on_message_received(
const message_received_t & cmd )
{
auto subscribers = m_delivery_map.match( cmd.m_topic );
if( !subscribers.empty() )
{
for( auto * s : subscribers )
s->deliver_message( cmd.m_topic, cmd.m_payload );
}
else
m_logger->warn( "message for unregistered topic, topic={}, "
"payloadlen={}",
cmd.m_topic, cmd.m_payload.size() );
}
void
a_transport_manager_t::on_publish_message(
const publish_message_t & cmd )
{
m_logger->debug( "message publish, topic={}, "
"payloadlen={}",
cmd.m_topic_name, cmd.m_payload.size() );
auto r = mosquitto_publish( m_mosq.get(), 0 /* mid */,
cmd.m_topic_name.c_str(),
static_cast< int >(cmd.m_payload.size()),
cmd.m_payload.data(),
qos_to_use,
false /* retain */ );
// If error just log it and ignore.
if( MOSQ_ERR_SUCCESS != r )
m_logger->warn( "message_publish failed, rc={}, topic={}, "
"payloadlen={}",
r, cmd.m_topic_name, cmd.m_payload.size() );
}
void
a_transport_manager_t::try_subscribe_topic(
const std::string & topic_name )
{
if( st_connected == so_current_state() )
do_subscription_actions( topic_name );
}
void
a_transport_manager_t::do_subscription_actions(
const std::string & topic_name )
{
int mid{};
m_logger->info( "topic subscription, topic={}", topic_name );
auto r = mosquitto_subscribe( m_mosq.get(),
&mid, topic_name.c_str(), qos_to_use );
ensure_with_explblock< ex_t >(
MOSQ_ERR_SUCCESS == r ||
MOSQ_ERR_NO_CONN == r ||
MOSQ_ERR_CONN_LOST == r,
[&]{ return fmt::format( "mosquitto_subscribe({}, {}) "
"failed, rc={}", topic_name, qos_to_use, r ); } );
m_pending_subscriptions[ mid ] = pending_subscription_t{
topic_name,
std::chrono::steady_clock::now() };
}
void
a_transport_manager_t::process_subscription_result(
const std::string & topic_name,
subscription_info_t & info,
int granted_qos )
{
if( qos_to_use == granted_qos )
info.subscription_created( topic_name );
else
{
m_logger->error( "unexpected qos, topic_filter={}, granted_qos={}",
topic_name, granted_qos );
info.subscription_failed(
topic_name,
fmt::format( "unexpected qos: {}", granted_qos ) );
}
}
void
a_transport_manager_t::drop_subscription_statuses()
{
for( auto & info : m_registered_subscriptions )
info.second.subscription_lost( info.first );
}
void
a_transport_manager_t::restore_subscriptions_on_reconnect()
{
for( auto & info : m_registered_subscriptions )
do_subscription_actions( info.first );
}
} /* namespace mosquitto_transport */
| 25.771757 | 75 | 0.700414 | Stiffstream |
e03872fde4523879b1bcc864c20c9eb567fca8cf | 855 | cpp | C++ | StoryTime/Source/StoryTime/Private/Components/Narrative/Stories/DataAssets/StoryDA.cpp | vamidi/-StoryTime-plugin-UE5 | 9658f77160a9890897211ec76bd51d885d3c502c | [
"Apache-2.0"
] | 1 | 2022-03-23T04:35:51.000Z | 2022-03-23T04:35:51.000Z | StoryTime/Source/StoryTime/Private/Components/Narrative/Stories/DataAssets/StoryDA.cpp | vamidi/-StoryTime-plugin-UE5 | 9658f77160a9890897211ec76bd51d885d3c502c | [
"Apache-2.0"
] | null | null | null | StoryTime/Source/StoryTime/Private/Components/Narrative/Stories/DataAssets/StoryDA.cpp | vamidi/-StoryTime-plugin-UE5 | 9658f77160a9890897211ec76bd51d885d3c502c | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Components/Narrative/Stories/DataAssets/StoryDA.h"
#include "Database/TableDatabase.h"
void UStoryDA::ConvertRow()
{
Super::ConvertRow();
const auto row = GetRow(GetTableName(), ID);
if (row.Fields.Num() == 0) {
return;
}
for (auto& Field : row.Fields)
{
if (Field.Key == "typeId")
{
int32 d;
memcpy(&d, Field.Value.Data.Get(), Field.Value.Size);
TypeId = static_cast<EStoryType>(d);
}
}
}
void UStoryDA::Initialize()
{
if(ID != UINT_MAX && ChildId != UINT_MAX) {
// DialogueLines.Clear();
const auto entryId = FString::FromInt(ID + 1);
const auto* Field = TableDatabase::Get().GetField(GetTableName(), "data", ID);
if (Field)
{
// Parse story data
// StoryTable.ParseNodeData(this, (JObject) Field.Data);
}
}
}
| 19.431818 | 80 | 0.65731 | vamidi |
e038913d9505eb6d97ba25ebe656a921cde0c046 | 3,755 | cpp | C++ | src/GlfwApp.cpp | akoylasar/PBR | 17e6197fb5357220e2f1454898a18f8890844d4d | [
"MIT"
] | null | null | null | src/GlfwApp.cpp | akoylasar/PBR | 17e6197fb5357220e2f1454898a18f8890844d4d | [
"MIT"
] | null | null | null | src/GlfwApp.cpp | akoylasar/PBR | 17e6197fb5357220e2f1454898a18f8890844d4d | [
"MIT"
] | null | null | null | /*
* Copyright (c) Fouad Valadbeigi (akoylasar@gmail.com) */
#include "GlfwApp.hpp"
#include <GL/gl3w.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <exception>
namespace
{
constexpr double kToMs = 1000.0;
}
namespace Akoylasar
{
GlfwApp::GlfwApp(const std::string& title, int width, int height, int major, int minor)
: mWindow(nullptr),
mDrawRequested(true)
{
glfwSetErrorCallback(glfwErrorCallback);
if (!glfwInit())
throw std::runtime_error("GlfwApp: Failed to initialise glfw.\n");
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
mWindow = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);
if (!mWindow)
{
glfwTerminate();
std::string msg = "GlfwApp: Failed to create an OpenGL";
msg += std::to_string(major) + "." + std::to_string(minor) + " window.\n";
throw std::runtime_error(msg.c_str());
}
glfwSetWindowUserPointer(mWindow, this);
setupCallbacks();
glfwMakeContextCurrent(mWindow);
if (gl3wInit())
{
glfwDestroyWindow(mWindow);
glfwTerminate();
throw std::runtime_error("GlfwApp: Failed to initialize gl3w.\n");
}
}
GlfwApp::~GlfwApp()
{
glfwDestroyWindow(mWindow);
glfwTerminate();
}
void GlfwApp::glfwErrorCallback(int error, const char* description)
{
std::cerr << "Error code: " << error << ". Error description: " << description << "\n";
}
void GlfwApp::setSwapInterval(int swapInterval)
{
glfwSwapInterval(swapInterval);
}
void GlfwApp::setStickyKeys(bool state)
{
glfwSetInputMode(mWindow, GLFW_LOCK_KEY_MODS, state);
}
void GlfwApp::swapBuffers()
{
glfwSwapBuffers(mWindow);
}
void GlfwApp::requestRedraw()
{
mDrawRequested = true;
}
void GlfwApp::run()
{
setup();
double lastTime = glfwGetTime();
while (!glfwWindowShouldClose(mWindow))
{
double currentTime = glfwGetTime();
const double deltaTime = currentTime - lastTime;
if (mDrawRequested)
{
mDrawRequested = false;
draw(deltaTime);
}
glfwPollEvents();
lastTime = currentTime;
}
shutDown();
}
void GlfwApp::maximize()
{
glfwMaximizeWindow(mWindow);
}
double getTimeMs()
{
return glfwGetTime() * kToMs;
}
void GlfwApp::setupCallbacks()
{
glfwSetFramebufferSizeCallback(mWindow, [](GLFWwindow* window, int width, int height)
{
GlfwApp* app = static_cast<GlfwApp*>(glfwGetWindowUserPointer(window));
app->onFramebufferSize(width, height);
});
glfwSetCursorPosCallback(mWindow, [](GLFWwindow* window, double xPos, double yPos)
{
GlfwApp* app = static_cast<GlfwApp*>(glfwGetWindowUserPointer(window));
app->onCursorPos(xPos, yPos);
});
glfwSetMouseButtonCallback(mWindow, [](GLFWwindow* window, int button, int action, int mods)
{
GlfwApp* app = static_cast<GlfwApp*>(glfwGetWindowUserPointer(window));
app->onMouseButton(button, action, mods);
});
glfwSetScrollCallback(mWindow, [](GLFWwindow* window, double xOffset, double yOffset)
{
GlfwApp* app = static_cast<GlfwApp*>(glfwGetWindowUserPointer(window));
app->onScroll(xOffset, yOffset);
});
glfwSetKeyCallback(mWindow, [](GLFWwindow* window, int key, int scanCode, int action, int mods)
{
GlfwApp* app = static_cast<GlfwApp*>(glfwGetWindowUserPointer(window));
app->onKey(key, scanCode, action, mods);
});
}
}
| 24.383117 | 99 | 0.663116 | akoylasar |
e03a6c57dae6545a2840a96a3ce9a02d65b61c80 | 828 | cpp | C++ | tests/gain_tests.cpp | IRT-Open-Source/libadm | 442f51229e760db1caca4b962bfaad58a9c7d9b8 | [
"Apache-2.0"
] | 14 | 2018-07-24T12:18:05.000Z | 2020-05-11T19:14:49.000Z | tests/gain_tests.cpp | IRT-Open-Source/libadm | 442f51229e760db1caca4b962bfaad58a9c7d9b8 | [
"Apache-2.0"
] | 19 | 2018-07-30T15:02:54.000Z | 2020-05-21T10:13:19.000Z | tests/gain_tests.cpp | IRT-Open-Source/libadm | 442f51229e760db1caca4b962bfaad58a9c7d9b8 | [
"Apache-2.0"
] | 7 | 2018-07-24T12:18:12.000Z | 2020-02-14T11:18:12.000Z | #include <catch2/catch.hpp>
#include <limits>
#include <adm/elements/gain.hpp>
using namespace adm;
TEST_CASE("Gain linear") {
Gain g = Gain::fromLinear(10.0);
CHECK(g.isLinear());
CHECK(!g.isDb());
CHECK(g.asLinear() == 10.0);
CHECK(g.asDb() == Approx(20.0));
}
TEST_CASE("Gain linear 0") {
Gain g = Gain::fromLinear(0.0);
CHECK(g.asDb() == -std::numeric_limits<double>::infinity());
}
TEST_CASE("Gain Db") {
Gain g = Gain::fromDb(20.0);
CHECK(g.isDb());
CHECK(!g.isLinear());
CHECK(g.asDb() == 20.0);
CHECK(g.asLinear() == Approx(10.0));
}
TEST_CASE("Gain Db -inf") {
Gain g = Gain::fromDb(-std::numeric_limits<double>::infinity());
CHECK(g.asLinear() == 0.0);
}
TEST_CASE("Gain NamedType compatibility") {
Gain g(1.5);
CHECK(g.isLinear());
CHECK(g.get() == 1.5);
CHECK(*g == 1.5);
}
| 21.230769 | 66 | 0.612319 | IRT-Open-Source |
e03fd075ceb330a18641c0a1defa77292a6f7ec3 | 38,308 | cpp | C++ | test/test_surface.cpp | zhangxaochen/CuFusion | e8bab7a366b1f2c85a80b95093d195d9f0774c11 | [
"MIT"
] | 52 | 2017-09-05T13:31:44.000Z | 2022-03-14T08:48:29.000Z | test/test_surface.cpp | GucciPrada/CuFusion | 522920bcf316d1ddf9732fc71fa457174168d2fb | [
"MIT"
] | 4 | 2018-05-17T22:45:35.000Z | 2020-02-01T21:46:42.000Z | test/test_surface.cpp | GucciPrada/CuFusion | 522920bcf316d1ddf9732fc71fa457174168d2fb | [
"MIT"
] | 21 | 2015-07-27T13:00:36.000Z | 2022-01-17T08:18:41.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, 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 the copyright holder(s) 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.
*
* $Id: test_surface.cpp 6579 2012-07-27 18:57:32Z rusu $
*
*/
#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_io.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/mls.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/grid_projection.h>
#include <pcl/surface/convex_hull.h>
#include <pcl/surface/concave_hull.h>
#include <pcl/surface/organized_fast_mesh.h>
#include <pcl/surface/ear_clipping.h>
#include <pcl/surface/poisson.h>
#include <pcl/surface/marching_cubes_hoppe.h>
#include <pcl/surface/marching_cubes_rbf.h>
#include <pcl/common/common.h>
#include "boost.h"
#include <pcl/io/obj_io.h>
#include <pcl/TextureMesh.h>
#include <pcl/surface/texture_mapping.h>
using namespace pcl;
using namespace pcl::io;
using namespace std;
PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ>);
PointCloud<PointNormal>::Ptr cloud_with_normals (new PointCloud<PointNormal>);
search::KdTree<PointXYZ>::Ptr tree;
search::KdTree<PointNormal>::Ptr tree2;
// add by ktran to test update functions
PointCloud<PointXYZ>::Ptr cloud1 (new PointCloud<PointXYZ>);
PointCloud<PointNormal>::Ptr cloud_with_normals1 (new PointCloud<PointNormal>);
search::KdTree<PointXYZ>::Ptr tree3;
search::KdTree<PointNormal>::Ptr tree4;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, MarchingCubesTest)
{
MarchingCubesHoppe<PointNormal> hoppe;
hoppe.setIsoLevel (0);
hoppe.setGridResolution (30, 30, 30);
hoppe.setPercentageExtendGrid (0.3f);
hoppe.setInputCloud (cloud_with_normals);
PointCloud<PointNormal> points;
std::vector<Vertices> vertices;
hoppe.reconstruct (points, vertices);
EXPECT_NEAR (points.points[points.size()/2].x, -0.042528, 1e-3);
EXPECT_NEAR (points.points[points.size()/2].y, 0.080196, 1e-3);
EXPECT_NEAR (points.points[points.size()/2].z, 0.043159, 1e-3);
EXPECT_EQ (vertices[vertices.size ()/2].vertices[0], 10854);
EXPECT_EQ (vertices[vertices.size ()/2].vertices[1], 10855);
EXPECT_EQ (vertices[vertices.size ()/2].vertices[2], 10856);
MarchingCubesRBF<PointNormal> rbf;
rbf.setIsoLevel (0);
rbf.setGridResolution (20, 20, 20);
rbf.setPercentageExtendGrid (0.1f);
rbf.setInputCloud (cloud_with_normals);
rbf.setOffSurfaceDisplacement (0.02f);
rbf.reconstruct (points, vertices);
EXPECT_NEAR (points.points[points.size()/2].x, -0.033919, 1e-3);
EXPECT_NEAR (points.points[points.size()/2].y, 0.151683, 1e-3);
EXPECT_NEAR (points.points[points.size()/2].z, -0.000086, 1e-3);
EXPECT_EQ (vertices[vertices.size ()/2].vertices[0], 4284);
EXPECT_EQ (vertices[vertices.size ()/2].vertices[1], 4285);
EXPECT_EQ (vertices[vertices.size ()/2].vertices[2], 4286);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, MovingLeastSquares)
{
// Init objects
PointCloud<PointXYZ> mls_points;
PointCloud<PointNormal>::Ptr mls_normals (new PointCloud<PointNormal> ());
MovingLeastSquares<PointXYZ, PointNormal> mls;
// Set parameters
mls.setInputCloud (cloud);
mls.setComputeNormals (true);
mls.setPolynomialFit (true);
mls.setSearchMethod (tree);
mls.setSearchRadius (0.03);
// Reconstruct
mls.process (*mls_normals);
EXPECT_NEAR (mls_normals->points[0].x, 0.005417, 1e-3);
EXPECT_NEAR (mls_normals->points[0].y, 0.113463, 1e-3);
EXPECT_NEAR (mls_normals->points[0].z, 0.040715, 1e-3);
EXPECT_NEAR (fabs (mls_normals->points[0].normal[0]), 0.111894, 1e-3);
EXPECT_NEAR (fabs (mls_normals->points[0].normal[1]), 0.594906, 1e-3);
EXPECT_NEAR (fabs (mls_normals->points[0].normal[2]), 0.795969, 1e-3);
EXPECT_NEAR (mls_normals->points[0].curvature, 0.012019, 1e-3);
// Testing OpenMP version
MovingLeastSquares<PointXYZ, PointNormal> mls_omp;
mls_omp.setInputCloud (cloud);
mls_omp.setComputeNormals (true);
mls_omp.setPolynomialFit (true);
mls_omp.setSearchMethod (tree);
mls_omp.setSearchRadius (0.03);
//mls_omp.setNumberOfThreads (4);
// Reconstruct
mls_normals->clear ();
mls_omp.process (*mls_normals);
int count = 0;
for (size_t i = 0; i < mls_normals->size (); ++i)
{
if (fabs (mls_normals->points[i].x - 0.005417) < 1e-3 &&
fabs (mls_normals->points[i].y - 0.113463) < 1e-3 &&
fabs (mls_normals->points[i].z - 0.040715) < 1e-3 &&
fabs (fabs (mls_normals->points[i].normal[0]) - 0.111894) < 1e-3 &&
fabs (fabs (mls_normals->points[i].normal[1]) - 0.594906) < 1e-3 &&
fabs (fabs (mls_normals->points[i].normal[2]) - 0.795969) < 1e-3 &&
fabs (mls_normals->points[i].curvature - 0.012019) < 1e-3)
count ++;
}
EXPECT_EQ (count, 1);
// Testing upsampling
MovingLeastSquares<PointXYZ, PointNormal> mls_upsampling;
// Set parameters
mls_upsampling.setInputCloud (cloud);
mls_upsampling.setComputeNormals (true);
mls_upsampling.setPolynomialFit (true);
mls_upsampling.setSearchMethod (tree);
mls_upsampling.setSearchRadius (0.03);
mls_upsampling.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::SAMPLE_LOCAL_PLANE);
mls_upsampling.setUpsamplingRadius (0.025);
mls_upsampling.setUpsamplingStepSize (0.01);
mls_normals->clear ();
mls_upsampling.process (*mls_normals);
EXPECT_NEAR (mls_normals->points[10].x, -0.000538, 1e-3);
EXPECT_NEAR (mls_normals->points[10].y, 0.110080, 1e-3);
EXPECT_NEAR (mls_normals->points[10].z, 0.043602, 1e-3);
EXPECT_NEAR (fabs (mls_normals->points[10].normal[0]), 0.022678, 1e-3);
EXPECT_NEAR (fabs (mls_normals->points[10].normal[1]), 0.554978, 1e-3);
EXPECT_NEAR (fabs (mls_normals->points[10].normal[2]), 0.831556, 1e-3);
EXPECT_NEAR (mls_normals->points[10].curvature, 0.012019, 1e-3);
EXPECT_EQ (mls_normals->size (), 6352);
/// TODO Would need to set a seed point here for the random number generator
/// But as long as the other 2 upsampling methods work fine, this should have no issues.
/// The RANDOM_UNIFORM_DENSITY upsampling will be changed soon anyway, hopefully in PCL 1.6.1
// mls_upsampling.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::RANDOM_UNIFORM_DENSITY);
// mls_upsampling.setPointDensity (100);
// mls_normals->clear ();
// mls_upsampling.process (*mls_normals);
//
// EXPECT_NEAR (mls_normals->points[10].x, 0.018806, 1e-3);
// EXPECT_NEAR (mls_normals->points[10].y, 0.114685, 1e-3);
// EXPECT_NEAR (mls_normals->points[10].z, 0.037500, 1e-3);
// EXPECT_NEAR (fabs (mls_normals->points[10].normal[0]), 0.351352, 1e-3);
// EXPECT_NEAR (fabs (mls_normals->points[10].normal[1]), 0.537741, 1e-3);
// EXPECT_NEAR (fabs (mls_normals->points[10].normal[2]), 0.766411, 1e-3);
// EXPECT_NEAR (mls_normals->points[10].curvature, 0.019003, 1e-3);
// EXPECT_EQ (mls_normals->size (), 457);
mls_upsampling.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::VOXEL_GRID_DILATION);
mls_upsampling.setDilationIterations (5);
mls_upsampling.setDilationVoxelSize (0.005f);
mls_normals->clear ();
mls_upsampling.process (*mls_normals);
EXPECT_NEAR (mls_normals->points[10].x, -0.075887121260166168, 2e-3);
EXPECT_NEAR (mls_normals->points[10].y, 0.030984390527009964, 2e-3);
EXPECT_NEAR (mls_normals->points[10].z, 0.020856190472841263, 2e-3);
EXPECT_NEAR (mls_normals->points[10].curvature, 0.107273, 1e-1);
EXPECT_NEAR (double (mls_normals->size ()), 26266, 2);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, GreedyProjectionTriangulation)
{
// Init objects
PolygonMesh triangles;
GreedyProjectionTriangulation<PointNormal> gp3;
// Set parameters
gp3.setInputCloud (cloud_with_normals);
gp3.setSearchMethod (tree2);
gp3.setSearchRadius (0.025);
gp3.setMu (2.5);
gp3.setMaximumNearestNeighbors (100);
gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp3.setMinimumAngle(M_PI/18); // 10 degrees
gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
gp3.setNormalConsistency(false);
// Reconstruct
gp3.reconstruct (triangles);
//saveVTKFile ("./test/bun0-gp3.vtk", triangles);
EXPECT_EQ (triangles.cloud.width, cloud_with_normals->width);
EXPECT_EQ (triangles.cloud.height, cloud_with_normals->height);
EXPECT_NEAR (int (triangles.polygons.size ()), 685, 5);
// Check triangles
EXPECT_EQ (int (triangles.polygons.at (0).vertices.size ()), 3);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.at (0)), 0);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.at (1)), 12);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.at (2)), 198);
EXPECT_EQ (int (triangles.polygons.at (684).vertices.size ()), 3);
EXPECT_EQ (int (triangles.polygons.at (684).vertices.at (0)), 393);
EXPECT_EQ (int (triangles.polygons.at (684).vertices.at (1)), 394);
EXPECT_EQ (int (triangles.polygons.at (684).vertices.at (2)), 395);
// Additional vertex information
std::vector<int> parts = gp3.getPartIDs();
std::vector<int> states = gp3.getPointStates();
int nr_points = cloud_with_normals->width * cloud_with_normals->height;
EXPECT_EQ (int (parts.size ()), nr_points);
EXPECT_EQ (int (states.size ()), nr_points);
EXPECT_EQ (parts[0], 0);
EXPECT_EQ (states[0], gp3.COMPLETED);
EXPECT_EQ (parts[393], 5);
EXPECT_EQ (states[393], gp3.BOUNDARY);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, GreedyProjectionTriangulation_Merge2Meshes)
{
// check if exist update cloud
if(cloud_with_normals1->width * cloud_with_normals1->height > 0){
// Init objects
PolygonMesh triangles;
PolygonMesh triangles1;
GreedyProjectionTriangulation<PointNormal> gp3;
GreedyProjectionTriangulation<PointNormal> gp31;
// Set parameters
gp3.setInputCloud (cloud_with_normals);
gp3.setSearchMethod (tree2);
gp3.setSearchRadius (0.025);
gp3.setMu (2.5);
gp3.setMaximumNearestNeighbors (100);
gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp3.setMinimumAngle(M_PI/18); // 10 degrees
gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
gp3.setNormalConsistency(false);
// for mesh 2
// Set parameters
gp31.setInputCloud (cloud_with_normals1);
gp31.setSearchMethod (tree4);
gp31.setSearchRadius (0.025);
gp31.setMu (2.5);
gp31.setMaximumNearestNeighbors (100);
gp31.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp31.setMinimumAngle(M_PI/18); // 10 degrees
gp31.setMaximumAngle(2*M_PI/3); // 120 degrees
gp31.setNormalConsistency(false);
// Reconstruct
//gp3.reconstruct (triangles);
//saveVTKFile ("bun01.vtk", triangles);
//gp31.reconstruct (triangles1);
//saveVTKFile ("bun02.vtk", triangles1);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, UpdateMesh_With_TextureMapping)
{
if(cloud_with_normals1->width * cloud_with_normals1->height > 0){
// Init objects
PolygonMesh triangles;
PolygonMesh triangles1;
GreedyProjectionTriangulation<PointNormal> gp3;
GreedyProjectionTriangulation<PointNormal> gp31;
// Set parameters
gp3.setInputCloud (cloud_with_normals);
gp3.setSearchMethod (tree2);
gp3.setSearchRadius (0.025);
gp3.setMu (2.5);
gp3.setMaximumNearestNeighbors (100);
gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp3.setMinimumAngle(M_PI/18); // 10 degrees
gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
gp3.setNormalConsistency(false);
gp3.reconstruct (triangles);
EXPECT_EQ (triangles.cloud.width, cloud_with_normals->width);
EXPECT_EQ (triangles.cloud.height, cloud_with_normals->height);
EXPECT_EQ (int (triangles.polygons.size ()), 685);
// update with texture mapping
// set 2 texture for 2 mesh
std::vector<std::string> tex_files;
tex_files.push_back("tex4.jpg");
// initialize texture mesh
TextureMesh tex_mesh;
tex_mesh.header = triangles.header;
tex_mesh.cloud = triangles.cloud;
// add the 1st mesh
tex_mesh.tex_polygons.push_back(triangles.polygons);
// update mesh and texture mesh
//gp3.updateMesh(cloud_with_normals1, triangles, tex_mesh);
// set texture for added cloud
//tex_files.push_back("tex8.jpg");
// save updated mesh
//saveVTKFile ("update_bunny.vtk", triangles);
//TextureMapping<PointXYZ> tm;
//// set mesh scale control
//tm.setF(0.01);
//// set vector field
//tm.setVectorField(1, 0, 0);
//TexMaterial tex_material;
//// default texture materials parameters
//tex_material.tex_Ka.r = 0.2f;
//tex_material.tex_Ka.g = 0.2f;
//tex_material.tex_Ka.b = 0.2f;
//tex_material.tex_Kd.r = 0.8f;
//tex_material.tex_Kd.g = 0.8f;
//tex_material.tex_Kd.b = 0.8f;
//tex_material.tex_Ks.r = 1.0f;
//tex_material.tex_Ks.g = 1.0f;
//tex_material.tex_Ks.b = 1.0f;
//tex_material.tex_d = 1.0f;
//tex_material.tex_Ns = 0.0f;
//tex_material.tex_illum = 2;
//// set texture material paramaters
//tm.setTextureMaterials(tex_material);
//// set texture files
//tm.setTextureFiles(tex_files);
//// mapping
//tm.mapTexture2Mesh(tex_mesh);
//saveOBJFile ("update_bunny.obj", tex_mesh);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Organized)
{
//construct dataset
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_organized (new pcl::PointCloud<pcl::PointXYZ> ());
cloud_organized->width = 5;
cloud_organized->height = 10;
cloud_organized->points.resize (cloud_organized->width * cloud_organized->height);
int npoints = 0;
for (size_t i = 0; i < cloud_organized->height; i++)
{
for (size_t j = 0; j < cloud_organized->width; j++)
{
cloud_organized->points[npoints].x = static_cast<float> (i);
cloud_organized->points[npoints].y = static_cast<float> (j);
cloud_organized->points[npoints].z = static_cast<float> (cloud_organized->points.size ()); // to avoid shadowing
npoints++;
}
}
int nan_idx = cloud_organized->width*cloud_organized->height - 2*cloud_organized->width + 1;
cloud_organized->points[nan_idx].x = numeric_limits<float>::quiet_NaN ();
cloud_organized->points[nan_idx].y = numeric_limits<float>::quiet_NaN ();
cloud_organized->points[nan_idx].z = numeric_limits<float>::quiet_NaN ();
// Init objects
PolygonMesh triangles;
OrganizedFastMesh<PointXYZ> ofm;
// Set parameters
ofm.setInputCloud (cloud_organized);
ofm.setMaxEdgeLength (1.5);
ofm.setTrianglePixelSize (1);
ofm.setTriangulationType (OrganizedFastMesh<PointXYZ>::TRIANGLE_ADAPTIVE_CUT);
// Reconstruct
ofm.reconstruct (triangles);
//saveVTKFile ("./test/organized.vtk", triangles);
// Check triangles
EXPECT_EQ (triangles.cloud.width, cloud_organized->width);
EXPECT_EQ (triangles.cloud.height, cloud_organized->height);
EXPECT_EQ (int (triangles.polygons.size ()), 2*(triangles.cloud.width-1)*(triangles.cloud.height-1) - 4);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.size ()), 3);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.at (0)), 0);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.at (1)), triangles.cloud.width+1);
EXPECT_EQ (int (triangles.polygons.at (0).vertices.at (2)), 1);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, GridProjection)
{
// Init objects
PolygonMesh grid;
GridProjection<PointNormal> gp;
// Set parameters
gp.setInputCloud (cloud_with_normals);
gp.setSearchMethod (tree2);
gp.setResolution (0.005);
gp.setPaddingSize (3);
// Reconstruct
gp.reconstruct (grid);
//saveVTKFile ("./test/bun0-grid.vtk", grid);
EXPECT_GE (grid.cloud.width, 5180);
EXPECT_GE (int (grid.polygons.size ()), 1295);
EXPECT_EQ (int (grid.polygons.at (0).vertices.size ()), 4);
EXPECT_EQ (int (grid.polygons.at (0).vertices.at (0)), 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, ConvexHull_bunny)
{
pcl::PointCloud<pcl::PointXYZ> hull;
std::vector<pcl::Vertices> polygons;
pcl::ConvexHull<pcl::PointXYZ> chull;
chull.setInputCloud (cloud);
chull.reconstruct (hull, polygons);
//PolygonMesh convex;
//toROSMsg (hull, convex.cloud);
//convex.polygons = polygons;
//saveVTKFile ("./test/bun0-convex.vtk", convex);
EXPECT_EQ (polygons.size (), 206);
//check distance between min and max in the hull
Eigen::Vector4f min_pt_hull, max_pt_hull;
pcl::getMinMax3D (hull, min_pt_hull, max_pt_hull);
Eigen::Vector4f min_pt, max_pt;
pcl::getMinMax3D (hull, min_pt, max_pt);
EXPECT_NEAR ((min_pt - max_pt).norm (), (min_pt_hull - max_pt_hull).norm (), 1e-5);
//
// Test the face-vertices-only output variant
//
// construct the hull mesh
std::vector<pcl::Vertices> polygons2;
chull.reconstruct (polygons2);
// compare the face vertices (polygons2) to the output from the original test --- they should be identical
ASSERT_EQ (polygons.size (), polygons2.size ());
for (size_t i = 0; i < polygons.size (); ++i)
{
const pcl::Vertices & face1 = polygons[i];
const pcl::Vertices & face2 = polygons2[i];
ASSERT_EQ (face1.vertices.size (), face2.vertices.size ());
for (size_t j = 0; j < face1.vertices.size (); ++j)
{
ASSERT_EQ (face1.vertices[j], face2.vertices[j]);
}
}
//
// Test the PolygonMesh output variant
//
// construct the hull mesh
PolygonMesh mesh;
chull.reconstruct (mesh);
// convert the internal PointCloud2 to a PointCloud
PointCloud<pcl::PointXYZ> hull2;
pcl::fromROSMsg (mesh.cloud, hull2);
// compare the PointCloud (hull2) to the output from the original test --- they should be identical
ASSERT_EQ (hull.points.size (), hull2.points.size ());
for (size_t i = 0; i < hull.points.size (); ++i)
{
const PointXYZ & p1 = hull.points[i];
const PointXYZ & p2 = hull2.points[i];
ASSERT_EQ (p1.x, p2.x);
ASSERT_EQ (p1.y, p2.y);
ASSERT_EQ (p1.z, p2.z);
}
// compare the face vertices (mesh.polygons) to the output from the original test --- they should be identical
ASSERT_EQ (polygons.size (), mesh.polygons.size ());
for (size_t i = 0; i < polygons.size (); ++i)
{
const pcl::Vertices & face1 = polygons[i];
const pcl::Vertices & face2 = mesh.polygons[i];
ASSERT_EQ (face1.vertices.size (), face2.vertices.size ());
for (size_t j = 0; j < face1.vertices.size (); ++j)
{
ASSERT_EQ (face1.vertices[j], face2.vertices[j]);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, ConvexHull_LTable)
{
//construct dataset
pcl::PointCloud<pcl::PointXYZ> cloud_out_ltable;
cloud_out_ltable.points.resize (100);
int npoints = 0;
for (size_t i = 0; i < 8; i++)
{
for (size_t j = 0; j <= 2; j++)
{
cloud_out_ltable.points[npoints].x = float (i) * 0.5f;
cloud_out_ltable.points[npoints].y = -float (j) * 0.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
}
}
for (size_t i = 0; i <= 2; i++)
{
for (size_t j = 3; j < 8; j++)
{
cloud_out_ltable.points[npoints].x = float (i) * 0.5f;
cloud_out_ltable.points[npoints].y = -float (j) * 0.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
}
}
// add the five points on the hull
cloud_out_ltable.points[npoints].x = -0.5f;
cloud_out_ltable.points[npoints].y = 0.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
cloud_out_ltable.points[npoints].x = 4.5f;
cloud_out_ltable.points[npoints].y = 0.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
cloud_out_ltable.points[npoints].x = 4.5f;
cloud_out_ltable.points[npoints].y = -1.0f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
cloud_out_ltable.points[npoints].x = 1.0f;
cloud_out_ltable.points[npoints].y = -4.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
cloud_out_ltable.points[npoints].x = -0.5f;
cloud_out_ltable.points[npoints].y = -4.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
cloud_out_ltable.points.resize (npoints);
pcl::PointCloud<pcl::PointXYZ> hull;
std::vector<pcl::Vertices> polygons;
pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudptr (new pcl::PointCloud<pcl::PointXYZ> (cloud_out_ltable));
pcl::ConvexHull<pcl::PointXYZ> chull;
chull.setInputCloud (cloudptr);
chull.reconstruct (hull, polygons);
EXPECT_EQ (polygons.size (), 1);
EXPECT_EQ (hull.points.size (), 5);
//
// Test the face-vertices-only output variant
//
// construct the hull mesh
std::vector<pcl::Vertices> polygons2;
chull.reconstruct (polygons2);
// compare the face vertices (polygons2) to the output from the original test --- they should be identical
ASSERT_EQ (polygons.size (), polygons2.size ());
for (size_t i = 0; i < polygons.size (); ++i)
{
const pcl::Vertices & face1 = polygons[i];
const pcl::Vertices & face2 = polygons2[i];
ASSERT_EQ (face1.vertices.size (), face2.vertices.size ());
for (size_t j = 0; j < face1.vertices.size (); ++j)
{
ASSERT_EQ (face1.vertices[j], face2.vertices[j]);
}
}
//
// Test the PolygonMesh output variant
//
// construct the hull mesh
PolygonMesh mesh;
chull.reconstruct (mesh);
// convert the internal PointCloud2 to a PointCloud
PointCloud<pcl::PointXYZ> hull2;
pcl::fromROSMsg (mesh.cloud, hull2);
// compare the PointCloud (hull2) to the output from the original test --- they should be identical
ASSERT_EQ (hull.points.size (), hull2.points.size ());
for (size_t i = 0; i < hull.points.size (); ++i)
{
const PointXYZ & p1 = hull.points[i];
const PointXYZ & p2 = hull2.points[i];
ASSERT_EQ (p1.x, p2.x);
ASSERT_EQ (p1.y, p2.y);
ASSERT_EQ (p1.z, p2.z);
}
// compare the face vertices (mesh.polygons) to the output from the original test --- they should be identical
ASSERT_EQ (polygons.size (), mesh.polygons.size ());
for (size_t i = 0; i < polygons.size (); ++i)
{
const pcl::Vertices & face1 = polygons[i];
const pcl::Vertices & face2 = mesh.polygons[i];
ASSERT_EQ (face1.vertices.size (), face2.vertices.size ());
for (size_t j = 0; j < face1.vertices.size (); ++j)
{
ASSERT_EQ (face1.vertices[j], face2.vertices[j]);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, ConvexHull_2dsquare)
{
//Generate data
pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud (new pcl::PointCloud<pcl::PointXYZ> ());
input_cloud->width = 1000000;
input_cloud->height = 1;
input_cloud->points.resize (input_cloud->width * input_cloud->height);
//rng
boost::mt19937 rng_alg;
boost::uniform_01<boost::mt19937> rng (rng_alg);
rng.base ().seed (12345u);
for (size_t i = 0; i < input_cloud->points.size (); i++)
{
input_cloud->points[i].x = (2.0f * float (rng ()))-1.0f;
input_cloud->points[i].y = (2.0f * float (rng ()))-1.0f;
input_cloud->points[i].z = 1.0f;
}
//Set up for creating a hull
pcl::PointCloud<pcl::PointXYZ> hull;
pcl::ConvexHull<pcl::PointXYZ> chull;
chull.setInputCloud (input_cloud);
//chull.setDim (2); //We'll skip this, so we can check auto-detection
chull.reconstruct (hull);
//Check that input was correctly detected as 2D input
ASSERT_EQ (2, chull.getDimension ());
//Verify that all points lie within the plane we generated
//This plane has normal equal to the z-axis (parallel to the xy plane, 1m up)
Eigen::Vector4f plane_normal (0.0, 0.0, -1.0, 1.0);
//Make sure they're actually near some edge
std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > facets;
facets.push_back (Eigen::Vector4f (-1.0, 0.0, 0.0, 1.0));
facets.push_back (Eigen::Vector4f (-1.0, 0.0, 0.0, -1.0));
facets.push_back (Eigen::Vector4f (0.0, -1.0, 0.0, 1.0));
facets.push_back (Eigen::Vector4f (0.0, -1.0, 0.0, -1.0));
//Make sure they're in the plane
for (size_t i = 0; i < hull.points.size (); i++)
{
float dist = fabs (hull.points[i].getVector4fMap ().dot (plane_normal));
EXPECT_NEAR (dist, 0.0, 1e-2);
float min_dist = std::numeric_limits<float>::infinity ();
for (size_t j = 0; j < facets.size (); j++)
{
float d2 = fabs (hull.points[i].getVector4fMap ().dot (facets[j]));
if (d2 < min_dist)
min_dist = d2;
}
EXPECT_NEAR (min_dist, 0.0, 1e-2);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, ConvexHull_3dcube)
{
//Generate data
pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud (new pcl::PointCloud<pcl::PointXYZ> ());
input_cloud->width = 10000000;
input_cloud->height = 1;
input_cloud->points.resize (input_cloud->width * input_cloud->height);
//rng
boost::mt19937 rng_alg;
boost::uniform_01<boost::mt19937> rng (rng_alg);
rng.base ().seed (12345u);
for (size_t i = 0; i < input_cloud->points.size (); i++)
{
input_cloud->points[i].x = (2.0f * float (rng ()))-1.0f;
input_cloud->points[i].y = (2.0f * float (rng ()))-1.0f;
input_cloud->points[i].z = (2.0f * float (rng ()))-1.0f;
}
//Set up for creating a hull
pcl::PointCloud<pcl::PointXYZ> hull;
pcl::ConvexHull<pcl::PointXYZ> chull;
chull.setInputCloud (input_cloud);
//chull.setDim (3); //We'll skip this, so we can check auto-detection
chull.reconstruct (hull);
//Check that input was correctly detected as 3D input
ASSERT_EQ (3, chull.getDimension ());
//Make sure they're actually near some edge
std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > facets;
facets.push_back (Eigen::Vector4f (-1.0f, 0.0f, 0.0f, 1.0f));
facets.push_back (Eigen::Vector4f (-1.0f, 0.0f, 0.0f, -1.0f));
facets.push_back (Eigen::Vector4f (0.0f, -1.0f, 0.0f, 1.0f));
facets.push_back (Eigen::Vector4f (0.0f, -1.0f, 0.0f, -1.0f));
facets.push_back (Eigen::Vector4f (0.0f, 0.0f, -1.0f, 1.0f));
facets.push_back (Eigen::Vector4f (0.0f, 0.0f, -1.0f, -1.0f));
//Make sure they're near a facet
for (size_t i = 0; i < hull.points.size (); i++)
{
float min_dist = std::numeric_limits<float>::infinity ();
for (size_t j = 0; j < facets.size (); j++)
{
float dist = fabs (hull.points[i].getVector4fMap ().dot (facets[j]));
if (dist < min_dist)
min_dist = dist;
}
EXPECT_NEAR (min_dist, 0.0, 1e-2);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, ConcaveHull_bunny)
{
//construct dataset
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2D (new pcl::PointCloud<pcl::PointXYZ> (*cloud));
for (size_t i = 0; i < cloud2D->points.size (); i++)
cloud2D->points[i].z = 0;
pcl::PointCloud<pcl::PointXYZ> alpha_shape;
pcl::PointCloud<pcl::PointXYZ>::Ptr voronoi_centers (new pcl::PointCloud<pcl::PointXYZ>);
std::vector<pcl::Vertices> polygons_alpha;
pcl::ConcaveHull<pcl::PointXYZ> concave_hull;
concave_hull.setInputCloud (cloud2D);
concave_hull.setAlpha (0.5);
concave_hull.setVoronoiCenters (voronoi_centers);
concave_hull.reconstruct (alpha_shape, polygons_alpha);
EXPECT_EQ (alpha_shape.points.size (), 21);
pcl::PointCloud<pcl::PointXYZ> alpha_shape1;
pcl::PointCloud<pcl::PointXYZ>::Ptr voronoi_centers1 (new pcl::PointCloud<pcl::PointXYZ>);
std::vector<pcl::Vertices> polygons_alpha1;
pcl::ConcaveHull<pcl::PointXYZ> concave_hull1;
concave_hull1.setInputCloud (cloud2D);
concave_hull1.setAlpha (1.5);
concave_hull1.setVoronoiCenters (voronoi_centers1);
concave_hull1.reconstruct (alpha_shape1, polygons_alpha1);
EXPECT_EQ (alpha_shape1.points.size (), 20);
pcl::PointCloud<pcl::PointXYZ> alpha_shape2;
pcl::PointCloud<pcl::PointXYZ>::Ptr voronoi_centers2 (new pcl::PointCloud<pcl::PointXYZ>);
std::vector<pcl::Vertices> polygons_alpha2;
pcl::ConcaveHull<pcl::PointXYZ> concave_hull2;
concave_hull2.setInputCloud (cloud2D);
concave_hull2.setAlpha (0.01);
concave_hull2.setVoronoiCenters (voronoi_centers2);
concave_hull2.reconstruct (alpha_shape2, polygons_alpha2);
EXPECT_EQ (alpha_shape2.points.size (), 81);
//PolygonMesh concave;
//toROSMsg (alpha_shape2, concave.cloud);
//concave.polygons = polygons_alpha2;
//saveVTKFile ("./test/bun0-concave2d.vtk", concave);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, ConcaveHull_LTable)
{
//construct dataset
pcl::PointCloud<pcl::PointXYZ> cloud_out_ltable;
cloud_out_ltable.points.resize (100);
int npoints = 0;
for (size_t i = 0; i < 8; i++)
{
for (size_t j = 0; j <= 2; j++)
{
cloud_out_ltable.points[npoints].x = float (i) * 0.5f;
cloud_out_ltable.points[npoints].y = -float (j) * 0.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
}
}
for (size_t i = 0; i <= 2; i++)
{
for(size_t j = 3; j < 8; j++)
{
cloud_out_ltable.points[npoints].x = float (i) * 0.5f;
cloud_out_ltable.points[npoints].y = -float (j) * 0.5f;
cloud_out_ltable.points[npoints].z = 0.f;
npoints++;
}
}
cloud_out_ltable.points.resize (npoints);
pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudptr (new pcl::PointCloud<pcl::PointXYZ> (cloud_out_ltable));
pcl::PointCloud<pcl::PointXYZ> alpha_shape;
pcl::PointCloud<pcl::PointXYZ>::Ptr voronoi_centers (new pcl::PointCloud<pcl::PointXYZ>);
std::vector<pcl::Vertices> polygons_alpha;
pcl::ConcaveHull<pcl::PointXYZ> concave_hull;
concave_hull.setInputCloud (cloudptr);
concave_hull.setAlpha (0.5);
concave_hull.setVoronoiCenters (voronoi_centers);
concave_hull.reconstruct (alpha_shape, polygons_alpha);
EXPECT_EQ (alpha_shape.points.size (), 27);
pcl::PointCloud<pcl::PointXYZ> alpha_shape1;
pcl::PointCloud<pcl::PointXYZ>::Ptr voronoi_centers1 (new pcl::PointCloud<pcl::PointXYZ>);
std::vector<pcl::Vertices> polygons_alpha1;
pcl::ConcaveHull<pcl::PointXYZ> concave_hull1;
concave_hull1.setInputCloud (cloudptr);
concave_hull1.setAlpha (1.5);
concave_hull1.setVoronoiCenters (voronoi_centers1);
concave_hull1.reconstruct (alpha_shape1, polygons_alpha1);
EXPECT_EQ (alpha_shape1.points.size (), 23);
pcl::PointCloud<pcl::PointXYZ> alpha_shape2;
pcl::PointCloud<pcl::PointXYZ>::Ptr voronoi_centers2 (new pcl::PointCloud<pcl::PointXYZ>);
std::vector<pcl::Vertices> polygons_alpha2;
pcl::ConcaveHull<pcl::PointXYZ> concave_hull2;
concave_hull2.setInputCloud (cloudptr);
concave_hull2.setAlpha (3);
concave_hull2.setVoronoiCenters (voronoi_centers2);
concave_hull2.reconstruct (alpha_shape2, polygons_alpha2);
EXPECT_EQ (alpha_shape2.points.size (), 19);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, EarClipping)
{
PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ>());
cloud->height = 1;
cloud->points.push_back (PointXYZ ( 0.f, 0.f, 0.5f));
cloud->points.push_back (PointXYZ ( 5.f, 0.f, 0.6f));
cloud->points.push_back (PointXYZ ( 9.f, 4.f, 0.5f));
cloud->points.push_back (PointXYZ ( 4.f, 7.f, 0.5f));
cloud->points.push_back (PointXYZ ( 2.f, 5.f, 0.5f));
cloud->points.push_back (PointXYZ (-1.f, 8.f, 0.5f));
cloud->width = static_cast<uint32_t> (cloud->points.size ());
Vertices vertices;
vertices.vertices.resize (cloud->points.size ());
for (int i = 0; i < static_cast<int> (vertices.vertices.size ()); ++i)
vertices.vertices[i] = i;
PolygonMesh::Ptr mesh (new PolygonMesh);
toROSMsg (*cloud, mesh->cloud);
mesh->polygons.push_back (vertices);
EarClipping clipper;
PolygonMesh::ConstPtr mesh_aux (mesh);
clipper.setInputMesh (mesh_aux);
PolygonMesh triangulated_mesh;
clipper.process (triangulated_mesh);
EXPECT_EQ (triangulated_mesh.polygons.size (), 4);
for (int i = 0; i < static_cast<int> (triangulated_mesh.polygons.size ()); ++i)
EXPECT_EQ (triangulated_mesh.polygons[i].vertices.size (), 3);
const int truth[][3] = { {5, 0, 1},
{2, 3, 4},
{4, 5, 1},
{1, 2, 4} };
for (int pi = 0; pi < static_cast<int> (triangulated_mesh.polygons.size ()); ++pi)
for (int vi = 0; vi < 3; ++vi)
{
EXPECT_EQ (triangulated_mesh.polygons[pi].vertices[vi], truth[pi][vi]);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Poisson)
{
Poisson<PointNormal> poisson;
poisson.setInputCloud (cloud_with_normals);
PolygonMesh mesh;
poisson.reconstruct (mesh);
// io::saveVTKFile ("bunny_poisson.vtk", mesh);
ASSERT_EQ (mesh.polygons.size (), 1051);
// All polygons should be triangles
for (size_t i = 0; i < mesh.polygons.size (); ++i)
EXPECT_EQ (mesh.polygons[i].vertices.size (), 3);
EXPECT_EQ (mesh.polygons[10].vertices[0], 121);
EXPECT_EQ (mesh.polygons[10].vertices[1], 120);
EXPECT_EQ (mesh.polygons[10].vertices[2], 23);
EXPECT_EQ (mesh.polygons[200].vertices[0], 130);
EXPECT_EQ (mesh.polygons[200].vertices[1], 119);
EXPECT_EQ (mesh.polygons[200].vertices[2], 131);
EXPECT_EQ (mesh.polygons[1000].vertices[0], 521);
EXPECT_EQ (mesh.polygons[1000].vertices[1], 516);
EXPECT_EQ (mesh.polygons[1000].vertices[2], 517);
}
/* ---[ */
int
main (int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "No test file given. Please download `bun0.pcd` and pass its path to the test." << std::endl;
return (-1);
}
// Load file
sensor_msgs::PointCloud2 cloud_blob;
loadPCDFile (argv[1], cloud_blob);
fromROSMsg (cloud_blob, *cloud);
// Create search tree
tree.reset (new search::KdTree<PointXYZ> (false));
tree->setInputCloud (cloud);
// Normal estimation
NormalEstimation<PointXYZ, Normal> n;
PointCloud<Normal>::Ptr normals (new PointCloud<Normal> ());
n.setInputCloud (cloud);
//n.setIndices (indices[B);
n.setSearchMethod (tree);
n.setKSearch (20);
n.compute (*normals);
// Concatenate XYZ and normal information
pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
// Create search tree
tree2.reset (new search::KdTree<PointNormal>);
tree2->setInputCloud (cloud_with_normals);
// Process for update cloud
if(argc == 3){
sensor_msgs::PointCloud2 cloud_blob1;
loadPCDFile (argv[2], cloud_blob1);
fromROSMsg (cloud_blob1, *cloud1);
// Create search tree
tree3.reset (new search::KdTree<PointXYZ> (false));
tree3->setInputCloud (cloud1);
// Normal estimation
NormalEstimation<PointXYZ, Normal> n1;
PointCloud<Normal>::Ptr normals1 (new PointCloud<Normal> ());
n1.setInputCloud (cloud1);
n1.setSearchMethod (tree3);
n1.setKSearch (20);
n1.compute (*normals1);
// Concatenate XYZ and normal information
pcl::concatenateFields (*cloud1, *normals1, *cloud_with_normals1);
// Create search tree
tree4.reset (new search::KdTree<PointNormal>);
tree4->setInputCloud (cloud_with_normals1);
}
// Testing
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
| 36.037629 | 119 | 0.638091 | zhangxaochen |
e049fbdab29a6b37f26d4717542ddb51805fb305 | 1,988 | hxx | C++ | opencascade/GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1993-06-22
// Created by: Martine LANGLOIS
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface_HeaderFile
#define _GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomToStep_Root.hxx>
class StepGeom_BSplineSurfaceWithKnotsAndRationalBSplineSurface;
class Geom_BSplineSurface;
//! This class implements the mapping between class
//! BSplineSurface from Geom and the class
//! BSplineSurfaceWithKnotsAndRationalBSplineSurface from
//! StepGeom which describes a
//! rational_bspline_Surface_with_knots from Prostep
class GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface : public GeomToStep_Root
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface(const Handle(Geom_BSplineSurface)& Bsplin);
Standard_EXPORT const Handle(StepGeom_BSplineSurfaceWithKnotsAndRationalBSplineSurface)& Value() const;
protected:
private:
Handle(StepGeom_BSplineSurfaceWithKnotsAndRationalBSplineSurface) theBSplineSurfaceWithKnotsAndRationalBSplineSurface;
};
#endif // _GeomToStep_MakeBSplineSurfaceWithKnotsAndRationalBSplineSurface_HeaderFile
| 28.4 | 125 | 0.828974 | mgreminger |
e0502f8d55c3e20c46d030dcca520b649c835073 | 1,769 | cpp | C++ | Client/source/NewCode.cpp | isonil/mmorpg | 679afebd7231a103146325a59e92bc1ebda9fc29 | [
"MIT"
] | 12 | 2016-05-31T06:28:26.000Z | 2021-02-10T03:46:13.000Z | Client/source/NewCode.cpp | isonil/MMORPG | 679afebd7231a103146325a59e92bc1ebda9fc29 | [
"MIT"
] | null | null | null | Client/source/NewCode.cpp | isonil/MMORPG | 679afebd7231a103146325a59e92bc1ebda9fc29 | [
"MIT"
] | 6 | 2016-05-22T17:22:34.000Z | 2021-01-11T23:33:35.000Z | #include "NewCode.hpp"
Faction::AddPlayerResult::Enum Faction::addPlayer(Character &player)
{
//if(player.hasFaction()) return AddPlayerResult::PlayerHasFaction;
//if(isFull()) return AddPlayerResult::FactionIsFull;
//member.push_back(player);
return AddPlayerResult::OK;
}
Faction::RemovePlayerResult::Enum Faction::removePlayer(Character &player)
{
//if(!isPlayerMember(player)) return RemovePlayerResult::PlayerIsNotMember;
//if(leader.ID == player.ID) return RemovePlayerResult::PlayerIsLeader;
return RemovePlayerResult::OK;
}
Faction::ChangePlayerRankResult::Enum Faction::changePlayerRank(Character &player, Faction::PlayerRank::Enum newRank)
{
/*if(!isPlayerMember(player)) return ChangePlayerRankResult::PlayerIsNotMember;
if(getPlayerRank(player) == ) return ChangePlayerRankResult::
if(!PlayerRank::isValid(newRank)) return ChangePlayerRankResult::InvalidRank;
if()*/
}
Faction::Faction(Character &newLeader)
: name("undefined"),
leader(newLeader)
{
member.push_back(Member(newLeader, PlayerRank::Leader));
}
void test()
{
CharacterClass a;
Faction faction(a);
container <Character> cont;
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
cont.push_back(Character());
for(size_t i=0; i<cont.size(); ++i) faction.addPlayer(cont[i]);
faction.KUPSKO();
//printf("%d %d\n", cont[5].param[0], cont[9].param[0]);
}
| 28.079365 | 117 | 0.702657 | isonil |
e0504a763501fa912c1eb7715c5e3bc1c4bf5426 | 1,142 | hpp | C++ | include/codegen/include/System/Collections/Generic/IEqualityComparer_1.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Collections/Generic/IEqualityComparer_1.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Collections/Generic/IEqualityComparer_1.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:53 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: System.Collections.Generic
namespace System::Collections::Generic {
// Autogenerated type: System.Collections.Generic.IEqualityComparer`1
template<typename T>
class IEqualityComparer_1 {
public:
// public System.Boolean Equals(T x, T y)
// Offset: 0xFFFFFFFF
bool Equals(T x, T y) {
return CRASH_UNLESS(il2cpp_utils::RunMethod<bool>(this, "Equals", x, y));
}
// public System.Int32 GetHashCode(T obj)
// Offset: 0xFFFFFFFF
int GetHashCode(T obj) {
return CRASH_UNLESS(il2cpp_utils::RunMethod<int>(this, "GetHashCode", obj));
}
}; // System.Collections.Generic.IEqualityComparer`1
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(System::Collections::Generic::IEqualityComparer_1, "System.Collections.Generic", "IEqualityComparer`1");
#pragma pack(pop)
| 36.83871 | 141 | 0.683012 | Futuremappermydud |
e05206df55d4e88d83113747660102bdbdd7e568 | 1,174 | cpp | C++ | 2_age-calculator/age.cpp | HelinaBerhane/cpp-exercises | 60767b65ef81d9a95e9174343d1faf2383423af7 | [
"MIT"
] | null | null | null | 2_age-calculator/age.cpp | HelinaBerhane/cpp-exercises | 60767b65ef81d9a95e9174343d1faf2383423af7 | [
"MIT"
] | null | null | null | 2_age-calculator/age.cpp | HelinaBerhane/cpp-exercises | 60767b65ef81d9a95e9174343d1faf2383423af7 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int year_now, month_now, age_now, birth_month, another_year, another_month, another_age, another_date;
cout << "Enter the current year then press RETURN.\n";
cin >> year_now;
cout << "Enter the current month then press RETURN.\n";
cin >> month_now;
cout << "Enter your current age in years.\n";
cin >> age_now;
cout << "Enter the month in which you were born (a number from 1 to 12).\n";
cin >> birth_month;
cout << "Enter the year for which you wish to know your age.\n";
cin >> another_year;
cout << "Enter the month for which you wish to know your age.\n";
cin >> another_month;
//WIP
another_date = (another_year * 12) + another_month
age_now = (age_now * 12)
another_age = + - (year_now - age_now);
if (another_age >= 150){
cout << "Sorry, but you'll probably be dead by " << another_year << ". ";
cout << "You'll be " << another_age << "\n";
}else if(another_age >= 0){
cout << "Your age in " << another_year << ": ";
cout << another_age << "\n";
}else{
cout << "You weren't even born in ";
cout << another_year << "!\n";
}
return 0;
}
| 26.088889 | 104 | 0.625213 | HelinaBerhane |
e05f7cbce31ae155637792187d921ce6e19d1c17 | 456 | cpp | C++ | algo/algo.cpp | CodeCrackerSND/BarsWF_v2 | 6f77a7bca11f9b6044abde7f16984ddf1a68e31d | [
"MIT"
] | 12 | 2020-02-10T12:55:41.000Z | 2021-07-08T14:28:51.000Z | algo/algo.cpp | CodeCrackerSND/BarsWF_v1 | 68cdf3acc89d659b4d1f80393e2782908118c5a9 | [
"MIT"
] | 1 | 2017-07-12T17:59:43.000Z | 2017-07-13T06:36:20.000Z | algo/algo.cpp | CodeCrackerSND/BarsWF_v2 | 6f77a7bca11f9b6044abde7f16984ddf1a68e31d | [
"MIT"
] | 7 | 2020-02-09T12:20:21.000Z | 2021-07-25T20:14:08.000Z | #include "algo.h"
#include "../perm.h"
#include <assert.h>
algo::algo()
{
}
algo::~algo()
{
}
void algo::prepare_keys(int *data, int num)
{
//default is asci key preparation
prepare_keys_asci(data, num);
}
void algo::prepare_keys_asci(int *data, int num)
{
perm::lock();//enter critical section
perm::gen((unsigned int*)data, num);
perm::unlock();//done
}
void algo::prepare_keys_unicode(int *data, int num)
{
assert(false);//not implemented
} | 14.709677 | 51 | 0.677632 | CodeCrackerSND |
e0660dc34544e44824bf25d302a680316b499af8 | 5,691 | cxx | C++ | Modules/Registration/DisparityMap/test/otbDisparityMapEstimationMethod.cxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Registration/DisparityMap/test/otbDisparityMapEstimationMethod.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Registration/DisparityMap/test/otbDisparityMapEstimationMethod.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbDisparityMapEstimationMethod.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "itkTranslationTransform.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"
#include "otbThresholdImageToPointSetFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
int otbDisparityMapEstimationMethod(int itkNotUsed(argc), char* argv[])
{
const char* fixedFileName = argv[1];
const char* movingFileName = argv[2];
const char* pointSetFileName = argv[3];
const char* outputFileName = argv[4];
const unsigned int exploSize = atoi(argv[5]);
const unsigned int winSize = atoi(argv[6]);
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::Image<PixelType, Dimension> ImageType;
typedef itk::TranslationTransform<double, Dimension> TransformType;
typedef TransformType::ParametersType ParametersType;
typedef itk::PointSet<ParametersType, Dimension> PointSetType;
typedef otb::DisparityMapEstimationMethod<ImageType, ImageType, PointSetType> DMEstimationType;
typedef itk::NormalizedCorrelationImageToImageMetric<ImageType, ImageType> MetricType;
typedef itk::LinearInterpolateImageFunction<ImageType, double> InterpolatorType;
typedef itk::GradientDescentOptimizer OptimizerType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ThresholdImageToPointSetFilter<ImageType, PointSetType> PointSetSourceType;
typedef PointSetType::PointsContainer::Iterator PointSetIteratorType;
typedef PointSetType::PointDataContainer::Iterator PointDataIteratorType;
// Input images reading
ReaderType::Pointer fixedReader = ReaderType::New();
ReaderType::Pointer movingReader = ReaderType::New();
ReaderType::Pointer pointSetReader = ReaderType::New();
fixedReader->SetFileName(fixedFileName);
movingReader->SetFileName(movingFileName);
pointSetReader->SetFileName(pointSetFileName);
fixedReader->Update();
movingReader->Update();
pointSetReader->Update();
// Ajout
typedef itk::MinimumMaximumImageCalculator<ImageType> MinMaxType;
MinMaxType::Pointer mm = MinMaxType::New();
mm->SetImage(pointSetReader->GetOutput());
mm->Compute();
std::cout << "min: " << (int)mm->GetMinimum() << " max: " << (int)mm->GetMaximum() << std::endl;
PointSetSourceType::Pointer pointSetSource = PointSetSourceType::New();
pointSetSource->SetLowerThreshold(mm->GetMaximum());
pointSetSource->SetUpperThreshold(mm->GetMaximum());
pointSetSource->SetInput(0, pointSetReader->GetOutput());
pointSetSource->Update();
std::cout << "PointSet size: " << pointSetSource->GetOutput()->GetPoints()->Size() << std::endl;
// Instantiation
DMEstimationType::Pointer dmestimator = DMEstimationType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
MetricType::Pointer metric = MetricType::New();
// Set up
dmestimator->SetTransform(transform);
dmestimator->SetOptimizer(optimizer);
dmestimator->SetInterpolator(interpolator);
dmestimator->SetMetric(metric);
// For gradient descent
optimizer->SetLearningRate(5.0);
optimizer->SetNumberOfIterations(100);
DMEstimationType::ParametersType initialParameters(transform->GetNumberOfParameters());
initialParameters[0] = 0.0; // Initial offset in mm along X
initialParameters[1] = 0.0; // Initial offset in mm along Y
// Initial parameter set up
// dmestimator->SetInitialTransformParameters(initialParameters);
// inputs wiring
ImageType::SizeType win, explo;
win.Fill(winSize);
explo.Fill(exploSize);
dmestimator->SetFixedImage(fixedReader->GetOutput());
dmestimator->SetMovingImage(movingReader->GetOutput());
dmestimator->SetPointSet(pointSetSource->GetOutput());
dmestimator->SetWinSize(win);
dmestimator->SetExploSize(explo);
dmestimator->SetInitialTransformParameters(initialParameters);
// Estimation trigger
dmestimator->Update();
// Point set retrieving
PointSetType::Pointer pointSet = dmestimator->GetOutput();
// Writing output transform parameters
std::ofstream out;
out.open(outputFileName, std::ios::out);
out.setf(std::ios::fixed);
// out.setprecision(10);
PointSetIteratorType it = pointSet->GetPoints()->Begin();
// unsigned int idData=0;
PointDataIteratorType itData = pointSet->GetPointData()->Begin();
std::cout << "Point data size: " << pointSet->GetPointData()->Size() << std::endl;
for (; it != pointSet->GetPoints()->End() && itData != pointSet->GetPointData()->End(); ++it, ++itData)
{
out << "Point " << it.Value() << " -> transform parameters: ";
out << itData.Value();
out << std::endl;
}
out.close();
return EXIT_SUCCESS;
}
| 39.797203 | 105 | 0.730979 | heralex |
e06c090c557f7bd421c7843597d36ebf41c225c3 | 1,915 | hpp | C++ | include/private/coherence/component/net/extend/protocol/NotifyShutdown.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | include/private/coherence/component/net/extend/protocol/NotifyShutdown.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | include/private/coherence/component/net/extend/protocol/NotifyShutdown.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_NOTIFY_SHUTDOWN_HPP
#define COH_NOTIFY_SHUTDOWN_HPP
#include "private/coherence/component/net/extend/AbstractPofMessage.hpp"
COH_OPEN_NAMESPACE5(coherence,component,net,extend,protocol)
using coherence::component::net::extend::AbstractPofMessage;
/**
* This internal Message is sent to a ConnectionManager it is supposed to shut
* down. The ConnectionManager must clean up and unregister itself. Note that
* the only task of the shut-down is to begin the process of shutting down the
* service; technically the ConnectionManager does not have to be stopped by
* the time the shutdown Message completes its processing, although the default
* implementation does stop it immediately.
*
* @author nsa 2008.03.19
*/
class COH_EXPORT NotifyShutdown
: public class_spec<NotifyShutdown,
extends<AbstractPofMessage> >
{
friend class factory<NotifyShutdown>;
// ----- constructors ---------------------------------------------------
protected:
/**
* Create a new NamedCacheProtocol instance.
*/
NotifyShutdown();
private:
/**
* Blocked copy constructor.
*/
NotifyShutdown(const NotifyShutdown&);
// ----- Message interface ----------------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual int32_t getTypeId() const;
/**
* {@inheritDoc}
*/
virtual void run();
// ----- constants ------------------------------------------------------
public:
/**
* The type identifier of this Message class.
*/
static const int32_t type_id = -5;
};
COH_CLOSE_NAMESPACE5
#endif // COH_NOTIFY_SHUTDOWN_HPP
| 25.878378 | 78 | 0.609922 | chpatel3 |
e0737229f647fe778938bba3994ceb6734254364 | 3,948 | hpp | C++ | src/libshit/utils.hpp | u3shit/libshit | 8ab8f12b4068edc269356debef78cd04de67edb4 | [
"WTFPL",
"BSD-3-Clause"
] | null | null | null | src/libshit/utils.hpp | u3shit/libshit | 8ab8f12b4068edc269356debef78cd04de67edb4 | [
"WTFPL",
"BSD-3-Clause"
] | null | null | null | src/libshit/utils.hpp | u3shit/libshit | 8ab8f12b4068edc269356debef78cd04de67edb4 | [
"WTFPL",
"BSD-3-Clause"
] | null | null | null | #ifndef GUARD_ILL_NATUREDLY_UNSCUFFED_MANY_WORLDS_INTERPRETATION_GRECIANIZES_1359
#define GUARD_ILL_NATUREDLY_UNSCUFFED_MANY_WORLDS_INTERPRETATION_GRECIANIZES_1359
#pragma once
#include "libshit/assert.hpp"
#include <algorithm>
#include <type_traits>
namespace Libshit
{
template <typename T, typename U>
T asserted_cast(U* ptr)
{
LIBSHIT_ASSERT_MSG(
dynamic_cast<T>(ptr) == static_cast<T>(ptr), "U is not T");
return static_cast<T>(ptr);
}
template <typename T, typename U>
T asserted_cast(U& ref)
{
using raw_t = std::remove_reference_t<T>;
LIBSHIT_ASSERT_MSG(
dynamic_cast<raw_t*>(&ref) == static_cast<raw_t*>(&ref), "U is not T");
return static_cast<T>(ref);
}
template <typename T>
struct AddConst { using Type = const T; };
template <typename T>
struct AddConst<T*> { using Type = typename AddConst<T>::Type* const; };
template <typename T>
inline T implicit_const_cast(typename AddConst<T>::Type x)
{ return const_cast<T>(x); }
template <typename T>
class Key
{
friend T;
Key() noexcept {}
};
template <typename... Args> struct Overloaded : Args...
{ using Args::operator()...; };
template <typename... Args> Overloaded(Args...) -> Overloaded<Args...>;
/**
* `std::move` alternative that errors on const refs (instead of silently
* producing `const T&&`, which will not move).
*/
template <typename T>
constexpr std::remove_const_t<std::remove_reference_t<T>>&&
Move(T&& t) noexcept
{ return static_cast<std::remove_const_t<std::remove_reference_t<T>>&&>(t); }
template <typename T>
constexpr T&& Move(const T&) noexcept = delete;
/**
* Execute a function when the variable is destroyed.
* Designed as a simpler, macro less, C++17 alternate to
* [http://www.boost.org/doc/libs/1_57_0/libs/scope_exit/doc/html/index.html](Boost.ScopeExit),
* this allows you to execute arbitrary code when a variable goes out of
* scope. It can be used when writing a RAII class to manage some resource
* would be overkill.
* @par Usage
* @code{.cpp}
* {
* auto something = InitSomething()
* AtScopeExit x([&]() { DeinitSomething(something); });
*
* DoSomething(something);
* // ...
* } // DeinitSomething (or earlier in case of an exception)
* @endcode
* @warning The function you give should be `noexcept`, because it'll executed
* in a destructor, and destructors [shouldn't throw during stack
* unwinding](https://isocpp.org/wiki/faq/exceptions#dtors-shouldnt-throw).
*/
template <typename T>
class AtScopeExit
{
const T func;
public:
explicit AtScopeExit(const T& func)
noexcept(std::is_nothrow_copy_constructible_v<T>) : func(func) {}
AtScopeExit(const AtScopeExit&) = delete;
void operator=(const AtScopeExit&) = delete;
~AtScopeExit() noexcept(noexcept(func())) { func(); }
};
/// Conditional AtScopeExit, can be disabled.
template <typename T>
class AtScopeExitC
{
T func;
bool enabled;
public:
explicit AtScopeExitC(const T& func, bool enabled = true)
noexcept(std::is_nothrow_copy_constructible_v<T>)
: func(func), enabled{enabled} {}
AtScopeExitC(AtScopeExitC&& o)
noexcept(std::is_nothrow_move_constructible_v<T>)
: func(Move(o.func)), enabled{o.enabled} { o.enabled = false; }
AtScopeExitC& operator=(AtScopeExitC o)
noexcept(std::is_nothrow_swappable_v<T>)
{
using std::swap;
swap(func, o.func);
enabled = o.enabled;
return *this;
}
void Enable() noexcept { enabled = true; }
void Disable() noexcept { enabled = false; }
bool IsEnabled() const noexcept { return enabled; }
/// Execute the function if it wasn't yet
void Fire() noexcept
{
if (enabled) func();
enabled = false;
}
~AtScopeExitC() noexcept(noexcept(func())) { if (enabled) func(); }
};
}
#endif
| 29.244444 | 97 | 0.663374 | u3shit |
e0747be65cdda8b67b6be3aa93972f65528d18cd | 2,158 | cpp | C++ | test/src/test_cons.cpp | mori0091/cparsec2 | e439cd07147286e4d9aa9e93f9b41192b977adfd | [
"MIT"
] | 1 | 2019-07-08T02:20:44.000Z | 2019-07-08T02:20:44.000Z | test/src/test_cons.cpp | mori0091/cparsec2 | e439cd07147286e4d9aa9e93f9b41192b977adfd | [
"MIT"
] | 101 | 2019-06-01T00:58:36.000Z | 2019-10-20T05:43:56.000Z | test/src/test_cons.cpp | mori0091/cparsec2 | e439cd07147286e4d9aa9e93f9b41192b977adfd | [
"MIT"
] | 1 | 2019-06-01T03:50:09.000Z | 2019-06-01T03:50:09.000Z | /* -*- coding: utf-8-unix -*- */
#include <catch.hpp>
#include <cparsec2.hpp>
SCENARIO("cons(letter, many(digit))", "[cparsec2][parser][cons]") {
cparsec2_init();
GIVEN("an input: \"a1234\"") {
Source src = Source_new("a1234");
WHEN("apply cons(letter, many(digit))") {
THEN("results \"a1234\"") {
REQUIRE(std::string("a1234") ==
parse(cons(letter, many(digit)), src));
}
}
}
GIVEN("an input: \"abc123\"") {
Source src = Source_new("abc123");
WHEN("apply cons(letter, many(digit))") {
THEN("results \"a\"") {
REQUIRE(std::string("a") ==
parse(cons(letter, many(digit)), src));
}
}
}
GIVEN("an input: \"a123bc\"") {
Source src = Source_new("a123bc");
WHEN("apply cons(letter, many(digit))") {
THEN("results \"a123\"") {
REQUIRE(std::string("a123") ==
parse(cons(letter, many(digit)), src));
}
}
}
GIVEN("an input: \"123\"") {
Source src = Source_new("123");
WHEN("apply cons(letter, many(digit))") {
THEN("cause exception(\"not satisfy\")") {
REQUIRE_THROWS_WITH(parse(cons(letter, many(digit)), src),
"not satisfy");
}
}
}
cparsec2_end();
}
SCENARIO("cons(p, ps)", "[cparsec2][parser][cons]") {
cparsec2_init();
GIVEN("an input: \"123 456 789\"") {
Source src = Source_new("123 456 789");
WHEN("apply cons(number, many(number))") {
List(Int) xs = parse(cons(number, many(number)), src);
THEN("results [123, 456, 789]") {
int* itr = list_begin(xs);
REQUIRE(123 == itr[0]);
REQUIRE(456 == itr[1]);
REQUIRE(789 == itr[2]);
}
}
WHEN("apply cons(x, many(x)) where x = token(many1(digit))") {
PARSER(String) x = token(many1(digit));
List(String) xs = parse(cons(x, many(x)), src);
THEN("results [\"123\", \"456\", \"789\"]") {
const char** itr = list_begin(xs);
REQUIRE(std::string("123") == itr[0]);
REQUIRE(std::string("456") == itr[1]);
REQUIRE(std::string("789") == itr[2]);
}
}
}
cparsec2_end();
}
| 29.561644 | 67 | 0.520389 | mori0091 |
e0771c06fc9147a4cab59ed26f5ba8bd2808cb5b | 67 | cpp | C++ | examples/breakpad/boo.cpp | sanblch/hunter | a21edf8a43f567d2ae60ea1acdaab7d4facf3db7 | [
"BSD-2-Clause"
] | 2,146 | 2015-01-10T07:26:58.000Z | 2022-03-21T02:28:01.000Z | examples/breakpad/boo.cpp | koinos/hunter | fc17bc391210bf139c55df7f947670c5dff59c57 | [
"BSD-2-Clause"
] | 1,778 | 2015-01-03T11:50:30.000Z | 2019-12-26T05:31:20.000Z | examples/breakpad/boo.cpp | koinos/hunter | fc17bc391210bf139c55df7f947670c5dff59c57 | [
"BSD-2-Clause"
] | 734 | 2015-03-05T19:52:34.000Z | 2022-02-22T23:18:54.000Z | #include <google_breakpad/common/breakpad_types.h>
int main() {
}
| 13.4 | 50 | 0.746269 | sanblch |
2fdb99c198eaf6d2ad95a9fb8c926aaa89970a5f | 6,947 | cpp | C++ | Omniscript/src/Interpreter.cpp | aaronh82/Omniscript | a072dad8a7a2e94032a144eb8e7115b9d4ccc29f | [
"MIT"
] | null | null | null | Omniscript/src/Interpreter.cpp | aaronh82/Omniscript | a072dad8a7a2e94032a144eb8e7115b9d4ccc29f | [
"MIT"
] | null | null | null | Omniscript/src/Interpreter.cpp | aaronh82/Omniscript | a072dad8a7a2e94032a144eb8e7115b9d4ccc29f | [
"MIT"
] | null | null | null | //
// Interpreter.cpp
// OmniScript
//
// Created by Aaron Houghton on 6/30/14.
// Copyright (c) 2014 CCBAC. All rights reserved.
//
#include "Interpreter.h"
#include <chrono>
#include <unistd.h>
namespace interp {
Interpreter::Interpreter(script::Script &prog): program_(prog),
pool(prog.startingBlocks().size()) {
initPrims();
}
void Interpreter::initPrims() {
// Triggers
primTable["whenOn"] = std::make_shared<whenOn>();
primTable["whenSchedule"] = std::make_shared<whenSchedule>();
primTable["whenNotSchedule"] = std::make_shared<whenNotSchedule>();
primTable["whenBool"] = std::make_shared<whenBool>();
primTable["whenIReceive"] = std::make_shared<whenIReceive>();
primTable["doBroadcast:"] = std::make_shared<doBroadcast>();
primTable["doBroadcastAndWait"] = std::make_shared<doBroadcastAndWait>();
primTable["getLastMessage"] = std::make_shared<getLastMessage>();
primTable["doStopThis"] = std::make_shared<doStopThis>();
primTable["doStopOthers"] = std::make_shared<doStopOthers>();
// Logic
primTable["doWait"] = std::make_shared<doWait>();
primTable["doWaitUntil"] = std::make_shared<doWaitUntil>();
primTable["doRepeat"] = std::make_shared<doRepeat>();
primTable["doForever"] = std::make_shared<doForever>();
primTable["doIf"] = std::make_shared<doIf>();
primTable["doIfElse"] = std::make_shared<doIfElse>();
primTable["doUntil"] = std::make_shared<doUntil>();
// Operators
primTable["reportSum"] = std::make_shared<add>();
primTable["reportDifference"] = std::make_shared<subtract>();
primTable["reportProduct"] = std::make_shared<multiply>();
primTable["reportQuotient"] = std::make_shared<divide>();
primTable["reportRandom"] = std::make_shared<randomFromTo>();
primTable["reportLessThan"] = std::make_shared<lessThan>();
primTable["reportEquals"] = std::make_shared<equalTo>();
primTable["reportGreaterThan"] = std::make_shared<greaterThan>();
primTable["reportAnd"] = std::make_shared<logicalAnd>();
primTable["reportOr"] = std::make_shared<logicalOr>();
primTable["reportNot"] = std::make_shared<logicalNegation>();
primTable["reportModulus"] = std::make_shared<modulo>();
primTable["reportRound"] = std::make_shared<roundToNearest>();
primTable["reportMonadic"] = std::make_shared<computeFunction>();
primTable["reportTrue"] = std::make_shared<reportTrue>();
primTable["reportFalse"] = std::make_shared<reportFalse>();
primTable["avg"] = std::make_shared<avg>();
primTable["maxOf"] = std::make_shared<maxOf>();
primTable["minOf"] = std::make_shared<minOf>();
primTable["getValOf"] = std::make_shared<getValueOf>();
// primTable["reportJSFunction"] = std::make_shared<reportJSFunction>();
// HVAC
primTable["coolSetpoint"] = std::make_shared<coolSetpoint>();
primTable["heatSetpoint"] = std::make_shared<heatSetpoint>();
// Variables
primTable["readVariable"] = std::make_shared<readVariable>();
primTable["doSetVar"] = std::make_shared<setVar>();
primTable["changeVar"] = std::make_shared<changeVar>();
primTable["readPoint"] = std::make_shared<readPoint>();
primTable["doSetPoint"] = std::make_shared<setPoint>();
primTable["doChangePoint"] = std::make_shared<changePoint>();
// Alarms
primTable["highLimit"] = std::make_shared<highLimit>();
primTable["highLimitDelay"] = std::make_shared<highLimitDelay>();
primTable["lowLimit"] = std::make_shared<lowLimit>();
primTable["lowLimitDelay"] = std::make_shared<lowLimitDelay>();
primTable["runtimeLimit"] = std::make_shared<runtimeLimit>();
primTable["statusAlarm"] = std::make_shared<statusAlarm>();
primTable["customAlarm"] = std::make_shared<customAlarm>();
}
void Interpreter::start() {
// std::map<const int, std::shared_future<float> > threads;
for (auto script : program_.startingBlocks()) {
if (script.second->opcode().find("when") == 0) {
try {
pool.enqueue(&Interpreter::execute, &(*this), script.second);
} catch (std::runtime_error e) {
LOG(Log::ERROR, e.what());
}
// std::shared_future<float> f(std::async(std::launch::async,
// &Interpreter::execute, *this, script.second));
// if (f.valid())
// threads.insert({script.first, f});
} else {
LOG(Log::ERROR, "A script failed to start: " + script.second->opcode());
}
}
while (!program_.needsRestart()) {
// for (auto &thread : threads) {
// if ((thread.second).wait_for(std::chrono::milliseconds(0))
// == std::future_status::ready) {
// const int idx(thread.first);
// thread.second = std::shared_future<float>(std::async(std::launch::async, &Interpreter::execute, *this, program_.startingBlocks()[idx]));
// }
//
// }
// TODO: Break out into its own function
for (auto& device: program_.devices()) {
std::shared_ptr<sql::ResultSet> res =
DB_READ("SELECT devicestatus.name "
"FROM `devicestatus` "
"INNER JOIN `device` "
"ON device.devicestatusid=devicestatus.devicestatusid "
"WHERE device.deviceid='" + std::to_string(device->id()) + "'");
if (res->next()) {
std::string state = res->getString("name");
device->prevState(device->state());
if (state == "Offline")
device->state(DeviceStatus::Offline);
else if (state == "Online")
device->state(DeviceStatus::Online);
else if (state == "Error")
device->state(DeviceStatus::Error);
else if (state == "Deleted")
device->state(DeviceStatus::Deleted);
}
}
sleep(5);
// std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
}
float Interpreter::execute(const block_ptr &b) {
func_map::const_iterator op = primTable.find(b->opcode());
if (op == primTable.end()) {
LOG(Log::ERROR, "No function for " + b->opcode() + " was found");
return -1;
}
float res = callFunc(op, b);
if (b->next()) {
execute(b->next());
}
return res;
}
float Interpreter::callFunc(const func_map::const_iterator& func, const block_ptr &b) {
if (std::shared_ptr<VoidFunctor> p = std::dynamic_pointer_cast<VoidFunctor>(func->second)) {
(*p)(b, *this);
} else if (std::shared_ptr<BoolFunctor> p = std::dynamic_pointer_cast<BoolFunctor>(func->second)) {
return (*p)(b, *this);
} else if (std::shared_ptr<FloatFunctor> p = std::dynamic_pointer_cast<FloatFunctor>(func->second)) {
return (*p)(b, *this);
} else if (std::shared_ptr<IntFunctor> p = std::dynamic_pointer_cast<IntFunctor>(func->second)) {
return (*p)(b, *this);
}
return 0;
}
const std::vector<var_ptr>& Interpreter::variables() {
return program_.variables();
}
const std::vector<point_ptr>& Interpreter::points() {
return program_.points();
}
const std::vector<dev_ptr>& Interpreter::devices() {
return program_.devices();
}
}
| 37.961749 | 143 | 0.652512 | aaronh82 |
2fe5fd2a7c9524274834a904724210c05e8c10f2 | 861 | hpp | C++ | VSProject/LeetCodeSol/Src/RemoveNthNodeFromEndOfListSolution.hpp | wangxiaotao1980/leetCodeCPP | 1806c00cd89eacddbdd20a7c33875f54400a20a8 | [
"MIT"
] | null | null | null | VSProject/LeetCodeSol/Src/RemoveNthNodeFromEndOfListSolution.hpp | wangxiaotao1980/leetCodeCPP | 1806c00cd89eacddbdd20a7c33875f54400a20a8 | [
"MIT"
] | null | null | null | VSProject/LeetCodeSol/Src/RemoveNthNodeFromEndOfListSolution.hpp | wangxiaotao1980/leetCodeCPP | 1806c00cd89eacddbdd20a7c33875f54400a20a8 | [
"MIT"
] | null | null | null | /*******************************************************************************************
* @file RemoveNthNodeFromEndOfListSolution.hpp 2015\12\7 18:00:31 $
* @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试)
* @note LeetCode No.19 Remove Nth Node From End of List
*******************************************************************************************/
#ifndef LEETCODESOL_REMOVENTHNODEFROMENDOFLISTSOLUTION_HPP
#define LEETCODESOL_REMOVENTHNODEFROMENDOFLISTSOLUTION_HPP
struct ListNode;
class RemoveNthNodeFromEndOfListSolution
{
public:
/**
* LeetCode No.19 Remove Nth Node From End of List
*/
ListNode* removeNthFromEnd(ListNode* head, int n);
};
/*******************************************************************************************/
#endif //LEETCODESOL_REMOVENTHNODEFROMENDOFLISTSOLUTION_HPP | 39.136364 | 93 | 0.518002 | wangxiaotao1980 |
2fe9544cd33458415422898cbce4b8cc48c75654 | 333 | cpp | C++ | src/sqlite/SQLiteCountProxy.cpp | alvarudras/dbc-cpp | b5bdb6c0584edeb24b65e939d3d95742e4716ccf | [
"MIT"
] | 2 | 2015-04-08T06:53:06.000Z | 2021-10-02T06:28:43.000Z | src/sqlite/SQLiteCountProxy.cpp | alvarudras/dbc-cpp | b5bdb6c0584edeb24b65e939d3d95742e4716ccf | [
"MIT"
] | 1 | 2018-11-23T06:31:18.000Z | 2018-11-23T10:38:50.000Z | src/sqlite/SQLiteCountProxy.cpp | alvarudras/dbc-cpp | b5bdb6c0584edeb24b65e939d3d95742e4716ccf | [
"MIT"
] | 6 | 2015-11-13T03:44:44.000Z | 2021-07-28T23:10:39.000Z | #include "SQLiteCountProxy.h"
#include <sqlite3.h>
namespace dbc
{
SQLiteCountProxy::operator int() const
{
// If a separate thread makes changes on the same database connection
// while sqlite3_changes() is running then the value returned is
// unpredictable and not meaningful.
return sqlite3_changes(_db);
}
}
| 19.588235 | 73 | 0.72973 | alvarudras |
2fee719c3fa6be900d072284e51976f5523981fe | 1,965 | hh | C++ | ProductionSolenoidGeom/inc/PSExternalShielding.hh | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | ProductionSolenoidGeom/inc/PSExternalShielding.hh | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | ProductionSolenoidGeom/inc/PSExternalShielding.hh | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | #ifndef ProductionSolenoidGeom_PSExternalShielding_hh
#define ProductionSolenoidGeom_PSExternalShielding_hh
//
//
// Original author David Norvil Brown
//
// The PS External Shield is extruded, upside-down "u" shape, made of
// concrete.
#include <vector>
#include <ostream>
#include "CLHEP/Vector/TwoVector.h"
#include "CLHEP/Vector/ThreeVector.h"
#include "Offline/Mu2eInterfaces/inc/Detector.hh"
#include "canvas/Persistency/Common/Wrapper.h"
namespace mu2e {
class PSExternalShieldingMaker;
class PSExternalShielding : virtual public Detector {
public:
// Use a vector of Hep2Vectors for the corners of the shape to be extruded
const std::vector<CLHEP::Hep2Vector>& externalShieldOutline() const { return _externalShieldOutline; }
const double& getLength() const { return _length; }
const std::string materialName() const { return _materialName; }
const CLHEP::Hep3Vector centerOfShield() const { return _centerPosition; }
private:
friend class PSExternalShieldingMaker;
// Private ctr: the class should only be constructed via PSExternalShielding::PSExternalShieldingMaker.
PSExternalShielding(const std::vector<CLHEP::Hep2Vector>& shape, const double& leng, const std::string mat, const CLHEP::Hep3Vector site)
: _externalShieldOutline(shape),
_length(leng), _materialName(mat),
_centerPosition(site)
{ }
// Or read back from persistent storage
PSExternalShielding();
template<class T> friend class art::Wrapper;
// Current description based on private email Rick Coleman ->
// D. Norvil Brown, describing the implementation of the external shield
// in G4BeamLine.
std::vector<CLHEP::Hep2Vector> _externalShieldOutline;
double _length;
std::string _materialName;
CLHEP::Hep3Vector _centerPosition;
};
std::ostream& operator<<(std::ostream& os, const PSExternalShielding& pse);
}
#endif/*ProductionSolenoidGeom_PSExternalShielding_hh*/
| 29.328358 | 141 | 0.747583 | resnegfk |
2ff5ac4adb71636991eca358dd170b54ccfb9fad | 28,720 | cpp | C++ | src/Base/PositionDragger.cpp | orikuma/choreonoid-org | d63dff5fa2249a586ffb2dbdbfa0aef0081bad66 | [
"MIT"
] | null | null | null | src/Base/PositionDragger.cpp | orikuma/choreonoid-org | d63dff5fa2249a586ffb2dbdbfa0aef0081bad66 | [
"MIT"
] | null | null | null | src/Base/PositionDragger.cpp | orikuma/choreonoid-org | d63dff5fa2249a586ffb2dbdbfa0aef0081bad66 | [
"MIT"
] | null | null | null | /**
@author Shin'ichiro Nakaoka
*/
#include "PositionDragger.h"
#include "SceneDragProjector.h"
#include "SceneWidget.h"
#include <cnoid/SceneNodeClassRegistry>
#include <cnoid/SceneRenderer>
#include <cnoid/SceneUtil>
#include <cnoid/MeshGenerator>
#include <cnoid/EigenUtil>
#include <cnoid/CloneMap>
#include <bitset>
#include <deque>
#include <array>
#include <unordered_map>
#include <iostream>
using namespace std;
using namespace cnoid;
namespace {
constexpr int NumHandleVariants = 5;
typedef bitset<6> AxisBitSet;
const char* AxisNames[6] = { "tx", "ty", "tz", "rx", "ry", "rz" };
const Vector3f AxisColors[3] = {
{ 1.0f, 0.2f, 0.2f },
{ 0.2f, 1.0f, 0.2f },
{ 0.2f, 0.2f, 1.0f }
};
const Vector3f HighlightedAxisColors[3] = {
{ 1.0f, 0.4f, 0.4f },
{ 0.5f, 1.0f, 0.4f },
{ 0.4f, 0.5f, 1.0f }
};
constexpr double StdUnitHandleWidth = 0.02;
constexpr double StdPixelHandleWidth = 6.0;
constexpr double MaxPixelHandleWidthCorrectionRatio = 3.0;
constexpr double StdRotationHandleSizeRatio = 0.6;
constexpr double WideUnitHandleWidth = 0.08;
constexpr double WideRotationHandleSizeRatio = 0.5;
constexpr float DefaultTransparency = 0.4f;
class SgHandleVariantSelector : public SgGroup
{
PositionDragger::Impl* dragger;
public:
SgHandleVariantSelector(PositionDragger::Impl* dragger);
void render(SceneRenderer* renderer);
};
/**
\note This node is not inserted the node path obtained by SceneWidgetEvent::nodePath()
*/
class SgViewpointDependentSelector : public SgGroup
{
Vector3 axis;
double thresh;
public:
SgViewpointDependentSelector();
void setAxis(const Vector3& axis);
void setSwitchAngle(double rad);
void render(SceneRenderer* renderer);
};
void registerPickingShapeSelector(SceneNodeClassRegistry& registry)
{
registry.registerClass<SgHandleVariantSelector, SgGroup>();
SceneRenderer::addExtension(
[](SceneRenderer* renderer){
auto functions = renderer->renderingFunctions();
functions->setFunction<SgHandleVariantSelector>(
[=](SgNode* node){
static_cast<SgHandleVariantSelector*>(node)->render(renderer);
});
});
}
void registerViewpointDependentSelector(SceneNodeClassRegistry& registry)
{
registry.registerClass<SgViewpointDependentSelector, SgGroup>();
SceneRenderer::addExtension(
[](SceneRenderer* renderer){
auto functions = renderer->renderingFunctions();
functions->setFunction<SgViewpointDependentSelector>(
[=](SgNode* node){
static_cast<SgViewpointDependentSelector*>(node)->render(renderer);
});
});
}
float convertToTubeTransparency(float t)
{
// Reduce the alpha value by half because the total alpha value of the handle
// is a composite of the front and back surfaces of the handle tube shape
return (t == 0.0f) ? 0.0f : (1.0f - (1.0f - t) / 2.0f);
}
}
namespace cnoid {
class PositionDragger::Impl
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PositionDragger* self;
unordered_map<double, SgNodePtr> handleVariantMap;
AxisBitSet draggableAxisBitSet;
SgSwitchPtr axisSwitch[6];
int handleType;
double handleSize;
double handleWidth;
double unitHandleWidth;
Signal<void(int axisBitSet)> sigDraggableAxesChanged;
DisplayMode displayMode;
bool isEditMode;
bool isOverlayMode;
bool isFixedPixelSizeMode;
bool isContainerMode;
bool isDragEnabled;
bool isContentsDragEnabled;
bool isUndoEnabled;
bool hasOffset;
Affine3 T_parent;
Position T_offset;
SgSwitchableGroupPtr topSwitch;
SgOverlayPtr overlay;
SgFixedPixelSizeGroupPtr fixedPixelSizeGroup;
double rotationHandleSizeRatio;
array<SgMaterialPtr, 6> axisMaterials;
float transparency;
AxisBitSet highlightedAxisBitSet;
MeshGenerator meshGenerator;
SceneDragProjector dragProjector;
Signal<void()> sigDragStarted;
Signal<void()> sigPositionDragged;
Signal<void()> sigDragFinished;
std::deque<Affine3> history;
Impl(PositionDragger* self, int mode, int axes);
SgNode* createHandle(double widthRatio);
SgNode* createTranslationHandle(double widthRatio);
SgNode* createRotationRingHandle(double widthRatio);
SgNode* createRotationDiscHandle(double widthRatio);
double calcWidthRatio(double pixelSizeRatio);
SgNode* getOrCreateHandleVariant(double pixelSizeRatio, bool isForPicking);
void clearHandleVariants();
void setDraggableAxes(AxisBitSet axisBitSet);
void setMaterialParameters(AxisBitSet axisBitSet, float t, bool isHighlighted);
void highlightAxes(AxisBitSet axisBitSet);
void showDragMarkers(bool on);
AxisBitSet detectTargetAxes(const SceneWidgetEvent& event);
bool onButtonPressEvent(const SceneWidgetEvent& event);
bool onTranslationDraggerPressed(
const SceneWidgetEvent& event, const Affine3& T_global, AxisBitSet axisBitSet);
bool onRotationDraggerPressed(
const SceneWidgetEvent& event, const Affine3& T_global, AxisBitSet axisBitSet);
void storeCurrentPositionToHistory();
};
}
SgHandleVariantSelector::SgHandleVariantSelector(PositionDragger::Impl* dragger)
: SgGroup(findClassId<SgHandleVariantSelector>()),
dragger(dragger)
{
}
void SgHandleVariantSelector::render(SceneRenderer* renderer)
{
double pixelSizeRatio = -1.0;
bool isForPicking = false;
if(!dragger->isFixedPixelSizeMode){
pixelSizeRatio = renderer->projectedPixelSizeRatio(
renderer->currentModelTransform().translation());
isForPicking = renderer->isRenderingPickingImage();
}
//
clearChildren();
if(auto node = dragger->getOrCreateHandleVariant(pixelSizeRatio, isForPicking)){
addChildOnce(node);
renderer->renderNode(node);
}
}
SgViewpointDependentSelector::SgViewpointDependentSelector()
: SgGroup(findClassId<SgViewpointDependentSelector>())
{
axis = Vector3::UnitX();
thresh = cos(radian(45.0));
}
void SgViewpointDependentSelector::setAxis(const Vector3& axis)
{
this->axis = axis;
}
void SgViewpointDependentSelector::setSwitchAngle(double rad)
{
thresh = cos(rad);
}
void SgViewpointDependentSelector::render(SceneRenderer* renderer)
{
const Affine3& C = renderer->currentCameraPosition();
const Affine3& M = renderer->currentModelTransform();
double d = fabs((C.translation() - M.translation()).normalized().dot((M.linear() * axis).normalized()));
if(d > thresh){
if(numChildren() > 0){
renderer->renderNode(child(0));
}
} else {
if(numChildren() > 1){
renderer->renderNode(child(1));
}
}
}
PositionDragger::PositionDragger(int mode, int axes)
{
impl = new Impl(this, mode, axes);
}
PositionDragger::Impl::Impl(PositionDragger* self, int axes, int handleType)
: self(self),
draggableAxisBitSet(axes),
handleType(handleType)
{
auto& registry = SceneNodeClassRegistry::instance();
handleSize = 1.0;
if(!registry.hasRegistration<SgHandleVariantSelector>()){
registerPickingShapeSelector(registry);
}
if(handleType != WideHandle){
unitHandleWidth = StdUnitHandleWidth;
rotationHandleSizeRatio = StdRotationHandleSizeRatio;
} else {
if(!registry.hasRegistration<SgViewpointDependentSelector>()){
registerViewpointDependentSelector(registry);
}
unitHandleWidth = WideUnitHandleWidth;
rotationHandleSizeRatio = WideRotationHandleSizeRatio;
}
for(int i=0; i < 6; ++i){
axisSwitch[i] = new SgSwitch(draggableAxisBitSet[i]);
}
displayMode = DisplayInFocus;
isEditMode = false;
isOverlayMode = false;
isFixedPixelSizeMode = false;
isContainerMode = false;
isDragEnabled = true;
isContentsDragEnabled = true;
isUndoEnabled = false;
hasOffset = false;
T_offset.setIdentity();
transparency = DefaultTransparency;
highlightedAxisBitSet.reset();
for(int i=0; i < 3; ++i){
auto material = new SgMaterial;
material->setDiffuseColor(Vector3f::Zero());
material->setEmissiveColor(AxisColors[i]);
material->setAmbientIntensity(0.0f);
material->setTransparency(convertToTubeTransparency(transparency));
axisMaterials[i] = material;
auto rotationAxisMaterial = new SgMaterial(*material);
if(handleType == WideHandle){
rotationAxisMaterial->setTransparency(transparency);
}
axisMaterials[i+3] = rotationAxisMaterial;
}
topSwitch = new SgSwitchableGroup;
topSwitch->addChild(new SgHandleVariantSelector(this));
self->addChild(topSwitch);
}
SgNode* PositionDragger::Impl::createHandle(double widthRatio)
{
auto draggerAxes = new SgGroup;
draggerAxes->addChild(createTranslationHandle(widthRatio));
if(handleType != WideHandle){
draggerAxes->addChild(createRotationRingHandle(widthRatio));
} else {
draggerAxes->addChild(createRotationDiscHandle(widthRatio));
}
return draggerAxes;
}
SgNode* PositionDragger::Impl::createTranslationHandle(double widthRatio)
{
auto scale = new SgScaleTransform(handleSize);
double endLength = unitHandleWidth * 2.5;
double extraEndLength = endLength * (widthRatio - 1.0);
double stickLength = 1.0 - endLength;
if(!(handleType == PositiveOnlyHandle)){
stickLength *= 2.0;
}
stickLength -= extraEndLength / 2.0;
int divisionNumber = std::max((int)(24 / widthRatio), 8);
meshGenerator.setDivisionNumber(divisionNumber);
SgMeshPtr mesh = meshGenerator.generateArrow(
(unitHandleWidth / 2.0) * widthRatio,
stickLength,
unitHandleWidth * 1.25 * widthRatio,
endLength * widthRatio);
for(int i=0; i < 3; ++i){
auto shape = new SgShape;
shape->setMesh(mesh);
shape->setMaterial(axisMaterials[i]);
auto arrow = new SgPosTransform;
arrow->addChild(shape);
if(i == 0){
arrow->setRotation(AngleAxis(-PI / 2.0, Vector3::UnitZ()));
} else if(i == 2){
arrow->setRotation(AngleAxis(PI / 2.0, Vector3::UnitX()));
}
if(handleType == PositiveOnlyHandle){
arrow->translation()[i] = stickLength / 2.0;
} else {
arrow->translation()[i] = -extraEndLength / 2.0;
}
arrow->setName(AxisNames[i]);
auto axis = new SgSwitchableGroup(axisSwitch[i]);
axis->addChild(arrow);
scale->addChild(axis);
}
return scale;
}
SgNode* PositionDragger::Impl::createRotationRingHandle(double widthRatio)
{
auto scale = new SgScaleTransform(handleSize * rotationHandleSizeRatio);
double radius = widthRatio * unitHandleWidth / 2.0 / rotationHandleSizeRatio;
double endAngle = (handleType == PositiveOnlyHandle) ? (PI / 2.0) : 2.0 * PI;
int divisionNumber = std::max((int)(72 / widthRatio), 24);
meshGenerator.setDivisionNumber(divisionNumber);
auto ringMesh = meshGenerator.generateTorus(1.0, radius, 0.0, endAngle);
for(int i=0; i < 3; ++i){
auto material = axisMaterials[i+3];
auto ringShape = new SgShape;
ringShape->setMesh(ringMesh);
ringShape->setMaterial(material);
auto ring = new SgPosTransform;
if(i == 0){ // x-axis
ring->setRotation(AngleAxis(PI / 2.0, Vector3::UnitZ()));
} else if(i == 2) { // z-axis
ring->setRotation(AngleAxis(-PI / 2.0, Vector3::UnitX()));
}
ring->addChild(ringShape);
ring->setName(AxisNames[i + 3]);
auto axis = new SgSwitchableGroup(axisSwitch[i + 3]);
axis->addChild(ring);
scale->addChild(axis);
}
return scale;
}
SgNode* PositionDragger::Impl::createRotationDiscHandle(double widthRatio)
{
auto scale = new SgScaleTransform(handleSize * rotationHandleSizeRatio);
SgMesh* mesh[2];
double width = unitHandleWidth / rotationHandleSizeRatio * widthRatio;
meshGenerator.setDivisionNumber(36);
mesh[0] = meshGenerator.generateDisc(1.0, 1.0 - width);
mesh[1] = meshGenerator.generateCylinder(1.0, width, false, false);
for(int i=0; i < 3; ++i){
auto selector = new SgViewpointDependentSelector;
Vector3 a = Vector3::Zero();
a(i) = 1.0;
selector->setAxis(a);
for(int j=0; j < 2; ++j){
auto shape = new SgShape;
shape->setMesh(mesh[j]);
shape->setMaterial(axisMaterials[i+3]);
auto disc = new SgPosTransform;
if(i == 0){ // x-axis
disc->setRotation(AngleAxis(-PI / 2.0, Vector3::UnitZ()));
} else if(i == 2) { // z-axis
disc->setRotation(AngleAxis(PI / 2.0, Vector3::UnitX()));
}
disc->addChild(shape);
disc->setName(AxisNames[i + 3]);
selector->addChild(disc);
}
auto axis = new SgSwitchableGroup(axisSwitch[i + 3]);
axis->addChild(selector);
scale->addChild(axis);
}
return scale;
}
double PositionDragger::Impl::calcWidthRatio(double pixelSizeRatio)
{
double widthRatio = 1.0;
if(pixelSizeRatio >= 0.0){
double pixelWidth = unitHandleWidth * handleSize * pixelSizeRatio;
if(pixelWidth > 0.1){
if(pixelWidth < StdPixelHandleWidth){
widthRatio = StdPixelHandleWidth / pixelWidth;
}
if(widthRatio > MaxPixelHandleWidthCorrectionRatio){
widthRatio = MaxPixelHandleWidthCorrectionRatio;
}
}
}
return widthRatio;
}
/**
\todo
- Make the handles for picking a bit wider
- Cache the generated handles in handleVariantMap
- Adjust the width considering the DPI of the display
*/
SgNode* PositionDragger::Impl::getOrCreateHandleVariant(double pixelSizeRatio, bool isForPicking)
{
double widthRatio;
if(handleType != WideHandle){
widthRatio = calcWidthRatio(pixelSizeRatio);
} else {
widthRatio = 1.0;
}
return createHandle(widthRatio);
}
void PositionDragger::Impl::clearHandleVariants()
{
handleVariantMap.clear();
}
void PositionDragger::setOffset(const Affine3& T)
{
impl->T_offset = T;
impl->hasOffset = (T.matrix() != Affine3::Identity().matrix());
}
void PositionDragger::setDraggableAxes(int axisBitSet)
{
impl->setDraggableAxes(axisBitSet);
}
void PositionDragger::Impl::setDraggableAxes(AxisBitSet axisBitSet)
{
if(axisBitSet != draggableAxisBitSet){
for(int i=0; i < 6; ++i){
axisSwitch[i]->setTurnedOn(axisBitSet[i], true);
}
draggableAxisBitSet = axisBitSet;
}
}
int PositionDragger::draggableAxes() const
{
return static_cast<int>(impl->draggableAxisBitSet.to_ulong());
}
SignalProxy<void(int axisSet)> PositionDragger::sigDraggableAxesChanged()
{
return impl->sigDraggableAxesChanged;
}
double PositionDragger::handleSize() const
{
return impl->handleSize;
}
void PositionDragger::setHandleSize(double s)
{
if(s != impl->handleSize){
impl->handleSize = s;
impl->clearHandleVariants();
}
}
void PositionDragger::setHandleWidthRatio(double w)
{
if(w != impl->unitHandleWidth){
impl->unitHandleWidth = w;
impl->clearHandleVariants();
}
}
double PositionDragger::rotationHandleSizeRatio() const
{
return impl->rotationHandleSizeRatio;
}
void PositionDragger::setRotationHandleSizeRatio(double r)
{
if(r != impl->rotationHandleSizeRatio){
impl->rotationHandleSizeRatio = r;
impl->clearHandleVariants();
}
}
void PositionDragger::setRadius(double r, double translationAxisRatio)
{
impl->rotationHandleSizeRatio = 1.0 / translationAxisRatio;
setHandleSize(2.0 * r);
}
double PositionDragger::radius() const
{
return impl->handleSize * impl->rotationHandleSizeRatio;
}
bool PositionDragger::adjustSize(const BoundingBox& bb)
{
if(bb.empty()){
return false;
}
Vector3 s = bb.size() / 2.0;
std::sort(s.data(), s.data() + 3);
double r = Vector2(s[0], s[1]).norm();
if(!impl->isOverlayMode){
r *= 1.05;
}
setHandleSize(r / impl->rotationHandleSizeRatio);
return true;
}
bool PositionDragger::adjustSize()
{
BoundingBox bb;
for(int i=0; i < numChildren(); ++i){
auto node = child(i);
if(node != impl->topSwitch){
bb.expandBy(node->boundingBox());
}
}
return adjustSize(bb);
}
void PositionDragger::setTransparency(float t)
{
impl->setMaterialParameters(AllAxes, t, false);
impl->transparency = t;
impl->highlightedAxisBitSet.reset();
}
void PositionDragger::Impl::setMaterialParameters(AxisBitSet axisBitSet, float t, bool isHighlighted)
{
float t2 = convertToTubeTransparency(t);
for(int i=0; i < 6; ++i){
int axis = i < 3 ? i : i - 3;
if(i == 3){
if(handleType == WideHandle){
t2 = t;
}
}
if(axisBitSet[i]){
bool updated = false;
auto& material = axisMaterials[i];
if(t != material->transparency()){
material->setTransparency(t2);
updated = true;
}
if(transparency == 0.0f){
const Vector3f& color = isHighlighted ? HighlightedAxisColors[axis] : AxisColors[axis];
if(color != material->emissiveColor()){
material->setEmissiveColor(color);
updated = true;
}
}
if(updated){
material->notifyUpdate();
}
}
}
}
float PositionDragger::transparency() const
{
return impl->transparency;
}
void PositionDragger::Impl::highlightAxes(AxisBitSet axisBitSet)
{
if(axisBitSet != highlightedAxisBitSet){
if(highlightedAxisBitSet.any()){
setMaterialParameters(highlightedAxisBitSet, transparency, false);
}
if(axisBitSet.any()){
setMaterialParameters(axisBitSet, 0.0f, true);
}
highlightedAxisBitSet = axisBitSet;
}
}
void PositionDragger::setOverlayMode(bool on)
{
if(on != impl->isOverlayMode){
if(on){
if(!impl->overlay){
impl->overlay = new SgOverlay;
}
impl->topSwitch->insertChainedGroup(impl->overlay);
} else {
impl->topSwitch->removeChainedGroup(impl->overlay);
}
impl->isOverlayMode = on;
}
}
bool PositionDragger::isOverlayMode() const
{
return impl->isOverlayMode;
}
void PositionDragger::setFixedPixelSizeMode(bool on, double pixelSizeRatio)
{
if(impl->fixedPixelSizeGroup){
impl->fixedPixelSizeGroup->setPixelSizeRatio(pixelSizeRatio);
}
if(on != impl->isFixedPixelSizeMode){
if(on){
if(!impl->fixedPixelSizeGroup){
impl->fixedPixelSizeGroup = new SgFixedPixelSizeGroup(pixelSizeRatio);
}
impl->topSwitch->insertChainedGroup(impl->fixedPixelSizeGroup);
} else {
impl->topSwitch->removeChainedGroup(impl->fixedPixelSizeGroup);
}
impl->isFixedPixelSizeMode = on;
}
}
bool PositionDragger::isFixedPixelSizeMode() const
{
return impl->isFixedPixelSizeMode;
}
bool PositionDragger::isContainerMode() const
{
return impl->isContainerMode;
}
void PositionDragger::setContainerMode(bool on)
{
impl->isContainerMode = on;
}
void PositionDragger::setContentsDragEnabled(bool on)
{
impl->isContentsDragEnabled = on;
}
bool PositionDragger::isContentsDragEnabled() const
{
return impl->isContentsDragEnabled;
}
PositionDragger::DisplayMode PositionDragger::displayMode() const
{
return impl->displayMode;
}
void PositionDragger::setDisplayMode(DisplayMode mode)
{
if(mode != impl->displayMode){
impl->displayMode = mode;
if(mode == DisplayAlways){
impl->showDragMarkers(true);
} else if(mode == DisplayInEditMode){
if(impl->isEditMode){
impl->showDragMarkers(true);
}
} else if(mode == DisplayNever){
impl->showDragMarkers(false);
}
}
}
void PositionDragger::Impl::showDragMarkers(bool on)
{
if(displayMode == DisplayNever){
on = false;
} else if(displayMode == DisplayAlways){
on = true;
}
topSwitch->setTurnedOn(on, true);
}
void PositionDragger::setDraggerAlwaysShown(bool on)
{
if(on){
setDisplayMode(DisplayAlways);
}
}
bool PositionDragger::isDraggerAlwaysShown() const
{
return (impl->displayMode == DisplayAlways);
}
void PositionDragger::setDraggerAlwaysHidden(bool on)
{
if(on){
setDisplayMode(DisplayNever);
}
}
bool PositionDragger::isDraggerAlwaysHidden() const
{
return (impl->displayMode == DisplayNever);
}
bool PositionDragger::isDragEnabled() const
{
return impl->isDragEnabled;
}
void PositionDragger::setDragEnabled(bool on)
{
impl->isDragEnabled = on;
}
bool PositionDragger::isDragging() const
{
return impl->dragProjector.isDragging();
}
Affine3 PositionDragger::draggingPosition() const
{
Affine3 T1;
if(impl->dragProjector.isDragging()){
T1 = impl->T_parent.inverse(Eigen::Isometry) * impl->dragProjector.position();
} else {
T1 = T();
}
if(impl->hasOffset){
return T1 * impl->T_offset.inverse(Eigen::Isometry);
}
return T1;
}
Affine3 PositionDragger::globalDraggingPosition() const
{
Affine3 T1;
if(impl->dragProjector.isDragging()){
T1 = impl->dragProjector.position();
} else {
T1 = impl->T_parent * T();
}
if(impl->hasOffset){
return T1 * impl->T_offset.inverse(Eigen::Isometry);
}
return T1;
}
SignalProxy<void()> PositionDragger::sigDragStarted()
{
return impl->sigDragStarted;
}
SignalProxy<void()> PositionDragger::sigPositionDragged()
{
return impl->sigPositionDragged;
}
SignalProxy<void()> PositionDragger::sigDragFinished()
{
return impl->sigDragFinished;
}
AxisBitSet PositionDragger::Impl::detectTargetAxes(const SceneWidgetEvent& event)
{
AxisBitSet axisBitSet(0);
auto& path = event.nodePath();
for(size_t i=0; i < path.size(); ++i){
if(path[i] == self){
for(size_t j=i+1; j < path.size(); ++j){
auto& name = path[j]->name();
if(!name.empty()){
for(int k=0; k < 6; ++k){
if(name == AxisNames[k]){
axisBitSet.set(k);
break;
}
}
}
}
break;
}
}
if((axisBitSet & AxisBitSet(TRANSLATION_AXES)).any()){
const Affine3 T_global = calcTotalTransform(event.nodePath(), self);
const Vector3 p_local = T_global.inverse() * event.point();
double width = handleSize * unitHandleWidth * calcWidthRatio(event.pixelSizeRatio());
if(p_local.norm() < 1.5 * width){
axisBitSet |= AxisBitSet(TRANSLATION_AXES);
}
}
return axisBitSet;
}
bool PositionDragger::onButtonPressEvent(const SceneWidgetEvent& event)
{
return impl->onButtonPressEvent(event);
}
bool PositionDragger::Impl::onButtonPressEvent(const SceneWidgetEvent& event)
{
bool processed = false;
if(!isDragEnabled){
return processed;
}
auto& path = event.nodePath();
auto iter = std::find(path.begin(), path.end(), self);
if(iter != path.end()){
T_parent = calcTotalTransform(path.begin(), iter);
const Affine3 T_global = T_parent * self->T();
auto axisBitSet = detectTargetAxes(event);
if(axisBitSet.none()){
if(self->isContainerMode() && isContentsDragEnabled){
if(displayMode == DisplayInFocus){
showDragMarkers(true);
}
dragProjector.setInitialPosition(T_global);
dragProjector.setTranslationAlongViewPlane();
if(dragProjector.startTranslation(event)){
processed = true;
}
}
} else {
if((axisBitSet & AxisBitSet(TRANSLATION_AXES)).any()){
processed = onTranslationDraggerPressed(event, T_global, axisBitSet);
} else if((axisBitSet & AxisBitSet(ROTATION_AXES)).any()){
processed = onRotationDraggerPressed(event, T_global, axisBitSet);
}
}
}
if(processed){
storeCurrentPositionToHistory();
sigDragStarted();
} else {
dragProjector.resetDragMode();
}
return processed;
}
bool PositionDragger::Impl::onTranslationDraggerPressed
(const SceneWidgetEvent& event, const Affine3& T_global, AxisBitSet axisBitSet)
{
bool processed = false;
dragProjector.setInitialPosition(T_global);
if(axisBitSet.count() == 1){
for(int i=0; i < 3; ++i){
if(axisBitSet[i]){
dragProjector.setTranslationAxis(T_global.linear().col(i));
break;
}
}
} else {
dragProjector.setTranslationAlongViewPlane();
}
if(dragProjector.startTranslation(event)){
processed = true;
}
return processed;
}
bool PositionDragger::Impl::onRotationDraggerPressed
(const SceneWidgetEvent& event, const Affine3& T_global, AxisBitSet axisBitSet)
{
bool processed = false;
if(axisBitSet.count() == 1){
dragProjector.setInitialPosition(T_global);
for(int i=0; i < 3; ++i){
if(axisBitSet[i + 3]){
dragProjector.setRotationAxis(T_global.linear().col(i));
if(dragProjector.startRotation(event)){
processed = true;
}
break;
}
}
}
return processed;
}
bool PositionDragger::onButtonReleaseEvent(const SceneWidgetEvent&)
{
if(impl->dragProjector.isDragging()){
impl->sigDragFinished();
impl->dragProjector.resetDragMode();
return true;
}
return false;
}
bool PositionDragger::onPointerMoveEvent(const SceneWidgetEvent& event)
{
if(!impl->dragProjector.isDragging()){
if(impl->isDragEnabled){
auto axisBitSet = impl->detectTargetAxes(event);
if(axisBitSet.any()){
impl->highlightAxes(axisBitSet);
}
}
} else if(impl->dragProjector.drag(event)){
if(isContainerMode()){
setPosition(impl->dragProjector.position());
notifyUpdate();
}
impl->sigPositionDragged();
}
return true;
}
void PositionDragger::onPointerLeaveEvent(const SceneWidgetEvent&)
{
if(impl->dragProjector.isDragging()){
impl->sigDragFinished();
impl->dragProjector.resetDragMode();
}
impl->highlightAxes(0);
}
void PositionDragger::onFocusChanged(const SceneWidgetEvent&, bool on)
{
if(isContainerMode()){
if(impl->displayMode == DisplayInFocus){
impl->showDragMarkers(on);
}
}
}
void PositionDragger::onSceneModeChanged(const SceneWidgetEvent& event)
{
if(event.sceneWidget()->isEditMode()){
impl->isEditMode = true;
if(impl->displayMode == DisplayInEditMode){
impl->showDragMarkers(true);
}
} else {
impl->isEditMode = false;
if(impl->displayMode == DisplayInEditMode || impl->displayMode == DisplayInFocus){
impl->showDragMarkers(false);
}
}
}
void PositionDragger::storeCurrentPositionToHistory()
{
impl->storeCurrentPositionToHistory();
}
void PositionDragger::Impl::storeCurrentPositionToHistory()
{
if(isUndoEnabled){
history.push_back(self->position());
if(history.size() > 10){
history.pop_front();
}
}
}
void PositionDragger::setUndoEnabled(bool on)
{
impl->isUndoEnabled = on;
}
bool PositionDragger::isUndoEnabled() const
{
return impl->isUndoEnabled;
}
bool PositionDragger::onUndoRequest()
{
if(!impl->history.empty()){
const Affine3& T = impl->history.back();
setPosition(T);
impl->history.pop_back();
notifyUpdate();
}
return true;
}
bool PositionDragger::onRedoRequest()
{
return true;
}
| 25.597148 | 108 | 0.638162 | orikuma |
2ff8cc1123ab38f21623fde19ebd249a31c6c8bf | 1,791 | cpp | C++ | 18.4Sum/Solution.cpp | BrandonHe/leetcode | 83ed1ad7e384551b8f5cc20a65b2a3903df7ff93 | [
"BSD-3-Clause"
] | null | null | null | 18.4Sum/Solution.cpp | BrandonHe/leetcode | 83ed1ad7e384551b8f5cc20a65b2a3903df7ff93 | [
"BSD-3-Clause"
] | null | null | null | 18.4Sum/Solution.cpp | BrandonHe/leetcode | 83ed1ad7e384551b8f5cc20a65b2a3903df7ff93 | [
"BSD-3-Clause"
] | null | null | null | class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int n = nums.size();
if (n < 4) return res;
// Sort to prepare for scanning
sort(nums.begin(), nums.end());
for (int i = 0; i < n-3; i++) {
if(i > 0 && nums[i] == nums[i-1]) continue;
if(nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;
if(nums[i] + nums[n-3] + nums[n-2] + nums[n-1] < target) continue;
for (int j = i+1; j < n - 2; j++) {
if (j > i+1 && nums[j] == nums[j-1]) continue;
if (nums[j] + nums[j+1] + nums[j+2] > target - nums[i]) break;
if (nums[j] + nums[n-2] + nums[n-1] < target - nums[i]) continue;
int left = j + 1;
int right = n - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum < target) left++;
else if (sum > target) right--;
else {
vector<int> quadruplets = {nums[i], nums[j], nums[left], nums[right]};
res.push_back(quadruplets);
//Avoid the duplicate
do {left++;}while (right < left && nums[j+1] == quadruplets[1]);
do {right--;}while (right < left && nums[j+2] == quadruplets[2]);
}
}
while ( j < n-2 && nums[j+1] == nums[j]) j++;
}
while ( i < n-3 && nums[i+1] == nums[i]) i++;
}
return res;
}
}; | 39.8 | 94 | 0.384143 | BrandonHe |
2ff95775da1cf35fadebcfadd40fae8502f0773f | 3,416 | cc | C++ | irrun.cc | falsycat/libirrun | eb6850b72629681f0acb8dcfb4189d5cb0ac6137 | [
"WTFPL"
] | null | null | null | irrun.cc | falsycat/libirrun | eb6850b72629681f0acb8dcfb4189d5cb0ac6137 | [
"WTFPL"
] | null | null | null | irrun.cc | falsycat/libirrun | eb6850b72629681f0acb8dcfb4189d5cb0ac6137 | [
"WTFPL"
] | null | null | null | #include "./irrun.h"
#include <atomic>
#include <iostream>
#include <memory>
#include <string>
#include <llvm/ExecutionEngine/JITSymbol.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/Orc/LambdaResolver.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
struct irrun_t {
irrun_resolver_t resolver;
void* udata;
std::string error;
llvm::LLVMContext Context;
std::unique_ptr<llvm::ExecutionEngine> Engine;
class Resolver : public llvm::LegacyJITSymbolResolver {
irrun_t* super;
Resolver() = delete;
Resolver(const Resolver&) = delete;
Resolver(Resolver&&) = delete;
Resolver& operator=(const Resolver&) = delete;
Resolver& operator=(Resolver&&) = delete;
llvm::JITSymbol findSymbol(const std::string& name) final {
const void* ptr = super->resolver?
super->resolver(name.c_str(), super->udata):
nullptr;
return ptr?
llvm::JITSymbol((llvm::JITTargetAddress) ptr, llvm::JITSymbolFlags::Exported):
llvm::JITSymbol(nullptr);
}
llvm::JITSymbol findSymbolInLogicalDylib(const std::string& name) final {
return 0;
}
public: explicit Resolver(irrun_t* s) : super(s) {}
};
irrun_t() = delete;
irrun_t(const irrun_t&) = delete;
irrun_t(irrun_t&&) = delete;
irrun_t& operator=(const irrun_t&) = delete;
irrun_t& operator=(irrun_t&&) = delete;
explicit irrun_t(irrun_resolver_t r, void* u, llvm::CodeGenOpt::Level opt) :
resolver(r), udata(u) {
Engine.reset(
llvm::EngineBuilder(std::make_unique<llvm::Module>("irrun", Context)).
setEngineKind(llvm::EngineKind::Kind::JIT).
setOptLevel(opt).
setErrorStr(&error).
setSymbolResolver(std::make_unique<Resolver>(this)).
setVerifyModules(true).
create());
}
void addModule(std::unique_ptr<llvm::Module> M) {
Engine->addModule(std::move(M));
}
void* getSymbol(const std::string& str) {
Engine->finalizeObject();
return Engine->getPointerToNamedFunction(str, false /* not to abort on fail */);
}
};
extern "C" {
irrun_t* irrun_new(irrun_resolver_t resolver, void* udata, irrun_optimize_level_t opt) {
static std::atomic_flag once_ = ATOMIC_FLAG_INIT;
if (!once_.test_and_set()) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
}
const auto o =
opt == IRRUN_OPTIMIZE_LEVEL_AGGRESSIVE? llvm::CodeGenOpt::Level::Aggressive:
llvm::CodeGenOpt::Level::None;
return new irrun_t(resolver, udata, o);
}
void irrun_delete(irrun_t* ctx) {
delete ctx;
}
const char* irrun_get_error(const irrun_t* ctx) {
return ctx->error == ""? nullptr: ctx->error.c_str();
}
int irrun_add_module_from_file(irrun_t* ctx, const char* path) {
llvm::SMDiagnostic d;
std::unique_ptr<llvm::Module> m(llvm::parseIRFile(path, d, ctx->Context));
if (!m) {
llvm::raw_string_ostream o(ctx->error);
d.print("irrun", o);
return 0;
}
ctx->addModule(std::move(m));
return 1;
}
void* irrun_sym(irrun_t* ctx, const char* name) {
return ctx->getSymbol(name);
}
}
| 28.466667 | 88 | 0.6774 | falsycat |
2fffc9ba96e859c0eace166a56a440427c223e40 | 282 | hpp | C++ | pythran/pythonic/operator_/__iand__.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/operator_/__iand__.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/operator_/__iand__.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_OPERATOR_IAND__HPP
#define PYTHONIC_OPERATOR_IAND__HPP
#include "pythonic/include/operator_/__iand__.hpp"
#include "pythonic/operator_/iand.hpp"
namespace pythonic
{
namespace operator_
{
FPROXY_IMPL(pythonic::operator_, __iand__, iand);
}
}
#endif
| 14.842105 | 53 | 0.776596 | artas360 |
64003b105304a6e99e404a229c47a8a4075cd256 | 364 | hpp | C++ | falcon/math/minmax.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | 2 | 2018-02-02T14:19:59.000Z | 2018-05-13T02:48:24.000Z | falcon/math/minmax.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | falcon/math/minmax.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | #ifndef FALCON_MATH_MINMAX_HPP
#define FALCON_MATH_MINMAX_HPP
#include <falcon/math/min.hpp>
#include <falcon/math/max.hpp>
#include <utility>
namespace falcon {
template<typename T, typename... _Args>
std::pair<const T&, const T&> minmax(const T& a, const _Args&... args)
{
return std::pair<const T&, const T&>(min(a, args...), max(a, args...));
}
}
#endif
| 19.157895 | 72 | 0.695055 | jonathanpoelen |
6402ae42c22bb1c0027b676c7133b47a47f1a389 | 1,629 | cpp | C++ | ytlib/misc/misc_test.cpp | wt201501/ytlib | 4422eda4c7a1fdbe1500f46bb72f1f43bc4eed3c | [
"MIT"
] | null | null | null | ytlib/misc/misc_test.cpp | wt201501/ytlib | 4422eda4c7a1fdbe1500f46bb72f1f43bc4eed3c | [
"MIT"
] | null | null | null | ytlib/misc/misc_test.cpp | wt201501/ytlib | 4422eda4c7a1fdbe1500f46bb72f1f43bc4eed3c | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <functional>
#include <iostream>
#include <string>
#include "print_ctr.hpp"
namespace ytlib {
using std::cout;
using std::endl;
using std::vector;
struct TestObj {
int age;
std::string name;
friend std::ostream& operator<<(std::ostream& out, const TestObj& obj) {
out << "age:" << obj.age << "\n";
out << "name:" << obj.name << "\n";
return out;
}
};
TEST(PRINTCTR_TEST, BASE_test) {
PrintCtr::Ins().SetPrint(true);
ASSERT_TRUE(PrintCtr::Ins().IfPrint());
TestObj obj = {20, "testname"};
std::string struct_str = R"str(test msg:
age:20
name:testname
)str";
EXPECT_STREQ(PrintCtr::Ins().PrintStruct("test msg", obj).c_str(), struct_str.c_str());
std::vector<std::string> v = {"val1", "val2", "val3\nval3val3"};
std::string v_str = R"str(test vec:
vec size = 3
[index=0]:val1
[index=1]:val2
[index=2]:
val3
val3val3
)str";
EXPECT_STREQ(PrintCtr::Ins().PrintVec("test vec", v).c_str(), v_str.c_str());
std::set<std::string> s = {"val1", "val2", "val3\nval3val3"};
std::string s_str = R"str(test set:
set size = 3
[index=0]:val1
[index=1]:val2
[index=2]:
val3
val3val3
)str";
EXPECT_STREQ(PrintCtr::Ins().PrintSet("test set", s).c_str(), s_str.c_str());
std::map<std::string, std::string> m = {{"key1", "val1"}, {"key2", "val2"}, {"key3", "val3\nval3val3"}};
std::string m_str = R"str(test map:
map size = 3
[index=0]:
[key]:key1
[val]:val1
[index=1]:
[key]:key2
[val]:val2
[index=2]:
[key]:key3
[val]:
val3
val3val3
)str";
EXPECT_STREQ(PrintCtr::Ins().PrintMap("test map", m).c_str(), m_str.c_str());
}
} // namespace ytlib
| 20.620253 | 106 | 0.63229 | wt201501 |
64056cf65634955f0907694509d81a08907631ed | 1,427 | cc | C++ | source/src/core/palmprint.cc | freelandy/EDCC-Palmprint-Recognition | a5c4a0c701be9650944cbeec7cef2fa6113ecada | [
"MIT"
] | 1 | 2019-05-11T01:33:01.000Z | 2019-05-11T01:33:01.000Z | source/src/core/palmprint.cc | freelandy/EDCC-Palmprint-Recognition | a5c4a0c701be9650944cbeec7cef2fa6113ecada | [
"MIT"
] | null | null | null | source/src/core/palmprint.cc | freelandy/EDCC-Palmprint-Recognition | a5c4a0c701be9650944cbeec7cef2fa6113ecada | [
"MIT"
] | null | null | null | // Copyright (c) 2017 Leosocy. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.
#include "core/palmprint.h"
#include "util/pub.h"
namespace edcc
{
Palmprint::Palmprint(const char *identity, const char *image_path)
: identity_(identity),
image_path_(image_path)
{
}
Palmprint::Palmprint(const Palmprint &rhs)
: identity_(rhs.identity_),
image_path_(rhs.image_path_),
image_(rhs.image_.clone())
{
}
Palmprint& Palmprint::operator =(const Palmprint &rhs)
{
if (this != &rhs)
{
identity_ = rhs.identity_;
image_path_ = rhs.image_path_;
image_ = rhs.image_.clone();
}
return *this;
}
bool Palmprint::operator==(const Palmprint &rhs) const
{
return identity_ == rhs.identity_
&& image_path_ == rhs.image_path_;
}
cv::Mat* Palmprint::GetOrigImg()
{
image_ = cv::imread(image_path_, CV_LOAD_IMAGE_COLOR);
if (!image_.data)
{
EDCC_Log("Read image failed!");
return NULL;
}
return &image_;
}
cv::Mat* Palmprint::GetSpecImg(const cv::Size &img_size, bool is_gray)
{
Mat *origin_image = GetOrigImg();
CHECK_POINTER_NULL_RETURN(origin_image, NULL);
resize(*origin_image, *origin_image, img_size);
if (is_gray)
{
cvtColor(*origin_image, *origin_image, CV_BGR2GRAY);
}
return origin_image;
}
} // namespace edcc
| 21.953846 | 70 | 0.662929 | freelandy |
6408655df552782992203108b8559ebebc7aa3ba | 2,892 | cpp | C++ | examples/ImportCplusplus/example_cplusplus.cpp | cndabai/jerryscript | 865788c26af9ad65cdd19b58c15a59ffd85d36ca | [
"Apache-2.0"
] | 15 | 2018-01-11T11:43:58.000Z | 2021-08-19T18:34:43.000Z | examples/ImportCplusplus/example_cplusplus.cpp | cndabai/jerryscript | 865788c26af9ad65cdd19b58c15a59ffd85d36ca | [
"Apache-2.0"
] | 2 | 2018-12-06T09:44:16.000Z | 2019-05-29T07:53:52.000Z | examples/ImportCplusplus/example_cplusplus.cpp | cndabai/jerryscript | 865788c26af9ad65cdd19b58c15a59ffd85d36ca | [
"Apache-2.0"
] | 19 | 2018-01-09T05:04:15.000Z | 2022-02-06T14:29:23.000Z | #include <rtthread.h>
#include <jerry_util.h>
class Rectangle
{
private:
int length;
int width;
public:
Rectangle(int length,int width);
int getSize();
int getLength();
int getWidth();
};
Rectangle::Rectangle(int length,int width)
{
this->length = length;
this->width = width;
}
int Rectangle::getSize()
{
return (this->length * this->width);
}
int Rectangle::getLength()
{
return this->length;
}
int Rectangle::getWidth()
{
return this->width;
}
void rectangle_free_callback(void *native_p)
{
Rectangle* rect = (Rectangle*)native_p;
delete(rect);
}
const static jerry_object_native_info_t rectangle_info =
{
rectangle_free_callback
};
DECLARE_HANDLER(getSize)
{
void *native_pointer = RT_NULL;
jerry_get_object_native_pointer(this_value,&native_pointer,RT_NULL);
if(native_pointer)
{
Rectangle* rectangle = (Rectangle*)native_pointer;
jerry_value_t js_size = jerry_create_number(rectangle->getSize());
return js_size;
}
return jerry_create_undefined();
}
DECLARE_HANDLER(getLength)
{
void *native_pointer = RT_NULL;
jerry_get_object_native_pointer(this_value,&native_pointer,RT_NULL);
if(native_pointer)
{
Rectangle* rectangle = (Rectangle*)native_pointer;
jerry_value_t js_length = jerry_create_number(rectangle->getLength());
return js_length;
}
return jerry_create_undefined();
}
DECLARE_HANDLER(getWidth)
{
void *native_pointer = RT_NULL;
jerry_get_object_native_pointer(this_value,&native_pointer,RT_NULL);
if(native_pointer)
{
Rectangle* rectangle = (Rectangle*)native_pointer;
jerry_value_t js_width = jerry_create_number(rectangle->getWidth());
return js_width;
}
return jerry_create_undefined();
}
DECLARE_HANDLER(rectangle)
{
if(args_cnt !=2 || !jerry_value_is_number(args[0]) || !jerry_value_is_number(args[1]))
return jerry_create_undefined();
jerry_value_t js_rect = jerry_create_object();
Rectangle* rectangle = new Rectangle(jerry_get_number_value(args[0]),jerry_get_number_value(args[1]));
jerry_set_object_native_pointer(js_rect, rectangle,&rectangle_info);
jerry_value_t js_length = jerry_create_number(rectangle->getLength());
jerry_value_t js_width = jerry_create_number(rectangle->getWidth());
js_set_property(js_rect,"length",js_length);
js_set_property(js_rect,"width",js_width);
jerry_release_value(js_length);
jerry_release_value(js_width);
REGISTER_METHOD(js_rect,getSize);
REGISTER_METHOD(js_rect,getLength);
REGISTER_METHOD(js_rect,getWidth);
return js_rect;
}
extern "C"
{
int js_example_rect_init(jerry_value_t obj)
{
REGISTER_METHOD(obj, rectangle);
return 0;
}
}
| 22.952381 | 106 | 0.689488 | cndabai |
640e3fae3077933df14bd8ae1372c028c700919d | 4,494 | hpp | C++ | src/mongocxx/options/create_collection.hpp | CURG-old/mongo-cxx-driver | 06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/options/create_collection.hpp | CURG-old/mongo-cxx-driver | 06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/options/create_collection.hpp | CURG-old/mongo-cxx-driver | 06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8 | [
"Apache-2.0"
] | null | null | null | // Copyright 2015 MongoDB 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.
#pragma once
#include <bsoncxx/document/view_or_value.hpp>
#include <bsoncxx/stdx/optional.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/validation_criteria.hpp>
#include <mongocxx/config/prelude.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
namespace options {
///
/// Class representing the optional arguments to a MongoDB createCollection command
///
class MONGOCXX_API create_collection {
public:
///
/// To create a capped collection, specify true.
///
/// @note If you specify true, you must also set a maximum size using the size() method.
///
/// @param capped
/// Whether or not this collection will be capped.
///
/// @see https://docs.mongodb.org/manual/reference/glossary/#term-capped-collection
///
void capped(bool capped);
///
/// Specify false to disable the automatic creation of an index on the _id field.
///
/// @note For replica sets, all collections must have autoIndexId set to true.
///
/// @param auto_index_id
/// Whether or not this collection will automatically generate an index on _id.
///
void auto_index_id(bool auto_index_id);
///
/// A maximum size, in bytes, for a capped collection.
///
/// @note Once a capped collection reaches its maximum size, MongoDB removes older
/// documents to make space for new documents.
///
/// @note Size is required for capped collections and ignored for other collections.
///
/// @param max_size
/// Maximum size, in bytes, of this collection (if capped)
///
void size(int max_size);
///
/// The maximum number of documents allowed in the capped collection.
///
/// @note The size limit takes precedence over this limit. If a capped collection reaches
/// the size limit before it reaches the maximum number of documents, MongoDB removes
/// old documents.
///
/// @param max_documents
/// Maximum number of documents allowed in the collection (if capped)
///
void max(int max_documents);
///
/// Specify configuration to the storage on a per-collection basis.
///
/// @note This option is currently only available with the WiredTiger storage engine.
///
/// @param storage_engine_options
/// Configuration options specific to the storage engine.
///
void storage_engine(bsoncxx::document::view_or_value storage_engine_opts);
///
/// When true, disables the power of 2 sizes allocation for the collection.
///
/// @see: https://docs.mongodb.org/manual/reference/method/db.createCollection/
///
/// @param no_padding
/// When true, disables power of 2 sizing for this collection.
///
void no_padding(bool no_padding);
///
/// Specify validation criteria for this collection.
///
/// @param validation
/// Validation criteria for this collection.
///
/// @see https://docs.mongodb.org/manual/core/document-validation/
///
void validation_criteria(class validation_criteria validation);
///
/// Return a bson document representing the options set on this object.
///
/// @return Options, as a document.
///
bsoncxx::document::value to_document() const;
MONGOCXX_INLINE operator bsoncxx::document::value() const;
private:
stdx::optional<bool> _capped;
stdx::optional<bool> _auto_index_id;
stdx::optional<int> _max_size;
stdx::optional<int> _max_documents;
stdx::optional<bsoncxx::document::view_or_value> _storage_engine_opts;
stdx::optional<bool> _no_padding;
stdx::optional<class validation_criteria> _validation;
};
MONGOCXX_INLINE create_collection::operator bsoncxx::document::value() const {
return to_document();
}
} // namespace options
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
#include <mongocxx/config/postlude.hpp>
| 32.565217 | 93 | 0.686693 | CURG-old |
64136454b94dd7c69233cb34d03df94d458a72c1 | 1,091 | hpp | C++ | libs/core/include/fcppt/iterator/category_at_least.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/iterator/category_at_least.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/iterator/category_at_least.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_ITERATOR_CATEGORY_AT_LEAST_HPP_INCLUDED
#define FCPPT_ITERATOR_CATEGORY_AT_LEAST_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace iterator
{
/**
\brief Checks if an iterator category includes another.
\ingroup fcpptiterator
Checks if \a Category models \a CategoryRef. For example,
if \a Category is <code>std::bidirectional_iterator_category</code>
and \a CategoryRef is <code>std::forward_iterator_category</code>, then
the value is true.
\tparam Category Must be one of the <code>std::</code> iterator category classes.
\tparam CategoryRef Must be one of the <code>std::</code> iterator category classes.
*/
template<
typename Category,
typename CategoryRef
>
using category_at_least
=
std::is_base_of<
CategoryRef,
Category
>;
}
}
#endif
| 22.265306 | 84 | 0.764436 | pmiddend |
641451a54d55098e6da21543e7f98cd270e715af | 733 | cpp | C++ | src/Paradajz.cpp | pavle0903/Singidunum-OOP2-Projekat | 5050b8e6e47cc9c7a6a2fb6ff9d4199839b1d2a0 | [
"FTL",
"libtiff",
"libpng-2.0",
"BSD-3-Clause"
] | null | null | null | src/Paradajz.cpp | pavle0903/Singidunum-OOP2-Projekat | 5050b8e6e47cc9c7a6a2fb6ff9d4199839b1d2a0 | [
"FTL",
"libtiff",
"libpng-2.0",
"BSD-3-Clause"
] | null | null | null | src/Paradajz.cpp | pavle0903/Singidunum-OOP2-Projekat | 5050b8e6e47cc9c7a6a2fb6ff9d4199839b1d2a0 | [
"FTL",
"libtiff",
"libpng-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Paradajz.cpp
*
* Created on: 11.09.2020.
* Author: Pavle
*/
#include "Paradajz.h"
Paradajz::Paradajz(int width, int height, string sheetPath, SDL_Renderer *renderer) {
dest = new SDL_Rect();
dest->x = rand() % 400 + 100;
dest->y = rand() % 400 + 100;
dest->w = width;
dest->h = height;
this->width = width;
this->height = height;
src = new SDL_Rect();
src->x = 0;
src->y = 0;
src->w = width;
src->h = height;
SDL_Surface *surface = IMG_Load(sheetPath.c_str());
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
}
void Paradajz::draw(SDL_Renderer *renderer){
SDL_RenderCopy(renderer, texture, src, dest);
}
Paradajz::~Paradajz() {
delete src;
delete dest;
}
| 18.794872 | 85 | 0.656207 | pavle0903 |
6415b444a970976640583110e2a7e8a6f9a17cc5 | 24,495 | hpp | C++ | octree/include/pcl/octree/impl/octree_base.hpp | zhangxaochen/CuFusion | e8bab7a366b1f2c85a80b95093d195d9f0774c11 | [
"MIT"
] | 52 | 2017-09-05T13:31:44.000Z | 2022-03-14T08:48:29.000Z | octree/include/pcl/octree/impl/octree_base.hpp | GucciPrada/CuFusion | 522920bcf316d1ddf9732fc71fa457174168d2fb | [
"MIT"
] | 4 | 2018-05-17T22:45:35.000Z | 2020-02-01T21:46:42.000Z | octree/include/pcl/octree/impl/octree_base.hpp | GucciPrada/CuFusion | 522920bcf316d1ddf9732fc71fa457174168d2fb | [
"MIT"
] | 21 | 2015-07-27T13:00:36.000Z | 2022-01-17T08:18:41.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, 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.
*
* $Id: octree_base.hpp 7148 2012-09-14 23:08:00Z jkammerl $
*/
#ifndef PCL_OCTREE_BASE_HPP
#define PCL_OCTREE_BASE_HPP
#include <vector>
#include <pcl/impl/instantiate.hpp>
#include <pcl/point_types.h>
#include <pcl/octree/octree.h>
// maximum depth of octree as we are using "unsigned int" octree keys / bit masks
#define OCT_MAXTREEDEPTH ( sizeof(size_t) * 8 )
namespace pcl
{
namespace octree
{
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT>
OctreeBase<DataT, LeafContainerT, BranchContainerT>::OctreeBase () :
leafCount_ (0),
branchCount_ (1),
objectCount_ (0),
rootNode_ (new BranchNode ()),
maxObjsPerLeaf_(0),
depthMask_ (0),
octreeDepth_ (0),
maxKey_ (),
branchNodePool_ (),
leafNodePool_ ()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT>
OctreeBase<DataT, LeafContainerT, BranchContainerT>::~OctreeBase ()
{
// deallocate tree structure
deleteTree ();
delete (rootNode_);
poolCleanUp ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::setMaxVoxelIndex (unsigned int maxVoxelIndex_arg)
{
unsigned int treeDepth;
assert (maxVoxelIndex_arg>0);
// tree depth == amount of bits of maxVoxels
treeDepth = std::max ((std::min (static_cast<unsigned int> (OCT_MAXTREEDEPTH),
static_cast<unsigned int> (std::ceil (Log2 (maxVoxelIndex_arg))))),
static_cast<unsigned int> (0));
// define depthMask_ by setting a single bit to 1 at bit position == tree depth
depthMask_ = (1 << (treeDepth - 1));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT>
void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::setTreeDepth (unsigned int depth_arg)
{
assert(depth_arg>0);
// set octree depth
octreeDepth_ = depth_arg;
// define depthMask_ by setting a single bit to 1 at bit position == tree depth
depthMask_ = (1 << (depth_arg - 1));
// define max. keys
maxKey_.x = maxKey_.y = maxKey_.z = (1 << depth_arg) - 1;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::addData (unsigned int idxX_arg, unsigned int idxY_arg,
unsigned int idxZ_arg, const DataT& data_arg)
{
// generate key
OctreeKey key (idxX_arg, idxY_arg, idxZ_arg);
// add data_arg to octree
addData (key, data_arg);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT>bool
OctreeBase<DataT, LeafContainerT, BranchContainerT>::getData (unsigned int idxX_arg, unsigned int idxY_arg,
unsigned int idxZ_arg, DataT& data_arg) const
{
// generate key
OctreeKey key (idxX_arg, idxY_arg, idxZ_arg);
// search for leaf at key
LeafNode* leaf = findLeaf (key);
if (leaf)
{
// if successful, decode data to data_arg
leaf->getData (data_arg);
}
// returns true on success
return (leaf != 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> bool
OctreeBase<DataT, LeafContainerT, BranchContainerT>::existLeaf (unsigned int idxX_arg, unsigned int idxY_arg,
unsigned int idxZ_arg) const
{
// generate key
OctreeKey key (idxX_arg, idxY_arg, idxZ_arg);
// check if key exist in octree
return ( existLeaf (key));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::removeLeaf (unsigned int idxX_arg, unsigned int idxY_arg,
unsigned int idxZ_arg)
{
// generate key
OctreeKey key (idxX_arg, idxY_arg, idxZ_arg);
// check if key exist in octree
deleteLeafRecursive (key, depthMask_, rootNode_);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::deleteTree (bool freeMemory_arg )
{
if (rootNode_)
{
// reset octree
deleteBranch (*rootNode_);
leafCount_ = 0;
branchCount_ = 1;
objectCount_ = 0;
}
// delete node pool
if (freeMemory_arg)
poolCleanUp ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::serializeTree (std::vector<char>& binaryTreeOut_arg)
{
// serialization requires fixed octree depth
// maxObjsPerLeaf_>0 indicates a dynamic octree structure
assert (!maxObjsPerLeaf_);
OctreeKey newKey;
// clear binary vector
binaryTreeOut_arg.clear ();
binaryTreeOut_arg.reserve (this->branchCount_);
serializeTreeRecursive (rootNode_, newKey, &binaryTreeOut_arg, 0 );
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::serializeTree (std::vector<char>& binaryTreeOut_arg, std::vector<DataT>& dataVector_arg)
{
// serialization requires fixed octree depth
// maxObjsPerLeaf_>0 indicates a dynamic octree structure
assert (!maxObjsPerLeaf_);
OctreeKey newKey;
// clear output vectors
binaryTreeOut_arg.clear ();
dataVector_arg.clear ();
dataVector_arg.reserve (this->objectCount_);
binaryTreeOut_arg.reserve (this->branchCount_);
serializeTreeRecursive (rootNode_, newKey, &binaryTreeOut_arg, &dataVector_arg );
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::serializeLeafs (std::vector<DataT>& dataVector_arg)
{
// serialization requires fixed octree depth
// maxObjsPerLeaf_>0 indicates a dynamic octree structure
assert (!maxObjsPerLeaf_);
OctreeKey newKey;
// clear output vector
dataVector_arg.clear ();
dataVector_arg.reserve(this->objectCount_);
serializeTreeRecursive (rootNode_, newKey, 0, &dataVector_arg );
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::deserializeTree (std::vector<char>& binaryTreeIn_arg)
{
// serialization requires fixed octree depth
// maxObjsPerLeaf_>0 indicates a dynamic octree structure
assert (!maxObjsPerLeaf_);
OctreeKey newKey;
// free existing tree before tree rebuild
deleteTree ();
//iterator for binary tree structure vector
std::vector<char>::const_iterator binaryTreeVectorIterator = binaryTreeIn_arg.begin ();
std::vector<char>::const_iterator binaryTreeVectorIteratorEnd = binaryTreeIn_arg.end ();
deserializeTreeRecursive (rootNode_, depthMask_, newKey,
binaryTreeVectorIterator, binaryTreeVectorIteratorEnd, 0, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::deserializeTree (std::vector<char>& binaryTreeIn_arg,
std::vector<DataT>& dataVector_arg)
{
// serialization requires fixed octree depth
// maxObjsPerLeaf_>0 indicates a dynamic octree structure
assert (!maxObjsPerLeaf_);
OctreeKey newKey;
// set data iterator to first element
typename std::vector<DataT>::const_iterator dataVectorIterator = dataVector_arg.begin ();
// set data iterator to last element
typename std::vector<DataT>::const_iterator dataVectorEndIterator = dataVector_arg.end ();
// free existing tree before tree rebuild
deleteTree ();
//iterator for binary tree structure vector
std::vector<char>::const_iterator binaryTreeVectorIterator = binaryTreeIn_arg.begin ();
std::vector<char>::const_iterator binaryTreeVectorIteratorEnd = binaryTreeIn_arg.end ();
deserializeTreeRecursive (rootNode_, depthMask_, newKey,
binaryTreeVectorIterator, binaryTreeVectorIteratorEnd, &dataVectorIterator, &dataVectorEndIterator);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void OctreeBase<
DataT, LeafContainerT, BranchContainerT>::createLeafRecursive (
const OctreeKey& key_arg, unsigned int depthMask_arg,
const DataT& data_arg, BranchNode* branch_arg, LeafNode*& returnLeaf_arg)
{
// index to branch child
unsigned char childIdx;
// find branch child from key
childIdx = key_arg.getChildIdxWithDepthMask(depthMask_arg);
// add data to branch node container
branch_arg->setData (data_arg);
OctreeNode* childNode = (*branch_arg)[childIdx];
if (!childNode)
{
if ((!maxObjsPerLeaf_) && (depthMask_arg > 1)) {
// if required branch does not exist -> create it
BranchNode* childBranch;
createBranchChild (*branch_arg, childIdx, childBranch);
branchCount_++;
// recursively proceed with indexed child branch
createLeafRecursive (key_arg, depthMask_arg / 2, data_arg, childBranch, returnLeaf_arg);
} else {
// if leaf node at childIdx does not exist
createLeafChild (*branch_arg, childIdx, returnLeaf_arg);
leafCount_++;
}
} else {
// Node exists already
switch (childNode->getNodeType()) {
case BRANCH_NODE:
// recursively proceed with indexed child branch
createLeafRecursive (key_arg, depthMask_arg / 2, data_arg, static_cast<BranchNode*> (childNode), returnLeaf_arg);
break;
case LEAF_NODE:
LeafNode* childLeaf = static_cast<LeafNode*> (childNode);
returnLeaf_arg = childLeaf;
// get amount of objects in leaf container
size_t leafObjCount = childLeaf->getSize ();
if (! ( (!maxObjsPerLeaf_) || (!depthMask_arg) ) && (leafObjCount >= maxObjsPerLeaf_) )
{
// leaf node needs to be expanded
// copy leaf data
std::vector<DataT> leafData;
leafData.reserve(leafObjCount);
childLeaf->getData (leafData);
// delete current leaf node
deleteBranchChild(*branch_arg,childIdx);
leafCount_ --;
// create new branch node
BranchNode* childBranch;
createBranchChild (*branch_arg, childIdx, childBranch);
branchCount_ ++;
typename std::vector<DataT>::const_iterator lData = leafData.begin();
typename std::vector<DataT>::const_iterator lDataEnd = leafData.end();
// add data to new branch
OctreeKey dataKey;
while (lData!=lDataEnd) {
// get data object
const DataT& data = *lData;
++lData;
// generate new key for data object
if (this->genOctreeKeyForDataT(data, dataKey)) {
LeafNode* newLeaf;
createLeafRecursive (dataKey, depthMask_arg / 2, data, childBranch, newLeaf);
// add data to leaf
newLeaf->setData (data);
objectCount_++;
}
}
// and return new leaf node
createLeafRecursive (key_arg, depthMask_arg / 2, data_arg, childBranch, returnLeaf_arg);
// correct object counter
objectCount_ -= leafObjCount;
}
break;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::findLeafRecursive (
const OctreeKey& key_arg, unsigned int depthMask_arg, BranchNode* branch_arg, LeafNode*& result_arg) const
{
// index to branch child
unsigned char childIdx;
// find branch child from key
childIdx = key_arg.getChildIdxWithDepthMask(depthMask_arg);
OctreeNode* childNode = (*branch_arg)[childIdx];
if (childNode) {
switch (childNode->getNodeType()) {
case BRANCH_NODE:
// we have not reached maximum tree depth
BranchNode* childBranch;
childBranch = static_cast<BranchNode*> (childNode);
findLeafRecursive (key_arg, depthMask_arg / 2, childBranch, result_arg);
break;
case LEAF_NODE:
// return existing leaf node
LeafNode* childLeaf;
childLeaf = static_cast<LeafNode*> (childNode);
result_arg = childLeaf;
break;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> bool
OctreeBase<DataT, LeafContainerT, BranchContainerT>::deleteLeafRecursive (const OctreeKey& key_arg, unsigned int depthMask_arg,
BranchNode* branch_arg)
{
// index to branch child
unsigned char childIdx;
// indicates if branch is empty and can be safely removed
bool bNoChilds;
// find branch child from key
childIdx = key_arg.getChildIdxWithDepthMask(depthMask_arg);
OctreeNode* childNode = (*branch_arg)[childIdx];
if (childNode) {
switch (childNode->getNodeType()) {
case BRANCH_NODE:
BranchNode* childBranch;
childBranch = static_cast<BranchNode*> (childNode);
// recursively explore the indexed child branch
bNoChilds = deleteLeafRecursive (key_arg, depthMask_arg / 2, childBranch);
if (!bNoChilds)
{
// child branch does not own any sub-child nodes anymore -> delete child branch
deleteBranchChild(*branch_arg, childIdx);
branchCount_--;
}
break;
case LEAF_NODE:
// return existing leaf node
// our child is a leaf node -> delete it
deleteBranchChild (*branch_arg, childIdx);
leafCount_--;
break;
}
}
// check if current branch still owns childs
bNoChilds = false;
for (childIdx = 0; (!bNoChilds) && (childIdx < 8); childIdx++)
{
bNoChilds = branch_arg->hasChild(childIdx);
}
// return true if current branch can be deleted
return (bNoChilds);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void OctreeBase<
DataT, LeafContainerT, BranchContainerT>::serializeTreeRecursive (const BranchNode* branch_arg, OctreeKey& key_arg,
std::vector<char>* binaryTreeOut_arg,
typename std::vector<DataT>* dataVector_arg) const
{
// child iterator
unsigned char childIdx;
char nodeBitPattern;
// branch occupancy bit pattern
nodeBitPattern = getBranchBitPattern (*branch_arg);
// write bit pattern to output vector
if (binaryTreeOut_arg)
binaryTreeOut_arg->push_back (nodeBitPattern);
// iterate over all children
for (childIdx = 0; childIdx < 8; childIdx++)
{
// if child exist
if (branch_arg->hasChild(childIdx))
{
// add current branch voxel to key
key_arg.pushBranch(childIdx);
const OctreeNode *childNode = branch_arg->getChildPtr(childIdx);
switch (childNode->getNodeType ())
{
case BRANCH_NODE:
{
// recursively proceed with indexed child branch
serializeTreeRecursive (
static_cast<const BranchNode*> (childNode), key_arg,
binaryTreeOut_arg, dataVector_arg);
break;
}
case LEAF_NODE:
{
const LeafNode* childLeaf = static_cast<const LeafNode*> (childNode);
if (dataVector_arg)
childLeaf->getData (*dataVector_arg);
// we reached a leaf node -> execute serialization callback
serializeTreeCallback (*childLeaf, key_arg);
break;
}
default:
break;
}
// pop current branch voxel from key
key_arg.popBranch();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename DataT, typename LeafContainerT, typename BranchContainerT> void
OctreeBase<DataT, LeafContainerT, BranchContainerT>::deserializeTreeRecursive (BranchNode* branch_arg,
unsigned int depthMask_arg, OctreeKey& key_arg,
typename std::vector<char>::const_iterator& binaryTreeIT_arg,
typename std::vector<char>::const_iterator& binaryTreeIT_End_arg,
typename std::vector<DataT>::const_iterator* dataVectorIterator_arg,
typename std::vector<DataT>::const_iterator* dataVectorEndIterator_arg)
{
// child iterator
unsigned char childIdx;
char nodeBits;
if (binaryTreeIT_arg != binaryTreeIT_End_arg ) {
// read branch occupancy bit pattern from input vector
nodeBits = (*binaryTreeIT_arg);
binaryTreeIT_arg++;
// iterate over all children
for (childIdx = 0; childIdx < 8; childIdx++)
{
// if occupancy bit for childIdx is set..
if (nodeBits & (1 << childIdx))
{
// add current branch voxel to key
key_arg.pushBranch(childIdx);
if (depthMask_arg > 1)
{
// we have not reached maximum tree depth
BranchNode * newBranch;
// create new child branch
createBranchChild (*branch_arg, childIdx, newBranch);
branchCount_++;
// recursively proceed with new child branch
deserializeTreeRecursive (newBranch, depthMask_arg / 2, key_arg, binaryTreeIT_arg,binaryTreeIT_End_arg, dataVectorIterator_arg,
dataVectorEndIterator_arg);
}
else
{
// we reached leaf node level
LeafNode* childLeaf;
// create leaf node
createLeafChild (*branch_arg, childIdx, childLeaf);
OctreeKey dataKey;
bool bKeyBasedEncoding = false;
if (dataVectorIterator_arg
&& (*dataVectorIterator_arg != *dataVectorEndIterator_arg))
{
// add DataT objects to octree leaf as long as their key fit to voxel
while ( ( (*dataVectorIterator_arg)
!= (*dataVectorEndIterator_arg))
&& (this->genOctreeKeyForDataT (**dataVectorIterator_arg,
dataKey) && (dataKey == key_arg)))
{
childLeaf->setData (**dataVectorIterator_arg);
(*dataVectorIterator_arg)++;
bKeyBasedEncoding = true;
objectCount_++;
}
// add single DataT object to octree if key-based encoding is disabled
if (!bKeyBasedEncoding)
{
childLeaf->setData (**dataVectorIterator_arg);
(*dataVectorIterator_arg)++;
objectCount_++;
}
}
leafCount_++;
// execute deserialization callback
deserializeTreeCallback (*childLeaf, key_arg);
}
// pop current branch voxel from key
key_arg.popBranch();
}
}
}
}
}
}
#define PCL_INSTANTIATE_OctreeBase(T) template class PCL_EXPORTS pcl::octree::OctreeBase<T>;
#endif
| 37.976744 | 146 | 0.56387 | zhangxaochen |
6415d80a866fd64aabc7ebb9a78fe92d3675d2dc | 6,044 | cpp | C++ | src/chip-nrf52/timer.cpp | Testrigor123/cortex-demos | 1163db7f626de1420d5af4557de66713709ed136 | [
"Apache-2.0"
] | null | null | null | src/chip-nrf52/timer.cpp | Testrigor123/cortex-demos | 1163db7f626de1420d5af4557de66713709ed136 | [
"Apache-2.0"
] | null | null | null | src/chip-nrf52/timer.cpp | Testrigor123/cortex-demos | 1163db7f626de1420d5af4557de66713709ed136 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
Copyright 2018 Google LLC
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
https://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 "driver/timer.hpp"
#include "clk.h"
#include "cutils.h"
#include "memio.h"
#include "nrf52/clk.h"
#include "nrf52/peripheral.hpp"
#include "nrf52/periph_utils.hpp"
namespace driver {
namespace {
constexpr unsigned int kNumRTCEvents = 6;
void rtc0_irq_handler();
void rtc1_irq_handler();
void rtc2_irq_handler();
class RTC : public Timer, public nrf52::Peripheral {
public:
RTC(unsigned int id) : driver::Peripheral(periph::id_to_base(id), id, evt_handler_storage_, kNumRTCEvents) {}
void start() override {
if (!lfclk_started) {
clk_request(kLfclkSrc);
lfclk_started = 1;
}
trigger_task(Task::START);
}
void stop() override {
trigger_task(Task::STOP);
}
unsigned int get_rate() const override {
auto presc = raw_read32(base_ + kPrescalerOffset);
return kBaseRate / ((presc & 0xfff) + 1);
}
void set_prescaler(unsigned int presc) override {
// TODO: debug assert that the timer is stopped
raw_write32(base_ + kPrescalerOffset, presc - 1);
}
void enable_interrupts(uint32_t mask) override {
if (!irq_handler_configured_) {
void (*handler)(void) = nullptr;
switch (irq_n_) {
case 11:
handler = rtc0_irq_handler;
break;
case 17:
handler = rtc1_irq_handler;
break;
case 36:
handler = rtc2_irq_handler;
break;
}
if (handler) {
set_irq_handler(handler);
irq_handler_configured_ = true;
}
}
raw_write32(base_ + kIntenSetOffset, mask);
raw_write32(base_ + kEvtenSetOffset, mask);
enable_irq();
}
void disable_interrupts(uint32_t mask) override {
raw_write32(base_ + kIntenClrOffset, mask);
}
void enable_tick_interrupt() override {
enable_interrupts(kIntenTick);
}
private:
enum Task {
START,
STOP
};
static constexpr auto kIntenSetOffset = 0x304;
static constexpr auto kIntenClrOffset = 0x308;
static constexpr auto kEvtenSetOffset = 0x344;
static constexpr auto kEvtenClrOffset = 0x348;
static constexpr auto kPrescalerOffset = 0x508;
static constexpr auto kBaseRate = 32768;
static constexpr uint32_t kIntenTick = (1 << 0);
static bool lfclk_started;
// TODO: make this configurable
static constexpr auto kLfclkSrc = NRF52_LFCLK_XTAL;
evt_handler_func_t evt_handler_storage_[kNumRTCEvents];
bool irq_handler_configured_ = false;
};
bool RTC::lfclk_started = 0;
RTC rtc0{11};
RTC rtc1{17};
RTC rtc2{36};
void rtc0_irq_handler() {
rtc0.handle_events();
}
void rtc1_irq_handler() {
rtc1.handle_events();
}
void rtc2_irq_handler() {
rtc2.handle_events();
}
constexpr unsigned int kNumTimerEvents = 6;
class TimerCounter : public Timer, public nrf52::Peripheral {
public:
enum Task {
START,
STOP,
COUNT,
CLEAR,
SHUTDOWN,
};
TimerCounter(unsigned int id) : driver::Peripheral(periph::id_to_base(id), id, evt_handler_storage_, kNumRTCEvents) {}
void start() override {
trigger_task(Task::START);
}
void stop() override {
trigger_task(Task::STOP);
}
unsigned int get_rate() const override {
unsigned int presc = raw_read32(base_ + kPrescalerOffset);
return kInputRate / (1 << presc);
}
void set_prescaler(unsigned int presc) override {
unsigned int real_presc = MIN(presc, kMaxPrescaler);
raw_write32(base_ + kPrescalerOffset, real_presc);
}
void enable_tick_interrupt() override {}
private:
static constexpr unsigned kMaxPrescaler = 9;
static constexpr unsigned int kInputRate = 16 * 1000 * 1000;
static constexpr uint32_t kPrescalerOffset = 0x510;
evt_handler_func_t evt_handler_storage_[kNumTimerEvents];
};
TimerCounter timer0{8};
TimerCounter timer1{9};
TimerCounter timer2{10};
TimerCounter timer3{26};
TimerCounter timer4{27};
} // namespace
Timer* Timer::get_by_id(ID id) {
Timer* ret = nullptr;
switch (id) {
case ID::RTC0:
ret = &rtc0;
break;
case ID::RTC1:
ret = &rtc1;
break;
case ID::RTC2:
ret = &rtc2;
break;
case ID::TIMER0:
ret = &timer0;
break;
case ID::TIMER1:
ret = &timer1;
break;
case ID::TIMER2:
ret = &timer2;
break;
case ID::TIMER3:
ret = &timer3;
break;
case ID::TIMER4:
ret = &timer4;
break;
default:
break;
};
return ret;
}
} // namespace driver
| 26.393013 | 126 | 0.55824 | Testrigor123 |
6420a2f57921be42d19183700617aa42894a364a | 228,424 | hpp | C++ | Autogenerated/Bindings/Cpp/lib3mf_implicit.hpp | alexanderoster/lib3mf | 30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05 | [
"BSD-2-Clause"
] | 171 | 2015-04-30T21:54:02.000Z | 2022-03-13T13:33:59.000Z | Autogenerated/Bindings/Cpp/lib3mf_implicit.hpp | alexanderoster/lib3mf | 30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05 | [
"BSD-2-Clause"
] | 190 | 2015-07-21T22:15:54.000Z | 2022-03-30T15:48:37.000Z | Autogenerated/Bindings/Cpp/lib3mf_implicit.hpp | alexanderoster/lib3mf | 30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05 | [
"BSD-2-Clause"
] | 80 | 2015-04-30T22:15:54.000Z | 2022-03-09T12:38:49.000Z | /*++
Copyright (C) 2019 3MF Consortium (Original Author)
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 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.
This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0.
Abstract: This is an autogenerated C++-Header file in order to allow an easy
use of the 3MF Library
Interface version: 2.2.0
*/
#ifndef __LIB3MF_CPPHEADER_IMPLICIT_CPP
#define __LIB3MF_CPPHEADER_IMPLICIT_CPP
#include "lib3mf_types.hpp"
#include "lib3mf_abi.hpp"
#ifdef _WIN32
#include <windows.h>
#else // _WIN32
#include <dlfcn.h>
#endif // _WIN32
#include <string>
#include <memory>
#include <vector>
#include <exception>
namespace Lib3MF {
/*************************************************************************************************************************
Forward Declaration of all classes
**************************************************************************************************************************/
class CWrapper;
class CBase;
class CWriter;
class CReader;
class CPackagePart;
class CResource;
class CResourceIterator;
class CSliceStackIterator;
class CObjectIterator;
class CMeshObjectIterator;
class CComponentsObjectIterator;
class CTexture2DIterator;
class CBaseMaterialGroupIterator;
class CColorGroupIterator;
class CTexture2DGroupIterator;
class CCompositeMaterialsIterator;
class CMultiPropertyGroupIterator;
class CMetaData;
class CMetaDataGroup;
class CObject;
class CMeshObject;
class CBeamLattice;
class CComponent;
class CComponentsObject;
class CBeamSet;
class CBaseMaterialGroup;
class CColorGroup;
class CTexture2DGroup;
class CCompositeMaterials;
class CMultiPropertyGroup;
class CAttachment;
class CTexture2D;
class CBuildItem;
class CBuildItemIterator;
class CSlice;
class CSliceStack;
class CConsumer;
class CAccessRight;
class CContentEncryptionParams;
class CResourceData;
class CResourceDataGroup;
class CKeyStore;
class CModel;
/*************************************************************************************************************************
Declaration of deprecated class types
**************************************************************************************************************************/
typedef CWrapper CLib3MFWrapper;
typedef CBase CLib3MFBase;
typedef CWriter CLib3MFWriter;
typedef CReader CLib3MFReader;
typedef CPackagePart CLib3MFPackagePart;
typedef CResource CLib3MFResource;
typedef CResourceIterator CLib3MFResourceIterator;
typedef CSliceStackIterator CLib3MFSliceStackIterator;
typedef CObjectIterator CLib3MFObjectIterator;
typedef CMeshObjectIterator CLib3MFMeshObjectIterator;
typedef CComponentsObjectIterator CLib3MFComponentsObjectIterator;
typedef CTexture2DIterator CLib3MFTexture2DIterator;
typedef CBaseMaterialGroupIterator CLib3MFBaseMaterialGroupIterator;
typedef CColorGroupIterator CLib3MFColorGroupIterator;
typedef CTexture2DGroupIterator CLib3MFTexture2DGroupIterator;
typedef CCompositeMaterialsIterator CLib3MFCompositeMaterialsIterator;
typedef CMultiPropertyGroupIterator CLib3MFMultiPropertyGroupIterator;
typedef CMetaData CLib3MFMetaData;
typedef CMetaDataGroup CLib3MFMetaDataGroup;
typedef CObject CLib3MFObject;
typedef CMeshObject CLib3MFMeshObject;
typedef CBeamLattice CLib3MFBeamLattice;
typedef CComponent CLib3MFComponent;
typedef CComponentsObject CLib3MFComponentsObject;
typedef CBeamSet CLib3MFBeamSet;
typedef CBaseMaterialGroup CLib3MFBaseMaterialGroup;
typedef CColorGroup CLib3MFColorGroup;
typedef CTexture2DGroup CLib3MFTexture2DGroup;
typedef CCompositeMaterials CLib3MFCompositeMaterials;
typedef CMultiPropertyGroup CLib3MFMultiPropertyGroup;
typedef CAttachment CLib3MFAttachment;
typedef CTexture2D CLib3MFTexture2D;
typedef CBuildItem CLib3MFBuildItem;
typedef CBuildItemIterator CLib3MFBuildItemIterator;
typedef CSlice CLib3MFSlice;
typedef CSliceStack CLib3MFSliceStack;
typedef CConsumer CLib3MFConsumer;
typedef CAccessRight CLib3MFAccessRight;
typedef CContentEncryptionParams CLib3MFContentEncryptionParams;
typedef CResourceData CLib3MFResourceData;
typedef CResourceDataGroup CLib3MFResourceDataGroup;
typedef CKeyStore CLib3MFKeyStore;
typedef CModel CLib3MFModel;
/*************************************************************************************************************************
Declaration of shared pointer types
**************************************************************************************************************************/
typedef std::shared_ptr<CWrapper> PWrapper;
typedef std::shared_ptr<CBase> PBase;
typedef std::shared_ptr<CWriter> PWriter;
typedef std::shared_ptr<CReader> PReader;
typedef std::shared_ptr<CPackagePart> PPackagePart;
typedef std::shared_ptr<CResource> PResource;
typedef std::shared_ptr<CResourceIterator> PResourceIterator;
typedef std::shared_ptr<CSliceStackIterator> PSliceStackIterator;
typedef std::shared_ptr<CObjectIterator> PObjectIterator;
typedef std::shared_ptr<CMeshObjectIterator> PMeshObjectIterator;
typedef std::shared_ptr<CComponentsObjectIterator> PComponentsObjectIterator;
typedef std::shared_ptr<CTexture2DIterator> PTexture2DIterator;
typedef std::shared_ptr<CBaseMaterialGroupIterator> PBaseMaterialGroupIterator;
typedef std::shared_ptr<CColorGroupIterator> PColorGroupIterator;
typedef std::shared_ptr<CTexture2DGroupIterator> PTexture2DGroupIterator;
typedef std::shared_ptr<CCompositeMaterialsIterator> PCompositeMaterialsIterator;
typedef std::shared_ptr<CMultiPropertyGroupIterator> PMultiPropertyGroupIterator;
typedef std::shared_ptr<CMetaData> PMetaData;
typedef std::shared_ptr<CMetaDataGroup> PMetaDataGroup;
typedef std::shared_ptr<CObject> PObject;
typedef std::shared_ptr<CMeshObject> PMeshObject;
typedef std::shared_ptr<CBeamLattice> PBeamLattice;
typedef std::shared_ptr<CComponent> PComponent;
typedef std::shared_ptr<CComponentsObject> PComponentsObject;
typedef std::shared_ptr<CBeamSet> PBeamSet;
typedef std::shared_ptr<CBaseMaterialGroup> PBaseMaterialGroup;
typedef std::shared_ptr<CColorGroup> PColorGroup;
typedef std::shared_ptr<CTexture2DGroup> PTexture2DGroup;
typedef std::shared_ptr<CCompositeMaterials> PCompositeMaterials;
typedef std::shared_ptr<CMultiPropertyGroup> PMultiPropertyGroup;
typedef std::shared_ptr<CAttachment> PAttachment;
typedef std::shared_ptr<CTexture2D> PTexture2D;
typedef std::shared_ptr<CBuildItem> PBuildItem;
typedef std::shared_ptr<CBuildItemIterator> PBuildItemIterator;
typedef std::shared_ptr<CSlice> PSlice;
typedef std::shared_ptr<CSliceStack> PSliceStack;
typedef std::shared_ptr<CConsumer> PConsumer;
typedef std::shared_ptr<CAccessRight> PAccessRight;
typedef std::shared_ptr<CContentEncryptionParams> PContentEncryptionParams;
typedef std::shared_ptr<CResourceData> PResourceData;
typedef std::shared_ptr<CResourceDataGroup> PResourceDataGroup;
typedef std::shared_ptr<CKeyStore> PKeyStore;
typedef std::shared_ptr<CModel> PModel;
/*************************************************************************************************************************
Declaration of deprecated shared pointer types
**************************************************************************************************************************/
typedef PWrapper PLib3MFWrapper;
typedef PBase PLib3MFBase;
typedef PWriter PLib3MFWriter;
typedef PReader PLib3MFReader;
typedef PPackagePart PLib3MFPackagePart;
typedef PResource PLib3MFResource;
typedef PResourceIterator PLib3MFResourceIterator;
typedef PSliceStackIterator PLib3MFSliceStackIterator;
typedef PObjectIterator PLib3MFObjectIterator;
typedef PMeshObjectIterator PLib3MFMeshObjectIterator;
typedef PComponentsObjectIterator PLib3MFComponentsObjectIterator;
typedef PTexture2DIterator PLib3MFTexture2DIterator;
typedef PBaseMaterialGroupIterator PLib3MFBaseMaterialGroupIterator;
typedef PColorGroupIterator PLib3MFColorGroupIterator;
typedef PTexture2DGroupIterator PLib3MFTexture2DGroupIterator;
typedef PCompositeMaterialsIterator PLib3MFCompositeMaterialsIterator;
typedef PMultiPropertyGroupIterator PLib3MFMultiPropertyGroupIterator;
typedef PMetaData PLib3MFMetaData;
typedef PMetaDataGroup PLib3MFMetaDataGroup;
typedef PObject PLib3MFObject;
typedef PMeshObject PLib3MFMeshObject;
typedef PBeamLattice PLib3MFBeamLattice;
typedef PComponent PLib3MFComponent;
typedef PComponentsObject PLib3MFComponentsObject;
typedef PBeamSet PLib3MFBeamSet;
typedef PBaseMaterialGroup PLib3MFBaseMaterialGroup;
typedef PColorGroup PLib3MFColorGroup;
typedef PTexture2DGroup PLib3MFTexture2DGroup;
typedef PCompositeMaterials PLib3MFCompositeMaterials;
typedef PMultiPropertyGroup PLib3MFMultiPropertyGroup;
typedef PAttachment PLib3MFAttachment;
typedef PTexture2D PLib3MFTexture2D;
typedef PBuildItem PLib3MFBuildItem;
typedef PBuildItemIterator PLib3MFBuildItemIterator;
typedef PSlice PLib3MFSlice;
typedef PSliceStack PLib3MFSliceStack;
typedef PConsumer PLib3MFConsumer;
typedef PAccessRight PLib3MFAccessRight;
typedef PContentEncryptionParams PLib3MFContentEncryptionParams;
typedef PResourceData PLib3MFResourceData;
typedef PResourceDataGroup PLib3MFResourceDataGroup;
typedef PKeyStore PLib3MFKeyStore;
typedef PModel PLib3MFModel;
/*************************************************************************************************************************
Class ELib3MFException
**************************************************************************************************************************/
class ELib3MFException : public std::exception {
protected:
/**
* Error code for the Exception.
*/
Lib3MFResult m_errorCode;
/**
* Error message for the Exception.
*/
std::string m_errorMessage;
public:
/**
* Exception Constructor.
*/
ELib3MFException(Lib3MFResult errorCode, const std::string & sErrorMessage)
: m_errorMessage("Lib3MF Error " + std::to_string(errorCode) + " (" + sErrorMessage + ")")
{
m_errorCode = errorCode;
}
/**
* Returns error code
*/
Lib3MFResult getErrorCode() const noexcept
{
return m_errorCode;
}
/**
* Returns error message
*/
const char* what() const noexcept
{
return m_errorMessage.c_str();
}
};
/*************************************************************************************************************************
Class CInputVector
**************************************************************************************************************************/
template <typename T>
class CInputVector {
private:
const T* m_data;
size_t m_size;
public:
CInputVector(const std::vector<T>& vec)
: m_data( vec.data() ), m_size( vec.size() )
{
}
CInputVector(const T* in_data, size_t in_size)
: m_data( in_data ), m_size(in_size )
{
}
const T* data() const
{
return m_data;
}
size_t size() const
{
return m_size;
}
};
// declare deprecated class name
template<typename T>
using CLib3MFInputVector = CInputVector<T>;
/*************************************************************************************************************************
Class CWrapper
**************************************************************************************************************************/
class CWrapper {
public:
CWrapper()
{
}
~CWrapper()
{
}
static inline PWrapper loadLibrary()
{
return std::make_shared<CWrapper>();
}
inline void CheckError(CBase * pBaseClass, Lib3MFResult nResult);
inline void GetLibraryVersion(Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro);
inline bool GetPrereleaseInformation(std::string & sPrereleaseInfo);
inline bool GetBuildInformation(std::string & sBuildInformation);
inline void GetSpecificationVersion(const std::string & sSpecificationURL, bool & bIsSupported, Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro);
inline PModel CreateModel();
inline void Release(CBase * pInstance);
inline void Acquire(CBase * pInstance);
inline void SetJournal(const std::string & sJournalPath);
inline bool GetLastError(CBase * pInstance, std::string & sLastErrorString);
inline Lib3MF_pvoid GetSymbolLookupMethod();
inline void RetrieveProgressMessage(const eProgressIdentifier eTheProgressIdentifier, std::string & sProgressMessage);
inline sColor RGBAToColor(const Lib3MF_uint8 nRed, const Lib3MF_uint8 nGreen, const Lib3MF_uint8 nBlue, const Lib3MF_uint8 nAlpha);
inline sColor FloatRGBAToColor(const Lib3MF_single fRed, const Lib3MF_single fGreen, const Lib3MF_single fBlue, const Lib3MF_single fAlpha);
inline void ColorToRGBA(const sColor & TheColor, Lib3MF_uint8 & nRed, Lib3MF_uint8 & nGreen, Lib3MF_uint8 & nBlue, Lib3MF_uint8 & nAlpha);
inline void ColorToFloatRGBA(const sColor & TheColor, Lib3MF_single & fRed, Lib3MF_single & fGreen, Lib3MF_single & fBlue, Lib3MF_single & fAlpha);
inline sTransform GetIdentityTransform();
inline sTransform GetUniformScaleTransform(const Lib3MF_single fFactor);
inline sTransform GetScaleTransform(const Lib3MF_single fFactorX, const Lib3MF_single fFactorY, const Lib3MF_single fFactorZ);
inline sTransform GetTranslationTransform(const Lib3MF_single fVectorX, const Lib3MF_single fVectorY, const Lib3MF_single fVectorZ);
private:
Lib3MFResult checkBinaryVersion()
{
Lib3MF_uint32 nMajor, nMinor, nMicro;
GetLibraryVersion(nMajor, nMinor, nMicro);
if ( (nMajor != LIB3MF_VERSION_MAJOR) || (nMinor < LIB3MF_VERSION_MINOR) ) {
return LIB3MF_ERROR_INCOMPATIBLEBINARYVERSION;
}
return LIB3MF_SUCCESS;
}
friend class CBase;
friend class CWriter;
friend class CReader;
friend class CPackagePart;
friend class CResource;
friend class CResourceIterator;
friend class CSliceStackIterator;
friend class CObjectIterator;
friend class CMeshObjectIterator;
friend class CComponentsObjectIterator;
friend class CTexture2DIterator;
friend class CBaseMaterialGroupIterator;
friend class CColorGroupIterator;
friend class CTexture2DGroupIterator;
friend class CCompositeMaterialsIterator;
friend class CMultiPropertyGroupIterator;
friend class CMetaData;
friend class CMetaDataGroup;
friend class CObject;
friend class CMeshObject;
friend class CBeamLattice;
friend class CComponent;
friend class CComponentsObject;
friend class CBeamSet;
friend class CBaseMaterialGroup;
friend class CColorGroup;
friend class CTexture2DGroup;
friend class CCompositeMaterials;
friend class CMultiPropertyGroup;
friend class CAttachment;
friend class CTexture2D;
friend class CBuildItem;
friend class CBuildItemIterator;
friend class CSlice;
friend class CSliceStack;
friend class CConsumer;
friend class CAccessRight;
friend class CContentEncryptionParams;
friend class CResourceData;
friend class CResourceDataGroup;
friend class CKeyStore;
friend class CModel;
};
/*************************************************************************************************************************
Class CBase
**************************************************************************************************************************/
class CBase {
public:
protected:
/* Wrapper Object that created the class. */
CWrapper * m_pWrapper;
/* Handle to Instance in library*/
Lib3MFHandle m_pHandle;
/* Checks for an Error code and raises Exceptions */
void CheckError(Lib3MFResult nResult)
{
if (m_pWrapper != nullptr)
m_pWrapper->CheckError(this, nResult);
}
public:
/**
* CBase::CBase - Constructor for Base class.
*/
CBase(CWrapper * pWrapper, Lib3MFHandle pHandle)
: m_pWrapper(pWrapper), m_pHandle(pHandle)
{
}
/**
* CBase::~CBase - Destructor for Base class.
*/
virtual ~CBase()
{
if (m_pWrapper != nullptr)
m_pWrapper->Release(this);
m_pWrapper = nullptr;
}
/**
* CBase::GetHandle - Returns handle to instance.
*/
Lib3MFHandle GetHandle()
{
return m_pHandle;
}
friend class CWrapper;
};
/*************************************************************************************************************************
Class CWriter
**************************************************************************************************************************/
class CWriter : public CBase {
public:
/**
* CWriter::CWriter - Constructor for Writer class.
*/
CWriter(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline void WriteToFile(const std::string & sFilename);
inline Lib3MF_uint64 GetStreamSize();
inline void WriteToBuffer(std::vector<Lib3MF_uint8> & BufferBuffer);
inline void WriteToCallback(const WriteCallback pTheWriteCallback, const SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData);
inline void SetProgressCallback(const ProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData);
inline Lib3MF_uint32 GetDecimalPrecision();
inline void SetDecimalPrecision(const Lib3MF_uint32 nDecimalPrecision);
inline void SetStrictModeActive(const bool bStrictModeActive);
inline bool GetStrictModeActive();
inline std::string GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode);
inline Lib3MF_uint32 GetWarningCount();
inline void AddKeyWrappingCallback(const std::string & sConsumerID, const KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData);
inline void SetContentEncryptionCallback(const ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData);
};
/*************************************************************************************************************************
Class CReader
**************************************************************************************************************************/
class CReader : public CBase {
public:
/**
* CReader::CReader - Constructor for Reader class.
*/
CReader(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline void ReadFromFile(const std::string & sFilename);
inline void ReadFromBuffer(const CInputVector<Lib3MF_uint8> & BufferBuffer);
inline void ReadFromCallback(const ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData);
inline void SetProgressCallback(const ProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData);
inline void AddRelationToRead(const std::string & sRelationShipType);
inline void RemoveRelationToRead(const std::string & sRelationShipType);
inline void SetStrictModeActive(const bool bStrictModeActive);
inline bool GetStrictModeActive();
inline std::string GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode);
inline Lib3MF_uint32 GetWarningCount();
inline void AddKeyWrappingCallback(const std::string & sConsumerID, const KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData);
inline void SetContentEncryptionCallback(const ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData);
};
/*************************************************************************************************************************
Class CPackagePart
**************************************************************************************************************************/
class CPackagePart : public CBase {
public:
/**
* CPackagePart::CPackagePart - Constructor for PackagePart class.
*/
CPackagePart(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline std::string GetPath();
inline void SetPath(const std::string & sPath);
};
/*************************************************************************************************************************
Class CResource
**************************************************************************************************************************/
class CResource : public CBase {
public:
/**
* CResource::CResource - Constructor for Resource class.
*/
CResource(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetResourceID();
inline Lib3MF_uint32 GetUniqueResourceID();
inline PPackagePart PackagePart();
inline void SetPackagePart(CPackagePart * pPackagePart);
inline Lib3MF_uint32 GetModelResourceID();
};
/*************************************************************************************************************************
Class CResourceIterator
**************************************************************************************************************************/
class CResourceIterator : public CBase {
public:
/**
* CResourceIterator::CResourceIterator - Constructor for ResourceIterator class.
*/
CResourceIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline bool MoveNext();
inline bool MovePrevious();
inline PResource GetCurrent();
inline PResourceIterator Clone();
inline Lib3MF_uint64 Count();
};
/*************************************************************************************************************************
Class CSliceStackIterator
**************************************************************************************************************************/
class CSliceStackIterator : public CResourceIterator {
public:
/**
* CSliceStackIterator::CSliceStackIterator - Constructor for SliceStackIterator class.
*/
CSliceStackIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PSliceStack GetCurrentSliceStack();
};
/*************************************************************************************************************************
Class CObjectIterator
**************************************************************************************************************************/
class CObjectIterator : public CResourceIterator {
public:
/**
* CObjectIterator::CObjectIterator - Constructor for ObjectIterator class.
*/
CObjectIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PObject GetCurrentObject();
};
/*************************************************************************************************************************
Class CMeshObjectIterator
**************************************************************************************************************************/
class CMeshObjectIterator : public CResourceIterator {
public:
/**
* CMeshObjectIterator::CMeshObjectIterator - Constructor for MeshObjectIterator class.
*/
CMeshObjectIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PMeshObject GetCurrentMeshObject();
};
/*************************************************************************************************************************
Class CComponentsObjectIterator
**************************************************************************************************************************/
class CComponentsObjectIterator : public CResourceIterator {
public:
/**
* CComponentsObjectIterator::CComponentsObjectIterator - Constructor for ComponentsObjectIterator class.
*/
CComponentsObjectIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PComponentsObject GetCurrentComponentsObject();
};
/*************************************************************************************************************************
Class CTexture2DIterator
**************************************************************************************************************************/
class CTexture2DIterator : public CResourceIterator {
public:
/**
* CTexture2DIterator::CTexture2DIterator - Constructor for Texture2DIterator class.
*/
CTexture2DIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PTexture2D GetCurrentTexture2D();
};
/*************************************************************************************************************************
Class CBaseMaterialGroupIterator
**************************************************************************************************************************/
class CBaseMaterialGroupIterator : public CResourceIterator {
public:
/**
* CBaseMaterialGroupIterator::CBaseMaterialGroupIterator - Constructor for BaseMaterialGroupIterator class.
*/
CBaseMaterialGroupIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PBaseMaterialGroup GetCurrentBaseMaterialGroup();
};
/*************************************************************************************************************************
Class CColorGroupIterator
**************************************************************************************************************************/
class CColorGroupIterator : public CResourceIterator {
public:
/**
* CColorGroupIterator::CColorGroupIterator - Constructor for ColorGroupIterator class.
*/
CColorGroupIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PColorGroup GetCurrentColorGroup();
};
/*************************************************************************************************************************
Class CTexture2DGroupIterator
**************************************************************************************************************************/
class CTexture2DGroupIterator : public CResourceIterator {
public:
/**
* CTexture2DGroupIterator::CTexture2DGroupIterator - Constructor for Texture2DGroupIterator class.
*/
CTexture2DGroupIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PTexture2DGroup GetCurrentTexture2DGroup();
};
/*************************************************************************************************************************
Class CCompositeMaterialsIterator
**************************************************************************************************************************/
class CCompositeMaterialsIterator : public CResourceIterator {
public:
/**
* CCompositeMaterialsIterator::CCompositeMaterialsIterator - Constructor for CompositeMaterialsIterator class.
*/
CCompositeMaterialsIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PCompositeMaterials GetCurrentCompositeMaterials();
};
/*************************************************************************************************************************
Class CMultiPropertyGroupIterator
**************************************************************************************************************************/
class CMultiPropertyGroupIterator : public CResourceIterator {
public:
/**
* CMultiPropertyGroupIterator::CMultiPropertyGroupIterator - Constructor for MultiPropertyGroupIterator class.
*/
CMultiPropertyGroupIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResourceIterator(pWrapper, pHandle)
{
}
inline PMultiPropertyGroup GetCurrentMultiPropertyGroup();
};
/*************************************************************************************************************************
Class CMetaData
**************************************************************************************************************************/
class CMetaData : public CBase {
public:
/**
* CMetaData::CMetaData - Constructor for MetaData class.
*/
CMetaData(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline std::string GetNameSpace();
inline void SetNameSpace(const std::string & sNameSpace);
inline std::string GetName();
inline void SetName(const std::string & sName);
inline std::string GetKey();
inline bool GetMustPreserve();
inline void SetMustPreserve(const bool bMustPreserve);
inline std::string GetType();
inline void SetType(const std::string & sType);
inline std::string GetValue();
inline void SetValue(const std::string & sValue);
};
/*************************************************************************************************************************
Class CMetaDataGroup
**************************************************************************************************************************/
class CMetaDataGroup : public CBase {
public:
/**
* CMetaDataGroup::CMetaDataGroup - Constructor for MetaDataGroup class.
*/
CMetaDataGroup(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetMetaDataCount();
inline PMetaData GetMetaData(const Lib3MF_uint32 nIndex);
inline PMetaData GetMetaDataByKey(const std::string & sNameSpace, const std::string & sName);
inline void RemoveMetaDataByIndex(const Lib3MF_uint32 nIndex);
inline void RemoveMetaData(CMetaData * pTheMetaData);
inline PMetaData AddMetaData(const std::string & sNameSpace, const std::string & sName, const std::string & sValue, const std::string & sType, const bool bMustPreserve);
};
/*************************************************************************************************************************
Class CObject
**************************************************************************************************************************/
class CObject : public CResource {
public:
/**
* CObject::CObject - Constructor for Object class.
*/
CObject(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline eObjectType GetType();
inline void SetType(const eObjectType eObjectType);
inline std::string GetName();
inline void SetName(const std::string & sName);
inline std::string GetPartNumber();
inline void SetPartNumber(const std::string & sPartNumber);
inline bool IsMeshObject();
inline bool IsComponentsObject();
inline bool IsValid();
inline void SetAttachmentAsThumbnail(CAttachment * pAttachment);
inline PAttachment GetThumbnailAttachment();
inline void ClearThumbnailAttachment();
inline sBox GetOutbox();
inline std::string GetUUID(bool & bHasUUID);
inline void SetUUID(const std::string & sUUID);
inline PMetaDataGroup GetMetaDataGroup();
inline void SetSlicesMeshResolution(const eSlicesMeshResolution eMeshResolution);
inline eSlicesMeshResolution GetSlicesMeshResolution();
inline bool HasSlices(const bool bRecursive);
inline void ClearSliceStack();
inline PSliceStack GetSliceStack();
inline void AssignSliceStack(CSliceStack * pSliceStackInstance);
};
/*************************************************************************************************************************
Class CMeshObject
**************************************************************************************************************************/
class CMeshObject : public CObject {
public:
/**
* CMeshObject::CMeshObject - Constructor for MeshObject class.
*/
CMeshObject(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CObject(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetVertexCount();
inline Lib3MF_uint32 GetTriangleCount();
inline sPosition GetVertex(const Lib3MF_uint32 nIndex);
inline void SetVertex(const Lib3MF_uint32 nIndex, const sPosition & Coordinates);
inline Lib3MF_uint32 AddVertex(const sPosition & Coordinates);
inline void GetVertices(std::vector<sPosition> & VerticesBuffer);
inline sTriangle GetTriangle(const Lib3MF_uint32 nIndex);
inline void SetTriangle(const Lib3MF_uint32 nIndex, const sTriangle & Indices);
inline Lib3MF_uint32 AddTriangle(const sTriangle & Indices);
inline void GetTriangleIndices(std::vector<sTriangle> & IndicesBuffer);
inline void SetObjectLevelProperty(const Lib3MF_uint32 nUniqueResourceID, const Lib3MF_uint32 nPropertyID);
inline bool GetObjectLevelProperty(Lib3MF_uint32 & nUniqueResourceID, Lib3MF_uint32 & nPropertyID);
inline void SetTriangleProperties(const Lib3MF_uint32 nIndex, const sTriangleProperties & Properties);
inline void GetTriangleProperties(const Lib3MF_uint32 nIndex, sTriangleProperties & Property);
inline void SetAllTriangleProperties(const CInputVector<sTriangleProperties> & PropertiesArrayBuffer);
inline void GetAllTriangleProperties(std::vector<sTriangleProperties> & PropertiesArrayBuffer);
inline void ClearAllProperties();
inline void SetGeometry(const CInputVector<sPosition> & VerticesBuffer, const CInputVector<sTriangle> & IndicesBuffer);
inline bool IsManifoldAndOriented();
inline PBeamLattice BeamLattice();
};
/*************************************************************************************************************************
Class CBeamLattice
**************************************************************************************************************************/
class CBeamLattice : public CBase {
public:
/**
* CBeamLattice::CBeamLattice - Constructor for BeamLattice class.
*/
CBeamLattice(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline Lib3MF_double GetMinLength();
inline void SetMinLength(const Lib3MF_double dMinLength);
inline void GetClipping(eBeamLatticeClipMode & eClipMode, Lib3MF_uint32 & nUniqueResourceID);
inline void SetClipping(const eBeamLatticeClipMode eClipMode, const Lib3MF_uint32 nUniqueResourceID);
inline bool GetRepresentation(Lib3MF_uint32 & nUniqueResourceID);
inline void SetRepresentation(const Lib3MF_uint32 nUniqueResourceID);
inline void GetBallOptions(eBeamLatticeBallMode & eBallMode, Lib3MF_double & dBallRadius);
inline void SetBallOptions(const eBeamLatticeBallMode eBallMode, const Lib3MF_double dBallRadius);
inline Lib3MF_uint32 GetBeamCount();
inline sBeam GetBeam(const Lib3MF_uint32 nIndex);
inline Lib3MF_uint32 AddBeam(const sBeam & BeamInfo);
inline void SetBeam(const Lib3MF_uint32 nIndex, const sBeam & BeamInfo);
inline void SetBeams(const CInputVector<sBeam> & BeamInfoBuffer);
inline void GetBeams(std::vector<sBeam> & BeamInfoBuffer);
inline Lib3MF_uint32 GetBallCount();
inline sBall GetBall(const Lib3MF_uint32 nIndex);
inline Lib3MF_uint32 AddBall(const sBall & BallInfo);
inline void SetBall(const Lib3MF_uint32 nIndex, const sBall & BallInfo);
inline void SetBalls(const CInputVector<sBall> & BallInfoBuffer);
inline void GetBalls(std::vector<sBall> & BallInfoBuffer);
inline Lib3MF_uint32 GetBeamSetCount();
inline PBeamSet AddBeamSet();
inline PBeamSet GetBeamSet(const Lib3MF_uint32 nIndex);
};
/*************************************************************************************************************************
Class CComponent
**************************************************************************************************************************/
class CComponent : public CBase {
public:
/**
* CComponent::CComponent - Constructor for Component class.
*/
CComponent(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline PObject GetObjectResource();
inline Lib3MF_uint32 GetObjectResourceID();
inline std::string GetUUID(bool & bHasUUID);
inline void SetUUID(const std::string & sUUID);
inline bool HasTransform();
inline sTransform GetTransform();
inline void SetTransform(const sTransform & Transform);
};
/*************************************************************************************************************************
Class CComponentsObject
**************************************************************************************************************************/
class CComponentsObject : public CObject {
public:
/**
* CComponentsObject::CComponentsObject - Constructor for ComponentsObject class.
*/
CComponentsObject(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CObject(pWrapper, pHandle)
{
}
inline PComponent AddComponent(CObject * pObjectResource, const sTransform & Transform);
inline PComponent GetComponent(const Lib3MF_uint32 nIndex);
inline Lib3MF_uint32 GetComponentCount();
};
/*************************************************************************************************************************
Class CBeamSet
**************************************************************************************************************************/
class CBeamSet : public CBase {
public:
/**
* CBeamSet::CBeamSet - Constructor for BeamSet class.
*/
CBeamSet(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline void SetName(const std::string & sName);
inline std::string GetName();
inline void SetIdentifier(const std::string & sIdentifier);
inline std::string GetIdentifier();
inline Lib3MF_uint32 GetReferenceCount();
inline void SetReferences(const CInputVector<Lib3MF_uint32> & ReferencesBuffer);
inline void GetReferences(std::vector<Lib3MF_uint32> & ReferencesBuffer);
inline Lib3MF_uint32 GetBallReferenceCount();
inline void SetBallReferences(const CInputVector<Lib3MF_uint32> & BallReferencesBuffer);
inline void GetBallReferences(std::vector<Lib3MF_uint32> & BallReferencesBuffer);
};
/*************************************************************************************************************************
Class CBaseMaterialGroup
**************************************************************************************************************************/
class CBaseMaterialGroup : public CResource {
public:
/**
* CBaseMaterialGroup::CBaseMaterialGroup - Constructor for BaseMaterialGroup class.
*/
CBaseMaterialGroup(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetCount();
inline void GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer);
inline Lib3MF_uint32 AddMaterial(const std::string & sName, const sColor & DisplayColor);
inline void RemoveMaterial(const Lib3MF_uint32 nPropertyID);
inline std::string GetName(const Lib3MF_uint32 nPropertyID);
inline void SetName(const Lib3MF_uint32 nPropertyID, const std::string & sName);
inline void SetDisplayColor(const Lib3MF_uint32 nPropertyID, const sColor & TheColor);
inline sColor GetDisplayColor(const Lib3MF_uint32 nPropertyID);
};
/*************************************************************************************************************************
Class CColorGroup
**************************************************************************************************************************/
class CColorGroup : public CResource {
public:
/**
* CColorGroup::CColorGroup - Constructor for ColorGroup class.
*/
CColorGroup(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetCount();
inline void GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer);
inline Lib3MF_uint32 AddColor(const sColor & TheColor);
inline void RemoveColor(const Lib3MF_uint32 nPropertyID);
inline void SetColor(const Lib3MF_uint32 nPropertyID, const sColor & TheColor);
inline sColor GetColor(const Lib3MF_uint32 nPropertyID);
};
/*************************************************************************************************************************
Class CTexture2DGroup
**************************************************************************************************************************/
class CTexture2DGroup : public CResource {
public:
/**
* CTexture2DGroup::CTexture2DGroup - Constructor for Texture2DGroup class.
*/
CTexture2DGroup(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetCount();
inline void GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer);
inline Lib3MF_uint32 AddTex2Coord(const sTex2Coord & UVCoordinate);
inline sTex2Coord GetTex2Coord(const Lib3MF_uint32 nPropertyID);
inline void RemoveTex2Coord(const Lib3MF_uint32 nPropertyID);
inline PTexture2D GetTexture2D();
};
/*************************************************************************************************************************
Class CCompositeMaterials
**************************************************************************************************************************/
class CCompositeMaterials : public CResource {
public:
/**
* CCompositeMaterials::CCompositeMaterials - Constructor for CompositeMaterials class.
*/
CCompositeMaterials(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetCount();
inline void GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer);
inline PBaseMaterialGroup GetBaseMaterialGroup();
inline Lib3MF_uint32 AddComposite(const CInputVector<sCompositeConstituent> & CompositeBuffer);
inline void RemoveComposite(const Lib3MF_uint32 nPropertyID);
inline void GetComposite(const Lib3MF_uint32 nPropertyID, std::vector<sCompositeConstituent> & CompositeBuffer);
};
/*************************************************************************************************************************
Class CMultiPropertyGroup
**************************************************************************************************************************/
class CMultiPropertyGroup : public CResource {
public:
/**
* CMultiPropertyGroup::CMultiPropertyGroup - Constructor for MultiPropertyGroup class.
*/
CMultiPropertyGroup(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline Lib3MF_uint32 GetCount();
inline void GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer);
inline Lib3MF_uint32 AddMultiProperty(const CInputVector<Lib3MF_uint32> & PropertyIDsBuffer);
inline void SetMultiProperty(const Lib3MF_uint32 nPropertyID, const CInputVector<Lib3MF_uint32> & PropertyIDsBuffer);
inline void GetMultiProperty(const Lib3MF_uint32 nPropertyID, std::vector<Lib3MF_uint32> & PropertyIDsBuffer);
inline void RemoveMultiProperty(const Lib3MF_uint32 nPropertyID);
inline Lib3MF_uint32 GetLayerCount();
inline Lib3MF_uint32 AddLayer(const sMultiPropertyLayer & TheLayer);
inline sMultiPropertyLayer GetLayer(const Lib3MF_uint32 nLayerIndex);
inline void RemoveLayer(const Lib3MF_uint32 nLayerIndex);
};
/*************************************************************************************************************************
Class CAttachment
**************************************************************************************************************************/
class CAttachment : public CBase {
public:
/**
* CAttachment::CAttachment - Constructor for Attachment class.
*/
CAttachment(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline std::string GetPath();
inline void SetPath(const std::string & sPath);
inline PPackagePart PackagePart();
inline std::string GetRelationShipType();
inline void SetRelationShipType(const std::string & sPath);
inline void WriteToFile(const std::string & sFileName);
inline void ReadFromFile(const std::string & sFileName);
inline void ReadFromCallback(const ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData);
inline Lib3MF_uint64 GetStreamSize();
inline void WriteToBuffer(std::vector<Lib3MF_uint8> & BufferBuffer);
inline void ReadFromBuffer(const CInputVector<Lib3MF_uint8> & BufferBuffer);
};
/*************************************************************************************************************************
Class CTexture2D
**************************************************************************************************************************/
class CTexture2D : public CResource {
public:
/**
* CTexture2D::CTexture2D - Constructor for Texture2D class.
*/
CTexture2D(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline PAttachment GetAttachment();
inline void SetAttachment(CAttachment * pAttachment);
inline eTextureType GetContentType();
inline void SetContentType(const eTextureType eContentType);
inline void GetTileStyleUV(eTextureTileStyle & eTileStyleU, eTextureTileStyle & eTileStyleV);
inline void SetTileStyleUV(const eTextureTileStyle eTileStyleU, const eTextureTileStyle eTileStyleV);
inline eTextureFilter GetFilter();
inline void SetFilter(const eTextureFilter eFilter);
};
/*************************************************************************************************************************
Class CBuildItem
**************************************************************************************************************************/
class CBuildItem : public CBase {
public:
/**
* CBuildItem::CBuildItem - Constructor for BuildItem class.
*/
CBuildItem(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline PObject GetObjectResource();
inline std::string GetUUID(bool & bHasUUID);
inline void SetUUID(const std::string & sUUID);
inline Lib3MF_uint32 GetObjectResourceID();
inline bool HasObjectTransform();
inline sTransform GetObjectTransform();
inline void SetObjectTransform(const sTransform & Transform);
inline std::string GetPartNumber();
inline void SetPartNumber(const std::string & sSetPartnumber);
inline PMetaDataGroup GetMetaDataGroup();
inline sBox GetOutbox();
};
/*************************************************************************************************************************
Class CBuildItemIterator
**************************************************************************************************************************/
class CBuildItemIterator : public CBase {
public:
/**
* CBuildItemIterator::CBuildItemIterator - Constructor for BuildItemIterator class.
*/
CBuildItemIterator(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline bool MoveNext();
inline bool MovePrevious();
inline PBuildItem GetCurrent();
inline PBuildItemIterator Clone();
inline Lib3MF_uint64 Count();
};
/*************************************************************************************************************************
Class CSlice
**************************************************************************************************************************/
class CSlice : public CBase {
public:
/**
* CSlice::CSlice - Constructor for Slice class.
*/
CSlice(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline void SetVertices(const CInputVector<sPosition2D> & VerticesBuffer);
inline void GetVertices(std::vector<sPosition2D> & VerticesBuffer);
inline Lib3MF_uint64 GetVertexCount();
inline Lib3MF_uint64 AddPolygon(const CInputVector<Lib3MF_uint32> & IndicesBuffer);
inline Lib3MF_uint64 GetPolygonCount();
inline void SetPolygonIndices(const Lib3MF_uint64 nIndex, const CInputVector<Lib3MF_uint32> & IndicesBuffer);
inline void GetPolygonIndices(const Lib3MF_uint64 nIndex, std::vector<Lib3MF_uint32> & IndicesBuffer);
inline Lib3MF_uint64 GetPolygonIndexCount(const Lib3MF_uint64 nIndex);
inline Lib3MF_double GetZTop();
};
/*************************************************************************************************************************
Class CSliceStack
**************************************************************************************************************************/
class CSliceStack : public CResource {
public:
/**
* CSliceStack::CSliceStack - Constructor for SliceStack class.
*/
CSliceStack(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CResource(pWrapper, pHandle)
{
}
inline Lib3MF_double GetBottomZ();
inline Lib3MF_uint64 GetSliceCount();
inline PSlice GetSlice(const Lib3MF_uint64 nSliceIndex);
inline PSlice AddSlice(const Lib3MF_double dZTop);
inline Lib3MF_uint64 GetSliceRefCount();
inline void AddSliceStackReference(CSliceStack * pTheSliceStack);
inline PSliceStack GetSliceStackReference(const Lib3MF_uint64 nSliceRefIndex);
inline void CollapseSliceReferences();
inline void SetOwnPath(const std::string & sPath);
inline std::string GetOwnPath();
};
/*************************************************************************************************************************
Class CConsumer
**************************************************************************************************************************/
class CConsumer : public CBase {
public:
/**
* CConsumer::CConsumer - Constructor for Consumer class.
*/
CConsumer(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline std::string GetConsumerID();
inline std::string GetKeyID();
inline std::string GetKeyValue();
};
/*************************************************************************************************************************
Class CAccessRight
**************************************************************************************************************************/
class CAccessRight : public CBase {
public:
/**
* CAccessRight::CAccessRight - Constructor for AccessRight class.
*/
CAccessRight(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline PConsumer GetConsumer();
inline eWrappingAlgorithm GetWrappingAlgorithm();
inline eMgfAlgorithm GetMgfAlgorithm();
inline eDigestMethod GetDigestMethod();
};
/*************************************************************************************************************************
Class CContentEncryptionParams
**************************************************************************************************************************/
class CContentEncryptionParams : public CBase {
public:
/**
* CContentEncryptionParams::CContentEncryptionParams - Constructor for ContentEncryptionParams class.
*/
CContentEncryptionParams(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline eEncryptionAlgorithm GetEncryptionAlgorithm();
inline void GetKey(std::vector<Lib3MF_uint8> & ByteDataBuffer);
inline void GetInitializationVector(std::vector<Lib3MF_uint8> & ByteDataBuffer);
inline void GetAuthenticationTag(std::vector<Lib3MF_uint8> & ByteDataBuffer);
inline void SetAuthenticationTag(const CInputVector<Lib3MF_uint8> & ByteDataBuffer);
inline void GetAdditionalAuthenticationData(std::vector<Lib3MF_uint8> & ByteDataBuffer);
inline Lib3MF_uint64 GetDescriptor();
inline std::string GetKeyUUID();
};
/*************************************************************************************************************************
Class CResourceData
**************************************************************************************************************************/
class CResourceData : public CBase {
public:
/**
* CResourceData::CResourceData - Constructor for ResourceData class.
*/
CResourceData(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline PPackagePart GetPath();
inline eEncryptionAlgorithm GetEncryptionAlgorithm();
inline eCompression GetCompression();
inline void GetAdditionalAuthenticationData(std::vector<Lib3MF_uint8> & ByteDataBuffer);
};
/*************************************************************************************************************************
Class CResourceDataGroup
**************************************************************************************************************************/
class CResourceDataGroup : public CBase {
public:
/**
* CResourceDataGroup::CResourceDataGroup - Constructor for ResourceDataGroup class.
*/
CResourceDataGroup(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline std::string GetKeyUUID();
inline PAccessRight AddAccessRight(CConsumer * pConsumer, const eWrappingAlgorithm eWrappingAlgorithm, const eMgfAlgorithm eMgfAlgorithm, const eDigestMethod eDigestMethod);
inline PAccessRight FindAccessRightByConsumer(CConsumer * pConsumer);
inline void RemoveAccessRight(CConsumer * pConsumer);
};
/*************************************************************************************************************************
Class CKeyStore
**************************************************************************************************************************/
class CKeyStore : public CBase {
public:
/**
* CKeyStore::CKeyStore - Constructor for KeyStore class.
*/
CKeyStore(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline PConsumer AddConsumer(const std::string & sConsumerID, const std::string & sKeyID, const std::string & sKeyValue);
inline Lib3MF_uint64 GetConsumerCount();
inline PConsumer GetConsumer(const Lib3MF_uint64 nConsumerIndex);
inline void RemoveConsumer(CConsumer * pConsumer);
inline PConsumer FindConsumer(const std::string & sConsumerID);
inline Lib3MF_uint64 GetResourceDataGroupCount();
inline PResourceDataGroup AddResourceDataGroup();
inline PResourceDataGroup GetResourceDataGroup(const Lib3MF_uint64 nResourceDataIndex);
inline void RemoveResourceDataGroup(CResourceDataGroup * pResourceDataGroup);
inline PResourceDataGroup FindResourceDataGroup(CPackagePart * pPartPath);
inline PResourceData AddResourceData(CResourceDataGroup * pResourceDataGroup, CPackagePart * pPartPath, const eEncryptionAlgorithm eAlgorithm, const eCompression eCompression, const CInputVector<Lib3MF_uint8> & AdditionalAuthenticationDataBuffer);
inline void RemoveResourceData(CResourceData * pResourceData);
inline PResourceData FindResourceData(CPackagePart * pResourcePath);
inline Lib3MF_uint64 GetResourceDataCount();
inline PResourceData GetResourceData(const Lib3MF_uint64 nResourceDataIndex);
inline std::string GetUUID(bool & bHasUUID);
inline void SetUUID(const std::string & sUUID);
};
/*************************************************************************************************************************
Class CModel
**************************************************************************************************************************/
class CModel : public CBase {
public:
/**
* CModel::CModel - Constructor for Model class.
*/
CModel(CWrapper* pWrapper, Lib3MFHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline PPackagePart RootModelPart();
inline PPackagePart FindOrCreatePackagePart(const std::string & sAbsolutePath);
inline void SetUnit(const eModelUnit eUnit);
inline eModelUnit GetUnit();
inline std::string GetLanguage();
inline void SetLanguage(const std::string & sLanguage);
inline PWriter QueryWriter(const std::string & sWriterClass);
inline PReader QueryReader(const std::string & sReaderClass);
inline PTexture2D GetTexture2DByID(const Lib3MF_uint32 nUniqueResourceID);
inline ePropertyType GetPropertyTypeByID(const Lib3MF_uint32 nUniqueResourceID);
inline PBaseMaterialGroup GetBaseMaterialGroupByID(const Lib3MF_uint32 nUniqueResourceID);
inline PTexture2DGroup GetTexture2DGroupByID(const Lib3MF_uint32 nUniqueResourceID);
inline PCompositeMaterials GetCompositeMaterialsByID(const Lib3MF_uint32 nUniqueResourceID);
inline PMultiPropertyGroup GetMultiPropertyGroupByID(const Lib3MF_uint32 nUniqueResourceID);
inline PMeshObject GetMeshObjectByID(const Lib3MF_uint32 nUniqueResourceID);
inline PComponentsObject GetComponentsObjectByID(const Lib3MF_uint32 nUniqueResourceID);
inline PColorGroup GetColorGroupByID(const Lib3MF_uint32 nUniqueResourceID);
inline PSliceStack GetSliceStackByID(const Lib3MF_uint32 nUniqueResourceID);
inline std::string GetBuildUUID(bool & bHasUUID);
inline void SetBuildUUID(const std::string & sUUID);
inline PBuildItemIterator GetBuildItems();
inline sBox GetOutbox();
inline PResourceIterator GetResources();
inline PObjectIterator GetObjects();
inline PMeshObjectIterator GetMeshObjects();
inline PComponentsObjectIterator GetComponentsObjects();
inline PTexture2DIterator GetTexture2Ds();
inline PBaseMaterialGroupIterator GetBaseMaterialGroups();
inline PColorGroupIterator GetColorGroups();
inline PTexture2DGroupIterator GetTexture2DGroups();
inline PCompositeMaterialsIterator GetCompositeMaterials();
inline PMultiPropertyGroupIterator GetMultiPropertyGroups();
inline PSliceStackIterator GetSliceStacks();
inline PModel MergeToModel();
inline PMeshObject AddMeshObject();
inline PComponentsObject AddComponentsObject();
inline PSliceStack AddSliceStack(const Lib3MF_double dZBottom);
inline PTexture2D AddTexture2DFromAttachment(CAttachment * pTextureAttachment);
inline PBaseMaterialGroup AddBaseMaterialGroup();
inline PColorGroup AddColorGroup();
inline PTexture2DGroup AddTexture2DGroup(CTexture2D * pTexture2DInstance);
inline PCompositeMaterials AddCompositeMaterials(CBaseMaterialGroup * pBaseMaterialGroupInstance);
inline PMultiPropertyGroup AddMultiPropertyGroup();
inline PBuildItem AddBuildItem(CObject * pObject, const sTransform & Transform);
inline void RemoveBuildItem(CBuildItem * pBuildItemInstance);
inline PMetaDataGroup GetMetaDataGroup();
inline PAttachment AddAttachment(const std::string & sURI, const std::string & sRelationShipType);
inline void RemoveAttachment(CAttachment * pAttachmentInstance);
inline PAttachment GetAttachment(const Lib3MF_uint32 nIndex);
inline PAttachment FindAttachment(const std::string & sURI);
inline Lib3MF_uint32 GetAttachmentCount();
inline bool HasPackageThumbnailAttachment();
inline PAttachment CreatePackageThumbnailAttachment();
inline PAttachment GetPackageThumbnailAttachment();
inline void RemovePackageThumbnailAttachment();
inline void AddCustomContentType(const std::string & sExtension, const std::string & sContentType);
inline void RemoveCustomContentType(const std::string & sExtension);
inline void SetRandomNumberCallback(const RandomNumberCallback pTheCallback, const Lib3MF_pvoid pUserData);
inline PKeyStore GetKeyStore();
};
/**
* CWrapper::GetLibraryVersion - retrieves the binary version of this library.
* @param[out] nMajor - returns the major version of this library
* @param[out] nMinor - returns the minor version of this library
* @param[out] nMicro - returns the micro version of this library
*/
inline void CWrapper::GetLibraryVersion(Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro)
{
CheckError(nullptr,lib3mf_getlibraryversion(&nMajor, &nMinor, &nMicro));
}
/**
* CWrapper::GetPrereleaseInformation - retrieves prerelease information of this library.
* @return Does the library provide prerelease version?
* @param[out] sPrereleaseInfo - retrieves prerelease information of this library.
*/
inline bool CWrapper::GetPrereleaseInformation(std::string & sPrereleaseInfo)
{
bool resultHasPrereleaseInfo = 0;
Lib3MF_uint32 bytesNeededPrereleaseInfo = 0;
Lib3MF_uint32 bytesWrittenPrereleaseInfo = 0;
CheckError(nullptr,lib3mf_getprereleaseinformation(&resultHasPrereleaseInfo, 0, &bytesNeededPrereleaseInfo, nullptr));
std::vector<char> bufferPrereleaseInfo(bytesNeededPrereleaseInfo);
CheckError(nullptr,lib3mf_getprereleaseinformation(&resultHasPrereleaseInfo, bytesNeededPrereleaseInfo, &bytesWrittenPrereleaseInfo, &bufferPrereleaseInfo[0]));
sPrereleaseInfo = std::string(&bufferPrereleaseInfo[0]);
return resultHasPrereleaseInfo;
}
/**
* CWrapper::GetBuildInformation - retrieves build information of this library.
* @return Does the library provide build version?
* @param[out] sBuildInformation - retrieves build information of this library.
*/
inline bool CWrapper::GetBuildInformation(std::string & sBuildInformation)
{
bool resultHasBuildInfo = 0;
Lib3MF_uint32 bytesNeededBuildInformation = 0;
Lib3MF_uint32 bytesWrittenBuildInformation = 0;
CheckError(nullptr,lib3mf_getbuildinformation(&resultHasBuildInfo, 0, &bytesNeededBuildInformation, nullptr));
std::vector<char> bufferBuildInformation(bytesNeededBuildInformation);
CheckError(nullptr,lib3mf_getbuildinformation(&resultHasBuildInfo, bytesNeededBuildInformation, &bytesWrittenBuildInformation, &bufferBuildInformation[0]));
sBuildInformation = std::string(&bufferBuildInformation[0]);
return resultHasBuildInfo;
}
/**
* CWrapper::GetSpecificationVersion - retrieves whether a specification is supported, and if so, which version.
* @param[in] sSpecificationURL - URL of extension to check
* @param[out] bIsSupported - returns whether this specification is supported
* @param[out] nMajor - returns the major version of the extension (if IsSupported)
* @param[out] nMinor - returns the minor version of the extension (if IsSupported)
* @param[out] nMicro - returns the micro version of the extension (if IsSupported)
*/
inline void CWrapper::GetSpecificationVersion(const std::string & sSpecificationURL, bool & bIsSupported, Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro)
{
CheckError(nullptr,lib3mf_getspecificationversion(sSpecificationURL.c_str(), &bIsSupported, &nMajor, &nMinor, &nMicro));
}
/**
* CWrapper::CreateModel - creates an empty model instance.
* @return returns an empty model instance
*/
inline PModel CWrapper::CreateModel()
{
Lib3MFHandle hModel = nullptr;
CheckError(nullptr,lib3mf_createmodel(&hModel));
if (!hModel) {
CheckError(nullptr,LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CModel>(this, hModel);
}
/**
* CWrapper::Release - releases shared ownership of an object instance
* @param[in] pInstance - the object instance to release
*/
inline void CWrapper::Release(CBase * pInstance)
{
Lib3MFHandle hInstance = nullptr;
if (pInstance != nullptr) {
hInstance = pInstance->GetHandle();
};
CheckError(nullptr,lib3mf_release(hInstance));
}
/**
* CWrapper::Acquire - acquires shared ownership of an object instance
* @param[in] pInstance - the object instance to acquire
*/
inline void CWrapper::Acquire(CBase * pInstance)
{
Lib3MFHandle hInstance = nullptr;
if (pInstance != nullptr) {
hInstance = pInstance->GetHandle();
};
CheckError(nullptr,lib3mf_acquire(hInstance));
}
/**
* CWrapper::SetJournal - Sets the journal file path
* @param[in] sJournalPath - File name of the journal file
*/
inline void CWrapper::SetJournal(const std::string & sJournalPath)
{
CheckError(nullptr,lib3mf_setjournal(sJournalPath.c_str()));
}
/**
* CWrapper::GetLastError - Retrieves the last error string of an instance
* @param[in] pInstance - Object where the error occured.
* @param[out] sLastErrorString - Last Error String
* @return Returns if the instance has a last error.
*/
inline bool CWrapper::GetLastError(CBase * pInstance, std::string & sLastErrorString)
{
Lib3MFHandle hInstance = nullptr;
if (pInstance != nullptr) {
hInstance = pInstance->GetHandle();
};
Lib3MF_uint32 bytesNeededLastErrorString = 0;
Lib3MF_uint32 bytesWrittenLastErrorString = 0;
bool resultHasLastError = 0;
CheckError(nullptr,lib3mf_getlasterror(hInstance, 0, &bytesNeededLastErrorString, nullptr, &resultHasLastError));
std::vector<char> bufferLastErrorString(bytesNeededLastErrorString);
CheckError(nullptr,lib3mf_getlasterror(hInstance, bytesNeededLastErrorString, &bytesWrittenLastErrorString, &bufferLastErrorString[0], &resultHasLastError));
sLastErrorString = std::string(&bufferLastErrorString[0]);
return resultHasLastError;
}
/**
* CWrapper::GetSymbolLookupMethod - Returns the address of the SymbolLookupMethod
* @return Address of the SymbolAddressMethod
*/
inline Lib3MF_pvoid CWrapper::GetSymbolLookupMethod()
{
Lib3MF_pvoid resultSymbolLookupMethod = 0;
CheckError(nullptr,lib3mf_getsymbollookupmethod(&resultSymbolLookupMethod));
return resultSymbolLookupMethod;
}
/**
* CWrapper::RetrieveProgressMessage - Return an English text for a progress identifier.|Note: this is the only function you can call from your callback function.
* @param[in] eTheProgressIdentifier - the progress identifier that is passed to the callback function
* @param[out] sProgressMessage - English text for the progress identifier
*/
inline void CWrapper::RetrieveProgressMessage(const eProgressIdentifier eTheProgressIdentifier, std::string & sProgressMessage)
{
Lib3MF_uint32 bytesNeededProgressMessage = 0;
Lib3MF_uint32 bytesWrittenProgressMessage = 0;
CheckError(nullptr,lib3mf_retrieveprogressmessage(eTheProgressIdentifier, 0, &bytesNeededProgressMessage, nullptr));
std::vector<char> bufferProgressMessage(bytesNeededProgressMessage);
CheckError(nullptr,lib3mf_retrieveprogressmessage(eTheProgressIdentifier, bytesNeededProgressMessage, &bytesWrittenProgressMessage, &bufferProgressMessage[0]));
sProgressMessage = std::string(&bufferProgressMessage[0]);
}
/**
* CWrapper::RGBAToColor - Creates a Color from uint8 RGBA values
* @param[in] nRed - Red value of color (0-255)
* @param[in] nGreen - Green value of color (0-255)
* @param[in] nBlue - Blue value of color (0-255)
* @param[in] nAlpha - Alpha value of color (0-255)
* @return Assembled color
*/
inline sColor CWrapper::RGBAToColor(const Lib3MF_uint8 nRed, const Lib3MF_uint8 nGreen, const Lib3MF_uint8 nBlue, const Lib3MF_uint8 nAlpha)
{
sColor resultTheColor;
CheckError(nullptr,lib3mf_rgbatocolor(nRed, nGreen, nBlue, nAlpha, &resultTheColor));
return resultTheColor;
}
/**
* CWrapper::FloatRGBAToColor - Creates a Color from uint8 RGBA values
* @param[in] fRed - Red value of color (0-1)
* @param[in] fGreen - Green value of color (0-1)
* @param[in] fBlue - Blue value of color (0-1)
* @param[in] fAlpha - Alpha value of color (0-1)
* @return Assembled color
*/
inline sColor CWrapper::FloatRGBAToColor(const Lib3MF_single fRed, const Lib3MF_single fGreen, const Lib3MF_single fBlue, const Lib3MF_single fAlpha)
{
sColor resultTheColor;
CheckError(nullptr,lib3mf_floatrgbatocolor(fRed, fGreen, fBlue, fAlpha, &resultTheColor));
return resultTheColor;
}
/**
* CWrapper::ColorToRGBA - Calculates uint8-RGBA-values from a Color
* @param[in] TheColor - Color to handle
* @param[out] nRed - Red value of color (0-255)
* @param[out] nGreen - Green value of color (0-255)
* @param[out] nBlue - Blue value of color (0-255)
* @param[out] nAlpha - Alpha value of color (0-255)
*/
inline void CWrapper::ColorToRGBA(const sColor & TheColor, Lib3MF_uint8 & nRed, Lib3MF_uint8 & nGreen, Lib3MF_uint8 & nBlue, Lib3MF_uint8 & nAlpha)
{
CheckError(nullptr,lib3mf_colortorgba(&TheColor, &nRed, &nGreen, &nBlue, &nAlpha));
}
/**
* CWrapper::ColorToFloatRGBA - Calculates float-RGBA-values from a Color
* @param[in] TheColor - Color to handle
* @param[out] fRed - Red value of color (0-1)
* @param[out] fGreen - Green value of color (0-1)
* @param[out] fBlue - Blue value of color (0-1)
* @param[out] fAlpha - Alpha value of color (0-1)
*/
inline void CWrapper::ColorToFloatRGBA(const sColor & TheColor, Lib3MF_single & fRed, Lib3MF_single & fGreen, Lib3MF_single & fBlue, Lib3MF_single & fAlpha)
{
CheckError(nullptr,lib3mf_colortofloatrgba(&TheColor, &fRed, &fGreen, &fBlue, &fAlpha));
}
/**
* CWrapper::GetIdentityTransform - Creates an identity transform
* @return Transformation matrix.
*/
inline sTransform CWrapper::GetIdentityTransform()
{
sTransform resultTransform;
CheckError(nullptr,lib3mf_getidentitytransform(&resultTransform));
return resultTransform;
}
/**
* CWrapper::GetUniformScaleTransform - Creates a uniform scale transform
* @param[in] fFactor - Factor in X, Y and Z
* @return Transformation matrix.
*/
inline sTransform CWrapper::GetUniformScaleTransform(const Lib3MF_single fFactor)
{
sTransform resultTransform;
CheckError(nullptr,lib3mf_getuniformscaletransform(fFactor, &resultTransform));
return resultTransform;
}
/**
* CWrapper::GetScaleTransform - Creates a scale transform
* @param[in] fFactorX - Factor in X
* @param[in] fFactorY - Factor in Y
* @param[in] fFactorZ - Factor in Z
* @return Transformation matrix.
*/
inline sTransform CWrapper::GetScaleTransform(const Lib3MF_single fFactorX, const Lib3MF_single fFactorY, const Lib3MF_single fFactorZ)
{
sTransform resultTransform;
CheckError(nullptr,lib3mf_getscaletransform(fFactorX, fFactorY, fFactorZ, &resultTransform));
return resultTransform;
}
/**
* CWrapper::GetTranslationTransform - Creates an translation transform
* @param[in] fVectorX - Translation in X
* @param[in] fVectorY - Translation in Y
* @param[in] fVectorZ - Translation in Z
* @return Transformation matrix.
*/
inline sTransform CWrapper::GetTranslationTransform(const Lib3MF_single fVectorX, const Lib3MF_single fVectorY, const Lib3MF_single fVectorZ)
{
sTransform resultTransform;
CheckError(nullptr,lib3mf_gettranslationtransform(fVectorX, fVectorY, fVectorZ, &resultTransform));
return resultTransform;
}
inline void CWrapper::CheckError(CBase * pBaseClass, Lib3MFResult nResult)
{
if (nResult != 0) {
std::string sErrorMessage;
if (pBaseClass != nullptr) {
GetLastError(pBaseClass, sErrorMessage);
}
throw ELib3MFException(nResult, sErrorMessage);
}
}
/**
* Method definitions for class CBase
*/
/**
* Method definitions for class CWriter
*/
/**
* CWriter::WriteToFile - Writes out the model as file. The file type is specified by the Model Writer class.
* @param[in] sFilename - Filename to write into
*/
void CWriter::WriteToFile(const std::string & sFilename)
{
CheckError(lib3mf_writer_writetofile(m_pHandle, sFilename.c_str()));
}
/**
* CWriter::GetStreamSize - Retrieves the size of the full 3MF file stream.
* @return the stream size
*/
Lib3MF_uint64 CWriter::GetStreamSize()
{
Lib3MF_uint64 resultStreamSize = 0;
CheckError(lib3mf_writer_getstreamsize(m_pHandle, &resultStreamSize));
return resultStreamSize;
}
/**
* CWriter::WriteToBuffer - Writes out the 3MF file into a memory buffer
* @param[out] BufferBuffer - buffer to write into
*/
void CWriter::WriteToBuffer(std::vector<Lib3MF_uint8> & BufferBuffer)
{
Lib3MF_uint64 elementsNeededBuffer = 0;
Lib3MF_uint64 elementsWrittenBuffer = 0;
CheckError(lib3mf_writer_writetobuffer(m_pHandle, 0, &elementsNeededBuffer, nullptr));
BufferBuffer.resize((size_t) elementsNeededBuffer);
CheckError(lib3mf_writer_writetobuffer(m_pHandle, elementsNeededBuffer, &elementsWrittenBuffer, BufferBuffer.data()));
}
/**
* CWriter::WriteToCallback - Writes out the model and passes the data to a provided callback function. The file type is specified by the Model Writer class.
* @param[in] pTheWriteCallback - Callback to call for writing a data chunk
* @param[in] pTheSeekCallback - Callback to call for seeking in the stream
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CWriter::WriteToCallback(const WriteCallback pTheWriteCallback, const SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_writer_writetocallback(m_pHandle, pTheWriteCallback, pTheSeekCallback, pUserData));
}
/**
* CWriter::SetProgressCallback - Set the progress callback for calls to this writer
* @param[in] pProgressCallback - pointer to the callback function.
* @param[in] pUserData - pointer to arbitrary user data that is passed without modification to the callback.
*/
void CWriter::SetProgressCallback(const ProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_writer_setprogresscallback(m_pHandle, pProgressCallback, pUserData));
}
/**
* CWriter::GetDecimalPrecision - Returns the number of digits after the decimal point to be written in each vertex coordinate-value.
* @return The number of digits to be written in each vertex coordinate-value after the decimal point.
*/
Lib3MF_uint32 CWriter::GetDecimalPrecision()
{
Lib3MF_uint32 resultDecimalPrecision = 0;
CheckError(lib3mf_writer_getdecimalprecision(m_pHandle, &resultDecimalPrecision));
return resultDecimalPrecision;
}
/**
* CWriter::SetDecimalPrecision - Sets the number of digits after the decimal point to be written in each vertex coordinate-value.
* @param[in] nDecimalPrecision - The number of digits to be written in each vertex coordinate-value after the decimal point.
*/
void CWriter::SetDecimalPrecision(const Lib3MF_uint32 nDecimalPrecision)
{
CheckError(lib3mf_writer_setdecimalprecision(m_pHandle, nDecimalPrecision));
}
/**
* CWriter::SetStrictModeActive - Activates (deactivates) the strict mode of the reader.
* @param[in] bStrictModeActive - flag whether strict mode is active or not.
*/
void CWriter::SetStrictModeActive(const bool bStrictModeActive)
{
CheckError(lib3mf_writer_setstrictmodeactive(m_pHandle, bStrictModeActive));
}
/**
* CWriter::GetStrictModeActive - Queries whether the strict mode of the reader is active or not
* @return returns flag whether strict mode is active or not.
*/
bool CWriter::GetStrictModeActive()
{
bool resultStrictModeActive = 0;
CheckError(lib3mf_writer_getstrictmodeactive(m_pHandle, &resultStrictModeActive));
return resultStrictModeActive;
}
/**
* CWriter::GetWarning - Returns Warning and Error Information of the read process
* @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1
* @param[out] nErrorCode - filled with the error code of the warning
* @return the message of the warning
*/
std::string CWriter::GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode)
{
Lib3MF_uint32 bytesNeededWarning = 0;
Lib3MF_uint32 bytesWrittenWarning = 0;
CheckError(lib3mf_writer_getwarning(m_pHandle, nIndex, &nErrorCode, 0, &bytesNeededWarning, nullptr));
std::vector<char> bufferWarning(bytesNeededWarning);
CheckError(lib3mf_writer_getwarning(m_pHandle, nIndex, &nErrorCode, bytesNeededWarning, &bytesWrittenWarning, &bufferWarning[0]));
return std::string(&bufferWarning[0]);
}
/**
* CWriter::GetWarningCount - Returns Warning and Error Count of the read process
* @return filled with the count of the occurred warnings.
*/
Lib3MF_uint32 CWriter::GetWarningCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_writer_getwarningcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CWriter::AddKeyWrappingCallback - Registers a callback to deal with data key encryption/decryption from keystore
* @param[in] sConsumerID - The ConsumerID to register for
* @param[in] pTheCallback - The callback to be callede for wrapping and encryption key
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CWriter::AddKeyWrappingCallback(const std::string & sConsumerID, const KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_writer_addkeywrappingcallback(m_pHandle, sConsumerID.c_str(), pTheCallback, pUserData));
}
/**
* CWriter::SetContentEncryptionCallback - Registers a callback to deal with encryption of content
* @param[in] pTheCallback - The callback used to encrypt content
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CWriter::SetContentEncryptionCallback(const ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_writer_setcontentencryptioncallback(m_pHandle, pTheCallback, pUserData));
}
/**
* Method definitions for class CReader
*/
/**
* CReader::ReadFromFile - Reads a model from a file. The file type is specified by the Model Reader class
* @param[in] sFilename - Filename to read from
*/
void CReader::ReadFromFile(const std::string & sFilename)
{
CheckError(lib3mf_reader_readfromfile(m_pHandle, sFilename.c_str()));
}
/**
* CReader::ReadFromBuffer - Reads a model from a memory buffer.
* @param[in] BufferBuffer - Buffer to read from
*/
void CReader::ReadFromBuffer(const CInputVector<Lib3MF_uint8> & BufferBuffer)
{
CheckError(lib3mf_reader_readfrombuffer(m_pHandle, (Lib3MF_uint64)BufferBuffer.size(), BufferBuffer.data()));
}
/**
* CReader::ReadFromCallback - Reads a model and from the data provided by a callback function
* @param[in] pTheReadCallback - Callback to call for reading a data chunk
* @param[in] nStreamSize - number of bytes the callback returns
* @param[in] pTheSeekCallback - Callback to call for seeking in the stream.
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CReader::ReadFromCallback(const ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_reader_readfromcallback(m_pHandle, pTheReadCallback, nStreamSize, pTheSeekCallback, pUserData));
}
/**
* CReader::SetProgressCallback - Set the progress callback for calls to this writer
* @param[in] pProgressCallback - pointer to the callback function.
* @param[in] pUserData - pointer to arbitrary user data that is passed without modification to the callback.
*/
void CReader::SetProgressCallback(const ProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_reader_setprogresscallback(m_pHandle, pProgressCallback, pUserData));
}
/**
* CReader::AddRelationToRead - Adds a relationship type which shall be read as attachment in memory while loading
* @param[in] sRelationShipType - String of the relationship type
*/
void CReader::AddRelationToRead(const std::string & sRelationShipType)
{
CheckError(lib3mf_reader_addrelationtoread(m_pHandle, sRelationShipType.c_str()));
}
/**
* CReader::RemoveRelationToRead - Removes a relationship type which shall be read as attachment in memory while loading
* @param[in] sRelationShipType - String of the relationship type
*/
void CReader::RemoveRelationToRead(const std::string & sRelationShipType)
{
CheckError(lib3mf_reader_removerelationtoread(m_pHandle, sRelationShipType.c_str()));
}
/**
* CReader::SetStrictModeActive - Activates (deactivates) the strict mode of the reader.
* @param[in] bStrictModeActive - flag whether strict mode is active or not.
*/
void CReader::SetStrictModeActive(const bool bStrictModeActive)
{
CheckError(lib3mf_reader_setstrictmodeactive(m_pHandle, bStrictModeActive));
}
/**
* CReader::GetStrictModeActive - Queries whether the strict mode of the reader is active or not
* @return returns flag whether strict mode is active or not.
*/
bool CReader::GetStrictModeActive()
{
bool resultStrictModeActive = 0;
CheckError(lib3mf_reader_getstrictmodeactive(m_pHandle, &resultStrictModeActive));
return resultStrictModeActive;
}
/**
* CReader::GetWarning - Returns Warning and Error Information of the read process
* @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1
* @param[out] nErrorCode - filled with the error code of the warning
* @return the message of the warning
*/
std::string CReader::GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode)
{
Lib3MF_uint32 bytesNeededWarning = 0;
Lib3MF_uint32 bytesWrittenWarning = 0;
CheckError(lib3mf_reader_getwarning(m_pHandle, nIndex, &nErrorCode, 0, &bytesNeededWarning, nullptr));
std::vector<char> bufferWarning(bytesNeededWarning);
CheckError(lib3mf_reader_getwarning(m_pHandle, nIndex, &nErrorCode, bytesNeededWarning, &bytesWrittenWarning, &bufferWarning[0]));
return std::string(&bufferWarning[0]);
}
/**
* CReader::GetWarningCount - Returns Warning and Error Count of the read process
* @return filled with the count of the occurred warnings.
*/
Lib3MF_uint32 CReader::GetWarningCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_reader_getwarningcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CReader::AddKeyWrappingCallback - Registers a callback to deal with key wrapping mechanism from keystore
* @param[in] sConsumerID - The ConsumerID to register for
* @param[in] pTheCallback - The callback used to decrypt data key
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CReader::AddKeyWrappingCallback(const std::string & sConsumerID, const KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_reader_addkeywrappingcallback(m_pHandle, sConsumerID.c_str(), pTheCallback, pUserData));
}
/**
* CReader::SetContentEncryptionCallback - Registers a callback to deal with encryption of content
* @param[in] pTheCallback - The callback used to encrypt content
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CReader::SetContentEncryptionCallback(const ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_reader_setcontentencryptioncallback(m_pHandle, pTheCallback, pUserData));
}
/**
* Method definitions for class CPackagePart
*/
/**
* CPackagePart::GetPath - Returns the absolute path of this PackagePart.
* @return Returns the absolute path of this PackagePart
*/
std::string CPackagePart::GetPath()
{
Lib3MF_uint32 bytesNeededPath = 0;
Lib3MF_uint32 bytesWrittenPath = 0;
CheckError(lib3mf_packagepart_getpath(m_pHandle, 0, &bytesNeededPath, nullptr));
std::vector<char> bufferPath(bytesNeededPath);
CheckError(lib3mf_packagepart_getpath(m_pHandle, bytesNeededPath, &bytesWrittenPath, &bufferPath[0]));
return std::string(&bufferPath[0]);
}
/**
* CPackagePart::SetPath - Sets the absolute path of this PackagePart.
* @param[in] sPath - Sets the absolute path of this PackagePart.
*/
void CPackagePart::SetPath(const std::string & sPath)
{
CheckError(lib3mf_packagepart_setpath(m_pHandle, sPath.c_str()));
}
/**
* Method definitions for class CResource
*/
/**
* CResource::GetResourceID - Retrieves the unique id of this resource within a package. This function will be removed in a later release in favor of GetUniqueResourceID
* @return Retrieves the unique id of this resource within a package.
*/
Lib3MF_uint32 CResource::GetResourceID()
{
Lib3MF_uint32 resultUniqueResourceID = 0;
CheckError(lib3mf_resource_getresourceid(m_pHandle, &resultUniqueResourceID));
return resultUniqueResourceID;
}
/**
* CResource::GetUniqueResourceID - Retrieves the unique id of this resource within a package.
* @return Retrieves the unique id of this resource within a package.
*/
Lib3MF_uint32 CResource::GetUniqueResourceID()
{
Lib3MF_uint32 resultUniqueResourceID = 0;
CheckError(lib3mf_resource_getuniqueresourceid(m_pHandle, &resultUniqueResourceID));
return resultUniqueResourceID;
}
/**
* CResource::PackagePart - Returns the PackagePart within which this resource resides
* @return the PackagePart within which this resource resides.
*/
PPackagePart CResource::PackagePart()
{
Lib3MFHandle hPackagePart = nullptr;
CheckError(lib3mf_resource_packagepart(m_pHandle, &hPackagePart));
if (!hPackagePart) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CPackagePart>(m_pWrapper, hPackagePart);
}
/**
* CResource::SetPackagePart - Sets the new PackagePart within which this resource resides
* @param[in] pPackagePart - the new PackagePart within which this resource resides.
*/
void CResource::SetPackagePart(CPackagePart * pPackagePart)
{
Lib3MFHandle hPackagePart = nullptr;
if (pPackagePart != nullptr) {
hPackagePart = pPackagePart->GetHandle();
};
CheckError(lib3mf_resource_setpackagepart(m_pHandle, hPackagePart));
}
/**
* CResource::GetModelResourceID - Retrieves the id of this resource within a model.
* @return Retrieves the id of this resource within a model.
*/
Lib3MF_uint32 CResource::GetModelResourceID()
{
Lib3MF_uint32 resultModelResourceId = 0;
CheckError(lib3mf_resource_getmodelresourceid(m_pHandle, &resultModelResourceId));
return resultModelResourceId;
}
/**
* Method definitions for class CResourceIterator
*/
/**
* CResourceIterator::MoveNext - Iterates to the next resource in the list.
* @return Iterates to the next resource in the list.
*/
bool CResourceIterator::MoveNext()
{
bool resultHasNext = 0;
CheckError(lib3mf_resourceiterator_movenext(m_pHandle, &resultHasNext));
return resultHasNext;
}
/**
* CResourceIterator::MovePrevious - Iterates to the previous resource in the list.
* @return Iterates to the previous resource in the list.
*/
bool CResourceIterator::MovePrevious()
{
bool resultHasPrevious = 0;
CheckError(lib3mf_resourceiterator_moveprevious(m_pHandle, &resultHasPrevious));
return resultHasPrevious;
}
/**
* CResourceIterator::GetCurrent - Returns the resource the iterator points at.
* @return returns the resource instance.
*/
PResource CResourceIterator::GetCurrent()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_resourceiterator_getcurrent(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResource>(m_pWrapper, hResource);
}
/**
* CResourceIterator::Clone - Creates a new resource iterator with the same resource list.
* @return returns the cloned Iterator instance
*/
PResourceIterator CResourceIterator::Clone()
{
Lib3MFHandle hOutResourceIterator = nullptr;
CheckError(lib3mf_resourceiterator_clone(m_pHandle, &hOutResourceIterator));
if (!hOutResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResourceIterator>(m_pWrapper, hOutResourceIterator);
}
/**
* CResourceIterator::Count - Returns the number of resoucres the iterator captures.
* @return returns the number of resoucres the iterator captures.
*/
Lib3MF_uint64 CResourceIterator::Count()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_resourceiterator_count(m_pHandle, &resultCount));
return resultCount;
}
/**
* Method definitions for class CSliceStackIterator
*/
/**
* CSliceStackIterator::GetCurrentSliceStack - Returns the SliceStack the iterator points at.
* @return returns the SliceStack instance.
*/
PSliceStack CSliceStackIterator::GetCurrentSliceStack()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_slicestackiterator_getcurrentslicestack(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSliceStack>(m_pWrapper, hResource);
}
/**
* Method definitions for class CObjectIterator
*/
/**
* CObjectIterator::GetCurrentObject - Returns the Object the iterator points at.
* @return returns the Object instance.
*/
PObject CObjectIterator::GetCurrentObject()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_objectiterator_getcurrentobject(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CObject>(m_pWrapper, hResource);
}
/**
* Method definitions for class CMeshObjectIterator
*/
/**
* CMeshObjectIterator::GetCurrentMeshObject - Returns the MeshObject the iterator points at.
* @return returns the MeshObject instance.
*/
PMeshObject CMeshObjectIterator::GetCurrentMeshObject()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_meshobjectiterator_getcurrentmeshobject(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMeshObject>(m_pWrapper, hResource);
}
/**
* Method definitions for class CComponentsObjectIterator
*/
/**
* CComponentsObjectIterator::GetCurrentComponentsObject - Returns the ComponentsObject the iterator points at.
* @return returns the ComponentsObject instance.
*/
PComponentsObject CComponentsObjectIterator::GetCurrentComponentsObject()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_componentsobjectiterator_getcurrentcomponentsobject(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CComponentsObject>(m_pWrapper, hResource);
}
/**
* Method definitions for class CTexture2DIterator
*/
/**
* CTexture2DIterator::GetCurrentTexture2D - Returns the Texture2D the iterator points at.
* @return returns the Texture2D instance.
*/
PTexture2D CTexture2DIterator::GetCurrentTexture2D()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_texture2diterator_getcurrenttexture2d(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2D>(m_pWrapper, hResource);
}
/**
* Method definitions for class CBaseMaterialGroupIterator
*/
/**
* CBaseMaterialGroupIterator::GetCurrentBaseMaterialGroup - Returns the MaterialGroup the iterator points at.
* @return returns the BaseMaterialGroup instance.
*/
PBaseMaterialGroup CBaseMaterialGroupIterator::GetCurrentBaseMaterialGroup()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_basematerialgroupiterator_getcurrentbasematerialgroup(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBaseMaterialGroup>(m_pWrapper, hResource);
}
/**
* Method definitions for class CColorGroupIterator
*/
/**
* CColorGroupIterator::GetCurrentColorGroup - Returns the ColorGroup the iterator points at.
* @return returns the ColorGroup instance.
*/
PColorGroup CColorGroupIterator::GetCurrentColorGroup()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_colorgroupiterator_getcurrentcolorgroup(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CColorGroup>(m_pWrapper, hResource);
}
/**
* Method definitions for class CTexture2DGroupIterator
*/
/**
* CTexture2DGroupIterator::GetCurrentTexture2DGroup - Returns the Texture2DGroup the iterator points at.
* @return returns the Texture2DGroup instance.
*/
PTexture2DGroup CTexture2DGroupIterator::GetCurrentTexture2DGroup()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_texture2dgroupiterator_getcurrenttexture2dgroup(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2DGroup>(m_pWrapper, hResource);
}
/**
* Method definitions for class CCompositeMaterialsIterator
*/
/**
* CCompositeMaterialsIterator::GetCurrentCompositeMaterials - Returns the CompositeMaterials the iterator points at.
* @return returns the CompositeMaterials instance.
*/
PCompositeMaterials CCompositeMaterialsIterator::GetCurrentCompositeMaterials()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_compositematerialsiterator_getcurrentcompositematerials(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CCompositeMaterials>(m_pWrapper, hResource);
}
/**
* Method definitions for class CMultiPropertyGroupIterator
*/
/**
* CMultiPropertyGroupIterator::GetCurrentMultiPropertyGroup - Returns the MultiPropertyGroup the iterator points at.
* @return returns the MultiPropertyGroup instance.
*/
PMultiPropertyGroup CMultiPropertyGroupIterator::GetCurrentMultiPropertyGroup()
{
Lib3MFHandle hResource = nullptr;
CheckError(lib3mf_multipropertygroupiterator_getcurrentmultipropertygroup(m_pHandle, &hResource));
if (!hResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMultiPropertyGroup>(m_pWrapper, hResource);
}
/**
* Method definitions for class CMetaData
*/
/**
* CMetaData::GetNameSpace - returns the namespace URL of the metadata
* @return the namespace URL of the metadata
*/
std::string CMetaData::GetNameSpace()
{
Lib3MF_uint32 bytesNeededNameSpace = 0;
Lib3MF_uint32 bytesWrittenNameSpace = 0;
CheckError(lib3mf_metadata_getnamespace(m_pHandle, 0, &bytesNeededNameSpace, nullptr));
std::vector<char> bufferNameSpace(bytesNeededNameSpace);
CheckError(lib3mf_metadata_getnamespace(m_pHandle, bytesNeededNameSpace, &bytesWrittenNameSpace, &bufferNameSpace[0]));
return std::string(&bufferNameSpace[0]);
}
/**
* CMetaData::SetNameSpace - sets a new namespace URL of the metadata
* @param[in] sNameSpace - the new namespace URL of the metadata
*/
void CMetaData::SetNameSpace(const std::string & sNameSpace)
{
CheckError(lib3mf_metadata_setnamespace(m_pHandle, sNameSpace.c_str()));
}
/**
* CMetaData::GetName - returns the name of a metadata
* @return the name of the metadata
*/
std::string CMetaData::GetName()
{
Lib3MF_uint32 bytesNeededName = 0;
Lib3MF_uint32 bytesWrittenName = 0;
CheckError(lib3mf_metadata_getname(m_pHandle, 0, &bytesNeededName, nullptr));
std::vector<char> bufferName(bytesNeededName);
CheckError(lib3mf_metadata_getname(m_pHandle, bytesNeededName, &bytesWrittenName, &bufferName[0]));
return std::string(&bufferName[0]);
}
/**
* CMetaData::SetName - sets a new name of a metadata
* @param[in] sName - the new name of the metadata
*/
void CMetaData::SetName(const std::string & sName)
{
CheckError(lib3mf_metadata_setname(m_pHandle, sName.c_str()));
}
/**
* CMetaData::GetKey - returns the (namespace+name) of a metadata
* @return the key (namespace+name) of the metadata
*/
std::string CMetaData::GetKey()
{
Lib3MF_uint32 bytesNeededKey = 0;
Lib3MF_uint32 bytesWrittenKey = 0;
CheckError(lib3mf_metadata_getkey(m_pHandle, 0, &bytesNeededKey, nullptr));
std::vector<char> bufferKey(bytesNeededKey);
CheckError(lib3mf_metadata_getkey(m_pHandle, bytesNeededKey, &bytesWrittenKey, &bufferKey[0]));
return std::string(&bufferKey[0]);
}
/**
* CMetaData::GetMustPreserve - returns, whether a metadata must be preserved
* @return returns, whether a metadata must be preserved
*/
bool CMetaData::GetMustPreserve()
{
bool resultMustPreserve = 0;
CheckError(lib3mf_metadata_getmustpreserve(m_pHandle, &resultMustPreserve));
return resultMustPreserve;
}
/**
* CMetaData::SetMustPreserve - sets whether a metadata must be preserved
* @param[in] bMustPreserve - a new value whether a metadata must be preserved
*/
void CMetaData::SetMustPreserve(const bool bMustPreserve)
{
CheckError(lib3mf_metadata_setmustpreserve(m_pHandle, bMustPreserve));
}
/**
* CMetaData::GetType - returns the type of a metadata
* @return the type of the metadata
*/
std::string CMetaData::GetType()
{
Lib3MF_uint32 bytesNeededType = 0;
Lib3MF_uint32 bytesWrittenType = 0;
CheckError(lib3mf_metadata_gettype(m_pHandle, 0, &bytesNeededType, nullptr));
std::vector<char> bufferType(bytesNeededType);
CheckError(lib3mf_metadata_gettype(m_pHandle, bytesNeededType, &bytesWrittenType, &bufferType[0]));
return std::string(&bufferType[0]);
}
/**
* CMetaData::SetType - sets a new type of a metadata. This must be a simple XML type
* @param[in] sType - a new type of the metadata
*/
void CMetaData::SetType(const std::string & sType)
{
CheckError(lib3mf_metadata_settype(m_pHandle, sType.c_str()));
}
/**
* CMetaData::GetValue - returns the value of the metadata
* @return the value of the metadata
*/
std::string CMetaData::GetValue()
{
Lib3MF_uint32 bytesNeededValue = 0;
Lib3MF_uint32 bytesWrittenValue = 0;
CheckError(lib3mf_metadata_getvalue(m_pHandle, 0, &bytesNeededValue, nullptr));
std::vector<char> bufferValue(bytesNeededValue);
CheckError(lib3mf_metadata_getvalue(m_pHandle, bytesNeededValue, &bytesWrittenValue, &bufferValue[0]));
return std::string(&bufferValue[0]);
}
/**
* CMetaData::SetValue - sets a new value of the metadata
* @param[in] sValue - a new value of the metadata
*/
void CMetaData::SetValue(const std::string & sValue)
{
CheckError(lib3mf_metadata_setvalue(m_pHandle, sValue.c_str()));
}
/**
* Method definitions for class CMetaDataGroup
*/
/**
* CMetaDataGroup::GetMetaDataCount - returns the number of metadata in this metadatagroup
* @return returns the number metadata
*/
Lib3MF_uint32 CMetaDataGroup::GetMetaDataCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_metadatagroup_getmetadatacount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CMetaDataGroup::GetMetaData - returns a metadata value within this metadatagroup
* @param[in] nIndex - Index of the Metadata.
* @return an instance of the metadata
*/
PMetaData CMetaDataGroup::GetMetaData(const Lib3MF_uint32 nIndex)
{
Lib3MFHandle hMetaData = nullptr;
CheckError(lib3mf_metadatagroup_getmetadata(m_pHandle, nIndex, &hMetaData));
if (!hMetaData) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMetaData>(m_pWrapper, hMetaData);
}
/**
* CMetaDataGroup::GetMetaDataByKey - returns a metadata value within this metadatagroup
* @param[in] sNameSpace - the namespace of the metadata
* @param[in] sName - the name of the Metadata
* @return an instance of the metadata
*/
PMetaData CMetaDataGroup::GetMetaDataByKey(const std::string & sNameSpace, const std::string & sName)
{
Lib3MFHandle hMetaData = nullptr;
CheckError(lib3mf_metadatagroup_getmetadatabykey(m_pHandle, sNameSpace.c_str(), sName.c_str(), &hMetaData));
if (!hMetaData) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMetaData>(m_pWrapper, hMetaData);
}
/**
* CMetaDataGroup::RemoveMetaDataByIndex - removes metadata by index from the model.
* @param[in] nIndex - Index of the metadata to remove
*/
void CMetaDataGroup::RemoveMetaDataByIndex(const Lib3MF_uint32 nIndex)
{
CheckError(lib3mf_metadatagroup_removemetadatabyindex(m_pHandle, nIndex));
}
/**
* CMetaDataGroup::RemoveMetaData - removes metadata from the model.
* @param[in] pTheMetaData - The metadata to remove
*/
void CMetaDataGroup::RemoveMetaData(CMetaData * pTheMetaData)
{
Lib3MFHandle hTheMetaData = nullptr;
if (pTheMetaData != nullptr) {
hTheMetaData = pTheMetaData->GetHandle();
};
CheckError(lib3mf_metadatagroup_removemetadata(m_pHandle, hTheMetaData));
}
/**
* CMetaDataGroup::AddMetaData - adds a new metadata to this metadatagroup
* @param[in] sNameSpace - the namespace of the metadata
* @param[in] sName - the name of the metadata
* @param[in] sValue - the value of the metadata
* @param[in] sType - the type of the metadata
* @param[in] bMustPreserve - shuold the metadata be preserved
* @return a new instance of the metadata
*/
PMetaData CMetaDataGroup::AddMetaData(const std::string & sNameSpace, const std::string & sName, const std::string & sValue, const std::string & sType, const bool bMustPreserve)
{
Lib3MFHandle hMetaData = nullptr;
CheckError(lib3mf_metadatagroup_addmetadata(m_pHandle, sNameSpace.c_str(), sName.c_str(), sValue.c_str(), sType.c_str(), bMustPreserve, &hMetaData));
if (!hMetaData) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMetaData>(m_pWrapper, hMetaData);
}
/**
* Method definitions for class CObject
*/
/**
* CObject::GetType - Retrieves an object's type
* @return returns object type enum.
*/
eObjectType CObject::GetType()
{
eObjectType resultObjectType = (eObjectType) 0;
CheckError(lib3mf_object_gettype(m_pHandle, &resultObjectType));
return resultObjectType;
}
/**
* CObject::SetType - Sets an object's type
* @param[in] eObjectType - object type enum.
*/
void CObject::SetType(const eObjectType eObjectType)
{
CheckError(lib3mf_object_settype(m_pHandle, eObjectType));
}
/**
* CObject::GetName - Retrieves an object's name
* @return returns object name.
*/
std::string CObject::GetName()
{
Lib3MF_uint32 bytesNeededName = 0;
Lib3MF_uint32 bytesWrittenName = 0;
CheckError(lib3mf_object_getname(m_pHandle, 0, &bytesNeededName, nullptr));
std::vector<char> bufferName(bytesNeededName);
CheckError(lib3mf_object_getname(m_pHandle, bytesNeededName, &bytesWrittenName, &bufferName[0]));
return std::string(&bufferName[0]);
}
/**
* CObject::SetName - Sets an object's name string
* @param[in] sName - new object name.
*/
void CObject::SetName(const std::string & sName)
{
CheckError(lib3mf_object_setname(m_pHandle, sName.c_str()));
}
/**
* CObject::GetPartNumber - Retrieves an object's part number
* @return returns object part number.
*/
std::string CObject::GetPartNumber()
{
Lib3MF_uint32 bytesNeededPartNumber = 0;
Lib3MF_uint32 bytesWrittenPartNumber = 0;
CheckError(lib3mf_object_getpartnumber(m_pHandle, 0, &bytesNeededPartNumber, nullptr));
std::vector<char> bufferPartNumber(bytesNeededPartNumber);
CheckError(lib3mf_object_getpartnumber(m_pHandle, bytesNeededPartNumber, &bytesWrittenPartNumber, &bufferPartNumber[0]));
return std::string(&bufferPartNumber[0]);
}
/**
* CObject::SetPartNumber - Sets an objects partnumber string
* @param[in] sPartNumber - new object part number.
*/
void CObject::SetPartNumber(const std::string & sPartNumber)
{
CheckError(lib3mf_object_setpartnumber(m_pHandle, sPartNumber.c_str()));
}
/**
* CObject::IsMeshObject - Retrieves, if an object is a mesh object
* @return returns, whether the object is a mesh object
*/
bool CObject::IsMeshObject()
{
bool resultIsMeshObject = 0;
CheckError(lib3mf_object_ismeshobject(m_pHandle, &resultIsMeshObject));
return resultIsMeshObject;
}
/**
* CObject::IsComponentsObject - Retrieves, if an object is a components object
* @return returns, whether the object is a components object
*/
bool CObject::IsComponentsObject()
{
bool resultIsComponentsObject = 0;
CheckError(lib3mf_object_iscomponentsobject(m_pHandle, &resultIsComponentsObject));
return resultIsComponentsObject;
}
/**
* CObject::IsValid - Retrieves, if the object is valid according to the core spec. For mesh objects, we distinguish between the type attribute of the object:In case of object type other, this always means false.In case of object type model or solidsupport, this means, if the mesh suffices all requirements of the core spec chapter 4.1.In case of object type support or surface, this always means true.A component objects is valid if and only if it contains at least one component and all child components are valid objects.
* @return returns whether the object is a valid object description
*/
bool CObject::IsValid()
{
bool resultIsValid = 0;
CheckError(lib3mf_object_isvalid(m_pHandle, &resultIsValid));
return resultIsValid;
}
/**
* CObject::SetAttachmentAsThumbnail - Use an existing attachment as thumbnail for this object
* @param[in] pAttachment - Instance of a new or the existing thumbnailattachment object.
*/
void CObject::SetAttachmentAsThumbnail(CAttachment * pAttachment)
{
Lib3MFHandle hAttachment = nullptr;
if (pAttachment != nullptr) {
hAttachment = pAttachment->GetHandle();
};
CheckError(lib3mf_object_setattachmentasthumbnail(m_pHandle, hAttachment));
}
/**
* CObject::GetThumbnailAttachment - Get the attachment containing the object thumbnail.
* @return Instance of the thumbnailattachment object or NULL.
*/
PAttachment CObject::GetThumbnailAttachment()
{
Lib3MFHandle hAttachment = nullptr;
CheckError(lib3mf_object_getthumbnailattachment(m_pHandle, &hAttachment));
if (hAttachment) {
return std::make_shared<CAttachment>(m_pWrapper, hAttachment);
} else {
return nullptr;
}
}
/**
* CObject::ClearThumbnailAttachment - Clears the attachment. The attachment instance is not removed from the package.
*/
void CObject::ClearThumbnailAttachment()
{
CheckError(lib3mf_object_clearthumbnailattachment(m_pHandle));
}
/**
* CObject::GetOutbox - Returns the outbox of a build item
* @return Outbox of this build item
*/
sBox CObject::GetOutbox()
{
sBox resultOutbox;
CheckError(lib3mf_object_getoutbox(m_pHandle, &resultOutbox));
return resultOutbox;
}
/**
* CObject::GetUUID - Retrieves an object's uuid string (see production extension specification)
* @param[out] bHasUUID - flag whether the build item has a UUID
* @return returns object uuid.
*/
std::string CObject::GetUUID(bool & bHasUUID)
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_object_getuuid(m_pHandle, &bHasUUID, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_object_getuuid(m_pHandle, &bHasUUID, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* CObject::SetUUID - Sets a build object's uuid string (see production extension specification)
* @param[in] sUUID - new object uuid string.
*/
void CObject::SetUUID(const std::string & sUUID)
{
CheckError(lib3mf_object_setuuid(m_pHandle, sUUID.c_str()));
}
/**
* CObject::GetMetaDataGroup - Returns the metadatagroup of this object
* @return returns an Instance of the metadatagroup of this object
*/
PMetaDataGroup CObject::GetMetaDataGroup()
{
Lib3MFHandle hMetaDataGroup = nullptr;
CheckError(lib3mf_object_getmetadatagroup(m_pHandle, &hMetaDataGroup));
if (!hMetaDataGroup) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMetaDataGroup>(m_pWrapper, hMetaDataGroup);
}
/**
* CObject::SetSlicesMeshResolution - set the meshresolution of the mesh object
* @param[in] eMeshResolution - meshresolution of this object
*/
void CObject::SetSlicesMeshResolution(const eSlicesMeshResolution eMeshResolution)
{
CheckError(lib3mf_object_setslicesmeshresolution(m_pHandle, eMeshResolution));
}
/**
* CObject::GetSlicesMeshResolution - get the meshresolution of the mesh object
* @return meshresolution of this object
*/
eSlicesMeshResolution CObject::GetSlicesMeshResolution()
{
eSlicesMeshResolution resultMeshResolution = (eSlicesMeshResolution) 0;
CheckError(lib3mf_object_getslicesmeshresolution(m_pHandle, &resultMeshResolution));
return resultMeshResolution;
}
/**
* CObject::HasSlices - returns whether the Object has a slice stack. If Recursive is true, also checks whether any references object has a slice stack
* @param[in] bRecursive - check also all referenced objects?
* @return does the object have a slice stack?
*/
bool CObject::HasSlices(const bool bRecursive)
{
bool resultHasSlices = 0;
CheckError(lib3mf_object_hasslices(m_pHandle, bRecursive, &resultHasSlices));
return resultHasSlices;
}
/**
* CObject::ClearSliceStack - unlinks the attached slicestack from this object. If no slice stack is attached, do noting.
*/
void CObject::ClearSliceStack()
{
CheckError(lib3mf_object_clearslicestack(m_pHandle));
}
/**
* CObject::GetSliceStack - get the Slicestack attached to the object
* @return returns the slicestack instance
*/
PSliceStack CObject::GetSliceStack()
{
Lib3MFHandle hSliceStackInstance = nullptr;
CheckError(lib3mf_object_getslicestack(m_pHandle, &hSliceStackInstance));
if (!hSliceStackInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSliceStack>(m_pWrapper, hSliceStackInstance);
}
/**
* CObject::AssignSliceStack - assigns a slicestack to the object
* @param[in] pSliceStackInstance - the new slice stack of this Object
*/
void CObject::AssignSliceStack(CSliceStack * pSliceStackInstance)
{
Lib3MFHandle hSliceStackInstance = nullptr;
if (pSliceStackInstance != nullptr) {
hSliceStackInstance = pSliceStackInstance->GetHandle();
};
CheckError(lib3mf_object_assignslicestack(m_pHandle, hSliceStackInstance));
}
/**
* Method definitions for class CMeshObject
*/
/**
* CMeshObject::GetVertexCount - Returns the vertex count of a mesh object.
* @return filled with the vertex count.
*/
Lib3MF_uint32 CMeshObject::GetVertexCount()
{
Lib3MF_uint32 resultVertexCount = 0;
CheckError(lib3mf_meshobject_getvertexcount(m_pHandle, &resultVertexCount));
return resultVertexCount;
}
/**
* CMeshObject::GetTriangleCount - Returns the triangle count of a mesh object.
* @return filled with the triangle count.
*/
Lib3MF_uint32 CMeshObject::GetTriangleCount()
{
Lib3MF_uint32 resultVertexCount = 0;
CheckError(lib3mf_meshobject_gettrianglecount(m_pHandle, &resultVertexCount));
return resultVertexCount;
}
/**
* CMeshObject::GetVertex - Returns the vertex count of a mesh object.
* @param[in] nIndex - Index of the vertex (0 to vertexcount - 1)
* @return filled with the vertex coordinates.
*/
sPosition CMeshObject::GetVertex(const Lib3MF_uint32 nIndex)
{
sPosition resultCoordinates;
CheckError(lib3mf_meshobject_getvertex(m_pHandle, nIndex, &resultCoordinates));
return resultCoordinates;
}
/**
* CMeshObject::SetVertex - Sets the coordinates of a single vertex of a mesh object
* @param[in] nIndex - Index of the vertex (0 to vertexcount - 1)
* @param[in] Coordinates - contains the vertex coordinates.
*/
void CMeshObject::SetVertex(const Lib3MF_uint32 nIndex, const sPosition & Coordinates)
{
CheckError(lib3mf_meshobject_setvertex(m_pHandle, nIndex, &Coordinates));
}
/**
* CMeshObject::AddVertex - Adds a single vertex to a mesh object
* @param[in] Coordinates - contains the vertex coordinates.
* @return Index of the new vertex
*/
Lib3MF_uint32 CMeshObject::AddVertex(const sPosition & Coordinates)
{
Lib3MF_uint32 resultNewIndex = 0;
CheckError(lib3mf_meshobject_addvertex(m_pHandle, &Coordinates, &resultNewIndex));
return resultNewIndex;
}
/**
* CMeshObject::GetVertices - Obtains all vertex positions of a mesh object
* @param[out] VerticesBuffer - contains the vertex coordinates.
*/
void CMeshObject::GetVertices(std::vector<sPosition> & VerticesBuffer)
{
Lib3MF_uint64 elementsNeededVertices = 0;
Lib3MF_uint64 elementsWrittenVertices = 0;
CheckError(lib3mf_meshobject_getvertices(m_pHandle, 0, &elementsNeededVertices, nullptr));
VerticesBuffer.resize((size_t) elementsNeededVertices);
CheckError(lib3mf_meshobject_getvertices(m_pHandle, elementsNeededVertices, &elementsWrittenVertices, VerticesBuffer.data()));
}
/**
* CMeshObject::GetTriangle - Returns indices of a single triangle of a mesh object.
* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1)
* @return filled with the triangle indices.
*/
sTriangle CMeshObject::GetTriangle(const Lib3MF_uint32 nIndex)
{
sTriangle resultIndices;
CheckError(lib3mf_meshobject_gettriangle(m_pHandle, nIndex, &resultIndices));
return resultIndices;
}
/**
* CMeshObject::SetTriangle - Sets the indices of a single triangle of a mesh object.
* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1)
* @param[in] Indices - contains the triangle indices.
*/
void CMeshObject::SetTriangle(const Lib3MF_uint32 nIndex, const sTriangle & Indices)
{
CheckError(lib3mf_meshobject_settriangle(m_pHandle, nIndex, &Indices));
}
/**
* CMeshObject::AddTriangle - Adds a single triangle to a mesh object
* @param[in] Indices - contains the triangle indices.
* @return Index of the new triangle
*/
Lib3MF_uint32 CMeshObject::AddTriangle(const sTriangle & Indices)
{
Lib3MF_uint32 resultNewIndex = 0;
CheckError(lib3mf_meshobject_addtriangle(m_pHandle, &Indices, &resultNewIndex));
return resultNewIndex;
}
/**
* CMeshObject::GetTriangleIndices - Get all triangles of a mesh object
* @param[out] IndicesBuffer - contains the triangle indices.
*/
void CMeshObject::GetTriangleIndices(std::vector<sTriangle> & IndicesBuffer)
{
Lib3MF_uint64 elementsNeededIndices = 0;
Lib3MF_uint64 elementsWrittenIndices = 0;
CheckError(lib3mf_meshobject_gettriangleindices(m_pHandle, 0, &elementsNeededIndices, nullptr));
IndicesBuffer.resize((size_t) elementsNeededIndices);
CheckError(lib3mf_meshobject_gettriangleindices(m_pHandle, elementsNeededIndices, &elementsWrittenIndices, IndicesBuffer.data()));
}
/**
* CMeshObject::SetObjectLevelProperty - Sets the property at the object-level of the mesh object.
* @param[in] nUniqueResourceID - the object-level Property UniqueResourceID.
* @param[in] nPropertyID - the object-level PropertyID.
*/
void CMeshObject::SetObjectLevelProperty(const Lib3MF_uint32 nUniqueResourceID, const Lib3MF_uint32 nPropertyID)
{
CheckError(lib3mf_meshobject_setobjectlevelproperty(m_pHandle, nUniqueResourceID, nPropertyID));
}
/**
* CMeshObject::GetObjectLevelProperty - Gets the property at the object-level of the mesh object.
* @param[out] nUniqueResourceID - the object-level Property UniqueResourceID.
* @param[out] nPropertyID - the object-level PropertyID.
* @return Has an object-level property been specified?
*/
bool CMeshObject::GetObjectLevelProperty(Lib3MF_uint32 & nUniqueResourceID, Lib3MF_uint32 & nPropertyID)
{
bool resultHasObjectLevelProperty = 0;
CheckError(lib3mf_meshobject_getobjectlevelproperty(m_pHandle, &nUniqueResourceID, &nPropertyID, &resultHasObjectLevelProperty));
return resultHasObjectLevelProperty;
}
/**
* CMeshObject::SetTriangleProperties - Sets the properties of a single triangle of a mesh object.
* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1)
* @param[in] Properties - contains the triangle properties.
*/
void CMeshObject::SetTriangleProperties(const Lib3MF_uint32 nIndex, const sTriangleProperties & Properties)
{
CheckError(lib3mf_meshobject_settriangleproperties(m_pHandle, nIndex, &Properties));
}
/**
* CMeshObject::GetTriangleProperties - Gets the properties of a single triangle of a mesh object.
* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1)
* @param[out] Property - returns the triangle properties.
*/
void CMeshObject::GetTriangleProperties(const Lib3MF_uint32 nIndex, sTriangleProperties & Property)
{
CheckError(lib3mf_meshobject_gettriangleproperties(m_pHandle, nIndex, &Property));
}
/**
* CMeshObject::SetAllTriangleProperties - Sets the properties of all triangles of a mesh object. Sets the object level property to the first entry of the passed triangle properties, if not yet specified.
* @param[in] PropertiesArrayBuffer - contains the triangle properties array. Must have trianglecount elements.
*/
void CMeshObject::SetAllTriangleProperties(const CInputVector<sTriangleProperties> & PropertiesArrayBuffer)
{
CheckError(lib3mf_meshobject_setalltriangleproperties(m_pHandle, (Lib3MF_uint64)PropertiesArrayBuffer.size(), PropertiesArrayBuffer.data()));
}
/**
* CMeshObject::GetAllTriangleProperties - Gets the properties of all triangles of a mesh object.
* @param[out] PropertiesArrayBuffer - returns the triangle properties array. Must have trianglecount elements.
*/
void CMeshObject::GetAllTriangleProperties(std::vector<sTriangleProperties> & PropertiesArrayBuffer)
{
Lib3MF_uint64 elementsNeededPropertiesArray = 0;
Lib3MF_uint64 elementsWrittenPropertiesArray = 0;
CheckError(lib3mf_meshobject_getalltriangleproperties(m_pHandle, 0, &elementsNeededPropertiesArray, nullptr));
PropertiesArrayBuffer.resize((size_t) elementsNeededPropertiesArray);
CheckError(lib3mf_meshobject_getalltriangleproperties(m_pHandle, elementsNeededPropertiesArray, &elementsWrittenPropertiesArray, PropertiesArrayBuffer.data()));
}
/**
* CMeshObject::ClearAllProperties - Clears all properties of this mesh object (triangle and object-level).
*/
void CMeshObject::ClearAllProperties()
{
CheckError(lib3mf_meshobject_clearallproperties(m_pHandle));
}
/**
* CMeshObject::SetGeometry - Set all triangles of a mesh object
* @param[in] VerticesBuffer - contains the positions.
* @param[in] IndicesBuffer - contains the triangle indices.
*/
void CMeshObject::SetGeometry(const CInputVector<sPosition> & VerticesBuffer, const CInputVector<sTriangle> & IndicesBuffer)
{
CheckError(lib3mf_meshobject_setgeometry(m_pHandle, (Lib3MF_uint64)VerticesBuffer.size(), VerticesBuffer.data(), (Lib3MF_uint64)IndicesBuffer.size(), IndicesBuffer.data()));
}
/**
* CMeshObject::IsManifoldAndOriented - Retrieves, if an object describes a topologically oriented and manifold mesh, according to the core spec.
* @return returns, if the object is oriented and manifold.
*/
bool CMeshObject::IsManifoldAndOriented()
{
bool resultIsManifoldAndOriented = 0;
CheckError(lib3mf_meshobject_ismanifoldandoriented(m_pHandle, &resultIsManifoldAndOriented));
return resultIsManifoldAndOriented;
}
/**
* CMeshObject::BeamLattice - Retrieves the BeamLattice within this MeshObject.
* @return the BeamLattice within this MeshObject
*/
PBeamLattice CMeshObject::BeamLattice()
{
Lib3MFHandle hTheBeamLattice = nullptr;
CheckError(lib3mf_meshobject_beamlattice(m_pHandle, &hTheBeamLattice));
if (!hTheBeamLattice) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBeamLattice>(m_pWrapper, hTheBeamLattice);
}
/**
* Method definitions for class CBeamLattice
*/
/**
* CBeamLattice::GetMinLength - Returns the minimal length of beams for the beamlattice.
* @return minimal length of beams for the beamlattice
*/
Lib3MF_double CBeamLattice::GetMinLength()
{
Lib3MF_double resultMinLength = 0;
CheckError(lib3mf_beamlattice_getminlength(m_pHandle, &resultMinLength));
return resultMinLength;
}
/**
* CBeamLattice::SetMinLength - Sets the minimal length of beams for the beamlattice.
* @param[in] dMinLength - minimal length of beams for the beamlattice
*/
void CBeamLattice::SetMinLength(const Lib3MF_double dMinLength)
{
CheckError(lib3mf_beamlattice_setminlength(m_pHandle, dMinLength));
}
/**
* CBeamLattice::GetClipping - Returns the clipping mode and the clipping-mesh for the beamlattice of this mesh.
* @param[out] eClipMode - contains the clip mode of this mesh
* @param[out] nUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object or an undefined value if pClipMode is MODELBEAMLATTICECLIPMODE_NONE
*/
void CBeamLattice::GetClipping(eBeamLatticeClipMode & eClipMode, Lib3MF_uint32 & nUniqueResourceID)
{
CheckError(lib3mf_beamlattice_getclipping(m_pHandle, &eClipMode, &nUniqueResourceID));
}
/**
* CBeamLattice::SetClipping - Sets the clipping mode and the clipping-mesh for the beamlattice of this mesh.
* @param[in] eClipMode - contains the clip mode of this mesh
* @param[in] nUniqueResourceID - the UniqueResourceID of the clipping mesh-object. This mesh-object has to be defined before setting the Clipping.
*/
void CBeamLattice::SetClipping(const eBeamLatticeClipMode eClipMode, const Lib3MF_uint32 nUniqueResourceID)
{
CheckError(lib3mf_beamlattice_setclipping(m_pHandle, eClipMode, nUniqueResourceID));
}
/**
* CBeamLattice::GetRepresentation - Returns the representation-mesh for the beamlattice of this mesh.
* @return flag whether the beamlattice has a representation mesh.
* @param[out] nUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object.
*/
bool CBeamLattice::GetRepresentation(Lib3MF_uint32 & nUniqueResourceID)
{
bool resultHasRepresentation = 0;
CheckError(lib3mf_beamlattice_getrepresentation(m_pHandle, &resultHasRepresentation, &nUniqueResourceID));
return resultHasRepresentation;
}
/**
* CBeamLattice::SetRepresentation - Sets the representation-mesh for the beamlattice of this mesh.
* @param[in] nUniqueResourceID - the UniqueResourceID of the representation mesh-object. This mesh-object has to be defined before setting the representation.
*/
void CBeamLattice::SetRepresentation(const Lib3MF_uint32 nUniqueResourceID)
{
CheckError(lib3mf_beamlattice_setrepresentation(m_pHandle, nUniqueResourceID));
}
/**
* CBeamLattice::GetBallOptions - Returns the ball mode and the default ball radius for the beamlattice of this mesh.
* @param[out] eBallMode - contains the ball mode of this mesh
* @param[out] dBallRadius - default ball radius of balls for the beamlattice
*/
void CBeamLattice::GetBallOptions(eBeamLatticeBallMode & eBallMode, Lib3MF_double & dBallRadius)
{
CheckError(lib3mf_beamlattice_getballoptions(m_pHandle, &eBallMode, &dBallRadius));
}
/**
* CBeamLattice::SetBallOptions - Sets the ball mode and thedefault ball radius for the beamlattice.
* @param[in] eBallMode - contains the ball mode of this mesh
* @param[in] dBallRadius - default ball radius of balls for the beamlattice
*/
void CBeamLattice::SetBallOptions(const eBeamLatticeBallMode eBallMode, const Lib3MF_double dBallRadius)
{
CheckError(lib3mf_beamlattice_setballoptions(m_pHandle, eBallMode, dBallRadius));
}
/**
* CBeamLattice::GetBeamCount - Returns the beam count of a mesh object.
* @return filled with the beam count.
*/
Lib3MF_uint32 CBeamLattice::GetBeamCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_beamlattice_getbeamcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CBeamLattice::GetBeam - Returns indices, radii and capmodes of a single beam of a mesh object.
* @param[in] nIndex - Index of the beam (0 to beamcount - 1).
* @return filled with the beam indices, radii and capmodes.
*/
sBeam CBeamLattice::GetBeam(const Lib3MF_uint32 nIndex)
{
sBeam resultBeamInfo;
CheckError(lib3mf_beamlattice_getbeam(m_pHandle, nIndex, &resultBeamInfo));
return resultBeamInfo;
}
/**
* CBeamLattice::AddBeam - Adds a single beam to a mesh object.
* @param[in] BeamInfo - contains the node indices, radii and capmodes.
* @return filled with the new Index of the beam.
*/
Lib3MF_uint32 CBeamLattice::AddBeam(const sBeam & BeamInfo)
{
Lib3MF_uint32 resultIndex = 0;
CheckError(lib3mf_beamlattice_addbeam(m_pHandle, &BeamInfo, &resultIndex));
return resultIndex;
}
/**
* CBeamLattice::SetBeam - Sets the indices, radii and capmodes of a single beam of a mesh object.
* @param[in] nIndex - Index of the beam (0 to beamcount - 1).
* @param[in] BeamInfo - filled with the beam indices, radii and capmodes.
*/
void CBeamLattice::SetBeam(const Lib3MF_uint32 nIndex, const sBeam & BeamInfo)
{
CheckError(lib3mf_beamlattice_setbeam(m_pHandle, nIndex, &BeamInfo));
}
/**
* CBeamLattice::SetBeams - Sets all beam indices, radii and capmodes of a mesh object.
* @param[in] BeamInfoBuffer - contains information of a number of beams
*/
void CBeamLattice::SetBeams(const CInputVector<sBeam> & BeamInfoBuffer)
{
CheckError(lib3mf_beamlattice_setbeams(m_pHandle, (Lib3MF_uint64)BeamInfoBuffer.size(), BeamInfoBuffer.data()));
}
/**
* CBeamLattice::GetBeams - obtains all beam indices, radii and capmodes of a mesh object.
* @param[out] BeamInfoBuffer - contains information of all beams
*/
void CBeamLattice::GetBeams(std::vector<sBeam> & BeamInfoBuffer)
{
Lib3MF_uint64 elementsNeededBeamInfo = 0;
Lib3MF_uint64 elementsWrittenBeamInfo = 0;
CheckError(lib3mf_beamlattice_getbeams(m_pHandle, 0, &elementsNeededBeamInfo, nullptr));
BeamInfoBuffer.resize((size_t) elementsNeededBeamInfo);
CheckError(lib3mf_beamlattice_getbeams(m_pHandle, elementsNeededBeamInfo, &elementsWrittenBeamInfo, BeamInfoBuffer.data()));
}
/**
* CBeamLattice::GetBallCount - Returns the ball count of a mesh object.
* @return filled with the ball count.
*/
Lib3MF_uint32 CBeamLattice::GetBallCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_beamlattice_getballcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CBeamLattice::GetBall - Returns index and radius of a single ball of a mesh object.
* @param[in] nIndex - Index of the ball (0 to ballcount - 1).
* @return filled with the ball node index and radius.
*/
sBall CBeamLattice::GetBall(const Lib3MF_uint32 nIndex)
{
sBall resultBallInfo;
CheckError(lib3mf_beamlattice_getball(m_pHandle, nIndex, &resultBallInfo));
return resultBallInfo;
}
/**
* CBeamLattice::AddBall - Adds a single ball to a mesh object.
* @param[in] BallInfo - contains the node index and radius.
* @return filled with the new Index of the ball.
*/
Lib3MF_uint32 CBeamLattice::AddBall(const sBall & BallInfo)
{
Lib3MF_uint32 resultIndex = 0;
CheckError(lib3mf_beamlattice_addball(m_pHandle, &BallInfo, &resultIndex));
return resultIndex;
}
/**
* CBeamLattice::SetBall - Sets the index and radius of a single ball of a mesh object.
* @param[in] nIndex - Index of the ball (0 to ballcount - 1).
* @param[in] BallInfo - filled with the ball node index and radius.
*/
void CBeamLattice::SetBall(const Lib3MF_uint32 nIndex, const sBall & BallInfo)
{
CheckError(lib3mf_beamlattice_setball(m_pHandle, nIndex, &BallInfo));
}
/**
* CBeamLattice::SetBalls - Sets all ball indices and radii of a mesh object.
* @param[in] BallInfoBuffer - contains information of a number of balls
*/
void CBeamLattice::SetBalls(const CInputVector<sBall> & BallInfoBuffer)
{
CheckError(lib3mf_beamlattice_setballs(m_pHandle, (Lib3MF_uint64)BallInfoBuffer.size(), BallInfoBuffer.data()));
}
/**
* CBeamLattice::GetBalls - obtains all ball indices and radii of a mesh object.
* @param[out] BallInfoBuffer - contains information of all balls
*/
void CBeamLattice::GetBalls(std::vector<sBall> & BallInfoBuffer)
{
Lib3MF_uint64 elementsNeededBallInfo = 0;
Lib3MF_uint64 elementsWrittenBallInfo = 0;
CheckError(lib3mf_beamlattice_getballs(m_pHandle, 0, &elementsNeededBallInfo, nullptr));
BallInfoBuffer.resize((size_t) elementsNeededBallInfo);
CheckError(lib3mf_beamlattice_getballs(m_pHandle, elementsNeededBallInfo, &elementsWrittenBallInfo, BallInfoBuffer.data()));
}
/**
* CBeamLattice::GetBeamSetCount - Returns the number of beamsets of a mesh object.
* @return filled with the beamset count.
*/
Lib3MF_uint32 CBeamLattice::GetBeamSetCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_beamlattice_getbeamsetcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CBeamLattice::AddBeamSet - Adds an empty beamset to a mesh object
* @return the new beamset
*/
PBeamSet CBeamLattice::AddBeamSet()
{
Lib3MFHandle hBeamSet = nullptr;
CheckError(lib3mf_beamlattice_addbeamset(m_pHandle, &hBeamSet));
if (!hBeamSet) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBeamSet>(m_pWrapper, hBeamSet);
}
/**
* CBeamLattice::GetBeamSet - Returns a beamset of a mesh object
* @param[in] nIndex - index of the requested beamset (0 ... beamsetcount-1).
* @return the requested beamset
*/
PBeamSet CBeamLattice::GetBeamSet(const Lib3MF_uint32 nIndex)
{
Lib3MFHandle hBeamSet = nullptr;
CheckError(lib3mf_beamlattice_getbeamset(m_pHandle, nIndex, &hBeamSet));
if (!hBeamSet) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBeamSet>(m_pWrapper, hBeamSet);
}
/**
* Method definitions for class CComponent
*/
/**
* CComponent::GetObjectResource - Returns the Resource Instance of the component.
* @return filled with the Resource Instance.
*/
PObject CComponent::GetObjectResource()
{
Lib3MFHandle hObjectResource = nullptr;
CheckError(lib3mf_component_getobjectresource(m_pHandle, &hObjectResource));
if (!hObjectResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CObject>(m_pWrapper, hObjectResource);
}
/**
* CComponent::GetObjectResourceID - Returns the UniqueResourceID of the component.
* @return returns the UniqueResourceID.
*/
Lib3MF_uint32 CComponent::GetObjectResourceID()
{
Lib3MF_uint32 resultUniqueResourceID = 0;
CheckError(lib3mf_component_getobjectresourceid(m_pHandle, &resultUniqueResourceID));
return resultUniqueResourceID;
}
/**
* CComponent::GetUUID - returns, whether a component has a UUID and, if true, the component's UUID
* @param[out] bHasUUID - flag whether the component has a UUID
* @return the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx'
*/
std::string CComponent::GetUUID(bool & bHasUUID)
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_component_getuuid(m_pHandle, &bHasUUID, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_component_getuuid(m_pHandle, &bHasUUID, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* CComponent::SetUUID - sets the component's UUID
* @param[in] sUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx'
*/
void CComponent::SetUUID(const std::string & sUUID)
{
CheckError(lib3mf_component_setuuid(m_pHandle, sUUID.c_str()));
}
/**
* CComponent::HasTransform - Returns, if the component has a different transformation than the identity matrix
* @return if true is returned, the transformation is not equal than the identity
*/
bool CComponent::HasTransform()
{
bool resultHasTransform = 0;
CheckError(lib3mf_component_hastransform(m_pHandle, &resultHasTransform));
return resultHasTransform;
}
/**
* CComponent::GetTransform - Returns the transformation matrix of the component.
* @return filled with the component transformation matrix
*/
sTransform CComponent::GetTransform()
{
sTransform resultTransform;
CheckError(lib3mf_component_gettransform(m_pHandle, &resultTransform));
return resultTransform;
}
/**
* CComponent::SetTransform - Sets the transformation matrix of the component.
* @param[in] Transform - new transformation matrix
*/
void CComponent::SetTransform(const sTransform & Transform)
{
CheckError(lib3mf_component_settransform(m_pHandle, &Transform));
}
/**
* Method definitions for class CComponentsObject
*/
/**
* CComponentsObject::AddComponent - Adds a new component to a components object.
* @param[in] pObjectResource - object to add as component. Must not lead to circular references!
* @param[in] Transform - optional transform matrix for the component.
* @return new component instance
*/
PComponent CComponentsObject::AddComponent(CObject * pObjectResource, const sTransform & Transform)
{
Lib3MFHandle hObjectResource = nullptr;
if (pObjectResource != nullptr) {
hObjectResource = pObjectResource->GetHandle();
};
Lib3MFHandle hComponentInstance = nullptr;
CheckError(lib3mf_componentsobject_addcomponent(m_pHandle, hObjectResource, &Transform, &hComponentInstance));
if (!hComponentInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CComponent>(m_pWrapper, hComponentInstance);
}
/**
* CComponentsObject::GetComponent - Retrieves a component from a component object.
* @param[in] nIndex - index of the component to retrieve (0 to componentcount - 1)
* @return component instance
*/
PComponent CComponentsObject::GetComponent(const Lib3MF_uint32 nIndex)
{
Lib3MFHandle hComponentInstance = nullptr;
CheckError(lib3mf_componentsobject_getcomponent(m_pHandle, nIndex, &hComponentInstance));
if (!hComponentInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CComponent>(m_pWrapper, hComponentInstance);
}
/**
* CComponentsObject::GetComponentCount - Retrieves a component count of a component object.
* @return returns the component count
*/
Lib3MF_uint32 CComponentsObject::GetComponentCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_componentsobject_getcomponentcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* Method definitions for class CBeamSet
*/
/**
* CBeamSet::SetName - Sets a beamset's name string
* @param[in] sName - new name of the beamset.
*/
void CBeamSet::SetName(const std::string & sName)
{
CheckError(lib3mf_beamset_setname(m_pHandle, sName.c_str()));
}
/**
* CBeamSet::GetName - Retrieves a beamset's name string
* @return returns the name of the beamset.
*/
std::string CBeamSet::GetName()
{
Lib3MF_uint32 bytesNeededName = 0;
Lib3MF_uint32 bytesWrittenName = 0;
CheckError(lib3mf_beamset_getname(m_pHandle, 0, &bytesNeededName, nullptr));
std::vector<char> bufferName(bytesNeededName);
CheckError(lib3mf_beamset_getname(m_pHandle, bytesNeededName, &bytesWrittenName, &bufferName[0]));
return std::string(&bufferName[0]);
}
/**
* CBeamSet::SetIdentifier - Sets a beamset's identifier string
* @param[in] sIdentifier - new name of the beamset.
*/
void CBeamSet::SetIdentifier(const std::string & sIdentifier)
{
CheckError(lib3mf_beamset_setidentifier(m_pHandle, sIdentifier.c_str()));
}
/**
* CBeamSet::GetIdentifier - Retrieves a beamset's identifier string
* @return returns the identifier of the beamset.
*/
std::string CBeamSet::GetIdentifier()
{
Lib3MF_uint32 bytesNeededIdentifier = 0;
Lib3MF_uint32 bytesWrittenIdentifier = 0;
CheckError(lib3mf_beamset_getidentifier(m_pHandle, 0, &bytesNeededIdentifier, nullptr));
std::vector<char> bufferIdentifier(bytesNeededIdentifier);
CheckError(lib3mf_beamset_getidentifier(m_pHandle, bytesNeededIdentifier, &bytesWrittenIdentifier, &bufferIdentifier[0]));
return std::string(&bufferIdentifier[0]);
}
/**
* CBeamSet::GetReferenceCount - Retrieves the reference count of a beamset
* @return returns the reference count
*/
Lib3MF_uint32 CBeamSet::GetReferenceCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_beamset_getreferencecount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CBeamSet::SetReferences - Sets the references of a beamset
* @param[in] ReferencesBuffer - the new indices of all beams in this beamset
*/
void CBeamSet::SetReferences(const CInputVector<Lib3MF_uint32> & ReferencesBuffer)
{
CheckError(lib3mf_beamset_setreferences(m_pHandle, (Lib3MF_uint64)ReferencesBuffer.size(), ReferencesBuffer.data()));
}
/**
* CBeamSet::GetReferences - Retrieves the references of a beamset
* @param[out] ReferencesBuffer - retrieves the indices of all beams in this beamset
*/
void CBeamSet::GetReferences(std::vector<Lib3MF_uint32> & ReferencesBuffer)
{
Lib3MF_uint64 elementsNeededReferences = 0;
Lib3MF_uint64 elementsWrittenReferences = 0;
CheckError(lib3mf_beamset_getreferences(m_pHandle, 0, &elementsNeededReferences, nullptr));
ReferencesBuffer.resize((size_t) elementsNeededReferences);
CheckError(lib3mf_beamset_getreferences(m_pHandle, elementsNeededReferences, &elementsWrittenReferences, ReferencesBuffer.data()));
}
/**
* CBeamSet::GetBallReferenceCount - Retrieves the ball reference count of a beamset
* @return returns the ball reference count
*/
Lib3MF_uint32 CBeamSet::GetBallReferenceCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_beamset_getballreferencecount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CBeamSet::SetBallReferences - Sets the ball references of a beamset
* @param[in] BallReferencesBuffer - the new indices of all balls in this beamset
*/
void CBeamSet::SetBallReferences(const CInputVector<Lib3MF_uint32> & BallReferencesBuffer)
{
CheckError(lib3mf_beamset_setballreferences(m_pHandle, (Lib3MF_uint64)BallReferencesBuffer.size(), BallReferencesBuffer.data()));
}
/**
* CBeamSet::GetBallReferences - Retrieves the ball references of a beamset
* @param[out] BallReferencesBuffer - retrieves the indices of all balls in this beamset
*/
void CBeamSet::GetBallReferences(std::vector<Lib3MF_uint32> & BallReferencesBuffer)
{
Lib3MF_uint64 elementsNeededBallReferences = 0;
Lib3MF_uint64 elementsWrittenBallReferences = 0;
CheckError(lib3mf_beamset_getballreferences(m_pHandle, 0, &elementsNeededBallReferences, nullptr));
BallReferencesBuffer.resize((size_t) elementsNeededBallReferences);
CheckError(lib3mf_beamset_getballreferences(m_pHandle, elementsNeededBallReferences, &elementsWrittenBallReferences, BallReferencesBuffer.data()));
}
/**
* Method definitions for class CBaseMaterialGroup
*/
/**
* CBaseMaterialGroup::GetCount - Retrieves the count of base materials in the material group.
* @return returns the count of base materials.
*/
Lib3MF_uint32 CBaseMaterialGroup::GetCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_basematerialgroup_getcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CBaseMaterialGroup::GetAllPropertyIDs - returns all the PropertyIDs of all materials in this group
* @param[out] PropertyIDsBuffer - PropertyID of the material in the material group.
*/
void CBaseMaterialGroup::GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint64 elementsNeededPropertyIDs = 0;
Lib3MF_uint64 elementsWrittenPropertyIDs = 0;
CheckError(lib3mf_basematerialgroup_getallpropertyids(m_pHandle, 0, &elementsNeededPropertyIDs, nullptr));
PropertyIDsBuffer.resize((size_t) elementsNeededPropertyIDs);
CheckError(lib3mf_basematerialgroup_getallpropertyids(m_pHandle, elementsNeededPropertyIDs, &elementsWrittenPropertyIDs, PropertyIDsBuffer.data()));
}
/**
* CBaseMaterialGroup::AddMaterial - Adds a new material to the material group
* @param[in] sName - new name of the base material.
* @param[in] DisplayColor - Display color of the material
* @return returns new PropertyID of the new material in the material group.
*/
Lib3MF_uint32 CBaseMaterialGroup::AddMaterial(const std::string & sName, const sColor & DisplayColor)
{
Lib3MF_uint32 resultPropertyID = 0;
CheckError(lib3mf_basematerialgroup_addmaterial(m_pHandle, sName.c_str(), &DisplayColor, &resultPropertyID));
return resultPropertyID;
}
/**
* CBaseMaterialGroup::RemoveMaterial - Removes a material from the material group.
* @param[in] nPropertyID - PropertyID of the material in the material group.
*/
void CBaseMaterialGroup::RemoveMaterial(const Lib3MF_uint32 nPropertyID)
{
CheckError(lib3mf_basematerialgroup_removematerial(m_pHandle, nPropertyID));
}
/**
* CBaseMaterialGroup::GetName - Returns the base material's name
* @param[in] nPropertyID - PropertyID of the material in the material group.
* @return returns the name of the base material.
*/
std::string CBaseMaterialGroup::GetName(const Lib3MF_uint32 nPropertyID)
{
Lib3MF_uint32 bytesNeededName = 0;
Lib3MF_uint32 bytesWrittenName = 0;
CheckError(lib3mf_basematerialgroup_getname(m_pHandle, nPropertyID, 0, &bytesNeededName, nullptr));
std::vector<char> bufferName(bytesNeededName);
CheckError(lib3mf_basematerialgroup_getname(m_pHandle, nPropertyID, bytesNeededName, &bytesWrittenName, &bufferName[0]));
return std::string(&bufferName[0]);
}
/**
* CBaseMaterialGroup::SetName - Sets a base material's name
* @param[in] nPropertyID - PropertyID of the material in the material group.
* @param[in] sName - new name of the base material.
*/
void CBaseMaterialGroup::SetName(const Lib3MF_uint32 nPropertyID, const std::string & sName)
{
CheckError(lib3mf_basematerialgroup_setname(m_pHandle, nPropertyID, sName.c_str()));
}
/**
* CBaseMaterialGroup::SetDisplayColor - Sets a base material's display color.
* @param[in] nPropertyID - PropertyID of the material in the material group.
* @param[in] TheColor - The base material's display color
*/
void CBaseMaterialGroup::SetDisplayColor(const Lib3MF_uint32 nPropertyID, const sColor & TheColor)
{
CheckError(lib3mf_basematerialgroup_setdisplaycolor(m_pHandle, nPropertyID, &TheColor));
}
/**
* CBaseMaterialGroup::GetDisplayColor - Returns a base material's display color.
* @param[in] nPropertyID - PropertyID of the material in the material group.
* @return The base material's display color
*/
sColor CBaseMaterialGroup::GetDisplayColor(const Lib3MF_uint32 nPropertyID)
{
sColor resultTheColor;
CheckError(lib3mf_basematerialgroup_getdisplaycolor(m_pHandle, nPropertyID, &resultTheColor));
return resultTheColor;
}
/**
* Method definitions for class CColorGroup
*/
/**
* CColorGroup::GetCount - Retrieves the count of base materials in this Color Group.
* @return returns the count of colors within this color group.
*/
Lib3MF_uint32 CColorGroup::GetCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_colorgroup_getcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CColorGroup::GetAllPropertyIDs - returns all the PropertyIDs of all colors within this group
* @param[out] PropertyIDsBuffer - PropertyID of the color in the color group.
*/
void CColorGroup::GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint64 elementsNeededPropertyIDs = 0;
Lib3MF_uint64 elementsWrittenPropertyIDs = 0;
CheckError(lib3mf_colorgroup_getallpropertyids(m_pHandle, 0, &elementsNeededPropertyIDs, nullptr));
PropertyIDsBuffer.resize((size_t) elementsNeededPropertyIDs);
CheckError(lib3mf_colorgroup_getallpropertyids(m_pHandle, elementsNeededPropertyIDs, &elementsWrittenPropertyIDs, PropertyIDsBuffer.data()));
}
/**
* CColorGroup::AddColor - Adds a new value.
* @param[in] TheColor - The new color
* @return PropertyID of the new color within this color group.
*/
Lib3MF_uint32 CColorGroup::AddColor(const sColor & TheColor)
{
Lib3MF_uint32 resultPropertyID = 0;
CheckError(lib3mf_colorgroup_addcolor(m_pHandle, &TheColor, &resultPropertyID));
return resultPropertyID;
}
/**
* CColorGroup::RemoveColor - Removes a color from the color group.
* @param[in] nPropertyID - PropertyID of the color to be removed from the color group.
*/
void CColorGroup::RemoveColor(const Lib3MF_uint32 nPropertyID)
{
CheckError(lib3mf_colorgroup_removecolor(m_pHandle, nPropertyID));
}
/**
* CColorGroup::SetColor - Sets a color value.
* @param[in] nPropertyID - PropertyID of a color within this color group.
* @param[in] TheColor - The color
*/
void CColorGroup::SetColor(const Lib3MF_uint32 nPropertyID, const sColor & TheColor)
{
CheckError(lib3mf_colorgroup_setcolor(m_pHandle, nPropertyID, &TheColor));
}
/**
* CColorGroup::GetColor - Sets a color value.
* @param[in] nPropertyID - PropertyID of a color within this color group.
* @return The color
*/
sColor CColorGroup::GetColor(const Lib3MF_uint32 nPropertyID)
{
sColor resultTheColor;
CheckError(lib3mf_colorgroup_getcolor(m_pHandle, nPropertyID, &resultTheColor));
return resultTheColor;
}
/**
* Method definitions for class CTexture2DGroup
*/
/**
* CTexture2DGroup::GetCount - Retrieves the count of tex2coords in the Texture2DGroup.
* @return returns the count of tex2coords.
*/
Lib3MF_uint32 CTexture2DGroup::GetCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_texture2dgroup_getcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CTexture2DGroup::GetAllPropertyIDs - returns all the PropertyIDs of all tex2coords in this Texture2DGroup
* @param[out] PropertyIDsBuffer - PropertyID of the tex2coords in the Texture2DGroup.
*/
void CTexture2DGroup::GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint64 elementsNeededPropertyIDs = 0;
Lib3MF_uint64 elementsWrittenPropertyIDs = 0;
CheckError(lib3mf_texture2dgroup_getallpropertyids(m_pHandle, 0, &elementsNeededPropertyIDs, nullptr));
PropertyIDsBuffer.resize((size_t) elementsNeededPropertyIDs);
CheckError(lib3mf_texture2dgroup_getallpropertyids(m_pHandle, elementsNeededPropertyIDs, &elementsWrittenPropertyIDs, PropertyIDsBuffer.data()));
}
/**
* CTexture2DGroup::AddTex2Coord - Adds a new tex2coord to the Texture2DGroup
* @param[in] UVCoordinate - The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture.
* @return returns new PropertyID of the new tex2coord in the Texture2DGroup.
*/
Lib3MF_uint32 CTexture2DGroup::AddTex2Coord(const sTex2Coord & UVCoordinate)
{
Lib3MF_uint32 resultPropertyID = 0;
CheckError(lib3mf_texture2dgroup_addtex2coord(m_pHandle, &UVCoordinate, &resultPropertyID));
return resultPropertyID;
}
/**
* CTexture2DGroup::GetTex2Coord - Obtains a tex2coord to the Texture2DGroup
* @param[in] nPropertyID - the PropertyID of the tex2coord in the Texture2DGroup.
* @return The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture.
*/
sTex2Coord CTexture2DGroup::GetTex2Coord(const Lib3MF_uint32 nPropertyID)
{
sTex2Coord resultUVCoordinate;
CheckError(lib3mf_texture2dgroup_gettex2coord(m_pHandle, nPropertyID, &resultUVCoordinate));
return resultUVCoordinate;
}
/**
* CTexture2DGroup::RemoveTex2Coord - Removes a tex2coords from the Texture2DGroup.
* @param[in] nPropertyID - PropertyID of the tex2coords in the Texture2DGroup.
*/
void CTexture2DGroup::RemoveTex2Coord(const Lib3MF_uint32 nPropertyID)
{
CheckError(lib3mf_texture2dgroup_removetex2coord(m_pHandle, nPropertyID));
}
/**
* CTexture2DGroup::GetTexture2D - Obtains the texture2D instance of this group.
* @return the texture2D instance of this group.
*/
PTexture2D CTexture2DGroup::GetTexture2D()
{
Lib3MFHandle hTexture2DInstance = nullptr;
CheckError(lib3mf_texture2dgroup_gettexture2d(m_pHandle, &hTexture2DInstance));
if (!hTexture2DInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2D>(m_pWrapper, hTexture2DInstance);
}
/**
* Method definitions for class CCompositeMaterials
*/
/**
* CCompositeMaterials::GetCount - Retrieves the count of Composite-s in the CompositeMaterials.
* @return returns the count of Composite-s
*/
Lib3MF_uint32 CCompositeMaterials::GetCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_compositematerials_getcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CCompositeMaterials::GetAllPropertyIDs - returns all the PropertyIDs of all Composite-Mixing Values in this CompositeMaterials
* @param[out] PropertyIDsBuffer - PropertyID of the Composite-Mixing Values in the CompositeMaterials.
*/
void CCompositeMaterials::GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint64 elementsNeededPropertyIDs = 0;
Lib3MF_uint64 elementsWrittenPropertyIDs = 0;
CheckError(lib3mf_compositematerials_getallpropertyids(m_pHandle, 0, &elementsNeededPropertyIDs, nullptr));
PropertyIDsBuffer.resize((size_t) elementsNeededPropertyIDs);
CheckError(lib3mf_compositematerials_getallpropertyids(m_pHandle, elementsNeededPropertyIDs, &elementsWrittenPropertyIDs, PropertyIDsBuffer.data()));
}
/**
* CCompositeMaterials::GetBaseMaterialGroup - Obtains the BaseMaterialGroup instance of this CompositeMaterials.
* @return returns the BaseMaterialGroup instance of this CompositeMaterials
*/
PBaseMaterialGroup CCompositeMaterials::GetBaseMaterialGroup()
{
Lib3MFHandle hBaseMaterialGroupInstance = nullptr;
CheckError(lib3mf_compositematerials_getbasematerialgroup(m_pHandle, &hBaseMaterialGroupInstance));
if (!hBaseMaterialGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBaseMaterialGroup>(m_pWrapper, hBaseMaterialGroupInstance);
}
/**
* CCompositeMaterials::AddComposite - Adds a new Composite-Mixing Values to the CompositeMaterials.
* @param[in] CompositeBuffer - The Composite Constituents to be added as composite
* @return returns new PropertyID of the new Composite in the CompositeMaterials.
*/
Lib3MF_uint32 CCompositeMaterials::AddComposite(const CInputVector<sCompositeConstituent> & CompositeBuffer)
{
Lib3MF_uint32 resultPropertyID = 0;
CheckError(lib3mf_compositematerials_addcomposite(m_pHandle, (Lib3MF_uint64)CompositeBuffer.size(), CompositeBuffer.data(), &resultPropertyID));
return resultPropertyID;
}
/**
* CCompositeMaterials::RemoveComposite - Removes a Composite-Maxing Ratio from the CompositeMaterials.
* @param[in] nPropertyID - PropertyID of the Composite-Mixing Values in the CompositeMaterials to be removed.
*/
void CCompositeMaterials::RemoveComposite(const Lib3MF_uint32 nPropertyID)
{
CheckError(lib3mf_compositematerials_removecomposite(m_pHandle, nPropertyID));
}
/**
* CCompositeMaterials::GetComposite - Obtains a Composite-Maxing Ratio of this CompositeMaterials.
* @param[in] nPropertyID - the PropertyID of the Composite-Maxing Ratio in the CompositeMaterials.
* @param[out] CompositeBuffer - The Composite-Mixing Values with the given PropertyID
*/
void CCompositeMaterials::GetComposite(const Lib3MF_uint32 nPropertyID, std::vector<sCompositeConstituent> & CompositeBuffer)
{
Lib3MF_uint64 elementsNeededComposite = 0;
Lib3MF_uint64 elementsWrittenComposite = 0;
CheckError(lib3mf_compositematerials_getcomposite(m_pHandle, nPropertyID, 0, &elementsNeededComposite, nullptr));
CompositeBuffer.resize((size_t) elementsNeededComposite);
CheckError(lib3mf_compositematerials_getcomposite(m_pHandle, nPropertyID, elementsNeededComposite, &elementsWrittenComposite, CompositeBuffer.data()));
}
/**
* Method definitions for class CMultiPropertyGroup
*/
/**
* CMultiPropertyGroup::GetCount - Retrieves the count of MultiProperty-s in the MultiPropertyGroup.
* @return returns the count of MultiProperty-s
*/
Lib3MF_uint32 CMultiPropertyGroup::GetCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_multipropertygroup_getcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CMultiPropertyGroup::GetAllPropertyIDs - returns all the PropertyIDs of all MultiProperty-s in this MultiPropertyGroup
* @param[out] PropertyIDsBuffer - PropertyID of the MultiProperty-s in the MultiPropertyGroup.
*/
void CMultiPropertyGroup::GetAllPropertyIDs(std::vector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint64 elementsNeededPropertyIDs = 0;
Lib3MF_uint64 elementsWrittenPropertyIDs = 0;
CheckError(lib3mf_multipropertygroup_getallpropertyids(m_pHandle, 0, &elementsNeededPropertyIDs, nullptr));
PropertyIDsBuffer.resize((size_t) elementsNeededPropertyIDs);
CheckError(lib3mf_multipropertygroup_getallpropertyids(m_pHandle, elementsNeededPropertyIDs, &elementsWrittenPropertyIDs, PropertyIDsBuffer.data()));
}
/**
* CMultiPropertyGroup::AddMultiProperty - Adds a new MultiProperty to the MultiPropertyGroup.
* @param[in] PropertyIDsBuffer - The PropertyIDs of the new MultiProperty.
* @return returns the PropertyID of the new MultiProperty in the MultiPropertyGroup.
*/
Lib3MF_uint32 CMultiPropertyGroup::AddMultiProperty(const CInputVector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint32 resultPropertyID = 0;
CheckError(lib3mf_multipropertygroup_addmultiproperty(m_pHandle, (Lib3MF_uint64)PropertyIDsBuffer.size(), PropertyIDsBuffer.data(), &resultPropertyID));
return resultPropertyID;
}
/**
* CMultiPropertyGroup::SetMultiProperty - Sets the PropertyIDs of a MultiProperty.
* @param[in] nPropertyID - the PropertyID of the MultiProperty to be changed.
* @param[in] PropertyIDsBuffer - The new PropertyIDs of the MultiProperty
*/
void CMultiPropertyGroup::SetMultiProperty(const Lib3MF_uint32 nPropertyID, const CInputVector<Lib3MF_uint32> & PropertyIDsBuffer)
{
CheckError(lib3mf_multipropertygroup_setmultiproperty(m_pHandle, nPropertyID, (Lib3MF_uint64)PropertyIDsBuffer.size(), PropertyIDsBuffer.data()));
}
/**
* CMultiPropertyGroup::GetMultiProperty - Obtains the PropertyIDs of a MultiProperty.
* @param[in] nPropertyID - the PropertyID of the MultiProperty to be queried.
* @param[out] PropertyIDsBuffer - The PropertyIDs of the MultiProperty
*/
void CMultiPropertyGroup::GetMultiProperty(const Lib3MF_uint32 nPropertyID, std::vector<Lib3MF_uint32> & PropertyIDsBuffer)
{
Lib3MF_uint64 elementsNeededPropertyIDs = 0;
Lib3MF_uint64 elementsWrittenPropertyIDs = 0;
CheckError(lib3mf_multipropertygroup_getmultiproperty(m_pHandle, nPropertyID, 0, &elementsNeededPropertyIDs, nullptr));
PropertyIDsBuffer.resize((size_t) elementsNeededPropertyIDs);
CheckError(lib3mf_multipropertygroup_getmultiproperty(m_pHandle, nPropertyID, elementsNeededPropertyIDs, &elementsWrittenPropertyIDs, PropertyIDsBuffer.data()));
}
/**
* CMultiPropertyGroup::RemoveMultiProperty - Removes a MultiProperty from this MultiPropertyGroup.
* @param[in] nPropertyID - the PropertyID of the MultiProperty to be removed.
*/
void CMultiPropertyGroup::RemoveMultiProperty(const Lib3MF_uint32 nPropertyID)
{
CheckError(lib3mf_multipropertygroup_removemultiproperty(m_pHandle, nPropertyID));
}
/**
* CMultiPropertyGroup::GetLayerCount - Retrieves the number of layers of this MultiPropertyGroup.
* @return returns the number of layers
*/
Lib3MF_uint32 CMultiPropertyGroup::GetLayerCount()
{
Lib3MF_uint32 resultCount = 0;
CheckError(lib3mf_multipropertygroup_getlayercount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CMultiPropertyGroup::AddLayer - Adds a MultiPropertyLayer to this MultiPropertyGroup.
* @param[in] TheLayer - The MultiPropertyLayer to add to this MultiPropertyGroup
* @return returns the index of this MultiPropertyLayer
*/
Lib3MF_uint32 CMultiPropertyGroup::AddLayer(const sMultiPropertyLayer & TheLayer)
{
Lib3MF_uint32 resultLayerIndex = 0;
CheckError(lib3mf_multipropertygroup_addlayer(m_pHandle, &TheLayer, &resultLayerIndex));
return resultLayerIndex;
}
/**
* CMultiPropertyGroup::GetLayer - Obtains a MultiPropertyLayer of this MultiPropertyGroup.
* @param[in] nLayerIndex - The Index of the MultiPropertyLayer queried
* @return The MultiPropertyLayer with index LayerIndex within MultiPropertyGroup
*/
sMultiPropertyLayer CMultiPropertyGroup::GetLayer(const Lib3MF_uint32 nLayerIndex)
{
sMultiPropertyLayer resultTheLayer;
CheckError(lib3mf_multipropertygroup_getlayer(m_pHandle, nLayerIndex, &resultTheLayer));
return resultTheLayer;
}
/**
* CMultiPropertyGroup::RemoveLayer - Removes a MultiPropertyLayer from this MultiPropertyGroup.
* @param[in] nLayerIndex - The Index of the MultiPropertyLayer to be removed
*/
void CMultiPropertyGroup::RemoveLayer(const Lib3MF_uint32 nLayerIndex)
{
CheckError(lib3mf_multipropertygroup_removelayer(m_pHandle, nLayerIndex));
}
/**
* Method definitions for class CAttachment
*/
/**
* CAttachment::GetPath - Retrieves an attachment's package path. This function will be removed in a later release.
* @return returns the attachment's package path string
*/
std::string CAttachment::GetPath()
{
Lib3MF_uint32 bytesNeededPath = 0;
Lib3MF_uint32 bytesWrittenPath = 0;
CheckError(lib3mf_attachment_getpath(m_pHandle, 0, &bytesNeededPath, nullptr));
std::vector<char> bufferPath(bytesNeededPath);
CheckError(lib3mf_attachment_getpath(m_pHandle, bytesNeededPath, &bytesWrittenPath, &bufferPath[0]));
return std::string(&bufferPath[0]);
}
/**
* CAttachment::SetPath - Sets an attachment's package path. This function will be removed in a later release.
* @param[in] sPath - new path of the attachment.
*/
void CAttachment::SetPath(const std::string & sPath)
{
CheckError(lib3mf_attachment_setpath(m_pHandle, sPath.c_str()));
}
/**
* CAttachment::PackagePart - Returns the PackagePart that is this attachment.
* @return The PackagePart of this attachment.
*/
PPackagePart CAttachment::PackagePart()
{
Lib3MFHandle hPackagePart = nullptr;
CheckError(lib3mf_attachment_packagepart(m_pHandle, &hPackagePart));
if (!hPackagePart) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CPackagePart>(m_pWrapper, hPackagePart);
}
/**
* CAttachment::GetRelationShipType - Retrieves an attachment's relationship type
* @return returns the attachment's package relationship type string
*/
std::string CAttachment::GetRelationShipType()
{
Lib3MF_uint32 bytesNeededPath = 0;
Lib3MF_uint32 bytesWrittenPath = 0;
CheckError(lib3mf_attachment_getrelationshiptype(m_pHandle, 0, &bytesNeededPath, nullptr));
std::vector<char> bufferPath(bytesNeededPath);
CheckError(lib3mf_attachment_getrelationshiptype(m_pHandle, bytesNeededPath, &bytesWrittenPath, &bufferPath[0]));
return std::string(&bufferPath[0]);
}
/**
* CAttachment::SetRelationShipType - Sets an attachment's relationship type.
* @param[in] sPath - new relationship type string.
*/
void CAttachment::SetRelationShipType(const std::string & sPath)
{
CheckError(lib3mf_attachment_setrelationshiptype(m_pHandle, sPath.c_str()));
}
/**
* CAttachment::WriteToFile - Writes out the attachment as file.
* @param[in] sFileName - file to write into.
*/
void CAttachment::WriteToFile(const std::string & sFileName)
{
CheckError(lib3mf_attachment_writetofile(m_pHandle, sFileName.c_str()));
}
/**
* CAttachment::ReadFromFile - Reads an attachment from a file. The path of this file is only read when this attachment is being written as part of the 3MF packege, or via the WriteToFile or WriteToBuffer-methods.
* @param[in] sFileName - file to read from.
*/
void CAttachment::ReadFromFile(const std::string & sFileName)
{
CheckError(lib3mf_attachment_readfromfile(m_pHandle, sFileName.c_str()));
}
/**
* CAttachment::ReadFromCallback - Reads a model and from the data provided by a callback function
* @param[in] pTheReadCallback - Callback to call for reading a data chunk
* @param[in] nStreamSize - number of bytes the callback returns
* @param[in] pTheSeekCallback - Callback to call for seeking in the stream.
* @param[in] pUserData - Userdata that is passed to the callback function
*/
void CAttachment::ReadFromCallback(const ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_attachment_readfromcallback(m_pHandle, pTheReadCallback, nStreamSize, pTheSeekCallback, pUserData));
}
/**
* CAttachment::GetStreamSize - Retrieves the size of the attachment stream
* @return the stream size
*/
Lib3MF_uint64 CAttachment::GetStreamSize()
{
Lib3MF_uint64 resultStreamSize = 0;
CheckError(lib3mf_attachment_getstreamsize(m_pHandle, &resultStreamSize));
return resultStreamSize;
}
/**
* CAttachment::WriteToBuffer - Writes out the attachment into a buffer
* @param[out] BufferBuffer - Buffer to write into
*/
void CAttachment::WriteToBuffer(std::vector<Lib3MF_uint8> & BufferBuffer)
{
Lib3MF_uint64 elementsNeededBuffer = 0;
Lib3MF_uint64 elementsWrittenBuffer = 0;
CheckError(lib3mf_attachment_writetobuffer(m_pHandle, 0, &elementsNeededBuffer, nullptr));
BufferBuffer.resize((size_t) elementsNeededBuffer);
CheckError(lib3mf_attachment_writetobuffer(m_pHandle, elementsNeededBuffer, &elementsWrittenBuffer, BufferBuffer.data()));
}
/**
* CAttachment::ReadFromBuffer - Reads an attachment from a memory buffer
* @param[in] BufferBuffer - Buffer to read from
*/
void CAttachment::ReadFromBuffer(const CInputVector<Lib3MF_uint8> & BufferBuffer)
{
CheckError(lib3mf_attachment_readfrombuffer(m_pHandle, (Lib3MF_uint64)BufferBuffer.size(), BufferBuffer.data()));
}
/**
* Method definitions for class CTexture2D
*/
/**
* CTexture2D::GetAttachment - Retrieves the attachment located at the path of the texture.
* @return attachment that holds the texture's image information.
*/
PAttachment CTexture2D::GetAttachment()
{
Lib3MFHandle hAttachment = nullptr;
CheckError(lib3mf_texture2d_getattachment(m_pHandle, &hAttachment));
if (!hAttachment) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CAttachment>(m_pWrapper, hAttachment);
}
/**
* CTexture2D::SetAttachment - Sets the texture's package path to the path of the attachment.
* @param[in] pAttachment - attachment that holds the texture's image information.
*/
void CTexture2D::SetAttachment(CAttachment * pAttachment)
{
Lib3MFHandle hAttachment = nullptr;
if (pAttachment != nullptr) {
hAttachment = pAttachment->GetHandle();
};
CheckError(lib3mf_texture2d_setattachment(m_pHandle, hAttachment));
}
/**
* CTexture2D::GetContentType - Retrieves a texture's content type.
* @return returns content type enum.
*/
eTextureType CTexture2D::GetContentType()
{
eTextureType resultContentType = (eTextureType) 0;
CheckError(lib3mf_texture2d_getcontenttype(m_pHandle, &resultContentType));
return resultContentType;
}
/**
* CTexture2D::SetContentType - Retrieves a texture's content type.
* @param[in] eContentType - new Content Type
*/
void CTexture2D::SetContentType(const eTextureType eContentType)
{
CheckError(lib3mf_texture2d_setcontenttype(m_pHandle, eContentType));
}
/**
* CTexture2D::GetTileStyleUV - Retrieves a texture's tilestyle type.
* @param[out] eTileStyleU - returns tilestyle type enum.
* @param[out] eTileStyleV - returns tilestyle type enum.
*/
void CTexture2D::GetTileStyleUV(eTextureTileStyle & eTileStyleU, eTextureTileStyle & eTileStyleV)
{
CheckError(lib3mf_texture2d_gettilestyleuv(m_pHandle, &eTileStyleU, &eTileStyleV));
}
/**
* CTexture2D::SetTileStyleUV - Sets a texture's tilestyle type.
* @param[in] eTileStyleU - new tilestyle type enum.
* @param[in] eTileStyleV - new tilestyle type enum.
*/
void CTexture2D::SetTileStyleUV(const eTextureTileStyle eTileStyleU, const eTextureTileStyle eTileStyleV)
{
CheckError(lib3mf_texture2d_settilestyleuv(m_pHandle, eTileStyleU, eTileStyleV));
}
/**
* CTexture2D::GetFilter - Retrieves a texture's filter type.
* @return returns filter type enum.
*/
eTextureFilter CTexture2D::GetFilter()
{
eTextureFilter resultFilter = (eTextureFilter) 0;
CheckError(lib3mf_texture2d_getfilter(m_pHandle, &resultFilter));
return resultFilter;
}
/**
* CTexture2D::SetFilter - Sets a texture's filter type.
* @param[in] eFilter - sets new filter type enum.
*/
void CTexture2D::SetFilter(const eTextureFilter eFilter)
{
CheckError(lib3mf_texture2d_setfilter(m_pHandle, eFilter));
}
/**
* Method definitions for class CBuildItem
*/
/**
* CBuildItem::GetObjectResource - Retrieves the object resource associated to a build item
* @return returns the associated resource instance
*/
PObject CBuildItem::GetObjectResource()
{
Lib3MFHandle hObjectResource = nullptr;
CheckError(lib3mf_builditem_getobjectresource(m_pHandle, &hObjectResource));
if (!hObjectResource) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CObject>(m_pWrapper, hObjectResource);
}
/**
* CBuildItem::GetUUID - returns, whether a build item has a UUID and, if true, the build item's UUID
* @param[out] bHasUUID - flag whether the build item has a UUID
* @return the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx'
*/
std::string CBuildItem::GetUUID(bool & bHasUUID)
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_builditem_getuuid(m_pHandle, &bHasUUID, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_builditem_getuuid(m_pHandle, &bHasUUID, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* CBuildItem::SetUUID - sets the build item's UUID
* @param[in] sUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx'
*/
void CBuildItem::SetUUID(const std::string & sUUID)
{
CheckError(lib3mf_builditem_setuuid(m_pHandle, sUUID.c_str()));
}
/**
* CBuildItem::GetObjectResourceID - Retrieves the object UniqueResourceID associated to a build item
* @return returns the UniqueResourceID of the object
*/
Lib3MF_uint32 CBuildItem::GetObjectResourceID()
{
Lib3MF_uint32 resultUniqueResourceID = 0;
CheckError(lib3mf_builditem_getobjectresourceid(m_pHandle, &resultUniqueResourceID));
return resultUniqueResourceID;
}
/**
* CBuildItem::HasObjectTransform - Checks, if a build item has a non-identity transformation matrix
* @return returns true, if the transformation matrix is not the identity
*/
bool CBuildItem::HasObjectTransform()
{
bool resultHasTransform = 0;
CheckError(lib3mf_builditem_hasobjecttransform(m_pHandle, &resultHasTransform));
return resultHasTransform;
}
/**
* CBuildItem::GetObjectTransform - Retrieves a build item's transformation matrix.
* @return returns the transformation matrix
*/
sTransform CBuildItem::GetObjectTransform()
{
sTransform resultTransform;
CheckError(lib3mf_builditem_getobjecttransform(m_pHandle, &resultTransform));
return resultTransform;
}
/**
* CBuildItem::SetObjectTransform - Sets a build item's transformation matrix.
* @param[in] Transform - new transformation matrix
*/
void CBuildItem::SetObjectTransform(const sTransform & Transform)
{
CheckError(lib3mf_builditem_setobjecttransform(m_pHandle, &Transform));
}
/**
* CBuildItem::GetPartNumber - Retrieves a build item's part number string
* @return Returns a build item's part number string
*/
std::string CBuildItem::GetPartNumber()
{
Lib3MF_uint32 bytesNeededPartNumber = 0;
Lib3MF_uint32 bytesWrittenPartNumber = 0;
CheckError(lib3mf_builditem_getpartnumber(m_pHandle, 0, &bytesNeededPartNumber, nullptr));
std::vector<char> bufferPartNumber(bytesNeededPartNumber);
CheckError(lib3mf_builditem_getpartnumber(m_pHandle, bytesNeededPartNumber, &bytesWrittenPartNumber, &bufferPartNumber[0]));
return std::string(&bufferPartNumber[0]);
}
/**
* CBuildItem::SetPartNumber - Sets a build item's part number string
* @param[in] sSetPartnumber - new part number string for referencing parts from the outside world
*/
void CBuildItem::SetPartNumber(const std::string & sSetPartnumber)
{
CheckError(lib3mf_builditem_setpartnumber(m_pHandle, sSetPartnumber.c_str()));
}
/**
* CBuildItem::GetMetaDataGroup - Returns the metadatagroup of this build item
* @return returns an Instance of the metadatagroup of this build item
*/
PMetaDataGroup CBuildItem::GetMetaDataGroup()
{
Lib3MFHandle hMetaDataGroup = nullptr;
CheckError(lib3mf_builditem_getmetadatagroup(m_pHandle, &hMetaDataGroup));
if (!hMetaDataGroup) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMetaDataGroup>(m_pWrapper, hMetaDataGroup);
}
/**
* CBuildItem::GetOutbox - Returns the outbox of a build item
* @return Outbox of this build item
*/
sBox CBuildItem::GetOutbox()
{
sBox resultOutbox;
CheckError(lib3mf_builditem_getoutbox(m_pHandle, &resultOutbox));
return resultOutbox;
}
/**
* Method definitions for class CBuildItemIterator
*/
/**
* CBuildItemIterator::MoveNext - Iterates to the next build item in the list.
* @return Iterates to the next build item in the list.
*/
bool CBuildItemIterator::MoveNext()
{
bool resultHasNext = 0;
CheckError(lib3mf_builditemiterator_movenext(m_pHandle, &resultHasNext));
return resultHasNext;
}
/**
* CBuildItemIterator::MovePrevious - Iterates to the previous build item in the list.
* @return Iterates to the previous build item in the list.
*/
bool CBuildItemIterator::MovePrevious()
{
bool resultHasPrevious = 0;
CheckError(lib3mf_builditemiterator_moveprevious(m_pHandle, &resultHasPrevious));
return resultHasPrevious;
}
/**
* CBuildItemIterator::GetCurrent - Returns the build item the iterator points at.
* @return returns the build item instance.
*/
PBuildItem CBuildItemIterator::GetCurrent()
{
Lib3MFHandle hBuildItem = nullptr;
CheckError(lib3mf_builditemiterator_getcurrent(m_pHandle, &hBuildItem));
if (!hBuildItem) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBuildItem>(m_pWrapper, hBuildItem);
}
/**
* CBuildItemIterator::Clone - Creates a new build item iterator with the same build item list.
* @return returns the cloned Iterator instance
*/
PBuildItemIterator CBuildItemIterator::Clone()
{
Lib3MFHandle hOutBuildItemIterator = nullptr;
CheckError(lib3mf_builditemiterator_clone(m_pHandle, &hOutBuildItemIterator));
if (!hOutBuildItemIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBuildItemIterator>(m_pWrapper, hOutBuildItemIterator);
}
/**
* CBuildItemIterator::Count - Returns the number of build items the iterator captures.
* @return returns the number of build items the iterator captures.
*/
Lib3MF_uint64 CBuildItemIterator::Count()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_builditemiterator_count(m_pHandle, &resultCount));
return resultCount;
}
/**
* Method definitions for class CSlice
*/
/**
* CSlice::SetVertices - Set all vertices of a slice. All polygons will be cleared.
* @param[in] VerticesBuffer - contains the positions.
*/
void CSlice::SetVertices(const CInputVector<sPosition2D> & VerticesBuffer)
{
CheckError(lib3mf_slice_setvertices(m_pHandle, (Lib3MF_uint64)VerticesBuffer.size(), VerticesBuffer.data()));
}
/**
* CSlice::GetVertices - Get all vertices of a slice
* @param[out] VerticesBuffer - contains the positions.
*/
void CSlice::GetVertices(std::vector<sPosition2D> & VerticesBuffer)
{
Lib3MF_uint64 elementsNeededVertices = 0;
Lib3MF_uint64 elementsWrittenVertices = 0;
CheckError(lib3mf_slice_getvertices(m_pHandle, 0, &elementsNeededVertices, nullptr));
VerticesBuffer.resize((size_t) elementsNeededVertices);
CheckError(lib3mf_slice_getvertices(m_pHandle, elementsNeededVertices, &elementsWrittenVertices, VerticesBuffer.data()));
}
/**
* CSlice::GetVertexCount - Get the number of vertices in a slice
* @return the number of vertices in the slice
*/
Lib3MF_uint64 CSlice::GetVertexCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_slice_getvertexcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CSlice::AddPolygon - Add a new polygon to this slice
* @param[in] IndicesBuffer - the new indices of the new polygon
* @return the index of the new polygon
*/
Lib3MF_uint64 CSlice::AddPolygon(const CInputVector<Lib3MF_uint32> & IndicesBuffer)
{
Lib3MF_uint64 resultIndex = 0;
CheckError(lib3mf_slice_addpolygon(m_pHandle, (Lib3MF_uint64)IndicesBuffer.size(), IndicesBuffer.data(), &resultIndex));
return resultIndex;
}
/**
* CSlice::GetPolygonCount - Get the number of polygons in the slice
* @return the number of polygons in the slice
*/
Lib3MF_uint64 CSlice::GetPolygonCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_slice_getpolygoncount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CSlice::SetPolygonIndices - Set all indices of a polygon
* @param[in] nIndex - the index of the polygon to manipulate
* @param[in] IndicesBuffer - the new indices of the index-th polygon
*/
void CSlice::SetPolygonIndices(const Lib3MF_uint64 nIndex, const CInputVector<Lib3MF_uint32> & IndicesBuffer)
{
CheckError(lib3mf_slice_setpolygonindices(m_pHandle, nIndex, (Lib3MF_uint64)IndicesBuffer.size(), IndicesBuffer.data()));
}
/**
* CSlice::GetPolygonIndices - Get all vertices of a slice
* @param[in] nIndex - the index of the polygon to manipulate
* @param[out] IndicesBuffer - the indices of the index-th polygon
*/
void CSlice::GetPolygonIndices(const Lib3MF_uint64 nIndex, std::vector<Lib3MF_uint32> & IndicesBuffer)
{
Lib3MF_uint64 elementsNeededIndices = 0;
Lib3MF_uint64 elementsWrittenIndices = 0;
CheckError(lib3mf_slice_getpolygonindices(m_pHandle, nIndex, 0, &elementsNeededIndices, nullptr));
IndicesBuffer.resize((size_t) elementsNeededIndices);
CheckError(lib3mf_slice_getpolygonindices(m_pHandle, nIndex, elementsNeededIndices, &elementsWrittenIndices, IndicesBuffer.data()));
}
/**
* CSlice::GetPolygonIndexCount - Get the number of vertices in a slice
* @param[in] nIndex - the index of the polygon to manipulate
* @return the number of indices of the index-th polygon
*/
Lib3MF_uint64 CSlice::GetPolygonIndexCount(const Lib3MF_uint64 nIndex)
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_slice_getpolygonindexcount(m_pHandle, nIndex, &resultCount));
return resultCount;
}
/**
* CSlice::GetZTop - Get the upper Z-Coordinate of this slice.
* @return the upper Z-Coordinate of this slice
*/
Lib3MF_double CSlice::GetZTop()
{
Lib3MF_double resultZTop = 0;
CheckError(lib3mf_slice_getztop(m_pHandle, &resultZTop));
return resultZTop;
}
/**
* Method definitions for class CSliceStack
*/
/**
* CSliceStack::GetBottomZ - Get the lower Z-Coordinate of the slice stack.
* @return the lower Z-Coordinate the slice stack
*/
Lib3MF_double CSliceStack::GetBottomZ()
{
Lib3MF_double resultZBottom = 0;
CheckError(lib3mf_slicestack_getbottomz(m_pHandle, &resultZBottom));
return resultZBottom;
}
/**
* CSliceStack::GetSliceCount - Returns the number of slices
* @return the number of slices
*/
Lib3MF_uint64 CSliceStack::GetSliceCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_slicestack_getslicecount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CSliceStack::GetSlice - Query a slice from the slice stack
* @param[in] nSliceIndex - the index of the slice
* @return the Slice instance
*/
PSlice CSliceStack::GetSlice(const Lib3MF_uint64 nSliceIndex)
{
Lib3MFHandle hTheSlice = nullptr;
CheckError(lib3mf_slicestack_getslice(m_pHandle, nSliceIndex, &hTheSlice));
if (!hTheSlice) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSlice>(m_pWrapper, hTheSlice);
}
/**
* CSliceStack::AddSlice - Returns the number of slices
* @param[in] dZTop - upper Z coordinate of the slice
* @return a new Slice instance
*/
PSlice CSliceStack::AddSlice(const Lib3MF_double dZTop)
{
Lib3MFHandle hTheSlice = nullptr;
CheckError(lib3mf_slicestack_addslice(m_pHandle, dZTop, &hTheSlice));
if (!hTheSlice) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSlice>(m_pWrapper, hTheSlice);
}
/**
* CSliceStack::GetSliceRefCount - Returns the number of slice refs
* @return the number of slicereferences
*/
Lib3MF_uint64 CSliceStack::GetSliceRefCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_slicestack_getslicerefcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CSliceStack::AddSliceStackReference - Adds another existing slicestack as sliceref in this slicestack
* @param[in] pTheSliceStack - the slicestack to use as sliceref
*/
void CSliceStack::AddSliceStackReference(CSliceStack * pTheSliceStack)
{
Lib3MFHandle hTheSliceStack = nullptr;
if (pTheSliceStack != nullptr) {
hTheSliceStack = pTheSliceStack->GetHandle();
};
CheckError(lib3mf_slicestack_addslicestackreference(m_pHandle, hTheSliceStack));
}
/**
* CSliceStack::GetSliceStackReference - Adds another existing slicestack as sliceref in this slicestack
* @param[in] nSliceRefIndex - the index of the slice ref
* @return the slicestack that is used as sliceref
*/
PSliceStack CSliceStack::GetSliceStackReference(const Lib3MF_uint64 nSliceRefIndex)
{
Lib3MFHandle hTheSliceStack = nullptr;
CheckError(lib3mf_slicestack_getslicestackreference(m_pHandle, nSliceRefIndex, &hTheSliceStack));
if (!hTheSliceStack) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSliceStack>(m_pWrapper, hTheSliceStack);
}
/**
* CSliceStack::CollapseSliceReferences - Removes the indirection of slices via slice-refs, i.e. creates the slices of all slice refs of this SliceStack as actual slices of this SliceStack. All previously existing slices or slicerefs will be removed.
*/
void CSliceStack::CollapseSliceReferences()
{
CheckError(lib3mf_slicestack_collapseslicereferences(m_pHandle));
}
/**
* CSliceStack::SetOwnPath - Sets the package path where this Slice should be stored. Input an empty string to reset the path
* @param[in] sPath - the package path where this Slice should be stored
*/
void CSliceStack::SetOwnPath(const std::string & sPath)
{
CheckError(lib3mf_slicestack_setownpath(m_pHandle, sPath.c_str()));
}
/**
* CSliceStack::GetOwnPath - Obtains the package path where this Slice should be stored. Returns an empty string if the slicestack is stored within the root model.
* @return the package path where this Slice will be stored
*/
std::string CSliceStack::GetOwnPath()
{
Lib3MF_uint32 bytesNeededPath = 0;
Lib3MF_uint32 bytesWrittenPath = 0;
CheckError(lib3mf_slicestack_getownpath(m_pHandle, 0, &bytesNeededPath, nullptr));
std::vector<char> bufferPath(bytesNeededPath);
CheckError(lib3mf_slicestack_getownpath(m_pHandle, bytesNeededPath, &bytesWrittenPath, &bufferPath[0]));
return std::string(&bufferPath[0]);
}
/**
* Method definitions for class CConsumer
*/
/**
* CConsumer::GetConsumerID - Gets the consumerid
* @return A unique identifier for the consumers
*/
std::string CConsumer::GetConsumerID()
{
Lib3MF_uint32 bytesNeededConsumerID = 0;
Lib3MF_uint32 bytesWrittenConsumerID = 0;
CheckError(lib3mf_consumer_getconsumerid(m_pHandle, 0, &bytesNeededConsumerID, nullptr));
std::vector<char> bufferConsumerID(bytesNeededConsumerID);
CheckError(lib3mf_consumer_getconsumerid(m_pHandle, bytesNeededConsumerID, &bytesWrittenConsumerID, &bufferConsumerID[0]));
return std::string(&bufferConsumerID[0]);
}
/**
* CConsumer::GetKeyID - Getts the keyid
* @return The identifier for the key of this consumer
*/
std::string CConsumer::GetKeyID()
{
Lib3MF_uint32 bytesNeededKeyID = 0;
Lib3MF_uint32 bytesWrittenKeyID = 0;
CheckError(lib3mf_consumer_getkeyid(m_pHandle, 0, &bytesNeededKeyID, nullptr));
std::vector<char> bufferKeyID(bytesNeededKeyID);
CheckError(lib3mf_consumer_getkeyid(m_pHandle, bytesNeededKeyID, &bytesWrittenKeyID, &bufferKeyID[0]));
return std::string(&bufferKeyID[0]);
}
/**
* CConsumer::GetKeyValue - Gets the keyvalue associated with this consumer
* @return The public key, when available, of this consumer
*/
std::string CConsumer::GetKeyValue()
{
Lib3MF_uint32 bytesNeededKeyValue = 0;
Lib3MF_uint32 bytesWrittenKeyValue = 0;
CheckError(lib3mf_consumer_getkeyvalue(m_pHandle, 0, &bytesNeededKeyValue, nullptr));
std::vector<char> bufferKeyValue(bytesNeededKeyValue);
CheckError(lib3mf_consumer_getkeyvalue(m_pHandle, bytesNeededKeyValue, &bytesWrittenKeyValue, &bufferKeyValue[0]));
return std::string(&bufferKeyValue[0]);
}
/**
* Method definitions for class CAccessRight
*/
/**
* CAccessRight::GetConsumer - Gets the consumer associated with this access right
* @return The consumer instance
*/
PConsumer CAccessRight::GetConsumer()
{
Lib3MFHandle hConsumer = nullptr;
CheckError(lib3mf_accessright_getconsumer(m_pHandle, &hConsumer));
if (!hConsumer) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CConsumer>(m_pWrapper, hConsumer);
}
/**
* CAccessRight::GetWrappingAlgorithm - Gets the associated encryption algorithm
* @return The algorithm used for the key in this accessright
*/
eWrappingAlgorithm CAccessRight::GetWrappingAlgorithm()
{
eWrappingAlgorithm resultAlgorithm = (eWrappingAlgorithm) 0;
CheckError(lib3mf_accessright_getwrappingalgorithm(m_pHandle, &resultAlgorithm));
return resultAlgorithm;
}
/**
* CAccessRight::GetMgfAlgorithm - Gets the associated mask generation function algorithm
* @return The MFG1 algorithm
*/
eMgfAlgorithm CAccessRight::GetMgfAlgorithm()
{
eMgfAlgorithm resultAlgorithm = (eMgfAlgorithm) 0;
CheckError(lib3mf_accessright_getmgfalgorithm(m_pHandle, &resultAlgorithm));
return resultAlgorithm;
}
/**
* CAccessRight::GetDigestMethod - Gets the digest method assoicated
* @return The digest method for this accessright
*/
eDigestMethod CAccessRight::GetDigestMethod()
{
eDigestMethod resultAlgorithm = (eDigestMethod) 0;
CheckError(lib3mf_accessright_getdigestmethod(m_pHandle, &resultAlgorithm));
return resultAlgorithm;
}
/**
* Method definitions for class CContentEncryptionParams
*/
/**
* CContentEncryptionParams::GetEncryptionAlgorithm - Returns the encryption method to be used in this encryption process
* @return
*/
eEncryptionAlgorithm CContentEncryptionParams::GetEncryptionAlgorithm()
{
eEncryptionAlgorithm resultAlgorithm = (eEncryptionAlgorithm) 0;
CheckError(lib3mf_contentencryptionparams_getencryptionalgorithm(m_pHandle, &resultAlgorithm));
return resultAlgorithm;
}
/**
* CContentEncryptionParams::GetKey - Gets the key for the resource associated
* @param[out] ByteDataBuffer - Pointer to a buffer where to place the key.
*/
void CContentEncryptionParams::GetKey(std::vector<Lib3MF_uint8> & ByteDataBuffer)
{
Lib3MF_uint64 elementsNeededByteData = 0;
Lib3MF_uint64 elementsWrittenByteData = 0;
CheckError(lib3mf_contentencryptionparams_getkey(m_pHandle, 0, &elementsNeededByteData, nullptr));
ByteDataBuffer.resize((size_t) elementsNeededByteData);
CheckError(lib3mf_contentencryptionparams_getkey(m_pHandle, elementsNeededByteData, &elementsWrittenByteData, ByteDataBuffer.data()));
}
/**
* CContentEncryptionParams::GetInitializationVector - Gets the IV data
* @param[out] ByteDataBuffer - Pointer to a buffer where to place the data.
*/
void CContentEncryptionParams::GetInitializationVector(std::vector<Lib3MF_uint8> & ByteDataBuffer)
{
Lib3MF_uint64 elementsNeededByteData = 0;
Lib3MF_uint64 elementsWrittenByteData = 0;
CheckError(lib3mf_contentencryptionparams_getinitializationvector(m_pHandle, 0, &elementsNeededByteData, nullptr));
ByteDataBuffer.resize((size_t) elementsNeededByteData);
CheckError(lib3mf_contentencryptionparams_getinitializationvector(m_pHandle, elementsNeededByteData, &elementsWrittenByteData, ByteDataBuffer.data()));
}
/**
* CContentEncryptionParams::GetAuthenticationTag - A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value
* @param[out] ByteDataBuffer - Pointer to a buffer where to place the data.
*/
void CContentEncryptionParams::GetAuthenticationTag(std::vector<Lib3MF_uint8> & ByteDataBuffer)
{
Lib3MF_uint64 elementsNeededByteData = 0;
Lib3MF_uint64 elementsWrittenByteData = 0;
CheckError(lib3mf_contentencryptionparams_getauthenticationtag(m_pHandle, 0, &elementsNeededByteData, nullptr));
ByteDataBuffer.resize((size_t) elementsNeededByteData);
CheckError(lib3mf_contentencryptionparams_getauthenticationtag(m_pHandle, elementsNeededByteData, &elementsWrittenByteData, ByteDataBuffer.data()));
}
/**
* CContentEncryptionParams::SetAuthenticationTag - Sets the authentication tag
* @param[in] ByteDataBuffer - The authentication tag size
*/
void CContentEncryptionParams::SetAuthenticationTag(const CInputVector<Lib3MF_uint8> & ByteDataBuffer)
{
CheckError(lib3mf_contentencryptionparams_setauthenticationtag(m_pHandle, (Lib3MF_uint64)ByteDataBuffer.size(), ByteDataBuffer.data()));
}
/**
* CContentEncryptionParams::GetAdditionalAuthenticationData - A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value
* @param[out] ByteDataBuffer - Buffer where the data will be placed
*/
void CContentEncryptionParams::GetAdditionalAuthenticationData(std::vector<Lib3MF_uint8> & ByteDataBuffer)
{
Lib3MF_uint64 elementsNeededByteData = 0;
Lib3MF_uint64 elementsWrittenByteData = 0;
CheckError(lib3mf_contentencryptionparams_getadditionalauthenticationdata(m_pHandle, 0, &elementsNeededByteData, nullptr));
ByteDataBuffer.resize((size_t) elementsNeededByteData);
CheckError(lib3mf_contentencryptionparams_getadditionalauthenticationdata(m_pHandle, elementsNeededByteData, &elementsWrittenByteData, ByteDataBuffer.data()));
}
/**
* CContentEncryptionParams::GetDescriptor - A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value
* @return
*/
Lib3MF_uint64 CContentEncryptionParams::GetDescriptor()
{
Lib3MF_uint64 resultDescriptor = 0;
CheckError(lib3mf_contentencryptionparams_getdescriptor(m_pHandle, &resultDescriptor));
return resultDescriptor;
}
/**
* CContentEncryptionParams::GetKeyUUID - Gets the resourcedatagroup keyuuid
* @return The resourcedatagroup keyuuid that may be use to reference an external key
*/
std::string CContentEncryptionParams::GetKeyUUID()
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_contentencryptionparams_getkeyuuid(m_pHandle, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_contentencryptionparams_getkeyuuid(m_pHandle, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* Method definitions for class CResourceData
*/
/**
* CResourceData::GetPath - Gets the encrypted part path
* @return The part path
*/
PPackagePart CResourceData::GetPath()
{
Lib3MFHandle hPath = nullptr;
CheckError(lib3mf_resourcedata_getpath(m_pHandle, &hPath));
if (!hPath) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CPackagePart>(m_pWrapper, hPath);
}
/**
* CResourceData::GetEncryptionAlgorithm - Gets the encryption algorithm used to encrypt this ResourceData
* @return The encryption algorithm
*/
eEncryptionAlgorithm CResourceData::GetEncryptionAlgorithm()
{
eEncryptionAlgorithm resultEncryptionAlgorithm = (eEncryptionAlgorithm) 0;
CheckError(lib3mf_resourcedata_getencryptionalgorithm(m_pHandle, &resultEncryptionAlgorithm));
return resultEncryptionAlgorithm;
}
/**
* CResourceData::GetCompression - Tells whether this ResourceData is compressed or not
* @return The compression method
*/
eCompression CResourceData::GetCompression()
{
eCompression resultCompression = (eCompression) 0;
CheckError(lib3mf_resourcedata_getcompression(m_pHandle, &resultCompression));
return resultCompression;
}
/**
* CResourceData::GetAdditionalAuthenticationData - Tells whether this ResourceData is compressed or not
* @param[out] ByteDataBuffer - The compression method
*/
void CResourceData::GetAdditionalAuthenticationData(std::vector<Lib3MF_uint8> & ByteDataBuffer)
{
Lib3MF_uint64 elementsNeededByteData = 0;
Lib3MF_uint64 elementsWrittenByteData = 0;
CheckError(lib3mf_resourcedata_getadditionalauthenticationdata(m_pHandle, 0, &elementsNeededByteData, nullptr));
ByteDataBuffer.resize((size_t) elementsNeededByteData);
CheckError(lib3mf_resourcedata_getadditionalauthenticationdata(m_pHandle, elementsNeededByteData, &elementsWrittenByteData, ByteDataBuffer.data()));
}
/**
* Method definitions for class CResourceDataGroup
*/
/**
* CResourceDataGroup::GetKeyUUID - Sets the resourcedatagroup keyuuid
* @return The new resourcedatagroup keyuuid.
*/
std::string CResourceDataGroup::GetKeyUUID()
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_resourcedatagroup_getkeyuuid(m_pHandle, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_resourcedatagroup_getkeyuuid(m_pHandle, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* CResourceDataGroup::AddAccessRight - Add accessright to resourcedatagroup element
* @param[in] pConsumer - The Consumer reference
* @param[in] eWrappingAlgorithm - The key wrapping algorithm to be used
* @param[in] eMgfAlgorithm - The mask generation function to be used
* @param[in] eDigestMethod - The digest mechanism to be used
* @return The acess right instance
*/
PAccessRight CResourceDataGroup::AddAccessRight(CConsumer * pConsumer, const eWrappingAlgorithm eWrappingAlgorithm, const eMgfAlgorithm eMgfAlgorithm, const eDigestMethod eDigestMethod)
{
Lib3MFHandle hConsumer = nullptr;
if (pConsumer != nullptr) {
hConsumer = pConsumer->GetHandle();
};
Lib3MFHandle hTheAccessRight = nullptr;
CheckError(lib3mf_resourcedatagroup_addaccessright(m_pHandle, hConsumer, eWrappingAlgorithm, eMgfAlgorithm, eDigestMethod, &hTheAccessRight));
if (!hTheAccessRight) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CAccessRight>(m_pWrapper, hTheAccessRight);
}
/**
* CResourceDataGroup::FindAccessRightByConsumer - Finds the AccessRight associated with a Consumer
* @param[in] pConsumer - The Consumer instance
* @return The AcessRight instance
*/
PAccessRight CResourceDataGroup::FindAccessRightByConsumer(CConsumer * pConsumer)
{
Lib3MFHandle hConsumer = nullptr;
if (pConsumer != nullptr) {
hConsumer = pConsumer->GetHandle();
};
Lib3MFHandle hTheAccessRight = nullptr;
CheckError(lib3mf_resourcedatagroup_findaccessrightbyconsumer(m_pHandle, hConsumer, &hTheAccessRight));
if (hTheAccessRight) {
return std::make_shared<CAccessRight>(m_pWrapper, hTheAccessRight);
} else {
return nullptr;
}
}
/**
* CResourceDataGroup::RemoveAccessRight - Removes access from a Consumer on this resource data group
* @param[in] pConsumer - The Consumer instance
*/
void CResourceDataGroup::RemoveAccessRight(CConsumer * pConsumer)
{
Lib3MFHandle hConsumer = nullptr;
if (pConsumer != nullptr) {
hConsumer = pConsumer->GetHandle();
};
CheckError(lib3mf_resourcedatagroup_removeaccessright(m_pHandle, hConsumer));
}
/**
* Method definitions for class CKeyStore
*/
/**
* CKeyStore::AddConsumer - Adds a consumer to the keystore
* @param[in] sConsumerID - A unique identifier for the consumer
* @param[in] sKeyID - The id of the key of the consumer
* @param[in] sKeyValue - The public key for this consumer in PEM format
* @return The consumer instance
*/
PConsumer CKeyStore::AddConsumer(const std::string & sConsumerID, const std::string & sKeyID, const std::string & sKeyValue)
{
Lib3MFHandle hConsumer = nullptr;
CheckError(lib3mf_keystore_addconsumer(m_pHandle, sConsumerID.c_str(), sKeyID.c_str(), sKeyValue.c_str(), &hConsumer));
if (!hConsumer) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CConsumer>(m_pWrapper, hConsumer);
}
/**
* CKeyStore::GetConsumerCount - Gets the number of consumers in the keystore
* @return The consumer count
*/
Lib3MF_uint64 CKeyStore::GetConsumerCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_keystore_getconsumercount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CKeyStore::GetConsumer - Get a consumer from the keystore
* @param[in] nConsumerIndex - The index of the consumer
* @return The consumer instance
*/
PConsumer CKeyStore::GetConsumer(const Lib3MF_uint64 nConsumerIndex)
{
Lib3MFHandle hConsumer = nullptr;
CheckError(lib3mf_keystore_getconsumer(m_pHandle, nConsumerIndex, &hConsumer));
if (!hConsumer) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CConsumer>(m_pWrapper, hConsumer);
}
/**
* CKeyStore::RemoveConsumer - Removes a consumer from the keystore
* @param[in] pConsumer - The consumer instance to remove
*/
void CKeyStore::RemoveConsumer(CConsumer * pConsumer)
{
Lib3MFHandle hConsumer = nullptr;
if (pConsumer != nullptr) {
hConsumer = pConsumer->GetHandle();
};
CheckError(lib3mf_keystore_removeconsumer(m_pHandle, hConsumer));
}
/**
* CKeyStore::FindConsumer - Finds a consumer by ID
* @param[in] sConsumerID - The ID of the consumer
* @return The consumer instance
*/
PConsumer CKeyStore::FindConsumer(const std::string & sConsumerID)
{
Lib3MFHandle hConsumer = nullptr;
CheckError(lib3mf_keystore_findconsumer(m_pHandle, sConsumerID.c_str(), &hConsumer));
if (hConsumer) {
return std::make_shared<CConsumer>(m_pWrapper, hConsumer);
} else {
return nullptr;
}
}
/**
* CKeyStore::GetResourceDataGroupCount - Gets the number of resource data group in the keysore
* @return The number of resource data available
*/
Lib3MF_uint64 CKeyStore::GetResourceDataGroupCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_keystore_getresourcedatagroupcount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CKeyStore::AddResourceDataGroup - Adds a resource data group into the keystore.
* @return The resource data group instance
*/
PResourceDataGroup CKeyStore::AddResourceDataGroup()
{
Lib3MFHandle hResourceDataGroup = nullptr;
CheckError(lib3mf_keystore_addresourcedatagroup(m_pHandle, &hResourceDataGroup));
if (!hResourceDataGroup) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResourceDataGroup>(m_pWrapper, hResourceDataGroup);
}
/**
* CKeyStore::GetResourceDataGroup - Gets a resource data group
* @param[in] nResourceDataIndex - The index of the resource data
* @return The resource data group instance
*/
PResourceDataGroup CKeyStore::GetResourceDataGroup(const Lib3MF_uint64 nResourceDataIndex)
{
Lib3MFHandle hResourceDataGroup = nullptr;
CheckError(lib3mf_keystore_getresourcedatagroup(m_pHandle, nResourceDataIndex, &hResourceDataGroup));
if (!hResourceDataGroup) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResourceDataGroup>(m_pWrapper, hResourceDataGroup);
}
/**
* CKeyStore::RemoveResourceDataGroup - Removes a resource data group
* @param[in] pResourceDataGroup - The resource data group instance
*/
void CKeyStore::RemoveResourceDataGroup(CResourceDataGroup * pResourceDataGroup)
{
Lib3MFHandle hResourceDataGroup = nullptr;
if (pResourceDataGroup != nullptr) {
hResourceDataGroup = pResourceDataGroup->GetHandle();
};
CheckError(lib3mf_keystore_removeresourcedatagroup(m_pHandle, hResourceDataGroup));
}
/**
* CKeyStore::FindResourceDataGroup - Finds a resource data group that contains a particular resourcedata
* @param[in] pPartPath - The target path for the resourcedata hold by the resource data group
* @return The data resource instance
*/
PResourceDataGroup CKeyStore::FindResourceDataGroup(CPackagePart * pPartPath)
{
Lib3MFHandle hPartPath = nullptr;
if (pPartPath != nullptr) {
hPartPath = pPartPath->GetHandle();
};
Lib3MFHandle hResourceDataGroup = nullptr;
CheckError(lib3mf_keystore_findresourcedatagroup(m_pHandle, hPartPath, &hResourceDataGroup));
if (hResourceDataGroup) {
return std::make_shared<CResourceDataGroup>(m_pWrapper, hResourceDataGroup);
} else {
return nullptr;
}
}
/**
* CKeyStore::AddResourceData - Add resourcedata to resourcedatagroup element
* @param[in] pResourceDataGroup - The resource data group where to add this resource data
* @param[in] pPartPath - The path of the part to be encrypted
* @param[in] eAlgorithm - The encryption algorithm to be used to encrypt this resource
* @param[in] eCompression - Whether compression should be used prior to encryption
* @param[in] AdditionalAuthenticationDataBuffer - Additional data to be encrypted along the contents for better security
* @return The data resource instance
*/
PResourceData CKeyStore::AddResourceData(CResourceDataGroup * pResourceDataGroup, CPackagePart * pPartPath, const eEncryptionAlgorithm eAlgorithm, const eCompression eCompression, const CInputVector<Lib3MF_uint8> & AdditionalAuthenticationDataBuffer)
{
Lib3MFHandle hResourceDataGroup = nullptr;
if (pResourceDataGroup != nullptr) {
hResourceDataGroup = pResourceDataGroup->GetHandle();
};
Lib3MFHandle hPartPath = nullptr;
if (pPartPath != nullptr) {
hPartPath = pPartPath->GetHandle();
};
Lib3MFHandle hResourceData = nullptr;
CheckError(lib3mf_keystore_addresourcedata(m_pHandle, hResourceDataGroup, hPartPath, eAlgorithm, eCompression, (Lib3MF_uint64)AdditionalAuthenticationDataBuffer.size(), AdditionalAuthenticationDataBuffer.data(), &hResourceData));
if (!hResourceData) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResourceData>(m_pWrapper, hResourceData);
}
/**
* CKeyStore::RemoveResourceData - Removes a resource data
* @param[in] pResourceData - The resource data to be removed
*/
void CKeyStore::RemoveResourceData(CResourceData * pResourceData)
{
Lib3MFHandle hResourceData = nullptr;
if (pResourceData != nullptr) {
hResourceData = pResourceData->GetHandle();
};
CheckError(lib3mf_keystore_removeresourcedata(m_pHandle, hResourceData));
}
/**
* CKeyStore::FindResourceData - Finds a resource data on this resource group
* @param[in] pResourcePath - The target path for the resourcedata
* @return The resource data instance
*/
PResourceData CKeyStore::FindResourceData(CPackagePart * pResourcePath)
{
Lib3MFHandle hResourcePath = nullptr;
if (pResourcePath != nullptr) {
hResourcePath = pResourcePath->GetHandle();
};
Lib3MFHandle hResourceData = nullptr;
CheckError(lib3mf_keystore_findresourcedata(m_pHandle, hResourcePath, &hResourceData));
if (hResourceData) {
return std::make_shared<CResourceData>(m_pWrapper, hResourceData);
} else {
return nullptr;
}
}
/**
* CKeyStore::GetResourceDataCount - Gets the number of resource data in the keysore
* @return The number of resource data available
*/
Lib3MF_uint64 CKeyStore::GetResourceDataCount()
{
Lib3MF_uint64 resultCount = 0;
CheckError(lib3mf_keystore_getresourcedatacount(m_pHandle, &resultCount));
return resultCount;
}
/**
* CKeyStore::GetResourceData - Gets a resource data
* @param[in] nResourceDataIndex - The index of the resource data
* @return The data resource instance
*/
PResourceData CKeyStore::GetResourceData(const Lib3MF_uint64 nResourceDataIndex)
{
Lib3MFHandle hResourceData = nullptr;
CheckError(lib3mf_keystore_getresourcedata(m_pHandle, nResourceDataIndex, &hResourceData));
if (!hResourceData) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResourceData>(m_pWrapper, hResourceData);
}
/**
* CKeyStore::GetUUID - Gets the keystore UUID
* @param[out] bHasUUID - flag whether the keystore has a UUID
* @return returns the keystore uuid.
*/
std::string CKeyStore::GetUUID(bool & bHasUUID)
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_keystore_getuuid(m_pHandle, &bHasUUID, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_keystore_getuuid(m_pHandle, &bHasUUID, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* CKeyStore::SetUUID - Sets the keystore UUID
* @param[in] sUUID - The new keystore uuid.
*/
void CKeyStore::SetUUID(const std::string & sUUID)
{
CheckError(lib3mf_keystore_setuuid(m_pHandle, sUUID.c_str()));
}
/**
* Method definitions for class CModel
*/
/**
* CModel::RootModelPart - Returns the PackagePart within the OPC package that holds the root model.
* @return the PackagePart within the OPC package that holds the model-file
*/
PPackagePart CModel::RootModelPart()
{
Lib3MFHandle hRootModelPart = nullptr;
CheckError(lib3mf_model_rootmodelpart(m_pHandle, &hRootModelPart));
if (!hRootModelPart) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CPackagePart>(m_pWrapper, hRootModelPart);
}
/**
* CModel::FindOrCreatePackagePart - Returns a new PackagePart for use within the OPC package.
* @param[in] sAbsolutePath - the absolute Path (physical location) within the OPC package
* @return the new PackagePart within the OPC package
*/
PPackagePart CModel::FindOrCreatePackagePart(const std::string & sAbsolutePath)
{
Lib3MFHandle hModelPart = nullptr;
CheckError(lib3mf_model_findorcreatepackagepart(m_pHandle, sAbsolutePath.c_str(), &hModelPart));
if (!hModelPart) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CPackagePart>(m_pWrapper, hModelPart);
}
/**
* CModel::SetUnit - sets the units of a model.
* @param[in] eUnit - Unit enum value for the model unit
*/
void CModel::SetUnit(const eModelUnit eUnit)
{
CheckError(lib3mf_model_setunit(m_pHandle, eUnit));
}
/**
* CModel::GetUnit - returns the units of a model.
* @return Unit enum value for the model unit
*/
eModelUnit CModel::GetUnit()
{
eModelUnit resultUnit = (eModelUnit) 0;
CheckError(lib3mf_model_getunit(m_pHandle, &resultUnit));
return resultUnit;
}
/**
* CModel::GetLanguage - retrieves the language of a model
* @return language identifier
*/
std::string CModel::GetLanguage()
{
Lib3MF_uint32 bytesNeededLanguage = 0;
Lib3MF_uint32 bytesWrittenLanguage = 0;
CheckError(lib3mf_model_getlanguage(m_pHandle, 0, &bytesNeededLanguage, nullptr));
std::vector<char> bufferLanguage(bytesNeededLanguage);
CheckError(lib3mf_model_getlanguage(m_pHandle, bytesNeededLanguage, &bytesWrittenLanguage, &bufferLanguage[0]));
return std::string(&bufferLanguage[0]);
}
/**
* CModel::SetLanguage - sets the language of a model
* @param[in] sLanguage - language identifier
*/
void CModel::SetLanguage(const std::string & sLanguage)
{
CheckError(lib3mf_model_setlanguage(m_pHandle, sLanguage.c_str()));
}
/**
* CModel::QueryWriter - creates a model writer instance for a specific file type
* @param[in] sWriterClass - string identifier for the file type
* @return string identifier for the file type
*/
PWriter CModel::QueryWriter(const std::string & sWriterClass)
{
Lib3MFHandle hWriterInstance = nullptr;
CheckError(lib3mf_model_querywriter(m_pHandle, sWriterClass.c_str(), &hWriterInstance));
if (!hWriterInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CWriter>(m_pWrapper, hWriterInstance);
}
/**
* CModel::QueryReader - creates a model reader instance for a specific file type
* @param[in] sReaderClass - string identifier for the file type
* @return string identifier for the file type
*/
PReader CModel::QueryReader(const std::string & sReaderClass)
{
Lib3MFHandle hReaderInstance = nullptr;
CheckError(lib3mf_model_queryreader(m_pHandle, sReaderClass.c_str(), &hReaderInstance));
if (!hReaderInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CReader>(m_pWrapper, hReaderInstance);
}
/**
* CModel::GetTexture2DByID - finds a model texture by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the texture2d instance
*/
PTexture2D CModel::GetTexture2DByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hTextureInstance = nullptr;
CheckError(lib3mf_model_gettexture2dbyid(m_pHandle, nUniqueResourceID, &hTextureInstance));
if (!hTextureInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2D>(m_pWrapper, hTextureInstance);
}
/**
* CModel::GetPropertyTypeByID - returns a Property's type
* @param[in] nUniqueResourceID - Resource ID of the Property to Query
* @return returns a Property's type
*/
ePropertyType CModel::GetPropertyTypeByID(const Lib3MF_uint32 nUniqueResourceID)
{
ePropertyType resultThePropertyType = (ePropertyType) 0;
CheckError(lib3mf_model_getpropertytypebyid(m_pHandle, nUniqueResourceID, &resultThePropertyType));
return resultThePropertyType;
}
/**
* CModel::GetBaseMaterialGroupByID - finds a model base material group by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the BaseMaterialGroup instance
*/
PBaseMaterialGroup CModel::GetBaseMaterialGroupByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hBaseMaterialGroupInstance = nullptr;
CheckError(lib3mf_model_getbasematerialgroupbyid(m_pHandle, nUniqueResourceID, &hBaseMaterialGroupInstance));
if (!hBaseMaterialGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBaseMaterialGroup>(m_pWrapper, hBaseMaterialGroupInstance);
}
/**
* CModel::GetTexture2DGroupByID - finds a model texture2d group by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the Texture2DGroup instance
*/
PTexture2DGroup CModel::GetTexture2DGroupByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hTexture2DGroupInstance = nullptr;
CheckError(lib3mf_model_gettexture2dgroupbyid(m_pHandle, nUniqueResourceID, &hTexture2DGroupInstance));
if (!hTexture2DGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2DGroup>(m_pWrapper, hTexture2DGroupInstance);
}
/**
* CModel::GetCompositeMaterialsByID - finds a model CompositeMaterials by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the CompositeMaterials instance
*/
PCompositeMaterials CModel::GetCompositeMaterialsByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hCompositeMaterialsInstance = nullptr;
CheckError(lib3mf_model_getcompositematerialsbyid(m_pHandle, nUniqueResourceID, &hCompositeMaterialsInstance));
if (!hCompositeMaterialsInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CCompositeMaterials>(m_pWrapper, hCompositeMaterialsInstance);
}
/**
* CModel::GetMultiPropertyGroupByID - finds a model MultiPropertyGroup by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the MultiPropertyGroup instance
*/
PMultiPropertyGroup CModel::GetMultiPropertyGroupByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hMultiPropertyGroupInstance = nullptr;
CheckError(lib3mf_model_getmultipropertygroupbyid(m_pHandle, nUniqueResourceID, &hMultiPropertyGroupInstance));
if (!hMultiPropertyGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMultiPropertyGroup>(m_pWrapper, hMultiPropertyGroupInstance);
}
/**
* CModel::GetMeshObjectByID - finds a mesh object by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the mesh object instance
*/
PMeshObject CModel::GetMeshObjectByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hMeshObjectInstance = nullptr;
CheckError(lib3mf_model_getmeshobjectbyid(m_pHandle, nUniqueResourceID, &hMeshObjectInstance));
if (!hMeshObjectInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMeshObject>(m_pWrapper, hMeshObjectInstance);
}
/**
* CModel::GetComponentsObjectByID - finds a components object by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the components object instance
*/
PComponentsObject CModel::GetComponentsObjectByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hComponentsObjectInstance = nullptr;
CheckError(lib3mf_model_getcomponentsobjectbyid(m_pHandle, nUniqueResourceID, &hComponentsObjectInstance));
if (!hComponentsObjectInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CComponentsObject>(m_pWrapper, hComponentsObjectInstance);
}
/**
* CModel::GetColorGroupByID - finds a model color group by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the ColorGroup instance
*/
PColorGroup CModel::GetColorGroupByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hColorGroupInstance = nullptr;
CheckError(lib3mf_model_getcolorgroupbyid(m_pHandle, nUniqueResourceID, &hColorGroupInstance));
if (!hColorGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CColorGroup>(m_pWrapper, hColorGroupInstance);
}
/**
* CModel::GetSliceStackByID - finds a model slicestack by its UniqueResourceID
* @param[in] nUniqueResourceID - UniqueResourceID
* @return returns the slicestack instance
*/
PSliceStack CModel::GetSliceStackByID(const Lib3MF_uint32 nUniqueResourceID)
{
Lib3MFHandle hSliceStacInstance = nullptr;
CheckError(lib3mf_model_getslicestackbyid(m_pHandle, nUniqueResourceID, &hSliceStacInstance));
if (!hSliceStacInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSliceStack>(m_pWrapper, hSliceStacInstance);
}
/**
* CModel::GetBuildUUID - returns, whether a build has a UUID and, if true, the build's UUID
* @param[out] bHasUUID - flag whether the build has a UUID
* @return the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx'
*/
std::string CModel::GetBuildUUID(bool & bHasUUID)
{
Lib3MF_uint32 bytesNeededUUID = 0;
Lib3MF_uint32 bytesWrittenUUID = 0;
CheckError(lib3mf_model_getbuilduuid(m_pHandle, &bHasUUID, 0, &bytesNeededUUID, nullptr));
std::vector<char> bufferUUID(bytesNeededUUID);
CheckError(lib3mf_model_getbuilduuid(m_pHandle, &bHasUUID, bytesNeededUUID, &bytesWrittenUUID, &bufferUUID[0]));
return std::string(&bufferUUID[0]);
}
/**
* CModel::SetBuildUUID - sets the build's UUID
* @param[in] sUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx'
*/
void CModel::SetBuildUUID(const std::string & sUUID)
{
CheckError(lib3mf_model_setbuilduuid(m_pHandle, sUUID.c_str()));
}
/**
* CModel::GetBuildItems - creates a build item iterator instance with all build items.
* @return returns the iterator instance.
*/
PBuildItemIterator CModel::GetBuildItems()
{
Lib3MFHandle hBuildItemIterator = nullptr;
CheckError(lib3mf_model_getbuilditems(m_pHandle, &hBuildItemIterator));
if (!hBuildItemIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBuildItemIterator>(m_pWrapper, hBuildItemIterator);
}
/**
* CModel::GetOutbox - Returns the outbox of a Model
* @return Outbox of this Model
*/
sBox CModel::GetOutbox()
{
sBox resultOutbox;
CheckError(lib3mf_model_getoutbox(m_pHandle, &resultOutbox));
return resultOutbox;
}
/**
* CModel::GetResources - creates a resource iterator instance with all resources.
* @return returns the iterator instance.
*/
PResourceIterator CModel::GetResources()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getresources(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CResourceIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetObjects - creates a resource iterator instance with all object resources.
* @return returns the iterator instance.
*/
PObjectIterator CModel::GetObjects()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getobjects(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CObjectIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetMeshObjects - creates a resource iterator instance with all mesh object resources.
* @return returns the iterator instance.
*/
PMeshObjectIterator CModel::GetMeshObjects()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getmeshobjects(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMeshObjectIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetComponentsObjects - creates a resource iterator instance with all components object resources.
* @return returns the iterator instance.
*/
PComponentsObjectIterator CModel::GetComponentsObjects()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getcomponentsobjects(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CComponentsObjectIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetTexture2Ds - creates a Texture2DIterator instance with all texture2d resources.
* @return returns the iterator instance.
*/
PTexture2DIterator CModel::GetTexture2Ds()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_gettexture2ds(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2DIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetBaseMaterialGroups - creates a BaseMaterialGroupIterator instance with all base material resources.
* @return returns the iterator instance.
*/
PBaseMaterialGroupIterator CModel::GetBaseMaterialGroups()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getbasematerialgroups(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBaseMaterialGroupIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetColorGroups - creates a ColorGroupIterator instance with all ColorGroup resources.
* @return returns the iterator instance.
*/
PColorGroupIterator CModel::GetColorGroups()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getcolorgroups(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CColorGroupIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetTexture2DGroups - creates a Texture2DGroupIterator instance with all base material resources.
* @return returns the iterator instance.
*/
PTexture2DGroupIterator CModel::GetTexture2DGroups()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_gettexture2dgroups(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2DGroupIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetCompositeMaterials - creates a CompositeMaterialsIterator instance with all CompositeMaterials resources.
* @return returns the iterator instance.
*/
PCompositeMaterialsIterator CModel::GetCompositeMaterials()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getcompositematerials(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CCompositeMaterialsIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetMultiPropertyGroups - creates a MultiPropertyGroupsIterator instance with all MultiPropertyGroup resources.
* @return returns the iterator instance.
*/
PMultiPropertyGroupIterator CModel::GetMultiPropertyGroups()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getmultipropertygroups(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMultiPropertyGroupIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::GetSliceStacks - creates a resource iterator instance with all slice stack resources.
* @return returns the iterator instance.
*/
PSliceStackIterator CModel::GetSliceStacks()
{
Lib3MFHandle hResourceIterator = nullptr;
CheckError(lib3mf_model_getslicestacks(m_pHandle, &hResourceIterator));
if (!hResourceIterator) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSliceStackIterator>(m_pWrapper, hResourceIterator);
}
/**
* CModel::MergeToModel - Merges all components and objects which are referenced by a build item into a mesh. The memory is duplicated and a new model is created.
* @return returns the merged model instance
*/
PModel CModel::MergeToModel()
{
Lib3MFHandle hMergedModelInstance = nullptr;
CheckError(lib3mf_model_mergetomodel(m_pHandle, &hMergedModelInstance));
if (!hMergedModelInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CModel>(m_pWrapper, hMergedModelInstance);
}
/**
* CModel::AddMeshObject - adds an empty mesh object to the model.
* @return returns the mesh object instance
*/
PMeshObject CModel::AddMeshObject()
{
Lib3MFHandle hMeshObjectInstance = nullptr;
CheckError(lib3mf_model_addmeshobject(m_pHandle, &hMeshObjectInstance));
if (!hMeshObjectInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMeshObject>(m_pWrapper, hMeshObjectInstance);
}
/**
* CModel::AddComponentsObject - adds an empty component object to the model.
* @return returns the components object instance
*/
PComponentsObject CModel::AddComponentsObject()
{
Lib3MFHandle hComponentsObjectInstance = nullptr;
CheckError(lib3mf_model_addcomponentsobject(m_pHandle, &hComponentsObjectInstance));
if (!hComponentsObjectInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CComponentsObject>(m_pWrapper, hComponentsObjectInstance);
}
/**
* CModel::AddSliceStack - creates a new model slicestack by its id
* @param[in] dZBottom - Bottom Z value of the slicestack
* @return returns the new slicestack instance
*/
PSliceStack CModel::AddSliceStack(const Lib3MF_double dZBottom)
{
Lib3MFHandle hSliceStackInstance = nullptr;
CheckError(lib3mf_model_addslicestack(m_pHandle, dZBottom, &hSliceStackInstance));
if (!hSliceStackInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CSliceStack>(m_pWrapper, hSliceStackInstance);
}
/**
* CModel::AddTexture2DFromAttachment - adds a texture2d resource to the model. Its path is given by that of an existing attachment.
* @param[in] pTextureAttachment - attachment containing the image data.
* @return returns the new texture instance.
*/
PTexture2D CModel::AddTexture2DFromAttachment(CAttachment * pTextureAttachment)
{
Lib3MFHandle hTextureAttachment = nullptr;
if (pTextureAttachment != nullptr) {
hTextureAttachment = pTextureAttachment->GetHandle();
};
Lib3MFHandle hTexture2DInstance = nullptr;
CheckError(lib3mf_model_addtexture2dfromattachment(m_pHandle, hTextureAttachment, &hTexture2DInstance));
if (!hTexture2DInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2D>(m_pWrapper, hTexture2DInstance);
}
/**
* CModel::AddBaseMaterialGroup - adds an empty BaseMaterialGroup resource to the model.
* @return returns the new base material instance.
*/
PBaseMaterialGroup CModel::AddBaseMaterialGroup()
{
Lib3MFHandle hBaseMaterialGroupInstance = nullptr;
CheckError(lib3mf_model_addbasematerialgroup(m_pHandle, &hBaseMaterialGroupInstance));
if (!hBaseMaterialGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBaseMaterialGroup>(m_pWrapper, hBaseMaterialGroupInstance);
}
/**
* CModel::AddColorGroup - adds an empty ColorGroup resource to the model.
* @return returns the new ColorGroup instance.
*/
PColorGroup CModel::AddColorGroup()
{
Lib3MFHandle hColorGroupInstance = nullptr;
CheckError(lib3mf_model_addcolorgroup(m_pHandle, &hColorGroupInstance));
if (!hColorGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CColorGroup>(m_pWrapper, hColorGroupInstance);
}
/**
* CModel::AddTexture2DGroup - adds an empty Texture2DGroup resource to the model.
* @param[in] pTexture2DInstance - The texture2D instance of the created Texture2DGroup.
* @return returns the new Texture2DGroup instance.
*/
PTexture2DGroup CModel::AddTexture2DGroup(CTexture2D * pTexture2DInstance)
{
Lib3MFHandle hTexture2DInstance = nullptr;
if (pTexture2DInstance != nullptr) {
hTexture2DInstance = pTexture2DInstance->GetHandle();
};
Lib3MFHandle hTexture2DGroupInstance = nullptr;
CheckError(lib3mf_model_addtexture2dgroup(m_pHandle, hTexture2DInstance, &hTexture2DGroupInstance));
if (!hTexture2DGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CTexture2DGroup>(m_pWrapper, hTexture2DGroupInstance);
}
/**
* CModel::AddCompositeMaterials - adds an empty CompositeMaterials resource to the model.
* @param[in] pBaseMaterialGroupInstance - The BaseMaterialGroup instance of the created CompositeMaterials.
* @return returns the new CompositeMaterials instance.
*/
PCompositeMaterials CModel::AddCompositeMaterials(CBaseMaterialGroup * pBaseMaterialGroupInstance)
{
Lib3MFHandle hBaseMaterialGroupInstance = nullptr;
if (pBaseMaterialGroupInstance != nullptr) {
hBaseMaterialGroupInstance = pBaseMaterialGroupInstance->GetHandle();
};
Lib3MFHandle hCompositeMaterialsInstance = nullptr;
CheckError(lib3mf_model_addcompositematerials(m_pHandle, hBaseMaterialGroupInstance, &hCompositeMaterialsInstance));
if (!hCompositeMaterialsInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CCompositeMaterials>(m_pWrapper, hCompositeMaterialsInstance);
}
/**
* CModel::AddMultiPropertyGroup - adds an empty MultiPropertyGroup resource to the model.
* @return returns the new MultiPropertyGroup instance.
*/
PMultiPropertyGroup CModel::AddMultiPropertyGroup()
{
Lib3MFHandle hMultiPropertyGroupInstance = nullptr;
CheckError(lib3mf_model_addmultipropertygroup(m_pHandle, &hMultiPropertyGroupInstance));
if (!hMultiPropertyGroupInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMultiPropertyGroup>(m_pWrapper, hMultiPropertyGroupInstance);
}
/**
* CModel::AddBuildItem - adds a build item to the model.
* @param[in] pObject - Object instance.
* @param[in] Transform - Transformation matrix.
* @return returns the build item instance.
*/
PBuildItem CModel::AddBuildItem(CObject * pObject, const sTransform & Transform)
{
Lib3MFHandle hObject = nullptr;
if (pObject != nullptr) {
hObject = pObject->GetHandle();
};
Lib3MFHandle hBuildItemInstance = nullptr;
CheckError(lib3mf_model_addbuilditem(m_pHandle, hObject, &Transform, &hBuildItemInstance));
if (!hBuildItemInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CBuildItem>(m_pWrapper, hBuildItemInstance);
}
/**
* CModel::RemoveBuildItem - removes a build item from the model
* @param[in] pBuildItemInstance - Build item to remove.
*/
void CModel::RemoveBuildItem(CBuildItem * pBuildItemInstance)
{
Lib3MFHandle hBuildItemInstance = nullptr;
if (pBuildItemInstance != nullptr) {
hBuildItemInstance = pBuildItemInstance->GetHandle();
};
CheckError(lib3mf_model_removebuilditem(m_pHandle, hBuildItemInstance));
}
/**
* CModel::GetMetaDataGroup - Returns the metadata of the model as MetaDataGroup
* @return returns an Instance of the metadatagroup of the model
*/
PMetaDataGroup CModel::GetMetaDataGroup()
{
Lib3MFHandle hTheMetaDataGroup = nullptr;
CheckError(lib3mf_model_getmetadatagroup(m_pHandle, &hTheMetaDataGroup));
if (!hTheMetaDataGroup) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CMetaDataGroup>(m_pWrapper, hTheMetaDataGroup);
}
/**
* CModel::AddAttachment - adds an attachment stream to the model. The OPC part will be related to the model stream with a certain relationship type.
* @param[in] sURI - Path of the attachment
* @param[in] sRelationShipType - Relationship type of the attachment
* @return Instance of the attachment object
*/
PAttachment CModel::AddAttachment(const std::string & sURI, const std::string & sRelationShipType)
{
Lib3MFHandle hAttachmentInstance = nullptr;
CheckError(lib3mf_model_addattachment(m_pHandle, sURI.c_str(), sRelationShipType.c_str(), &hAttachmentInstance));
if (!hAttachmentInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CAttachment>(m_pWrapper, hAttachmentInstance);
}
/**
* CModel::RemoveAttachment - Removes attachment from the model.
* @param[in] pAttachmentInstance - Attachment instance to remove
*/
void CModel::RemoveAttachment(CAttachment * pAttachmentInstance)
{
Lib3MFHandle hAttachmentInstance = nullptr;
if (pAttachmentInstance != nullptr) {
hAttachmentInstance = pAttachmentInstance->GetHandle();
};
CheckError(lib3mf_model_removeattachment(m_pHandle, hAttachmentInstance));
}
/**
* CModel::GetAttachment - retrieves an attachment stream object from the model..
* @param[in] nIndex - Index of the attachment stream
* @return Instance of the attachment object
*/
PAttachment CModel::GetAttachment(const Lib3MF_uint32 nIndex)
{
Lib3MFHandle hAttachmentInstance = nullptr;
CheckError(lib3mf_model_getattachment(m_pHandle, nIndex, &hAttachmentInstance));
if (!hAttachmentInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CAttachment>(m_pWrapper, hAttachmentInstance);
}
/**
* CModel::FindAttachment - retrieves an attachment stream object from the model.
* @param[in] sURI - Path URI in the package
* @return Instance of the attachment object
*/
PAttachment CModel::FindAttachment(const std::string & sURI)
{
Lib3MFHandle hAttachmentInstance = nullptr;
CheckError(lib3mf_model_findattachment(m_pHandle, sURI.c_str(), &hAttachmentInstance));
if (!hAttachmentInstance) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CAttachment>(m_pWrapper, hAttachmentInstance);
}
/**
* CModel::GetAttachmentCount - retrieves the number of attachments of the model.
* @return Returns the number of attachments.
*/
Lib3MF_uint32 CModel::GetAttachmentCount()
{
Lib3MF_uint32 resultAttachmentCount = 0;
CheckError(lib3mf_model_getattachmentcount(m_pHandle, &resultAttachmentCount));
return resultAttachmentCount;
}
/**
* CModel::HasPackageThumbnailAttachment - Retrieve whether the OPC package contains a package thumbnail.
* @return returns whether the OPC package contains a package thumbnail
*/
bool CModel::HasPackageThumbnailAttachment()
{
bool resultHasThumbnail = 0;
CheckError(lib3mf_model_haspackagethumbnailattachment(m_pHandle, &resultHasThumbnail));
return resultHasThumbnail;
}
/**
* CModel::CreatePackageThumbnailAttachment - Create a new or the existing package thumbnail for the OPC package.
* @return Instance of a new or the existing thumbnailattachment object.
*/
PAttachment CModel::CreatePackageThumbnailAttachment()
{
Lib3MFHandle hAttachment = nullptr;
CheckError(lib3mf_model_createpackagethumbnailattachment(m_pHandle, &hAttachment));
if (!hAttachment) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CAttachment>(m_pWrapper, hAttachment);
}
/**
* CModel::GetPackageThumbnailAttachment - Get the attachment to the OPC package containing the package thumbnail.
* @return Instance of the thumbnailattachment object or NULL.
*/
PAttachment CModel::GetPackageThumbnailAttachment()
{
Lib3MFHandle hAttachment = nullptr;
CheckError(lib3mf_model_getpackagethumbnailattachment(m_pHandle, &hAttachment));
if (hAttachment) {
return std::make_shared<CAttachment>(m_pWrapper, hAttachment);
} else {
return nullptr;
}
}
/**
* CModel::RemovePackageThumbnailAttachment - Remove the attachment to the OPC package containing the package thumbnail.
*/
void CModel::RemovePackageThumbnailAttachment()
{
CheckError(lib3mf_model_removepackagethumbnailattachment(m_pHandle));
}
/**
* CModel::AddCustomContentType - Adds a new Content Type to the model.
* @param[in] sExtension - File Extension
* @param[in] sContentType - Content Type Identifier
*/
void CModel::AddCustomContentType(const std::string & sExtension, const std::string & sContentType)
{
CheckError(lib3mf_model_addcustomcontenttype(m_pHandle, sExtension.c_str(), sContentType.c_str()));
}
/**
* CModel::RemoveCustomContentType - Removes a custom Content Type from the model (UTF8 version).
* @param[in] sExtension - File Extension
*/
void CModel::RemoveCustomContentType(const std::string & sExtension)
{
CheckError(lib3mf_model_removecustomcontenttype(m_pHandle, sExtension.c_str()));
}
/**
* CModel::SetRandomNumberCallback - Sets the random number generator callback for use in the library
* @param[in] pTheCallback - The callback used to generate random numbers
* @param[in] pUserData - Userdata to be passed to the callback function
*/
void CModel::SetRandomNumberCallback(const RandomNumberCallback pTheCallback, const Lib3MF_pvoid pUserData)
{
CheckError(lib3mf_model_setrandomnumbercallback(m_pHandle, pTheCallback, pUserData));
}
/**
* CModel::GetKeyStore - Gets the keystore associated with this model
* @return The package keystore
*/
PKeyStore CModel::GetKeyStore()
{
Lib3MFHandle hKeyStore = nullptr;
CheckError(lib3mf_model_getkeystore(m_pHandle, &hKeyStore));
if (!hKeyStore) {
CheckError(LIB3MF_ERROR_INVALIDPARAM);
}
return std::make_shared<CKeyStore>(m_pWrapper, hKeyStore);
}
} // namespace Lib3MF
#endif // __LIB3MF_CPPHEADER_IMPLICIT_CPP
| 36.373248 | 525 | 0.736796 | alexanderoster |
6429bf15428badc280d0bca7f4bf7c4291572b7c | 10,154 | cpp | C++ | src/forwardingmetaobject.cpp | msorvig/qt-quick-bindings | 43408197e9b05b41814ca49ce50b5902c0d5add9 | [
"MIT"
] | 1 | 2015-06-08T05:15:17.000Z | 2015-06-08T05:15:17.000Z | src/forwardingmetaobject.cpp | msorvig/qt-quick-bindings | 43408197e9b05b41814ca49ce50b5902c0d5add9 | [
"MIT"
] | null | null | null | src/forwardingmetaobject.cpp | msorvig/qt-quick-bindings | 43408197e9b05b41814ca49ce50b5902c0d5add9 | [
"MIT"
] | null | null | null | #include "forwardingmetaobject.h"
#include <QtCore/QtCore>
#include <QtCore/private/qmetaobjectbuilder_p.h>
#include <QtQuick/QQuickItem>
ForwardMetaObjectBuilder::ForwardMetaObjectBuilder()
{
builder = new QMetaObjectBuilder;
builder->setSuperClass(&QQuickItem::staticMetaObject);
//builder->setStaticMetacallFunction(ForwardObject::qt_static_metacall);
}
ForwardMetaObjectBuilder::~ForwardMetaObjectBuilder()
{
delete builder;
}
void ForwardMetaObjectBuilder::setClassName(const QByteArray &name)
{
builder->setClassName(name);
}
void ForwardMetaObjectBuilder::setSuperClass(const QMetaObject *metaObject)
{
builder->setSuperClass(metaObject);
}
void ForwardMetaObjectBuilder::addProperty(const QByteArray &propertyName, const QByteArray &typeName)
{
// names
QByteArray signalName = propertyNotifySignalName(propertyName, typeName);
QByteArray signalParameterName = "newValue";
// property
QMetaPropertyBuilder prop = builder->addProperty(propertyName, typeName);
// qDebug() << "property" << propertyName << prop.index();
// notifier
QMetaMethodBuilder intPropChanged = builder->addSignal(signalName);
intPropChanged.setParameterNames(QList<QByteArray>() << signalParameterName);
prop.setNotifySignal(intPropChanged);
}
QByteArray ForwardMetaObjectBuilder::propertyNotifySignalName(const QByteArray &propertyName,
const QByteArray &typeName)
{
return propertyName + "Changed(" + typeName + ")";
}
QMetaObjectBuilder *ForwardMetaObjectBuilder::metaObjectBuilder()
{
return builder;
}
QMetaObject *ForwardMetaObjectBuilder::metaObject()
{
// qDebug() << __PRETTY_FUNCTION__;
builder->addConstructor(builder->className() + "(QObject*)");
builder->addConstructor(builder->className() + "()");
// QMetaMethodBuilder foo = builder.addMethod("foo(QString)");
// foo.setReturnType("void");
// foo.setParameterNames(QList<QByteArray>() << "qstringArg");
// setter?
// QByteArray slotName = "voidSlot" + typeName + "(" + typeName + ")";
// QMetaMethodBuilder voidSlotInt = builder.addSlot(slotName);
// voidSlotInt.setParameterNames(QList<QByteArray>() << signalParameterName);
// Create the new metaOBejct
QMetaObject *metaObject = builder->toMetaObject();
// Set the static meta object here in order for it to be
// a valid during reigstration with QML. This will of
// course override any previously set meta object.
//ForwardObject::staticMetaObject = *metaObject;
//SimpleForwardObject::staticMetaObject = *metaObject;
return metaObject;
}
/*
QMetaObject ForwardObject::staticMetaObject = {
{ 0, 0, 0, 0, 0, 0 }
};
QMetaObject SimpleForwardObject::staticMetaObject = {
{ 0, 0, 0, 0, 0, 0 }
};
ForwardObject::ForwardObject(QObject *parent)
: QObject(parent), m_metaObject(&staticMetaObject)
{
}
void ForwardObject::setMetaObject(const QMetaObject *metaObject)
{
m_metaObject = metaObject;
}
void ForwardObject::propertyChange(const QByteArray name)
{
//QByteArray signalName = name + "Changed(" + typeName + ")";
//int signal = m_metaObject->indexOfSignal(signalName);
//char *argv = 0;
//m_metaObject->activate(this, signal, &argv);
}
ForwardObject::~ForwardObject()
{
//free(m_metaObject);
}
void ForwardObject::init()
{
}
QVariant ForwardObject::readProperty(const QByteArray &name)
{
qDebug() << __PRETTY_FUNCTION__ << name;
return QVariant();
}
void ForwardObject::wrtiteProperty(const QByteArray &name, const QVariant &value)
{
qDebug() << __PRETTY_FUNCTION__ << name << value;
}
void ForwardObject::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
qDebug() << __PRETTY_FUNCTION__ << _o << _id;
if (_c == QMetaObject::CreateInstance) {
switch (_id) {
case 0: {
ForwardObject *_r = new ForwardObject((*reinterpret_cast< QObject*(*)>(_a[1])));
if (_a[0]) *reinterpret_cast<QObject**>(_a[0]) = _r;
} break;
case 1: {
ForwardObject *_r = new ForwardObject();
if (_a[0]) *reinterpret_cast<QObject**>(_a[0]) = _r;
} break;
default: {
QMetaMethod ctor = _o->metaObject()->constructor(_id);
qFatal("You forgot to add a case for CreateInstance %s", ctor.methodSignature().constData());
}
}
} else if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(_o->metaObject()->cast(_o));
ForwardObject *_t = static_cast<ForwardObject *>(_o);
//qDebug() << " qt_static_metacall InvokeMetaMethod" << _id;
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
//qDebug() << " qt_static_metacall IndexOfMethod" << *func;
*result = 0;
}
}
const QMetaObject *ForwardObject::metaObject() const
{
qDebug() << __PRETTY_FUNCTION__;
return m_metaObject;
}
void *ForwardObject::qt_metacast(const char *_clname)
{
qDebug() << __PRETTY_FUNCTION__;
if (!_clname) return 0;
if (!strcmp(_clname, "ForwardingMetaObject"))
return static_cast<void*>(const_cast< ForwardObject*>(this));
return QObject::qt_metacast(_clname);
}
int ForwardObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
qDebug() << this << __PRETTY_FUNCTION__;
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
int ownMethodCount = m_metaObject->methodCount() - m_metaObject->methodOffset();
int ownPropertyCount = m_metaObject->propertyCount() - m_metaObject->propertyOffset();
int ownId = _id + m_metaObject->propertyOffset();
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < ownMethodCount)
qt_static_metacall(this, _c, _id, _a);
_id -= ownMethodCount;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
qDebug() << " qt_metacall ReadProperty" << _id << ownPropertyCount;
QMetaProperty property = m_metaObject->property(ownId);
QByteArray name = property.name();
QVariant value = readProperty(name);
// ### now _v is a T *, which we want to copy the value into.
switch (property.type()) {
case QMetaType::Int: *static_cast<int *>(_v) = value.toInt(); break;
case QMetaType::QString: *static_cast<QString *>(_v) = value.toString(); break;
default:
qDebug() << "ForwardObject::qt_metacall: Unsupported type" << property.typeName();
};
_id -= ownPropertyCount;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
qDebug() << " qt_metacall WriteProperty" << _id << ownPropertyCount << m_metaObject->propertyCount() << m_metaObject->propertyOffset();
QMetaProperty property = m_metaObject->property(ownId);
QByteArray name = property.name();
QVariant value = QVariant(property.type(), _v);
wrtiteProperty(name, value);
_id -= ownPropertyCount;
} else if (_c == QMetaObject::ResetProperty) {
_id -= ownPropertyCount;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= ownPropertyCount;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= ownPropertyCount;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= ownPropertyCount;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= ownPropertyCount;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= ownPropertyCount;
}
#endif // QT_NO_PROPERTIES
return _id;
}
void SimpleForwardObject::setMetaObject(const QMetaObject *metaObject)
{
qDebug() << "SimpleForwardObject setMetaObject" << metaObject;
m_metaObject = metaObject;
}
const QMetaObject *SimpleForwardObject::metaObject() const
{
qDebug() << __PRETTY_FUNCTION__;
return m_metaObject;
}
int SimpleForwardObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
//qDebug() << this << __PRETTY_FUNCTION__ << _id;
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
int ownMethodCount = m_metaObject->methodCount() - m_metaObject->methodOffset();
int ownPropertyCount = m_metaObject->propertyCount() - m_metaObject->propertyOffset();
int ownId = _id + m_metaObject->propertyOffset();
if (_c == QMetaObject::InvokeMetaMethod) {
} else if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
//qDebug() << " qt_metacall ReadProperty" << _id << ownPropertyCount;
QMetaProperty property = m_metaObject->property(ownId);
QByteArray name = property.name();
QVariant value = readProperty(name);
// ### now _v is a T *, which we want to copy the value into.
//MetaType::convert(
//QVariant::convert(c
switch (property.type()) {
// case QMetaType::Int: *static_cast<int *>(_v) = value.toInt(); break;
//case QMetaType::QString: *static_cast<QString *>(_v) = value.toString(); break;
default:
qDebug() << "ForwardObject::qt_metacall: Unsupported type" << property.typeName();
};
_id -= ownPropertyCount;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
// qDebug() << " qt_metacall WriteProperty" << _id << ownPropertyCount << m_metaObject->propertyCount() << m_metaObject->propertyOffset();
QMetaProperty property = m_metaObject->property(ownId);
QByteArray name = property.name();
QVariant value = QVariant(property.type(), _v);
wrtiteProperty(name, value);
_id -= ownPropertyCount;
}
return _id;
}
QVariant SimpleForwardObject::readProperty(const QByteArray &name)
{
qDebug() << __PRETTY_FUNCTION__ << name;
return QVariant();
}
void SimpleForwardObject::wrtiteProperty(const QByteArray &name, const QVariant &value)
{
qDebug() << __PRETTY_FUNCTION__ << name << value;
}
*/
| 33.846667 | 152 | 0.657869 | msorvig |
642ac146ea49c5af7d95b6b5fe0279ff74ee7dfa | 3,107 | cpp | C++ | Firmware/Drivers/STM32/stm32_pwm_input.cpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | 1 | 2021-02-19T09:44:02.000Z | 2021-02-19T09:44:02.000Z | Firmware/Drivers/STM32/stm32_pwm_input.cpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | null | null | null | Firmware/Drivers/STM32/stm32_pwm_input.cpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | null | null | null |
#include "stm32_pwm_input.hpp"
#include "stm32_timer.hpp"
#include <algorithm>
void Stm32PwmInput::init(std::array<bool, 4> enable_channels) {
Stm32Timer{htim_->Instance}.enable_clock();
TIM_IC_InitTypeDef sConfigIC;
sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE;
sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
sConfigIC.ICFilter = 15;
uint32_t channels[] = {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4};
for (size_t i = 0; i < 4; ++i) {
if (enable_channels[i]) {
HAL_TIM_IC_ConfigChannel(htim_, &sConfigIC, channels[i]);
HAL_TIM_IC_Start_IT(htim_, channels[i]);
}
}
}
//TODO: These expressions have integer division by 1MHz, so it will be incorrect for clock speeds of not-integer MHz
#define TIM_2_5_CLOCK_HZ TIM_APB1_CLOCK_HZ
#define PWM_MIN_HIGH_TIME ((TIM_2_5_CLOCK_HZ / 1000000UL) * 1000UL) // 1ms high is considered full reverse
#define PWM_MAX_HIGH_TIME ((TIM_2_5_CLOCK_HZ / 1000000UL) * 2000UL) // 2ms high is considered full forward
#define PWM_MIN_LEGAL_HIGH_TIME ((TIM_2_5_CLOCK_HZ / 1000000UL) * 500UL) // ignore high periods shorter than 0.5ms
#define PWM_MAX_LEGAL_HIGH_TIME ((TIM_2_5_CLOCK_HZ / 1000000UL) * 2500UL) // ignore high periods longer than 2.5ms
#define PWM_INVERT_INPUT false
/**
* @param channel: A channel number in [0, 3]
*/
void Stm32PwmInput::handle_pulse(int channel, uint32_t high_time) {
if (high_time < PWM_MIN_LEGAL_HIGH_TIME || high_time > PWM_MAX_LEGAL_HIGH_TIME)
return;
high_time = std::clamp(high_time, PWM_MIN_HIGH_TIME, PWM_MAX_HIGH_TIME);
float fraction = (float)(high_time - PWM_MIN_HIGH_TIME) / (float)(PWM_MAX_HIGH_TIME - PWM_MIN_HIGH_TIME);
pwm_values_[channel] = fraction;
}
/**
* @param channel: A channel number in [0, 3]
*/
void Stm32PwmInput::on_capture(int channel, uint32_t timestamp) {
if (channel >= 4)
return;
Stm32Gpio gpio = gpios_[channel];
if (!gpio)
return;
bool current_pin_state = gpio.read();
if (last_sample_valid_[channel]
&& (last_pin_state_[channel] != PWM_INVERT_INPUT)
&& (current_pin_state == PWM_INVERT_INPUT)) {
handle_pulse(channel, timestamp - last_timestamp_[channel]);
}
last_timestamp_[channel] = timestamp;
last_pin_state_[channel] = current_pin_state;
last_sample_valid_[channel] = true;
}
void Stm32PwmInput::on_capture() {
if(__HAL_TIM_GET_FLAG(htim_, TIM_FLAG_CC1)) {
__HAL_TIM_CLEAR_IT(htim_, TIM_IT_CC1);
on_capture(0, htim_->Instance->CCR1);
}
if(__HAL_TIM_GET_FLAG(htim_, TIM_FLAG_CC2)) {
__HAL_TIM_CLEAR_IT(htim_, TIM_IT_CC2);
on_capture(1, htim_->Instance->CCR2);
}
if(__HAL_TIM_GET_FLAG(htim_, TIM_FLAG_CC3)) {
__HAL_TIM_CLEAR_IT(htim_, TIM_IT_CC3);
on_capture(2, htim_->Instance->CCR3);
}
if(__HAL_TIM_GET_FLAG(htim_, TIM_FLAG_CC4)) {
__HAL_TIM_CLEAR_IT(htim_, TIM_IT_CC4);
on_capture(3, htim_->Instance->CCR4);
}
}
| 36.127907 | 117 | 0.698745 | takijo0116 |
642f0fcb15e46b12e3b121e31b8c2930b5c4832e | 1,489 | cpp | C++ | src/Kernel.cpp | JesseMaurais/SGe | f73bd03d30074a54642847b05f82151128481371 | [
"MIT"
] | 1 | 2017-04-20T06:27:36.000Z | 2017-04-20T06:27:36.000Z | src/Kernel.cpp | JesseMaurais/SGe | f73bd03d30074a54642847b05f82151128481371 | [
"MIT"
] | null | null | null | src/Kernel.cpp | JesseMaurais/SGe | f73bd03d30074a54642847b05f82151128481371 | [
"MIT"
] | null | null | null | #include "Kernel.hpp"
#include "OpenCL.hpp"
namespace
{
class Kernel::Program
{
public:
bool CreateProgram() = 0;
bool UpdateSource() override;
protected:
cl_program program = nullptr;
private:
static void OnNotify(cl_program program, void *that);
};
class SourceCode : public Kernel::Program
{
public:
SourceCode(std::string sourceCode);
bool CreateProgram() override;
private:
std::string sourceCode;
};
}
bool SourceCode::CreateProgram()
{
// Split the code into lines.
std::vector<std::string> lines;
str::split(lines, sourceCode, "\n");
// Collect raw C strings.
std::vector<std::size_t> lengths;
std::vector<char const *> strings;
for (auto const &line : lines)
{
lengths.emplace_back(line.size());
strings.emplace_back(line.data());
}
// Create from source lines
cl_context const context = OpenCL::GetContext();
if (context)
{
cl_int error;
program = clCreateProgramWithSource(context, lines.size(), strings.data(), lengths.data(), &error);
if (OpenCL::CheckError("clCreateProgramWithSource", error))
{
SDL::LogError(CannotAllocateResource);
}
}
return program;
}
bool Kernel::Program::UpdateSource()
{
if (CreateProgram())
{
auto &devices = OpenCL::GetDeviceIDs();
cl_int error = clBuildProgram(program, devices.size(), devices.data(), options.c_str(), OnNotify, this);
if (not OpenCL::CheckError("clBuildProgram", error))
{
return true;
}
SDL::LogError(CannotBuildProgram);
}
return false;
}
| 19.592105 | 106 | 0.696441 | JesseMaurais |
6433a87c0bdfdf0e77a1313427a02b41ad34981f | 1,939 | hpp | C++ | modules/boost/simd/base/include/boost/simd/constant/constants/fact_9.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/boost/simd/base/include/boost/simd/constant/constants/fact_9.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/boost/simd/base/include/boost/simd/constant/constants/fact_9.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 9623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_FACT_9_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_CONSTANTS_FACT_9_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/simd/constant/register.hpp>
#include <boost/simd/constant/hierarchy.hpp>
#include <boost/config.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4310) // truncation of constant
#endif
namespace boost { namespace simd
{
namespace tag
{
/*!
@brief Fact_9 generic tag
Represents the Fact_9 constant in generic contexts.
@par Models:
Hierarchy
**/
BOOST_SIMD_CONSTANT_REGISTER( Fact_9,double
, 362880, 0x48b13000,0x4116260000000000ll
)
}
namespace ext
{
template<class Site, class... Ts>
BOOST_FORCEINLINE generic_dispatcher<tag::Fact_9, Site> dispatching_Fact_9(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
{
return generic_dispatcher<tag::Fact_9, Site>();
}
template<class... Args>
struct impl_Fact_9;
}
/*!
Generates 9! that is 362880,
@par Semantic:
@code
T r = Fact_9<T>();
@endcode
is similar to:
@code
T r = T(362880);
@endcode
**/
BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Fact_9, Fact_9)
} }
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#include <boost/simd/constant/common.hpp>
#endif
| 26.202703 | 168 | 0.606498 | psiha |
643650585d5705b7609d0c32f3ba10728c9da6c2 | 30,883 | cpp | C++ | src/Inventor/Gtk/SoGtkComponent.cpp | coin3d/sogtk | 822e290109ef2fb8a4df75dcbf8acf70c5167549 | [
"BSD-3-Clause"
] | null | null | null | src/Inventor/Gtk/SoGtkComponent.cpp | coin3d/sogtk | 822e290109ef2fb8a4df75dcbf8acf70c5167549 | [
"BSD-3-Clause"
] | null | null | null | src/Inventor/Gtk/SoGtkComponent.cpp | coin3d/sogtk | 822e290109ef2fb8a4df75dcbf8acf70c5167549 | [
"BSD-3-Clause"
] | 1 | 2020-05-13T13:52:51.000Z | 2020-05-13T13:52:51.000Z | /**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* 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
* 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.
\**************************************************************************/
// *************************************************************************
// Class documentation in common/SoGuiComponentCommon.cpp.in.
// *************************************************************************
#if HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#include <stdio.h>
#include <string.h>
#include <Inventor/Gtk/SoGtk.h>
#include <Inventor/Gtk/SoGtkComponent.h>
#include <Inventor/Gtk/SoGtkComponentP.h>
#include <Inventor/Gtk/SoGtkCursor.h>
#include <Inventor/Gtk/SoGtkGLWidget.h>
#include <Inventor/Gtk/SoGtkGraphEditor.h>
#include <Inventor/Gtk/SoGtkRenderArea.h>
#include <Inventor/Gtk/SoGtkRoster.h>
#include <Inventor/Gtk/viewers/SoGtkConstrainedViewer.h>
#include <Inventor/Gtk/viewers/SoGtkExaminerViewer.h>
#include <Inventor/Gtk/viewers/SoGtkFlyViewer.h>
#include <Inventor/Gtk/viewers/SoGtkFullViewer.h>
#include <Inventor/Gtk/viewers/SoGtkPlaneViewer.h>
#include <Inventor/Gtk/viewers/SoGtkViewer.h>
#include <Inventor/errors/SoDebugError.h>
#include <sogtkdefs.h>
// *************************************************************************
GdkCursor * SoGtkComponentP::arrowcursor = NULL;
GdkCursor * SoGtkComponentP::crosscursor = NULL;
GdkCursor * SoGtkComponentP::uparrowcursor = NULL;
SbDict * SoGtkComponentP::cursordict = NULL;
// *************************************************************************
SOGTK_OBJECT_ABSTRACT_SOURCE(SoGtkComponent);
// documented in common/SoGuiComponentCommon.cpp.in.
void
SoGtkComponent::initClasses(void)
{
SoGtkComponent::initClass();
SoGtkGLWidget::initClass();
SoGtkRenderArea::initClass();
SoGtkViewer::initClass();
SoGtkFullViewer::initClass();
SoGtkExaminerViewer::initClass();
SoGtkPlaneViewer::initClass();
SoGtkConstrainedViewer::initClass();
#if 0 // TMP DISABLED: walkviewer not properly implemented yet. 20020624 mortene.
SoGtkWalkViewer::initClass();
#endif // TMP DISABLED
SoGtkFlyViewer::initClass();
SoGtkGraphEditor::initClass();
SoGtkRoster::initClass();
}
// *************************************************************************
/*!
Constructor.
\a parent is the widget we'll build this component inside. If \a
parent is \a NULL, make a new top level window.
\a name is mostly interesting for debugging purposes.
\a embed specifies whether or not we should make a new top level
window for the component even when we've got a non-NULL \a parent.
*/
SoGtkComponent::SoGtkComponent(GtkWidget * const parent,
const char * const name,
const SbBool embed)
{
PRIVATE(this) = new SoGtkComponentP(this);
PRIVATE(this)->parent = parent;
if (name) {
PRIVATE(this)->widgetName = strcpy(new char [strlen(name)+1], name);
}
this->setClassName("SoGtkComponent");
if (parent == NULL || ! embed) {
PRIVATE(this)->parent = gtk_window_new(GTK_WINDOW_TOPLEVEL);
PRIVATE(this)->shelled = TRUE;
PRIVATE(this)->embedded = FALSE;
}
else if (parent == SoGtk::getTopLevelWidget()) {
PRIVATE(this)->embedded = FALSE; // what if...?
}
else {
PRIVATE(this)->embedded = TRUE;
}
gtk_signal_connect(GTK_OBJECT(PRIVATE(this)->parent), "event",
GTK_SIGNAL_FUNC(SoGtkComponent::eventHandler),
(gpointer) this);
gtk_idle_add((GtkFunction) SoGtk::componentCreation, (gpointer) this);
}
/*!
Destructor.
*/
SoGtkComponent::~SoGtkComponent()
{
if (PRIVATE(this)->widget) {
this->unregisterWidget(PRIVATE(this)->widget);
}
SoGtk::componentDestruction(this);
// FIXME: this is tmp disabled as it causes a
// segfault. Investigate. 20020107 mortene.
#if 0
if (PRIVATE(this)->widget) { gtk_widget_destroy(PRIVATE(this)->widget); }
#endif
delete PRIVATE(this);
}
// *************************************************************************
/*!
Add a callback which will be called whenever the widget component
changes visibility status (because of iconification or
deiconification, for instance).
\sa removeVisibilityChangeCallback(), isVisible()
*/
void
SoGtkComponent::addVisibilityChangeCallback(SoGtkComponentVisibilityCB * const func,
void * const userData)
{
if (! PRIVATE(this)->visibilityChangeCBs) {
PRIVATE(this)->visibilityChangeCBs = new SbPList;
}
PRIVATE(this)->visibilityChangeCBs->append((void *) func);
PRIVATE(this)->visibilityChangeCBs->append(userData);
}
/*!
Remove one of the callbacks from the list of visibility notification
callbacks.
\sa addVisibilityChangeCallback(), isVisible()
*/
void
SoGtkComponent::removeVisibilityChangeCallback(SoGtkComponentVisibilityCB * const func,
void * const userData)
{
#if SOGTK_DEBUG
if (! PRIVATE(this)->visibilityChangeCBs) {
SoDebugError::postWarning("SoGtkComponent::removeVisibilityChangeCallback",
"empty callback list");
return;
}
#endif // SOGTK_DEBUG
int idx = PRIVATE(this)->visibilityChangeCBs->find((void *)func);
if (idx != -1) {
PRIVATE(this)->visibilityChangeCBs->remove(idx);
PRIVATE(this)->visibilityChangeCBs->remove(idx);
}
#if SOGTK_DEBUG
if (idx == -1) {
SoDebugError::postWarning("SoGtkComponent::removeVisibilityChangeCallback",
"tried to remove non-existant callback");
return;
}
#endif // SOGTK_DEBUG
}
// *************************************************************************
/*!
Set class name of widget.
\sa getClassName(), componentClassName()
*/
void
SoGtkComponent::setClassName(const char * const name)
{
if (PRIVATE(this)->className) {
delete [] PRIVATE(this)->className;
PRIVATE(this)->className = NULL;
}
if (name) {
PRIVATE(this)->className = strcpy(new char [strlen(name)+1], name);
}
}
// *************************************************************************
/*!
Set the core widget for this SoGtk component. It is important that
subclasses get this correct, as the widget set here will be the
widget returned from query methods.
\sa baseWidget()
*/
void
SoGtkComponent::setBaseWidget(GtkWidget * widget)
{
if (PRIVATE(this)->widget) {
gtk_signal_disconnect_by_func(GTK_OBJECT(PRIVATE(this)->widget),
GTK_SIGNAL_FUNC(SoGtkComponentP::realizeHandlerCB),
(gpointer) this);
this->unregisterWidget(PRIVATE(this)->widget);
}
PRIVATE(this)->widget = NULL;
if (! GTK_IS_WIDGET(widget)) {
#if SOGTK_DEBUG
SoDebugError::postInfo("SoGtkComponent::setBaseWidget", "not a widget");
#endif
return;
}
PRIVATE(this)->widget = widget;
if (PRIVATE(this)->widget) {
// We connect to the "map" signal instead of the "realize" event,
// so the widget will have a window when the afterRealizeHook()
// method is invoked. (Which again is necessary for being able to
// set a cursor on the widget in that callback.)
gtk_signal_connect(GTK_OBJECT(PRIVATE(this)->widget), "map",
GTK_SIGNAL_FUNC(SoGtkComponentP::realizeHandlerCB),
(gpointer) this);
this->registerWidget(PRIVATE(this)->widget);
}
}
// *************************************************************************
static const char * gdk_event_name(GdkEventType type) {
switch (type) {
case GDK_NOTHING: return "GDK_NOTHING";
case GDK_DELETE: return "GDK_DELETE";
case GDK_DESTROY: return "GDK_DESTROY";
case GDK_EXPOSE: return "GDK_EXPOSE";
case GDK_MOTION_NOTIFY: return "GDK_MOTION_NOTIFY";
case GDK_BUTTON_PRESS: return "GDK_BUTTON_PRESS";
case GDK_2BUTTON_PRESS: return "GDK_2BUTTON_PRESS";
case GDK_3BUTTON_PRESS: return "GDK_3BUTTON_PRESS";
case GDK_BUTTON_RELEASE: return "GDK_BUTTON_RELEASE";
case GDK_KEY_PRESS: return "GDK_KEY_PRESS";
case GDK_KEY_RELEASE: return "GDK_KEY_RELEASE";
case GDK_ENTER_NOTIFY: return "GDK_ENTER_NOTIFY";
case GDK_LEAVE_NOTIFY: return "GDK_LEAVE_NOTIFY";
case GDK_FOCUS_CHANGE: return "GDK_FOCUS_CHANGE";
case GDK_CONFIGURE: return "GDK_CONFIGURE";
case GDK_MAP: return "GDK_MAP";
case GDK_UNMAP: return "GDK_UNMAP";
case GDK_PROPERTY_NOTIFY: return "GDK_PROPERTY_NOTIFY";
case GDK_SELECTION_CLEAR: return "GDK_SELECTION_CLEAR";
case GDK_SELECTION_REQUEST: return "GDK_SELECTION_REQUEST";
case GDK_SELECTION_NOTIFY: return "GDK_SELECTION_NOTIFY";
case GDK_PROXIMITY_IN: return "GDK_PROXIMITY_IN";
case GDK_PROXIMITY_OUT: return "GDK_PROXIMITY_OUT";
case GDK_DRAG_ENTER: return "GDK_DRAG_ENTER";
case GDK_DRAG_LEAVE: return "GDK_DRAG_LEAVE";
case GDK_DRAG_MOTION: return "GDK_DRAG_MOTION";
case GDK_DRAG_STATUS: return "GDK_DRAG_STATUS";
case GDK_DROP_START: return "GDK_DROP_START";
case GDK_DROP_FINISHED: return "GDK_DROP_FINISHED";
case GDK_CLIENT_EVENT: return "GDK_CLIENT_EVENT";
case GDK_VISIBILITY_NOTIFY: return "GDK_VISIBILITY_NOTIFY";
case GDK_NO_EXPOSE: return "GDK_NO_EXPOSE";
default:
break;
}
return _("<unknown>");
}
/*!
\internal
Helps us detect changes in size (base widget and parent widget) and
visibility status.
*/
SbBool
SoGtkComponent::eventFilter(GtkWidget * obj, GdkEvent * ev)
{
assert(GTK_IS_WIDGET(obj) && "something in gtk is fishy");
GtkWidget * widget = GTK_WIDGET(obj);
if (widget != this->getBaseWidget() &&
!gtk_widget_is_ancestor(GTK_WIDGET(this->getBaseWidget()),
GTK_WIDGET(widget))) {
return FALSE;
}
switch (ev->type) {
case GDK_KEY_PRESS:
case GDK_KEY_RELEASE:
return FALSE;
case GDK_CONFIGURE:
if(GTK_WIDGET_REALIZED(this->getBaseWidget())) {
GdkEventConfigure * event = (GdkEventConfigure *) ev;
SbVec2s size(event->width, event->height);
PRIVATE(this)->storeSize.setValue(event->width, event->height);
this->sizeChanged(size);
}
break;
case GDK_DELETE:
if (PRIVATE(this)->closeCB) {
PRIVATE(this)->closeCB(PRIVATE(this)->closeCBdata, this);
}
// FIXME: should we perhaps *not* just go on and quit the
// application if there's a closeCB installed? Investigate what
// the original SGI InventorXt does. 20020107 mortene.
SoGtk::exitMainLoop();
break;
default:
break;
}
return TRUE;
}
// Static callback, just forwards control to
// SoGtkComponent::eventFilter() member-function.
gint
SoGtkComponent::eventHandler(GtkWidget * object,
GdkEvent * event,
gpointer closure)
{
SoGtkComponent * const component = (SoGtkComponent *) closure;
component->eventFilter(object, event);
return FALSE;
}
// *************************************************************************
/*!
Returns the visibility status of the component. If any parent
widgets of this component is hidden, returns \c FALSE.
Note that a widget which is just obscured by other windows on the
desktop is not hidden in this sense, and \c TRUE will be returned.
\sa show(), hide()
*/
SbBool
SoGtkComponent::isVisible(void)
{
if (! this->getBaseWidget()) { return FALSE; }
// FIXME - return true visibility state. 200????? larsa.
// Close, but probably still incomplete
return GTK_WIDGET_DRAWABLE(this->getBaseWidget()) ? TRUE : FALSE;
}
/*!
This will show the widget, deiconifying and raising it if
necessary.
\sa hide(), isVisible()
*/
void
SoGtkComponent::show(void)
{
if(! this->getBaseWidget() || ! GTK_IS_WIDGET(this->getBaseWidget())) {
#if SOGTK_DEBUG
SoDebugError::postWarning("SoGtkComponent::show",
this->getBaseWidget() ?
"not a widget" : "no widget");
#endif // SOGTK_DEBUG
return;
}
GtkWidget * parent = this->getParentWidget();
GtkWidget * widget = this->getBaseWidget();
assert(parent != NULL);
assert(widget != NULL);
if (! widget->parent)
gtk_container_add(GTK_CONTAINER(parent), widget);
if (PRIVATE(this)->storeSize != SbVec2s(-1, -1) && GTK_IS_WINDOW(parent)) {
gtk_window_set_default_size(GTK_WINDOW(parent),
PRIVATE(this)->storeSize[0],
PRIVATE(this)->storeSize[1]);
}
if (PRIVATE(this)->shelled) {
if (! GTK_WIDGET_REALIZED(this->getBaseWidget())) {
gtk_widget_show(widget);
}
gtk_widget_show(parent);
}
else {
gtk_widget_show(widget);
}
this->sizeChanged(PRIVATE(this)->storeSize);
}
/*!
This will hide the component.
\sa show(), isVisible()
*/
void
SoGtkComponent::hide(void)
{
#if SOGTK_DEBUG
if (! this->getBaseWidget() || ! GTK_IS_WIDGET(this->getBaseWidget())) {
SoDebugError::postWarning("SoGtkComponent::hide",
this->getBaseWidget() ?
"not a widget" : "no widget");
return;
}
#endif // SOGTK_DEBUG
if (PRIVATE(this)->shelled) {
gtk_widget_hide(GTK_WIDGET(this->getParentWidget()));
}
else {
gtk_widget_hide(GTK_WIDGET(this->getBaseWidget()));
}
}
// *************************************************************************
/*!
Returns a pointer to the component's window system widget.
\sa getShellWidget(), getParentWidget()
*/
GtkWidget *
SoGtkComponent::getWidget(void) const
{
return PRIVATE(this)->widget;
}
/*!
An SoGtkComponent may be composed of any number of widgets in
parent-children relationships in a tree structure with any depth.
This method will return the root widget in that tree.
\sa setBaseWidget()
*/
GtkWidget *
SoGtkComponent::getBaseWidget(void) const
{
return PRIVATE(this)->widget;
}
// *************************************************************************
/*!
Returns \c TRUE if this component is a top level shell, i.e. it has a
window representation on the desktop.
\sa getShellWidget()
*/
SbBool
SoGtkComponent::isTopLevelShell(void) const
{
#if SOGTK_DEBUG
if(! PRIVATE(this)->widget) {
SoDebugError::postWarning("SoGtkComponent::isTopLevelShell",
"Called while no GtkWidget has been set.");
return FALSE;
}
#endif // SOGTK_DEBUG
if (PRIVATE(this)->widget->parent == 0)
{
// FIXME: Dunno if this can happen. 200????? larsa.
SoDebugError::postWarning("SoGtkComponent::isTopLevelShell",
"No parent.");
}
else {
if (PRIVATE(this)->widget->parent == gtk_widget_get_toplevel(PRIVATE(this)->widget)) {
return TRUE;
}
else {
return FALSE;
}
}
return FALSE;
}
// *************************************************************************
/*!
Returns the widget which is the parent of (i.e. contains) this
component's base widget.
\sa getWidget(), baseWidget(), isTopLevelShell()
*/
GtkWidget *
SoGtkComponent::getParentWidget(void) const
{
return PRIVATE(this)->parent;
}
// *************************************************************************
/*!
Set the window title of this component. This will not work unless
the component is a top level shell.
\sa getTitle(), setIconTitle(), isTopLevelShell()
*/
void
SoGtkComponent::setTitle(const char * const title)
{
if (PRIVATE(this)->captionText) {
delete [] PRIVATE(this)->captionText;
PRIVATE(this)->captionText = NULL;
}
if (title) {
PRIVATE(this)->captionText = strcpy(new char [strlen(title)+1], title);
}
if (! PRIVATE(this)->embedded) {
gtk_window_set_title(GTK_WINDOW(PRIVATE(this)->parent), title ? title : "");
}
}
/*!
Returns the window title. The component should be a top level shell
if you call this method.
\sa setTitle(), isTopLevelShell()
*/
const char *
SoGtkComponent::getTitle(void) const
{
if (PRIVATE(this)->captionText == NULL) {
return this->getDefaultTitle();
}
return PRIVATE(this)->captionText;
}
// *************************************************************************
/*!
Sets the window's title when it is iconified. The component you use
this method on should be a top level shell.
\sa getIconTitle(), setTitle(), isTopLevelShell()
*/
void
SoGtkComponent::setIconTitle(const char * const title)
{
if (PRIVATE(this)->iconText) {
delete [] PRIVATE(this)->iconText;
PRIVATE(this)->iconText = NULL;
}
if (title) {
PRIVATE(this)->iconText = strcpy(new char [strlen(title)+1], title);
}
if (PRIVATE(this)->widget) {
GtkWidget * window = gtk_widget_get_toplevel(PRIVATE(this)->widget);
assert(window != NULL);
gdk_window_set_icon_name((GTK_WIDGET(PRIVATE(this)->parent))->window,(char*)( title ? title : ""));
#if 0
gdk_window_set_icon_name(window->window,(char*)( title ? title : ""));
#endif
}
}
/*!
Returns the title the window has when iconified. The component should
be a top level shell if you use this method.
\sa setIconTitle(), isTopLevelShell()
*/
const char *
SoGtkComponent::getIconTitle(void) const
{
return PRIVATE(this)->iconText;
}
// *************************************************************************
/*!
Returns name of the widget.
*/
const char *
SoGtkComponent::getWidgetName(void) const
{
return PRIVATE(this)->widgetName;
}
// *************************************************************************
/*!
Returns class name of widget.
*/
const char *
SoGtkComponent::getClassName(void) const
{
return (const char *) PRIVATE(this)->className;
}
// *************************************************************************
/*!
Resize the component widget.
\sa getSize()
*/
void
SoGtkComponent::setSize(const SbVec2s size)
{
if (size[0] <= 0 || size[1] <= 0) {
#if SOGTK_DEBUG
SoDebugError::postWarning("SoGtkComponent::setSize",
"Invalid size setting: <%d, %d>.",
size[0], size[1]);
#endif // SOGTK_DEBUG
return;
}
if (! PRIVATE(this)->embedded) {
if (PRIVATE(this)->parent) {
GtkRequisition req = { size[0], size[1] };
gtk_widget_size_request(GTK_WIDGET(PRIVATE(this)->parent), &req);
}
}
else if (PRIVATE(this)->widget) {
GtkRequisition req = { size[0], size[1] };
gtk_widget_size_request(GTK_WIDGET(PRIVATE(this)->widget), &req);
}
PRIVATE(this)->storeSize = size;
this->sizeChanged(size);
}
/*!
Returns the component widget size.
\sa setSize()
*/
SbVec2s
SoGtkComponent::getSize(void) const
{
return PRIVATE(this)->storeSize;
}
// *************************************************************************
/*!
Override to detect when the base widget in the component changes its
dimensions (an operation which is usually triggered by the user).
*/
void
SoGtkComponent::sizeChanged(const SbVec2s & size)
{
// nada
}
// *************************************************************************
/*!
Set up a callback function to use when the component is closed. A
component must be a top level shell for this to have any effect.
For top level shells with no close callback set, the window will
simply be hidden. The typical action to take in the callback would
be to delete the component.
\sa isTopLevelShell()
*/
void
SoGtkComponent::setWindowCloseCallback(SoGtkComponentCB * const func,
void * const data)
{
// FIXME: make list instead of one slot that is overwritten?
// 200????? larsa.
PRIVATE(this)->closeCB = func;
PRIVATE(this)->closeCBdata = data;
}
// *************************************************************************
// Documented in common/SoGuiComponentCommon.cpp.in.
void
SoGtkComponent::afterRealizeHook(void)
{
#if SOGTK_DEBUG && 0
SoDebugError::postInfo("SoGtkComponent::afterRealizeHook", "[invoked]");
#endif
gtk_signal_connect(GTK_OBJECT(PRIVATE(this)->widget), "event",
GTK_SIGNAL_FUNC(SoGtkComponent::eventHandler),
(gpointer) this);
if (GTK_IS_WINDOW(PRIVATE(this)->parent)) {
gtk_window_set_title(GTK_WINDOW(PRIVATE(this)->parent), this->getTitle());
}
}
// *************************************************************************
//
// Private implementation
//
/*
initialize private memory
*/
SoGtkComponentP::SoGtkComponentP(SoGtkComponent * owner)
: SoGuiComponentP(owner)
{
this->widget = NULL;
this->parent = NULL;
this->embedded = FALSE;
this->fullscreen = FALSE;
this->shelled = FALSE;
this->widget = NULL;
this->closeCB = NULL;
this->closeCBdata = NULL;
this->visibilityChangeCBs = NULL;
this->storeSize.setValue(-1, -1);
this->className = NULL;
this->widgetName = NULL;
this->captionText = NULL;
this->iconText = NULL;
}
/*
free privately allocated memory
*/
SoGtkComponentP::~SoGtkComponentP()
{
delete this->visibilityChangeCBs;
delete [] this->widgetName;
delete [] this->className;
delete [] this->captionText;
delete [] this->iconText;
}
// *************************************************************************
/*
event handler for realize events, used for invoking afterRealizeHook()
*/
gint
SoGtkComponentP::realizeHandlerCB(GtkObject * object,
gpointer closure)
{
assert(closure != NULL);
SoGtkComponent * const component = (SoGtkComponent *) closure;
GtkWidget * widget = component->getBaseWidget();
assert(GTK_WIDGET_REALIZED(widget));
if (PRIVATE(component)->storeSize != SbVec2s(-1, -1)) {
GtkRequisition req = {
PRIVATE(component)->storeSize[0],
PRIVATE(component)->storeSize[1] };
gtk_widget_size_request(widget, &req);
}
SbVec2s size(widget->allocation.width, widget->allocation.height);
component->sizeChanged(size);
component->afterRealizeHook();
return FALSE;
}
// *************************************************************************
/*!
Toggle full screen mode for this component, if possible.
Returns \c FALSE if operation failed. This might happen if the
toolkit doesn't support attempts at making the component cover the
complete screen or if the component is not a top level window.
*/
SbBool
SoGtkComponent::setFullScreen(const SbBool onoff)
{
if (onoff == PRIVATE(this)->fullscreen) { return TRUE; }
GtkWidget * w = SoGtk::getTopLevelWidget();
// FIXME: this looks a /little/ fishy -- should investigate what
// gtk_widget_realize() actually does. Does the widget automatically
// pop up on the display if this is done, for instance? If so, that
// might not be the expected behavior for the application
// programmer.
//
// See:
// <URL:http://developer.gnome.org/doc/GGAD/z57.html#SEC-REALIZINGSHOWING>
// <URL:http://developer.gnome.org/doc/GGAD/faqs.html>
// [When do I need to call gtk_widget_realize() vs. gtk_widget_show()?]
//
// 20020108 mortene.
if (!GTK_WIDGET_REALIZED(GTK_WIDGET(w))) {
gtk_widget_realize(GTK_WIDGET(w));
}
GdkWindow * gdk_window = GTK_WIDGET(w)->window;
if (onoff) {
// Store current window position and geometry for later resetting.
{
// FIXME: does this work as expected if setFullScreen() is
// called before the window has been realized?
// Investigate. (Note that the window is explicitly realized 10
// lines up.) 20020107 mortene.
gdk_window_get_root_origin(gdk_window,
&PRIVATE(this)->nonfull.x,
&PRIVATE(this)->nonfull.y);
gdk_window_get_size(gdk_window,
&PRIVATE(this)->nonfull.w,
&PRIVATE(this)->nonfull.h);
}
#ifdef HAVE_XINERAMA
// FIXME: from the galeon sourcecode, we've gleamed that if the
// user has Xinerama (ie multi-headed X11 server) installed, there
// need to be some code here to (quote:) "adjust the area and
// positioning of the fullscreen window so it's not occupying any
// dead area or covering all of the heads".
//
// Can't fix and test properly before we lay our hands on a
// multi-head display system.
//
// (Note that the HAVE_XINERAMA define is just a dummy at the
// moment, there's no configure-check for it yet.)
//
// 20020107 mortene.
#endif // HAVE_XINERAMA
gdk_window_hide(gdk_window);
gdk_window_set_decorations(gdk_window, (GdkWMDecoration) 0);
gdk_window_show(gdk_window);
gdk_window_move_resize(gdk_window, 0, 0,
gdk_screen_width(), gdk_screen_height());
}
else {
gdk_window_hide(gdk_window);
gdk_window_set_decorations(gdk_window, GDK_DECOR_ALL);
gdk_window_show(gdk_window);
// Restore initial position and size.
gdk_window_move_resize(gdk_window,
PRIVATE(this)->nonfull.x,
PRIVATE(this)->nonfull.y,
PRIVATE(this)->nonfull.w,
PRIVATE(this)->nonfull.h);
}
// FIXME: is this really necessary? 20020107 mortene.
PRIVATE(this)->storeSize.setValue(PRIVATE(this)->nonfull.w,
PRIVATE(this)->nonfull.h);
PRIVATE(this)->fullscreen = onoff;
return TRUE;
}
/*!
Returns flag indicated whether or not this widget / component is
currently in full screen mode.
*/
SbBool
SoGtkComponent::isFullScreen(void) const
{
return PRIVATE(this)->fullscreen;
}
// Converts from the common generic cursor format to a Win32 HCURSOR
// instance.
GdkCursor *
SoGtkComponentP::getNativeCursor(GtkWidget * w,
const SoGtkCursor::CustomCursor * cc)
{
if (SoGtkComponentP::cursordict == NULL) { // first call, initialize
SoGtkComponentP::cursordict = new SbDict; // FIXME: mem leak. 20011121 mortene.
}
void * qc;
SbBool b = SoGtkComponentP::cursordict->find((unsigned long)cc, qc);
if (b) { return (GdkCursor *)qc; }
GtkStyle * style = w->style;
GdkColor fg = style->black;
GdkColor bg = style->white;
GdkPixmap * bitmap =
gdk_bitmap_create_from_data(NULL, (const gchar *)cc->bitmap,
cc->dim[0], cc->dim[1]);
GdkPixmap *mask =
gdk_bitmap_create_from_data(NULL, (const gchar *)cc->mask,
cc->dim[0], cc->dim[1]);
// FIXME: plug memleak. 20011126 mortene.
GdkCursor * cursor =
gdk_cursor_new_from_pixmap(bitmap, mask, &fg, &bg,
cc->hotspot[0], cc->hotspot[1]);
gdk_pixmap_unref(bitmap);
gdk_pixmap_unref(mask);
SoGtkComponentP::cursordict->enter((unsigned long)cc, cursor);
return cursor;
}
/*!
Sets the cursor for this component.
*/
void
SoGtkComponent::setComponentCursor(const SoGtkCursor & cursor)
{
SoGtkComponent::setWidgetCursor(this->getWidget(), cursor);
}
/*!
Set cursor for a native widget in the underlying toolkit.
*/
void
SoGtkComponent::setWidgetCursor(GtkWidget * w, const SoGtkCursor & cursor)
{
if (GTK_WIDGET_NO_WINDOW(w)) {
if (SOGTK_DEBUG) {
// FIXME: This should not happen, but there seems to be a bug in
// SoGtk's event handling causing this. 20001219 RC.
static SbBool first = TRUE;
if (first) {
SoDebugError::postWarning("SoGtkComponent::setWidgetCursor",
"widget %p: NO WINDOW\n", w);
first = FALSE;
}
}
return;
}
if (w->window == (GdkWindow *)NULL) {
if (SOGTK_DEBUG) {
// FIXME: This should not happen, but there seems to be a bug in
// SoGtk's event handling causing this. 20001219 RC.
static SbBool first = TRUE;
if (first) {
SoDebugError::postWarning("SoGtkComponent::setWidgetCursor",
"widget %p: widget->window == 0\n", w);
first = FALSE;
}
}
return;
}
if (cursor.getShape() == SoGtkCursor::CUSTOM_BITMAP) {
const SoGtkCursor::CustomCursor * cc = &cursor.getCustomCursor();
gdk_window_set_cursor(w->window, SoGtkComponentP::getNativeCursor(w, cc));
}
else {
switch (cursor.getShape()) {
case SoGtkCursor::DEFAULT:
if (!SoGtkComponentP::arrowcursor) {
// FIXME: plug memleak with gdk_cursor_destroy(). 20011126 mortene.
SoGtkComponentP::arrowcursor = gdk_cursor_new(GDK_TOP_LEFT_ARROW);
}
gdk_window_set_cursor(w->window, SoGtkComponentP::arrowcursor);
break;
case SoGtkCursor::BUSY:
SOGTK_STUB();
break;
case SoGtkCursor::CROSSHAIR:
if (!SoGtkComponentP::crosscursor) {
// FIXME: plug memleak. 20011126 mortene.
SoGtkComponentP::crosscursor = gdk_cursor_new(GDK_CROSSHAIR);
}
gdk_window_set_cursor(w->window, SoGtkComponentP::crosscursor);
break;
case SoGtkCursor::UPARROW:
if (!SoGtkComponentP::uparrowcursor) {
// FIXME: plug memleak. 20011126 mortene.
SoGtkComponentP::uparrowcursor = gdk_cursor_new(GDK_SB_UP_ARROW);
}
gdk_window_set_cursor(w->window, SoGtkComponentP::uparrowcursor);
break;
default:
assert(FALSE && "unsupported cursor shape type");
break;
}
}
}
// *************************************************************************
| 29.983495 | 103 | 0.626299 | coin3d |
643b2ac0e48394a0e2dcabc8914437b4bf3f9c09 | 906 | hpp | C++ | third_party/include/mvscxx/oglplus/error/code.hpp | Simmesimme/swift2d | 147a862208dee56f972361b5325009e020124137 | [
"MIT"
] | 24 | 2015-01-31T15:30:49.000Z | 2022-01-29T08:36:42.000Z | third_party/include/mvscxx/oglplus/error/code.hpp | Simmesimme/swift2d | 147a862208dee56f972361b5325009e020124137 | [
"MIT"
] | 4 | 2015-08-21T02:29:15.000Z | 2020-05-02T13:50:36.000Z | third_party/include/mvscxx/oglplus/error/code.hpp | Simmesimme/swift2d | 147a862208dee56f972361b5325009e020124137 | [
"MIT"
] | 9 | 2015-06-08T22:04:15.000Z | 2021-08-16T03:52:11.000Z | /**
* @file oglplus/error/code.hpp
* @brief Enumeration of error-codes
*
* @author Matus Chochlik
*
* Copyright 2010-2014 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_ERROR_CODE_1405082311_HPP
#define OGLPLUS_ERROR_CODE_1405082311_HPP
#include <oglplus/enumerations.hpp>
namespace oglplus {
/// Error code enumeration
/**
* @ingroup enumerations
*
* @glsymbols
* @glfunref{GetError}
*/
OGLPLUS_ENUM_CLASS_BEGIN(ErrorCode, GLenum)
#include <oglplus/enums/error_code.ipp>
OGLPLUS_ENUM_CLASS_END(ErrorCode)
#if !OGLPLUS_NO_ENUM_VALUE_NAMES
#include <oglplus/enums/error_code_names.ipp>
#endif
#if !OGLPLUS_ENUM_VALUE_RANGES
#include <oglplus/enums/error_code_range.ipp>
#endif
} // namespace oglplus
#endif // include guard
| 21.571429 | 68 | 0.763797 | Simmesimme |
643c3e653c6571eb70e44244337d2d73e14df51b | 80 | cxx | C++ | Part1/src/Test/test.cxx | siredmar/CMakeTests | 7d3d6c9177326126e48dcf483c75662db6941a98 | [
"BSD-3-Clause"
] | null | null | null | Part1/src/Test/test.cxx | siredmar/CMakeTests | 7d3d6c9177326126e48dcf483c75662db6941a98 | [
"BSD-3-Clause"
] | null | null | null | Part1/src/Test/test.cxx | siredmar/CMakeTests | 7d3d6c9177326126e48dcf483c75662db6941a98 | [
"BSD-3-Clause"
] | null | null | null | #include "test.h"
#include <stdio.h>
void test(void)
{
printf("test\n");
}
| 10 | 21 | 0.6 | siredmar |
643ca74d156956844d0e8269e7883cdcd1ccfab4 | 1,262 | hxx | C++ | Jimbo/Jimbo/resource/thread/resourcethreadpool.hxx | BenStorey/Jimbo | 937ff92a432fea2cb9a8e837d0e6839405f1a6c6 | [
"MIT"
] | 3 | 2017-05-29T15:44:13.000Z | 2019-08-24T09:15:09.000Z | Jimbo/Jimbo/resource/thread/resourcethreadpool.hxx | BenStorey/Jimbo | 937ff92a432fea2cb9a8e837d0e6839405f1a6c6 | [
"MIT"
] | null | null | null | Jimbo/Jimbo/resource/thread/resourcethreadpool.hxx | BenStorey/Jimbo | 937ff92a432fea2cb9a8e837d0e6839405f1a6c6 | [
"MIT"
] | null | null | null |
#ifndef JIMBO_RESOURCE_THREAD_RESOURCETHREADPOOL_HPP
#define JIMBO_RESOURCE_THREAD_RESOURCETHREADPOOL_HPP
/////////////////////////////////////////////////////////
// resourcethreadpool.hxx
//
// Ben Storey
//
// We have a specific thread pool for loading resources. This class essentially
// wraps around our ThreadPool class but gives a nice interface for our ResourceManager
// Then our manager class need only focus on what should/shouldn't be loaded
// without any code describing how that happens
//
/////////////////////////////////////////////////////////
#include <boost/noncopyable.hpp>
#include <memory>
#include "resource/thread/threadpool.hxx"
#include "resource/thread/threadsafequeue.hxx"
#include "resource/resource.hpp"
#include "resource/resourcedatasource.hpp"
namespace jimbo
{
class ResourceID;
class ResourceDataSource;
class ResourceFactory;
class ResourceThreadPool : public ThreadPool
{
public:
void loadResource(ResourceFactory*, ResourceDataSource*, ResourceID);
std::unique_ptr<Resource> getLoadedResource();
void updateResource(Resource*);
private:
ThreadSafeQueue<std::unique_ptr<Resource>> queue_;
};
}
#endif // JIMBO_RESOURCE_THREAD_RESOURCETHREADPOOL_HPP | 28.044444 | 87 | 0.694136 | BenStorey |
643dc2df69e2b89e5c17c6222f660533403a2c22 | 3,466 | cpp | C++ | engine/src/graphics/shader.cpp | jodelahithit/Diamond | d4620b7c38e4639acf06f6aa9ca692bbd22c0a28 | [
"Apache-2.0"
] | null | null | null | engine/src/graphics/shader.cpp | jodelahithit/Diamond | d4620b7c38e4639acf06f6aa9ca692bbd22c0a28 | [
"Apache-2.0"
] | null | null | null | engine/src/graphics/shader.cpp | jodelahithit/Diamond | d4620b7c38e4639acf06f6aa9ca692bbd22c0a28 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "util/path.h"
#include "shader.h"
#include "shadInclude.h"
#include "util/fileSystem.h"
#include "util/utils.h"
#include "glError.h"
namespace Diamond {
Shader::Shader(const std::string& name, const std::string& filePath, bool hasGeometry, bool hasTessellation) : m_shaderProgram(nullptr), m_hasGeometry(hasGeometry), m_hasTessellation(hasTessellation), m_name(name), m_shaderPath(filePath) {
m_shaderProgram = load();
if (!m_shaderProgram) LOG_ERROR("[~bShaders~x] ~1%s~x shader failed to compile", name.c_str());
m_uniformBuffer.initialize(m_shaderProgram);
}
Shader::~Shader() {
delete m_shaderProgram;
}
uint32_t Shader::loadShader(const std::string& path, uint32_t type) {
GL(uint32_t shader = glCreateShader(type));
if (!FileSystem::doesFileExist(path)) LOG_WARN("[~bShaders~x] ~1%s ~xshader ~1%s ~xat ~1%s does not exist", m_name.c_str(), GLUtils::shaderTypeToString(type), path.c_str());
std::string source = "";
std::string logOutput = "";
if (!Shadinclude::load(path, source, logOutput)) {
LOG_WARN("[~bShaders~x] Failed to load ~1%s ~xshader ~1%s ~xat ~1%s~x [~1%s]", m_name.c_str(), GLUtils::shaderTypeToString(type), path.c_str(), logOutput.c_str());
return 0xffffffff;
}
const char* sourceCC = source.c_str();
GL(glShaderSource(shader, 1, &sourceCC, 0));
GL(glCompileShader(shader));
GLint result;
GL(glGetShaderiv(shader, GL_COMPILE_STATUS, &result));
if (result == GL_FALSE) {
GLint length;
GL(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length));
std::vector<char> error(length);
GL(glGetShaderInfoLog(shader, length, &length, &error[0]));
LOG_WARN("[~bShaders~x] Failed to compile %s %s shader with error: \n%s", m_name.c_str(), GLUtils::shaderTypeToString(type), &error[0]);
return 0xffffffff;
}
LOG("[~bShaders~x] Compiled ~1%s~x %s", m_name.c_str(), GLUtils::shaderTypeToString(type));
return shader;
}
bool Shader::addShaderToProgram(ShaderProgram* program, const std::string& shader, uint32_t shaderType) {
uint32_t shaderHandle = loadShader(shader, shaderType);
if (shaderHandle == 0xffffffff) return true;
program->attachShader(shaderHandle);
return false;
}
ShaderProgram* Shader::load() {
ShaderProgram* shaderProgram = new ShaderProgram();
shaderProgram->createProgram();
bool failed = false;
std::string vertexFile = m_shaderPath + ".vert";
std::string fragFile = m_shaderPath + ".frag";
failed |= addShaderToProgram(shaderProgram, vertexFile, GL_VERTEX_SHADER);
failed |= addShaderToProgram(shaderProgram, fragFile, GL_FRAGMENT_SHADER);
if (m_hasGeometry) {
std::string geomFile = m_shaderPath + ".geom";
failed |= addShaderToProgram(shaderProgram, geomFile, GL_GEOMETRY_SHADER);
}
if (m_hasTessellation) {
std::string te = m_shaderPath + ".tese";
std::string tc = m_shaderPath + ".tesc";
failed |= addShaderToProgram(shaderProgram, te, GL_TESS_EVALUATION_SHADER);
failed |= addShaderToProgram(shaderProgram, tc, GL_TESS_CONTROL_SHADER);
}
if (failed) {
delete shaderProgram;
shaderProgram = nullptr;
} else {
shaderProgram->linkAndValidate();
shaderProgram->deleteAttachedShaders();
}
return shaderProgram;
}
void Shader::reload() {
ShaderProgram* program = load();
if (program) {
delete m_shaderProgram;
m_shaderProgram = program;
m_uniformBuffer.reload(m_shaderProgram);
};
}
void Shader::bind() {
m_shaderProgram->bind();
}
} | 33.326923 | 240 | 0.712926 | jodelahithit |
643e005d4db08bf7edfab5f90801087bc2fbbb9d | 326 | hpp | C++ | include/factory/console_creator.hpp | OBess/logger | 95ef8c39a554bee3f3e26563f6bd058c1283fabb | [
"MIT"
] | null | null | null | include/factory/console_creator.hpp | OBess/logger | 95ef8c39a554bee3f3e26563f6bd058c1283fabb | [
"MIT"
] | null | null | null | include/factory/console_creator.hpp | OBess/logger | 95ef8c39a554bee3f3e26563f6bd058c1283fabb | [
"MIT"
] | null | null | null | #pragma once
#ifndef CONSOLE_CREATOR_HPP
#define CONSOLE_CREATOR_HPP
// Custom
#include "creator.hpp"
#include "../loggers/console_logger.hpp"
class console_creator : public creator
{
public:
logger *getLogger() const override
{
return new console_logger();
}
};
#endif //CONSOLE_CREATOR_HPP | 18.111111 | 41 | 0.699387 | OBess |
643fc99168b31512536aec023ab8fd31e7ff4462 | 19,407 | cpp | C++ | src/jablotron/JablotronDeviceManager.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | null | null | null | src/jablotron/JablotronDeviceManager.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | null | null | null | src/jablotron/JablotronDeviceManager.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 1 | 2021-05-03T08:51:50.000Z | 2021-05-03T08:51:50.000Z | #include <vector>
#include <Poco/Clock.h>
#include <Poco/Message.h>
#include <Poco/NumberFormatter.h>
#include <Poco/NumberParser.h>
#include <Poco/RegularExpression.h>
#include <Poco/StringTokenizer.h>
#include <Poco/Thread.h>
#include "commands/NewDeviceCommand.h"
#include "core/CommandDispatcher.h"
#include "di/Injectable.h"
#include "jablotron/JablotronDeviceManager.h"
#include "hotplug/HotplugEvent.h"
#include "model/SensorData.h"
#include "util/BlockingAsyncWork.h"
#include "util/UnsafePtr.h"
BEEEON_OBJECT_BEGIN(BeeeOn, JablotronDeviceManager)
BEEEON_OBJECT_CASTABLE(CommandHandler)
BEEEON_OBJECT_CASTABLE(StoppableRunnable)
BEEEON_OBJECT_CASTABLE(HotplugListener)
BEEEON_OBJECT_CASTABLE(DeviceStatusHandler)
BEEEON_OBJECT_PROPERTY("deviceCache", &JablotronDeviceManager::setDeviceCache)
BEEEON_OBJECT_PROPERTY("distributor", &JablotronDeviceManager::setDistributor)
BEEEON_OBJECT_PROPERTY("commandDispatcher", &JablotronDeviceManager::setCommandDispatcher)
BEEEON_OBJECT_PROPERTY("txBackOffFactory", &JablotronDeviceManager::setTxBackOffFactory)
BEEEON_OBJECT_PROPERTY("unpairErasesSlot", &JablotronDeviceManager::setUnpairErasesSlot)
BEEEON_OBJECT_PROPERTY("pgyEnrollGap", &JablotronDeviceManager::setPGYEnrollGap)
BEEEON_OBJECT_PROPERTY("eraseAllOnProbe", &JablotronDeviceManager::setEraseAllOnProbe)
BEEEON_OBJECT_PROPERTY("registerOnProbe", &JablotronDeviceManager::setRegisterOnProbe)
BEEEON_OBJECT_PROPERTY("maxProbeAttempts", &JablotronDeviceManager::setMaxProbeAttempts)
BEEEON_OBJECT_PROPERTY("probeTimeout", &JablotronDeviceManager::setProbeTimeout)
BEEEON_OBJECT_PROPERTY("ioJoinTimeout", &JablotronDeviceManager::setIOJoinTimeout)
BEEEON_OBJECT_PROPERTY("ioReadTimeout", &JablotronDeviceManager::setIOReadTimeout)
BEEEON_OBJECT_PROPERTY("ioErrorSleep", &JablotronDeviceManager::setIOErrorSleep)
BEEEON_OBJECT_END(BeeeOn, JablotronDeviceManager)
using namespace BeeeOn;
using namespace Poco;
using namespace std;
static const int MAX_GADGETS_COUNT = 32;
static set<unsigned int> allSlots()
{
set<unsigned int> slots;
for (unsigned int i = 0; i < MAX_GADGETS_COUNT; ++i)
slots.emplace(i);
return slots;
}
static const Timespan SHORT_TIMEOUT = 1 * Timespan::SECONDS;
static const Timespan ERASE_ALL_TIMEOUT = 5 * Timespan::SECONDS;
static const Timespan SCAN_SLOTS_TIMEOUT = 15 * Timespan::SECONDS;
static const Timespan CONTROLLER_ERROR_SLEEP = 1 * Timespan::SECONDS;
static const DeviceID PGX_ID = {DevicePrefix::PREFIX_JABLOTRON, 0x00ffffffffffff01};
static const DeviceID PGY_ID = {DevicePrefix::PREFIX_JABLOTRON, 0x00ffffffffffff02};
static const DeviceID SIREN_ID = {DevicePrefix::PREFIX_JABLOTRON, 0x00ffffffffffff03};
static const ModuleID SIREN_ALARM_ID = 0;
static const ModuleID SIREN_BEEP_ID = 1;
static list<ModuleType> PG_MODULES = {
{ModuleType::Type::TYPE_ON_OFF, {ModuleType::Attribute::ATTR_CONTROLLABLE}},
};
static list<ModuleType> SIREN_MODULES = {
{ModuleType::Type::TYPE_ON_OFF, {ModuleType::Attribute::ATTR_CONTROLLABLE}},
{ModuleType::Type::TYPE_ENUM, {"SIREN_BEEPING"}, {ModuleType::Attribute::ATTR_CONTROLLABLE}},
};
static string addressToString(const uint32_t address)
{
return NumberFormatter::format0(address, 8)
+ " [" + NumberFormatter::formatHex(address, 6) + "]";
}
JablotronDeviceManager::JablotronDeviceManager():
DeviceManager(DevicePrefix::PREFIX_JABLOTRON, {
typeid(GatewayListenCommand),
typeid(DeviceAcceptCommand),
typeid(DeviceUnpairCommand),
typeid(DeviceSetValueCommand),
typeid(DeviceSearchCommand),
}),
m_unpairErasesSlot(false),
m_pgyEnrollGap(4 * Timespan::SECONDS), // determined experimentally
m_pgx(false),
m_pgy(false),
m_alarm(false),
m_beep(JablotronController::BEEP_NONE)
{
}
void JablotronDeviceManager::setUnpairErasesSlot(bool erase)
{
m_unpairErasesSlot = erase;
}
void JablotronDeviceManager::setTxBackOffFactory(BackOffFactory::Ptr factory)
{
m_txBackOffFactory = factory;
}
void JablotronDeviceManager::setPGYEnrollGap(const Timespan &gap)
{
if (gap < 0)
throw InvalidArgumentException("pgyEnrollGap must be non-negative");
m_pgyEnrollGap = gap;
}
void JablotronDeviceManager::setEraseAllOnProbe(bool erase)
{
m_eraseAllOnProbe = erase;
}
void JablotronDeviceManager::setRegisterOnProbe(const list<string> &addresses)
{
list<uint32_t> registerOnProbe;
for (const auto &address : addresses) {
registerOnProbe.emplace_back(
NumberParser::parseUnsigned(address));
}
m_registerOnProbe = registerOnProbe;
}
void JablotronDeviceManager::setMaxProbeAttempts(int count)
{
m_controller.setMaxProbeAttempts(count);
}
void JablotronDeviceManager::setProbeTimeout(const Timespan &timeout)
{
m_controller.setProbeTimeout(timeout);
}
void JablotronDeviceManager::setIOJoinTimeout(const Timespan &timeout)
{
m_controller.setIOJoinTimeout(timeout);
}
void JablotronDeviceManager::setIOReadTimeout(const Timespan &timeout)
{
m_controller.setIOReadTimeout(timeout);
}
void JablotronDeviceManager::setIOErrorSleep(const Timespan &delay)
{
m_controller.setIOErrorSleep(delay);
}
DeviceID JablotronDeviceManager::buildID(uint32_t address)
{
const auto primary = JablotronGadget::Info::primaryAddress(address);
return DeviceID(DevicePrefix::PREFIX_JABLOTRON, primary);
}
uint32_t JablotronDeviceManager::extractAddress(const DeviceID &id)
{
return id.ident() & 0x0ffffff;
}
void JablotronDeviceManager::sleep(const Timespan &delay)
{
const Clock started;
while (true) {
Timespan remaining = delay - started.elapsed();
if (remaining < 0)
return;
if (remaining < 1 * Timespan::MILLISECONDS)
remaining = 1 * Timespan::MILLISECONDS;
Thread::sleep(remaining.totalMilliseconds());
}
}
void JablotronDeviceManager::onAdd(const HotplugEvent &e)
{
const auto dev = hotplugMatch(e);
if (dev.empty())
return;
FastMutex::ScopedLock guard(m_lock);
m_controller.probe(dev);
initDongle();
syncSlots();
}
void JablotronDeviceManager::onRemove(const HotplugEvent &e)
{
const auto dev = hotplugMatch(e);
if (dev.empty())
return;
m_controller.release(dev);
}
string JablotronDeviceManager::hotplugMatch(const HotplugEvent &e)
{
if (!e.properties()->has("tty.BEEEON_DONGLE"))
return "";
const auto &dongle = e.properties()->getString("tty.BEEEON_DONGLE");
if (dongle != "jablotron")
return "";
return e.node();
}
void JablotronDeviceManager::run()
{
UnsafePtr<Thread>(Thread::current())->setName("reporting");
StopControl::Run run(m_stopControl);
while (run) {
try {
const auto report = m_controller.pollReport(-1);
if (!report)
continue;
if (logger().debug()) {
logger().debug(
"shipping report " + report.toString(),
__FILE__, __LINE__);
}
const auto id = buildID(report.address);
if (!deviceCache()->paired(id)) {
if (logger().debug()) {
logger().debug(
"skipping report from unpaired device " + id.toString(),
__FILE__, __LINE__);
}
continue;
}
shipReport(report);
}
BEEEON_CATCH_CHAIN(logger())
}
}
void JablotronDeviceManager::stop()
{
answerQueue().dispose();
DeviceManager::stop();
m_controller.dispose();
}
void JablotronDeviceManager::handleRemoteStatus(
const DevicePrefix &prefix,
const set<DeviceID> &devices,
const DeviceStatusHandler::DeviceValues &values)
{
FastMutex::ScopedLock guard(m_lock);
DeviceManager::handleRemoteStatus(prefix, devices, values);
syncSlots();
}
vector<JablotronGadget> JablotronDeviceManager::readGadgets(
const Timespan &timeout)
{
const Clock started;
vector<JablotronGadget> gadgets;
for (unsigned int i = 0; i < MAX_GADGETS_COUNT; ++i) {
Timespan remaining = timeout - started.elapsed();
if (remaining < 0)
throw TimeoutException("timeout exceeded while reading gadgets");
const auto address = m_controller.readSlot(i, remaining);
if (address.isNull()) {
if (logger().trace()) {
logger().trace(
"slot " + to_string(i) + " is empty",
__FILE__, __LINE__);
}
continue;
}
const auto info = JablotronGadget::Info::resolve(address);
if (!info) {
logger().warning(
"unrecognized gadget address "
+ addressToString(address));
}
gadgets.emplace_back(JablotronGadget{i, address, info});
}
return gadgets;
}
void JablotronDeviceManager::scanSlots(
set<uint32_t> ®istered,
set<unsigned int> &freeSlots,
set<unsigned int> &unknownSlots)
{
registered.clear();
freeSlots = allSlots();
unknownSlots.clear();
for (const auto &gadget : readGadgets(SCAN_SLOTS_TIMEOUT)) {
freeSlots.erase(gadget.slot());
if (!gadget.info()) {
logger().warning(
"discovered registered unknown gadget: " + gadget.toString()
+ " " + buildID(gadget.address()).toString(),
__FILE__, __LINE__);
unknownSlots.emplace(gadget.slot());
continue;
}
registered.emplace(gadget.address());
logger().information(
"discovered registered gadget: " + gadget.toString()
+ " " + buildID(gadget.address()).toString(),
__FILE__, __LINE__);
}
}
void JablotronDeviceManager::initDongle()
{
if (m_eraseAllOnProbe) {
logger().notice("erasing all slots after probe...");
m_controller.eraseSlots(ERASE_ALL_TIMEOUT);
}
if (m_registerOnProbe.empty())
return;
logger().notice("registering slots after probe...");
set<uint32_t> registered;
set<unsigned int> freeSlots;
set<unsigned int> unknownSlots;
scanSlots(registered, freeSlots, unknownSlots);
for (const auto &address : m_registerOnProbe) {
if (registered.find(address) != registered.end()) {
logger().information(
addressToString(address) + " is already registered");
continue;
}
if (!freeSlots.empty()) {
registerGadget(freeSlots, address, SHORT_TIMEOUT);
}
else {
logger().warning("overwriting a non-free slot...");
registerGadget(unknownSlots, address, SHORT_TIMEOUT);
}
}
}
void JablotronDeviceManager::syncSlots()
{
logger().information("syncing slots...");
set<uint32_t> registered;
set<unsigned int> freeSlots;
set<unsigned int> unknownSlots;
scanSlots(registered, freeSlots, unknownSlots);
const set<DeviceID> paired = deviceCache()->paired(prefix());
for (const auto &id : paired) {
if (id == PGX_ID || id == PGY_ID || id == SIREN_ID) {
// ignore, nothing to sync for those
continue;
}
const auto primary = extractAddress(id);
const auto secondary = JablotronGadget::Info::secondaryAddress(primary);
if (logger().debug()) {
logger().debug(
"try sync gadget " + addressToString(primary)
+ " (secondary: " + NumberFormatter::format0(secondary, 8) + "): "
+ id.toString(),
__FILE__, __LINE__);
}
if (registered.find(primary) == registered.end()) {
if (!freeSlots.empty()) {
registerGadget(freeSlots, primary, SHORT_TIMEOUT);
}
else {
logger().warning("overwriting a non-free slot...");
registerGadget(unknownSlots, primary, SHORT_TIMEOUT);
}
}
else {
if (logger().debug()) {
logger().debug(
"device " + id.toString() + " is already registered",
__FILE__, __LINE__);
}
}
if (primary == secondary) {
if (logger().debug()) {
logger().debug(
"device " + id.toString() + " is not dual, continue",
__FILE__, __LINE__);
}
continue;
}
if (registered.find(secondary) == registered.end()) {
if (!freeSlots.empty()) {
registerGadget(freeSlots, secondary, SHORT_TIMEOUT);
}
else {
logger().warning("overwriting a non-free slot...");
registerGadget(unknownSlots, primary, SHORT_TIMEOUT);
}
}
}
}
void JablotronDeviceManager::shipReport(const JablotronReport &report)
{
const auto info = JablotronGadget::Info::resolve(report.address);
if (!info) {
logger().warning(
"unrecognized device by address "
+ addressToString(report.address));
return;
}
const Timestamp now;
const auto values = info.parse(report);
if (!values.empty()) {
if (logger().debug()) {
logger().debug(
"shipping data from " + info.name(),
__FILE__, __LINE__);
}
ship({buildID(report.address), now, values});
}
}
void JablotronDeviceManager::registerGadget(
set<unsigned int> &freeSlots,
const uint32_t address,
const Timespan &timeout)
{
const auto targetSlot = freeSlots.begin();
if (targetSlot == freeSlots.end()) {
throw IllegalStateException(
"no free slots available to register "
+ addressToString(address));
}
logger().information(
"registering address " + addressToString(address)
+ " at slot " + to_string(*targetSlot),
__FILE__, __LINE__);
m_controller.registerSlot(*targetSlot, address, timeout);
freeSlots.erase(targetSlot);
}
void JablotronDeviceManager::acceptGadget(const DeviceID &id)
{
FastMutex::ScopedLock guard(m_lock);
set<uint32_t> registered;
set<unsigned int> freeSlots = allSlots();
for (const auto &gadget : readGadgets(SCAN_SLOTS_TIMEOUT)) {
registered.emplace(gadget.address());
freeSlots.erase(gadget.slot());
}
const auto address = extractAddress(id);
const auto it = registered.find(address);
if (it == registered.end())
registerGadget(freeSlots, address, SHORT_TIMEOUT);
const auto secondary = JablotronGadget::Info::secondaryAddress(address);
if (secondary != address) {
const auto it = registered.find(secondary);
if (it == registered.end())
registerGadget(freeSlots, secondary, SHORT_TIMEOUT);
}
}
void JablotronDeviceManager::enrollTX()
{
m_controller.sendEnroll(SHORT_TIMEOUT);
}
void JablotronDeviceManager::handleAccept(const DeviceAcceptCommand::Ptr cmd)
{
const auto id = cmd->deviceID();
if (id == PGX_ID || id == SIREN_ID) {
enrollTX();
}
else if (id == PGY_ID) {
enrollTX();
sleep(m_pgyEnrollGap);
enrollTX();
}
else {
acceptGadget(id);
}
DeviceManager::handleAccept(cmd);
}
void JablotronDeviceManager::newDevice(
const DeviceID &id,
const string &name,
const list<ModuleType> &types,
const RefreshTime &refreshTime)
{
auto builder = DeviceDescription::Builder()
.id(id)
.type("Jablotron", name)
.modules(types)
.refreshTime(refreshTime);
dispatch(new NewDeviceCommand(builder.build()));
}
AsyncWork<>::Ptr JablotronDeviceManager::startDiscovery(const Timespan &timeout)
{
const Clock started;
if (!deviceCache()->paired(PGX_ID))
newDevice(PGX_ID, "PGX", PG_MODULES, RefreshTime::NONE);
if (!deviceCache()->paired(PGY_ID))
newDevice(PGY_ID, "PGY", PG_MODULES, RefreshTime::NONE);
if (!deviceCache()->paired(SIREN_ID))
newDevice(SIREN_ID, "Siren", SIREN_MODULES, RefreshTime::NONE);
FastMutex::ScopedLock guard(m_lock);
for (const auto &gadget : readGadgets(timeout)) {
if (!gadget.info())
continue;
const auto id = buildID(gadget.address());
const bool paired = deviceCache()->paired(id);
logger().information(
"gadget (" + string(paired? "paired" : "not-paired") + "): "
+ gadget.toString() + " " + id.toString(),
__FILE__, __LINE__);
if (paired)
continue;
if (gadget.isSecondary())
continue; // secondary devices are not reported
newDevice(id, gadget.info().name(),
gadget.info().modules, gadget.info().refreshTime);
}
return BlockingAsyncWork<>::instance();
}
AsyncWork<>::Ptr JablotronDeviceManager::startSearch(
const Timespan &timeout,
const uint64_t serialNumber)
{
if (serialNumber > 0xffffffff) {
throw InvalidArgumentException(
"address " + to_string(serialNumber)
+ " is out-of range");
}
const uint32_t address = static_cast<uint32_t>(serialNumber);
const auto info = JablotronGadget::Info::resolve(address);
if (!info) {
throw InvalidArgumentException(
"address " + NumberFormatter::format0(address, 8)
+ " was not recognized");
}
const auto id = buildID(address);
FastMutex::ScopedLock guard(m_lock);
set<uint32_t> registered;
set<unsigned int> freeSlots;
set<unsigned int> unknownSlots;
scanSlots(registered, freeSlots, unknownSlots);
if (registered.find(address) == registered.end()) {
if (!freeSlots.empty()) {
registerGadget(freeSlots, address, timeout);
}
else {
logger().warning("overwriting a non-free slot...", __FILE__, __LINE__);
registerGadget(unknownSlots, address, timeout);
}
}
if (!deviceCache()->paired(id))
newDevice(id, info.name(), info.modules, info.refreshTime);
return BlockingAsyncWork<>::instance();
}
void JablotronDeviceManager::unregisterGadget(
const DeviceID &id,
const Timespan &timeout)
{
if (!m_unpairErasesSlot) {
if (logger().debug()) {
logger().debug(
"unregistering of gadgets from slots is disabled",
__FILE__, __LINE__);
}
return;
}
const uint32_t address = extractAddress(id);
const uint32_t secondary = JablotronGadget::Info::secondaryAddress(address);
bool done = false;
FastMutex::ScopedLock guard(m_lock);
for (const auto &gadget : readGadgets(timeout)) {
if (address != gadget.address() && secondary != gadget.address())
continue;
m_controller.unregisterSlot(gadget.slot(), SHORT_TIMEOUT);
logger().information(
"gadget " + gadget.toString()
+ " was unregistered from its slot");
done = true;
}
if (!done)
logger().warning("device " + id.toString() + " was not registered in any slot");
}
AsyncWork<set<DeviceID>>::Ptr JablotronDeviceManager::startUnpair(
const DeviceID &id,
const Timespan &timeout)
{
set<DeviceID> result;
logger().information("unpairing device " + id.toString());
if (id == PGX_ID || id == PGY_ID || id == SIREN_ID) {
// almost nothing to do, un-enroll does not exist
deviceCache()->markUnpaired(id);
result.emplace(id);
}
else {
unregisterGadget(id, timeout);
deviceCache()->markUnpaired(id);
result.emplace(id);
}
auto work = BlockingAsyncWork<set<DeviceID>>::instance();
work->setResult(result);
return work;
}
AsyncWork<double>::Ptr JablotronDeviceManager::startSetValue(
const DeviceID &id,
const ModuleID &module,
const double value,
const Timespan &timeout)
{
if (!deviceCache()->paired(id)) {
throw NotFoundException(
"no such device " + id.toString() + " is paired");
}
if (id != PGX_ID && id != PGY_ID && id != SIREN_ID) {
throw InvalidArgumentException(
"device " + id.toString() + " is not controllable");
}
if ((id == PGX_ID || id == PGY_ID) && module != ModuleID(0)) {
throw NotFoundException(
"no such controllable module " + module.toString()
+ " for device " + id.toString());
}
if (value < 0) {
throw InvalidArgumentException(
"invalid value for device "
+ id.toString() + ": " + to_string(value));
}
const auto v = static_cast<unsigned int>(value);
if (id == PGX_ID) {
m_pgx = v != 0;
}
else if (id == PGY_ID) {
m_pgy = v != 0;
}
else if (id == SIREN_ID) {
if (module == SIREN_ALARM_ID) {
m_alarm = v != 0;
}
else if (module != SIREN_BEEP_ID) {
throw NotFoundException(
"no such controllable module " + module.toString()
+ " for device " + id.toString());
}
switch (v) {
case 0:
m_beep = JablotronController::BEEP_NONE;
break;
case 1:
m_beep = JablotronController::BEEP_SLOW;
break;
case 2:
m_beep = JablotronController::BEEP_FAST;
break;
default:
throw InvalidArgumentException(
"invalid value for beep control: " + to_string(value));
}
}
BackOff::Ptr backoff = m_txBackOffFactory->create();
Timespan delay;
do {
m_controller.sendTX(m_pgx, m_pgy, m_alarm, m_beep, timeout);
delay = backoff->next();
sleep(delay);
} while (delay != BackOff::STOP);
auto work = BlockingAsyncWork<double>::instance();
work->setResult(static_cast<double>(v));
return work;
}
| 24.976834 | 94 | 0.718504 | jalowiczor |
6445847f7a81ff6c620ce0cec4612881c72a6f8f | 347 | cpp | C++ | simulation/src/main.cpp | hps-ucsd/steering-control | 04fe420641c5c70b4128c72d15df4c490e168ff2 | [
"MIT"
] | null | null | null | simulation/src/main.cpp | hps-ucsd/steering-control | 04fe420641c5c70b4128c72d15df4c490e168ff2 | [
"MIT"
] | null | null | null | simulation/src/main.cpp | hps-ucsd/steering-control | 04fe420641c5c70b4128c72d15df4c490e168ff2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <Gyro.hpp>
#include <Stepper.hpp>
int pid(int setPoint, int sensor)
{
int error = setPoint - sensor;
return error;
}
int main()
{
Gyro gyro("zero.txt");
Stepper stepper("stepper_zero_out.txt");
for (int i = 0; i < 10000; i++)
{
stepper.move(pid(0, gyro.readY()));
}
} | 14.458333 | 41 | 0.651297 | hps-ucsd |
6447943e7aeb646b095b1082200e9647d2b9b0b7 | 16,380 | hpp | C++ | include/autogen/core/generated_codegen.hpp | dmillard/autogen | c14790f01b7e6ff4c140331317ad981c33e9b40f | [
"MIT"
] | null | null | null | include/autogen/core/generated_codegen.hpp | dmillard/autogen | c14790f01b7e6ff4c140331317ad981c33e9b40f | [
"MIT"
] | null | null | null | include/autogen/core/generated_codegen.hpp | dmillard/autogen | c14790f01b7e6ff4c140331317ad981c33e9b40f | [
"MIT"
] | 1 | 2021-10-31T10:59:49.000Z | 2021-10-31T10:59:49.000Z | #pragma once
// clang-format off
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
#include <thread>
#include "../utils/conditionals.hpp"
#include "../cuda/cuda_codegen.hpp"
#include "../cuda/cuda_library_processor.hpp"
#include "../cuda/cuda_library.hpp"
#include "codegen.hpp"
// clang-format on
namespace autogen {
enum CodeGenTarget { TARGET_CPU, TARGET_CUDA };
class GeneratedCodeGen : public GeneratedBase {
template <template <typename> typename Functor>
friend struct Generated;
public:
using CppADScalar = typename CppAD::AD<BaseScalar>;
using CGScalar = typename CppAD::AD<CppAD::cg::CG<BaseScalar>>;
using ADFun = typename FunctionTrace<BaseScalar>::ADFun;
using AbstractCCompiler = typename CppAD::cg::AbstractCCompiler<double>;
using MsvcCompiler = typename CppAD::cg::MsvcCompiler<double>;
using ClangCompiler = typename CppAD::cg::ClangCompiler<double>;
using GccCompiler = typename CppAD::cg::GccCompiler<double>;
private:
using CGAtomicFunBridge =
typename FunctionTrace<BaseScalar>::CGAtomicFunBridge;
typedef CppAD::cg::GenericModel<BaseScalar> GenericModel;
typedef std::shared_ptr<GenericModel> GenericModelPtr;
CodeGenTarget target_{TARGET_CUDA};
protected:
using GeneratedBase::global_input_dim_;
using GeneratedBase::local_input_dim_;
using GeneratedBase::output_dim_;
AccumulationMethod jac_acc_method_{ACCUMULATE_NONE};
// name of the compiled library
std::string library_name_;
std::string name_;
FunctionTrace<BaseScalar> main_trace_;
mutable std::shared_ptr<CudaLibrary<BaseScalar>> cuda_library_{nullptr};
#if AUTOGEN_SYSTEM_WIN
typedef CppAD::cg::WindowsDynamicLib<BaseScalar> DynamicLib;
#else
typedef CppAD::cg::LinuxDynamicLib<BaseScalar> DynamicLib;
#endif
mutable std::shared_ptr<DynamicLib> cpu_library_{nullptr};
mutable std::map<std::string, GenericModelPtr> cpu_models_;
public:
int num_gpu_threads_per_block{32};
/**
* Whether the generated code is compiled in debug mode (only applies to CPU
* and CUDA).
*/
bool debug_mode{false};
/**
* Optimization level to use when compiling CPU and CUDA code.
* Will be 0 when debug_mode is active.
*/
int optimization_level{2};
/**
* Whether to generate code for the zero-order forward mode.
*/
bool generate_forward{true};
/**
* Whether to generate code for the Jacobian.
*/
bool generate_jacobian{true};
CodeGenTarget target() const { return target_; }
void set_target(CodeGenTarget target) { target_ = target; }
std::shared_ptr<AbstractCCompiler> cpu_compiler{nullptr};
GeneratedCodeGen(const FunctionTrace<BaseScalar> &main_trace)
: name_(main_trace.name), main_trace_(main_trace) {
output_dim_ = main_trace_.output_dim;
local_input_dim_ = main_trace_.input_dim;
}
GeneratedCodeGen(const std::string &name, std::shared_ptr<ADFun> tape)
: name_(name) {
main_trace_.tape = tape;
output_dim_ = static_cast<int>(tape->Range());
local_input_dim_ = static_cast<int>(tape->Domain());
std::cout << "tape->Range(): " << tape->Range() << std::endl;
std::cout << "tape->Domain(): " << tape->Domain() << std::endl;
}
void set_cpu_compiler_clang(
std::string compiler_path = "",
const std::vector<std::string> &compile_flags =
std::vector<std::string>{},
const std::vector<std::string> &compile_lib_flags = {}) {
if (compiler_path.empty()) {
compiler_path = autogen::find_exe("clang");
}
cpu_compiler = std::make_shared<ClangCompiler>(compiler_path);
for (const auto &flag : compile_flags) {
cpu_compiler->addCompileFlag(flag);
}
for (const auto &flag : compile_lib_flags) {
cpu_compiler->addCompileLibFlag(flag);
}
}
void set_cpu_compiler_gcc(
std::string compiler_path = "",
const std::vector<std::string> &compile_flags =
std::vector<std::string>{},
const std::vector<std::string> &compile_lib_flags = {}) {
if (compiler_path.empty()) {
compiler_path = autogen::find_exe("gcc");
}
cpu_compiler = std::make_shared<GccCompiler>(compiler_path);
for (const auto &flag : compile_flags) {
cpu_compiler->addCompileFlag(flag);
}
for (const auto &flag : compile_lib_flags) {
cpu_compiler->addCompileLibFlag(flag);
}
}
void set_cpu_compiler_msvc(
std::string compiler_path = "", std::string linker_path = "",
const std::vector<std::string> &compile_flags =
std::vector<std::string>{},
const std::vector<std::string> &compile_lib_flags = {}) {
if (compiler_path.empty()) {
compiler_path = autogen::find_exe("cl.exe");
}
if (linker_path.empty()) {
linker_path = autogen::find_exe("link.exe");
}
cpu_compiler = std::make_shared<MsvcCompiler>(compiler_path, linker_path);
for (const auto &flag : compile_flags) {
cpu_compiler->addCompileFlag(flag);
}
for (const auto &flag : compile_lib_flags) {
cpu_compiler->addCompileLibFlag(flag);
}
}
// discards the compiled library (so that it gets recompiled at the next
// evaluation)
void discard_library() { library_name_ = ""; }
const std::string &library_name() const { return library_name_; }
void load_precompiled_library(const std::string &library_name) {
if (library_name != library_name_) {
discard_library();
}
library_name_ = library_name;
}
void set_global_input_dim(int dim) override {
global_input_dim_ = dim;
local_input_dim_ = static_cast<int>(main_trace_.tape->Domain() - dim);
discard_library();
}
bool is_compiled() const { return !library_name_.empty(); }
void operator()(const std::vector<BaseScalar> &input,
std::vector<BaseScalar> &output) override {
if (target_ == TARGET_CPU) {
assert(!library_name_.empty());
auto model = get_cpu_model();
model->ForwardZero(input, output);
} else if (target_ == TARGET_CUDA) {
const auto &model = get_cuda_model();
model.forward_zero(input, output);
}
}
void operator()(const std::vector<std::vector<BaseScalar>> &local_inputs,
std::vector<std::vector<BaseScalar>> &outputs,
const std::vector<BaseScalar> &global_input) override {
outputs.resize(local_inputs.size());
if (target_ == TARGET_CPU) {
assert(!library_name_.empty());
for (auto &o : outputs) {
o.resize(output_dim_);
}
int num_tasks = static_cast<int>(local_inputs.size());
#pragma omp parallel for
for (int i = 0; i < num_tasks; ++i) {
if (global_input.empty()) {
auto model = get_cpu_model();
model->ForwardZero(local_inputs[i], outputs[i]);
} else {
static thread_local std::vector<BaseScalar> input;
input = global_input;
input.resize(global_input.size() + local_inputs[0].size());
for (size_t j = 0; j < local_inputs[i].size(); ++j) {
input[j + global_input.size()] = local_inputs[i][j];
}
auto model = get_cpu_model();
model->ForwardZero(input, outputs[i]);
}
}
} else if (target_ == TARGET_CUDA) {
const auto &model = get_cuda_model();
model.forward_zero(&outputs, local_inputs, num_gpu_threads_per_block,
global_input);
}
}
void jacobian(const std::vector<BaseScalar> &input,
std::vector<BaseScalar> &output) override {
if (target_ == TARGET_CPU) {
assert(!library_name_.empty());
auto model = get_cpu_model();
model->Jacobian(input, output);
} else if (target_ == TARGET_CUDA) {
const auto &model = get_cuda_model();
model.jacobian(input, output);
}
}
void jacobian(const std::vector<std::vector<BaseScalar>> &local_inputs,
std::vector<std::vector<BaseScalar>> &outputs,
const std::vector<BaseScalar> &global_input) override {
outputs.resize(local_inputs.size());
if (target_ == TARGET_CPU) {
assert(!library_name_.empty());
for (auto &o : outputs) {
o.resize(input_dim() * output_dim_);
}
int num_tasks = static_cast<int>(local_inputs.size());
#pragma omp parallel for
for (int i = 0; i < num_tasks; ++i) {
if (global_input.empty()) {
auto model = get_cpu_model();
// model->ForwardZero(local_inputs[i], outputs[i]);
model->Jacobian(local_inputs[i], outputs[i]);
} else {
static thread_local std::vector<BaseScalar> input;
if (input.empty()) {
input.resize(global_input.size());
input.insert(input.begin(), global_input.begin(),
global_input.end());
}
for (size_t j = 0; j < local_inputs[i].size(); ++j) {
input[j + global_input.size()] = local_inputs[i][j];
}
auto model = get_cpu_model();
model->Jacobian(input, outputs[i]);
}
}
} else if (target_ == TARGET_CUDA) {
const auto &model = get_cuda_model();
model.jacobian(&outputs, local_inputs, num_gpu_threads_per_block,
global_input);
}
}
void compile_cpu() {
using namespace CppAD;
using namespace CppAD::cg;
ModelCSourceGen<BaseScalar> main_source_gen(*(main_trace_.tape), name_);
main_source_gen.setCreateForwardZero(generate_forward);
main_source_gen.setCreateJacobian(generate_jacobian);
ModelLibraryCSourceGen<BaseScalar> libcgen(main_source_gen);
// reverse order of invocation to first generate code for innermost
// functions
const auto &order = *CodeGenData<BaseScalar>::invocation_order;
std::list<ModelCSourceGen<BaseScalar> *> models;
for (auto it = order.rbegin(); it != order.rend(); ++it) {
FunctionTrace<BaseScalar> &trace =
(*CodeGenData<BaseScalar>::traces)[*it];
// trace.tape->optimize();
auto *source_gen = new ModelCSourceGen<BaseScalar>(*(trace.tape), *it);
source_gen->setCreateForwardZero(generate_forward);
// source_gen->setCreateSparseJacobian(generate_jacobian);
// source_gen->setCreateJacobian(generate_jacobian);
source_gen->setCreateForwardOne(generate_jacobian);
source_gen->setCreateReverseOne(generate_jacobian);
models.push_back(source_gen);
// we need a stable reference
libcgen.addModel(*(models.back()));
}
libcgen.setVerbose(true);
DynamicModelLibraryProcessor<BaseScalar> p(libcgen);
// if (clang_path.empty()) {
// clang_path = autogen::find_exe("clang", false);
// }
// if (clang_path.empty()) {
// throw std::runtime_error(
// "Clang path is empty, make sure clang is "
// "available on the system path or provide it manually to the "
// "GeneratedCodegen instance.");
// }
// auto compiler = std::make_unique<ClangCompiler<BaseScalar>>(clang_path);
if (!cpu_compiler) {
#if AUTOGEN_SYSTEM_WIN
set_cpu_compiler_msvc();
#else
set_cpu_compiler_clang();
#endif
}
cpu_compiler->setSourcesFolder(name_ + "_cpu_srcs");
cpu_compiler->setTemporaryFolder(name_ + "_cpu_tmp");
cpu_compiler->setSaveToDiskFirst(true);
if (debug_mode) {
cpu_compiler->addCompileFlag("-g");
cpu_compiler->addCompileFlag("-O0");
} else {
cpu_compiler->addCompileFlag("-O" + std::to_string(optimization_level));
}
p.setLibraryName(name_ + "_cpu");
bool load_library = false; // we do this in another step
p.createDynamicLibrary(*cpu_compiler, load_library);
library_name_ = "./" + name_ + "_cpu";
target_ = TARGET_CPU;
}
mutable std::mutex cpu_library_loading_mutex_{};
GenericModelPtr get_cpu_model() const {
if (!cpu_library_) {
cpu_library_loading_mutex_.lock();
cpu_library_ = std::make_shared<DynamicLib>(library_name_ + library_ext_);
std::set<std::string> model_names = cpu_library_->getModelNames();
std::cout << "Successfully loaded CPU library "
<< library_name_ + library_ext_ << std::endl;
for (auto &name : model_names) {
std::cout << " Found model " << name << std::endl;
}
// load and wire up atomic functions in this library
const auto &order = *CodeGenData<BaseScalar>::invocation_order;
const auto &hierarchy = CodeGenData<BaseScalar>::call_hierarchy;
cpu_models_[name_] =
GenericModelPtr(cpu_library_->model(name_).release());
if (!cpu_models_[name_]) {
throw std::runtime_error("Failed to load model from library " +
library_name_ + library_ext_);
}
// atomic functions to be added
typedef std::pair<std::string, std::string> ParentChild;
std::set<ParentChild> remaining_atomics;
for (const std::string &s :
cpu_models_[name_]->getAtomicFunctionNames()) {
remaining_atomics.insert(std::make_pair(name_, s));
}
while (!remaining_atomics.empty()) {
ParentChild member = *(remaining_atomics.begin());
const std::string &parent = member.first;
const std::string &atomic_name = member.second;
remaining_atomics.erase(remaining_atomics.begin());
if (cpu_models_.find(atomic_name) == cpu_models_.end()) {
std::cout << " Adding atomic function " << atomic_name << std::endl;
cpu_models_[atomic_name] =
GenericModelPtr(cpu_library_->model(atomic_name).release());
for (const std::string &s :
cpu_models_[atomic_name]->getAtomicFunctionNames()) {
remaining_atomics.insert(std::make_pair(atomic_name, s));
}
}
auto &atomic_model = cpu_models_[atomic_name];
cpu_models_[parent]->addAtomicFunction(atomic_model->asAtomic());
}
std::cout << "Loaded compiled model \"" << name_ << "\" from \""
<< library_name_ << "\".\n";
cpu_library_loading_mutex_.unlock();
}
return cpu_models_[name_];
}
void compile_cuda() {
using namespace CppAD;
using namespace CppAD::cg;
std::cout << "Compiling CUDA code...\n";
std::cout << "Invocation order: ";
for (const auto &s : *(CodeGenData<BaseScalar>::invocation_order)) {
std::cout << s << " ";
}
std::cout << std::endl;
CudaModelSourceGen<BaseScalar> main_source_gen(*(main_trace_.tape), name_);
main_source_gen.setCreateForwardZero(generate_forward);
main_source_gen.setCreateJacobian(generate_jacobian);
main_source_gen.global_input_dim() = global_input_dim_;
main_source_gen.jacobian_acc_method() = jac_acc_method_;
CudaLibraryProcessor<BaseScalar> cuda_proc(&main_source_gen,
name_ + "_cuda");
// reverse order of invocation to first generate code for innermost
// functions
const auto &order = *CodeGenData<BaseScalar>::invocation_order;
std::list<CudaModelSourceGen<BaseScalar> *> models;
for (auto it = order.rbegin(); it != order.rend(); ++it) {
std::cout << "Adding cuda model " << *it << "\n";
FunctionTrace<BaseScalar> &trace =
(*CodeGenData<BaseScalar>::traces)[*it];
auto *source_gen = new CudaModelSourceGen<BaseScalar>(*(trace.tape), *it);
source_gen->setCreateForwardOne(generate_jacobian);
source_gen->setCreateReverseOne(generate_jacobian);
source_gen->set_kernel_only(true);
models.push_back(source_gen);
cuda_proc.add_model(models.back(), false);
}
cuda_proc.debug_mode() = debug_mode;
cuda_proc.generate_code();
cuda_proc.save_sources();
cuda_proc.optimization_level() = optimization_level;
cuda_proc.create_library();
library_name_ = name_ + "_cuda";
for (auto *model : models) {
delete model;
}
target_ = TARGET_CUDA;
}
const CudaModel<BaseScalar> &get_cuda_model() const {
if (!cuda_library_) {
cuda_library_ = std::make_shared<CudaLibrary<BaseScalar>>(library_name_);
}
return cuda_library_->get_model(name_);
}
private:
#if AUTOGEN_SYSTEM_WIN
static const inline std::string library_ext_ = ".dll";
#else
static const inline std::string library_ext_ = ".so";
#endif
};
} // namespace autogen | 35.454545 | 80 | 0.655067 | dmillard |
644940e7453c92248091666c721fa1cdf3a1057b | 374 | hpp | C++ | src/AST/Expressions/UnaryOperators/NegExpression.hpp | CarsonFox/CPSL | 07a949166d9399f273ddf15e239ade6e5ea6e4a5 | [
"MIT"
] | null | null | null | src/AST/Expressions/UnaryOperators/NegExpression.hpp | CarsonFox/CPSL | 07a949166d9399f273ddf15e239ade6e5ea6e4a5 | [
"MIT"
] | null | null | null | src/AST/Expressions/UnaryOperators/NegExpression.hpp | CarsonFox/CPSL | 07a949166d9399f273ddf15e239ade6e5ea6e4a5 | [
"MIT"
] | null | null | null | #pragma once
#include "UnaryOpExpression.hpp"
struct NegExpression : UnaryOpExpression {
explicit NegExpression(Expression *);
~NegExpression() override = default;
void print() const override;
std::optional<int> try_fold() override;
bool isConst() const override;
std::string emitToRegister(SymbolTable &table, RegisterPool &pool) override;
}; | 22 | 80 | 0.724599 | CarsonFox |
644965e33f7d1c4580fd39f180fddf67c4f4629c | 1,268 | cpp | C++ | src/menus/battle_menu/summon_view/battle_summon_callbacks.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | src/menus/battle_menu/summon_view/battle_summon_callbacks.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | src/menus/battle_menu/summon_view/battle_summon_callbacks.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null |
#include "battle_summon_callbacks.h"
#include "../../menu.h"
#include <unordered_set>
#include "../../../impl.h"
using namespace BattleMenuWidgetNames;
void initializeBattleSummonMenu() {
CursorContext summonSelection = { 0, 0, 1, 3, 0, 0, 1, SUMMON_COUNT, 0, 0, 0, 0, 0, 1 };
Cursor summonChoiceCursor = { summonSelection, 8, 364, 32, 156 };
auto battleMenu = gContext.menuWidgets.getElement(BATTLE_MENU_NAME);
setStateCursor(battleMenu, BATTLE_SUMMON_STATE, summonChoiceCursor, 0);
setStateCursor(battleMenu, BATTLE_SUMMON_STATE, summonChoiceCursor, 1);
setStateCursor(battleMenu, BATTLE_SUMMON_STATE, summonChoiceCursor, 2);
}
void registerSummonViewListeners() {
const auto& modName = std::string("srFF7Base");
const auto& contextKeys = std::unordered_set<SrEventContext>({BATTLE_MENU});
gContext.eventBus.addListener(DRAW_BATTLE_MENU, (SrEventCallback)&drawBattleSummonViewWidget, modName);
gContext.eventBus.addListener(INIT_BATTLE_MENU, (SrEventCallback)&initBattleSummonViewWidget, modName);
gContext.eventBus.addListener(MENU_INPUT_OK, (SrEventCallback)&handleSelectSummon, modName, contextKeys);
gContext.eventBus.addListener(MENU_INPUT_CANCEL, (SrEventCallback)&handleExitSummon, modName, contextKeys);
}
| 48.769231 | 111 | 0.771293 | Kor-Hal |
644e4aff07c28ffc5ef04635b081ddbac4d02666 | 415 | cpp | C++ | Source/CBackground.cpp | DegitechWorldClass/Who-am-I_Game | ae90c7a60b747667d6571557c72e2b29dc1fc767 | [
"Apache-2.0"
] | null | null | null | Source/CBackground.cpp | DegitechWorldClass/Who-am-I_Game | ae90c7a60b747667d6571557c72e2b29dc1fc767 | [
"Apache-2.0"
] | null | null | null | Source/CBackground.cpp | DegitechWorldClass/Who-am-I_Game | ae90c7a60b747667d6571557c72e2b29dc1fc767 | [
"Apache-2.0"
] | null | null | null | #include "DXUT.h"
#include "CBackground.h"
CBackground::CBackground()
{
}
CBackground::~CBackground()
{
}
void CBackground::Init()
{
}
void CBackground::Update()
{
}
void CBackground::Render()
{
}
void CBackground::Release()
{
}
void CBackground::OnCollisionEnter(CObject * _pObject)
{
}
void CBackground::OnCollisionStay(CObject * _pObject)
{
}
void CBackground::OnCollisionExit(CObject * _pObject)
{
}
| 10.121951 | 54 | 0.708434 | DegitechWorldClass |
644f07d3ed65f02310bd452fb33177ef1599b02c | 2,752 | cpp | C++ | source/scene.cpp | simonrose121/slidinghome | fb6d8cacfa8da0c52fb6202731dad11785f2f881 | [
"MIT"
] | null | null | null | source/scene.cpp | simonrose121/slidinghome | fb6d8cacfa8da0c52fb6202731dad11785f2f881 | [
"MIT"
] | null | null | null | source/scene.cpp | simonrose121/slidinghome | fb6d8cacfa8da0c52fb6202731dad11785f2f881 | [
"MIT"
] | null | null | null | /*
* (C) 2001-2012 Marmalade. All Rights Reserved.
*
* This document is protected by copyright, and contains information
* proprietary to Marmalade.
*
* This file consists of source code released by Marmalade under
* the terms of the accompanying End User License Agreement (EULA).
* Please do not use this program/source code before you have read the
* EULA and have agreed to be bound by its terms.
*/
#include "scene.h"
#include "IwGx.h"
#include "input.h"
#include "main.h"
SceneManager* g_pSceneManager = 0;
Scene::Scene() : m_NameHash(0), m_IsActive(true), m_IsInputActive(false)
{
m_X = -(float)IwGxGetScreenWidth();
}
Scene::~Scene()
{
}
void Scene::Init()
{
}
void Scene::Update(float deltaTime, float alphaMul)
{
if (!m_IsActive)
return;
m_Tweener.Update(deltaTime);
CNode::Update(deltaTime, alphaMul);
}
void Scene::Render()
{
CNode::Render();
}
void Scene::setName(const char* name)
{
m_NameHash = IwHashString(name);
}
//
//
// SceneManager class
//
//
SceneManager::~SceneManager()
{
for (std::list<Scene*>::iterator it = m_Scenes.begin(); it != m_Scenes.end(); ++it)
delete *it;
}
void SceneManager::SwitchTo(Scene* scene)
{
m_Next = scene;
if (m_Current == 0)
{
m_Current = m_Next;
m_Current->m_X = 0;
m_Current->setActive(true);
m_Current->setInputActive(true);
m_Next = 0;
}
else
{
m_Current->setInputActive(false);
m_Next->setActive(true);
m_Next->m_X = -(float)IwGxGetScreenWidth();
g_pTweener->Tween(0.5f,
FLOAT, &m_Next->m_X, 0.0f,
FLOAT, &m_Current->m_X, (float)IwGxGetScreenWidth(),
EASING, Ease::linear,
ONCOMPLETE, OnSwitchComplete,
END);
}
}
void SceneManager::Update(float deltaTime)
{
for (std::list<Scene*>::iterator it = m_Scenes.begin(); it != m_Scenes.end(); ++it)
(*it)->Update(deltaTime);
}
void SceneManager::Render()
{
for (std::list<Scene*>::iterator it = m_Scenes.begin(); it != m_Scenes.end(); ++it)
(*it)->Render();
}
void SceneManager::Add(Scene* scene)
{
m_Scenes.push_back(scene);
scene->setManager(this);
}
void SceneManager::Remove(Scene* scene)
{
m_Scenes.remove(scene);
}
Scene* SceneManager::Find(const char* name)
{
unsigned int name_hash = IwHashString(name);
for (std::list<Scene*>::iterator it = m_Scenes.begin(); it != m_Scenes.end(); ++it)
{
if ((*it)->getNameHash() == name_hash)
return *it;
}
return 0;
}
void SceneManager::OnSwitchComplete(CTween* pTween)
{
g_pSceneManager->FinishSwitch();
}
void SceneManager::FinishSwitch()
{
m_Next->setInputActive(true);
m_Next->setActive(true);
m_Current->Update(0); // Update one last time to ensure that last tweened values get set because on the next frame the scene will inactive
m_Current->setActive(false);
m_Current = m_Next;
m_Next = 0;
}
| 19.798561 | 149 | 0.689317 | simonrose121 |
64529c58690161ae6ca526066649eb1edd25c5e3 | 13,118 | cpp | C++ | nodes/https/src/controller.cpp | solosTec/node | e35e127867a4f66129477b780cbd09c5231fc7da | [
"MIT"
] | 2 | 2020-03-03T12:40:29.000Z | 2021-05-06T06:20:19.000Z | nodes/https/src/controller.cpp | solosTec/node | e35e127867a4f66129477b780cbd09c5231fc7da | [
"MIT"
] | 7 | 2020-01-14T20:38:04.000Z | 2021-05-17T09:52:07.000Z | nodes/https/src/controller.cpp | solosTec/node | e35e127867a4f66129477b780cbd09c5231fc7da | [
"MIT"
] | 2 | 2019-11-09T09:14:48.000Z | 2020-03-03T12:40:30.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Sylko Olzscher
*
*/
#include "controller.h"
#include <NODE_project_info.h>
#include "logic.h"
#include <cyng/log.h>
#include <cyng/async/scheduler.h>
#include <cyng/async/signal_handler.h>
#include <cyng/factory/set_factory.h>
#include <cyng/io/serializer.h>
#include <cyng/dom/reader.h>
#include <cyng/dom/tree_walker.h>
#include <cyng/json.h>
#include <cyng/value_cast.hpp>
#include <cyng/compatibility/io_service.h>
#include <cyng/vector_cast.hpp>
#include <cyng/vm/controller.h>
#include <fstream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/nil_generator.hpp>
#include <boost/filesystem.hpp>
#include <boost/assert.hpp>
namespace node
{
//
// forward declarations
//
bool start(cyng::async::scheduler&, cyng::logging::log_ptr, cyng::object);
bool wait(cyng::logging::log_ptr logger);
bool load_server_certificate(boost::asio::ssl::context& ctx
, cyng::logging::log_ptr
, std::string const& tls_pwd
, std::string const& tls_certificate_chain
, std::string const& tls_private_key
, std::string const& tls_dh);
controller::controller(unsigned int pool_size, std::string const& json_path)
: pool_size_(pool_size)
, json_path_(json_path)
{}
int controller::run(bool console)
{
//
// to calculate uptime
//
const std::chrono::system_clock::time_point tp_start = std::chrono::system_clock::now();
//
// controller loop
//
try
{
//
// controller loop
//
bool shutdown {false};
while (!shutdown)
{
//
// establish I/O context
//
cyng::async::scheduler scheduler{this->pool_size_};
//
// read configuration file
//
cyng::object config = cyng::json::read_file(json_path_);
if (config)
{
cyng::vector_t vec;
vec = cyng::value_cast(config, vec);
if (vec.empty())
{
std::cerr
<< "use option -D to generate a configuration file"
<< std::endl;
shutdown = true;
}
else
{
//
// initialize logger
//
#if BOOST_OS_LINUX
auto logger = cyng::logging::make_sys_logger("HTTPS", true);
// auto logger = cyng::logging::make_console_logger(ioc, "HTTPS");
#else
auto logger = cyng::logging::make_console_logger(scheduler.get_io_service(), "HTTPS");
#endif
CYNG_LOG_TRACE(logger, cyng::io::to_str(config));
CYNG_LOG_INFO(logger, "pool size: " << this->pool_size_);
//
// start application
//
shutdown = start(scheduler, logger, vec.at(0));
//
// print uptime
//
const auto duration = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - tp_start);
CYNG_LOG_INFO(logger, "HTTPS uptime " << cyng::io::to_str(cyng::make_object(duration)));
}
}
else
{
// CYNG_LOG_FATAL(logger, "no configuration data");
std::cout
<< "use option -D to generate a configuration file"
<< std::endl;
//
// no configuration found
//
shutdown = true;
}
//
// stop scheduler
//
scheduler.stop();
}
return EXIT_SUCCESS;
}
catch (std::exception& ex)
{
// CYNG_LOG_FATAL(logger, ex.what());
std::cerr
<< ex.what()
<< std::endl;
}
return EXIT_FAILURE;
}
int controller::create_config(std::string const& type) const
{
return (boost::algorithm::iequals(type, "XML"))
? create_xml_config()
: create_json_config()
;
}
int controller::create_xml_config() const
{
return EXIT_SUCCESS;
}
int controller::create_json_config() const
{
std::fstream fout(json_path_, std::ios::trunc | std::ios::out);
if (fout.is_open())
{
//
// get default values
//
const boost::filesystem::path tmp = boost::filesystem::temp_directory_path();
const boost::filesystem::path pwd = boost::filesystem::current_path();
boost::uuids::random_generator uidgen;
//
// to send emails from cgp see https://cloud.google.com/compute/docs/tutorials/sending-mail/
//
const auto conf = cyng::vector_factory({
cyng::tuple_factory(cyng::param_factory("log-dir", tmp.string())
, cyng::param_factory("log-level", "INFO")
, cyng::param_factory("tag", uidgen())
, cyng::param_factory("generated", std::chrono::system_clock::now())
, cyng::param_factory("version", cyng::version(NODE_VERSION_MAJOR, NODE_VERSION_MINOR))
, cyng::param_factory("https", cyng::tuple_factory(
cyng::param_factory("address", "0.0.0.0"),
cyng::param_factory("service", "8443"), // default is 443
#if BOOST_OS_LINUX
cyng::param_factory("document-root", "/var/www/html"),
#else
cyng::param_factory("document-root", (pwd / "htdocs").string()),
#endif
cyng::param_factory("tls-pwd", "test"),
cyng::param_factory("tls-certificate-chain", "fullchain.pem"),
cyng::param_factory("tls-private-key", "privkey.pem"),
cyng::param_factory("tls-dh", "dh4096.pem"), // diffie-hellman
cyng::param_factory("auth", cyng::vector_factory({
// directory: /
// authType:
// user:
// pwd:
cyng::tuple_factory(
cyng::param_factory("directory", "/"),
cyng::param_factory("authType", "Basic"),
cyng::param_factory("realm", "Restricted Content"),
cyng::param_factory("name", "auth@example.com"),
cyng::param_factory("pwd", "secret")
),
cyng::tuple_factory(
cyng::param_factory("directory", "/temp"),
cyng::param_factory("authType", "Basic"),
cyng::param_factory("realm", "Restricted Content"),
cyng::param_factory("name", "auth@example.com"),
cyng::param_factory("pwd", "secret")
)}
)), // auth
//185.244.25.187
cyng::param_factory("blacklist", cyng::vector_factory({
// https://bl.isx.fr/raw
cyng::make_address("185.244.25.187"), // KV Solutions B.V. scans for "login.cgi"
cyng::make_address("139.219.100.104"), // ISP Microsoft (China) Co. Ltd. - 2018-07-31T21:14
cyng::make_address("194.147.32.109") // Udovikhin Evgenii - 2019-02-01 15:23:08.13699453
})), // blacklist
cyng::param_factory("redirect", cyng::vector_factory({
cyng::param_factory("/", "/index.html")
}))
))
, cyng::param_factory("mail", cyng::tuple_factory(
cyng::param_factory("host", "smtp.gmail.com"),
cyng::param_factory("port", 465),
cyng::param_factory("auth", cyng::tuple_factory(
cyng::param_factory("name", "auth@example.com"),
cyng::param_factory("pwd", "secret"),
cyng::param_factory("method", "START_TLS")
)),
cyng::param_factory("sender", cyng::tuple_factory(
cyng::param_factory("name", "sender"),
cyng::param_factory("address", "sender@example.com")
)),
cyng::param_factory("recipients", cyng::vector_factory({
cyng::tuple_factory(
cyng::param_factory("name", "recipient"),
cyng::param_factory("address", "recipient@example.com"))}
))
))
)
});
cyng::json::write(std::cout, cyng::make_object(conf));
std::cout << std::endl;
cyng::json::write(fout, cyng::make_object(conf));
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
/**
* Start application - simplified
*/
bool start(cyng::async::scheduler& scheduler, cyng::logging::log_ptr logger, cyng::object cfg)
{
CYNG_LOG_TRACE(logger, cyng::dom_counter(cfg) << " configuration nodes found" );
auto dom = cyng::make_reader(cfg);
const auto doc_root = cyng::io::to_str(dom["https"].get("document-root"));
const auto host = cyng::io::to_str(dom["https"].get("address"));
const auto service = cyng::io::to_str(dom["https"].get("service"));
const auto port = static_cast<unsigned short>(std::stoi(service));
CYNG_LOG_TRACE(logger, "document root: " << doc_root);
// This holds the self-signed certificate used by the server
//load_server_certificate(ctx);
auto const address = cyng::make_address(host);
BOOST_ASSERT_MSG(scheduler.is_running(), "scheduler not running");
//
// get user credentials
//
auth_dirs ad;
init(dom["https"].get("auth"), ad);
for (auto const& dir : ad) {
CYNG_LOG_INFO(logger, "restricted access to [" << dir.first << "]");
}
//
// get blacklisted addresses
//
const auto blacklist_str = cyng::vector_cast<std::string>(dom["https"].get("blacklist"), "");
CYNG_LOG_INFO(logger, blacklist_str.size() << " adresses are blacklisted");
std::set<boost::asio::ip::address> blacklist;
for (auto const& a : blacklist_str) {
auto r = blacklist.insert(boost::asio::ip::make_address(a));
if (r.second) {
CYNG_LOG_TRACE(logger, *r.first);
}
else {
CYNG_LOG_WARNING(logger, "cannot insert " << a);
}
}
// The SSL context is required, and holds certificates
boost::asio::ssl::context ctx{ boost::asio::ssl::context::sslv23 };
//
// get SSL configuration
//
auto tls_pwd = cyng::value_cast<std::string>(dom["https"].get("tls-pwd"), "test");
auto tls_certificate_chain = cyng::value_cast<std::string>(dom["https"].get("tls-certificate-chain"), "fullchain.pem");
auto tls_private_key = cyng::value_cast<std::string>(dom["https"].get("tls-private-key"), "privkey.pem");
auto tls_dh = cyng::value_cast<std::string>(dom["https"].get("tls-dh"), "dh4096.pem");
CYNG_LOG_TRACE(logger, "tls-certificate-chain: " << tls_certificate_chain);
CYNG_LOG_TRACE(logger, "tls-private-key: " << tls_private_key);
CYNG_LOG_TRACE(logger, "tls-dh: " << tls_dh);
//
// This holds the self-signed certificate used by the server
//
if (load_server_certificate(ctx, logger, tls_pwd, tls_certificate_chain, tls_private_key, tls_dh)) {
//
// create VM controller
//
boost::uuids::random_generator uidgen;
cyng::controller vm(scheduler.get_io_service(), uidgen(), std::cout, std::cerr);
CYNG_LOG_TRACE(logger, "VM tag: " << vm.tag());
// Create and launch a listening port
auto srv = std::make_shared<https::server>(logger
, scheduler.get_io_service()
, ctx
, boost::asio::ip::tcp::endpoint{ address, port }
, doc_root
, ad
, blacklist
, vm);
if (srv) {
CYNG_LOG_TRACE(logger, "HTTPS server established");
}
else {
CYNG_LOG_FATAL(logger, "no HTTPS server instance");
}
//
// add logic
//
https::logic handler(*srv, vm, logger);
CYNG_LOG_TRACE(logger, "HTTPS server logic initialized - start listening");
if (srv->run())
{
//
// wait for system signals
//
const bool shutdown = wait(logger);
//
// close acceptor
//
CYNG_LOG_INFO(logger, "close acceptor");
srv->close();
return shutdown;
}
else
{
CYNG_LOG_FATAL(logger, "HTTPS server startup failed");
}
}
else {
CYNG_LOG_FATAL(logger, "loading server certificates failed");
}
//
// shutdown
//
return true;
}
bool wait(cyng::logging::log_ptr logger)
{
//
// wait for system signals
//
bool shutdown = false;
cyng::signal_mgr signal;
switch (signal.wait())
{
#if BOOST_OS_WINDOWS
case CTRL_BREAK_EVENT:
#else
case SIGHUP:
#endif
CYNG_LOG_INFO(logger, "SIGHUP received");
break;
default:
CYNG_LOG_WARNING(logger, "SIGINT received");
shutdown = true;
break;
}
return shutdown;
}
bool load_server_certificate(boost::asio::ssl::context& ctx
, cyng::logging::log_ptr logger
, std::string const& tls_pwd
, std::string const& tls_certificate_chain
, std::string const& tls_private_key
, std::string const& tls_dh)
{
//
// generate files with (see https://www.adfinis-sygroup.ch/blog/de/openssl-x509-certificates/):
// https://certbot.eff.org/lets-encrypt/ubuntubionic-other
//
// openssl genrsa -out solostec.com.key 4096
// openssl req -new -sha256 -key solostec.com.key -out solostec.com.csr
// openssl req -new -sha256 -nodes -newkey rsa:4096 -keyout solostec.com.key -out solostec.com.csr
// openssl req -x509 -sha256 -nodes -newkey rsa:4096 -keyout solostec.com.key -days 730 -out solostec.com.pem
ctx.set_password_callback([&tls_pwd](std::size_t, boost::asio::ssl::context_base::password_purpose) {
return "test";
//return tls_pwd;
});
ctx.set_options(
boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
//boost::asio::ssl::context::no_sslv3 |
boost::asio::ssl::context::single_dh_use);
try {
ctx.use_certificate_chain_file(tls_certificate_chain);
CYNG_LOG_INFO(logger, tls_certificate_chain << " successfull loaded");
ctx.use_private_key_file(tls_private_key, boost::asio::ssl::context::pem);
CYNG_LOG_INFO(logger, tls_private_key << " successfull loaded");
ctx.use_tmp_dh_file(tls_dh);
CYNG_LOG_INFO(logger, tls_dh << " successfull loaded");
}
catch (std::exception const& ex) {
CYNG_LOG_FATAL(logger, ex.what());
return false;
}
return true;
}
}
| 28.210753 | 122 | 0.642476 | solosTec |
645564c972f60cb675ead1ab523d3c909127964f | 43 | cpp | C++ | src/boundary/boundary_condition.cpp | FredyTP/CFDcode | 3c11671a25dc2b84626484bf30b63089166078df | [
"MIT"
] | null | null | null | src/boundary/boundary_condition.cpp | FredyTP/CFDcode | 3c11671a25dc2b84626484bf30b63089166078df | [
"MIT"
] | null | null | null | src/boundary/boundary_condition.cpp | FredyTP/CFDcode | 3c11671a25dc2b84626484bf30b63089166078df | [
"MIT"
] | null | null | null | #include <boundary/boundary_condition.h>
| 10.75 | 40 | 0.790698 | FredyTP |
645fed5baefc3bc9b5415e593fd3a3fb2d965780 | 4,380 | cpp | C++ | src/Multiplayer.cpp | LukacsBotond/Battleship-Game-Engine | 53dc545b4c0df2efb143d9ef8872fa566e7baa93 | [
"Unlicense"
] | 2 | 2020-10-13T05:54:24.000Z | 2020-10-16T08:58:11.000Z | src/Multiplayer.cpp | LukacsBotond/Battleship-Game-Engine | 53dc545b4c0df2efb143d9ef8872fa566e7baa93 | [
"Unlicense"
] | null | null | null | src/Multiplayer.cpp | LukacsBotond/Battleship-Game-Engine | 53dc545b4c0df2efb143d9ef8872fa566e7baa93 | [
"Unlicense"
] | 1 | 2020-12-15T09:15:08.000Z | 2020-12-15T09:15:08.000Z | #include "Multiplayer.h"
void InitializeWinsock()
{
WSADATA wsaData;
int result;
result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != NO_ERROR)
{
cout << "Hiba a WSAStartup() –nál\n";
}
//cout << "initialize test" << endl;
}
/*void stringToCharArray(string s, string s1, char* char_array)
{
string fullString = s + "." + s1;
//char* char_array;
char_array = &fullString[0];
//cout << char_array;
//return char_array;
}*/
string CharArrayToString(char* array)
{
string s(array);
return s;
}
string recvFromPlayer(SOCKET PlayerSocket, sockaddr_in Address)
{
const int messageLen = 25;
char message[messageLen];
int result;
int addressSize = sizeof(Address);
string coordinates;
cout << "waiting for message" << endl;
//recvfrom waits for a message to arrive
result = recvfrom(PlayerSocket, message, messageLen, 0, (SOCKADDR*)&Address, &addressSize);
if (result == SOCKET_ERROR)
{
cout << "Hiba a fogadasnal a kovetkezo hibakoddal:\n" << WSAGetLastError();
closesocket(PlayerSocket);
WSACleanup();
return "";
}
message[result] = '\0';
//convert the char array message to a string
coordinates = CharArrayToString(message);
//cout << "Received message:" << coordinates;
if (result == 0)
{
cout << "A kapcsolat megszakadt.\n";
WSACleanup();
return "";
}
return coordinates;
}
sockaddr_in createAddress()
{
sockaddr_in Address;
Address.sin_family = AF_INET;
Address.sin_port = htons(13000);
inet_pton(AF_INET, "127.0.0.1", &Address.sin_addr);
return Address;
}
SOCKET bindPlayers(sockaddr_in Address)
{
SOCKET playerSocket;
playerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// Bind the socket.
if (bind(playerSocket, (SOCKADDR*)&Address, sizeof(Address)) == SOCKET_ERROR)
{
printf("bind() failed.\n");
cout << WSAGetLastError();
closesocket(playerSocket);
WSACleanup();
}
return playerSocket;
}
void sendToPlayer(sockaddr_in Address, string x, string y)
{
int addressSize = sizeof(Address);
int result;
string fullString = x + "." + y;
//creating a char array and copy the string into it,sendto only works with char array
char* message = new char[fullString.length() + 1];
strcpy_s(message, fullString.length() + 1, fullString.c_str());
const int messageLen = strlen(message);
SOCKET playerSocket;
playerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//Send message to the address
result = sendto(playerSocket, message, messageLen, 0, (SOCKADDR*)&Address, addressSize);
if (result == SOCKET_ERROR)
{
cout << "Hiba a kuldesnel a kovetkezo hibakoddal:\n" << WSAGetLastError();
closesocket(playerSocket);
WSACleanup();
}
if (result == 0)
{
cout << "A kapcsolat megszakadt.\n";
closesocket(playerSocket);
WSACleanup();
}
}
void sendSettingToPlayer(sockaddr_in Address, string setting)
{
int addressSize = sizeof(Address);
int result;
//creating a char array and copy the string into it,sendto only works with char array
char* message = new char[setting.length() + 1];
strcpy_s(message, setting.length() + 1, setting.c_str());
const int messageLen = strlen(message);
SOCKET playerSocket;
playerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//Send message to the address
result = sendto(playerSocket, message, messageLen, 0, (SOCKADDR*)&Address, addressSize);
if (result == SOCKET_ERROR)
{
cout << "Hiba a kuldesnel a kovetkezo hibakoddal:\n" << WSAGetLastError();
closesocket(playerSocket);
WSACleanup();
}
if (result == 0)
{
cout << "A kapcsolat megszakadt.\n";
closesocket(playerSocket);
WSACleanup();
}
}
void sendMessage(string x, string y)
{
sockaddr_in Address;
InitializeWinsock();
Address = createAddress();
sendToPlayer(Address, x, y);
WSACleanup();
}
void sendSetting(string x)
{
sockaddr_in Address;
InitializeWinsock();
Address = createAddress();
sendSettingToPlayer(Address, x);
WSACleanup();
}
string recvMessage()
{
InitializeWinsock();
sockaddr_in Address;
SOCKET player;
string coordinates;
Address = createAddress();
player = bindPlayers(Address);
coordinates = recvFromPlayer(player, Address);
WSACleanup();
return coordinates;
}
| 20.372093 | 93 | 0.669863 | LukacsBotond |
64613718df175d329d83560c24aff0abd6231b15 | 2,945 | hpp | C++ | src/Subsystems/GearBox.hpp | frc3512/Robot-2016 | a3f8b6f6c9cb9f7ddddc7f05581178dc3494ae86 | [
"BSD-3-Clause"
] | null | null | null | src/Subsystems/GearBox.hpp | frc3512/Robot-2016 | a3f8b6f6c9cb9f7ddddc7f05581178dc3494ae86 | [
"BSD-3-Clause"
] | null | null | null | src/Subsystems/GearBox.hpp | frc3512/Robot-2016 | a3f8b6f6c9cb9f7ddddc7f05581178dc3494ae86 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016-2020 FRC Team 3512. All Rights Reserved.
#pragma once
#include <limits>
#include <memory>
#include <vector>
#include <PIDOutput.h>
#include <PIDSource.h>
#include <Solenoid.h>
#include "../WPILib/CANTalon.hpp"
namespace frc {
class DigitalInput;
} // namespace frc
/**
* Represents a gear box with up to 3 motors and an encoder
*
* Notes:
* - This class uses only CANTalons.
* - Up to three motors can be specified per gearbox, since drive train
* gearboxes will use up to three and other gearboxes will use less.
*/
class GearBox : public frc::PIDOutput, public frc::PIDSource {
public:
GearBox(int shifterChan, int forwardLimitPin, int reverseLimitPin,
int motor1, int motor2 = -1, int motor3 = -1);
// Disables PID controller and sets the motor speeds manually
void Set(double value);
// Returns current count on encoder
double Get() const;
// Returns current position of master CANTalon
double GetPosition() const;
// Returns current speed of master CANTalon
double GetSpeed() const;
void SetDistancePerPulse(double distancePerPulse);
void SetFeedbackDevice(frc::CANTalon::FeedbackDevice device);
// Resets encoder distance to 0
void ResetEncoder();
// Reverses gearbox drive direction
void SetInverted(bool reverse);
// Returns motor reversal state of gearbox
bool GetInverted() const;
// Reverses gearbox drive direction
void SetSensorDirection(bool reverse);
// Returns motor reversal state of gearbox
bool IsEncoderReversed() const;
// If true, motor is stopped when either limit switch reads high
void SetLimitOnHigh(bool limitOnHigh);
// Keeps gearbox within a certain position range
void SetSoftPositionLimits(double min, double max);
// Shifts gearbox to another gear if available
void SetGear(bool gear);
// Gets current gearbox gear if available (false if not)
bool GetGear() const;
// Returns non-owning pointer to master CANTalon
CANTalon* GetMaster() const;
// PIDOutput interface
void PIDWrite(double output) override;
// PIDSource interface
double PIDGet() override;
private:
bool m_isEncoderReversed = false;
bool m_limitOnHigh = true;
double m_min = std::numeric_limits<double>::min();
double m_max = std::numeric_limits<double>::max();
// Conversion factor for setpoints with respect to encoder readings
double m_distancePerPulse = 1.0;
// Feedback device
frc::CANTalon::FeedbackDevice m_feedbackDevice = frc::CANTalon::QuadEncoder;
std::unique_ptr<frc::Solenoid> m_shifter;
// Prevents motor from rotating forward when switch is pressed
frc::DigitalInput* m_forwardLimit = nullptr;
// Prevents motor from rotating in reverse when switch is pressed
frc::DigitalInput* m_reverseLimit = nullptr;
std::vector<std::unique_ptr<frc::CANTalon>> m_motors;
};
| 27.523364 | 80 | 0.710696 | frc3512 |
646714c13c091146e51b2e4d173296f00636f741 | 19,774 | cpp | C++ | src/asp_preprocessor.cpp | timn/clasp | 60cd7b35e164f4acc9d7954779270538b2765c34 | [
"MIT"
] | 85 | 2016-10-25T10:44:32.000Z | 2022-02-04T23:34:39.000Z | src/asp_preprocessor.cpp | timn/clasp | 60cd7b35e164f4acc9d7954779270538b2765c34 | [
"MIT"
] | 63 | 2016-12-17T07:36:12.000Z | 2022-03-14T23:08:01.000Z | src/asp_preprocessor.cpp | timn/clasp | 60cd7b35e164f4acc9d7954779270538b2765c34 | [
"MIT"
] | 16 | 2016-11-19T13:52:42.000Z | 2021-03-15T15:15:35.000Z | //
// Copyright (c) 2006-2017 Benjamin Kaufmann
//
// This file is part of Clasp. See http://www.cs.uni-potsdam.de/clasp/
//
// 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 <clasp/asp_preprocessor.h>
#include <clasp/logic_program.h>
#include <clasp/shared_context.h>
namespace Clasp { namespace Asp {
/////////////////////////////////////////////////////////////////////////////////////////
// simple preprocessing
//
// Simplifies the program by computing max consequences.
// Then assign variables to non-trivial supported bodies and atoms.
/////////////////////////////////////////////////////////////////////////////////////////
bool Preprocessor::preprocessSimple() {
if (!prg_->propagate(true)) { return false; }
uint32 startVar = prg_->ctx()->numVars() + 1;
// start with initially supported bodies
VarVec& supported = prg_->getSupportedBodies(true);
VarVec unitBodies;
for (VarVec::size_type i = 0; i != supported.size(); ++i) {
// set up body
PrgBody* b = prg_->getBody(supported[i]);
if (!b->simplify(*prg_, false)) { return false; }
if (b->var() < startVar) {
if (b->size() != 1) { b->assignVar(*prg_); }
else { unitBodies.push_back(supported[i]); }
}
// add all heads of b to the "upper"-closure and
// remove any false/removed atoms from head
if (!addHeadsToUpper(b) || !b->simplifyHeads(*prg_, true)) {
return false;
}
}
for (VarVec::const_iterator it = unitBodies.begin(), end = unitBodies.end(); it != end; ++it) {
prg_->getBody(*it)->assignVar(*prg_);
}
return prg_->propagate();
}
bool Preprocessor::addHeadToUpper(PrgHead* head, PrgEdge support) {
assert(head->relevant() && !head->inUpper());
head->simplifySupports(*prg_, false);
head->assignVar(*prg_, support, eq());
head->clearSupports();
head->setInUpper(true);
if (head->isAtom()) {
return propagateAtomVar(static_cast<PrgAtom*>(head), support);
}
// add all unseen atoms of disjunction to upper
PrgDisj* d = static_cast<PrgDisj*>(head);
support = PrgEdge::newEdge(*d, PrgEdge::Choice);
bool ok = true;
for (PrgDisj::atom_iterator it = d->begin(), end = d->end(); it != end && ok; ++it) {
PrgAtom* at = prg_->getAtom(*it);
if (!at->relevant()) { continue; }
if (!at->inUpper()) { ok = addHeadToUpper(at, support); }
at->addSupport(support);
}
return ok;
}
/////////////////////////////////////////////////////////////////////////////////////////
// equivalence preprocessing
//
// Computes max consequences and minimizes the number of necessary variables
// by computing equivalence-classes.
/////////////////////////////////////////////////////////////////////////////////////////
bool Preprocessor::preprocessEq(uint32 maxIters) {
uint32 startVar = prg_->ctx()->numVars();
ValueRep res = value_true;
pass_ = 0;
maxPass_ = maxIters;
HeadRange atoms = HeadRange(prg_->atom_begin() + prg_->startAtom(), prg_->atom_end());
bodyInfo_.resize( prg_->numBodies() + 1 );
do {
if (++pass_ > 1) {
for (HeadIter it = prg_->atom_begin(), end = atoms.second; it != end; ) {
while (it != atoms.first){ (*it)->setInUpper(false); ++it; }
while (it != end) { (*it)->clearLiteral(false); (*it)->setInUpper(false); ++it; }
}
for (HeadIter it = prg_->disj_begin(), end = prg_->disj_end(); it != end; ++it) {
(*it)->clearLiteral(false);
(*it)->setInUpper(false);
}
prg_->ctx()->popVars(prg_->ctx()->numVars() - startVar);
litToNode_.clear();
}
VarVec& supported = prg_->getSupportedBodies(true);
if (!classifyProgram(supported)) { return false; }
res = simplifyClassifiedProgram(atoms, pass_ != maxPass_, supported);
} while (res == value_free && pass_ != maxPass_);
return res != value_false;
}
// Computes necessary equivalence-classes starting from the supported bodies
// of a program.
bool Preprocessor::classifyProgram(const VarVec& supported) {
Var bodyId; PrgBody* body;
VarVec::size_type index = 0;
follow_.clear();
if (!prg_->propagate(true)) { return false; }
for (VarVec::size_type i = 0;;) {
while ( (bodyId = nextBodyId(index)) != varMax ) {
body = addBodyVar(bodyId);
if (prg_->hasConflict()) { return false; }
if (!addHeadsToUpper(body)) { return false; }
}
follow_.clear();
index = 0;
// select next unclassified supported body
for (; i < supported.size(); ++i) {
bodyId = supported[i];
body = prg_->getBody(bodyId);
if (bodyInfo_[bodyId].bSeen == 0 && body->relevant()) {
follow_.push_back(bodyId);
break;
}
else if (!body->relevant() && body->hasVar()) {
body->clearLiteral(false);
}
}
if (follow_.empty()) break;
}
return !prg_->hasConflict();
}
ValueRep Preprocessor::simplifyClassifiedProgram(const HeadRange& atoms, bool more, VarVec& supported) {
ValueRep res = value_true, simp;
if (!prg_->propagate()) { return value_false; }
supported.clear();
// simplify supports
for (uint32 i = 0; i != prg_->numBodies(); ++i) {
PrgBody* b = prg_->getBody(i);
if (bodyInfo_[i].bSeen == 0 || !b->relevant()) {
// !bodyInfo_[i].bSeen: body is unsupported
// !b->relevant() : body is eq to other body or was derived to false
// In either case, body is no longer relevant and can be ignored.
b->clearLiteral(true);
b->markRemoved();
}
else if ( (simp = simplifyBody(b, more, supported)) != value_true ) {
if (simp == value_false) { return simp; }
res = value_free;
}
}
if (!prg_->propagate()) { return value_false; }
PrgEdge noSup = PrgEdge::noEdge();
for (LogicProgram::VarIter it = prg_->unfreeze_begin(), end = prg_->unfreeze_end(); it != end; ++it) {
PrgAtom* a = prg_->getAtom(*it);
ValueRep v = a->value();
if (!a->simplifySupports(*prg_, true)){ return value_false; }
else if (!a->inUpper() && v != value_false){
if (!prg_->assignValue(a, value_false, noSup)){ return value_false; }
if (more && a->hasDep(PrgAtom::dep_all)) { res = value_free; }
}
}
if (!prg_->propagate()) { return value_false; }
bool strong = more && res == value_true;
HeadRange heads[2] = { HeadRange(prg_->disj_begin(), prg_->disj_end()), atoms };
for (const HeadRange* range = heads, *endR = heads+2; range != endR; ++range) {
for (HeadIter it = range->first, end = range->second; it != end; ++it) {
PrgHead* head = *it;
if ((simp = simplifyHead(head, strong)) != value_true) {
if (simp == value_false){ return simp; }
else if (strong) { strong = false; res = value_free; }
}
}
}
if (!prg_->propagate()) { res = value_false; }
return res;
}
// associates a variable with the body if necessary
PrgBody* Preprocessor::addBodyVar(Var bodyId) {
// make sure we don't add an irrelevant body
PrgBody* body = prg_->getBody(bodyId);
assert((body->isSupported() && !body->eq()) || body->hasVar());
body->clearLiteral(false); // clear var in case we are iterating
bodyInfo_[bodyId].bSeen = 1; // mark as seen, so we don't classify the body again
bool known = bodyInfo_[bodyId].known == body->size();
uint32 eqId;
if (!body->simplifyBody(*prg_, known, &eqId) || !body->simplifyHeads(*prg_, false)) {
prg_->setConflict();
return body;
}
if (superfluous(body)) {
body->markRemoved();
return body;
}
if (eqId == bodyId) {
// The body is unique
body->assignVar(*prg_);
PrgAtom* aEq = body->size() == 1 ? prg_->getAtom(body->goal(0).var()) : 0;
if (!known) { body->markDirty(); }
else if (aEq && aEq->var() == body->var()){
// Body is equivalent to an atom or its negation
// Check if the atom is itself equivalent to a body.
// If so, the body is equivalent to the atom's body.
PrgBody* r = 0; // possible eq-body
uint32 rId = varMax;
if (body->goal(0).sign()) {
Var dualAtom = getRootAtom(body->literal());
aEq = dualAtom != varMax ? prg_->getAtom(dualAtom) : 0;
}
if (aEq && aEq->supports() && aEq->supps_begin()->isBody()) {
rId = aEq->supps_begin()->node();
r = prg_->getBody(rId);
if (r && r->var() == aEq->var()) {
mergeEqBodies(body, rId, false);
}
}
}
}
else {
// body is eq to eq body
mergeEqBodies(body, eqId, true);
}
return body;
}
// Adds all heads of body to the upper closure if not yet present and
// associates variables with the heads if necessary.
// The body b is the supported body that provides a support for the heads.
// RETURN: true if no conflict
// POST : the addition of atoms to the closure was propagated
bool Preprocessor::addHeadsToUpper(PrgBody* body) {
PrgHead* head;
PrgEdge support;
bool ok = !prg_->hasConflict();
int dirty= 0;
for (PrgBody::head_iterator it = body->heads_begin(), end = body->heads_end(); it != end && ok; ++it) {
head = prg_->getHead(*it);
support= PrgEdge::newEdge(*body, it->type());
if (head->relevant() && head->value() != value_false) {
if (body->value() == value_true && head->isAtom()) {
// Since b is true, it is always a valid support for head, head can never become unfounded.
// So ignore it during SCC check and unfounded set computation.
head->setIgnoreScc(true);
if (support.isNormal() && head->isAtom()) {
ok = propagateAtomValue(static_cast<PrgAtom*>(head), value_true, support);
}
}
if (!head->inUpper()) {
// first time we see this head - assign var...
ok = addHeadToUpper(head, support);
}
else if (head->supports() && head->supps_begin()->isNormal()) {
PrgEdge source = *head->supps_begin();
assert(source.isBody());
if (prg_->getBody(source.node())->var() == body->var()) {
// Check if we really need a new variable for head.
head->markDirty();
}
}
head->addSupport(support, PrgHead::no_simplify);
}
dirty += (head->eq() || head->value() == value_false);
}
if (dirty) {
// remove eq atoms from head
prg_->getBody(body->id())->markHeadsDirty();
}
return ok;
}
// Propagates that a was added to the "upper"-closure.
// If atom a has a truth-value or is eq to a', we'll remove
// it from all bodies. If there is an atom x, s.th. a.lit == ~x.lit, we mark all
// bodies containing both a and x for simplification in order to detect
// duplicates/contradictory body-literals.
// In case that a == a', we also mark all bodies containing a
// for head simplification in order to detect rules like: a' :- a,B. and a' :- B,not a.
bool Preprocessor::propagateAtomVar(PrgAtom* a, PrgEdge source) {
const Var aId = a->id();
PrgAtom* comp = 0;
ValueRep value = a->value();
bool fullEq = eq();
bool removeAtom = value == value_true || value == value_false;
bool removeNeg = removeAtom || value == value_weak_true;
Literal aLit = a->literal();
if (fullEq) {
if (getRootAtom(aLit) == varMax) {
setRootAtom(aLit, aId);
}
else if (prg_->mergeEqAtoms(a, getRootAtom(aLit))) {
assert(source.isBody());
removeAtom = true;
removeNeg = true;
value = a->value();
PrgBody* B = prg_->getBody(source.node());
a->setEqGoal(posLit(a->id()));
// set positive eq goal - replace if a == {not a'}, replace a with not a' in bodies
if (getRootAtom(~aLit) != varMax && B->literal() == aLit && B->size() == 1 && B->goal(0).sign()) {
a->setEqGoal(negLit(getRootAtom(~aLit)));
}
a->clearLiteral(true); // equivalent atoms don't need vars
}
else { return false; }
}
if (getRootAtom(~aLit) != varMax) {
PrgAtom* negA = prg_->getAtom(getRootAtom(~aLit));
assert(aLit == ~negA->literal());
// propagate any truth-value to complementary eq-class
ValueRep cv = value_free;
uint32 mark = 0;
if (value != value_free && (cv = (value_false | (value^value_true))) != negA->value()) {
mark = 1;
if (!propagateAtomValue(negA, cv, PrgEdge::noEdge())) {
return false;
}
}
if ( !removeAtom ) {
for (PrgAtom::dep_iterator it = (comp=negA)->deps_begin(); it != comp->deps_end(); ++it) {
bodyInfo_[it->var()].mBody = 1;
if (mark) { prg_->getBody(it->var())->markDirty(); }
}
}
}
for (PrgAtom::dep_iterator it = a->deps_begin(), end = a->deps_end(); it != end; ++it) {
Var bodyId = it->var();
PrgBody* bn = prg_->getBody(bodyId);
if (bn->relevant()) {
bool wasSup = bn->isSupported();
bool isSup = wasSup || (value != value_false && !it->sign() && bn->propagateSupported(aId));
bool seen = false;
bool dirty = removeAtom || (removeNeg && it->sign());
if (fullEq) {
seen = bodyInfo_[bodyId].bSeen != 0;
dirty |= bodyInfo_[bodyId].mBody == 1;
if (++bodyInfo_[bodyId].known == bn->size() && !seen && isSup) {
follow_.push_back( bodyId );
seen = true;
}
}
if (!seen && isSup && !wasSup) {
prg_->getSupportedBodies(false).push_back(bodyId);
}
if (dirty) {
bn->markDirty();
if (a->eq()) {
bn->markHeadsDirty();
}
}
}
}
if (removeAtom) { a->clearDeps(PrgAtom::dep_all); }
else if (removeNeg) { a->clearDeps(PrgAtom::dep_neg); }
if (comp) {
for (PrgAtom::dep_iterator it = comp->deps_begin(), end = comp->deps_end(); it != end; ++it) {
bodyInfo_[it->var()].mBody = 0;
}
}
return true;
}
// Propagates the assignment of val to a.
bool Preprocessor::propagateAtomValue(PrgAtom* atom, ValueRep val, PrgEdge sup) {
// No backpropagation possible because supports are not yet fully established.
return prg_->assignValue(atom, val, sup) && prg_->propagate(false);
}
bool Preprocessor::mergeEqBodies(PrgBody* body, Var rootId, bool equalLits) {
PrgBody* root = prg_->mergeEqBodies(body, rootId, equalLits, false);
if (root && root != body && bodyInfo_[root->id()].bSeen == 0) {
// If root is not yet classified, we can ignore body.
// The heads of body are added to the "upper"-closure
// once root is eventually classified.
body->clearHeads();
body->markRemoved();
}
return root != 0;
}
bool Preprocessor::hasRootLiteral(PrgBody* body) const {
return body->size() >= 1
&& getRootAtom(body->literal()) == varMax
&& getRootAtom(~body->literal())== varMax;
}
// Pre: body is simplified!
bool Preprocessor::superfluous(PrgBody* body) const {
if (!body->relevant()) { return true; }
if (!body->inRule()) {
if (body->value() == value_free) { return true; }
if (body->bound() <= 0) { return true; }
if (body->size() == 1) {
// unit constraint
ValueRep exp = body->value() ^ (int)body->goal(0).sign();
ValueRep got = prg_->getAtom(body->goal(0).var())->value();
assert(got != value_free || !prg_->options().backprop);
return got != value_free && (got&value_true) == (exp&value_true);
}
}
return false;
}
// Simplify the classified body with the given id.
// Return:
// value_false : conflict
// value_true : ok
// value_weak_true: ok but program should be reclassified
ValueRep Preprocessor::simplifyBody(PrgBody* b, bool reclass, VarVec& supported) {
assert(b->relevant() && bodyInfo_[b->id()].bSeen == 1);
bodyInfo_[b->id()].bSeen = 0;
bodyInfo_[b->id()].known = 0;
bool hadHeads = b->hasHeads();
bool hasRoot = hasRootLiteral(b);
uint32 eqId = b->id();
if (!b->simplify(*prg_, true, &eqId)) {
return value_false;
}
ValueRep ret = value_true;
if (reclass) {
if (hadHeads && b->value() == value_false) {
assert(b->hasHeads() == false);
// New false body. If it was derived to false, we can ignore the body.
// Otherwise, we have a new integrity constraint.
if (!b->relevant()) {
b->clearLiteral(true);
}
}
else if (b->var() != 0 && superfluous(b)) {
// Body is no longer needed. All heads are either superfluous or equivalent
// to other atoms.
// Reclassify only if var is not used
if (getRootAtom(b->literal()) == varMax) { ret = value_weak_true; }
b->clearLiteral(true);
b->markRemoved();
}
else if (b->value() == value_true && b->var() != 0) {
// New fact body
for (PrgBody::head_iterator it = b->heads_begin(), end = b->heads_end(); it != end; ++it) {
if (it->isNormal() && prg_->getHead(*it)->var() != 0) {
ret = value_weak_true;
break;
}
}
b->markDirty();
}
}
if (b->relevant() && eqId != b->id() && (reclass || prg_->getBody(eqId)->var() == b->var())) {
// Body is now eq to some other body - reclassify if body var is not needed
Var bVar = b->var();
prg_->mergeEqBodies(b, eqId, true, true);
if (hasRoot && bVar != b->var()) {
ret = value_weak_true;
}
}
if (b->relevant() && b->resetSupported()) {
supported.push_back(b->id());
}
return ret;
}
// Simplify the classified head h.
// Update list of bodies defining this head and check
// if atom or disjunction has a distinct var although it is eq to some body.
// Return:
// value_false : conflict
// value_true : ok
// value_weak_true: ok but atom should be reclassified
ValueRep Preprocessor::simplifyHead(PrgHead* h, bool more) {
if (!h->hasVar() || !h->relevant()) {
// unsupported or eq
h->clearLiteral(false);
h->markRemoved();
h->clearSupports();
h->setInUpper(false);
return value_true;
}
assert(h->inUpper());
ValueRep v = h->value();
ValueRep ret = value_true;
PrgEdge support = h->supports() ? *h->supps_begin() : PrgEdge::noEdge();
uint32 numSuppLits= 0;
if (!h->simplifySupports(*prg_, true, &numSuppLits)) {
return value_false;
}
if (v != h->value() && (h->value() == value_false || (h->value() == value_true && h->var() != 0))) {
ret = value_weak_true;
}
if (more) {
if (numSuppLits == 0 && h->hasVar()) {
// unsupported head does not need a variable
ret = value_weak_true;
}
else if (h->supports() > 0 && h->supps_begin()->rep != support.rep) {
// support for head has changed
ret = value_weak_true;
}
else if ((support.isNormal() && h->supports() == 1) || (h->supports() > 1 && numSuppLits == 1 && h->isAtom())) {
assert(support.isBody());
PrgBody* supBody = prg_->getBody(support.node());
if (supBody->literal() != h->literal()) {
if (h->supports() > 1) {
// atom is equivalent to one of its bodies
EdgeVec temp(h->supps_begin(), h->supps_end());
h->clearSupports();
support = temp[0];
for (EdgeIterator it = temp.begin(), end = temp.end(); it != end; ++it) {
assert(!it->isDisj());
PrgBody* B = prg_->getBody(it->node());
if (it->isNormal() && B->size() == 1 && B->goal(0).sign()) {
support = *it;
}
B->removeHead(h, it->type());
}
supBody = prg_->getBody(support.node());
supBody->addHead(h, support.type());
if (!supBody->simplifyHeads(*prg_, true)) {
return value_false;
}
}
ret = value_weak_true;
if (h->value() == value_weak_true || h->value() == value_true) {
supBody->assignValue(h->value());
supBody->propagateValue(*prg_, true);
}
}
}
}
return ret;
}
} }
| 36.282569 | 114 | 0.620815 | timn |
646739078156c1cd1990b15d2950cd2a561dcfce | 321 | cpp | C++ | Codeforces/599A - Patrick and Shopping.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/599A - Patrick and Shopping.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/599A - Patrick and Shopping.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("files/input.txt", "r", stdin);
#endif
int d1, d2, d3;
cin >> d1 >> d2 >> d3;
cout << min(d1, d2) + min (d3, d1 + d2) + min( max(d1, d2), d3 + min(d1, d2) );
return 0;
}
| 21.4 | 83 | 0.548287 | naimulcsx |
6469c6f49af59f911378a6788fd472a125502f08 | 2,457 | cpp | C++ | src/engine/instance/instance.cpp | kurbaniec/PuzzleGame | 5fdf67d14ee635f8c74f82a6b2af4ed354b6e5fe | [
"MIT"
] | null | null | null | src/engine/instance/instance.cpp | kurbaniec/PuzzleGame | 5fdf67d14ee635f8c74f82a6b2af4ed354b6e5fe | [
"MIT"
] | null | null | null | src/engine/instance/instance.cpp | kurbaniec/PuzzleGame | 5fdf67d14ee635f8c74f82a6b2af4ed354b6e5fe | [
"MIT"
] | null | null | null | //
// Created by kurbaniec on 22.12.2021.
//
#include "instance.h"
#include <utility>
#include "glm/ext/matrix_transform.hpp"
namespace engine {
Instance::Instance(
std::string id,
glm::vec3 position,
glm::vec3 rotation,
glm::vec3 scale,
glm::vec3 origin,
glm::vec3 boundsMin,
glm::vec3 boundsMax,
std::set<std::string> tags,
bool enabled,
glm::vec3 localForward,
glm::vec3 localUp,
glm::vec3 localRight
) : id(std::move(id)), position(position), rotation(rotation), scale(scale), origin(origin),
localForward(glm::vec4(localForward, 1.0f)), forward(glm::vec3{}),
localUp(glm::vec4(localUp, 1.0f)), up(glm::vec3{}),
localRight(glm::vec4(localRight, 1.0f)), right(glm::vec3{}),
enabled(enabled), modelMatrix(glm::mat4(1.0f)),
boundsVal(Bounds(boundsMin, boundsMax)), tags(std::move(tags)) {
}
void Instance::updateModelMatrix() {
// Build unique transformation for model
// See: https://learnopengl.com/Getting-started/
auto& modelMtx = const_cast<glm::mat4&>(modelMatrix);
modelMtx = glm::mat4(1.0f);
auto rotationMtx = glm::mat4(1.0f);
// Transformations must be in reversed order!
modelMtx = glm::translate(modelMtx, position);
modelMtx = glm::translate(modelMtx, -origin);
rotationMtx = glm::rotate(rotationMtx, glm::radians(rotation.x), glm::vec3(0.1, 0.0, 0.0));
rotationMtx = glm::rotate(rotationMtx, glm::radians(rotation.y), glm::vec3(0.0, 1.0, 0.0));
rotationMtx = glm::rotate(rotationMtx, glm::radians(rotation.z), glm::vec3(0.0, 0.0, 1.0));
modelMtx = modelMatrix * rotationMtx;
modelMtx = glm::scale(modelMtx, scale);
modelMtx = glm::translate(modelMtx, origin);
// Update forward/up/right vectors
auto& f = const_cast<glm::vec3&>(forward);
f = rotationMtx * localForward;
auto& u = const_cast<glm::vec3&>(up);
u = rotationMtx * localUp;
auto& r = const_cast<glm::vec3&>(right);
r = rotationMtx * localRight;
// Update bounds
boundsVal.updateWorldBounds(modelMtx);
}
const Bounds& Instance::bounds() {
return boundsVal;
}
bool Instance::intersectsAabb(const std::shared_ptr<Instance>& other) const {
return boundsVal.aabb().intersects(other->boundsVal.aabb());
}
}
| 36.132353 | 99 | 0.612943 | kurbaniec |
646c2050050703ec4c4ecffd08b9900adb6274ee | 9,253 | cpp | C++ | Eagle/src/Eagle/Physics/PhysicsScene.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 1 | 2021-12-10T19:15:25.000Z | 2021-12-10T19:15:25.000Z | Eagle/src/Eagle/Physics/PhysicsScene.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 41 | 2021-08-18T21:32:14.000Z | 2022-02-20T11:44:06.000Z | Eagle/src/Eagle/Physics/PhysicsScene.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | null | null | null | #include "egpch.h"
#include "PhysicsScene.h"
#include "PhysicsEngine.h"
#include "PhysicsSettings.h"
#include "PhysXDebugger.h"
#include "PhysXInternal.h"
#include "ContactListener.h"
#include "Eagle/Core/Project.h"
namespace Eagle
{
static ContactListener s_ContactListener;
PhysicsScene::PhysicsScene(const PhysicsSettings& settings)
: m_Settings(settings)
, m_SubstepSize(settings.FixedTimeStep)
{
physx::PxSceneDesc sceneDesc(PhysXInternal::GetPhysics().getTolerancesScale());
sceneDesc.dynamicTreeRebuildRateHint *= 5;
sceneDesc.flags |= physx::PxSceneFlag::eENABLE_CCD | physx::PxSceneFlag::eENABLE_PCM;
sceneDesc.flags |= physx::PxSceneFlag::eENABLE_ENHANCED_DETERMINISM;
sceneDesc.flags |= physx::PxSceneFlag::eENABLE_ACTIVE_ACTORS;
sceneDesc.gravity = PhysXUtils::ToPhysXVector(settings.Gravity);
sceneDesc.broadPhaseType = PhysXUtils::ToPhysXBroadphaseType(settings.BroadphaseAlgorithm);
sceneDesc.cpuDispatcher = PhysXInternal::GetCPUDispatcher();
sceneDesc.filterShader = m_Settings.EditorScene ? (physx::PxSimulationFilterShader)PhysXInternal::EditorFilterShader :(physx::PxSimulationFilterShader)PhysXInternal::FilterShader;
sceneDesc.simulationEventCallback = &s_ContactListener;
sceneDesc.frictionType = PhysXUtils::ToPhysXFrictionType(settings.FrictionModel);
EG_CORE_ASSERT(sceneDesc.isValid(), "Invalid scene desc");
m_Scene = PhysXInternal::GetPhysics().createScene(sceneDesc);
EG_CORE_ASSERT(m_Scene, "Invalid scene");
m_Scene->setVisualizationParameter(physx::PxVisualizationParameter::eSCALE, 1.f);
m_Scene->setVisualizationParameter(physx::PxVisualizationParameter::eCOLLISION_SHAPES, 2.f);
CreateRegions();
#ifdef EG_DEBUG
if (settings.DebugOnPlay && !PhysXDebugger::IsDebugging())
PhysXDebugger::StartDebugging(Project::GetSavedPath() / "PhysXDebugInfo", settings.DebugType == DebugType::Live);
#endif
}
void PhysicsScene::ConstructFromScene(Scene* scene)
{
for (auto& it : scene->GetAliveEntities())
{
Entity& entity = it.second;
CreatePhysicsActor(entity);
}
}
void PhysicsScene::Simulate(Timestep ts, bool bFixedUpdate)
{
if (bFixedUpdate)
{
for (auto& actor : m_Actors)
actor.second->OnFixedUpdate(ts);
}
bool bAdvanced = Advance(ts);
if (bAdvanced)
{
uint32_t nActiveActors;
physx::PxActor** activeActors = m_Scene->getActiveActors(nActiveActors);
for (uint32_t i = 0; i < nActiveActors; ++i)
{
PhysicsActor* activeActor = (PhysicsActor*)activeActors[i]->userData;
activeActor->SynchronizeTransform();
}
}
}
Ref<PhysicsActor>& PhysicsScene::GetPhysicsActor(const Entity& entity)
{
Ref<PhysicsActor> s_InvalidPhysicsActor = nullptr;
auto it = m_Actors.find(entity.GetGUID());
return it != m_Actors.end() ? it->second : s_InvalidPhysicsActor;
}
const Ref<PhysicsActor>& PhysicsScene::GetPhysicsActor(const Entity& entity) const
{
static Ref<PhysicsActor> s_InvalidPhysicsActor = nullptr;
auto it = m_Actors.find(entity.GetGUID());
return it != m_Actors.end() ? it->second : s_InvalidPhysicsActor;
}
Ref<PhysicsActor> PhysicsScene::CreatePhysicsActor(Entity& entity)
{
static const Ref<PhysicsActor> s_InvalidActor;
const bool bHasRigidBody = entity.HasComponent<RigidBodyComponent>();
const bool bHasAnyCollider = entity.HasAny<BoxColliderComponent, SphereColliderComponent, CapsuleColliderComponent, MeshColliderComponent>();
if (!bHasAnyCollider && !bHasRigidBody)
return s_InvalidActor;
if (!bHasRigidBody)
entity.AddComponent<RigidBodyComponent>();
Ref<PhysicsActor> actor = MakeRef<PhysicsActor>(entity, m_Settings);
m_Actors[entity.GetGUID()] = actor;
m_Scene->addActor(*actor->m_RigidActor);
actor->SetSimulationData();
return actor;
}
void PhysicsScene::RemovePhysicsActor(const Ref<PhysicsActor>& physicsActor)
{
if (!physicsActor)
return;
physicsActor->RemoveAllColliders();
m_Scene->removeActor(*physicsActor->m_RigidActor);
physicsActor->m_RigidActor->release();
physicsActor->m_RigidActor = nullptr;
m_Actors.erase(physicsActor->GetEntity().GetGUID());
}
bool PhysicsScene::Raycast(const glm::vec3& origin, const glm::vec3& dir, float maxDistance, RaycastHit* outHit)
{
physx::PxRaycastBuffer hitInfo;
bool bResult = m_Scene->raycast(PhysXUtils::ToPhysXVector(origin), PhysXUtils::ToPhysXVector(dir), maxDistance, hitInfo);
if (bResult)
{
PhysicsActor* actor = (PhysicsActor*)hitInfo.block.actor->userData;
outHit->HitEntity = actor->GetEntity().GetGUID();
outHit->Position = PhysXUtils::FromPhysXVector(hitInfo.block.position);
outHit->Normal = PhysXUtils::FromPhysXVector(hitInfo.block.normal);
outHit->Distance = hitInfo.block.distance;
}
return bResult;
}
bool PhysicsScene::OverlapBox(const glm::vec3& origin, const glm::vec3& halfSize, std::array<physx::PxOverlapHit, OVERLAP_MAX_COLLIDERS>& buffer, uint32_t& count)
{
return OverlapGeometry(origin, physx::PxBoxGeometry(halfSize.x, halfSize.y, halfSize.z), buffer, count);
}
bool PhysicsScene::OverlapCapsule(const glm::vec3& origin, float radius, float halfHeight, std::array<physx::PxOverlapHit, OVERLAP_MAX_COLLIDERS>& buffer, uint32_t& count)
{
return OverlapGeometry(origin, physx::PxCapsuleGeometry(radius, halfHeight), buffer, count);
}
bool PhysicsScene::OverlapSphere(const glm::vec3& origin, float radius, std::array<physx::PxOverlapHit, OVERLAP_MAX_COLLIDERS>& buffer, uint32_t& count)
{
return OverlapGeometry(origin, physx::PxSphereGeometry(radius), buffer, count);
}
void PhysicsScene::CreateRegions()
{
const PhysicsSettings& settings = m_Settings;
if (settings.BroadphaseAlgorithm == BroadphaseType::AutomaticBoxPrune)
return;
physx::PxBounds3* regionBounds = new physx::PxBounds3[(uint64_t)settings.WorldBoundsSubdivisions * settings.WorldBoundsSubdivisions];
physx::PxBounds3 globalBounds(PhysXUtils::ToPhysXVector(settings.WorldBoundsMin), PhysXUtils::ToPhysXVector(settings.WorldBoundsMax));
uint32_t regionCount = physx::PxBroadPhaseExt::createRegionsFromWorldBounds(regionBounds, globalBounds, settings.WorldBoundsSubdivisions);
for (uint32_t i = 0; i < regionCount; ++i)
{
physx::PxBroadPhaseRegion region;
region.bounds = regionBounds[i];
m_Scene->addBroadPhaseRegion(region);
}
}
bool PhysicsScene::Advance(Timestep ts)
{
SubstepStrategy(ts);
for (uint32_t i = 0; i < m_NumSubsteps; ++i)
{
m_Scene->simulate(m_SubstepSize);
m_Scene->fetchResults(true);
}
return m_NumSubsteps != 0;
}
void PhysicsScene::SubstepStrategy(Timestep ts)
{
if (m_Accumulator > m_SubstepSize)
m_Accumulator = 0.f;
m_Accumulator += ts;
if (m_Accumulator < m_SubstepSize)
{
m_NumSubsteps = 0;
return;
}
m_NumSubsteps = glm::min((uint32_t)(m_Accumulator / m_SubstepSize), c_MaxSubsteps);
m_Accumulator -= m_NumSubsteps * m_SubstepSize;
}
void PhysicsScene::Clear()
{
if (m_Scene)
{
while (m_Actors.size())
RemovePhysicsActor(m_Actors.begin()->second);
m_Actors.clear(); //Just in case
}
}
void PhysicsScene::Reset()
{
Clear();
m_Accumulator = 0.f;
m_NumSubsteps = 0;
}
void PhysicsScene::Destroy()
{
if (m_Scene)
{
#ifdef EG_DEBUG
if (m_Settings.DebugOnPlay && PhysXDebugger::IsDebugging())
PhysXDebugger::StopDebugging();
#endif
while(m_Actors.size())
RemovePhysicsActor(m_Actors.begin()->second);
m_Actors.clear(); //Just in case
m_Scene->release();
m_Scene = nullptr;
}
}
bool PhysicsScene::OverlapGeometry(const glm::vec3& origin, const physx::PxGeometry& geometry, std::array<physx::PxOverlapHit, OVERLAP_MAX_COLLIDERS>& buffer, uint32_t& count)
{
physx::PxOverlapBuffer buf(buffer.data(), OVERLAP_MAX_COLLIDERS);
physx::PxTransform pose = PhysXUtils::ToPhysXTranform(glm::translate(glm::mat4(1.f), origin));
bool bResult = m_Scene->overlap(geometry, pose, buf);
if (bResult)
{
memcpy(buffer.data(), buf.touches, buf.nbTouches * sizeof(physx::PxOverlapHit));
count = buf.nbTouches;
}
return bResult;
}
}
| 36.718254 | 187 | 0.649627 | IceLuna |
646d31a349f948b7f96fd2e134030632fd5fe49c | 10,750 | cpp | C++ | Source/ModuleRender.cpp | AlbertVVila/Engine | adbd5e7b7afc28f230006d1b61f00aa85fa559c4 | [
"MIT"
] | 4 | 2019-02-08T23:08:36.000Z | 2019-11-09T21:25:15.000Z | Source/ModuleRender.cpp | AlbertVVila/Engine | adbd5e7b7afc28f230006d1b61f00aa85fa559c4 | [
"MIT"
] | 2 | 2019-02-05T13:49:47.000Z | 2019-05-27T16:25:46.000Z | Source/ModuleRender.cpp | AlbertVVila/Engine | adbd5e7b7afc28f230006d1b61f00aa85fa559c4 | [
"MIT"
] | 2 | 2019-01-16T21:21:20.000Z | 2019-01-27T22:54:33.000Z | #include "Application.h"
#include "ModuleRender.h"
#include "ModuleCamera.h"
#include "ModuleScene.h"
#include "ModuleProgram.h"
#include "ModuleEditor.h"
#include "ModuleWindow.h"
#include "ModuleResourceManager.h"
#include "GameObject.h"
#include "ComponentCamera.h"
#include "Skybox.h"
#include "Viewport.h"
#include "JSON.h"
#include "SDL.h"
#include "GL/glew.h"
#include "imgui.h"
#include "Math/MathFunc.h"
#include "Math/float4x4.h"
#include "Brofiler.h"
ModuleRender::ModuleRender()
{
}
// Destructor
ModuleRender::~ModuleRender()
{
RELEASE(skybox);
RELEASE(viewScene);
RELEASE(viewGame);
}
// Called before render is available
bool ModuleRender::Init(JSON * config)
{
LOG("Creating Renderer context");
InitSDL();
glewInit();
InitOpenGL();
SDL_GL_SetSwapInterval((int)vsync);
skybox = new Skybox();
viewScene = new Viewport("Scene");
viewGame = new Viewport("Game");
JSON_value* renderer = config->GetValue("renderer");
if (renderer == nullptr) return true;
msaa = renderer->GetInt("msaa");
msaa_level = renderer->GetInt("msaa_level");
picker_debug = renderer->GetInt("picker_debug");
light_debug = renderer->GetInt("light_debug");
quadtree_debug = renderer->GetInt("quadtree_debug");
grid_debug = renderer->GetInt("grid_debug");
depthTest = renderer->GetInt("depthTest");
wireframe = renderer->GetInt("wireframe");
vsync = renderer->GetInt("vsync");
useMainCameraFrustum = renderer->GetInt("frustumMainCamera");
skybox->enabled = renderer->GetInt("skybox");
current_scale = renderer->GetInt("current_scale");
switch (current_scale)
{
case 1:
item_current = 0;
break;
case 10:
item_current = 1;
break;
case 100:
item_current = 2;
break;
}
return true;
}
bool ModuleRender::Start()
{
GenBlockUniforms();
return true;
}
update_status ModuleRender::PreUpdate()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return UPDATE_CONTINUE;
}
// Called every draw update
update_status ModuleRender::Update(float dt)
{
return UPDATE_CONTINUE;
}
update_status ModuleRender::PostUpdate()
{
BROFILER_CATEGORY("Render PostUpdate", Profiler::Color::Black);
viewScene->Draw(App->camera->editorcamera, true);
viewGame->Draw(App->scene->maincamera);
App->editor->RenderGUI();
SDL_GL_SwapWindow(App->window->window);
return UPDATE_CONTINUE;
}
void ModuleRender::SaveConfig(JSON * config)
{
JSON_value* renderer = config->CreateValue();
renderer->AddInt("msaa", msaa);
renderer->AddInt("msaa_level", msaa_level);
renderer->AddInt("picker_debug", picker_debug);
renderer->AddInt("light_debug", light_debug);
renderer->AddInt("quadtree_debug", light_debug);
renderer->AddInt("grid_debug", grid_debug);
renderer->AddInt("current_scale", current_scale);
renderer->AddInt("depthTest", depthTest);
renderer->AddInt("wireframe", wireframe);
renderer->AddInt("vsync", vsync);
renderer->AddInt("frustumMainCamera", useMainCameraFrustum);
renderer->AddInt("skybox", skybox->enabled);
config->AddValue("renderer", *renderer);
}
void ModuleRender::Draw(const ComponentCamera& cam, int width, int height, bool isEditor) const
{
PROFILE;
glViewport(0, 0, width, height);
glClearColor(0.3f, 0.3f, 0.3f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (wireframe)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
SetProjectionUniform(cam);
SetViewUniform(cam);
skybox->Draw(*cam.frustum);
if (isEditor)
{
DrawGizmos();
}
App->scene->Draw(*cam.frustum, isEditor);
}
bool ModuleRender::IsSceneViewFocused() const
{
return viewScene->focus;
}
bool ModuleRender::IsSceneHovered() const
{
return viewScene->hover;
}
// Called before quitting
bool ModuleRender::CleanUp()
{
LOG("Destroying renderer");
if (UBO != 0)
{
glDeleteBuffers(1, &UBO);
}
return true;
}
void ModuleRender::OnResize()
{
glViewport(0, 0, App->window->width, App->window->height);
App->camera->editorcamera->SetAspect((float)App->window->width / (float)App->window->height);
}
void ModuleRender::DrawGizmos() const
{
PROFILE;
unsigned shader = App->program->defaultShader->id;
glUseProgram(shader);
if (picker_debug)
{
for (const auto & line : App->scene->debuglines)
{
math::float4x4 model = math::float4x4::identity;
glUniformMatrix4fv(glGetUniformLocation(shader,
"model"), 1, GL_TRUE, &model[0][0]);
glLineWidth(3.0f);
glBegin(GL_LINES);
glVertex3f(line.a.x, line.a.y, line.a.z);
glVertex3f(line.b.x, line.b.y, line.b.z);
glEnd();
}
}
math::float4x4 model = math::float4x4::identity;
glUniformMatrix4fv(glGetUniformLocation(shader,
"model"), 1, GL_TRUE, &model[0][0]);
if (grid_debug)
{
DrawGrid();
}
DrawAxis();
if (App->scene->maincamera != nullptr && App->renderer->useMainCameraFrustum)
{
App->scene->maincamera->DrawFrustum(shader);
}
glUseProgram(0);
}
void ModuleRender::DrawGrid() const
{
float white[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
glUniform4fv(glGetUniformLocation(App->program->defaultShader->id,
"Vcolor"), 1, white);
glLineWidth(1.0f);
float d = 200.0f*current_scale;
glBegin(GL_LINES);
float distance = MAX(1, current_scale);
for (float i = -d; i <= d; i += distance)
{
glVertex3f(i, 0.0f, -d);
glVertex3f(i, 0.0f, d);
glVertex3f(-d, 0.0f, i);
glVertex3f(d, 0.0f, i);
}
glEnd();
}
void ModuleRender::DrawAxis() const //TODO: use debug draw
{
unsigned shader = App->program->defaultShader->id;
glLineWidth(2.0f);
float red[4] = { 1.0f, 0.0f, 0.0f, 1.0f };
glUniform4fv(glGetUniformLocation(shader,
"Vcolor"), 1, red);
glBegin(GL_LINES);
// red X
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(current_scale, 0.0f, 0.0f);
glVertex3f(current_scale, current_scale*0.1f, 0.0f);
glVertex3f(current_scale*1.1f, -0.1f*current_scale, 0.0f);
glVertex3f(current_scale*1.1f, current_scale*0.1f, 0.0f);
glVertex3f(current_scale, current_scale *-0.1f, 0.0f);
glEnd();
float green[4] = { 0.0f, 1.0f, 0.0f, 1.0f };
glUniform4fv(glGetUniformLocation(shader,
"Vcolor"), 1, green);
glBegin(GL_LINES);
// green Y
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, current_scale, 0.0f);
glVertex3f(-0.05f*current_scale, current_scale*1.25f, 0.0f);
glVertex3f(0.0f, current_scale*1.15f, 0.0f);
glVertex3f(current_scale*0.05f, current_scale*1.25f, 0.0f);
glVertex3f(0.0f, current_scale*1.15f, 0.0f);
glVertex3f(0.0f, current_scale*1.15f, 0.0f);
glVertex3f(0.0f, current_scale*1.05f, 0.0f);
glEnd();
float blue[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
glUniform4fv(glGetUniformLocation(shader,
"Vcolor"), 1, blue);
glBegin(GL_LINES);
// blue Z
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, current_scale);
glVertex3f(-0.05f*current_scale, current_scale*0.1f, current_scale*1.05f);
glVertex3f(current_scale*0.05f, current_scale*0.1f, current_scale*1.05f);
glVertex3f(current_scale*0.05f, current_scale*0.1f, current_scale*1.05f);
glVertex3f(current_scale *-0.05f, current_scale*-0.1f, current_scale*1.05f);
glVertex3f(current_scale *-0.05f, current_scale *-0.1f, current_scale*1.05f);
glVertex3f(current_scale *0.05f, current_scale *-0.1f, current_scale *1.05f);
glEnd();
glLineWidth(1.0f);
}
void ModuleRender::InitSDL()
{
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
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);
context = SDL_GL_CreateContext(App->window->window);
SDL_GetWindowSize(App->window->window, &App->window->width, &App->window->height);
}
void ModuleRender::InitOpenGL() const
{
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glEnable(GL_TEXTURE_2D);
glEnable(GL_MULTISAMPLE);
glClearDepth(1.0f);
glClearColor(0.3f, 0.3f, 0.3f, 1.f);
glViewport(0, 0, App->window->width, App->window->height);
}
void ModuleRender::DrawGUI()
{
if (ImGui::Checkbox("Depth Test", &depthTest))
{
if (App->renderer->depthTest)
{
glEnable(GL_DEPTH_TEST);
}
else
{
glDisable(GL_DEPTH_TEST);
}
}
ImGui::Checkbox("Wireframe", &wireframe);
if (ImGui::Checkbox("Vsync", &vsync))
{
SDL_GL_SetSwapInterval((int)vsync);
}
ImGui::Checkbox("Game Frustum", &useMainCameraFrustum);
ImGui::Checkbox("Skybox", &skybox->enabled);
ImGui::Checkbox("MSAA", &msaa);
if (msaa)
{
int previous_msaa_level = msaa_level;
ImGui::RadioButton("x2", &msaa_level, 2); ImGui::SameLine();
ImGui::RadioButton("x4", &msaa_level, 4); ImGui::SameLine();
ImGui::RadioButton("x8", &msaa_level, 8);
if (previous_msaa_level != msaa_level)
{
msaa_lvl_changed = true;
}
}
ImGui::Checkbox("Picker Debug", &picker_debug);
ImGui::Checkbox("Light Debug", &light_debug);
ImGui::Checkbox("QuadTree Debug", &quadtree_debug);
ImGui::Checkbox("Grid Debug", &grid_debug);
const char* scales[] = {"1", "10", "100"};
ImGui::Combo("Scale", &item_current, scales, 3);
unsigned new_scale = atoi(scales[item_current]);
if (new_scale != current_scale)
{
current_scale = new_scale;
std::vector<Component*> cameras = App->scene->root->GetComponentsInChildren(ComponentType::Camera);
for (auto &cam : cameras)
{
((ComponentCamera*)cam)->frustum->nearPlaneDistance = ZNEARDIST * current_scale;
((ComponentCamera*)cam)->frustum->farPlaneDistance = ZFARDIST * current_scale;
}
App->camera->editorcamera->frustum->nearPlaneDistance = ZNEARDIST * current_scale;
App->camera->editorcamera->frustum->farPlaneDistance = ZFARDIST * current_scale;
}
}
void ModuleRender::GenBlockUniforms()
{
glGenBuffers(1, &UBO); //Block uniform creation
glBindBuffer(GL_UNIFORM_BUFFER, UBO);
glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(float4x4), NULL, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glBindBufferRange(GL_UNIFORM_BUFFER, 0, UBO, 0, 2 * sizeof(float4x4));
}
void ModuleRender::AddBlockUniforms(const Shader &shader) const
{
unsigned int uniformBlockIndex = glGetUniformBlockIndex(shader.id, "Matrices");
glUniformBlockBinding(shader.id, uniformBlockIndex, 0);
}
void ModuleRender::SetViewUniform(const ComponentCamera &camera) const
{
glBindBuffer(GL_UNIFORM_BUFFER, UBO);
glBufferSubData(GL_UNIFORM_BUFFER, sizeof(float4x4), sizeof(float4x4), &camera.GetViewMatrix()[0][0]);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void ModuleRender::SetProjectionUniform(const ComponentCamera &camera) const
{
glBindBuffer(GL_UNIFORM_BUFFER, UBO);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(float4x4), &camera.GetProjectionMatrix()[0][0]);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
| 25.717703 | 103 | 0.722419 | AlbertVVila |
646f56500abecade2fdcf7dde0c19da7a2d87851 | 3,992 | hpp | C++ | include/scoped/plot.hpp | gotocoffee1/guinea | 2aa4ca1584695d52daa10846517de83d52bba2a8 | [
"MIT"
] | null | null | null | include/scoped/plot.hpp | gotocoffee1/guinea | 2aa4ca1584695d52daa10846517de83d52bba2a8 | [
"MIT"
] | null | null | null | include/scoped/plot.hpp | gotocoffee1/guinea | 2aa4ca1584695d52daa10846517de83d52bba2a8 | [
"MIT"
] | null | null | null | #pragma once
#ifndef _PLOT_SCOPED_HPP_
#define _PLOT_SCOPED_HPP_
#include "implot.h"
namespace scoped
{
namespace ui
{
namespace plot
{
#define DELETE_MOVE_COPY(Base) \
Base(Base&&) = delete; /* Move not allowed */ \
Base& operator=(Base&&) = delete; /* "" */ \
Base(const Base&) = delete; /* Copy not allowed */ \
Base& operator=(const Base&) = delete /* "" */
struct Plot
{
bool IsOpen;
Plot(const char* title_id,
const char* x_label = NULL,
const char* y_label = NULL,
const ImVec2& size = ImVec2(-1, 0),
ImPlotFlags flags = ImPlotFlags_None,
ImPlotAxisFlags x_flags = ImPlotAxisFlags_None,
ImPlotAxisFlags y_flags = ImPlotAxisFlags_None,
ImPlotAxisFlags y2_flags = ImPlotAxisFlags_NoGridLines,
ImPlotAxisFlags y3_flags = ImPlotAxisFlags_NoGridLines)
{
IsOpen = ImPlot::BeginPlot(title_id,
x_label,
y_label,
size,
flags,
x_flags,
y_flags,
y2_flags,
y3_flags);
}
~Plot()
{
if (IsOpen)
ImPlot::EndPlot();
}
explicit operator bool() const
{
return IsOpen;
}
DELETE_MOVE_COPY(Plot);
};
struct DragDropTarget
{
bool IsOpen;
DragDropTarget()
{
IsOpen = ImPlot::BeginDragDropTarget();
}
~DragDropTarget()
{
if (IsOpen)
ImPlot::EndDragDropTarget();
}
explicit operator bool() const
{
return IsOpen;
}
DELETE_MOVE_COPY(DragDropTarget);
};
struct DragDropSource
{
bool IsOpen;
DragDropSource(ImGuiKeyModFlags key_mods = ImGuiKeyModFlags_Ctrl, ImGuiDragDropFlags flags = 0)
{
IsOpen = ImPlot::BeginDragDropSource(key_mods, flags);
}
~DragDropSource()
{
if (IsOpen)
ImPlot::EndDragDropSource();
}
explicit operator bool() const
{
return IsOpen;
}
DELETE_MOVE_COPY(DragDropSource);
};
struct LegendPopup
{
bool IsOpen;
LegendPopup(const char* label_id, ImGuiMouseButton mouse_button = 1)
{
IsOpen = ImPlot::BeginLegendPopup(label_id, mouse_button);
}
~LegendPopup()
{
if (IsOpen)
ImPlot::EndLegendPopup();
}
explicit operator bool() const
{
return IsOpen;
}
DELETE_MOVE_COPY(LegendPopup);
};
struct StyleVar
{
StyleVar(ImPlotStyleVar idx, float val)
{
ImPlot::PushStyleVar(idx, val);
}
StyleVar(ImPlotStyleVar idx, int val)
{
ImPlot::PushStyleVar(idx, val);
}
StyleVar(ImPlotStyleVar idx, const ImVec2& val)
{
ImPlot::PushStyleVar(idx, val);
}
~StyleVar()
{
ImPlot::PopStyleVar();
}
DELETE_MOVE_COPY(StyleVar);
};
struct StyleColor
{
StyleColor(ImPlotCol idx, ImU32 col)
{
ImPlot::PushStyleColor(idx, col);
}
StyleColor(ImPlotCol idx, const ImVec4& col)
{
ImPlot::PushStyleColor(idx, col);
}
~StyleColor()
{
ImPlot::PopStyleColor();
}
DELETE_MOVE_COPY(StyleColor);
};
struct PlotClipRect
{
PlotClipRect()
{
ImPlot::PushPlotClipRect();
}
~PlotClipRect()
{
ImPlot::PopPlotClipRect();
}
DELETE_MOVE_COPY(PlotClipRect);
};
struct Colormap
{
Colormap(ImPlotColormap colormap)
{
ImPlot::PushColormap(colormap);
}
Colormap(const char* name)
{
ImPlot::PushColormap(name);
}
~Colormap()
{
ImPlot::PopColormap();
}
DELETE_MOVE_COPY(Colormap);
};
#undef DELETE_MOVE_COPY
} // namespace plot
} // namespace ui
} // namespace scoped
#endif
| 19.762376 | 99 | 0.547846 | gotocoffee1 |
646fbc8aed3cd1d0d0d82b40da25d41195784a39 | 28,527 | hpp | C++ | table.hpp | hmito/hmLib | 0f2515ba9c99c06d02e2fa633eeae73bcd793983 | [
"MIT"
] | null | null | null | table.hpp | hmito/hmLib | 0f2515ba9c99c06d02e2fa633eeae73bcd793983 | [
"MIT"
] | null | null | null | table.hpp | hmito/hmLib | 0f2515ba9c99c06d02e2fa633eeae73bcd793983 | [
"MIT"
] | 1 | 2015-09-22T03:32:11.000Z | 2015-09-22T03:32:11.000Z | #ifndef HMLIB_TABLE_INC
#define HMLIB_TABLE_INC 100
#
#include<string>
#include<vector>
#include<algorithm>
#include<limits>
#include<boost/lexical_cast.hpp>
#include<boost/iterator_adaptors.hpp>
#include"exceptions.hpp"
namespace hmLib{
namespace{
struct basic_table_identifier{};
}
using table_exception=exceptions::exception_pattern<basic_table_identifier>;
template<class Elem = char, class Traits = std::char_traits<Elem> >
class basic_table{
private:
using my_type = basic_table < Elem, Traits >;
public:
using size_type = unsigned int;
using diff_type = int;
using size_pair_type = std::pair<size_type,size_type>;
using string_type = std::basic_string < Elem, Traits >;
using column_type = std::vector < string_type >;
using data_type = std::pair < string_type, column_type >;
private:
std::vector<data_type> Data;
public://element proxy
struct element_proxy{
friend struct const_element_proxy;
private:
string_type& Str;
public:
element_proxy(string_type& Ref):Str(Ref){}
operator string_type&(){ return Str; }
operator const string_type&()const{ return Str; }
string_type& ref(){ return Str; }
const string_type& cref()const{ return Str; }
bool empty()const{ return cref().empty(); }
element_proxy& operator=(const string_type& Str_){
Str = Str_;
return *this;
}
template<typename type>
void operator>>(type& Val)const{
Val = boost::lexical_cast<type>(Str);
}
template<typename type>
void operator<<(type Val){
Str = boost::lexical_cast<string_type>(Val);
}
template<typename type>
type casted_get(){
type Value;
(*this) >> Value;
return Value;
}
template<typename type>
void casted_set(type Value_){
(*this) << Value;
}
public:
friend std::ostream& operator<<(std::ostream& out, const element_proxy& my){return out << my.cref();}
friend std::istream& operator>>(std::istream& in, const element_proxy& my){ return in >> my.ref(); }
};
struct const_element_proxy{
private:
const string_type& Str;
public:
const_element_proxy(const string_type& Ref) :Str(Ref){}
const_element_proxy(const element_proxy& Prx) :Str(Prx.Str){}
operator const string_type&()const{ return Str; }
const string_type& cref()const{ return Str; }
bool empty()const{ return cref().empty(); }
template<typename type>
void operator>>(type& Val)const{
Val = boost::lexical_cast<type>(Str);
}
template<typename type>
type casted_get(){
type Value;
(*this) >> Value;
return Value;
}
public:
friend std::ostream& operator<<(std::ostream& out, const const_element_proxy& my){ return out << my.cref(); }
};
template<typename type>
struct casted_element_proxy:private element_proxy{
public:
casted_element_proxy(string_type& Ref) :element_proxy(Ref){}
operator type()const{
type Val;
this->operator>>(Val);
return Val;
}
casted_element_proxy<type>& operator=(const type& Val){
this->operator<<(Val);
return *this;
}
type get()const{ return casted_get(); }
void set(const type& value){ casted_set(value); }
string_type& raw(){ return ref(); }
const string_type& craw()const{ return cref(); }
bool empty()const{ return cref().empty(); }
public:
friend std::ostream& operator<<(std::ostream& out, const casted_element_proxy<type>& my){ return out << my.get(); }
friend std::istream& operator>>(std::istream& in, const casted_element_proxy<type>& my){ type value; in >> value; my.set(value); }
};
template<typename type>
struct const_casted_element_proxy:private const_element_proxy{
public:
const_casted_element_proxy(const string_type& Ref) :const_element_proxy(Ref){}
const_casted_element_proxy(const casted_element_proxy<type>& Prx) : const_element_proxy(element_proxy(Prx)){}
operator type()const{
type Val;
this->operator>>(Val);
return Val;
}
type get()const{ return casted_get(); }
const string_type& craw()const{ return cref(); }
bool empty()const{ return cref().empty(); }
public:
friend std::ostream& operator<<(std::ostream& out, const const_casted_element_proxy<type>& my){ return out << my.get(); }
};
private://basic types for column/row iterators
using basic_row_element_iterator = typename std::vector<data_type>::iterator;
using basic_const_row_element_iterator = typename std::vector<data_type>::const_iterator;
using basic_column_element_iterator = typename data_type::second_type::iterator;
using basic_const_column_element_iterator = typename data_type::second_type::const_iterator;
public://column proxy
struct column_element_iterator
: public boost::iterator_adaptor<column_element_iterator, basic_column_element_iterator, element_proxy, boost::random_access_traversal_tag, element_proxy>{
using iterator_adaptor = boost::iterator_adaptor<column_element_iterator, basic_column_element_iterator, element_proxy, boost::random_access_traversal_tag, element_proxy>;
public:
column_element_iterator() = default;
column_element_iterator(basic_column_element_iterator bitr) : iterator_adaptor(bitr){}
private:
friend class boost::iterator_core_access;
element_proxy dereference()const{
return element_proxy(*(base_reference()));
}
};
struct const_column_element_iterator
: public boost::iterator_adaptor<const_column_element_iterator, basic_const_column_element_iterator, const_element_proxy, boost::random_access_traversal_tag, const_element_proxy>{
using iterator_adaptor = boost::iterator_adaptor<const_column_element_iterator, basic_const_column_element_iterator, const_element_proxy, boost::random_access_traversal_tag, const_element_proxy>;
public:
const_column_element_iterator() = default;
const_column_element_iterator(basic_const_column_element_iterator bitr) : iterator_adaptor(bitr){}
const_column_element_iterator(column_element_iterator itr) : iterator_adaptor(itr.base_reference()){}
private:
friend class boost::iterator_core_access;
const_element_proxy dereference()const{
return const_element_proxy(*(base_reference()));
}
};
template<typename type>
struct casted_column_element_iterator
: public boost::iterator_adaptor<casted_column_element_iterator<type>, basic_column_element_iterator, casted_element_proxy<type>, boost::random_access_traversal_tag, casted_element_proxy<type> >{
using iterator_adaptor = boost::iterator_adaptor<casted_column_element_iterator<type>, basic_column_element_iterator, casted_element_proxy<type>, boost::random_access_traversal_tag, casted_element_proxy<type> >;
public:
casted_column_element_iterator() = default;
casted_column_element_iterator(basic_column_element_iterator bitr) : iterator_adaptor(bitr){}
private:
friend class boost::iterator_core_access;
casted_element_proxy<type> dereference()const{
return casted_element_proxy<type>(*(base_reference()));
}
};
template<typename type>
struct const_casted_column_element_iterator
: public boost::iterator_adaptor<const_casted_column_element_iterator<type>, basic_const_column_element_iterator, const_casted_element_proxy<type>, boost::random_access_traversal_tag, const_casted_element_proxy<type> >{
using iterator_adaptor = boost::iterator_adaptor<const_casted_column_element_iterator<type>, basic_const_column_element_iterator, const_casted_element_proxy<type>, boost::random_access_traversal_tag, const_casted_element_proxy<type> >;
public:
const_casted_column_element_iterator() = default;
const_casted_column_element_iterator(basic_const_column_element_iterator bitr) : iterator_adaptor(bitr){}
const_casted_column_element_iterator(casted_column_element_iterator<type> itr) : iterator_adaptor(itr.base_reference()){} private:
private:
friend class boost::iterator_core_access;
const_casted_element_proxy<type> dereference()const{
return const_casted_element_proxy<type>(*(base_reference()));
}
};
struct column_proxy{
friend class my_type;
private:
data_type& rData;
public:
column_proxy(data_type& rData_) :rData(rData_){}
string_type name()const{ return rData.first; }
void rename(string_type Name_){ rData.first = Name_; }
const column_type& cref()const{ return rData.second; }
size_type size()const{ return rData.second.size(); }
element_proxy operator[](size_type Pos){ return element_proxy(rData.second.at(Pos)); }
element_proxy at(size_type Pos){ return element_proxy(rData.second.at(Pos)); }
template<typename type>
casted_element_proxy<type> casted_at(size_type Pos){ return casted_element_proxy<type>(rData.second.at(Pos)); }
const_element_proxy operator[](size_type Pos)const{ return const_element_proxy(rData.second.at(Pos)); }
const_element_proxy at(size_type Pos)const{ return const_element_proxy(rData.second.at(Pos)); }
template<typename type>
const_casted_element_proxy<type> casted_at(size_type Pos)const{ return const_casted_element_proxy<type>(rData.second.at(Pos)); }
column_element_iterator begin(){ return column_element_iterator(rData.second.begin()); }
column_element_iterator end(){ return column_element_iterator(rData.second.end()); }
const_column_element_iterator begin()const{ return const_column_element_iterator(rData.second.begin()); }
const_column_element_iterator end()const{ return const_column_element_iterator(rData.second.end()); }
template<typename type>
casted_column_element_iterator<type> casted_begin(){ return casted_column_element_iterator<type>(rData.second.begin()); }
template<typename type>
casted_column_element_iterator<type> casted_end(){ return casted_column_element_iterator<type>(rData.second.end()); }
template<typename type>
const_casted_column_element_iterator<type> casted_begin()const{ return const_casted_column_element_iterator<type>(rData.second.begin()); }
template<typename type>
const_casted_column_element_iterator<type> casted_end()const{ return const_casted_column_element_iterator<type>(rData.second.end()); }
};
struct const_column_proxy{
private:
const data_type& rData;
public:
const_column_proxy(const data_type& rData_) :rData(rData_){}
string_type name()const{ return rData.first; }
const column_type& cref()const{ return rData.second; }
size_type size()const{ return rData.second.size(); }
const_element_proxy operator[](size_type Pos)const{ return const_element_proxy(rData.second.at(Pos)); }
const_element_proxy at(size_type Pos)const{ return const_element_proxy(rData.second.at(Pos)); }
template<typename type>
const_casted_element_proxy<type> casted_at(size_type Pos)const{ return const_casted_element_proxy<type>(rData.second.at(Pos)); }
const_column_element_iterator begin()const{ return const_column_element_iterator(rData.second.begin()); }
const_column_element_iterator end()const{ return const_column_element_iterator(rData.second.end()); }
template<typename type>
const_casted_column_element_iterator<type> casted_begin()const{ return const_casted_column_element_iterator<type>(rData.second.begin()); }
template<typename type>
const_casted_column_element_iterator<type> casted_end()const{ return const_casted_column_element_iterator<type>(rData.second.end()); }
};
public://row proxy
struct row_element_iterator
: public boost::iterator_adaptor<row_element_iterator, basic_row_element_iterator, element_proxy, boost::random_access_traversal_tag, element_proxy>{
using iterator_adaptor = boost::iterator_adaptor<row_element_iterator, basic_row_element_iterator, element_proxy, boost::random_access_traversal_tag, element_proxy>;
friend struct const_row_element_iterator;
private:
size_type column_pos;
public:
row_element_iterator() = default;
row_element_iterator(basic_row_element_iterator bitr, size_type column_pos_) : iterator_adaptor(bitr), column_pos(column_pos_){}
private:
friend class boost::iterator_core_access;
bool equal(row_element_iterator itr_)const{
return (column_pos == itr_.column_pos) && (base_reference() == itr_.base_reference());
}
element_proxy dereference()const{
return element_proxy(base_reference()->second[column_pos]);
}
};
struct const_row_element_iterator
: public boost::iterator_adaptor<const_row_element_iterator, basic_const_row_element_iterator, const_element_proxy, boost::random_access_traversal_tag, const_element_proxy>{
using iterator_adaptor = boost::iterator_adaptor<const_row_element_iterator, basic_const_row_element_iterator, const_element_proxy, boost::random_access_traversal_tag, const_element_proxy>;
private:
size_type column_pos;
public:
const_row_element_iterator() = default;
const_row_element_iterator(basic_const_row_element_iterator bitr, size_type column_pos_) : iterator_adaptor(bitr), column_pos(column_pos_){}
const_row_element_iterator(row_element_iterator itr) : iterator_adaptor(itr.base_reference()), column_pos(itr.column_pos){}
private:
friend class boost::iterator_core_access;
bool equal(const_row_element_iterator itr_)const{
return (column_pos == itr_.column_pos) && (base_reference() == itr_.base_reference());
}
const_element_proxy dereference()const{
return const_element_proxy(base_reference()->second[column_pos]);
}
};
struct row_proxy{
friend struct const_row_proxy;
private:
my_type& My;
size_type row_pos;
public:
row_proxy(my_type& My_, size_type row_pos_) :My(My_), row_pos(row_pos_){}
size_type size()const{ return My.column_size(); }
size_type pos()const{ return row_pos; }
element_proxy operator[](size_type Pos){ return My(row_pos, Pos); }
element_proxy at(size_type Pos){ return My.at(row_pos, Pos); }
const_element_proxy operator[](size_type Pos)const{ return My(row_pos, Pos); }
const_element_proxy at(size_type Pos)const{ return My.at(row_pos, Pos); }
row_element_iterator begin(){ return row_element_iterator(My.Data.begin(), row_pos); }
row_element_iterator end(){return row_element_iterator(My.Data.end(), row_pos); }
const_row_element_iterator begin()const{ return const_row_element_iterator(My.Data.begin(), row_pos); }
const_row_element_iterator end()const{ return const_row_element_iterator(My.Data.end(), row_pos); }
};
struct const_row_proxy{
private:
const my_type& My;
size_type row_pos;
public:
const_row_proxy(const my_type& My_, size_type row_pos_) :My(My_), row_pos(row_pos_){}
const_row_proxy(row_proxy Prx) :My(Prx.My), row_pos(Prx.row_pos){}
size_type size()const{ return My.column_size() }
size_type pos()const{ return row_pos; }
const_element_proxy operator[](size_type Pos)const{ return My(row_pos, Pos); }
const_element_proxy at(size_type Pos)const{ return My.at(row_pos, Pos); }
const_row_element_iterator begin()const{ return const_row_element_iterator(My.Data.begin(), row_pos); }
const_row_element_iterator end()const{ return const_row_element_iterator(My.Data.end(), row_pos); }
};
public:
struct row_iterator
: public boost::iterator_facade<row_iterator, row_proxy, boost::random_access_traversal_tag, row_proxy, diff_type >{
using iterator_facade = boost::iterator_facade<row_iterator, row_proxy, boost::random_access_traversal_tag, row_proxy, diff_type >;
friend struct const_row_iterator;
private:
my_type* Ptr;
size_type RowPos;
public:
row_iterator():Ptr(nullptr),RowPos(std:numeric_limits<size_type>::max()){}
row_iterator(my_type& Ref_,size_type row_pos_) : Ptr(&Ref_), RowPos(row_pos_){}
public:
size_type row_pos()const{ return RowPos; }
private:
friend class boost::iterator_core_access;
row_proxy dereference()const{ return row_proxy(*Ptr, RowPos); }
bool equal(row_iterator itr_)const{ return (RowPos == itr_.RowPos) && (Ptr == itr_.Ptr); }
void increment(){ ++RowPos; }
void decrement(){ --RowPos; }
void advance(diff_type n){ RowPos += n; }
diff_type distance_to(row_iterator itr_)const{ return itr_.RowPos - row_itr.RowPos; }
};
struct const_row_iterator
: public boost::iterator_facade<const_row_iterator, const_row_proxy, boost::random_access_traversal_tag, const_row_proxy, diff_type >{
using iterator_facade = boost::iterator_facade<const_row_iterator, const_row_proxy, boost::random_access_traversal_tag, const_row_proxy, diff_type >;
private:
const my_type* Ptr;
size_type RowPos;
public:
const_row_iterator() :Ptr(nullptr), RowPos(std : numeric_limits<size_type>::max()){}
const_row_iterator(const my_type& Ref_, size_type row_pos_) : Ptr(&Ref_), RowPos(row_pos_){}
const_row_iterator(row_iterator itr) : Ptr(itr.Ptr), RowPos(itr.RowPos){}
public:
size_type row_pos()const{ return RowPos; }
private:
friend class boost::iterator_core_access;
const_row_proxy dereference()const{ return const_row_proxy(*Ptr, RowPos); }
bool equal(const_row_iterator itr_)const{ return (RowPos == itr_.RowPos) && (Ptr == itr_.Ptr); }
void increment(){ ++RowPos; }
void decrement(){ --RowPos; }
void advance(diff_type n){ RowPos += n; }
diff_type distance_to(const_row_iterator itr_)const{ return itr_.RowPos - row_itr.RowPos; }
};
struct column_iterator
: public boost::iterator_adaptor<column_iterator, basic_row_element_iterator, column_proxy, boost::random_access_traversal_tag, column_proxy>{
using iterator_adaptor = boost::iterator_adaptor<column_iterator, basic_row_element_iterator, column_proxy, boost::random_access_traversal_tag, column_proxy>;
friend struct const_column_iterator;
public:
column_iterator() = default;
column_iterator(basic_row_element_iterator bitr) : iterator_adaptor(bitr){}
private:
friend class boost::iterator_core_access;
bool equal(column_iterator itr_)const{
return (base_reference() == itr_.base_reference());
}
column_proxy dereference()const{
return column_proxy(*(base_reference()));
}
};
struct const_column_iterator
: public boost::iterator_adaptor<const_column_iterator, basic_const_row_element_iterator, const_column_proxy, boost::random_access_traversal_tag, const_column_proxy>{
using iterator_adaptor = boost::iterator_adaptor<const_column_iterator, basic_const_row_element_iterator, const_column_proxy, boost::random_access_traversal_tag, const_column_proxy>;
public:
const_column_iterator() = default;
const_column_iterator(basic_const_row_element_iterator bitr) : iterator_adaptor(bitr){}
const_column_iterator(column_iterator itr) : iterator_adaptor(itr.base_reference()){}
private:
friend class boost::iterator_core_access;
bool equal(const_column_iterator itr_)const{
return (base_reference() == itr_.base_reference());
}
const_column_proxy dereference()const{
return const_column_proxy(*(base_reference()));
}
};
struct name_iterator
: public boost::iterator_adaptor<name_iterator, basic_row_element_iterator, string_type, boost::random_access_traversal_tag>{
using iterator_adaptor = boost::iterator_adaptor<name_iterator, basic_row_element_iterator, string_type, boost::random_access_traversal_tag>;
friend struct const_name_iterator;
public:
name_iterator() = default;
name_iterator(basic_row_element_iterator bitr) : iterator_adaptor(bitr){}
private:
friend class boost::iterator_core_access;
bool equal(name_iterator itr_)const{
return (base_reference() == itr_.base_reference());
}
string_type& dereference()const{
return base_reference()->first;
}
};
struct const_name_iterator
: public boost::iterator_adaptor<const_name_iterator, basic_const_row_element_iterator, const string_type, boost::random_access_traversal_tag>{
using iterator_adaptor = boost::iterator_adaptor<const_name_iterator, basic_const_row_element_iterator, const string_type, boost::random_access_traversal_tag>;
public:
const_name_iterator() = default;
const_name_iterator(basic_const_row_element_iterator bitr) : iterator_adaptor(bitr){}
const_name_iterator(name_iterator itr) : iterator_adaptor(itr.base_reference()){}
private:
friend class boost::iterator_core_access;
bool equal(const_name_iterator itr_)const{
return (base_reference() == itr_.base_reference());
}
const string_type& dereference()const{
return base_reference()->first;
}
};
public:
basic_table() = default;
basic_table(const my_type& my_) = default;
my_type& operator=(const my_type& my_) = default;
basic_table(my_type&& my_) = default;
my_type& operator=(my_type&& my_) = default;
basic_table(size_type row_size_, size_type col_size_) :basic_table(){
assign(row_size_, col_size_);
}
explicit basic_table(size_pair_type size_) :basic_table(){
assign(size_.first, size_.second);
}
void swap(my_type& my_){Data.swap(my_.Data);}
public://access directoly
element_proxy at(size_type row_pos_, size_type column_pos_){ return element_proxy(Data.at(column_pos_).second.at(row_pos_)); }
const_element_proxy at(size_type row_pos_, size_type column_pos_)const{ return const_element_proxy(Data.at(column_pos_).second.at(row_pos_)); }
element_proxy operator()(size_type row_pos_, size_type column_pos_){ return element_proxy(Data.at(column_pos_).second.at(row_pos_)); }
const_element_proxy operator()(size_type row_pos_, size_type column_pos_)const{ return const_element_proxy(Data.at(column_pos_).second.at(row_pos_)); }
template<typename type>
casted_element_proxy<type> casted_at(size_type row_pos_, size_type column_pos_){ return casted_element_proxy<type>(Data.at(column_pos_).second.at(row_pos_)); }
template<typename type>
const_casted_element_proxy<type> casted_at(size_type row_pos_, size_type column_pos_)const{ return const_casted_element_proxy<type>(Data.at(column_pos_).second.at(row_pos_)); }
element_proxy at(size_pair_type pos_){ return at(pos_.first,pos_.second); }
const_element_proxy at(size_pair_type pos_)const{ return at(pos_.first,pos_.second); }
element_proxy operator[](size_pair_type pos_){ return operator()(pos_.first,pos_.second);}
const_element_proxy operator[](size_pair_type pos_)const{ return operator()(pos_.first,pos_.second);}
template<typename type>
casted_element_proxy<type> casted_at(size_pair_type pos_){return casted_at(pos_.first,pos_.second);}
template<typename type>
const_casted_element_proxy<type> casted_at(size_pair_type pos_)const{return casted_at(pos_.first,pos_.second);}
public://access column
size_type column_size()const{ return Data.size(); }
column_proxy column(size_type column_pos_){ return column_proxy(Data.at(column_pos_)); }
column_iterator column_begin(){ return column_iterator(Data.begin()); }
column_iterator column_end(){ return column_iterator(Data.end()); }
const_column_proxy column(size_type column_pos_)const{ return const_column_proxy(Data.at(column_pos_)); }
const_column_iterator column_begin()const{ return const_column_iterator(Data.begin()); }
const_column_iterator column_end()const{ return const_column_iterator(Data.end()); }
column_iterator find_column(const string_type& column_name_){
return std::find_if(column_begin(), column_end(), [](const column_proxy& col)->bool{return col.name() == column_name; });
}
const_column_iterator find_column(const string_type& column_name_)const{
return std::find_if(column_begin(), column_end(), [](const const_column_proxy& col)->bool{return col.name() == column_name; });
}
public://access row
size_type row_size()const{ return Data.at(0).second.size(); }
row_proxy row(size_type row_pos_){ return row_proxy(*this, row_pos_); }
row_iterator row_begin(){ return row_iterator(*this,0); }
row_iterator row_end(){ return row_iterator(*this,row_size()); }
const_row_proxy row(size_type row_pos_)const{ return row_proxy(*this, row_pos_); }
const_row_iterator row_begin()const{ return const_row_iterator(*this, 0);}
const_row_iterator row_end()const{ return const_row_iterator(*this, row_size()); }
public://access column_name
string_type& column_name(size_type column_pos_){return Data.at(column_pos_).first;}
name_iterator column_name_begin(){ return name_iterator(Data.begin()); }
name_iterator column_name_end(){ return name_iterator(Data.end()); }
const string_type& column_name(size_type column_pos_)const{ return Data.at(column_pos_).first; }
const_name_iterator column_name_begin()const{ return const_name_iterator(Data.begin()); }
const_name_iterator column_name_end()const{ return const_name_iterator(Data.end()); }
public://change elements
size_pair_type size(){
if(Data.empty())return size_pair_type(0, 0);
return size_pair_type(Data.size(), Data.at(0).second.size());
}
void assign(size_type row_size_, size_type col_size_){
Data.assign(col_size_, data_type());
for(auto& Column : Data)Column.second.assign(row_size_,string_type());
}
void reserve(size_type row_size_, size_type col_size_){
Data.reserve(col_size_);
for(auto& Column : Data)Column.second.reserve(row_size_);
}
void clear(){ Data.clear(); }
public://manage column
void push_back_column(string_type column_name_, column_type column_){
//set same rownum with other columns
if(row_size() > column_.size()){
column_.insert(column_.end(), row_size() - column_.size(), "");
} else if(row_size() < column_.size()){
column_.erase(column_.begin() + row_size(), column_.end());
}
//push_back new column
Data.push_back(std::make_pair(column_name_, column_));
}
void push_back_column(string_type column_name_ = ""){
push_back_column(column_name_, column_type(row_size(),""));
}
void pop_back_column(){ Data.pop_back(); }
column_iterator insert_column(column_iterator itr, size_type n, string_type column_name_, column_type column_){
if(n == 0)return itr;
hmLib_assert(itr->size() == column_.size(), table_exception, "column with different size is requested to insert.");
//Insert new column
return column_iterator(Data.insert(Data.begin() + (itr-column_begin()), n, std::make_pair(column_name_, std::move(column_))));
}
column_iterator insert_column(column_iterator itr, string_type column_name_ = ""){
return insert_column(itr, 1, std::move(column_name_), column_type(row_size(), ""));
}
column_iterator insert_column(column_iterator itr, column_iterator first, column_iterator last){
for(; first != last; ++first){
itr = insert_column(itr, first->cref(), first->name());
++itr;
}
}
column_iterator erase_column(column_iterator itr){
return column_iterator(Data.erase(Data.begin() + (itr - column_begin())));
}
column_iterator erase_column(column_iterator first, column_iterator last){
return column_iterator(Data.erase(Data.begin() + (first - column_begin()), Data.begin() + (last - column_begin())));
}
void swap_column(column_iterator itr1, column_iterator itr2){
hmLib_assert(itr1->size() == itr2->size(), table_exception, "columns with different size cannot be swaped.");
std::swap(itr1->rData, itr2->rData);
}
public://manage row
void push_back_row(){
for(auto& Column : Data){
Column.second.push_back("");
}
}
void pop_back_row(){
for(auto& Column : Data){
Column.second.pop_back();
}
}
row_iterator insert_row(row_iterator itr, size_type n = 1){
if(n == 0)return itr;
for(auto& Column : Data){
Column.second.insert(Column.second.begin()+itr.row_pos(), n, "");
}
return itr;
}
row_iterator insert_row(row_iterator itr, row_iterator first, row_iterator last){
hmLib_assert(itr->size() == first.size(), table_exception, "row with different size is requested to insert.");
itr = insert_row(itr, last-first);
for(; first != last; ++first){
for(size_type pos = 0; pos < row_size(); ++pos){
itr->at(pos) = first->at(pos);
}
}
return itr;
}
row_iterator erase_row(row_iterator itr){
for(auto& Column : Data){
Column.second.erase(Column.second.begin() + itr.row_pos());
}
return itr;
}
row_iterator erase_row(row_iterator first, row_iterator last){
for(auto& Column : Data){
Column.second.erase(Column.second.begin() + first.row_pos(), Column.second.begin() + last.row_pos());
}
return itr;
}
void swap_row(row_iterator itr1, row_iterator itr2){
hmLib_assert(itr1->size() == itr2->size(), table_exception, "rows with different size cannot be swaped.");
for(auto& Column : Data){
std::swap(Column.second.at(itr1.row_pos()), Column.second.at(itr2.row_pos()));
}
}
};
using table = basic_table<char, std::char_traits < char >> ;
}
#
#endif
| 48.764103 | 238 | 0.758545 | hmito |
647654a81e44abbb020941ec699277bd0b84dda7 | 47 | hpp | C++ | src/boost_icl_separate_interval_set.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_icl_separate_interval_set.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_icl_separate_interval_set.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/icl/separate_interval_set.hpp>
| 23.5 | 46 | 0.829787 | miathedev |
6477964ce0ce76b0600a3803248b7a512764c3fd | 4,140 | cpp | C++ | jrtp/rtprandomrands.cpp | gurumobile/RemoteControlGalileoExam | f9c2ce62091a5a7076020a4375475a8d70079cb3 | [
"MIT"
] | 21 | 2015-01-01T12:31:22.000Z | 2020-07-20T03:15:18.000Z | src/rtprandomrands.cpp | jjzhang166/JRTPLIB-2 | 8e79132ffc6400bb9e9b421676b3c632273ff5b5 | [
"MIT"
] | null | null | null | src/rtprandomrands.cpp | jjzhang166/JRTPLIB-2 | 8e79132ffc6400bb9e9b421676b3c632273ff5b5 | [
"MIT"
] | 19 | 2015-01-13T03:48:06.000Z | 2021-11-30T05:33:55.000Z | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 Jori Liesenborgs
Contact: jori.liesenborgs@gmail.com
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
#if defined(WIN32) && !defined(_WIN32_WCE)
#define _CRT_RAND_S
#endif // WIN32 || _WIN32_WCE
#include "rtprandomrands.h"
#include "rtperrors.h"
#if (defined(WIN32) && !defined(_WIN32_WCE)) && (defined(_MSC_VER) && _MSC_VER >= 1400 )
#include <math.h>
#include <stdlib.h>
// If compiling on VC 8 or later for full Windows, we'll attempt to use rand_s,
// which generates better random numbers. However, its only supported on Windows XP,
// Windows Server 2003, and later, so we'll do a run-time check to see if we can
// use it (it won't work on Windows 2000 SP4 for example).
#define RTP_SUPPORT_RANDS
#endif
#include "rtpdebug.h"
namespace jrtplib
{
#ifndef RTP_SUPPORT_RANDS
RTPRandomRandS::RTPRandomRandS()
{
initialized = false;
}
RTPRandomRandS::~RTPRandomRandS()
{
}
int RTPRandomRandS::Init()
{
return ERR_RTP_RTPRANDOMRANDS_NOTSUPPORTED;
}
uint8_t RTPRandomRandS::GetRandom8()
{
return 0;
}
uint16_t RTPRandomRandS::GetRandom16()
{
return 0;
}
uint32_t RTPRandomRandS::GetRandom32()
{
return 0;
}
double RTPRandomRandS::GetRandomDouble()
{
return 0;
}
#else
RTPRandomRandS::RTPRandomRandS()
{
initialized = false;
}
RTPRandomRandS::~RTPRandomRandS()
{
}
int RTPRandomRandS::Init()
{
if (initialized) // doesn't matter then
return 0;
HMODULE hAdvApi32 = LoadLibrary(TEXT("ADVAPI32.DLL"));
if(hAdvApi32 != NULL)
{
if(NULL != GetProcAddress( hAdvApi32, "SystemFunction036" )) // RtlGenRandom
{
initialized = true;
}
FreeLibrary(hAdvApi32);
hAdvApi32 = NULL;
}
if (!initialized)
return ERR_RTP_RTPRANDOMRANDS_NOTSUPPORTED;
return 0;
}
// rand_s gives a number between 0 and UINT_MAX. We'll assume that UINT_MAX is at least 8 bits
uint8_t RTPRandomRandS::GetRandom8()
{
if (!initialized)
return 0;
unsigned int r;
rand_s(&r);
return (uint8_t)(r&0xff);
}
uint16_t RTPRandomRandS::GetRandom16()
{
if (!initialized)
return 0;
unsigned int r;
int shift = 0;
uint16_t x = 0;
for (int i = 0 ; i < 2 ; i++, shift += 8)
{
rand_s(&r);
x ^= ((uint16_t)r << shift);
}
return x;
}
uint32_t RTPRandomRandS::GetRandom32()
{
if (!initialized)
return 0;
unsigned int r;
int shift = 0;
uint32_t x = 0;
for (int i = 0 ; i < 4 ; i++, shift += 8)
{
rand_s(&r);
x ^= ((uint32_t)r << shift);
}
return x;
}
double RTPRandomRandS::GetRandomDouble()
{
if (!initialized)
return 0;
unsigned int r;
int shift = 0;
uint64_t x = 0;
for (int i = 0 ; i < 8 ; i++, shift += 8)
{
rand_s(&r);
x ^= ((uint64_t)r << shift);
}
x &= 0x7fffffffffffffffULL;
int64_t x2 = (int64_t)x;
return RTPRANDOM_2POWMIN63*(double)x2;
}
#endif // RTP_SUPPORT_RANDS
} // end namespace
| 20.597015 | 94 | 0.710386 | gurumobile |
647e6d3d644158aec4f503a30f5a41f9649def22 | 3,215 | cc | C++ | Kakadu/JP2_Box.cc | pirl-lpl/libjp2 | 9815b55e8a5222018fe5f978ac0819e53aea5204 | [
"Apache-2.0"
] | 1 | 2019-07-31T19:47:53.000Z | 2019-07-31T19:47:53.000Z | Kakadu/JP2_Box.cc | pirl-lpl/libjp2 | 9815b55e8a5222018fe5f978ac0819e53aea5204 | [
"Apache-2.0"
] | null | null | null | Kakadu/JP2_Box.cc | pirl-lpl/libjp2 | 9815b55e8a5222018fe5f978ac0819e53aea5204 | [
"Apache-2.0"
] | 1 | 2022-03-11T05:40:11.000Z | 2022-03-11T05:40:11.000Z | /* JP2_Box
HiROC CVS ID: $Id: JP2_Box.cc,v 1.1 2012/04/26 00:39:32 castalia Exp $
Copyright (C) 2012 Arizona Board of Regents on behalf of the
Planetary Image Research Laboratory, Lunar and Planetary Laboratory at
the University of Arizona.
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License, version 2.1,
as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*******************************************************************************/
#ifndef DOXYGEN_PROCESSING
#include "jp2.h"
using namespace kdu_supp;
#include "JP2_Box.hh"
#include "JP2_Metadata.hh"
#include <ostream>
using std::hex;
using std::dec;
using std::endl;
namespace UA
{
namespace HiRISE
{
namespace Kakadu
{
std::ostream&
operator<<
(
std::ostream& stream,
JP2_Box& Box
)
{
if (Box.exists ())
{
JP2_Box
box;
box.open (Box.source (), Box.get_locator ());
kdu_supp::jp2_locator
locator (box.get_locator ());
stream
<< " JP2 " << JP2_Metadata::box_name (box.get_box_type ())
<< "/\"" << JP2_Metadata::type_name (box.get_box_type ())
<< "\" (0x" << hex << box.get_box_type () << dec << ") box -"
<< endl;
jp2_input_box*
parent (Box.parent ());
if (parent)
stream
<< " sub-box of "
<< JP2_Metadata::box_name (parent->get_box_type ())
<< "/\"" << JP2_Metadata::type_name (parent->get_box_type ())
<< "\" (0x" << hex << parent->get_box_type () << dec << ')'
<< endl;
stream
<< locator
<< " read position = "
<< box.get_pos () << endl
<< " header length = "
<< box.get_box_header_length () << endl
<< " remaining bytes = "
<< box.get_remaining_bytes () << endl
<< " total box bytes = "
<< box.get_box_bytes () << endl
<< " is complete = "
<< box.is_complete () << endl;
if (jp2_is_superbox (box.get_box_type ()))
{
JP2_Box
sub_box;
sub_box.open (&box);
if (sub_box.exists ())
{
stream
<< " --> Begin sub-box contents of "
<< JP2_Metadata::box_name (box.get_box_type ()) << endl;
while (sub_box.exists ())
{
stream << sub_box;
sub_box.close ();
sub_box.open_next ();
}
stream
<< " <-- End sub-box contents of "
<< JP2_Metadata::box_name (box.get_box_type ()) << endl;
}
}
box.close ();
}
else
stream << " The box is closed." << endl;
return stream;
}
std::ostream&
operator<<
(
std::ostream& stream,
jp2_locator& locator
)
{
stream
<< " file position = " << locator.get_file_pos () << endl
<< " databin id = " << locator.get_databin_id () << endl
<< " databin position = " << locator.get_databin_pos () << endl;
return stream;
}
} // namespace Kakadu
} // namespace HiRISE
} // namespace UA
#endif
| 24.541985 | 80 | 0.622084 | pirl-lpl |
64869e97c8945ce550a71efa7372c9155585aaf5 | 283 | cpp | C++ | Codeforces/1~999/482/A.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | 6 | 2018-12-30T06:16:54.000Z | 2022-03-23T08:03:33.000Z | Codeforces/1~999/482/A.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | null | null | null | Codeforces/1~999/482/A.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cstdio>
#include <cstring>
int n, k, x, y;
int main() {
scanf("%d%d", &n, &k), x = 1, y = n;
for (int i = 1; i <= k; i++) {
printf("%d ", x);
x += i % 2 ? 1 : -1;
std::swap(x, y);
}
for (n -= k; n--; y += y < x ? 1 : -1) printf("%d ", y);
} | 18.866667 | 57 | 0.431095 | tiger0132 |
6488e202bb24d9cb5ce265cefc8a82418015a0de | 1,388 | cpp | C++ | src/mesh.cpp | FrMarchand/pbr-material-viewer | cc665a10f036dc13b6fd6c94c48d5b8ddc3596a4 | [
"MIT"
] | 5 | 2019-08-07T09:48:04.000Z | 2021-08-12T07:31:51.000Z | src/mesh.cpp | FrMarchand/pbr-material-viewer | cc665a10f036dc13b6fd6c94c48d5b8ddc3596a4 | [
"MIT"
] | null | null | null | src/mesh.cpp | FrMarchand/pbr-material-viewer | cc665a10f036dc13b6fd6c94c48d5b8ddc3596a4 | [
"MIT"
] | 4 | 2020-03-19T04:30:55.000Z | 2021-08-08T01:28:28.000Z | #include "mesh.h"
Mesh::Mesh()
{}
Mesh::~Mesh()
{}
void Mesh::draw(const Shader& shader) const
{
shader.use();
// draw mesh
glBindVertexArray(mVAO);
glDrawElements(mPrimitive, mIndexCount, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void Mesh::setupMesh(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices)
{
mIndexCount = indices.size();
glGenVertexArrays(1, &mVAO);
glGenBuffers(1, &mVBO);
glGenBuffers(1, &mEBO);
glBindVertexArray(mVAO);
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
// vertex positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
// vertex tangent
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
// vertex texture coords
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
glBindVertexArray(0);
} | 27.76 | 107 | 0.75 | FrMarchand |
6489472c152bcd70623709c6e111233ce5f85a22 | 5,305 | hpp | C++ | source/hougfx/include/hou/gfx/framebuffer.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/hougfx/include/hou/gfx/framebuffer.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/hougfx/include/hou/gfx/framebuffer.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#ifndef HOU_GFX_FRAME_BUFFER_HPP
#define HOU_GFX_FRAME_BUFFER_HPP
#include "hou/cor/non_copyable.hpp"
#include "hou/gfx/framebuffer_blit_filter.hpp"
#include "hou/gfx/framebuffer_blit_mask.hpp"
#include "hou/gfx/gfx_config.hpp"
#include "hou/mth/rectangle_fwd.hpp"
#include "hou/gl/gl_framebuffer_handle.hpp"
namespace hou
{
class texture;
/** Represents a user defined framebuffer.
*/
class HOU_GFX_API framebuffer : public non_copyable
{
public:
/** Binds a framebuffer as the target for drawing operations.
*
* \param fb the framebuffer.
*
* \throws hou::precondition_violation if fb is not complete.
*/
static void bind_draw_target(const framebuffer& fb);
/** Binds a framebuffer as the source framebuffer.
*
* \param fb the framebuffer.
*
* \throws hou::precondition_violation if fb is not complete.
*/
static void bind_read_target(const framebuffer& fb);
/** Binds a framebuffer as both target and source.
*
* \param fb the framebuffer.
*
* \throws hou::precondition_violation if fb is not complete.
*/
static void bind(const framebuffer& fb);
/** Unbinds the current draw framebuffer.
*/
static void unbind_draw_target();
/** Unbinds the current read framebuffer.
*/
static void unbind_read_target();
/** Unbinds the current draw and read framebuffer objects.
*/
static void unbind();
/** Retrieves the number of available slots for color attachments in a
* framebuffer.
*
* \return the number of available slots for color attachments.
*/
static uint get_color_attachment_point_count();
public:
/** default constructor.
*/
framebuffer();
/** Retrieves a reference to the OpenGL framebuffer handle.
*
* \return a reference to the OpenGL framebuffer handle.
*/
const gl::framebuffer_handle& get_handle() const noexcept;
/** Checks if this framebuffer is currently bound as draw target.
*
* \return the result of the check.
*/
bool is_bound_to_draw_target() const;
/** Checks if this framebuffer is currently bound as read target.
*
* \return the result of the check.
*/
bool is_bound_to_read_target() const;
/** Checks if this framebuffer is complete.
*
* Only complete framebuffer objects can be bound or used as source or
* destination for blit destination. Using an incomplete framebuffer will
* cause an exception to be thrown.
*
* \return the result of the check.
*/
bool is_complete() const;
/** Sets a color attachment for this framebuffer.
*
* \param attachment_point an index representing the desired attachment point.
* Its value must be lower than the maximum number of available attachment
* points.
*
* \param tex the texture to be attached. The format of the
* texture must be r, rg, rgb, or rgba.
*
* \param mipmap_level the mip map level
* to bind. It must be a valid mip map level of texture.
*
* \throws hou::precondition_violation if attachment_point is greater or equal
* than the number of allowed attachments, if mipmap_level is greater or equal
* then the number of mipmap levels of tex, or if the format of tex is not r,
* rg, rgb, or rgba.
*/
void set_color_attachment(
uint attachment_point, const texture& tex, uint mipmap_level = 0u);
/** Sets the depth and stencil attachment for this framebuffer.
*
* \param tex the texture to be attached. The format of the texture must
* be depth_stencil.
*
* \param mipmap_level the mip map level to bind. It must be a valid mip map
* level of texture.
*
* \throws hou::precondition_violation if mipmap_level is greater or equal
* then the number of mipmap levels of tex, or if the format of tex is not
* depth_stencil.
*/
void set_depth_stencil_attachment(const texture& tex, uint mipmap_level = 0u);
/** Checks if this framebuffer has a multisample attachment.
*
* \return the result of the check.
*/
bool has_multisample_attachment() const;
private:
gl::framebuffer_handle m_handle;
bool m_has_multisample_color_attachment;
bool m_has_multisample_depth_attachment;
bool m_has_multisample_stencil_attachment;
};
/** Copies a rectangular region of a framebuffer into another framebuffer.
*
* The following constraints must be observed, or an exception will be thrown:
*
* * src and dst must be complete framebuffer objects.
*
* * If src or dst are multisampled, src_rect and dst_rect must have the same
* size.
*
* * If mask contains depth or stencil, filter must be set to nearest.
*
* \param src the source framebuffer.
*
* \param src_rect the source rectangle.
*
* \param dst the destination framebuffer.
*
* \param dst_rect the destination rectangle.
*
* \param mask a bitfield specifying what attachments to blit.
*
* \param filter the filter to apply for this operation.
*
* \throws hou::precondition_violation if one condition on the arguments is
* violated.
*/
HOU_GFX_API void blit(const framebuffer& src, const recti& src_rect,
framebuffer& dst, const recti& dst_rect, framebuffer_blit_mask mask,
framebuffer_blit_filter filter = framebuffer_blit_filter::nearest);
} // namespace hou
#endif
| 28.368984 | 80 | 0.719321 | DavideCorradiDev |
52bfb73113cf500a929e8637ffb6b7602ea0f2be | 782 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/scn/loc/LocStoreEmbedded.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/scn/loc/LocStoreEmbedded.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/scn/loc/LocStoreEmbedded.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Scripting/Natives/Generated/scn/loc/LocStoreEmbeddedVariantDescriptorEntry.hpp>
#include <RED4ext/Scripting/Natives/Generated/scn/loc/LocStoreEmbeddedVariantPayloadEntry.hpp>
namespace RED4ext
{
namespace scn::loc {
struct LocStoreEmbedded
{
static constexpr const char* NAME = "scnlocLocStoreEmbedded";
static constexpr const char* ALIAS = NAME;
DynArray<scn::loc::LocStoreEmbeddedVariantDescriptorEntry> vdEntries; // 00
DynArray<scn::loc::LocStoreEmbeddedVariantPayloadEntry> vpEntries; // 10
};
RED4EXT_ASSERT_SIZE(LocStoreEmbedded, 0x20);
} // namespace scn::loc
} // namespace RED4ext
| 31.28 | 97 | 0.786445 | jackhumbert |
52c0309cb7b6c128036562e0404f054a592f9620 | 464 | cpp | C++ | test/SubscriberHandleTest.cpp | eXpl0it3r/PubBus | 0455a605a799d3bf2bb6dfcd7970d5ba1ef7528f | [
"Unlicense"
] | 16 | 2016-03-16T11:20:20.000Z | 2021-10-19T04:55:05.000Z | test/SubscriberHandleTest.cpp | eXpl0it3r/PubBus | 0455a605a799d3bf2bb6dfcd7970d5ba1ef7528f | [
"Unlicense"
] | 1 | 2019-08-26T21:54:58.000Z | 2019-12-25T20:34:41.000Z | test/SubscriberHandleTest.cpp | eXpl0it3r/PubBus | 0455a605a799d3bf2bb6dfcd7970d5ba1ef7528f | [
"Unlicense"
] | 6 | 2019-06-14T16:42:21.000Z | 2022-01-17T08:31:33.000Z | #include "catch.hpp"
#include <cstddef>
#include <PubBus/SubscriberHandle.hpp>
TEST_CASE("Constructing a SubscriberHandle sets the index and id", "[SubscriberHandle]")
{
// Arrange
struct DummyMessage : pub::Message
{
};
auto id = pub::Message::id<DummyMessage>();
auto index = 10u;
// Act
auto handle = pub::SubscriberHandle{ id, index };
// Assert
REQUIRE(handle.id() == id);
REQUIRE(handle.index() == index);
}
| 19.333333 | 88 | 0.633621 | eXpl0it3r |
52c03b8c358e967f14be33024fcbdd7719129413 | 1,202 | cpp | C++ | 1396. Design Underground System.cpp | priyamittal15/Leetcode_Solutions | 21cb9c09e053425dba66acd62240399b1a35fba0 | [
"Apache-2.0"
] | 1 | 2022-01-28T08:07:32.000Z | 2022-01-28T08:07:32.000Z | 1396. Design Underground System.cpp | priyamittal15/Leetcode_Solutions | 21cb9c09e053425dba66acd62240399b1a35fba0 | [
"Apache-2.0"
] | null | null | null | 1396. Design Underground System.cpp | priyamittal15/Leetcode_Solutions | 21cb9c09e053425dba66acd62240399b1a35fba0 | [
"Apache-2.0"
] | 1 | 2022-03-16T14:46:09.000Z | 2022-03-16T14:46:09.000Z | class UndergroundSystem {
public:
map<Double,pair<string,double>> customer;
//customer is storing customer id as key and stationname and time as value
map<pair<string, string>, pair<double, double>> total;
//total storing startstation and endstation as key and totaltime and count as value
UndergroundSystem() {
customer.clear();
total.clear();
}
void checkIn(int id, string stationName, int t) {
customer[id]={stationName, t};
}
void checkOut(int id, string stationName, int t) {
total[{customer[id].first, stationName}]={total[{customer[id].first, stationName}].first+(t-customer[id].second),total[{customer[id].first, stationName}].second+1};
}
double getAverageTime(string startStation, string endStation) {
return total[{startStation,endStation}].first/total[{startStation,endStation}].second;
}
};
/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem* obj = new UndergroundSystem();
* obj->checkIn(id,stationName,t);
* obj->checkOut(id,stationName,t);
* double param_3 = obj->getAverageTime(startStation,endStation);
| 37.5625 | 173 | 0.678037 | priyamittal15 |
52c258fd021a646366cb8214ef9008e11e668ad4 | 737 | cpp | C++ | Sorting and Searching/Factory Machines.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T12:30:13.000Z | 2022-02-12T13:59:20.000Z | Sorting and Searching/Factory Machines.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T11:09:41.000Z | 2022-02-12T11:55:49.000Z | Sorting and Searching/Factory Machines.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | null | null | null | # include <bits/stdc++.h>
# define ll long long
# define all(x) x.begin(), x.end()
# define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL)
using namespace std;
int main(){
fastio;
int n,t;
cin>>n>>t;
double s=0;
vector <int> arr(n);
for (int i=0;i<n;i++){
cin>>arr[i];
s+=1.0/arr[i];
}
long long base=(double)t/s;
long long curr=0;
multiset <pair<int,int>> rem;
for (int i=0;i<n;i++){
curr+=base/arr[i];
rem.insert({arr[i]-base%arr[i],arr[i]});
}
long long re=base;
pair<int,int> tmp={0,0};
for(;curr<t;curr++){
tmp=(*(rem.begin()));
rem.insert({tmp.first+tmp.second,tmp.second});
rem.erase(rem.begin());
}
re+=tmp.first;
cout<<re<<'\n';
return 0;
} | 22.333333 | 79 | 0.580733 | DecSP |
52c4191e9ab0ac9f7bc43628d3cf80658cd2eed3 | 888 | hpp | C++ | modules/core/source/blub/core/sharedPointer.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 96 | 2015-02-02T20:01:24.000Z | 2021-11-14T20:33:29.000Z | modules/core/source/blub/core/sharedPointer.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 12 | 2016-06-04T15:45:30.000Z | 2020-02-04T11:10:51.000Z | modules/core/source/blub/core/sharedPointer.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 19 | 2015-09-22T01:21:45.000Z | 2020-09-30T09:52:27.000Z | #ifndef BLUB_SHAREDPOINTER_HPP
#define BLUB_SHAREDPOINTER_HPP
#include <memory>
namespace blub
{
template <class T>
class sharedPointer : public std::shared_ptr<T>
{
public:
typedef std::shared_ptr<T> t_base;
sharedPointer()
{}
sharedPointer(T* ptr)
: t_base(ptr)
{}
sharedPointer(t_base ptr)
: t_base(ptr)
{}
template <class U>
sharedPointer(std::shared_ptr<U> ptr)
: t_base(ptr)
{}
template <class U>
sharedPointer<U> staticCast()
{
std::shared_ptr<U> result(std::static_pointer_cast<U>(*this));
return result;
}
T* data() const
{
return t_base::get();
}
void reset()
{
t_base::reset();
}
bool isNull() const
{
return data() == nullptr;
}
protected:
};
using std::make_shared;
}
#endif // BLUB_SHAREDPOINTER_HPP
| 13.875 | 70 | 0.584459 | qwertzui11 |
52c6ec417ea289ea46d150dfc133e091c2c36621 | 1,502 | cpp | C++ | libs/db/src/Db.cpp | romz-pl/romz-btree | 8f0634fa68c9c3245e53c81d100c1cf7a0bcac41 | [
"Apache-2.0"
] | null | null | null | libs/db/src/Db.cpp | romz-pl/romz-btree | 8f0634fa68c9c3245e53c81d100c1cf7a0bcac41 | [
"Apache-2.0"
] | null | null | null | libs/db/src/Db.cpp | romz-pl/romz-btree | 8f0634fa68c9c3245e53c81d100c1cf7a0bcac41 | [
"Apache-2.0"
] | null | null | null | #include <romz/db/Db.h>
namespace romz {
// Constructor
Db::Db(Env *env_, DbConfig &config_)
: env(env_)
, context( nullptr )
, config(config_)
{
}
// Returns the runtime-flags - the flags are "mixed" with the flags from
// the Environment
uint32_t Db::flags() const
{
// return env->flags() | config.flags;
return 0;
}
// Returns the database name
uint16_t Db::name() const
{
return config.db_name;
}
// Sets the database name; required when renaming the local proxy of
// a remote database
void Db::set_name(uint16_t name)
{
config.db_name = name;
}
// Returns the memory buffer for the key data: the per-database buffer
// if |txn| is null or temporary, otherwise the buffer from the |txn|
ByteArray &Db::key_arena(Txn */*txn*/)
{
// return (txn == 0 || ISSET(txn->flags, UPS_TXN_TEMPORARY))
// ? _key_arena
// : txn->key_arena;
throw "Db::key_arena not implemented";
}
// Returns the memory buffer for the record data: the per-database buffer
// if |txn| is null or temporary, otherwise the buffer from the |txn|
ByteArray &Db::record_arena(Txn */*txn*/)
{
// return (txn == 0 || ISSET(txn->flags, UPS_TXN_TEMPORARY))
// ? _record_arena
// : txn->record_arena;
throw "Db::record_arena not implemented";
}
void Db::add_cursor(Cursor *cursor)
{
cursor_list.push_back( cursor );
}
void Db::remove_cursor(Cursor *cursor)
{
cursor_list.remove( cursor );
// fix the linked list of cursors
}
}
| 21.768116 | 73 | 0.656458 | romz-pl |
52cd030de87354ada76e3b661018c6aeaf284b7b | 8,066 | cpp | C++ | geodrawer/spatialdatadrawer.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | geodrawer/spatialdatadrawer.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | geodrawer/spatialdatadrawer.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | #include "coverage.h"
#include "table.h"
#include "featurecoverage.h"
#include "feature.h"
#include "raster.h"
#include "range.h"
#include "itemrange.h"
#include "identifieritem.h"
#include "identifierrange.h"
#include "itemdomain.h"
#include "colorlookup.h"
#include "representation.h"
#include "drawers/attributevisualproperties.h"
#include "rootdrawer.h"
#include "spatialdatadrawer.h"
using namespace Ilwis;
using namespace Geodrawer;
SpatialDataDrawer::SpatialDataDrawer(const QString &name, DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) : ComplexDrawer(name, parentDrawer, rootdrawer, options)
{
}
std::vector<double> SpatialDataDrawer::numericAttributeValues(const QString &attribute) const
{
if (_coverage.isValid()){
if ( hasType(_coverage->ilwisType(), itFEATURE)){
IFeatureCoverage features = _coverage.as<FeatureCoverage>();
auto columnValues = features->attributeTable()->column(attribute);
std::vector<double> attribValues(columnValues.size());
int count = 0;
for(const auto& value : columnValues){
bool ok;
const double v = value.toDouble(&ok);
attribValues[count++] = ok ? v : rUNDEF;
}
return attribValues;
}
return std::vector<double>();
}
return std::vector<double>();
}
ICoverage SpatialDataDrawer::coverage() const
{
return _coverage;
}
void SpatialDataDrawer::coverage(const ICoverage &cov)
{
_coverage = cov;
_envelope = cov->envelope();
}
Envelope SpatialDataDrawer::envelope() const
{
return _envelope;
}
void SpatialDataDrawer::envelope(const Envelope &env)
{
_envelope = env;
}
VisualAttribute SpatialDataDrawer::vPropertyFeatureCoverage(const QString &attrName) const
{
VisualAttribute attr;
IFeatureCoverage features = coverage().as<FeatureCoverage>();
if ( !features.isValid()){
ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization"));
}else {
int columnIndex = features->attributeDefinitions().columnIndex(attrName);
if ( columnIndex == iUNDEF){ // test a number of fallbacks to be able to show at least something
columnIndex = features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN);
if ( columnIndex == iUNDEF){
columnIndex = features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN);
if ( columnIndex == iUNDEF){ // default to a indexeditemdomain
IIndexedIdDomain itemdom;
itemdom.prepare();
IndexedIdentifierRange *rng = new IndexedIdentifierRange("feature", features->featureCount());
itemdom->range(rng);
attr = VisualAttribute(itemdom);
}else {
attr = visualProperty(FEATUREVALUECOLUMN);
}
}else {
attr = visualProperty(COVERAGEKEYCOLUMN);
}
}
attr.setColumnIndex(columnIndex);
}
return attr;
}
VisualAttribute SpatialDataDrawer::vPropertyRasterCoverage(const QString &attrName) const
{
//TODO later when displaying rasters with attributes
VisualAttribute attr;
IRasterCoverage features = coverage().as<RasterCoverage>();
if ( !features.isValid()){
ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization"));
}else {
}
return attr;
}
VisualAttribute SpatialDataDrawer::createVisualProperty(const ColumnDefinition& coldef, int index, const IRepresentation &rpr)
{
IlwisTypes attrType = coldef.datadef().domain()->ilwisType();
VisualAttribute props(coldef.datadef().domain(),index, rpr);
if ( attrType == itNUMERICDOMAIN){
SPNumericRange numrange = coldef.datadef().range<NumericRange>();
props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution()));
} else if ( attrType == itITEMDOMAIN){
int count = coldef.datadef().domain()->range<>()->count();
props.actualRange(NumericRange(0, count - 1,1));
}
return props;
}
VisualAttribute SpatialDataDrawer::visualProperty(const QString &attrName) const
{
auto iter = _visualProperties.find(attrName) ;
if ( iter != _visualProperties.end())
return iter->second;
if ( hasType(coverage()->ilwisType(), itFEATURE)){
return vPropertyFeatureCoverage(attrName);
} else if ( hasType(coverage()->ilwisType(), itRASTER)){
return vPropertyRasterCoverage(attrName);
}
return VisualAttribute();
}
void SpatialDataDrawer::visualProperty(const QString &attrName, const VisualAttribute &properties)
{
_visualProperties[attrName] = properties;
}
std::vector<QVariant> SpatialDataDrawer::attributes(const QString &keys) const
{
std::vector<QVariant> results = ComplexDrawer::attributes(keys);
QStringList parts = keys.split("|");
for(QString& part : parts)
part.toLower();
for(const QString& part : parts){
if ( part == "visualattributenames"){
for(auto pair : _visualProperties){
results.push_back(pair.first);
}
}else {
results.push_back(attribute(part));
}
}
return results;
}
bool SpatialDataDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
if(!ComplexDrawer::prepare(prepType, options))
return false;
if ( hasType(prepType, DrawerInterface::ptMVP) && !isPrepared(DrawerInterface::ptMVP) ){
if (!_shaders.bind())
return false;
_shaders.setUniformValue("mvp",rootDrawer()->mvpMatrix());
_shaders.enableAttributeArray("mvp");
_prepared |= DrawerInterface::ptMVP;
_shaders.release();
}
return true;
}
bool SpatialDataDrawer::isVisualProperty(const QString &attName) const
{
if ( coverage()->ilwisType() == itRASTER){
if ( attName == PIXELVALUE)
return true;
}
for(auto pair : _visualProperties){
if ( pair.first == attName)
return true;
}
return false;
}
QVariant SpatialDataDrawer::attribute(const QString &key) const
{
QVariant var = ComplexDrawer::attribute(key);
if ( var.isValid())
return var;
if ( key.indexOf("visualattribute") == 0){
QStringList parts = key.split("|");
if ( parts.size() == 3){
if ( parts[1] == "representation")
var.setValue<IRepresentation>(visualProperty(parts[2]).representation());
else if ( parts[1] == "stretchrange"){
var.setValue<NumericRange>(visualProperty(parts[2]).stretchRange());
} else if ( parts[1] == "domain"){
var.setValue<IDomain>(visualProperty(parts[2]).domain());
}
}
}
else if ( key == "coverage"){
var.setValue<ICoverage>(coverage());
}
else if ( key == "envelope"){
var.setValue<Envelope>(envelope());
}
return var;
}
void SpatialDataDrawer::setAttribute(const QString &key, const QVariant &attrib)
{
ComplexDrawer::setAttribute(key, attrib);
if ( key.indexOf("visualattribute") == 0){
QStringList parts = key.split("|");
auto iter = _visualProperties.find(parts[2]);
if (iter == _visualProperties.end())
return;
if ( parts.size() == 3){
if ( parts[1] == "representation"){
IRepresentation rpr = attrib.value<IRepresentation>();
if ( rpr.isValid()){
VisualAttribute& attr = _visualProperties[parts[2]];
attr.representation(rpr);
}
}else if( parts[1] == "domain"){
IDomain dom = attrib.value<IDomain>();
if ( dom.isValid()){
VisualAttribute& attr = _visualProperties[parts[2]];
attr.domain(dom);
}
}
}
}
}
| 31.507813 | 195 | 0.626457 | ridoo |
52cde33529dd0836d6f0dc64aeab6ea8044265d3 | 1,396 | cpp | C++ | 201703/20170304/main_Kruskal.cpp | Heliovic/My-CCF_CSP-Answer | 089ce2601bee3d3d5dc463486dd4192f087aa7f0 | [
"MIT"
] | 4 | 2019-03-16T14:42:08.000Z | 2019-07-18T13:57:29.000Z | 201703/20170304/main_Kruskal.cpp | Heliovic/My_CCF-CSP_Answer | 089ce2601bee3d3d5dc463486dd4192f087aa7f0 | [
"MIT"
] | null | null | null | 201703/20170304/main_Kruskal.cpp | Heliovic/My_CCF-CSP_Answer | 089ce2601bee3d3d5dc463486dd4192f087aa7f0 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
struct Edge
{
int from, to, cost;
Edge(int f, int t, int c): from(f), to(t), cost(c) {}
};
int father[100002];
int N, M;
vector<Edge*> edges;
int GetFather(int a)
{
int b = a;
while (true)
if (father[a] == a)
break;
else
a = father[a];
while (true)
if (father[b] == a)
break;
else {
int c = b;
b = father[b];
father[c] = a;
}
return a;
}
bool cmp(Edge* e1, Edge* e2)
{
return e1->cost < e2->cost;
}
void UnionSet(int a, int b)
{
if (GetFather(a) != GetFather(b))
father[GetFather(a)] = GetFather(b);
}
int main()
{
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++)
{
int s, t, c;
scanf("%d %d %d", &s, &t, &c);
edges.push_back(new Edge(s, t, c));
}
for (int i = 0; i <= N; i++)
father[i] = i;
sort(edges.begin(), edges.end(), cmp);
int index = 0;
for (; index < M; index++)
{
Edge* e = edges[index];
if (father[e->from] == father[e->to])
continue;
else
UnionSet(e->from, e->to);
if (GetFather(1) == GetFather(N))
break;
}
printf("%d", index == M ? edges[M-1]->cost : edges[index]->cost);
return 0;
}
| 17.02439 | 69 | 0.455587 | Heliovic |
52ce589bfc26e04cfbf0e41ddd8cceebd113b120 | 2,134 | cpp | C++ | src/_leetcode/leet_132.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_132.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_132.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | /*
* ====================== leet_132.cpp ==========================
* -- tpr --
* CREATE -- 2020.07.16
* MODIFY --
* ----------------------------------------------------------
* 132. 分割回文串 II
*/
#include "innLeet.h"
#include "TreeNode1.h"
#include "ListNode.h"
namespace leet_132 {//~
// 实现两个 dp
// 第一个 用来记录,dp[len][r] 不同字符不同长度时,是否为 回文
// 第二个,用来记录,dp[i] 每个字符为结尾时,最小 分配次数
class S{
public:
int minCut( std::string s ){
if(s.empty()){ return 0; }
int N = static_cast<int>(s.size());
//=== dp 1 ===//
std::vector<std::vector<char>> dp1 (N+1, std::vector<char>(N,0));// dp1[0] 空置
// dp1[1][w]
for( int w=0; w<N; w++ ){
dp1[1][w] = 1;
}
// dp1[2][w]
for( int w=1; w<N; w++ ){// [w-1], [w]
dp1[2][w] = s[w-1]==s[w] ? 1 : 0;
}
// dp1[h][w], h>2
for( int h=3; h<=N; h++ ){
for( int w=h-1; w<N; w++ ){
dp1[h][w] = (s[w-h+1]==s[w] && dp1[h-2][w-1]==1) ? 1 : 0;
}
}
if( dp1[N][N-1]==1 ){ return 0; }// s 自己就是个完整的 回文
//cout<<"dp1: "; for( auto &cv : dp1 ){ for( char c : cv ){ cout<<(int)c<<", "; }cout<<endl; }
//=== dp 2 ===//
std::vector<int> dp2 (N, 0);
// dp2[0]=0; 一个元素时,不需要分割
for( int i=1; i<N; i++ ){
if( dp1[i+1][i]==1 ){
dp2[i]=0;
continue;
}
int mmin = INT_MAX;
for( int len=1; len<=i; len++ ){
if( dp1[len][i]==1 ){
mmin = std::min( mmin, dp2[i-len]+1 );
}
}
dp2[i] = mmin;
}
//cout<<"dp2: "; for( int i : dp2 ){ cout<<i<<", "; }cout<<endl;
return dp2.back();
}
};
//=========================================================//
void main_(){
std::string s = "1412123";
auto ret = S{}.minCut(s);
cout<<"ret:"<<ret<<endl;
debug::log( "\n~~~~ leet: 132 :end ~~~~\n" );
}
}//~
| 24.25 | 102 | 0.336926 | turesnake |
52d475886e43c9c0322281171bdf7eb0954653ac | 450 | cpp | C++ | Day 06/leetcode.cpp | tushar-nath/100-days-of-code | 860c088968521d953f5ca9222f70037e95cb4ad4 | [
"MIT"
] | null | null | null | Day 06/leetcode.cpp | tushar-nath/100-days-of-code | 860c088968521d953f5ca9222f70037e95cb4ad4 | [
"MIT"
] | null | null | null | Day 06/leetcode.cpp | tushar-nath/100-days-of-code | 860c088968521d953f5ca9222f70037e95cb4ad4 | [
"MIT"
] | null | null | null | // https://codeforces.com/problemset/problem/69/A
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[100][3];
for (int i = 0; i < n; i++)
cin >> a[i][0] >> a[i][1] >> a[i][2];
int o =0,p=0,q=0;
for (int j = 0; j < n; j++)
o+=a[j][0];
for (int k = 0; k < n; k++)
p += a[k][1];
for (int l = 0; l < n; l++)
q += a[l][2];
if (o==0&&p==0&&q==0)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
} | 18.75 | 49 | 0.466667 | tushar-nath |
52d5babc01da5095c4a108c92aa6f5d63b4dda54 | 6,453 | hpp | C++ | include/data/FluidMeta.hpp | jamesb93/flucoma-core | 3e964dd569f6fff15bd5249a705dc0da8f7b2ad8 | [
"BSD-3-Clause"
] | null | null | null | include/data/FluidMeta.hpp | jamesb93/flucoma-core | 3e964dd569f6fff15bd5249a705dc0da8f7b2ad8 | [
"BSD-3-Clause"
] | null | null | null | include/data/FluidMeta.hpp | jamesb93/flucoma-core | 3e964dd569f6fff15bd5249a705dc0da8f7b2ad8 | [
"BSD-3-Clause"
] | null | null | null | /*
Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)
Copyright 2017-2019 University of Huddersfield.
Licensed under the BSD-3 License.
See license.md file in the project root for full license information.
This project has received funding from the European Research Council (ERC)
under the European Union’s Horizon 2020 research and innovation programme
(grant agreement No 725899).
*/
/// A place to keep metaprogramming gizmos. Quite probably with links to the
/// stack overflow answer I got them from ;-)
#pragma once
#include <iterator>
#include <tuple>
#include <type_traits>
#include <utility>
namespace fluid {
/****
All() and Some() are can be used with enable_if_t to check that
variadic template arguments satisfy some condition
These are names that stroustrup uses, however C++17 introduces
'conjunction' & 'disjunction' that seem to do the same, but are defined
slightly differently
So, one example of use is to make sure that all variadic arguments can
be converted to a given type. Let's say size_t, and again use our function
foo that returns int
enable_if_t<All(std::is_convertible<size_t, Args>::value...),int>
foo(){...
We use these for getting different versions of operator() for arguments
of indices and of slice specifications.
Both All() and Some() use the common trick with variadic template args of
recursing through the list. You'll see in both cases a 'base case' declared
as constexpr, which is the function without any args. Then, the template below
calls itself, consuming one more arg from the list at a time.
****/
// Base case
constexpr bool all() { return true; }
// Recurse
template <typename... Args>
constexpr bool all(bool b, Args... args)
{
return b && all(args...);
}
// Base case
constexpr bool some() { return false; }
// Recurse
template <typename... Args>
constexpr bool some(bool b, Args... args)
{
return b || some(args...);
}
/****
Does the iterator of this type fulfill the given itertator category?
Used by FluidTensorSlice to ensure that we have at least a ForwardIterator
in its constructor that takes a range
****/
template <typename Iterator, typename IteratorTag>
using IsIteratorType =
std::is_base_of<IteratorTag,
typename std::iterator_traits<Iterator>::iterator_category>;
// Detcting constexpr: https://stackoverflow.com/a/50169108
// p() here could be anything <- well, not really: only certain things are
// recognised as constant expressions Relies on the fact that the narrowing
// conversion in the first template will be an error except for constant
// expressions
template <int (*p)()>
std::true_type isConstexprImpl(decltype(int{(p(), 0U)}));
template <int (*p)()>
std::false_type isConstexprImpl(...);
template <int (*p)()>
using is_constexpr = decltype(isConstexprImpl<p>(0));
template <class T, template <typename...> class Template>
struct isSpecialization : std::false_type
{};
template <template <typename...> class Template, typename... Args>
struct isSpecialization<Template<Args...>, Template> : std::true_type
{};
////////////////////////////////////////////////////////////////////////////////
// Thank you https://en.cppreference.com/w/cpp/experimental/is_detected
namespace impl {
template <typename... Ts>
using void_t = void;
template <class Default, class AlwaysVoid, template <class...> class Op,
class... Args>
struct Detector
{
using value_t = std::false_type;
using type = Default;
};
template <class Default, template <class...> class Op, class... Args>
struct Detector<Default, void_t<Op<Args...>>, Op, Args...>
{
// Note that std::void_t is a C++17 feature
using value_t = std::true_type;
using type = Op<Args...>;
};
} // namespace impl
struct Nonesuch
{
~Nonesuch() = delete;
Nonesuch(Nonesuch const&) = delete;
void operator=(Nonesuch const&) = delete;
};
template <template <class...> class Op, class... Args>
using isDetected =
typename impl::Detector<Nonesuch, void, Op, Args...>::value_t;
template <template <class...> class Op, class... Args>
using Detected_t = typename impl::Detector<Nonesuch, void, Op, Args...>::type;
template <class Default, template <class...> class Op, class... Args>
using DetectedOr = impl::Detector<Default, void, Op, Args...>;
// Tuple for each
template <typename Tuple, typename F, typename... Args, size_t... Is>
void ForEachImpl(Tuple&& tuple, F&& f, std::index_sequence<Is...>,
Args&&... args)
{
// Nice trick from Louis Dionne makes this more readble;
using swallow = int[];
(void) swallow{1, (f(std::get<Is>(std::forward<Tuple>(tuple)),
std::forward<Args>(args)...),
void(), int{})...};
}
template <typename Tuple, typename F, typename... Args, size_t... Is>
void ForEachIndexImpl(Tuple&& tuple, F&& f, std::index_sequence<Is...>,
Args&&... args)
{
// Nice trick from Louis Dionne makes this more readble;
using swallow = int[];
(void) swallow{
1, (f(std::get<Is>(std::forward<Tuple>(tuple)),
std::integral_constant<size_t, Is>{}, std::forward<Args>(args)...),
void(), int{})...};
}
template <typename Tuple, typename F, typename... Args>
void ForEach(Tuple&& tuple, F&& f, Args&&... args)
{
constexpr size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
ForEachImpl(std::forward<Tuple>(tuple), std::forward<F>(f),
std::make_index_sequence<N>{}, std::forward<Args>(args)...);
}
template <typename Tuple, typename F, typename Indices, typename... Args>
void ForThese(Tuple&& tuple, F&& f, Indices idx, Args&&... args)
{
ForEachIndexImpl(std::forward<Tuple>(tuple), std::forward<F>(f), idx,
std::forward<Args>(args)...);
}
namespace impl {
template <std::size_t... Is>
constexpr auto indexSequenceReverse(std::index_sequence<Is...> const&)
-> decltype(std::index_sequence<sizeof...(Is) - 1U - Is...>{});
template <std::size_t N>
using ReverseIndexSequence =
decltype(indexSequenceReverse(std::make_index_sequence<N>{}));
} // namespace impl
template <typename Tuple, typename F, typename... Args>
void ReverseForEach(Tuple&& tuple, F&& f, Args&&... args)
{
constexpr size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
ForEachIndexImpl(std::forward<Tuple>(tuple), std::forward<F>(f),
impl::ReverseIndexSequence<N>{}, std::forward<Args>(args)...);
}
} // namespace fluid
| 32.923469 | 80 | 0.683093 | jamesb93 |
52dc40a0a0afda91637797976604b70381f72c07 | 6,150 | cpp | C++ | src/brdf_lut/main.cpp | diharaw/AssetConverter | 88b53d0d01795e5e112853304a9dbf3873f25fe6 | [
"MIT"
] | 14 | 2019-05-09T12:34:55.000Z | 2021-12-27T09:23:28.000Z | src/brdf_lut/main.cpp | diharaw/AssetCore | ddde1eb829f8a1b5f94357f94d8e23108c0c7962 | [
"MIT"
] | null | null | null | src/brdf_lut/main.cpp | diharaw/AssetCore | ddde1eb829f8a1b5f94357f94d8e23108c0c7962 | [
"MIT"
] | null | null | null | #include <exporter/image_exporter.h>
#include <common/filesystem.h>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <glm.hpp>
#include <chrono>
#define BRDF_LUT_SIZE 512
const float PI = 3.14159265359;
// ----------------------------------------------------------------------------
// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html
// efficient VanDerCorpus calculation.
float radical_inverse_vdc(uint32_t bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}
// ----------------------------------------------------------------------------
glm::vec2 hammersley(uint32_t i, uint32_t N)
{
return glm::vec2(float(i) / float(N), radical_inverse_vdc(i));
}
// ----------------------------------------------------------------------------
glm::vec3 importance_sample_ggx(glm::vec2 Xi, glm::vec3 N, float roughness)
{
float a = roughness * roughness;
float phi = 2.0 * PI * Xi.x;
float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
// from spherical coordinates to cartesian coordinates - halfway vector
glm::vec3 H;
H.x = cos(phi) * sinTheta;
H.y = sin(phi) * sinTheta;
H.z = cosTheta;
// from tangent-space H vector to world-space sample vector
glm::vec3 up = abs(N.z) < 0.999f ? glm::vec3(0.0f, 0.0f, 1.0f) : glm::vec3(1.0f, 0.0f, 0.0f);
glm::vec3 tangent = normalize(cross(up, N));
glm::vec3 bitangent = cross(N, tangent);
glm::vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;
return normalize(sampleVec);
}
// ----------------------------------------------------------------------------
float geometry_schlick_ggx(float NdotV, float roughness)
{
// note that we use a different k for IBL
float a = roughness;
float k = (a * a) / 2.0f;
float nom = NdotV;
float denom = NdotV * (1.0f - k) + k;
return nom / denom;
}
// ----------------------------------------------------------------------------
float geometry_smith(glm::vec3 N, glm::vec3 V, glm::vec3 L, float roughness)
{
float NdotV = std::max(glm::dot(N, V), 0.0f);
float NdotL = std::max(glm::dot(N, L), 0.0f);
float ggx2 = geometry_schlick_ggx(NdotV, roughness);
float ggx1 = geometry_schlick_ggx(NdotL, roughness);
return ggx1 * ggx2;
}
// ----------------------------------------------------------------------------
glm::vec2 integrate_brdf(float NdotV, float roughness)
{
glm::vec3 V;
V.x = sqrt(1.0f - NdotV * NdotV);
V.y = 0.0f;
V.z = NdotV;
float A = 0.0f;
float B = 0.0f;
glm::vec3 N = glm::vec3(0.0f, 0.0f, 1.0f);
const uint32_t SAMPLE_COUNT = 1024u;
for (uint32_t i = 0u; i < SAMPLE_COUNT; ++i)
{
// generates a sample vector that's biased towards the
// preferred alignment direction (importance sampling).
glm::vec2 Xi = hammersley(i, SAMPLE_COUNT);
glm::vec3 H = importance_sample_ggx(Xi, N, roughness);
glm::vec3 L = glm::normalize(2.0f * glm::dot(V, H) * H - V);
float NdotL = std::max(L.z, 0.0f);
float NdotH = std::max(H.z, 0.0f);
float VdotH = std::max(dot(V, H), 0.0f);
if (NdotL > 0.0)
{
float G = geometry_smith(N, V, L, roughness);
float G_Vis = (G * VdotH) / (NdotH * NdotV);
float Fc = pow(1.0 - VdotH, 5.0);
A += (1.0 - Fc) * G_Vis;
B += Fc * G_Vis;
}
}
A /= float(SAMPLE_COUNT);
B /= float(SAMPLE_COUNT);
return glm::vec2(A, B);
}
// ----------------------------------------------------------------------------
void print_usage()
{
printf("usage: brdf_lut [outpath]\n\n");
}
// ----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
if (argc == 1)
{
print_usage();
return 1;
}
else
{
std::string output = argv[1];
if (output.size() == 0)
{
printf("ERROR: Invalid output path: %s\n\n", argv[1]);
print_usage();
return 1;
}
auto start = std::chrono::high_resolution_clock::now();
ast::ImageExportOptions options;
options.compression = ast::COMPRESSION_NONE;
options.pixel_type = ast::PIXEL_TYPE_FLOAT32;
options.normal_map = false;
options.flip_green = false;
options.output_mips = 0;
std::string filename = filesystem::get_filename(output);
std::string path = filesystem::get_file_path(output);
if (path.size() > 0)
options.path = path;
else
options.path = "";
ast::Image img;
img.name = filename;
img.allocate(ast::PIXEL_TYPE_FLOAT32, BRDF_LUT_SIZE, BRDF_LUT_SIZE, 2, 1, 1);
glm::vec2* pixels = (glm::vec2*)img.data[0][0].data;
#ifndef __APPLE__
# pragma omp parallel for
#endif
for (int32_t y = 0; y < BRDF_LUT_SIZE; y++)
{
for (int32_t x = 0; x < BRDF_LUT_SIZE; x++)
{
glm::vec2 tex_coord = glm::vec2(float(x), float(y)) / float(BRDF_LUT_SIZE - 1);
pixels[(BRDF_LUT_SIZE - 1 - y) * BRDF_LUT_SIZE + x] = integrate_brdf(tex_coord.x, tex_coord.y);
}
}
if (!export_image(img, options))
printf("Failed to output BRDF LUT: %s\n", output.c_str());
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time = finish - start;
printf("\nSuccessfully generated BRDF LUT in %f seconds\n\n", time.count());
return 0;
}
}
// ---------------------------------------------------------------------------- | 29.854369 | 111 | 0.505366 | diharaw |
52e0cd5178776c5f0d173f6c9a0793429b1d8974 | 275 | cpp | C++ | UpdateSystemTest/src/UpdateManagerTestWorker.cpp | ProtocolONE/cord.update-system | ec14aa3210f41f788d2ea3229d36bff7f0b327d0 | [
"Apache-2.0"
] | 1 | 2019-08-07T06:13:57.000Z | 2019-08-07T06:13:57.000Z | UpdateSystemTest/src/UpdateManagerTestWorker.cpp | ProtocolONE/cord.update-system | ec14aa3210f41f788d2ea3229d36bff7f0b327d0 | [
"Apache-2.0"
] | null | null | null | UpdateSystemTest/src/UpdateManagerTestWorker.cpp | ProtocolONE/cord.update-system | ec14aa3210f41f788d2ea3229d36bff7f0b327d0 | [
"Apache-2.0"
] | null | null | null | #include "UpdateManagerTestWorker.h"
UpdateManagerTestWorker::UpdateManagerTestWorker(QObject *parrent)
: QObject(parrent)
{
}
UpdateManagerTestWorker::~UpdateManagerTestWorker(void)
{
}
void UpdateManagerTestWorker::doSimpleTest()
{
this->_target->checkUpdate();
}
| 15.277778 | 66 | 0.785455 | ProtocolONE |
52e3b161ce1df71096b08c94c16d6054e425e4ee | 5,735 | cpp | C++ | test/src/TestSort.cpp | abc1199281/DS_Common | 6b11dc19f2d3b33d19af315dd800aa37f89e7ae2 | [
"MIT"
] | null | null | null | test/src/TestSort.cpp | abc1199281/DS_Common | 6b11dc19f2d3b33d19af315dd800aa37f89e7ae2 | [
"MIT"
] | null | null | null | test/src/TestSort.cpp | abc1199281/DS_Common | 6b11dc19f2d3b33d19af315dd800aa37f89e7ae2 | [
"MIT"
] | null | null | null | // TestTime.cpp
/* Header */
//====================================================================================================
#include <iostream>
#include <string>
#include <DS_Common/Test/UnitTest.h>
#include <DS_Common/Time/Timer.h>
#include <DS_Common/Sort/HeapSort.h>
#include <DS_Common/Sort/InsertionSort.h>
#include <DS_Common/Sort/MergeSort.h>
#include <DS_Common/Sort/QuickSort.h>
//====================================================================================================
/* Definition */
//====================================================================================================
namespace UnitTest {
class TestSort :public UnitTest::Test {
protected:
std::string MODULE_NAME = "Sort";
DS_Common::Time::Timer *timer;
int *seq;
int seq_size;
protected: //function
//--------------------------------------------------------------------------------------------
virtual void SetUp()
{
timer = new DS_Common::Time::Timer();
seq = NULL;
}
//--------------------------------------------------------------------------------------------
virtual void TearDown()
{
timer->~Timer();
}
//--------------------------------------------------------------------------------------------
bool isSorted(int *seq, int n)
{
for (int i = 0; i < n - 1; i++)
{
if (seq[i] > seq[i + 1])
{
for (int j = 0; j < n; j++)
std::cout << seq[j] << "," << std::endl;
return false;
}
}
return true;
};
//--------------------------------------------------------------------------------------------
void initialize(const int n)
{
srand(time(NULL));
if (!seq)
{
free(seq);
seq = NULL;
}
seq = (int*)malloc(n * sizeof(int));
seq_size = n;
for (int i = 0; i < n; i++)
{
seq[i] = rand();
}
};
//--------------------------------------------------------------------------------------------
int* copySeq()
{
int *copySeq = (int*)malloc(seq_size *sizeof(int));
for (int i = 0; i < seq_size; i++)
copySeq[i] = seq[i];
return copySeq;
}
//--------------------------------------------------------------------------------------------
};
}
//====================================================================================================
/* Function */
//====================================================================================================
namespace UnitTest {
//------------------------------------------------------------------------------------------------
TEST_F(TestSort, TestAvgCase) {
/*
std::vector<int> test_size = {5, 50, 100,1000,10000};
std::vector<int> repeated_loop = { 10000, 10000,10000,1000 ,100};
//std::vector<int> test_size = { 10 };
//std::vector<int> repeated_loop = { 10000};
int number_methods = 4;
std::vector<double> elapsed_time(number_methods, 0);
for (int j = 0; j < test_size.size();j++) // size
{
for (int i = 0; i < repeated_loop[j]; i++)
{
initialize(test_size[j]); // initialize
int *test_seq;
// Quick Sort
test_seq = copySeq(); timer->start();
DS_Common::QuickSort(test_seq, 0, seq_size - 1); // sort
elapsed_time[0] += timer->getMicroSec();
EXPECT_TRUE(isSorted(test_seq, seq_size));
free(test_seq); test_seq = NULL;
//// Recursive Merge Sort (not very well defined.)
//int *link = (int*)calloc(seq_size+1, sizeof(int));
//for (int i = 0; i < seq_size+1; i++)
// link[i] = -1;
//test_seq = copySeq(); timer->start();
//DS_Common::rMergeSort(test_seq,link, 0,seq_size-1); // sort
//elapsed_time[1] += timer->getMicroSec();
////EXPECT_TRUE(isSorted(test_seq, seq_size));
//free(test_seq); test_seq = NULL;
//free(link); link = NULL;
//Recursive Merge Sort (with copy)
test_seq = copySeq(); timer->start();
DS_Common::rMergeSort_copy(test_seq,0, seq_size - 1); // sort
elapsed_time[1] += timer->getMicroSec();
EXPECT_TRUE(isSorted(test_seq, seq_size));
free(test_seq); test_seq = NULL;
// HeapSort (std::priority_queue is roughly quick sort)
test_seq = copySeq();
timer->start();
//DS_Common::HeapSort(test_seq, seq_size); // sort insert and delete 2*O(nlogn)
DS_Common::HeapSortNaive(test_seq, seq_size); // sort
elapsed_time[2] += timer->getMicroSec();
EXPECT_TRUE(isSorted(test_seq, seq_size));
free(test_seq); test_seq = NULL;
// Insertion Sort
test_seq = copySeq();
timer->start();
DS_Common::InsertionSort(test_seq, seq_size); // sort
elapsed_time[3] += timer->getMicroSec();
EXPECT_TRUE(isSorted(test_seq, seq_size));
free(test_seq); test_seq = NULL;
}
std::cout << "Size: " << test_size[j] << std::endl;
for (int k = 0; k < number_methods; k++)
{
elapsed_time[k] /= repeated_loop[k];
std::cout << "elapsed_time of " << k << " : " << elapsed_time[k] << std::endl;;
}
std::cout << std::endl;
} */
}
//------------------------------------------------------------------------------------------------
TEST_F(TestSort, Timer_start) {
//std::cout << "initial timer is (ms) " << timer->getMSec() <<
// ", (sec) " << timer->getSec() << std::endl;
//// just elapse time.
//system("pause");
//std::cout << "current timer is (ms) " << timer->getMSec() <<
// ", (sec) " << timer->getSec() << std::endl;
//timer->start();
//std::cout << "current timer after start() is (ms) " << timer->getMSec() <<
// ", (sec) " << timer->getSec() << std::endl;
}
//------------------------------------------------------------------------------------------------
}
//==================================================================================================== | 30.026178 | 102 | 0.434176 | abc1199281 |
52e6777d88ca817fe1fc50ccecd4afe813a29378 | 24,394 | cpp | C++ | APEX_1.4/module/destructible/fracture/Core/CompoundCreatorBase.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | APEX_1.4/module/destructible/fracture/Core/CompoundCreatorBase.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | APEX_1.4/module/destructible/fracture/Core/CompoundCreatorBase.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2018-2019 NVIDIA Corporation. All rights reserved.
#include "RTdef.h"
#if RT_COMPILE
#include "CompoundCreatorBase.h"
#include <algorithm>
#include <PxAssert.h>
namespace nvidia
{
namespace fracture
{
namespace base
{
using namespace nvidia;
int CompoundCreator::tetFaceIds[4][3] = {{0,1,3},{1,2,3},{2,0,3},{0,2,1}};
int CompoundCreator::tetEdgeVerts[6][2] = {{0,1},{1,2},{2,0},{0,3},{1,3},{2,3}};
int CompoundCreator::tetFaceEdges[4][3] = {{0,4,3},{1,5,4},{2,3,5},{0,2,1}};
#define CONVEX_THRESHOLD (PxPi + 0.05f)
// -----------------------------------------------------------------------------
void CompoundCreator::createTorus(float r0, float r1, int numSegs0, int numSegs1, const PxTransform *trans)
{
mGeom.clear();
CompoundGeometry::Convex c;
PxVec3 nr0,nr1,nz;
nz = PxVec3(0.0f, 0.0f, 1.0f);
PxVec3 p,n;
PxTransform t = PxTransform(PxIdentity);
if (trans)
t = *trans;
nvidia::Array<PxVec3> normals;
float dphi0 = PxTwoPi / (float)numSegs0;
float dphi1 = PxTwoPi / (float)numSegs1;
for (int i = 0; i < numSegs0; i++) {
nr0 = PxVec3(PxCos(i*dphi0), PxSin(i*dphi0), 0.0f);
nr1 = PxVec3(PxCos((i+1)*dphi0), PxSin((i+1)*dphi0), 0.0f);
mGeom.initConvex(c);
c.numVerts = 2*numSegs1;
normals.clear();
for (int j = 0; j < numSegs1; j++) {
p = nr0 * (r0 + r1 * PxCos(j*dphi1)) + nz * r1 * PxSin(j*dphi1);
mGeom.vertices.pushBack(t.transform(p));
n = nr0 * (PxCos(j*dphi1)) + nz * PxSin(j*dphi1);
normals.pushBack(t.rotate(n));
p = nr1 * (r0 + r1 * PxCos(j*dphi1)) + nz * r1 * PxSin(j*dphi1);
mGeom.vertices.pushBack(t.transform(p));
n = nr1 * (PxCos(j*dphi1)) + nz * PxSin(j*dphi1);
normals.pushBack(t.rotate(n));
}
c.numFaces = 2 + numSegs1;
mGeom.indices.pushBack(numSegs1); // face size
mGeom.indices.pushBack(CompoundGeometry::FF_INVISIBLE); // face flags
for (int j = 0; j < numSegs1; j++)
mGeom.indices.pushBack(2*j);
mGeom.indices.pushBack(numSegs1); // face size
mGeom.indices.pushBack(CompoundGeometry::FF_INVISIBLE); // face flags
for (int j = 0; j < numSegs1; j++) {
mGeom.indices.pushBack(2*(numSegs1-1-j) + 1);
}
for (int j = 0; j < numSegs1; j++) {
int k = (j+1)%numSegs1;
mGeom.indices.pushBack(4); // face size
mGeom.indices.pushBack(CompoundGeometry::FF_OBJECT_SURFACE | CompoundGeometry::FF_HAS_NORMALS);
int i0 = 2*j;
int i1 = 2*j+1;
int i2 = 2*k+1;
int i3 = 2*k;
mGeom.indices.pushBack(i0);
mGeom.indices.pushBack(i1);
mGeom.indices.pushBack(i2);
mGeom.indices.pushBack(i3);
mGeom.normals.pushBack(normals[(uint32_t)i0]);
mGeom.normals.pushBack(normals[(uint32_t)i1]);
mGeom.normals.pushBack(normals[(uint32_t)i2]);
mGeom.normals.pushBack(normals[(uint32_t)i3]);
}
c.numNeighbors = 2;
mGeom.neighbors.pushBack((i + (numSegs0-1)) % numSegs0);
mGeom.neighbors.pushBack((i + 1) % numSegs0);
mGeom.convexes.pushBack(c);
}
}
// -----------------------------------------------------------------------------
void CompoundCreator::createCylinder(float r, float h, int numSegs, const PxTransform *trans)
{
PxTransform t = PxTransform(PxIdentity);
if (trans)
t = *trans;
mGeom.clear();
CompoundGeometry::Convex c;
mGeom.initConvex(c);
float dphi = PxTwoPi / (float)numSegs;
c.numVerts = 2*numSegs;
mGeom.vertices.resize((uint32_t)c.numVerts);
for (int i = 0; i < numSegs; i++) {
PxVec3 p0(r * PxCos(i*dphi), r * PxSin(i*dphi), -0.5f * h);
PxVec3 p1(r * PxCos(i*dphi), r * PxSin(i*dphi), 0.5f * h);
mGeom.vertices[2*(uint32_t)i] = t.transform(p0);
mGeom.vertices[2*(uint32_t)i+1] = t.transform(p1);
}
c.numFaces = 2 + numSegs;
mGeom.indices.pushBack(numSegs);
mGeom.indices.pushBack(CompoundGeometry::FF_OBJECT_SURFACE);
for (int i = 0; i < numSegs; i++)
mGeom.indices.pushBack(2*(numSegs-1-i));
mGeom.indices.pushBack(numSegs);
mGeom.indices.pushBack(CompoundGeometry::FF_OBJECT_SURFACE);
for (int i = 0; i < numSegs; i++)
mGeom.indices.pushBack(2*i+1);
for (int i = 0; i < numSegs; i++) {
int j = (i+1) % numSegs;
PxVec3 n0(PxCos(i*dphi),PxSin(i*dphi),0.0f);
PxVec3 n1(PxCos(j*dphi),PxSin(j*dphi),0.0f);
n0 = t.rotate(n0);
n1 = t.rotate(n1);
//n0*=-1;
//n1*=-1;
mGeom.indices.pushBack(4);
mGeom.indices.pushBack(CompoundGeometry::FF_OBJECT_SURFACE | CompoundGeometry::FF_HAS_NORMALS);
mGeom.indices.pushBack(2*i);
mGeom.indices.pushBack(2*j);
mGeom.indices.pushBack(2*j+1);
mGeom.indices.pushBack(2*i+1);
mGeom.normals.pushBack(n0);
mGeom.normals.pushBack(n1);
mGeom.normals.pushBack(n1);
mGeom.normals.pushBack(n0);
}
mGeom.convexes.pushBack(c);
}
// -----------------------------------------------------------------------------
void CompoundCreator::createBox(const PxVec3 &dims, const PxTransform *trans)
{
PxTransform t = PxTransform(PxIdentity);
if (trans)
t = *trans;
mGeom.clear();
CompoundGeometry::Convex c;
mGeom.initConvex(c);
c.numVerts = 8;
mGeom.vertices.clear();
mGeom.vertices.pushBack(t.transform(PxVec3(-0.5f * dims.x, -0.5f * dims.y, -0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3( 0.5f * dims.x, -0.5f * dims.y, -0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3( 0.5f * dims.x, 0.5f * dims.y, -0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3(-0.5f * dims.x, 0.5f * dims.y, -0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3(-0.5f * dims.x, -0.5f * dims.y, 0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3( 0.5f * dims.x, -0.5f * dims.y, 0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3( 0.5f * dims.x, 0.5f * dims.y, 0.5f * dims.z)));
mGeom.vertices.pushBack(t.transform(PxVec3(-0.5f * dims.x, 0.5f * dims.y, 0.5f * dims.z)));
static int faceIds[6][4] = {{0,1,5,4},{1,2,6,5},{2,3,7,6},{3,0,4,7},{0,3,2,1},{4,5,6,7}};
c.numFaces = 6;
for (int i = 0; i < 6; i++) {
mGeom.indices.pushBack(4);
mGeom.indices.pushBack(CompoundGeometry::FF_OBJECT_SURFACE);
for (int j = 0; j < 4; j++)
mGeom.indices.pushBack(faceIds[i][j]);
}
mGeom.convexes.pushBack(c);
}
// -----------------------------------------------------------------------------
void CompoundCreator::createSphere(const PxVec3 &dims, int resolution, const PxTransform *trans)
{
PxTransform t = PxTransform(PxIdentity);
if (trans)
t = *trans;
if (resolution < 2) resolution = 2;
int numSegs0 = 2*resolution;
int numSegs1 = resolution;
float rx = 0.5f * dims.x;
float ry = 0.5f * dims.y;
float rz = 0.5f * dims.z;
mGeom.clear();
CompoundGeometry::Convex c;
mGeom.initConvex(c);
float dphi = PxTwoPi / (float)numSegs0;
float dteta = PxPi / (float)numSegs1;
PxVec3 p, n;
for (int i = 1; i < numSegs1; i++) {
for (int j = 0; j < numSegs0; j++) {
float phi = j * dphi;
float teta = -PxHalfPi + i * dteta;
p = PxVec3(PxCos(phi)*PxCos(teta), PxSin(phi)*PxCos(teta), PxSin(teta));
mGeom.vertices.pushBack(PxVec3(p.x * rx, p.y * ry, p.z * rz));
}
}
int bottomNr = (int32_t)mGeom.vertices.size();
mGeom.vertices.pushBack(PxVec3(0.0f, 0.0f, -rz));
int topNr = (int32_t)mGeom.vertices.size();
mGeom.vertices.pushBack(PxVec3(0.0f, 0.0f, +rz));
c.numVerts = (int32_t)mGeom.vertices.size();
for (int i = 0; i < numSegs1-2; i++) {
for (int j = 0; j < numSegs0; j++) {
mGeom.indices.pushBack(4); // face size
mGeom.indices.pushBack(CompoundGeometry::FF_HAS_NORMALS | CompoundGeometry::FF_OBJECT_SURFACE);
int i0 = i*numSegs0 + j;
int i1 = i*numSegs0 + (j+1)%numSegs0;
int i2 = (i+1)*numSegs0 + (j+1)%numSegs0;
int i3 = (i+1)*numSegs0 + j;
mGeom.indices.pushBack(i0);
mGeom.indices.pushBack(i1);
mGeom.indices.pushBack(i2);
mGeom.indices.pushBack(i3);
n = mGeom.vertices[(uint32_t)i0]; n.normalize(); mGeom.normals.pushBack(n);
n = mGeom.vertices[(uint32_t)i1]; n.normalize(); mGeom.normals.pushBack(n);
n = mGeom.vertices[(uint32_t)i2]; n.normalize(); mGeom.normals.pushBack(n);
n = mGeom.vertices[(uint32_t)i3]; n.normalize(); mGeom.normals.pushBack(n);
c.numFaces++;
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < numSegs0; j++) {
mGeom.indices.pushBack(3); // face size
mGeom.indices.pushBack(CompoundGeometry::FF_HAS_NORMALS | CompoundGeometry::FF_OBJECT_SURFACE);
int i0,i1,i2;
if (i == 0) {
i0 = j;
i1 = bottomNr;
i2 = (j+1)%numSegs0;
}
else {
i0 = (numSegs1-2)*numSegs0 + j;
i1 = (numSegs1-2)*numSegs0 + (j+1)%numSegs0;
i2 = topNr;
}
mGeom.indices.pushBack(i0);
mGeom.indices.pushBack(i1);
mGeom.indices.pushBack(i2);
n = mGeom.vertices[(uint32_t)i0]; n.normalize(); mGeom.normals.pushBack(n);
n = mGeom.vertices[(uint32_t)i1]; n.normalize(); mGeom.normals.pushBack(n);
n = mGeom.vertices[(uint32_t)i2]; n.normalize(); mGeom.normals.pushBack(n);
c.numFaces++;
}
}
mGeom.convexes.pushBack(c);
}
// -----------------------------------------------------------------------------
void CompoundCreator::fromTetraMesh(const nvidia::Array<PxVec3> &tetVerts, const nvidia::Array<int> &tetIndices)
{
mTetVertices = tetVerts;
mTetIndices = tetIndices;
deleteColors();
computeTetNeighbors();
computeTetEdges();
colorTets();
colorsToConvexes();
}
// -----------------------------------------------------------------------------
void CompoundCreator::computeTetNeighbors()
{
uint32_t numTets = mTetIndices.size() / 4;
struct TetFace {
void init(int i0, int i1, int i2, int faceNr, int tetNr) {
if (i0 > i1) { int i = i0; i0 = i1; i1 = i; }
if (i1 > i2) { int i = i1; i1 = i2; i2 = i; }
if (i0 > i1) { int i = i0; i0 = i1; i1 = i; }
this->i0 = i0; this->i1 = i1; this->i2 = i2;
this->faceNr = faceNr; this->tetNr = tetNr;
}
bool operator < (const TetFace &f) const {
if (i0 < f.i0) return true;
if (i0 > f.i0) return false;
if (i1 < f.i1) return true;
if (i1 > f.i1) return false;
return i2 < f.i2;
}
bool operator == (const TetFace &f) const {
return i0 == f.i0 && i1 == f.i1 && i2 == f.i2;
}
int i0,i1,i2;
int faceNr, tetNr;
};
nvidia::Array<TetFace> faces(numTets * 4);
for (uint32_t i = 0; i < numTets; i++) {
int ids[4];
ids[0] = mTetIndices[4*i];
ids[1] = mTetIndices[4*i+1];
ids[2] = mTetIndices[4*i+2];
ids[3] = mTetIndices[4*i+3];
for (uint32_t j = 0; j < 4; j++) {
int i0 = ids[(uint32_t)tetFaceIds[j][0]];
int i1 = ids[(uint32_t)tetFaceIds[j][1]];
int i2 = ids[(uint32_t)tetFaceIds[j][2]];
faces[4*i+j].init(i0,i1,i2, (int32_t)j, (int32_t)i);
}
}
std::sort(faces.begin(), faces.end());
mTetNeighbors.clear();
mTetNeighbors.resize(numTets * 4, -1);
uint32_t i = 0;
while (i < faces.size()) {
TetFace &f0 = faces[i];
i++;
if (i < faces.size() && faces[i] == f0) {
TetFace &f1 = faces[i];
mTetNeighbors[uint32_t(4*f0.tetNr + f0.faceNr)] = f1.tetNr;
mTetNeighbors[uint32_t(4*f1.tetNr + f1.faceNr)] = f0.tetNr;
while (i < faces.size() && faces[i] == f0)
i++;
}
}
}
// -----------------------------------------------------------------------------
void CompoundCreator::computeTetEdges()
{
uint32_t numTets = mTetIndices.size() / 4;
struct SortEdge {
void init(int i0, int i1, int edgeNr, int tetNr) {
if (i0 < i1) { this->i0 = i0; this->i1 = i1; }
else { this->i0 = i1; this->i1 = i0; }
this->edgeNr = edgeNr; this->tetNr = tetNr;
}
bool operator < (const SortEdge &e) const {
if (i0 < e.i0) return true;
if (i0 > e.i0) return false;
return i1 < e.i1;
}
bool operator == (const SortEdge &e) const {
return i0 == e.i0 && i1 == e.i1;
}
int i0,i1;
int edgeNr, tetNr;
};
nvidia::Array<SortEdge> edges(numTets * 6);
for (uint32_t i = 0; i < numTets; i++) {
int ids[4];
ids[0] = mTetIndices[4*i];
ids[1] = mTetIndices[4*i+1];
ids[2] = mTetIndices[4*i+2];
ids[3] = mTetIndices[4*i+3];
for (uint32_t j = 0; j < 6; j++) {
int i0 = ids[(uint32_t)tetEdgeVerts[j][0]];
int i1 = ids[(uint32_t)tetEdgeVerts[j][1]];
edges[6*i + j].init(i0,i1, (int32_t)j, (int32_t)i);
}
}
std::sort(edges.begin(), edges.end());
mTetEdgeNrs.clear();
mTetEdgeNrs.resize(numTets * 6, -1);
mTetEdges.clear();
mEdgeTetNrs.clear();
mEdgeTetAngles.clear();
TetEdge te;
struct ChainVert {
int adjVert0;
int adjVert1;
int tet0;
int tet1;
float dihed0;
float dihed1;
int mark;
};
ChainVert cv;
cv.mark = 0;
nvidia::Array<ChainVert> chainVerts(mTetVertices.size(), cv);
nvidia::Array<int> chainVertNrs;
int mark = 1;
uint32_t i = 0;
while (i < edges.size()) {
SortEdge &e0 = edges[i];
int edgeNr = (int32_t)mTetEdges.size();
te.init(e0.i0, e0.i1);
te.firstTet = (int32_t)mEdgeTetNrs.size();
te.numTets = 0;
mark++;
chainVertNrs.clear();
do {
SortEdge &e = edges[i];
mTetEdgeNrs[uint32_t(6 * e.tetNr + e.edgeNr)] = edgeNr;
int i2 = -1;
int i3 = -1;
for (uint32_t j = 0; j < 4; j++) {
int id = mTetIndices[4 * (uint32_t)e.tetNr + j];
if (id != e0.i0 && id != e0.i1) {
if (i2 < 0) i2 = id;
else i3 = id;
}
}
PX_ASSERT(i2 >= 0 && i3 >= 0);
// dihedral angle at edge
PxVec3 &p0 = mTetVertices[(uint32_t)e0.i0];
PxVec3 &p1 = mTetVertices[(uint32_t)e0.i1];
PxVec3 &p2 = mTetVertices[(uint32_t)i2];
PxVec3 &p3 = mTetVertices[(uint32_t)i3];
PxVec3 n2 = (p1-p0).cross(p2-p0); n2.normalize();
if ((p3-p0).dot(n2) > 0.0f) n2 = -n2;
PxVec3 n3 = (p1-p0).cross(p3-p0); n3.normalize();
if ((p2-p0).dot(n3) > 0.0f) n3 = -n3;
float dot = n2.dot(n3);
float dihed = PxPi - PxAcos(dot);
// chain for ordering tets of edge correctly
ChainVert &cv2 = chainVerts[(uint32_t)i2];
ChainVert &cv3 = chainVerts[(uint32_t)i3];
if (cv2.mark != mark) { cv2.adjVert0 = -1; cv2.adjVert1 = -1; cv2.mark = mark; }
if (cv3.mark != mark) { cv3.adjVert0 = -1; cv3.adjVert1 = -1; cv3.mark = mark; }
if (cv2.adjVert0 < 0) { cv2.adjVert0 = i3; cv2.tet0 = e.tetNr; cv2.dihed0 = dihed; }
else { cv2.adjVert1 = i3; cv2.tet1 = e.tetNr; cv2.dihed1 = dihed; }
if (cv3.adjVert0 < 0) { cv3.adjVert0 = i2; cv3.tet0 = e.tetNr; cv3.dihed0 = dihed; }
else { cv3.adjVert1 = i2; cv3.tet1 = e.tetNr; cv3.dihed1 = dihed; }
chainVertNrs.pushBack(i2);
chainVertNrs.pushBack(i3);
i++;
}
while (i < edges.size() && edges[i] == e0);
te.numTets = (int32_t)chainVertNrs.size() / 2;
// find chain start;
int startVertNr = -1;
for (uint32_t j = 0; j < chainVertNrs.size(); j++) {
ChainVert &cv = chainVerts[(uint32_t)chainVertNrs[j]];
if (cv.adjVert0 < 0 || cv.adjVert1 < 0) {
startVertNr = chainVertNrs[j];
break;
}
}
te.onSurface = startVertNr >= 0;
mTetEdges.pushBack(te);
int curr = startVertNr;
if (curr < 0) curr = chainVertNrs[0];
int prev = -1;
// collect adjacent tetrahedra
for (int j = 0; j < te.numTets; j++) {
ChainVert &cv = chainVerts[(uint32_t)curr];
int next;
if (cv.adjVert0 == prev) {
next = cv.adjVert1;
mEdgeTetNrs.pushBack(cv.tet1);
mEdgeTetAngles.pushBack(cv.dihed1);
}
else {
next = cv.adjVert0;
mEdgeTetNrs.pushBack(cv.tet0);
mEdgeTetAngles.pushBack(cv.dihed0);
}
prev = curr;
curr = next;
}
}
}
// -----------------------------------------------------------------------------
bool CompoundCreator::tetHasColor(int tetNr, int color)
{
int nr = mTetFirstColor[(uint32_t)tetNr];
while (nr >= 0) {
if (mTetColors[(uint32_t)nr].color == color)
return true;
nr = mTetColors[(uint32_t)nr].next;
}
return false;
}
// -----------------------------------------------------------------------------
bool CompoundCreator::tetAddColor(int tetNr, int color)
{
if (tetHasColor(tetNr, color))
return false;
Color c;
c.color = color;
c.next = mTetFirstColor[(uint32_t)tetNr];
if (mTetColorsFirstEmpty <= 0) { // new entry
mTetFirstColor[(uint32_t)tetNr] = (int32_t)mTetColors.size();
mTetColors.pushBack(c);
}
else { // take from empty list
int newNr = mTetColorsFirstEmpty;
mTetFirstColor[(uint32_t)tetNr] = newNr;
mTetColorsFirstEmpty = mTetColors[(uint32_t)newNr].next;
mTetColors[(uint32_t)newNr] = c;
}
return true;
}
// -----------------------------------------------------------------------------
bool CompoundCreator::tetRemoveColor(int tetNr, int color)
{
int nr = mTetFirstColor[(uint32_t)tetNr];
int prev = -1;
while (nr >= 0) {
if (mTetColors[(uint32_t)nr].color == color) {
if (prev < 0)
mTetFirstColor[(uint32_t)tetNr] = mTetColors[(uint32_t)nr].next;
else
mTetColors[(uint32_t)prev].next = mTetColors[(uint32_t)nr].next;
// add to empty list
mTetColors[(uint32_t)nr].next = mTetColorsFirstEmpty;
mTetColorsFirstEmpty = nr;
return true;
}
prev = nr;
nr = mTetColors[(uint32_t)nr].next;
}
return false;
}
// -----------------------------------------------------------------------------
int CompoundCreator::tetNumColors(int tetNr)
{
int num = 0;
int nr = mTetFirstColor[(uint32_t)tetNr];
while (nr >= 0) {
num++;
nr = mTetColors[(uint32_t)nr].next;
}
return num;
}
// -----------------------------------------------------------------------------
void CompoundCreator::deleteColors()
{
mTetFirstColor.resize(mTetIndices.size()/4, -1);
mTetColors.clear();
mTetColorsFirstEmpty = -1;
}
// -----------------------------------------------------------------------------
bool CompoundCreator::tryTet(int tetNr, int color)
{
if (tetNr < 0)
return false;
//if (mTetColors[tetNr] >= 0)
// return false;
if (tetHasColor(tetNr, color))
return false;
mTestEdges.clear();
mAddedTets.clear();
tetAddColor(tetNr, color);
mAddedTets.pushBack(tetNr);
for (int i = 0; i < 6; i++)
mTestEdges.pushBack(mTetEdgeNrs[uint32_t(6*tetNr+i)]);
bool failed = false;
while (mTestEdges.size() > 0) {
int edgeNr = mTestEdges[mTestEdges.size()-1];
mTestEdges.popBack();
TetEdge &e = mTetEdges[(uint32_t)edgeNr];
bool anyOtherCol = false;
float sumAng = 0.0f;
for (int i = 0; i < e.numTets; i++) {
int edgeTetNr = mEdgeTetNrs[uint32_t(e.firstTet + i)];
if (tetHasColor(edgeTetNr, color))
sumAng += mEdgeTetAngles[uint32_t(e.firstTet + i)];
else if (tetNumColors(edgeTetNr) > 0)
anyOtherCol = true;
}
if (sumAng < CONVEX_THRESHOLD)
continue;
// if (e.onSurface || anyOtherCol) {
if (e.onSurface) {
failed = true;
break;
}
for (int i = 0; i < e.numTets; i++) {
int edgeTetNr = mEdgeTetNrs[uint32_t(e.firstTet + i)];
if (!tetHasColor(edgeTetNr, color)) {
tetAddColor(edgeTetNr, color);
mAddedTets.pushBack(edgeTetNr);
for (int j = 0; j < 6; j++)
mTestEdges.pushBack(mTetEdgeNrs[uint32_t(6*edgeTetNr+j)]);
}
}
}
if (failed) {
for (uint32_t i = 0; i < mAddedTets.size(); i++)
tetRemoveColor(mAddedTets[i], color);
mAddedTets.clear();
return false;
}
return true;
}
// -----------------------------------------------------------------------------
void CompoundCreator::colorTets()
{
int numTets = (int32_t)mTetIndices.size() / 4;
deleteColors();
int color = 0;
nvidia::Array<int> edges;
nvidia::Array<int> faces;
for (int i = 0; i < numTets; i++) {
if (tetNumColors(i) > 0)
continue;
tetAddColor(i, color);
faces.clear();
faces.pushBack(4*i);
faces.pushBack(4*i+1);
faces.pushBack(4*i+2);
faces.pushBack(4*i+3);
while (faces.size() > 0) {
int faceNr = faces[faces.size()-1];
faces.popBack();
int adjTetNr = mTetNeighbors[(uint32_t)faceNr];
if (adjTetNr < 0)
continue;
//if (tetNumColors(adjTetNr) > 0)
// continue;
if (!tryTet(adjTetNr, color))
continue;
for (uint32_t j = 0; j < mAddedTets.size(); j++) {
int addedTet = mAddedTets[j];
for (int k = 0; k < 4; k++) {
int adj = mTetNeighbors[uint32_t(4*addedTet+k)];
if (adj >= 0 && !tetHasColor(adj, color))
faces.pushBack(4*addedTet+k);
}
}
}
color++;
}
}
// -----------------------------------------------------------------------------
void CompoundCreator::colorsToConvexes()
{
mGeom.clear();
int numTets = (int32_t)mTetIndices.size() / 4;
int numColors = 0;
for (uint32_t i = 0; i < mTetColors.size(); i++) {
int color = mTetColors[i].color;
if (color >= numColors)
numColors = color+1;
}
nvidia::Array<bool> colorVisited((uint32_t)numColors, false);
nvidia::Array<int> queue;
nvidia::Array<int> globalToLocal(mTetVertices.size(), -1);
nvidia::Array<int> tetMarks((uint32_t)numTets, 0);
nvidia::Array<int> vertMarks(mTetVertices.size(), 0);
int mark = 1;
nvidia::Array<int> colorToConvexNr;
CompoundGeometry::Convex c;
for (uint32_t i = 0; i < (uint32_t)numTets; i++) {
int nr = mTetFirstColor[i];
while (nr >= 0) {
uint32_t color = (uint32_t)mTetColors[(uint32_t)nr].color;
nr = mTetColors[(uint32_t)nr].next;
if (colorVisited[color])
continue;
colorVisited[color] = true;
if ((uint32_t)colorToConvexNr.size() <= color)
colorToConvexNr.resize(color+1, -1);
colorToConvexNr[color] = (int32_t)mGeom.convexes.size();
queue.clear();
queue.pushBack((int32_t)i);
mGeom.initConvex(c);
mark++;
c.numVerts = 0;
// flood fill
while (!queue.empty()) {
uint32_t tetNr = (uint32_t)queue[queue.size()-1];
queue.popBack();
if (tetMarks[tetNr] == mark)
continue;
tetMarks[tetNr] = mark;
for (uint32_t j = 0; j < 4; j++) {
int adjNr = mTetNeighbors[4*tetNr + j];
if (adjNr < 0 || !tetHasColor(adjNr, (int32_t)color)) {
// create new face
mGeom.indices.pushBack(3); // face size
int flags = 0;
if (adjNr < 0) flags |= CompoundGeometry::FF_OBJECT_SURFACE;
mGeom.indices.pushBack(flags);
for (uint32_t k = 0; k < 3; k++) {
uint32_t id = (uint32_t)mTetIndices[4*tetNr + tetFaceIds[j][k]];
if (vertMarks[id] != mark) {
vertMarks[id] = mark;
globalToLocal[id] = c.numVerts;
c.numVerts++;
mGeom.vertices.pushBack(mTetVertices[id]);
}
mGeom.indices.pushBack(globalToLocal[id]);
}
c.numFaces++;
}
if (adjNr >= 0) {
// add neighbors
int colNr = mTetFirstColor[(uint32_t)adjNr];
while (colNr >= 0) {
int adjColor = mTetColors[(uint32_t)colNr].color;
colNr = mTetColors[(uint32_t)colNr].next;
if (adjColor != (int32_t)color) {
bool isNew = true;
for (int k = 0; k < c.numNeighbors; k++) {
if (mGeom.neighbors[uint32_t(c.firstNeighbor+k)] == adjColor) {
isNew = false;
break;
}
}
if (isNew) {
mGeom.neighbors.pushBack(adjColor);
c.numNeighbors++;
}
}
}
}
if (adjNr < 0 || !tetHasColor(adjNr, (int32_t)color) || tetMarks[(uint32_t)adjNr] == mark)
continue;
queue.pushBack(adjNr);
}
}
mGeom.convexes.pushBack(c);
}
}
for (uint32_t i = 0; i < mGeom.neighbors.size(); i++) {
if (mGeom.neighbors[i] >= 0)
mGeom.neighbors[i] = colorToConvexNr[(uint32_t)mGeom.neighbors[i]];
}
}
}
}
}
#endif | 29.64034 | 112 | 0.60683 | DoubleTT-Changan |
52e6f57902b7058e10b8235de57d4d4f6ef45fcb | 2,197 | cpp | C++ | YAD-Studio/Widgets/InputWidget.cpp | Yad-Studio/YAD-Studio | 3ff9be91a573fc189c5756068634e2c154f1cdbc | [
"MIT"
] | 22 | 2015-01-04T22:16:41.000Z | 2022-03-15T16:08:53.000Z | YAD-Studio/Widgets/InputWidget.cpp | Yad-Studio/YAD-Studio | 3ff9be91a573fc189c5756068634e2c154f1cdbc | [
"MIT"
] | 1 | 2015-02-26T12:08:14.000Z | 2015-02-27T07:38:38.000Z | YAD-Studio/Widgets/InputWidget.cpp | Yad-Studio/YAD-Studio | 3ff9be91a573fc189c5756068634e2c154f1cdbc | [
"MIT"
] | 2 | 2016-01-01T14:25:42.000Z | 2018-10-23T14:55:45.000Z | #include "InputWidget.h"
#include "ui_InputWidget.h"
#include "QPushButton"
InputWidget::InputWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::InputWidget)
{
ui->setupUi(this);
_can_run_algorythm = true;
//run button clicked
connect(ui->runButton,
SIGNAL(clicked()),
this,
SLOT(runCliked()));
//run with debug cliked
connect(ui->runWithDebug,
SIGNAL(clicked()),
this,
SLOT(runWithDebugClicked()));
//save clicked
connect(ui->runStepByStep,
SIGNAL(clicked()),
this,
SLOT(runWithDebugStepByStepClicked()));
}
InputWidget::~InputWidget()
{
delete ui;
}
void InputWidget::runStarted()
{
ui->runButton->setEnabled(false);
ui->runWithDebug->setEnabled(false);
ui->runStepByStep->setEnabled(false);
}
void InputWidget::runFinished()
{
if(_can_run_algorythm)
{
ui->runButton->setEnabled(true);
ui->runWithDebug->setEnabled(true);
ui->runStepByStep->setEnabled(true);
}
else
{
ui->runButton->setEnabled(false);
ui->runWithDebug->setEnabled(false);
ui->runStepByStep->setEnabled(false);
}
}
void InputWidget::setInput(QString new_input_word)
{
ui->lineEdit->setText(new_input_word);
}
void InputWidget::canRunAlgorithm(bool can_run)
{
_can_run_algorythm = can_run;
if(!_can_run_algorythm)
{
ui->runButton->setEnabled(false);
ui->runWithDebug->setEnabled(false);
ui->runStepByStep->setEnabled(false);
}
else
{
ui->runButton->setEnabled(true);
ui->runWithDebug->setEnabled(true);
ui->runStepByStep->setEnabled(true);
}
}
void InputWidget::runCliked( )
{
emit run(ui->lineEdit->text());
emit addToHistory(ui->lineEdit->text());
}
void InputWidget::runWithDebugClicked()
{
emit runWithDebug(ui->lineEdit->text());
emit addToHistory(ui->lineEdit->text());
}
void InputWidget::runWithDebugStepByStepClicked()
{
emit runWithDebugStepByStep(ui->lineEdit->text());
emit addToHistory(ui->lineEdit->text());
}
void InputWidget::saveCliked()
{
emit save();
}
| 21.752475 | 54 | 0.633136 | Yad-Studio |
52ebbc499b632c927fe80e567326ec75b9177f48 | 1,822 | cpp | C++ | test/any/add.cpp | mkn/mkn.gpu | 22946338e6a4790cc056708aa141c1a31538ba1c | [
"BSD-3-Clause"
] | null | null | null | test/any/add.cpp | mkn/mkn.gpu | 22946338e6a4790cc056708aa141c1a31538ba1c | [
"BSD-3-Clause"
] | 1 | 2020-09-13T10:39:29.000Z | 2021-05-07T08:12:11.000Z | test/any/add.cpp | mkn/mkn.gpu | 22946338e6a4790cc056708aa141c1a31538ba1c | [
"BSD-3-Clause"
] | null | null | null |
#include "kul/gpu.hpp"
static constexpr uint32_t WIDTH = 1024, HEIGHT = 1024;
static constexpr uint32_t NUM = WIDTH * HEIGHT;
static constexpr uint32_t TPB_X = 16, TPB_Y = 16;
template <typename T>
__global__ void vector_inc0(T* a) {
auto i = kul::gpu::idx();
a[i] = i + 1;
}
template <typename Float>
uint32_t test_inc() {
kul::gpu::DeviceMem<Float> devA(NUM);
kul::gpu::Launcher{WIDTH, HEIGHT, TPB_X, TPB_Y}(vector_inc0<Float>, devA);
auto a = devA();
for (uint32_t i = 0; i < NUM; i++)
if (a[i] != i + 1) return 1;
return 0;
}
template <typename T>
__global__ void vectoradd1(T* a, T* b) {
auto i = kul::gpu::idx();
a[i] = b[i] + 1;
}
template <typename Float>
uint32_t test_add1() {
std::vector<Float> b(NUM);
for (uint32_t i = 0; i < NUM; i++) b[i] = i;
kul::gpu::DeviceMem<Float> devA(NUM), devB(b);
kul::gpu::Launcher{WIDTH, HEIGHT, TPB_X, TPB_Y}(vectoradd1<Float>, devA, devB);
auto a = devA();
for (uint32_t i = 0; i < NUM; i++)
if (a[i] != b[i] + 1) return 1;
return 0;
}
template <typename T>
__global__ void vectoradd2(T* a, T const* const b, T const* const c) {
auto i = kul::gpu::idx();
a[i] = b[i] + c[i];
}
template <typename Float>
uint32_t test_add2() {
std::vector<Float> b(NUM), c(NUM);
for (uint32_t i = 0; i < NUM; i++) b[i] = i;
for (uint32_t i = 0; i < NUM; i++) c[i] = i * 100.0f;
kul::gpu::DeviceMem<Float> devA(NUM), devB(b), devC(c);
kul::gpu::Launcher{WIDTH, HEIGHT, TPB_X, TPB_Y}(vectoradd2<Float>, devA, devB, devC);
auto a = devA();
for (uint32_t i = 0; i < NUM; i++)
if (a[i] != b[i] + c[i]) return 1;
return 0;
}
int main() {
KOUT(NON) << __FILE__;
return test_inc<float>() + test_inc<double>() + //
test_add1<float>() + test_add1<double>() + //
test_add2<float>() + test_add2<double>();
}
| 27.606061 | 87 | 0.600439 | mkn |
52ebd12af502d6f1f191ba4566181254aa405a84 | 947 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/quest/CombatNodeParams_UseCover.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/quest/CombatNodeParams_UseCover.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/quest/CombatNodeParams_UseCover.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/NativeTypes.hpp>
#include <RED4ext/Scripting/Natives/Generated/AI/CoverExposureMethod.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/CombatNodeParams.hpp>
namespace RED4ext
{
namespace quest {
struct CombatNodeParams_UseCover : quest::CombatNodeParams
{
static constexpr const char* NAME = "questCombatNodeParams_UseCover";
static constexpr const char* ALIAS = NAME;
NodeRef cover; // 40
bool oneTimeSelection; // 48
uint8_t unk49[0x50 - 0x49]; // 49
CName forcedEntryAnimation; // 50
DynArray<AI::CoverExposureMethod> forceStance; // 58
bool immediately; // 68
uint8_t unk69[0x70 - 0x69]; // 69
};
RED4EXT_ASSERT_SIZE(CombatNodeParams_UseCover, 0x70);
} // namespace quest
} // namespace RED4ext
| 29.59375 | 73 | 0.749736 | jackhumbert |
52ee9e1fdc8ef703b60c13764f8a558cc7208047 | 1,428 | cpp | C++ | source/EterLib/ScreenFilter.cpp | beetle2k/Metin2Client | 114f492b71fcc90e8f5010c5b35b9fddb51639ca | [
"MIT"
] | 13 | 2018-08-27T19:06:54.000Z | 2021-11-12T05:44:04.000Z | source/EterLib/ScreenFilter.cpp | stempomzeskas/Metin2Client | 114f492b71fcc90e8f5010c5b35b9fddb51639ca | [
"MIT"
] | null | null | null | source/EterLib/ScreenFilter.cpp | stempomzeskas/Metin2Client | 114f492b71fcc90e8f5010c5b35b9fddb51639ca | [
"MIT"
] | 15 | 2018-10-25T14:28:10.000Z | 2022-03-25T14:05:09.000Z | #include "StdAfx.h"
#include "ScreenFilter.h"
#include "StateManager.h"
void CScreenFilter::Render()
{
if (!m_bEnable)
return;
STATEMANAGER.SaveTransform(D3DTS_PROJECTION, &ms_matIdentity);
STATEMANAGER.SaveTransform(D3DTS_VIEW, &ms_matIdentity);
STATEMANAGER.SetTransform(D3DTS_WORLD, &ms_matIdentity);
STATEMANAGER.SaveRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
STATEMANAGER.SaveRenderState(D3DRS_SRCBLEND, m_bySrcType);
STATEMANAGER.SaveRenderState(D3DRS_DESTBLEND, m_byDestType);
SetOrtho2D(CScreen::ms_iWidth, CScreen::ms_iHeight, 400.0f);
SetDiffuseColor(m_Color.r, m_Color.g, m_Color.b, m_Color.a);
RenderBar2d(0, 0, CScreen::ms_iWidth, CScreen::ms_iHeight);
STATEMANAGER.RestoreRenderState(D3DRS_ALPHABLENDENABLE);
STATEMANAGER.RestoreRenderState(D3DRS_SRCBLEND);
STATEMANAGER.RestoreRenderState(D3DRS_DESTBLEND);
STATEMANAGER.RestoreTransform(D3DTS_VIEW);
STATEMANAGER.RestoreTransform(D3DTS_PROJECTION);
}
void CScreenFilter::SetEnable(BOOL /*bFlag*/)
{
m_bEnable = FALSE;
}
void CScreenFilter::SetBlendType(BYTE bySrcType, BYTE byDestType)
{
m_bySrcType = bySrcType;
m_byDestType = byDestType;
}
void CScreenFilter::SetColor(const D3DXCOLOR & c_rColor)
{
m_Color = c_rColor;
}
CScreenFilter::CScreenFilter()
{
m_bEnable = FALSE;
m_bySrcType = D3DBLEND_SRCALPHA;
m_byDestType = D3DBLEND_INVSRCALPHA;
m_Color = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f);
}
CScreenFilter::~CScreenFilter()
{
}
| 26.943396 | 65 | 0.793417 | beetle2k |
5e0080bd13f86c45e1c0edc764d61b1d89440819 | 4,112 | hpp | C++ | gl/geometry_render.hpp | osyo-manga/boost-geometry-render | 7cdfb91572b31186fa48a1196bc34327ec561482 | [
"BSL-1.0"
] | 1 | 2018-04-04T20:06:24.000Z | 2018-04-04T20:06:24.000Z | gl/geometry_render.hpp | osyo-manga/boost-geometry-render | 7cdfb91572b31186fa48a1196bc34327ec561482 | [
"BSL-1.0"
] | null | null | null | gl/geometry_render.hpp | osyo-manga/boost-geometry-render | 7cdfb91572b31186fa48a1196bc34327ec561482 | [
"BSL-1.0"
] | null | null | null | //
// boost-geometry-render
//
// Copyright (c) 2011
// osyo-manga : http://d.hatena.ne.jp/osyo-manga/
//
// License:
// Boost Software License - Version 1.0
// <http://www.boost.org/LICENSE_1_0.txt>
//
#ifndef BOOST_GEOMETRY_RENDER_GL_GEOMETRY_RENDER_H
#define BOOST_GEOMETRY_RENDER_GL_GEOMETRY_RENDER_H
#include <boost/geometry/geometry.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/at.hpp>
#include <boost/geometry/algorithms/convert.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/range/algorithm/for_each.hpp>
namespace gl{
template<typename T>
void
render(T const& geometry);
namespace detail{
namespace mpl = boost::mpl;
namespace bg = boost::geometry;
typedef mpl::map<
mpl::pair<short, mpl::size_t<GL_SHORT> >,
mpl::pair<int, mpl::size_t<GL_INT> >,
mpl::pair<float, mpl::size_t<GL_FLOAT> >,
mpl::pair<double, mpl::size_t<GL_DOUBLE> >
> glVertexPointer_value_types;
template<typename Geometry>
struct glVertexPointer_value_type :
mpl::at<
glVertexPointer_value_types,
typename boost::geometry::coordinate_type<Geometry>::type
>::type
{};
template<typename Tag>
struct geometry_render;
template<>
struct geometry_render<boost::geometry::polygon_tag>{
template<typename T>
static void apply(T const& geometry){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(bg::dimension<T>::value,
glVertexPointer_value_type<T>::value, 0, &geometry.outer()[0]);
glDrawArrays(GL_POLYGON, 0, geometry.outer().size());
glDisableClientState(GL_VERTEX_ARRAY);
}
};
template<>
struct geometry_render<boost::geometry::ring_tag>{
template<typename T>
static void apply(T const& geometry){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(bg::dimension<T>::value,
glVertexPointer_value_type<T>::value, 0, &geometry[0]);
glDrawArrays(GL_POLYGON, 0, geometry.size());
glDisableClientState(GL_VERTEX_ARRAY);
}
};
template<>
struct geometry_render<boost::geometry::linestring_tag>{
template<typename T>
static void apply(T const& geometry){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(bg::dimension<T>::value,
glVertexPointer_value_type<T>::value, 0, &geometry[0]);
glDrawArrays(GL_LINE_STRIP, 0, geometry.size());
glDisableClientState(GL_VERTEX_ARRAY);
}
};
template<>
struct geometry_render<boost::geometry::point_tag>{
template<typename T>
static void apply(T const& geometry){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(bg::dimension<T>::value,
glVertexPointer_value_type<T>::value, 0, &geometry.template get<0>());
glDrawArrays(GL_POINTS, 0, 1);
glDisableClientState(GL_VERTEX_ARRAY);
}
};
template<>
struct geometry_render<boost::geometry::multi_point_tag>{
template<typename T>
static void apply(T const& geometry){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(bg::dimension<T>::value,
glVertexPointer_value_type<T>::value, 0, &geometry[0]);
glDrawArrays(GL_POINTS, 0, geometry.size());
glDisableClientState(GL_VERTEX_ARRAY);
}
};
template<>
struct geometry_render<boost::geometry::multi_linestring_tag>{
template<typename T>
static void apply(T const& geometry){
typedef bg::model::linestring<typename bg::point_type<T>::type> linestring_type;
boost::for_each(geometry, &render<linestring_type>);
}
};
template<>
struct geometry_render<boost::geometry::multi_polygon_tag>{
template<typename T>
static void apply(T const& geometry){
typedef bg::model::polygon<typename bg::point_type<T>::type> polygon_type;
boost::for_each(geometry, &render<polygon_type>);
}
};
template<>
struct geometry_render<boost::geometry::box_tag>{
template<typename T>
static void apply(T const& geometry){
bg::model::polygon<typename bg::point_type<T>::type> polygon;
bg::convert(geometry, polygon);
render(polygon);
}
};
} // namespace detail
template<typename T>
void
render(T const& geometry){
if(boost::geometry::num_points(geometry) > 0){
detail::geometry_render<
typename boost::geometry::tag<T>::type
>::apply(geometry);
}
}
} // namespace gl
#endif /* BOOST_GEOMETRY_RENDER_GL_GEOMETRY_RENDER_H */
| 26.701299 | 82 | 0.750973 | osyo-manga |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.