text
stringlengths
54
60.6k
<commit_before>/*! * This file is part of CameraPlus. * * Copyright (C) 2012 Mohammed Sameer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cameraresources.h" #include <dbusconnectioneventloop.h> #include <QDebug> // TODO: video recording ? // TODO: more resources ? CameraResources::CameraResources(QObject *parent) : QObject(parent), m_worker(new CameraResourcesWorker) { m_worker->moveToThread(&m_thread); DBUSConnectionEventLoop::getInstance().moveToThread(&m_thread); QObject::connect(&m_thread, SIGNAL(started()), m_worker, SLOT(init())); m_thread.start(); qRegisterMetaType<CameraResources::Mode>("CameraResources::Mode"); qRegisterMetaType<CameraResources::ResourceType>("CameraResources::ResourceType"); qRegisterMetaType<bool *>("bool *"); QObject::connect(m_worker, SIGNAL(acquiredChanged()), this, SIGNAL(acquiredChanged())); QObject::connect(m_worker, SIGNAL(hijackedChanged()), this, SIGNAL(hijackedChanged())); QObject::connect(m_worker, SIGNAL(updated()), this, SIGNAL(updated())); } CameraResources::~CameraResources() { m_thread.quit(); m_thread.wait(); delete m_worker; m_worker = 0; } bool CameraResources::isResourceGranted(const ResourceType& resource) { bool ok = false; QMetaObject::invokeMethod(m_worker, "isResourceGranted", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok), Q_ARG(CameraResources::ResourceType, resource)); return ok; } bool CameraResources::acquire(const Mode& mode) { bool ok = false; QMetaObject::invokeMethod(m_worker, "acquire", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok), Q_ARG(CameraResources::Mode, mode)); return ok; } bool CameraResources::acquired() const { bool ok = false; QMetaObject::invokeMethod(m_worker, "acquired", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok)); return ok; } bool CameraResources::hijacked() const { bool ok = false; QMetaObject::invokeMethod(m_worker, "hijacked", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok)); return ok; } CameraResourcesWorker::CameraResourcesWorker(QObject *parent) : QObject(parent), m_set(0), m_mode(CameraResources::None), m_acquired(false), m_acquiring(false), m_hijacked(false) { } CameraResourcesWorker::~CameraResourcesWorker() { bool ok; acquire(&ok, CameraResources::None); } void CameraResourcesWorker::init() { m_set = new ResourcePolicy::ResourceSet("camera", this); m_set->setAlwaysReply(); QObject::connect(m_set, SIGNAL(resourcesReleased()), this, SLOT(resourcesReleased())); QObject::connect(m_set, SIGNAL(lostResources()), this, SLOT(lostResources())); QObject::connect(m_set, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this, SLOT(resourcesGranted(const QList<ResourcePolicy::ResourceType>&))); QObject::connect(m_set, SIGNAL(resourcesDenied()), this, SLOT(resourcesDenied())); if (!m_set->initAndConnect()) { qCritical() << "Failed to connect to resource policy engine"; } } void CameraResourcesWorker::resourcesReleased() { setHijacked(false); setAcquired(false); m_acquiring = false; } void CameraResourcesWorker::lostResources() { setAcquired(false); setHijacked(true); m_acquiring = false; } void CameraResourcesWorker::resourcesGranted(const QList<ResourcePolicy::ResourceType>& optional) { Q_UNUSED(optional); if (!m_acquiring) { // This can happen when: // 1) We lose/gain optional resources. // 2) A higher priority application releases resources back. emit updated(); } m_acquiring = false; setAcquired(true); setHijacked(false); } void CameraResourcesWorker::resourcesDenied() { setAcquired(false); setHijacked(true); m_acquiring = false; } QList<ResourcePolicy::ResourceType> CameraResourcesWorker::listSet() { QList<ResourcePolicy::Resource *> resources = m_set->resources(); QList<ResourcePolicy::ResourceType> set; foreach (ResourcePolicy::Resource *r, resources) { set << r->type(); } return set; } void CameraResourcesWorker::acquire(bool *ok, const CameraResources::Mode& mode) { if (mode == m_mode) { *ok = true; return; } m_mode = mode; *ok = false; switch (m_mode) { case CameraResources::None: *ok = release(); break; case CameraResources::Image: *ok = updateSet(QList<ResourcePolicy::ResourceType>() << ResourcePolicy::VideoPlaybackType << ResourcePolicy::VideoRecorderType << ResourcePolicy::ScaleButtonType << ResourcePolicy::SnapButtonType); break; case CameraResources::Video: *ok = updateSet(QList<ResourcePolicy::ResourceType>() << ResourcePolicy::VideoPlaybackType << ResourcePolicy::VideoRecorderType << ResourcePolicy::ScaleButtonType << ResourcePolicy::SnapButtonType); break; case CameraResources::Recording: *ok = updateSet(QList<ResourcePolicy::ResourceType>() << ResourcePolicy::VideoPlaybackType << ResourcePolicy::VideoRecorderType << ResourcePolicy::ScaleButtonType << ResourcePolicy::SnapButtonType, QList<ResourcePolicy::ResourceType>() << ResourcePolicy::AudioRecorderType << ResourcePolicy::AudioPlaybackType); break; case CameraResources::PostCapture: *ok = updateSet(QList<ResourcePolicy::ResourceType>(), QList<ResourcePolicy::ResourceType>() << ResourcePolicy::ScaleButtonType); break; default: qWarning() << "Unknown mode" << mode; *ok = false; } } void CameraResourcesWorker::acquired(bool *ok) { *ok = m_acquired; } void CameraResourcesWorker::hijacked(bool *ok) { *ok = m_hijacked; } bool CameraResourcesWorker::updateSet(const QList<ResourcePolicy::ResourceType>& required, const QList<ResourcePolicy::ResourceType>& optional) { QList<ResourcePolicy::ResourceType> set = listSet(); foreach (ResourcePolicy::ResourceType r, set) { if (required.indexOf(r) != -1) { m_set->resource(r)->setOptional(false); } else if (optional.indexOf(r) != -1) { m_set->resource(r)->setOptional(true); } else { m_set->deleteResource(r); } } foreach (ResourcePolicy::ResourceType r, required) { m_set->addResource(r); } foreach (ResourcePolicy::ResourceType r, optional) { m_set->addResource(r); ResourcePolicy::Resource *res = m_set->resource(r); if (res) { res->setOptional(true); } } if (m_set->contains(ResourcePolicy::AudioPlaybackType)) { bool isOptional = m_set->resource(ResourcePolicy::AudioPlaybackType)->isOptional(); ResourcePolicy::AudioResource *audio = new ResourcePolicy::AudioResource("camera"); audio->setProcessID(QCoreApplication::applicationPid()); audio->setOptional(isOptional); m_set->addResourceObject(audio); } m_acquiring = true; m_set->update(); m_set->acquire(); while (m_acquiring) { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } return m_acquired; } bool CameraResourcesWorker::release() { m_acquiring = true; m_set->release(); while (m_acquiring) { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } m_mode = CameraResources::None; return true; } void CameraResourcesWorker::setAcquired(bool acquired) { if (m_acquired != acquired) { m_acquired = acquired; emit acquiredChanged(); } } void CameraResourcesWorker::setHijacked(bool hijacked) { if (m_hijacked != hijacked) { m_hijacked = hijacked; emit hijackedChanged(); } } void CameraResourcesWorker::isResourceGranted(bool *ok, const CameraResources::ResourceType& resource) { ResourcePolicy::ResourceType rt = (ResourcePolicy::ResourceType)resource; ResourcePolicy::Resource *r = m_set->resource(rt); if (r) { *ok = r->isGranted(); } } <commit_msg>obsolete TODO items<commit_after>/*! * This file is part of CameraPlus. * * Copyright (C) 2012 Mohammed Sameer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cameraresources.h" #include <dbusconnectioneventloop.h> #include <QDebug> CameraResources::CameraResources(QObject *parent) : QObject(parent), m_worker(new CameraResourcesWorker) { m_worker->moveToThread(&m_thread); DBUSConnectionEventLoop::getInstance().moveToThread(&m_thread); QObject::connect(&m_thread, SIGNAL(started()), m_worker, SLOT(init())); m_thread.start(); qRegisterMetaType<CameraResources::Mode>("CameraResources::Mode"); qRegisterMetaType<CameraResources::ResourceType>("CameraResources::ResourceType"); qRegisterMetaType<bool *>("bool *"); QObject::connect(m_worker, SIGNAL(acquiredChanged()), this, SIGNAL(acquiredChanged())); QObject::connect(m_worker, SIGNAL(hijackedChanged()), this, SIGNAL(hijackedChanged())); QObject::connect(m_worker, SIGNAL(updated()), this, SIGNAL(updated())); } CameraResources::~CameraResources() { m_thread.quit(); m_thread.wait(); delete m_worker; m_worker = 0; } bool CameraResources::isResourceGranted(const ResourceType& resource) { bool ok = false; QMetaObject::invokeMethod(m_worker, "isResourceGranted", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok), Q_ARG(CameraResources::ResourceType, resource)); return ok; } bool CameraResources::acquire(const Mode& mode) { bool ok = false; QMetaObject::invokeMethod(m_worker, "acquire", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok), Q_ARG(CameraResources::Mode, mode)); return ok; } bool CameraResources::acquired() const { bool ok = false; QMetaObject::invokeMethod(m_worker, "acquired", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok)); return ok; } bool CameraResources::hijacked() const { bool ok = false; QMetaObject::invokeMethod(m_worker, "hijacked", Qt::BlockingQueuedConnection, Q_ARG(bool *, &ok)); return ok; } CameraResourcesWorker::CameraResourcesWorker(QObject *parent) : QObject(parent), m_set(0), m_mode(CameraResources::None), m_acquired(false), m_acquiring(false), m_hijacked(false) { } CameraResourcesWorker::~CameraResourcesWorker() { bool ok; acquire(&ok, CameraResources::None); } void CameraResourcesWorker::init() { m_set = new ResourcePolicy::ResourceSet("camera", this); m_set->setAlwaysReply(); QObject::connect(m_set, SIGNAL(resourcesReleased()), this, SLOT(resourcesReleased())); QObject::connect(m_set, SIGNAL(lostResources()), this, SLOT(lostResources())); QObject::connect(m_set, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this, SLOT(resourcesGranted(const QList<ResourcePolicy::ResourceType>&))); QObject::connect(m_set, SIGNAL(resourcesDenied()), this, SLOT(resourcesDenied())); if (!m_set->initAndConnect()) { qCritical() << "Failed to connect to resource policy engine"; } } void CameraResourcesWorker::resourcesReleased() { setHijacked(false); setAcquired(false); m_acquiring = false; } void CameraResourcesWorker::lostResources() { setAcquired(false); setHijacked(true); m_acquiring = false; } void CameraResourcesWorker::resourcesGranted(const QList<ResourcePolicy::ResourceType>& optional) { Q_UNUSED(optional); if (!m_acquiring) { // This can happen when: // 1) We lose/gain optional resources. // 2) A higher priority application releases resources back. emit updated(); } m_acquiring = false; setAcquired(true); setHijacked(false); } void CameraResourcesWorker::resourcesDenied() { setAcquired(false); setHijacked(true); m_acquiring = false; } QList<ResourcePolicy::ResourceType> CameraResourcesWorker::listSet() { QList<ResourcePolicy::Resource *> resources = m_set->resources(); QList<ResourcePolicy::ResourceType> set; foreach (ResourcePolicy::Resource *r, resources) { set << r->type(); } return set; } void CameraResourcesWorker::acquire(bool *ok, const CameraResources::Mode& mode) { if (mode == m_mode) { *ok = true; return; } m_mode = mode; *ok = false; switch (m_mode) { case CameraResources::None: *ok = release(); break; case CameraResources::Image: *ok = updateSet(QList<ResourcePolicy::ResourceType>() << ResourcePolicy::VideoPlaybackType << ResourcePolicy::VideoRecorderType << ResourcePolicy::ScaleButtonType << ResourcePolicy::SnapButtonType); break; case CameraResources::Video: *ok = updateSet(QList<ResourcePolicy::ResourceType>() << ResourcePolicy::VideoPlaybackType << ResourcePolicy::VideoRecorderType << ResourcePolicy::ScaleButtonType << ResourcePolicy::SnapButtonType); break; case CameraResources::Recording: *ok = updateSet(QList<ResourcePolicy::ResourceType>() << ResourcePolicy::VideoPlaybackType << ResourcePolicy::VideoRecorderType << ResourcePolicy::ScaleButtonType << ResourcePolicy::SnapButtonType, QList<ResourcePolicy::ResourceType>() << ResourcePolicy::AudioRecorderType << ResourcePolicy::AudioPlaybackType); break; case CameraResources::PostCapture: *ok = updateSet(QList<ResourcePolicy::ResourceType>(), QList<ResourcePolicy::ResourceType>() << ResourcePolicy::ScaleButtonType); break; default: qWarning() << "Unknown mode" << mode; *ok = false; } } void CameraResourcesWorker::acquired(bool *ok) { *ok = m_acquired; } void CameraResourcesWorker::hijacked(bool *ok) { *ok = m_hijacked; } bool CameraResourcesWorker::updateSet(const QList<ResourcePolicy::ResourceType>& required, const QList<ResourcePolicy::ResourceType>& optional) { QList<ResourcePolicy::ResourceType> set = listSet(); foreach (ResourcePolicy::ResourceType r, set) { if (required.indexOf(r) != -1) { m_set->resource(r)->setOptional(false); } else if (optional.indexOf(r) != -1) { m_set->resource(r)->setOptional(true); } else { m_set->deleteResource(r); } } foreach (ResourcePolicy::ResourceType r, required) { m_set->addResource(r); } foreach (ResourcePolicy::ResourceType r, optional) { m_set->addResource(r); ResourcePolicy::Resource *res = m_set->resource(r); if (res) { res->setOptional(true); } } if (m_set->contains(ResourcePolicy::AudioPlaybackType)) { bool isOptional = m_set->resource(ResourcePolicy::AudioPlaybackType)->isOptional(); ResourcePolicy::AudioResource *audio = new ResourcePolicy::AudioResource("camera"); audio->setProcessID(QCoreApplication::applicationPid()); audio->setOptional(isOptional); m_set->addResourceObject(audio); } m_acquiring = true; m_set->update(); m_set->acquire(); while (m_acquiring) { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } return m_acquired; } bool CameraResourcesWorker::release() { m_acquiring = true; m_set->release(); while (m_acquiring) { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } m_mode = CameraResources::None; return true; } void CameraResourcesWorker::setAcquired(bool acquired) { if (m_acquired != acquired) { m_acquired = acquired; emit acquiredChanged(); } } void CameraResourcesWorker::setHijacked(bool hijacked) { if (m_hijacked != hijacked) { m_hijacked = hijacked; emit hijackedChanged(); } } void CameraResourcesWorker::isResourceGranted(bool *ok, const CameraResources::ResourceType& resource) { ResourcePolicy::ResourceType rt = (ResourcePolicy::ResourceType)resource; ResourcePolicy::Resource *r = m_set->resource(rt); if (r) { *ok = r->isGranted(); } } <|endoftext|>
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2008/11/01 // Author: Mike Ovsiannikov // // Copyright 2008-2010 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // Miscellaneous utility functions implementation. // //---------------------------------------------------------------------------- #include "QCUtils.h" #include <stdlib.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #if defined(QC_OS_NAME_LINUX) && ! defined(QC_USE_XFS_RESVSP) #define QC_USE_XFS_RESVSP #endif #ifdef QC_USE_XFS_RESVSP #include <xfs/xfs.h> #endif static inline void StrAppend( const char* inStrPtr, char*& ioPtr, size_t& ioMaxLen) { size_t theLen = inStrPtr ? strlen(inStrPtr) : 0; if (theLen > ioMaxLen) { theLen = ioMaxLen; } if (ioPtr != inStrPtr) { memmove(ioPtr, inStrPtr, theLen); } ioPtr += theLen; ioMaxLen -= theLen; *ioPtr = 0; } static int DoSysErrorMsg( const char* inMsgPtr, int inSysError, char* inMsgBufPtr, size_t inMsgBufSize) { if (inMsgBufSize <= 0) { return 0; } char* theMsgPtr = inMsgBufPtr; size_t theMaxLen = inMsgBufSize - 1; theMsgPtr[theMaxLen] = 0; StrAppend(inMsgPtr, theMsgPtr, theMaxLen); if (theMaxLen > 2) { if (theMsgPtr != inMsgBufPtr) { StrAppend(" ", theMsgPtr, theMaxLen); } #if defined(__EXTENSIONS__) || defined(QC_OS_NAME_DARWIN) || \ (! defined(_GNU_SOURCE) && defined(_XOPEN_SOURCE) && _XOPEN_SOURCE == 600) int theErr = strerror_r(inSysError, theMsgPtr, theMaxLen); if (theErr != 0) { theMsgPtr[0] = 0; } const char* const thePtr = theMsgPtr; #else const char* const thePtr = strerror_r(inSysError, theMsgPtr, theMaxLen); #endif StrAppend(thePtr, theMsgPtr, theMaxLen); if (theMaxLen > 0) { snprintf(theMsgPtr, theMaxLen, " %d", inSysError); StrAppend(theMsgPtr, theMsgPtr, theMaxLen); } } return (int)(theMsgPtr - inMsgBufPtr); } /* static */ void QCUtils::FatalError( const char* inMsgPtr, int inSysError) { char theMsgBuf[1<<9]; const int theLen = DoSysErrorMsg(inMsgPtr, inSysError, theMsgBuf, sizeof(theMsgBuf)); write(2, theMsgBuf, theLen); abort(); } /* static */ std::string QCUtils::SysError( int inSysError, const char* inMsgPtr /* = 0 */) { char theMsgBuf[1<<9]; DoSysErrorMsg(inMsgPtr, inSysError, theMsgBuf, sizeof(theMsgBuf)); return std::string(theMsgBuf); } /* static */ void QCUtils::AssertionFailure( const char* inMsgPtr, const char* inFileNamePtr, int inLineNum) { char theMsgBuf[1<<9]; char* theMsgPtr = theMsgBuf; size_t theMaxLen = sizeof(theMsgBuf) - 1; StrAppend("assertion failure: ", theMsgPtr, theMaxLen); StrAppend(inFileNamePtr ? inFileNamePtr : "???", theMsgPtr, theMaxLen); if (theMaxLen > 4) { snprintf(theMsgPtr, theMaxLen, ":%d\n", inLineNum); StrAppend(theMsgPtr, theMsgPtr, theMaxLen); } write(2, theMsgBuf, theMsgPtr - theMsgBuf); abort(); } /* static */ int64_t QCUtils::ReserveFileSpace( int inFd, int64_t inSize) { if (inSize <= 0) { return 0; } #ifdef QC_USE_XFS_RESVSP if (platform_test_xfs_fd(inFd)) { xfs_flock64_t theResv = {0}; // Clear to make valgrind happy. theResv.l_whence = 0; theResv.l_start = 0; theResv.l_len = inSize; if (xfsctl(0, inFd, XFS_IOC_RESVSP64, &theResv)) { return (errno > 0 ? -errno : (errno ? errno : -1)); } return inSize; } #endif /* QC_USE_XFS_RESVSP */ return (inFd < 0 ? -EINVAL : 0); } /* static */ int QCUtils::AllocateFileSpace( int inFd, int64_t inSize, int64_t inMinSize /* = -1 */, int64_t* inInitialFileSizePtr /* = 0 */) { int theErr = 0; const off_t theSize = lseek(inFd, 0, SEEK_END); if (theSize < 0 || theSize >= inSize) { theErr = theSize < 0 ? errno : 0; return theErr; } if (inInitialFileSizePtr) { *inInitialFileSizePtr = theSize; } // Assume direct io has to be page aligned. const long kPgSize = sysconf(_SC_PAGESIZE); const long kPgMask = kPgSize - 1; QCRTASSERT((kPgMask & kPgSize) == 0); if (ReserveFileSpace(inFd, (inSize + kPgMask) & ~kPgMask) > 0) { return (ftruncate(inFd, inSize) ? errno : 0); } if (inMinSize >= 0 && theSize >= inMinSize) { return theErr; } const ssize_t kWrLen = 1 << 20; void* const thePtr = mmap(0, kWrLen, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); off_t theOffset = theSize & ~kPgMask; // If logical eof is not page aligned, read partial block. if (thePtr == MAP_FAILED || (theOffset != theSize && ( lseek(inFd, theOffset, SEEK_SET) != theOffset || read(inFd, thePtr, kPgSize) != (theSize - theOffset) || lseek(inFd, theOffset, SEEK_SET) != theOffset ))) { theErr = errno; } else { const off_t theMinSize = inMinSize < 0 ? inSize : inMinSize; while (theOffset < theMinSize && write(inFd, thePtr, kWrLen) == kWrLen) { theOffset += kWrLen; } if (theOffset < theMinSize || ftruncate(inFd, theMinSize)) { theErr = errno; } } if (thePtr != MAP_FAILED) { munmap(thePtr, kWrLen); } return theErr; } /* static */ int QCUtils::AllocateFileSpace( const char* inFileNamePtr, int64_t inSize, int64_t inMinSize /* = -1 */, int64_t* inInitialFileSizePtr /* = 0 */) { const int theFd = open(inFileNamePtr, O_RDWR | O_CREAT #ifdef O_DIRECT | O_DIRECT #endif #ifdef O_NOATIME | O_NOATIME #endif , 0666); if (theFd < 0) { return errno; } const int theErr = AllocateFileSpace( theFd, inSize, inMinSize, inInitialFileSizePtr); return (close(theFd) ? (theErr ? theErr : errno) : theErr); } <commit_msg>QC_OS_NAME_FREEBSD uses XSI strerror_r. fixes #14<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2008/11/01 // Author: Mike Ovsiannikov // // Copyright 2008-2010 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // Miscellaneous utility functions implementation. // //---------------------------------------------------------------------------- #include "QCUtils.h" #include <stdlib.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #if defined(QC_OS_NAME_LINUX) && ! defined(QC_USE_XFS_RESVSP) #define QC_USE_XFS_RESVSP #endif #ifdef QC_USE_XFS_RESVSP #include <xfs/xfs.h> #endif static inline void StrAppend( const char* inStrPtr, char*& ioPtr, size_t& ioMaxLen) { size_t theLen = inStrPtr ? strlen(inStrPtr) : 0; if (theLen > ioMaxLen) { theLen = ioMaxLen; } if (ioPtr != inStrPtr) { memmove(ioPtr, inStrPtr, theLen); } ioPtr += theLen; ioMaxLen -= theLen; *ioPtr = 0; } static int DoSysErrorMsg( const char* inMsgPtr, int inSysError, char* inMsgBufPtr, size_t inMsgBufSize) { if (inMsgBufSize <= 0) { return 0; } char* theMsgPtr = inMsgBufPtr; size_t theMaxLen = inMsgBufSize - 1; theMsgPtr[theMaxLen] = 0; StrAppend(inMsgPtr, theMsgPtr, theMaxLen); if (theMaxLen > 2) { if (theMsgPtr != inMsgBufPtr) { StrAppend(" ", theMsgPtr, theMaxLen); } #if defined(__EXTENSIONS__) || defined(QC_OS_NAME_DARWIN) || defined(QC_OS_NAME_FREEBSD) || \ (! defined(_GNU_SOURCE) && (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE < 600 || \ defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE < 200112L)) int theErr = strerror_r(inSysError, theMsgPtr, theMaxLen); if (theErr != 0) { theMsgPtr[0] = 0; } const char* const thePtr = theMsgPtr; #else const char* const thePtr = strerror_r(inSysError, theMsgPtr, theMaxLen); #endif StrAppend(thePtr, theMsgPtr, theMaxLen); if (theMaxLen > 0) { snprintf(theMsgPtr, theMaxLen, " %d", inSysError); StrAppend(theMsgPtr, theMsgPtr, theMaxLen); } } return (int)(theMsgPtr - inMsgBufPtr); } /* static */ void QCUtils::FatalError( const char* inMsgPtr, int inSysError) { char theMsgBuf[1<<9]; const int theLen = DoSysErrorMsg(inMsgPtr, inSysError, theMsgBuf, sizeof(theMsgBuf)); write(2, theMsgBuf, theLen); abort(); } /* static */ std::string QCUtils::SysError( int inSysError, const char* inMsgPtr /* = 0 */) { char theMsgBuf[1<<9]; DoSysErrorMsg(inMsgPtr, inSysError, theMsgBuf, sizeof(theMsgBuf)); return std::string(theMsgBuf); } /* static */ void QCUtils::AssertionFailure( const char* inMsgPtr, const char* inFileNamePtr, int inLineNum) { char theMsgBuf[1<<9]; char* theMsgPtr = theMsgBuf; size_t theMaxLen = sizeof(theMsgBuf) - 1; StrAppend("assertion failure: ", theMsgPtr, theMaxLen); StrAppend(inFileNamePtr ? inFileNamePtr : "???", theMsgPtr, theMaxLen); if (theMaxLen > 4) { snprintf(theMsgPtr, theMaxLen, ":%d\n", inLineNum); StrAppend(theMsgPtr, theMsgPtr, theMaxLen); } write(2, theMsgBuf, theMsgPtr - theMsgBuf); abort(); } /* static */ int64_t QCUtils::ReserveFileSpace( int inFd, int64_t inSize) { if (inSize <= 0) { return 0; } #ifdef QC_USE_XFS_RESVSP if (platform_test_xfs_fd(inFd)) { xfs_flock64_t theResv = {0}; // Clear to make valgrind happy. theResv.l_whence = 0; theResv.l_start = 0; theResv.l_len = inSize; if (xfsctl(0, inFd, XFS_IOC_RESVSP64, &theResv)) { return (errno > 0 ? -errno : (errno ? errno : -1)); } return inSize; } #endif /* QC_USE_XFS_RESVSP */ return (inFd < 0 ? -EINVAL : 0); } /* static */ int QCUtils::AllocateFileSpace( int inFd, int64_t inSize, int64_t inMinSize /* = -1 */, int64_t* inInitialFileSizePtr /* = 0 */) { int theErr = 0; const off_t theSize = lseek(inFd, 0, SEEK_END); if (theSize < 0 || theSize >= inSize) { theErr = theSize < 0 ? errno : 0; return theErr; } if (inInitialFileSizePtr) { *inInitialFileSizePtr = theSize; } // Assume direct io has to be page aligned. const long kPgSize = sysconf(_SC_PAGESIZE); const long kPgMask = kPgSize - 1; QCRTASSERT((kPgMask & kPgSize) == 0); if (ReserveFileSpace(inFd, (inSize + kPgMask) & ~kPgMask) > 0) { return (ftruncate(inFd, inSize) ? errno : 0); } if (inMinSize >= 0 && theSize >= inMinSize) { return theErr; } const ssize_t kWrLen = 1 << 20; void* const thePtr = mmap(0, kWrLen, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); off_t theOffset = theSize & ~kPgMask; // If logical eof is not page aligned, read partial block. if (thePtr == MAP_FAILED || (theOffset != theSize && ( lseek(inFd, theOffset, SEEK_SET) != theOffset || read(inFd, thePtr, kPgSize) != (theSize - theOffset) || lseek(inFd, theOffset, SEEK_SET) != theOffset ))) { theErr = errno; } else { const off_t theMinSize = inMinSize < 0 ? inSize : inMinSize; while (theOffset < theMinSize && write(inFd, thePtr, kWrLen) == kWrLen) { theOffset += kWrLen; } if (theOffset < theMinSize || ftruncate(inFd, theMinSize)) { theErr = errno; } } if (thePtr != MAP_FAILED) { munmap(thePtr, kWrLen); } return theErr; } /* static */ int QCUtils::AllocateFileSpace( const char* inFileNamePtr, int64_t inSize, int64_t inMinSize /* = -1 */, int64_t* inInitialFileSizePtr /* = 0 */) { const int theFd = open(inFileNamePtr, O_RDWR | O_CREAT #ifdef O_DIRECT | O_DIRECT #endif #ifdef O_NOATIME | O_NOATIME #endif , 0666); if (theFd < 0) { return errno; } const int theErr = AllocateFileSpace( theFd, inSize, inMinSize, inInitialFileSizePtr); return (close(theFd) ? (theErr ? theErr : errno) : theErr); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "sbcomp.hxx" #include <stdio.h> #include <string.h> #include <ctype.h> // All symbol names are laid down int the symbol-pool's stringpool, so that // all symbols are handled in the same case. On saving the code-image, the // global stringpool with the respective symbols is also saved. // The local stringpool holds all the symbols that don't move to the image // (labels, constant names etc.). /*************************************************************************** |* |* SbiStringPool |* ***************************************************************************/ SbiStringPool::SbiStringPool( SbiParser* p ) { pParser = p; } SbiStringPool::~SbiStringPool() {} const OUString& SbiStringPool::Find( sal_uInt32 n ) const { if( n == 0 || n > aData.size() ) return aEmpty; //hack, returning a reference to a simulation of null else return aData[n - 1]; } short SbiStringPool::Add( const OUString& rVal, bool bNoCase ) { sal_uInt32 n = aData.size(); for( sal_uInt32 i = 0; i < n; ++i ) { OUString& p = aData[i]; if( ( bNoCase && p == rVal ) || ( !bNoCase && p.equalsIgnoreAsciiCase( rVal ) ) ) return i+1; } aData.push_back(rVal); return (short) ++n; } short SbiStringPool::Add( double n, SbxDataType t ) { char buf[ 40 ]; switch( t ) { case SbxINTEGER: snprintf( buf, sizeof(buf), "%d", (short) n ); break; case SbxLONG: snprintf( buf, sizeof(buf), "%ld", (long) n ); break; case SbxSINGLE: snprintf( buf, sizeof(buf), "%.6g", (float) n ); break; case SbxDOUBLE: snprintf( buf, sizeof(buf), "%.16g", n ); break; default: break; } return Add( OUString::createFromAscii( buf ) ); } /*************************************************************************** |* |* SbiSymPool |* ***************************************************************************/ SbiSymPool::SbiSymPool( SbiStringPool& r, SbiSymScope s ) : rStrings( r ) { pParser = r.GetParser(); eScope = s; pParent = NULL; nCur = nProcId = 0; } SbiSymPool::~SbiSymPool() {} SbiSymDef* SbiSymPool::First() { nCur = (sal_uInt16) -1; return Next(); } SbiSymDef* SbiSymPool::Next() { if( ++nCur >= aData.size() ) return NULL; else return &aData[ nCur ]; } SbiSymDef* SbiSymPool::AddSym( const OUString& rName ) { SbiSymDef* p = new SbiSymDef( rName ); p->nPos = aData.size(); p->nId = rStrings.Add( rName ); p->nProcId = nProcId; p->pIn = this; aData.insert( aData.begin() + p->nPos, p ); return p; } SbiProcDef* SbiSymPool::AddProc( const OUString& rName ) { SbiProcDef* p = new SbiProcDef( pParser, rName ); p->nPos = aData.size(); p->nId = rStrings.Add( rName ); // procs are always local p->nProcId = 0; p->pIn = this; aData.insert( aData.begin() + p->nPos, p ); return p; } // adding an externally constructed symbol definition void SbiSymPool::Add( SbiSymDef* pDef ) { if( pDef && pDef->pIn != this ) { if( pDef->pIn ) { #ifdef DBG_UTIL pParser->Error( SbERR_INTERNAL_ERROR, "Dbl Pool" ); #endif return; } pDef->nPos = aData.size(); if( !pDef->nId ) { // A unique name must be created in the string pool // for static variables (Form ProcName:VarName) OUString aName( pDef->aName ); if( pDef->IsStatic() ) { aName = pParser->aGblStrings.Find( nProcId ); aName += ":"; aName += pDef->aName; } pDef->nId = rStrings.Add( aName ); } if( !pDef->GetProcDef() ) { pDef->nProcId = nProcId; } pDef->pIn = this; aData.insert( aData.begin() + pDef->nPos, pDef ); } } SbiSymDef* SbiSymPool::Find( const OUString& rName ) { sal_uInt16 nCount = aData.size(); for( sal_uInt16 i = 0; i < nCount; i++ ) { SbiSymDef &r = aData[ nCount - i - 1 ]; if( ( !r.nProcId || ( r.nProcId == nProcId)) && ( r.aName.equalsIgnoreAsciiCase(rName))) { return &r; } } if( pParent ) { return pParent->Find( rName ); } else { return NULL; } } // find via position (from 0) SbiSymDef* SbiSymPool::Get( sal_uInt16 n ) { if( n >= aData.size() ) { return NULL; } else { return &aData[ n ]; } } sal_uInt32 SbiSymPool::Define( const OUString& rName ) { SbiSymDef* p = Find( rName ); if( p ) { if( p->IsDefined() ) { pParser->Error( SbERR_LABEL_DEFINED, rName ); } } else { p = AddSym( rName ); } return p->Define(); } sal_uInt32 SbiSymPool::Reference( const OUString& rName ) { SbiSymDef* p = Find( rName ); if( !p ) { p = AddSym( rName ); } // to be sure pParser->aGen.GenStmnt(); return p->Reference(); } void SbiSymPool::CheckRefs() { for( sal_uInt16 i = 0; i < aData.size(); i++ ) { SbiSymDef &r = aData[ i ]; if( !r.IsDefined() ) { pParser->Error( SbERR_UNDEF_LABEL, r.GetName() ); } } } /*************************************************************************** |* |* symbol definitions |* ***************************************************************************/ SbiSymDef::SbiSymDef( const OUString& rName ) : aName( rName ) { eType = SbxEMPTY; nDims = 0; nTypeId = 0; nProcId = 0; nId = 0; nPos = 0; nLen = 0; nChain = 0; bAs = bNew = bStatic = bOpt = bParamArray = bWithEvents = bWithBrackets = bByVal = bChained = bGlobal = false; pIn = pPool = NULL; nDefaultId = 0; nFixedStringLength = -1; } SbiSymDef::~SbiSymDef() { delete pPool; } SbiProcDef* SbiSymDef::GetProcDef() { return NULL; } SbiConstDef* SbiSymDef::GetConstDef() { return NULL; } const OUString& SbiSymDef::GetName() { if( pIn ) { aName = pIn->rStrings.Find( nId ); } return aName; } void SbiSymDef::SetType( SbxDataType t ) { if( t == SbxVARIANT && pIn ) { sal_Unicode cu = aName[0]; if( cu < 256 ) { char ch = (char)cu; if( ch == '_' ) { ch = 'Z'; } int ch2 = toupper( ch ); unsigned char c = (unsigned char)ch2; if( c > 0 && c < 128 ) { int nIndex = ch2 - 'A'; assert(nIndex >= 0 && nIndex < N_DEF_TYPES); if (nIndex >= 0 && nIndex < N_DEF_TYPES) t = pIn->pParser->eDefTypes[nIndex]; } } } eType = t; } // construct a backchain, if not yet defined // the value that shall be stored as an operand is returned sal_uInt32 SbiSymDef::Reference() { if( !bChained ) { sal_uInt32 n = nChain; nChain = pIn->pParser->aGen.GetOffset(); return n; } else return nChain; } sal_uInt32 SbiSymDef::Define() { sal_uInt32 n = pIn->pParser->aGen.GetPC(); pIn->pParser->aGen.GenStmnt(); if( nChain ) { pIn->pParser->aGen.BackChain( nChain ); } nChain = n; bChained = true; return nChain; } // A symbol definition may have its own pool. This is the case // for objects and procedures (local variable) SbiSymPool& SbiSymDef::GetPool() { if( !pPool ) { pPool = new SbiSymPool( pIn->pParser->aGblStrings, SbLOCAL ); // is dumped } return *pPool; } SbiSymScope SbiSymDef::GetScope() const { return pIn ? pIn->GetScope() : SbLOCAL; } // The procedure definition has three pools: // 1) aParams: is filled by the definition. Contains the // parameters' names, like they're used inside the body. // The first element is the return value. // 2) pPool: all local variables // 3) aLabels: labels SbiProcDef::SbiProcDef( SbiParser* pParser, const OUString& rName, bool bProcDecl ) : SbiSymDef( rName ) , aParams( pParser->aGblStrings, SbPARAM ) // is dumped , aLabels( pParser->aLclStrings, SbLOCAL ) // is not dumped , mbProcDecl( bProcDecl ) { aParams.SetParent( &pParser->aPublics ); pPool = new SbiSymPool( pParser->aGblStrings, SbLOCAL ); pPool->SetParent( &aParams ); nLine1 = nLine2 = 0; mePropMode = PROPERTY_MODE_NONE; bPublic = true; bCdecl = false; bStatic = false; // For return values the first element of the parameter // list is always defined with name and type of the proc aParams.AddSym( aName ); } SbiProcDef::~SbiProcDef() {} SbiProcDef* SbiProcDef::GetProcDef() { return this; } void SbiProcDef::SetType( SbxDataType t ) { SbiSymDef::SetType( t ); aParams.Get( 0 )->SetType( eType ); } // match with a forward-declaration // if the match is OK, pOld is replaced by this in the pool // pOld is deleted in any case! void SbiProcDef::Match( SbiProcDef* pOld ) { SbiSymDef *pn=NULL; // parameter 0 is the function name sal_uInt16 i; for( i = 1; i < aParams.GetSize(); i++ ) { SbiSymDef* po = pOld->aParams.Get( i ); pn = aParams.Get( i ); // no type matching - that is done during running // but is it maybe called with too little parameters? if( !po && !pn->IsOptional() && !pn->IsParamArray() ) { break; } pOld->aParams.Next(); } if( pn && i < aParams.GetSize() && pOld->pIn ) { // mark the whole line pOld->pIn->GetParser()->SetCol1( 0 ); pOld->pIn->GetParser()->Error( SbERR_BAD_DECLARATION, aName ); } if( !pIn && pOld->pIn ) { // Replace old entry with the new one nPos = pOld->nPos; nId = pOld->nId; pIn = pOld->pIn; pIn->aData.replace( nPos, this ).release(); } delete pOld; } void SbiProcDef::setPropertyMode( PropertyMode ePropMode ) { mePropMode = ePropMode; if( mePropMode != PROPERTY_MODE_NONE ) { // Prop name = original scanned procedure name maPropName = aName; // CompleteProcName includes "Property xxx " // to avoid conflicts with other symbols OUString aCompleteProcName = "Property "; switch( mePropMode ) { case PROPERTY_MODE_GET: aCompleteProcName += "Get "; break; case PROPERTY_MODE_LET: aCompleteProcName += "Let "; break; case PROPERTY_MODE_SET: aCompleteProcName += "Set "; break; case PROPERTY_MODE_NONE: OSL_FAIL( "Illegal PropertyMode PROPERTY_MODE_NONE" ); break; } aCompleteProcName += aName; aName = aCompleteProcName; } } SbiConstDef::SbiConstDef( const OUString& rName ) : SbiSymDef( rName ) { nVal = 0; eType = SbxINTEGER; } void SbiConstDef::Set( double n, SbxDataType t ) { aVal = ""; nVal = n; eType = t; } void SbiConstDef::Set( const OUString& n ) { aVal = n; nVal = 0; eType = SbxSTRING; } SbiConstDef::~SbiConstDef() {} SbiConstDef* SbiConstDef::GetConstDef() { return this; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>this is for detecting the type of a variable based on its name<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "sbcomp.hxx" #include <stdio.h> #include <string.h> #include <ctype.h> // All symbol names are laid down int the symbol-pool's stringpool, so that // all symbols are handled in the same case. On saving the code-image, the // global stringpool with the respective symbols is also saved. // The local stringpool holds all the symbols that don't move to the image // (labels, constant names etc.). /*************************************************************************** |* |* SbiStringPool |* ***************************************************************************/ SbiStringPool::SbiStringPool( SbiParser* p ) { pParser = p; } SbiStringPool::~SbiStringPool() {} const OUString& SbiStringPool::Find( sal_uInt32 n ) const { if( n == 0 || n > aData.size() ) return aEmpty; //hack, returning a reference to a simulation of null else return aData[n - 1]; } short SbiStringPool::Add( const OUString& rVal, bool bNoCase ) { sal_uInt32 n = aData.size(); for( sal_uInt32 i = 0; i < n; ++i ) { OUString& p = aData[i]; if( ( bNoCase && p == rVal ) || ( !bNoCase && p.equalsIgnoreAsciiCase( rVal ) ) ) return i+1; } aData.push_back(rVal); return (short) ++n; } short SbiStringPool::Add( double n, SbxDataType t ) { char buf[ 40 ]; switch( t ) { case SbxINTEGER: snprintf( buf, sizeof(buf), "%d", (short) n ); break; case SbxLONG: snprintf( buf, sizeof(buf), "%ld", (long) n ); break; case SbxSINGLE: snprintf( buf, sizeof(buf), "%.6g", (float) n ); break; case SbxDOUBLE: snprintf( buf, sizeof(buf), "%.16g", n ); break; default: break; } return Add( OUString::createFromAscii( buf ) ); } /*************************************************************************** |* |* SbiSymPool |* ***************************************************************************/ SbiSymPool::SbiSymPool( SbiStringPool& r, SbiSymScope s ) : rStrings( r ) { pParser = r.GetParser(); eScope = s; pParent = NULL; nCur = nProcId = 0; } SbiSymPool::~SbiSymPool() {} SbiSymDef* SbiSymPool::First() { nCur = (sal_uInt16) -1; return Next(); } SbiSymDef* SbiSymPool::Next() { if( ++nCur >= aData.size() ) return NULL; else return &aData[ nCur ]; } SbiSymDef* SbiSymPool::AddSym( const OUString& rName ) { SbiSymDef* p = new SbiSymDef( rName ); p->nPos = aData.size(); p->nId = rStrings.Add( rName ); p->nProcId = nProcId; p->pIn = this; aData.insert( aData.begin() + p->nPos, p ); return p; } SbiProcDef* SbiSymPool::AddProc( const OUString& rName ) { SbiProcDef* p = new SbiProcDef( pParser, rName ); p->nPos = aData.size(); p->nId = rStrings.Add( rName ); // procs are always local p->nProcId = 0; p->pIn = this; aData.insert( aData.begin() + p->nPos, p ); return p; } // adding an externally constructed symbol definition void SbiSymPool::Add( SbiSymDef* pDef ) { if( pDef && pDef->pIn != this ) { if( pDef->pIn ) { #ifdef DBG_UTIL pParser->Error( SbERR_INTERNAL_ERROR, "Dbl Pool" ); #endif return; } pDef->nPos = aData.size(); if( !pDef->nId ) { // A unique name must be created in the string pool // for static variables (Form ProcName:VarName) OUString aName( pDef->aName ); if( pDef->IsStatic() ) { aName = pParser->aGblStrings.Find( nProcId ); aName += ":"; aName += pDef->aName; } pDef->nId = rStrings.Add( aName ); } if( !pDef->GetProcDef() ) { pDef->nProcId = nProcId; } pDef->pIn = this; aData.insert( aData.begin() + pDef->nPos, pDef ); } } SbiSymDef* SbiSymPool::Find( const OUString& rName ) { sal_uInt16 nCount = aData.size(); for( sal_uInt16 i = 0; i < nCount; i++ ) { SbiSymDef &r = aData[ nCount - i - 1 ]; if( ( !r.nProcId || ( r.nProcId == nProcId)) && ( r.aName.equalsIgnoreAsciiCase(rName))) { return &r; } } if( pParent ) { return pParent->Find( rName ); } else { return NULL; } } // find via position (from 0) SbiSymDef* SbiSymPool::Get( sal_uInt16 n ) { if( n >= aData.size() ) { return NULL; } else { return &aData[ n ]; } } sal_uInt32 SbiSymPool::Define( const OUString& rName ) { SbiSymDef* p = Find( rName ); if( p ) { if( p->IsDefined() ) { pParser->Error( SbERR_LABEL_DEFINED, rName ); } } else { p = AddSym( rName ); } return p->Define(); } sal_uInt32 SbiSymPool::Reference( const OUString& rName ) { SbiSymDef* p = Find( rName ); if( !p ) { p = AddSym( rName ); } // to be sure pParser->aGen.GenStmnt(); return p->Reference(); } void SbiSymPool::CheckRefs() { for( sal_uInt16 i = 0; i < aData.size(); i++ ) { SbiSymDef &r = aData[ i ]; if( !r.IsDefined() ) { pParser->Error( SbERR_UNDEF_LABEL, r.GetName() ); } } } /*************************************************************************** |* |* symbol definitions |* ***************************************************************************/ SbiSymDef::SbiSymDef( const OUString& rName ) : aName( rName ) { eType = SbxEMPTY; nDims = 0; nTypeId = 0; nProcId = 0; nId = 0; nPos = 0; nLen = 0; nChain = 0; bAs = bNew = bStatic = bOpt = bParamArray = bWithEvents = bWithBrackets = bByVal = bChained = bGlobal = false; pIn = pPool = NULL; nDefaultId = 0; nFixedStringLength = -1; } SbiSymDef::~SbiSymDef() { delete pPool; } SbiProcDef* SbiSymDef::GetProcDef() { return NULL; } SbiConstDef* SbiSymDef::GetConstDef() { return NULL; } const OUString& SbiSymDef::GetName() { if( pIn ) { aName = pIn->rStrings.Find( nId ); } return aName; } void SbiSymDef::SetType( SbxDataType t ) { if( t == SbxVARIANT && pIn ) { //See if there have been any deftype statements to set the default type //of a variable based on its starting letter sal_Unicode cu = aName[0]; if( cu < 256 ) { char ch = (char)cu; if( ch == '_' ) { ch = 'Z'; } int ch2 = toupper( ch ); int nIndex = ch2 - 'A'; if (nIndex >= 0 && nIndex < N_DEF_TYPES) t = pIn->pParser->eDefTypes[nIndex]; } } eType = t; } // construct a backchain, if not yet defined // the value that shall be stored as an operand is returned sal_uInt32 SbiSymDef::Reference() { if( !bChained ) { sal_uInt32 n = nChain; nChain = pIn->pParser->aGen.GetOffset(); return n; } else return nChain; } sal_uInt32 SbiSymDef::Define() { sal_uInt32 n = pIn->pParser->aGen.GetPC(); pIn->pParser->aGen.GenStmnt(); if( nChain ) { pIn->pParser->aGen.BackChain( nChain ); } nChain = n; bChained = true; return nChain; } // A symbol definition may have its own pool. This is the case // for objects and procedures (local variable) SbiSymPool& SbiSymDef::GetPool() { if( !pPool ) { pPool = new SbiSymPool( pIn->pParser->aGblStrings, SbLOCAL ); // is dumped } return *pPool; } SbiSymScope SbiSymDef::GetScope() const { return pIn ? pIn->GetScope() : SbLOCAL; } // The procedure definition has three pools: // 1) aParams: is filled by the definition. Contains the // parameters' names, like they're used inside the body. // The first element is the return value. // 2) pPool: all local variables // 3) aLabels: labels SbiProcDef::SbiProcDef( SbiParser* pParser, const OUString& rName, bool bProcDecl ) : SbiSymDef( rName ) , aParams( pParser->aGblStrings, SbPARAM ) // is dumped , aLabels( pParser->aLclStrings, SbLOCAL ) // is not dumped , mbProcDecl( bProcDecl ) { aParams.SetParent( &pParser->aPublics ); pPool = new SbiSymPool( pParser->aGblStrings, SbLOCAL ); pPool->SetParent( &aParams ); nLine1 = nLine2 = 0; mePropMode = PROPERTY_MODE_NONE; bPublic = true; bCdecl = false; bStatic = false; // For return values the first element of the parameter // list is always defined with name and type of the proc aParams.AddSym( aName ); } SbiProcDef::~SbiProcDef() {} SbiProcDef* SbiProcDef::GetProcDef() { return this; } void SbiProcDef::SetType( SbxDataType t ) { SbiSymDef::SetType( t ); aParams.Get( 0 )->SetType( eType ); } // match with a forward-declaration // if the match is OK, pOld is replaced by this in the pool // pOld is deleted in any case! void SbiProcDef::Match( SbiProcDef* pOld ) { SbiSymDef *pn=NULL; // parameter 0 is the function name sal_uInt16 i; for( i = 1; i < aParams.GetSize(); i++ ) { SbiSymDef* po = pOld->aParams.Get( i ); pn = aParams.Get( i ); // no type matching - that is done during running // but is it maybe called with too little parameters? if( !po && !pn->IsOptional() && !pn->IsParamArray() ) { break; } pOld->aParams.Next(); } if( pn && i < aParams.GetSize() && pOld->pIn ) { // mark the whole line pOld->pIn->GetParser()->SetCol1( 0 ); pOld->pIn->GetParser()->Error( SbERR_BAD_DECLARATION, aName ); } if( !pIn && pOld->pIn ) { // Replace old entry with the new one nPos = pOld->nPos; nId = pOld->nId; pIn = pOld->pIn; pIn->aData.replace( nPos, this ).release(); } delete pOld; } void SbiProcDef::setPropertyMode( PropertyMode ePropMode ) { mePropMode = ePropMode; if( mePropMode != PROPERTY_MODE_NONE ) { // Prop name = original scanned procedure name maPropName = aName; // CompleteProcName includes "Property xxx " // to avoid conflicts with other symbols OUString aCompleteProcName = "Property "; switch( mePropMode ) { case PROPERTY_MODE_GET: aCompleteProcName += "Get "; break; case PROPERTY_MODE_LET: aCompleteProcName += "Let "; break; case PROPERTY_MODE_SET: aCompleteProcName += "Set "; break; case PROPERTY_MODE_NONE: OSL_FAIL( "Illegal PropertyMode PROPERTY_MODE_NONE" ); break; } aCompleteProcName += aName; aName = aCompleteProcName; } } SbiConstDef::SbiConstDef( const OUString& rName ) : SbiSymDef( rName ) { nVal = 0; eType = SbxINTEGER; } void SbiConstDef::Set( double n, SbxDataType t ) { aVal = ""; nVal = n; eType = t; } void SbiConstDef::Set( const OUString& n ) { aVal = n; nVal = 0; eType = SbxSTRING; } SbiConstDef::~SbiConstDef() {} SbiConstDef* SbiConstDef::GetConstDef() { return this; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/////////////////////////////////////// /// file: conversion.cpp /// 数制转换 /////////////////////////////////////// #include <iostream> #include "sqstack.h" using namespace std; /// /// 对于任意输入的一个非负十进制数,打印输出 /// 与其等值的八进制数 /// void conversion() { // 输入十进制数 int n; cout << "n = "; cin >> n; // 转换为八进制数 SqStack<int> s; InitStack(s); // 初始化为空栈 while(n) { Push(s, n%8); n = n / 8; } // 输出八进制数 while(!StackEmpty(s)) { int e; Pop(s,e); cout << e; } cout << endl; } /// /// 将十进制数转换为八进制数 /// int main() { conversion(); return 0; }<commit_msg>Fix: conversion zero<commit_after>/////////////////////////////////////// /// file: conversion.cpp /// 数制转换 /////////////////////////////////////// #include <iostream> #include "sqstack.h" using namespace std; /// /// 对于任意输入的一个非负十进制数,打印输出 /// 与其等值的八进制数 /// void conversion() { // 输入十进制数 int n; cout << "n = "; cin >> n; // 转换为八进制数 SqStack<int> s; InitStack(s); // 初始化为空栈 do { Push(s, n%8); n = n / 8; } while(n); // 输出八进制数 while(!StackEmpty(s)) { int e; Pop(s,e); cout << e; } cout << endl; } /// /// 将十进制数转换为八进制数 /// int main() { conversion(); return 0; }<|endoftext|>
<commit_before>#include <pqxx/compiler-internal.hxx> #include <iostream> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> // Don't try this at home: peeking inside libpqxx to see if we can test the // column_table() functionality #include <pqxx/config-internal-libpq.h> using namespace PGSTD; using namespace pqxx; // Example program for libpqxx. Perform a query and enumerate its output // using array indexing. // // Usage: test002 [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { // Set up connection to database string ConnectString = (argv[1] ? argv[1] : ""); connection C(ConnectString); // Start transaction within context of connection work T(C, "test2"); // Perform query within transaction result R( T.exec("SELECT * FROM pg_tables") ); // Let's keep the database waiting as briefly as possible: commit now, // before we start processing results. We could do this later, or since // we're not making any changes in the database that need to be committed, // we could in this case even omit it altogether. T.commit(); // Since we don't need the database anymore, we can be even more // considerate and close the connection now. This is optional. C.disconnect(); #ifdef PQXX_HAVE_PQFTABLE // Ah, this version of postgres will tell you which table a column in a // result came from. Let's just test that functionality... const oid rtable = R.column_table(0); if (rtable != R.column_table(result::tuple::size_type(0))) throw logic_error("Inconsistent result::column_table()"); const string rcol = R.column_name(0); const oid crtable = R.column_table(rcol); if (crtable != rtable) throw logic_error("Field " + rcol + " comes from " "'" + to_string(rtable) + "', " "but by name, result says it's from " "'" + to_string(crtable) + "'"); #endif // Now we've got all that settled, let's process our results. for (result::size_type i = 0; i < R.size(); ++i) { cout << '\t' << to_string(i) << '\t' << R[i][0].c_str() << endl; #ifdef PQXX_HAVE_PQFTABLE const oid ftable = R[i][0].table(); if (ftable != rtable) throw logic_error("Field says it comes from " "'" + to_string(ftable) + "'; " "expected '" + to_string(rtable) + "'"); const oid ttable = R[i].column_table(0); if (ttable != R[i].column_table(result::tuple::size_type(0))) throw logic_error("Inconsistent result::tuple::column_table()"); if (ttable != rtable) throw logic_error("Tuple says field comes from " "'" + to_string(ttable) + "'; " "expected '" + to_string(rtable) + "'"); const oid cttable = R[i].column_table(rcol); if (cttable != rtable) throw logic_error("Field comes from '" + to_string(rtable) + "', " "but by name, tuple says it's from '" + to_string(cttable) + "'"); #endif } } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <commit_msg>Verify that standard connection class reports errors immediately<commit_after>#include <pqxx/compiler-internal.hxx> #include <iostream> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> // Don't try this at home: peeking inside libpqxx to see if we can test the // column_table() functionality #include <pqxx/config-internal-libpq.h> using namespace PGSTD; using namespace pqxx; // Example program for libpqxx. Perform a query and enumerate its output // using array indexing. // // Usage: test002 [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { // Before we really connect, test the expected behaviour of the default // connection type, where a failure to connect results in an immediate // exception rather than a silent retry. bool failsOK = true; try { connection C("totally#invalid@connect$string!?"); failsOK = false; } catch (const broken_connection &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("Connection failure went unnoticed!"); // Set up connection to database string ConnectString = (argv[1] ? argv[1] : ""); connection C(ConnectString); // Start transaction within context of connection work T(C, "test2"); // Perform query within transaction result R( T.exec("SELECT * FROM pg_tables") ); // Let's keep the database waiting as briefly as possible: commit now, // before we start processing results. We could do this later, or since // we're not making any changes in the database that need to be committed, // we could in this case even omit it altogether. T.commit(); // Since we don't need the database anymore, we can be even more // considerate and close the connection now. This is optional. C.disconnect(); #ifdef PQXX_HAVE_PQFTABLE // Ah, this version of postgres will tell you which table a column in a // result came from. Let's just test that functionality... const oid rtable = R.column_table(0); if (rtable != R.column_table(result::tuple::size_type(0))) throw logic_error("Inconsistent result::column_table()"); const string rcol = R.column_name(0); const oid crtable = R.column_table(rcol); if (crtable != rtable) throw logic_error("Field " + rcol + " comes from " "'" + to_string(rtable) + "', " "but by name, result says it's from " "'" + to_string(crtable) + "'"); #endif // Now we've got all that settled, let's process our results. for (result::size_type i = 0; i < R.size(); ++i) { cout << '\t' << to_string(i) << '\t' << R[i][0].c_str() << endl; #ifdef PQXX_HAVE_PQFTABLE const oid ftable = R[i][0].table(); if (ftable != rtable) throw logic_error("Field says it comes from " "'" + to_string(ftable) + "'; " "expected '" + to_string(rtable) + "'"); const oid ttable = R[i].column_table(0); if (ttable != R[i].column_table(result::tuple::size_type(0))) throw logic_error("Inconsistent result::tuple::column_table()"); if (ttable != rtable) throw logic_error("Tuple says field comes from " "'" + to_string(ttable) + "'; " "expected '" + to_string(rtable) + "'"); const oid cttable = R[i].column_table(rcol); if (cttable != rtable) throw logic_error("Field comes from '" + to_string(rtable) + "', " "but by name, tuple says it's from '" + to_string(cttable) + "'"); #endif } } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" int main(int argc, char argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>Initial gtest main file<commit_after>#include "gtest/gtest.h" int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before>#include <hayai.hpp> #include <boost/format.hpp> #include <humblelogging/api.h> #include <db.h> #include <annotationsearch.h> #include <operators/precedence.h> #include <operators/inclusion.h> HUMBLE_LOGGER(logger, "default"); using namespace annis; class Tiger : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/tiger2"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class Ridges : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class RidgesFallback : public ::hayai::Fixture { public: RidgesFallback() :db(false) { } virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; BENCHMARK_F(Tiger, Cat, 5, 1) { AnnotationNameSearch search(db, "cat"); counter=0; while(search.hasNext()) { search.next(); counter++; } } // pos="NN" & norm="Blumen" & #1 _i_ #2 BENCHMARK_F(Ridges, PosNNIncludesNormBlumen, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "norm", "Blumen"); annis::Inclusion join(db, n1, n2); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(Ridges, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(Ridges, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(RidgesFallback, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(RidgesFallback, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } int main(int argc, char** argv) { humble::logging::Factory &fac = humble::logging::Factory::getInstance(); fac.setDefaultLogLevel(humble::logging::LogLevel::Info); fac.registerAppender(new humble::logging::FileAppender("benchmark_annis4.log")); hayai::ConsoleOutputter consoleOutputter; hayai::Benchmarker::AddOutputter(consoleOutputter); if(argc >= 2) { for(int i=1; i < argc; i++) { std::cout << "adding include filter" << argv[i] << std::endl; hayai::Benchmarker::AddIncludeFilter(argv[i]); } } hayai::Benchmarker::RunAllTests(); return 0; } <commit_msg>only execute benchmark once for testing<commit_after>#include <hayai.hpp> #include <boost/format.hpp> #include <humblelogging/api.h> #include <db.h> #include <annotationsearch.h> #include <operators/precedence.h> #include <operators/inclusion.h> HUMBLE_LOGGER(logger, "default"); using namespace annis; class Tiger : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/tiger2"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class Ridges : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class RidgesFallback : public ::hayai::Fixture { public: RidgesFallback() :db(false) { } virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; BENCHMARK_F(Tiger, Cat, 5, 1) { AnnotationNameSearch search(db, "cat"); counter=0; while(search.hasNext()) { search.next(); counter++; } } // pos="NN" & norm="Blumen" & #1 _i_ #2 BENCHMARK_F(Ridges, PosNNIncludesNormBlumen, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "norm", "Blumen"); annis::Inclusion join(db, n1, n2); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(Ridges, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(Ridges, TokPreceedingTok, 1, 1) { AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(RidgesFallback, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(RidgesFallback, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } int main(int argc, char** argv) { humble::logging::Factory &fac = humble::logging::Factory::getInstance(); fac.setDefaultLogLevel(humble::logging::LogLevel::Info); fac.registerAppender(new humble::logging::FileAppender("benchmark_annis4.log")); hayai::ConsoleOutputter consoleOutputter; hayai::Benchmarker::AddOutputter(consoleOutputter); if(argc >= 2) { for(int i=1; i < argc; i++) { std::cout << "adding include filter" << argv[i] << std::endl; hayai::Benchmarker::AddIncludeFilter(argv[i]); } } hayai::Benchmarker::RunAllTests(); return 0; } <|endoftext|>
<commit_before>/******************************************************************************/ /* Copyright (c) 2013 VectorChief (at github, bitbucket, sourceforge) */ /* Distributed under the MIT software license, see the accompanying */ /* file COPYING or http://www.opensource.org/licenses/mit-license.php */ /******************************************************************************/ #include "RooT.h" /******************************************************************************/ /**************************** PLATFORM - WIN32 ****************************/ /******************************************************************************/ #include <malloc.h> #include <windows.h> HINSTANCE hInst; HWND hWnd; HDC hWndDC; HBITMAP hFrm; HDC hFrmDC; BITMAPINFO DIBinfo = { sizeof(BITMAPINFOHEADER), /* biSize */ +x_res, /* biWidth */ -y_res, /* biHeight */ 1, /* biPlanes */ 32, /* biBitCount */ BI_RGB, /* biCompression */ x_res * y_res * sizeof(rt_word), /* biSizeImage */ 0, /* biXPelsPerMeter */ 0, /* biYPelsPerMeter */ 0, /* biClrUsed */ 0 /* biClrImportant */ }; /******************************************************************************/ /********************************** MAIN **********************************/ /******************************************************************************/ LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; hInst = hInstance; TCHAR wnd_class[] = "RooT"; WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpszClassName = wnd_class; wcex.style = CS_OWNDC; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.hInstance = hInst; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.hIconSm = NULL; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; if (!RegisterClassEx(&wcex)) { RT_LOGE("Couldn't register class\n"); return FALSE; } RECT wRect, cRect; hWnd = CreateWindow(wnd_class, title, WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, x_res, y_res, NULL, NULL, hInst, NULL); if (!hWnd) { RT_LOGE("Couldn't create window\n"); return FALSE; } GetWindowRect(hWnd, &wRect); GetClientRect(hWnd, &cRect); MoveWindow(hWnd, 100, 50, 2 * x_res - cRect.right, 2 * y_res - cRect.bottom, FALSE); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } /******************************************************************************/ /******************************** RENDERING *******************************/ /******************************************************************************/ rt_cell main_init() { try { scene = new rt_Scene(&sc_root, x_res, y_res, x_row, frame, malloc, free); } catch (rt_Exception e) { RT_LOGE("Exception: %s\n", e.err); return 0; } return 1; } /* performance variables */ static LARGE_INTEGER tm; static LARGE_INTEGER fr; /* time counter varibales */ static rt_long init_time = 0; static rt_long last_time = 0; static rt_long time = 0; static rt_word fps = 0; static rt_word cnt = 0; /* virtual keys array */ #define KEY_MASK 0x00FF static rt_byte h_keys[KEY_MASK + 1]; static rt_byte t_keys[KEY_MASK + 1]; static rt_byte r_keys[KEY_MASK + 1]; /* hold keys */ #define H_KEYS(k) (h_keys[(k) & KEY_MASK]) /* toggle on press */ #define T_KEYS(k) (t_keys[(k) & KEY_MASK]) /* toggle on release */ #define R_KEYS(k) (r_keys[(k) & KEY_MASK]) rt_cell main_step() { if (scene == RT_NULL) { return 0; } QueryPerformanceCounter(&tm); time = (rt_long)(tm.QuadPart * 1000 / fr.QuadPart); if (init_time == 0) { init_time = time; } time = time - init_time; cnt++; if (time - last_time >= 500) { fps = cnt * 1000 / (time - last_time); RT_LOGI("FPS = %d\n", fps); cnt = 0; last_time = time; } if (H_KEYS('W')) scene->update(time, RT_CAMERA_MOVE_FORWARD); if (H_KEYS('S')) scene->update(time, RT_CAMERA_MOVE_BACK); if (H_KEYS('A')) scene->update(time, RT_CAMERA_MOVE_LEFT); if (H_KEYS('D')) scene->update(time, RT_CAMERA_MOVE_RIGHT); if (H_KEYS(VK_UP)) scene->update(time, RT_CAMERA_ROTATE_DOWN); if (H_KEYS(VK_DOWN)) scene->update(time, RT_CAMERA_ROTATE_UP); if (H_KEYS(VK_LEFT)) scene->update(time, RT_CAMERA_ROTATE_LEFT); if (H_KEYS(VK_RIGHT)) scene->update(time, RT_CAMERA_ROTATE_RIGHT); if (T_KEYS(VK_F2)) fsaa = RT_FSAA_4X - fsaa; if (T_KEYS(VK_ESCAPE)) { return 0; } memset(t_keys, 0, sizeof(t_keys)); memset(r_keys, 0, sizeof(r_keys)); scene->set_fsaa(fsaa); scene->render(time); scene->render_fps(x_res - 10, 10, -1, 2, fps); SetDIBitsToDevice(hWndDC, 0, 0, x_res, y_res, 0, 0, 0, y_res, scene->get_frame(), &DIBinfo, DIB_RGB_COLORS); return 1; } rt_cell main_done() { if (scene == RT_NULL) { return 0; } delete scene; return 1; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { rt_cell ret, key; switch (message) { case WM_CREATE: { /* RT_LOGI("Window = %p\n", hWnd); */ hWndDC = GetDC(hWnd); if (hWndDC == NULL) { return -1; } hFrm = CreateDIBSection(NULL, &DIBinfo, DIB_RGB_COLORS, (void **)&frame, NULL, 0); if (hFrm == NULL || frame == NULL) { return -1; } hFrmDC = CreateCompatibleDC(hWndDC); if (hFrmDC == NULL) { return -1; } SelectObject(hFrmDC, hFrm); ret = main_init(); if (ret == 0) { return -1; } QueryPerformanceFrequency(&fr); } break; case WM_KEYDOWN: { key = wParam; /* RT_LOGI("Key press = %X\n", key); */ key &= KEY_MASK; if (h_keys[key] == 0) { t_keys[key] = 1; } h_keys[key] = 1; } break; case WM_KEYUP: { key = wParam; /* RT_LOGI("Key release = %X\n", key); */ key &= KEY_MASK; h_keys[key] = 0; r_keys[key] = 1; } break; case WM_MOUSEMOVE: break; case WM_PAINT: { ret = main_step(); if (ret == 0) { DestroyWindow(hWnd); } } break; case WM_DESTROY: { ret = main_done(); if (hFrmDC != NULL) { DeleteDC(hFrmDC); hFrmDC = NULL; } if (hFrm != NULL) { DeleteObject(hFrm); hFrm = NULL; } if (hWndDC != NULL) { ReleaseDC(hWnd, hWndDC); hWndDC = NULL; } PostQuitMessage(0); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ <commit_msg>rename time to cur_time for consistency with Linux code<commit_after>/******************************************************************************/ /* Copyright (c) 2013 VectorChief (at github, bitbucket, sourceforge) */ /* Distributed under the MIT software license, see the accompanying */ /* file COPYING or http://www.opensource.org/licenses/mit-license.php */ /******************************************************************************/ #include "RooT.h" /******************************************************************************/ /**************************** PLATFORM - WIN32 ****************************/ /******************************************************************************/ #include <malloc.h> #include <windows.h> HINSTANCE hInst; HWND hWnd; HDC hWndDC; HBITMAP hFrm; HDC hFrmDC; BITMAPINFO DIBinfo = { sizeof(BITMAPINFOHEADER), /* biSize */ +x_res, /* biWidth */ -y_res, /* biHeight */ 1, /* biPlanes */ 32, /* biBitCount */ BI_RGB, /* biCompression */ x_res * y_res * sizeof(rt_word), /* biSizeImage */ 0, /* biXPelsPerMeter */ 0, /* biYPelsPerMeter */ 0, /* biClrUsed */ 0 /* biClrImportant */ }; /******************************************************************************/ /********************************** MAIN **********************************/ /******************************************************************************/ LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; hInst = hInstance; TCHAR wnd_class[] = "RooT"; WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpszClassName = wnd_class; wcex.style = CS_OWNDC; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.hInstance = hInst; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.hIconSm = NULL; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; if (!RegisterClassEx(&wcex)) { RT_LOGE("Couldn't register class\n"); return FALSE; } RECT wRect, cRect; hWnd = CreateWindow(wnd_class, title, WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, x_res, y_res, NULL, NULL, hInst, NULL); if (!hWnd) { RT_LOGE("Couldn't create window\n"); return FALSE; } GetWindowRect(hWnd, &wRect); GetClientRect(hWnd, &cRect); MoveWindow(hWnd, 100, 50, 2 * x_res - cRect.right, 2 * y_res - cRect.bottom, FALSE); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } /******************************************************************************/ /******************************** RENDERING *******************************/ /******************************************************************************/ rt_cell main_init() { try { scene = new rt_Scene(&sc_root, x_res, y_res, x_row, frame, malloc, free); } catch (rt_Exception e) { RT_LOGE("Exception: %s\n", e.err); return 0; } return 1; } /* performance variables */ static LARGE_INTEGER tm; static LARGE_INTEGER fr; /* time counter varibales */ static rt_long init_time = 0; static rt_long last_time = 0; static rt_long cur_time = 0; static rt_word fps = 0; static rt_word cnt = 0; /* virtual keys array */ #define KEY_MASK 0x00FF static rt_byte h_keys[KEY_MASK + 1]; static rt_byte t_keys[KEY_MASK + 1]; static rt_byte r_keys[KEY_MASK + 1]; /* hold keys */ #define H_KEYS(k) (h_keys[(k) & KEY_MASK]) /* toggle on press */ #define T_KEYS(k) (t_keys[(k) & KEY_MASK]) /* toggle on release */ #define R_KEYS(k) (r_keys[(k) & KEY_MASK]) rt_cell main_step() { if (scene == RT_NULL) { return 0; } QueryPerformanceCounter(&tm); cur_time = (rt_long)(tm.QuadPart * 1000 / fr.QuadPart); if (init_time == 0) { init_time = cur_time; } cur_time = cur_time - init_time; cnt++; if (cur_time - last_time >= 500) { fps = cnt * 1000 / (cur_time - last_time); RT_LOGI("FPS = %.1f\n", (rt_real)fps); cnt = 0; last_time = cur_time; } if (H_KEYS('W')) scene->update(cur_time, RT_CAMERA_MOVE_FORWARD); if (H_KEYS('S')) scene->update(cur_time, RT_CAMERA_MOVE_BACK); if (H_KEYS('A')) scene->update(cur_time, RT_CAMERA_MOVE_LEFT); if (H_KEYS('D')) scene->update(cur_time, RT_CAMERA_MOVE_RIGHT); if (H_KEYS(VK_UP)) scene->update(cur_time, RT_CAMERA_ROTATE_DOWN); if (H_KEYS(VK_DOWN)) scene->update(cur_time, RT_CAMERA_ROTATE_UP); if (H_KEYS(VK_LEFT)) scene->update(cur_time, RT_CAMERA_ROTATE_LEFT); if (H_KEYS(VK_RIGHT)) scene->update(cur_time, RT_CAMERA_ROTATE_RIGHT); if (T_KEYS(VK_F2)) fsaa = RT_FSAA_4X - fsaa; if (T_KEYS(VK_ESCAPE)) { return 0; } memset(t_keys, 0, sizeof(t_keys)); memset(r_keys, 0, sizeof(r_keys)); scene->set_fsaa(fsaa); scene->render(cur_time); scene->render_fps(x_res - 10, 10, -1, 2, fps); SetDIBitsToDevice(hWndDC, 0, 0, x_res, y_res, 0, 0, 0, y_res, scene->get_frame(), &DIBinfo, DIB_RGB_COLORS); return 1; } rt_cell main_done() { if (scene == RT_NULL) { return 0; } delete scene; return 1; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { rt_cell ret, key; switch (message) { case WM_CREATE: { /* RT_LOGI("Window = %p\n", hWnd); */ hWndDC = GetDC(hWnd); if (hWndDC == NULL) { return -1; } hFrm = CreateDIBSection(NULL, &DIBinfo, DIB_RGB_COLORS, (void **)&frame, NULL, 0); if (hFrm == NULL || frame == NULL) { return -1; } hFrmDC = CreateCompatibleDC(hWndDC); if (hFrmDC == NULL) { return -1; } SelectObject(hFrmDC, hFrm); ret = main_init(); if (ret == 0) { return -1; } QueryPerformanceFrequency(&fr); } break; case WM_KEYDOWN: { key = wParam; /* RT_LOGI("Key press = %X\n", key); */ key &= KEY_MASK; if (h_keys[key] == 0) { t_keys[key] = 1; } h_keys[key] = 1; } break; case WM_KEYUP: { key = wParam; /* RT_LOGI("Key release = %X\n", key); */ key &= KEY_MASK; h_keys[key] = 0; r_keys[key] = 1; } break; case WM_MOUSEMOVE: break; case WM_PAINT: { ret = main_step(); if (ret == 0) { DestroyWindow(hWnd); } } break; case WM_DESTROY: { ret = main_done(); if (hFrmDC != NULL) { DeleteDC(hFrmDC); hFrmDC = NULL; } if (hFrm != NULL) { DeleteObject(hFrm); hFrm = NULL; } if (hWndDC != NULL) { ReleaseDC(hWnd, hWndDC); hWndDC = NULL; } PostQuitMessage(0); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ <|endoftext|>
<commit_before>// Copyright (c) 2015-2017 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "expedited.h" #include "tweak.h" #include "main.h" #include "rpc/server.h" #include "thinblock.h" #include "unlimited.h" #include <univalue.h> #define NUM_XPEDITED_STORE 10 // Just save the last few expedited sent blocks so we don't resend (uint256) uint256 xpeditedBlkSent[NUM_XPEDITED_STORE]; // zeros on construction) int xpeditedBlkSendPos = 0; using namespace std; bool CheckAndRequestExpeditedBlocks(CNode *pfrom) { if (pfrom->nVersion >= EXPEDITED_VERSION) { BOOST_FOREACH (std::string &strAddr, mapMultiArgs["-expeditedblock"]) { std::string strListeningPeerIP; std::string strPeerIP = pfrom->addr.ToString(); // Add the peer's listening port if it was provided (only misbehaving clients do not provide it) if (pfrom->addrFromPort != 0) { int pos1 = strAddr.rfind(":"); int pos2 = strAddr.rfind("]:"); if (pos1 <= 0 && pos2 <= 0) strAddr += ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); pos1 = strPeerIP.rfind(":"); pos2 = strPeerIP.rfind("]:"); // Handle both ipv4 and ipv6 cases if (pos1 <= 0 && pos2 <= 0) strListeningPeerIP = strPeerIP + ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); else if (pos1 > 0) strListeningPeerIP = strPeerIP.substr(0, pos1) + ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); else strListeningPeerIP = strPeerIP.substr(0, pos2) + ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); } else strListeningPeerIP = strPeerIP; if (strAddr == strListeningPeerIP) { if (!IsThinBlocksEnabled()) { LogPrintf("You do not have Thinblocks enabled. You can not request expedited blocks from peer %s " "(%d).\n", strListeningPeerIP, pfrom->id); return false; } else if (!pfrom->ThinBlockCapable()) { LogPrintf("Thinblocks is not enabled on remote peer. You can not request expedited blocks from " "peer %s (%d).\n", strListeningPeerIP, pfrom->id); return false; } else { LogPrintf("Requesting expedited blocks from peer %s (%d).\n", strListeningPeerIP, pfrom->id); pfrom->PushMessage(NetMsgType::XPEDITEDREQUEST, ((uint64_t)EXPEDITED_BLOCKS)); LOCK(cs_xpedited); xpeditedBlkUp.push_back(pfrom); return true; } } } } return false; } void HandleExpeditedRequest(CDataStream &vRecv, CNode *pfrom) { uint64_t options; vRecv >> options; bool stop = ((options & EXPEDITED_STOP) != 0); // Are we starting or stopping expedited service? if (options & EXPEDITED_BLOCKS) { LOCK(cs_xpedited); if (stop) // If stopping, find the array element and clear it. { LogPrint("blk", "Stopping expedited blocks to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); std::vector<CNode *>::iterator it = std::find(xpeditedBlk.begin(), xpeditedBlk.end(), pfrom); if (it != xpeditedBlk.end()) { *it = NULL; pfrom->Release(); } } else // Otherwise, add the new node to the end { std::vector<CNode *>::iterator it1 = std::find(xpeditedBlk.begin(), xpeditedBlk.end(), pfrom); if (it1 == xpeditedBlk.end()) // don't add it twice { unsigned int maxExpedited = GetArg("-maxexpeditedblockrecipients", 32); if (xpeditedBlk.size() < maxExpedited) { LogPrint("blk", "Starting expedited blocks to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); // find an empty array location std::vector<CNode *>::iterator it = std::find(xpeditedBlk.begin(), xpeditedBlk.end(), ((CNode *)NULL)); if (it != xpeditedBlk.end()) *it = pfrom; else xpeditedBlk.push_back(pfrom); pfrom->AddRef(); // add a reference because we have added this pointer into the expedited array } else { LogPrint("blk", "Expedited blocks requested from peer %s (%d), but I am full.\n", pfrom->addrName.c_str(), pfrom->id); } } } } if (options & EXPEDITED_TXNS) { LOCK(cs_xpedited); if (stop) // If stopping, find the array element and clear it. { LogPrint("blk", "Stopping expedited transactions to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); std::vector<CNode *>::iterator it = std::find(xpeditedTxn.begin(), xpeditedTxn.end(), pfrom); if (it != xpeditedTxn.end()) { *it = NULL; pfrom->Release(); } } else // Otherwise, add the new node to the end { std::vector<CNode *>::iterator it1 = std::find(xpeditedTxn.begin(), xpeditedTxn.end(), pfrom); if (it1 == xpeditedTxn.end()) // don't add it twice { unsigned int maxExpedited = GetArg("-maxexpeditedtxrecipients", 32); if (xpeditedTxn.size() < maxExpedited) { LogPrint("blk", "Starting expedited transactions to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); std::vector<CNode *>::iterator it = std::find(xpeditedTxn.begin(), xpeditedTxn.end(), ((CNode *)NULL)); if (it != xpeditedTxn.end()) *it = pfrom; else xpeditedTxn.push_back(pfrom); pfrom->AddRef(); } else { LogPrint("blk", "Expedited transactions requested from peer %s (%d), but I am full.\n", pfrom->addrName.c_str(), pfrom->id); } } } } } bool IsRecentlyExpeditedAndStore(const uint256 &hash) { for (int i = 0; i < NUM_XPEDITED_STORE; i++) if (xpeditedBlkSent[i] == hash) return true; xpeditedBlkSent[xpeditedBlkSendPos] = hash; xpeditedBlkSendPos++; if (xpeditedBlkSendPos >= NUM_XPEDITED_STORE) xpeditedBlkSendPos = 0; return false; } bool HandleExpeditedBlock(CDataStream &vRecv, CNode *pfrom) { unsigned char hops; unsigned char msgType; vRecv >> msgType >> hops; if (msgType == EXPEDITED_MSG_XTHIN) { CXThinBlock thinBlock; vRecv >> thinBlock; uint256 blkHash = thinBlock.header.GetHash(); CInv inv(MSG_BLOCK, blkHash); BlockMap::iterator mapEntry = mapBlockIndex.find(blkHash); CBlockIndex *blkidx = NULL; unsigned int status = 0; if (mapEntry != mapBlockIndex.end()) { blkidx = mapEntry->second; if (blkidx) status = blkidx->nStatus; } bool newBlock = ((blkidx == NULL) || (!(blkidx->nStatus & BLOCK_HAVE_DATA))); // If I have never seen the block or just seen an INV, treat the block as new int nSizeThinBlock = ::GetSerializeSize( thinBlock, SER_NETWORK, PROTOCOL_VERSION); // TODO replace with size of vRecv for efficiency LogPrint("thin", "Received %s expedited thinblock %s from peer %s (%d). Hop %d. Size %d bytes. (status %d,0x%x)\n", newBlock ? "new" : "repeated", inv.hash.ToString(), pfrom->addrName.c_str(), pfrom->id, hops, nSizeThinBlock, status, status); // Skip if we've already seen this block // TODO move this above the print, once we ensure no unexpected dups. if (IsRecentlyExpeditedAndStore(blkHash)) return true; if (!newBlock) { // TODO determine if we have the block or just have an INV to it. return true; } CValidationState state; if (!CheckBlockHeader(thinBlock.header, state, true)) // block header is bad { // demerit the sender, it should have checked the header before expedited relay return false; } // TODO: Start headers-only mining now SendExpeditedBlock(thinBlock, hops + 1, pfrom); // I should push the vRecv rather than reserialize thinBlock.process(pfrom, nSizeThinBlock, NetMsgType::XPEDITEDBLK); } else { LogPrint("thin", "Received unknown (0x%x) expedited message from peer %s (%d). Hop %d.\n", msgType, pfrom->addrName.c_str(), pfrom->id, hops); return false; } return true; } void SendExpeditedBlock(CXThinBlock &thinBlock, unsigned char hops, const CNode *skip) { // bool cameFromUpstream = false; LOCK(cs_xpedited); std::vector<CNode *>::iterator end = xpeditedBlk.end(); for (std::vector<CNode *>::iterator it = xpeditedBlk.begin(); it != end; it++) { CNode *n = *it; // if (n == skip) cameFromUpstream = true; if ((n != skip) && (n != NULL)) // Don't send it back in case there is a forwarding loop { if (n->fDisconnect) { *it = NULL; n->Release(); } else { LogPrint("thin", "Sending expedited block %s to %s.\n", thinBlock.header.GetHash().ToString(), n->addrName.c_str()); n->PushMessage(NetMsgType::XPEDITEDBLK, (unsigned char)EXPEDITED_MSG_XTHIN, hops, thinBlock); // I should push the vRecv rather than reserialize n->blocksSent += 1; } } } #if 0 // Probably better to have the upstream explicitly request blocks from the downstream. // Upstream // TODO, if it came from an upstream block I really want to delay for a short period and then check if we got it and then send. But this solves some of the issue if (!cameFromUpstream) { LOCK(cs_xpedited); std::vector<CNode*>::iterator end = xpeditedBlkUp.end(); for (std::vector<CNode*>::iterator it = xpeditedBlkUp.begin(); it != end; it++) { CNode* n = *it; if ((n != skip)&&(n != NULL)) // Don't send it back to the sender in case there is a forwarding loop { if (n->fDisconnect) { *it = NULL; n->Release(); } else { LogPrint("thin", "Sending expedited block %s upstream to %s.\n", thinBlock.header.GetHash().ToString(),n->addrName.c_str()); // I should push the vRecv rather than reserialize n->PushMessage(NetMsgType::XPEDITEDBLK, (unsigned char) EXPEDITED_MSG_XTHIN, hops, thinBlock); n->blocksSent += 1; } } } } #endif } void SendExpeditedBlock(const CBlock &block, const CNode *skip) { // If we've already put the block in our hash table, we've already sent it out // BlockMap::iterator it = mapBlockIndex.find(block.GetHash()); // if (it != mapBlockIndex.end()) return; if (!IsRecentlyExpeditedAndStore(block.GetHash())) { CXThinBlock thinBlock(block); SendExpeditedBlock(thinBlock, 0, skip); } else { // LogPrint("thin", "No need to send expedited block %s\n", block.GetHash().ToString()); } } <commit_msg>Cleanup HandleExpeditedBlock()<commit_after>// Copyright (c) 2015-2017 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "expedited.h" #include "tweak.h" #include "main.h" #include "rpc/server.h" #include "thinblock.h" #include "unlimited.h" #include <univalue.h> #define NUM_XPEDITED_STORE 10 // Just save the last few expedited sent blocks so we don't resend (uint256) uint256 xpeditedBlkSent[NUM_XPEDITED_STORE]; // zeros on construction) int xpeditedBlkSendPos = 0; using namespace std; bool CheckAndRequestExpeditedBlocks(CNode *pfrom) { if (pfrom->nVersion >= EXPEDITED_VERSION) { BOOST_FOREACH (std::string &strAddr, mapMultiArgs["-expeditedblock"]) { std::string strListeningPeerIP; std::string strPeerIP = pfrom->addr.ToString(); // Add the peer's listening port if it was provided (only misbehaving clients do not provide it) if (pfrom->addrFromPort != 0) { int pos1 = strAddr.rfind(":"); int pos2 = strAddr.rfind("]:"); if (pos1 <= 0 && pos2 <= 0) strAddr += ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); pos1 = strPeerIP.rfind(":"); pos2 = strPeerIP.rfind("]:"); // Handle both ipv4 and ipv6 cases if (pos1 <= 0 && pos2 <= 0) strListeningPeerIP = strPeerIP + ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); else if (pos1 > 0) strListeningPeerIP = strPeerIP.substr(0, pos1) + ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); else strListeningPeerIP = strPeerIP.substr(0, pos2) + ':' + boost::lexical_cast<std::string>(pfrom->addrFromPort); } else strListeningPeerIP = strPeerIP; if (strAddr == strListeningPeerIP) { if (!IsThinBlocksEnabled()) { LogPrintf("You do not have Thinblocks enabled. You can not request expedited blocks from peer %s " "(%d).\n", strListeningPeerIP, pfrom->id); return false; } else if (!pfrom->ThinBlockCapable()) { LogPrintf("Thinblocks is not enabled on remote peer. You can not request expedited blocks from " "peer %s (%d).\n", strListeningPeerIP, pfrom->id); return false; } else { LogPrintf("Requesting expedited blocks from peer %s (%d).\n", strListeningPeerIP, pfrom->id); pfrom->PushMessage(NetMsgType::XPEDITEDREQUEST, ((uint64_t)EXPEDITED_BLOCKS)); LOCK(cs_xpedited); xpeditedBlkUp.push_back(pfrom); return true; } } } } return false; } void HandleExpeditedRequest(CDataStream &vRecv, CNode *pfrom) { uint64_t options; vRecv >> options; bool stop = ((options & EXPEDITED_STOP) != 0); // Are we starting or stopping expedited service? if (options & EXPEDITED_BLOCKS) { LOCK(cs_xpedited); if (stop) // If stopping, find the array element and clear it. { LogPrint("blk", "Stopping expedited blocks to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); std::vector<CNode *>::iterator it = std::find(xpeditedBlk.begin(), xpeditedBlk.end(), pfrom); if (it != xpeditedBlk.end()) { *it = NULL; pfrom->Release(); } } else // Otherwise, add the new node to the end { std::vector<CNode *>::iterator it1 = std::find(xpeditedBlk.begin(), xpeditedBlk.end(), pfrom); if (it1 == xpeditedBlk.end()) // don't add it twice { unsigned int maxExpedited = GetArg("-maxexpeditedblockrecipients", 32); if (xpeditedBlk.size() < maxExpedited) { LogPrint("blk", "Starting expedited blocks to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); // find an empty array location std::vector<CNode *>::iterator it = std::find(xpeditedBlk.begin(), xpeditedBlk.end(), ((CNode *)NULL)); if (it != xpeditedBlk.end()) *it = pfrom; else xpeditedBlk.push_back(pfrom); pfrom->AddRef(); // add a reference because we have added this pointer into the expedited array } else { LogPrint("blk", "Expedited blocks requested from peer %s (%d), but I am full.\n", pfrom->addrName.c_str(), pfrom->id); } } } } if (options & EXPEDITED_TXNS) { LOCK(cs_xpedited); if (stop) // If stopping, find the array element and clear it. { LogPrint("blk", "Stopping expedited transactions to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); std::vector<CNode *>::iterator it = std::find(xpeditedTxn.begin(), xpeditedTxn.end(), pfrom); if (it != xpeditedTxn.end()) { *it = NULL; pfrom->Release(); } } else // Otherwise, add the new node to the end { std::vector<CNode *>::iterator it1 = std::find(xpeditedTxn.begin(), xpeditedTxn.end(), pfrom); if (it1 == xpeditedTxn.end()) // don't add it twice { unsigned int maxExpedited = GetArg("-maxexpeditedtxrecipients", 32); if (xpeditedTxn.size() < maxExpedited) { LogPrint("blk", "Starting expedited transactions to peer %s (%d).\n", pfrom->addrName.c_str(), pfrom->id); std::vector<CNode *>::iterator it = std::find(xpeditedTxn.begin(), xpeditedTxn.end(), ((CNode *)NULL)); if (it != xpeditedTxn.end()) *it = pfrom; else xpeditedTxn.push_back(pfrom); pfrom->AddRef(); } else { LogPrint("blk", "Expedited transactions requested from peer %s (%d), but I am full.\n", pfrom->addrName.c_str(), pfrom->id); } } } } } bool IsRecentlyExpeditedAndStore(const uint256 &hash) { for (int i = 0; i < NUM_XPEDITED_STORE; i++) if (xpeditedBlkSent[i] == hash) return true; xpeditedBlkSent[xpeditedBlkSendPos] = hash; xpeditedBlkSendPos++; if (xpeditedBlkSendPos >= NUM_XPEDITED_STORE) xpeditedBlkSendPos = 0; return false; } bool HandleExpeditedBlock(CDataStream &vRecv, CNode *pfrom) { unsigned char hops; unsigned char msgType; vRecv >> msgType >> hops; if (msgType == EXPEDITED_MSG_XTHIN) { CXThinBlock thinBlock; vRecv >> thinBlock; uint256 blkHash = thinBlock.header.GetHash(); CInv inv(MSG_BLOCK, blkHash); bool newBlock = false; unsigned int status = 0; { LOCK(cs_main); BlockMap::iterator mapEntry = mapBlockIndex.find(blkHash); CBlockIndex *blkidx = NULL; if (mapEntry != mapBlockIndex.end()) { blkidx = mapEntry->second; if (blkidx) status = blkidx->nStatus; } // If we do not have the block on disk or do not have the header yet then treat the block as new. newBlock = ((blkidx == NULL) || (!(blkidx->nStatus & BLOCK_HAVE_DATA))); } int nSizeThinBlock = ::GetSerializeSize(thinBlock, SER_NETWORK, PROTOCOL_VERSION); LogPrint("thin", "Received %s expedited thinblock %s from peer %s (%d). Hop %d. Size %d bytes. (status %d,0x%x)\n", newBlock ? "new" : "repeated", inv.hash.ToString(), pfrom->addrName.c_str(), pfrom->id, hops, nSizeThinBlock, status, status); // TODO: Move this section above the print once we ensure no unexpected dups. // Skip if we've already seen this block if (IsRecentlyExpeditedAndStore(blkHash)) return true; if (!newBlock) return true; CValidationState state; if (!CheckBlockHeader(thinBlock.header, state, true)) return false; // TODO: Start headers-only mining now SendExpeditedBlock(thinBlock, hops + 1, pfrom); // Process the thinblock thinBlock.process(pfrom, nSizeThinBlock, NetMsgType::XPEDITEDBLK); } else { LogPrint("thin", "Received unknown (0x%x) expedited message from peer %s (%d). Hop %d.\n", msgType, pfrom->addrName.c_str(), pfrom->id, hops); return false; } return true; } void SendExpeditedBlock(CXThinBlock &thinBlock, unsigned char hops, const CNode *skip) { // bool cameFromUpstream = false; LOCK(cs_xpedited); std::vector<CNode *>::iterator end = xpeditedBlk.end(); for (std::vector<CNode *>::iterator it = xpeditedBlk.begin(); it != end; it++) { CNode *n = *it; // if (n == skip) cameFromUpstream = true; if ((n != skip) && (n != NULL)) // Don't send it back in case there is a forwarding loop { if (n->fDisconnect) { *it = NULL; n->Release(); } else { LogPrint("thin", "Sending expedited block %s to %s.\n", thinBlock.header.GetHash().ToString(), n->addrName.c_str()); n->PushMessage(NetMsgType::XPEDITEDBLK, (unsigned char)EXPEDITED_MSG_XTHIN, hops, thinBlock); // I should push the vRecv rather than reserialize n->blocksSent += 1; } } } #if 0 // Probably better to have the upstream explicitly request blocks from the downstream. // Upstream // TODO, if it came from an upstream block I really want to delay for a short period and then check if we got it and then send. But this solves some of the issue if (!cameFromUpstream) { LOCK(cs_xpedited); std::vector<CNode*>::iterator end = xpeditedBlkUp.end(); for (std::vector<CNode*>::iterator it = xpeditedBlkUp.begin(); it != end; it++) { CNode* n = *it; if ((n != skip)&&(n != NULL)) // Don't send it back to the sender in case there is a forwarding loop { if (n->fDisconnect) { *it = NULL; n->Release(); } else { LogPrint("thin", "Sending expedited block %s upstream to %s.\n", thinBlock.header.GetHash().ToString(),n->addrName.c_str()); // I should push the vRecv rather than reserialize n->PushMessage(NetMsgType::XPEDITEDBLK, (unsigned char) EXPEDITED_MSG_XTHIN, hops, thinBlock); n->blocksSent += 1; } } } } #endif } void SendExpeditedBlock(const CBlock &block, const CNode *skip) { // If we've already put the block in our hash table, we've already sent it out // BlockMap::iterator it = mapBlockIndex.find(block.GetHash()); // if (it != mapBlockIndex.end()) return; if (!IsRecentlyExpeditedAndStore(block.GetHash())) { CXThinBlock thinBlock(block); SendExpeditedBlock(thinBlock, 0, skip); } else { // LogPrint("thin", "No need to send expedited block %s\n", block.GetHash().ToString()); } } <|endoftext|>
<commit_before>/* SbHalfPong, sort of like Pong but for one author: Ulrike Hager */ #include <iostream> #include <string> #include <sstream> #include <stdexcept> #include <climits> #include <cmath> #include <random> #include <algorithm> #include <functional> #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_image.h> #include "SbTexture.h" #include "SbTimer.h" #include "SbWindow.h" #include "SbObject.h" const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 600; class Ball; class Spark; class Paddle; class Paddle : public SbObject { public: Paddle(); void handle_event(const SDL_Event& event); int move(); }; class Ball : public SbObject { public: Ball(); // void handle_event(const SDL_Event& event); /*! \retval 1 if ball in goal \retval 0 else */ int move(const SDL_Rect& paddleBox); void render(); /*! Reset after goal. */ void reset(); static Uint32 resetball(Uint32 interval, void *param ); Uint32 remove_spark(Uint32 interval, void *param, int index ); private: int goal_ = 0; std::vector<Spark> sparks_; std::default_random_engine generator_; std::uniform_int_distribution<int> distr_number { 15, 30 }; std::normal_distribution<double> distr_position { 0.0, 0.01 }; std::normal_distribution<double> distr_size { 0.003, 0.002 }; std::uniform_int_distribution<int> distr_lifetime { 100, 350 }; void create_sparks(); void delete_spark(int index); }; class Spark : public SbObject { friend class Ball; public: Spark(double x, double y, double width, double height); ~Spark(); static Uint32 expire(Uint32 interval, void* param); void set_texture(SbTexture* tex) {texture_ = tex;} int index() { return index_;} bool is_dead() {return is_dead_;} Uint32 lifetime() { return lifetime_;} private: // SDL_TimerID spark_timer_; int index_ = 0; bool is_dead_ = false; Uint32 lifetime_ = 100; }; /*! Paddle implementation */ Paddle::Paddle() : SbObject(SCREEN_WIDTH - 70, 200, 20, 80) { // bounding_rect_ = {}; velocity_y_ = 0; velocity_ = 1200; SDL_Color color = {210, 160, 10, 0}; texture_ = new SbTexture(); texture_->from_rectangle( window->renderer(), bounding_rect_.w, bounding_rect_.h, color ); } void Paddle::handle_event(const SDL_Event& event) { SbObject::handle_event( event ); if( event.type == SDL_KEYDOWN && event.key.repeat == 0 ) { switch( event.key.keysym.sym ) { case SDLK_UP: velocity_y_ -= velocity_; break; case SDLK_DOWN: velocity_y_ += velocity_; break; } } else if( event.type == SDL_KEYUP && event.key.repeat == 0 ) { switch( event.key.keysym.sym ) { case SDLK_UP: velocity_y_ += velocity_; break; case SDLK_DOWN: velocity_y_ -= velocity_; break; } } } int Paddle::move() { Uint32 deltaT = timer_.get_time(); int velocity = ( window->height() / velocity_y_ )* deltaT; bounding_rect_.y += velocity; if( ( bounding_rect_.y < 0 ) || ( bounding_rect_.y + bounding_rect_.h > window->height() ) ) { bounding_rect_.y -= velocity; } move_bounding_box(); timer_.start(); return 0; } Spark::Spark(double x, double y, double width, double height) : SbObject(x,y,width,height) { } Spark::~Spark() { #ifdef DEBUG std::cout << "[Spark::~Spark] index " << index_ << " - lifetime " << lifetime_ << std::endl; #endif // DEBUG texture_ = nullptr; // SDL_RemoveTimer(spark_timer_); } Uint32 Spark::expire(Uint32 interval, void* param) { #ifdef DEBUG std::cout << "[Spark::expire] interval " << interval << std::flush; #endif // DEBUG Spark* spark = ((Spark*)param); #ifdef DEBUG std::cout << "[Spark::expire] index " << spark->index_ << std::endl; #endif // DEBUG if (spark) spark->is_dead_ = true; return(0); } Uint32 Ball::remove_spark(Uint32 interval, void *param, int index ) { ((Ball*)param)->delete_spark(index); return(0); } void Ball::delete_spark(int index) { std::remove_if( sparks_.begin(), sparks_.end(), [index](Spark& spark) -> bool { return spark.index() == index;} ); // ((Spark*)param)->set_texture( nullptr ); } /*! Ball implementation */ Ball::Ball() : SbObject(50, 300, 25, 25) { // bounding_box_ = {}; velocity_y_ = 1500; velocity_x_ = 1500; velocity_ = 1500; texture_ = new SbTexture(); texture_->from_file(window->renderer(), "resources/ball.png", bounding_rect_.w, bounding_rect_.h ); } void Ball::create_sparks() { #ifdef DEBUG std::cout << "[Ball::create_sparks]" << std::endl; #endif // DEBUG if (! sparks_.empty() ) { #ifdef DEBUG std::cout << "[Ball::create_sparks] clearing out." << std::endl; #endif // DEBUG sparks_.clear(); } int n_sparks = distr_number(generator_); for ( int i = 0 ; i < n_sparks ; ++i ) { #ifdef DEBUG std::cout << "[Ball::create_sparks] index " << i << std::endl; #endif // DEBUG double x = distr_position(generator_); double y = distr_position(generator_); double d = distr_size(generator_); std::cout << "test 3" << std::endl; x += ( bounding_box_[0] + bounding_box_[2]/2); y += ( bounding_box_[1] + bounding_box_[3]/2); Spark toAdd(x, y, d, d); std::cout << "test 4" << std::endl; toAdd.index_ = i; #ifdef DEBUG std::cout << "[Ball::create_sparks] back index " << sparks_.back().index_ << " - toAdd.index " << toAdd.index_ << std::endl; #endif // DEBUG toAdd.set_texture( texture_ ); toAdd.lifetime_ = Uint32(distr_lifetime(generator_)); toAdd.timer_.start(); sparks_.push_back(toAdd); #ifdef DEBUG std::cout << "[Ball::create_sparks] index " << i << " - lifetime " << (sparks_.back()).lifetime() << std::endl; #endif // DEBUG // std::function<Uint32(Uint32,void*)> funct = std::bind(&Ball::remove_spark, this, std::placeholders::_1, std::placeholders::_2, toAdd.index_ ); // sparks_.back().spark_timer_ = SDL_AddTimer(lifetime, Spark::expire, &sparks_.back()); } } int Ball::move(const SDL_Rect& paddleBox) { if ( goal_ ) return 0; Uint32 deltaT = timer_.get_time(); int x_velocity = ( window->width() / velocity_x_ ) * deltaT; int y_velocity = ( window->height() / velocity_y_ ) * deltaT; bounding_rect_.y += y_velocity; bounding_rect_.x += x_velocity; if ( bounding_rect_.x + bounding_rect_.w >= window->width() ) { goal_ = 1; bounding_rect_.x = 0; bounding_rect_.y = window->height() / 2 ; move_bounding_box(); return goal_; } bool in_xrange = false, in_yrange = false, x_hit = false, y_hit = false ; if ( bounding_rect_.x + bounding_rect_.w/2 >= paddleBox.x && bounding_rect_.x - bounding_rect_.w/2 <= paddleBox.x + paddleBox.w ) in_xrange = true; if ( bounding_rect_.y + bounding_rect_.h/2 >= paddleBox.y && bounding_rect_.y - bounding_rect_.h/2 <= paddleBox.y + paddleBox.h) in_yrange = true; if ( bounding_rect_.x + bounding_rect_.w >= paddleBox.x && bounding_rect_.x <= paddleBox.x + paddleBox.w ) x_hit = true; if ( bounding_rect_.y + bounding_rect_.h >= paddleBox.y && bounding_rect_.y <= paddleBox.y + paddleBox.h ) y_hit = true; if ( ( x_hit && in_yrange ) || bounding_rect_.x <= 0 ) { velocity_x_ *= -1; if ( x_hit && in_yrange ) create_sparks(); } if ( ( y_hit && in_xrange ) || bounding_rect_.y <= 0 || ( bounding_rect_.y + bounding_rect_.h >= window->height() ) ) velocity_y_ *= -1; move_bounding_box(); timer_.start(); return goal_; } void Ball::render() { SbObject::render(); if ( sparks_.empty() ) return; // std::for_each( sparks_.begin(), sparks_.end(), // [](Spark& spark) -> void { if ( !spark.is_dead() ) spark.render(); } ); auto iter = sparks_.begin(); while ( iter != sparks_.end() ) { if ( iter->time() > iter->lifetime() ){ iter = sparks_.erase(iter); } else { iter->render(); ++iter; } } } void Ball::reset() { goal_ = 0; timer_.start(); } Uint32 Ball::resetball(Uint32 interval, void *param ) { ((Ball*)param)->reset(); return(0); } SbWindow* SbObject::window; TTF_Font *fps_font = nullptr; int main() { try { SbWindow window; window.initialize("Half-Pong", SCREEN_WIDTH, SCREEN_HEIGHT); SbObject::window = &window ; Paddle paddle; Ball ball; SbTexture *fps_texture = new SbTexture(); SDL_Color fps_color = {210, 160, 10, 0}; SbTimer fps_timer; fps_font = TTF_OpenFont( "resources/FreeSans.ttf", 18 ); if ( !fps_font ) throw std::runtime_error( "TTF_OpenFont: " + std::string( TTF_GetError() ) ); SDL_TimerID reset_timer = 0; SDL_Event event; bool quit = false; int fps_counter = 0; fps_timer.start(); while (!quit) { while( SDL_PollEvent( &event ) ) { if (event.type == SDL_QUIT) quit = true; else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE ) quit = true; window.handle_event(event); paddle.handle_event(event); ball.handle_event( event ); } if ( fps_counter > 0 && fps_counter < INT_MAX ) { double average = double(fps_counter)/ ( fps_timer.get_time()/1000.0 ) ; std::string fps_text = std::to_string(int(average)) + " fps"; fps_texture->from_text( window.renderer(), fps_text, fps_font, fps_color); } else { fps_counter = 0; fps_timer.start(); } paddle.move(); int goal = ball.move( paddle.bounding_rect() ); if ( goal ) { reset_timer = SDL_AddTimer(1000, Ball::resetball, &ball); } SDL_RenderClear( window.renderer() ); paddle.render(); ball.render(); fps_texture->render( window.renderer(), 10,10); SDL_RenderPresent( window.renderer() ); ++fps_counter; } } catch (const std::exception& expt) { std::cerr << expt.what() << std::endl; } return 0; } <commit_msg>Output still weird, but results look OK.<commit_after>/* SbHalfPong, sort of like Pong but for one author: Ulrike Hager */ #include <iostream> #include <string> #include <sstream> #include <stdexcept> #include <climits> #include <cmath> #include <random> #include <algorithm> #include <functional> #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_image.h> #include "SbTexture.h" #include "SbTimer.h" #include "SbWindow.h" #include "SbObject.h" const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 600; class Ball; class Spark; class Paddle; class Paddle : public SbObject { public: Paddle(); void handle_event(const SDL_Event& event); int move(); }; class Ball : public SbObject { public: Ball(); // void handle_event(const SDL_Event& event); /*! \retval 1 if ball in goal \retval 0 else */ int move(const SDL_Rect& paddleBox); void render(); /*! Reset after goal. */ void reset(); static Uint32 resetball(Uint32 interval, void *param ); Uint32 remove_spark(Uint32 interval, void *param, int index ); private: int goal_ = 0; std::vector<Spark> sparks_; std::default_random_engine generator_; std::uniform_int_distribution<int> distr_number { 15, 30 }; std::normal_distribution<double> distr_position { 0.0, 0.01 }; std::normal_distribution<double> distr_size { 0.003, 0.002 }; std::uniform_int_distribution<int> distr_lifetime { 100, 400 }; void create_sparks(); void delete_spark(int index); }; class Spark : public SbObject { friend class Ball; public: Spark(double x, double y, double width, double height); ~Spark(); static Uint32 expire(Uint32 interval, void* param); void set_texture(SbTexture* tex) {texture_ = tex;} int index() { return index_;} bool is_dead() {return is_dead_;} Uint32 lifetime() { return lifetime_;} private: // SDL_TimerID spark_timer_; int index_ = 0; bool is_dead_ = false; Uint32 lifetime_ = 100; }; /*! Paddle implementation */ Paddle::Paddle() : SbObject(SCREEN_WIDTH - 70, 200, 20, 80) { // bounding_rect_ = {}; velocity_y_ = 0; velocity_ = 1200; SDL_Color color = {210, 160, 10, 0}; texture_ = new SbTexture(); texture_->from_rectangle( window->renderer(), bounding_rect_.w, bounding_rect_.h, color ); } void Paddle::handle_event(const SDL_Event& event) { SbObject::handle_event( event ); if( event.type == SDL_KEYDOWN && event.key.repeat == 0 ) { switch( event.key.keysym.sym ) { case SDLK_UP: velocity_y_ -= velocity_; break; case SDLK_DOWN: velocity_y_ += velocity_; break; } } else if( event.type == SDL_KEYUP && event.key.repeat == 0 ) { switch( event.key.keysym.sym ) { case SDLK_UP: velocity_y_ += velocity_; break; case SDLK_DOWN: velocity_y_ -= velocity_; break; } } } int Paddle::move() { Uint32 deltaT = timer_.get_time(); int velocity = ( window->height() / velocity_y_ )* deltaT; bounding_rect_.y += velocity; if( ( bounding_rect_.y < 0 ) || ( bounding_rect_.y + bounding_rect_.h > window->height() ) ) { bounding_rect_.y -= velocity; } move_bounding_box(); timer_.start(); return 0; } Spark::Spark(double x, double y, double width, double height) : SbObject(x,y,width,height) { } Spark::~Spark() { #ifdef DEBUG std::cout << "[Spark::~Spark] index " << index_ << " - lifetime " << lifetime_ << std::endl; #endif // DEBUG texture_ = nullptr; // SDL_RemoveTimer(spark_timer_); } Uint32 Spark::expire(Uint32 interval, void* param) { #ifdef DEBUG std::cout << "[Spark::expire] interval " << interval << std::flush; #endif // DEBUG Spark* spark = ((Spark*)param); #ifdef DEBUG std::cout << "[Spark::expire] index " << spark->index_ << std::endl; #endif // DEBUG if (spark) spark->is_dead_ = true; return(0); } Uint32 Ball::remove_spark(Uint32 interval, void *param, int index ) { ((Ball*)param)->delete_spark(index); return(0); } void Ball::delete_spark(int index) { std::remove_if( sparks_.begin(), sparks_.end(), [index](Spark& spark) -> bool { return spark.index() == index;} ); // ((Spark*)param)->set_texture( nullptr ); } /*! Ball implementation */ Ball::Ball() : SbObject(50, 300, 25, 25) { // bounding_box_ = {}; velocity_y_ = 1500; velocity_x_ = 1500; velocity_ = 1500; texture_ = new SbTexture(); texture_->from_file(window->renderer(), "resources/ball.png", bounding_rect_.w, bounding_rect_.h ); } void Ball::create_sparks() { #ifdef DEBUG std::cout << "[Ball::create_sparks]" << std::endl; #endif // DEBUG if (! sparks_.empty() ) { sparks_.clear(); } int n_sparks = distr_number(generator_); for ( int i = 0 ; i < n_sparks ; ++i ) { double x = distr_position(generator_); double y = distr_position(generator_); double d = distr_size(generator_); x += ( bounding_box_[0] + bounding_box_[2]/2); y += ( bounding_box_[1] + bounding_box_[3]/2); Spark toAdd(x, y, d, d); toAdd.index_ = i; toAdd.set_texture( texture_ ); toAdd.lifetime_ = Uint32(distr_lifetime(generator_)); toAdd.timer_.start(); sparks_.push_back(toAdd); #ifdef DEBUG std::cout << "[Ball::create_sparks] index " << i << " - lifetime " << (sparks_.back()).lifetime() << std::endl; #endif // DEBUG // std::function<Uint32(Uint32,void*)> funct = std::bind(&Ball::remove_spark, this, std::placeholders::_1, std::placeholders::_2, toAdd.index_ ); // sparks_.back().spark_timer_ = SDL_AddTimer(lifetime, Spark::expire, &sparks_.back()); } } int Ball::move(const SDL_Rect& paddleBox) { if ( goal_ ) return 0; Uint32 deltaT = timer_.get_time(); int x_velocity = ( window->width() / velocity_x_ ) * deltaT; int y_velocity = ( window->height() / velocity_y_ ) * deltaT; bounding_rect_.y += y_velocity; bounding_rect_.x += x_velocity; if ( bounding_rect_.x + bounding_rect_.w >= window->width() ) { goal_ = 1; bounding_rect_.x = 0; bounding_rect_.y = window->height() / 2 ; move_bounding_box(); return goal_; } bool in_xrange = false, in_yrange = false, x_hit = false, y_hit = false ; if ( bounding_rect_.x + bounding_rect_.w/2 >= paddleBox.x && bounding_rect_.x - bounding_rect_.w/2 <= paddleBox.x + paddleBox.w ) in_xrange = true; if ( bounding_rect_.y + bounding_rect_.h/2 >= paddleBox.y && bounding_rect_.y - bounding_rect_.h/2 <= paddleBox.y + paddleBox.h) in_yrange = true; if ( bounding_rect_.x + bounding_rect_.w >= paddleBox.x && bounding_rect_.x <= paddleBox.x + paddleBox.w ) x_hit = true; if ( bounding_rect_.y + bounding_rect_.h >= paddleBox.y && bounding_rect_.y <= paddleBox.y + paddleBox.h ) y_hit = true; if ( ( x_hit && in_yrange ) || bounding_rect_.x <= 0 ) { velocity_x_ *= -1; if ( x_hit && in_yrange ) create_sparks(); } if ( ( y_hit && in_xrange ) || bounding_rect_.y <= 0 || ( bounding_rect_.y + bounding_rect_.h >= window->height() ) ) velocity_y_ *= -1; move_bounding_box(); timer_.start(); return goal_; } void Ball::render() { SbObject::render(); if ( sparks_.empty() ) return; // std::for_each( sparks_.begin(), sparks_.end(), // [](Spark& spark) -> void { if ( !spark.is_dead() ) spark.render(); } ); auto iter = sparks_.begin(); while ( iter != sparks_.end() ) { if ( iter->time() > iter->lifetime() ){ iter = sparks_.erase(iter); } else { iter->render(); ++iter; } } } void Ball::reset() { goal_ = 0; timer_.start(); } Uint32 Ball::resetball(Uint32 interval, void *param ) { ((Ball*)param)->reset(); return(0); } SbWindow* SbObject::window; TTF_Font *fps_font = nullptr; int main() { try { SbWindow window; window.initialize("Half-Pong", SCREEN_WIDTH, SCREEN_HEIGHT); SbObject::window = &window ; Paddle paddle; Ball ball; SbTexture *fps_texture = new SbTexture(); SDL_Color fps_color = {210, 160, 10, 0}; SbTimer fps_timer; fps_font = TTF_OpenFont( "resources/FreeSans.ttf", 18 ); if ( !fps_font ) throw std::runtime_error( "TTF_OpenFont: " + std::string( TTF_GetError() ) ); SDL_TimerID reset_timer = 0; SDL_Event event; bool quit = false; int fps_counter = 0; fps_timer.start(); while (!quit) { while( SDL_PollEvent( &event ) ) { if (event.type == SDL_QUIT) quit = true; else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE ) quit = true; window.handle_event(event); paddle.handle_event(event); ball.handle_event( event ); } if ( fps_counter > 0 && fps_counter < INT_MAX ) { double average = double(fps_counter)/ ( fps_timer.get_time()/1000.0 ) ; std::string fps_text = std::to_string(int(average)) + " fps"; fps_texture->from_text( window.renderer(), fps_text, fps_font, fps_color); } else { fps_counter = 0; fps_timer.start(); } paddle.move(); int goal = ball.move( paddle.bounding_rect() ); if ( goal ) { reset_timer = SDL_AddTimer(1000, Ball::resetball, &ball); } SDL_RenderClear( window.renderer() ); paddle.render(); ball.render(); fps_texture->render( window.renderer(), 10,10); SDL_RenderPresent( window.renderer() ); ++fps_counter; } } catch (const std::exception& expt) { std::cerr << expt.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>/* PStreams - POSIX Process I/O for C++ Copyright (C) 2002 Jonathan Wakely This file is part of PStreams. PStreams is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. PStreams 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 PStreams; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // TODO test rpstream more // test eviscerated pstreams #define REDI_EVISCERATE_PSTREAMS 1 #include "pstream.h" // include these after pstream.h to ensure it #includes everything it needs #include <iostream> #include <iomanip> #include <string> #include <sstream> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> //#include <fcntl.h> #include <errno.h> using namespace std; using namespace redi; // explicit instantiations of template classes template class redi::pstreambuf; template class redi::pstream_common<char>; template class redi::ipstream; template class redi::opstream; template class redi::pstream; template class redi::rpstream; namespace // anon { // helper functions for printing test results char test_type(const istream& s) { return 'r'; } char test_type(const ostream& s) { return 'w'; } char test_type(const iostream& s) { return 'b'; } char test_type(const rpstream& s) { return 'x'; } template <typename T> string test_id(const T& s) { static int count = 0; ostringstream buf; buf << test_type(s) << ++count; return buf.str(); } template <typename T> void print_result(const T& s, bool result) { clog << "Test " << setw(4) << test_id(s) << ": " << (result ? "Pass" : "Fail!") << endl; } template <typename T> bool check_pass(const T& s, bool expected = true) { bool res = s.good() == expected; print_result(s, res); return res; } template <typename T> bool check_fail(const T& s) { return check_pass(s, false); } // exit status of shell when command not found #if defined(__sun) int sh_cmd_not_found = 1; #else int sh_cmd_not_found = 127; #endif } int main() { ios_base::sync_with_stdio(); string str; clog << "# Testing basic I/O\n"; { // test formatted output // // This should read the strings on stdin and print them on stdout // prefixed by "STDOUT: " opstream os("sed 's/^/STDIN: /' /dev/stdin /etc/resolv.conf"); os << ".fnord.\n"; str = "..fnord..\n"; os << str; check_pass(os); } { // test execve() style construction // // This should read the strings on stdin and print them on stdout // prefixed by "STDIN: " vector<string> argv; argv.push_back("sed"); argv.push_back("s/^/STDIN: /"); opstream os("sed", argv); check_pass(os << "Magic Monkey\n"); } { // test unformatted output // // This should read the strings on stdin and print them on stdout // prefixed by "STDIN: " opstream sed("sed 's/^/STDIN: /'"); str = "Monkey Magic\n"; for (string::const_iterator i = str.begin(); i!=str.end(); ++i) sed.put(*i); check_pass(sed); } { // test formatted input // should print hostname on stdout, prefixed by "STDOUT: " ipstream host("hostname"); if (getline(host, str)) // extracts up to newline, eats newline cout << "STDOUT: " << str << endl; check_pass(host); // check we hit EOF at next read char c; print_result(host, !host.get(c)); print_result(host, host.eof()); check_fail(host); } { // test unformatted input // should print hostname on stdout, prefixed by "STDOUT: " ipstream host("date"); str.clear(); char c; while (host.get(c)) // extracts up to EOF (including newline) str += c; cout << "STDOUT: " << str << flush; print_result(host, host.eof()); } { // open after construction, then write opstream os; os.open("sed 's/^/STDIN: /'"); os << "Hello, world!\n"; check_pass(os); } { // open after construction, then read ipstream is; is.open("hostname"); string s; is >> s; cout << "STDOUT: " << s << endl; check_pass(is); } { // open after construction, then write ipstream host; host.open("hostname"); if (host >> str) cout << "STDOUT: " << str << endl; check_pass(host); // chomp newline and try to read past end char c; host.get(c); host.get(c); check_fail(host); } clog << "# Testing bidirectional PStreams\n"; pstreambuf::pmode all3streams = pstreambuf::pstdin|pstreambuf::pstdout|pstreambuf::pstderr; { // test output on bidirectional pstream string cmd = "grep ^127 -- /etc/hosts /no/such/file"; pstream ps(cmd, all3streams); print_result(ps, ps.is_open()); check_pass(ps.out()); check_pass(ps.err()); string buf; while (getline(ps.out(), buf)) cout << "STDOUT: " << buf << endl; check_fail(ps); while (getline(ps.err(), buf)) cout << "STDERR: " << buf << endl; check_fail(ps); } { // test input on bidirectional pstream and test peof manip string cmd = "grep fnord -- /dev/stdin"; pstream ps(cmd, all3streams); print_result(ps, ps.is_open()); check_pass(ps); ps << "12345\nfnord\n0000" << peof; // manip calls ps.rdbuf()->peof(); string buf; getline(ps.out(), buf); do { print_result(ps, buf == "fnord"); cout << "STDOUT: " << buf << endl; } while (getline(ps.out(), buf)); check_fail(ps << "pipe closed, no fnord now"); } // TODO - test child moves onto next file after peof on stdin { // test signals string cmd = "grep 127 -- -"; pstream ps(cmd, all3streams); pstreambuf* pbuf = ps.rdbuf(); int e1 = pbuf->error(); print_result(ps, e1 == 0); pbuf->kill(SIGTERM); int e2 = pbuf->error(); print_result(ps, e1 == e2); pbuf->close(); int e3 = pbuf->error(); check_fail(ps << "127 fail 127\n"); print_result(ps, e1 == e3); } clog << "# Testing behaviour with bad commands" << endl; //string badcmd = "hgfhdgf"; string badcmd = "hgfhdgf 2>/dev/null"; { // check eof() works ipstream is(badcmd); print_result(is, is.get()==EOF); print_result(is, is.eof() ); } { // test writing to bad command opstream ofail(badcmd); sleep(1); // give shell time to try command and exit // this would cause SIGPIPE: ofail<<"blahblah"; // does not show failure: print_result(ofail, !ofail.is_open()); pstreambuf* buf = ofail.rdbuf(); print_result(ofail, buf->exited()); int status = buf->status(); print_result( ofail, WIFEXITED(status) && WEXITSTATUS(status) == sh_cmd_not_found ); } { // reading from bad cmd vector<string> argv; argv.push_back("hdhdhd"); argv.push_back("arg1"); argv.push_back("arg2"); ipstream ifail("hdhdhd", argv); check_fail(ifail>>str); } clog << "# Testing behaviour with uninit'ed streams" << endl; { // check eof() works ipstream is; print_result(is, is.get()==EOF); print_result(is, is.eof() ); } { // test writing to no command opstream ofail; check_fail(ofail<<"blahblah"); } clog << "# Testing other member functions\n"; { string cmd("grep re"); opstream s(cmd); print_result(s, cmd == s.command()); } { string cmd("grep re"); opstream s; s.open(cmd); print_result(s, cmd == s.command()); } { string cmd("/bin/ls"); ipstream s(cmd); print_result(s, cmd == s.command()); } { string cmd("/bin/ls"); ipstream s; s.open(cmd); print_result(s, cmd == s.command()); } // TODO more testing of other members clog << "# Testing writing to closed stream\n"; { opstream os("tr a-z A-Z | sed 's/^/STDIN: /'"); os << "foo\n"; os.close(); if (os << "bar\n") cout << "Wrote to closed stream" << endl; check_fail(os << "bar\n"); } clog << "# Testing restricted pstream\n"; { rpstream rs("tr a-z A-Z | sed 's/^/STDIN: /'"); rs << "big" << peof; string s; check_pass(rs.out() >> s); print_result(rs, s.size()>0); cout << "STDOUT: " << s << endl; } #if REDI_EVISCERATE_PSTREAMS clog << "# Testing eviscerated pstream\n"; { opstream os("tr a-z A-Z | sed 's/^/STDIN: /'"); FILE *in, *out, *err; size_t res = os.fopen(in, out, err); print_result(os, res & pstreambuf::pstdin); print_result(os, in!=NULL); int i = fputs("flax\n", in); fflush(in); print_result(os, i>=0 && i!=EOF); } { string cmd = "ls /etc/motd /no/such/file"; ipstream is(cmd, pstreambuf::pstdout|pstreambuf::pstderr); FILE *in, *out, *err; size_t res = is.fopen(in, out, err); print_result(is, res & pstreambuf::pstdout); print_result(is, res & pstreambuf::pstderr); print_result(is, out!=NULL); print_result(is, err!=NULL); size_t len = 256; char buf[len]; char* p = fgets(buf, len, out); cout << "STDOUT: " << buf; print_result(is, p!=NULL); p = fgets(buf, len, err); cout << "STDERR: " << buf; print_result(is, p!=NULL); } { string cmd = "grep 127 -- - /etc/hosts /no/such/file"; pstream ps(cmd, all3streams); FILE *in, *out, *err; size_t res = ps.fopen(in, out, err); print_result(ps, res & pstreambuf::pstdin); print_result(ps, res & pstreambuf::pstdout); print_result(ps, res & pstreambuf::pstderr); print_result(ps, in!=NULL); print_result(ps, out!=NULL); print_result(ps, err!=NULL); // ps << "12345\n1112777\n0000" << EOF; #if 0 size_t len = 256; char buf[len]; char* p = fgets(buf, len, out); cout << "STDOUT: " << buf; print_result(ps, p!=NULL); p = fgets(buf, len, err); cout << "STDERR: " << buf; print_result(ps, p!=NULL); #endif } #endif return 0; } <commit_msg>Use more portable arguments to tr, works for Solaris now.<commit_after>/* PStreams - POSIX Process I/O for C++ Copyright (C) 2002 Jonathan Wakely This file is part of PStreams. PStreams is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. PStreams 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 PStreams; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // TODO test rpstream more // test eviscerated pstreams #define REDI_EVISCERATE_PSTREAMS 1 #include "pstream.h" // include these after pstream.h to ensure it #includes everything it needs #include <iostream> #include <iomanip> #include <string> #include <sstream> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> //#include <fcntl.h> #include <errno.h> using namespace std; using namespace redi; // explicit instantiations of template classes template class redi::pstreambuf; template class redi::pstream_common<char>; template class redi::ipstream; template class redi::opstream; template class redi::pstream; template class redi::rpstream; namespace // anon { // helper functions for printing test results char test_type(const istream& s) { return 'r'; } char test_type(const ostream& s) { return 'w'; } char test_type(const iostream& s) { return 'b'; } char test_type(const rpstream& s) { return 'x'; } template <typename T> string test_id(const T& s) { static int count = 0; ostringstream buf; buf << test_type(s) << ++count; return buf.str(); } template <typename T> void print_result(const T& s, bool result) { clog << "Test " << setw(4) << test_id(s) << ": " << (result ? "Pass" : "Fail!") << endl; } template <typename T> bool check_pass(const T& s, bool expected = true) { bool res = s.good() == expected; print_result(s, res); return res; } template <typename T> bool check_fail(const T& s) { return check_pass(s, false); } // exit status of shell when command not found #if defined(__sun) int sh_cmd_not_found = 1; #else int sh_cmd_not_found = 127; #endif } int main() { ios_base::sync_with_stdio(); string str; clog << "# Testing basic I/O\n"; { // test formatted output // // This should read the strings on stdin and print them on stdout // prefixed by "STDOUT: " opstream os("sed 's/^/STDIN: /' /dev/stdin /etc/resolv.conf"); os << ".fnord.\n"; str = "..fnord..\n"; os << str; check_pass(os); } { // test execve() style construction // // This should read the strings on stdin and print them on stdout // prefixed by "STDIN: " vector<string> argv; argv.push_back("sed"); argv.push_back("s/^/STDIN: /"); opstream os("sed", argv); check_pass(os << "Magic Monkey\n"); } { // test unformatted output // // This should read the strings on stdin and print them on stdout // prefixed by "STDIN: " opstream sed("sed 's/^/STDIN: /'"); str = "Monkey Magic\n"; for (string::const_iterator i = str.begin(); i!=str.end(); ++i) sed.put(*i); check_pass(sed); } { // test formatted input // should print hostname on stdout, prefixed by "STDOUT: " ipstream host("hostname"); if (getline(host, str)) // extracts up to newline, eats newline cout << "STDOUT: " << str << endl; check_pass(host); // check we hit EOF at next read char c; print_result(host, !host.get(c)); print_result(host, host.eof()); check_fail(host); } { // test unformatted input // should print hostname on stdout, prefixed by "STDOUT: " ipstream host("date"); str.clear(); char c; while (host.get(c)) // extracts up to EOF (including newline) str += c; cout << "STDOUT: " << str << flush; print_result(host, host.eof()); } { // open after construction, then write opstream os; os.open("sed 's/^/STDIN: /'"); os << "Hello, world!\n"; check_pass(os); } { // open after construction, then read ipstream is; is.open("hostname"); string s; is >> s; cout << "STDOUT: " << s << endl; check_pass(is); } { // open after construction, then write ipstream host; host.open("hostname"); if (host >> str) cout << "STDOUT: " << str << endl; check_pass(host); // chomp newline and try to read past end char c; host.get(c); host.get(c); check_fail(host); } clog << "# Testing bidirectional PStreams\n"; pstreambuf::pmode all3streams = pstreambuf::pstdin|pstreambuf::pstdout|pstreambuf::pstderr; { // test output on bidirectional pstream string cmd = "grep ^127 -- /etc/hosts /no/such/file"; pstream ps(cmd, all3streams); print_result(ps, ps.is_open()); check_pass(ps.out()); check_pass(ps.err()); string buf; while (getline(ps.out(), buf)) cout << "STDOUT: " << buf << endl; check_fail(ps); while (getline(ps.err(), buf)) cout << "STDERR: " << buf << endl; check_fail(ps); } { // test input on bidirectional pstream and test peof manip string cmd = "grep fnord -- /dev/stdin"; pstream ps(cmd, all3streams); print_result(ps, ps.is_open()); check_pass(ps); ps << "12345\nfnord\n0000" << peof; // manip calls ps.rdbuf()->peof(); string buf; getline(ps.out(), buf); do { print_result(ps, buf == "fnord"); cout << "STDOUT: " << buf << endl; } while (getline(ps.out(), buf)); check_fail(ps << "pipe closed, no fnord now"); } // TODO - test child moves onto next file after peof on stdin { // test signals string cmd = "grep 127 -- -"; pstream ps(cmd, all3streams); pstreambuf* pbuf = ps.rdbuf(); int e1 = pbuf->error(); print_result(ps, e1 == 0); pbuf->kill(SIGTERM); int e2 = pbuf->error(); print_result(ps, e1 == e2); pbuf->close(); int e3 = pbuf->error(); check_fail(ps << "127 fail 127\n"); print_result(ps, e1 == e3); } clog << "# Testing behaviour with bad commands" << endl; //string badcmd = "hgfhdgf"; string badcmd = "hgfhdgf 2>/dev/null"; { // check eof() works ipstream is(badcmd); print_result(is, is.get()==EOF); print_result(is, is.eof() ); } { // test writing to bad command opstream ofail(badcmd); sleep(1); // give shell time to try command and exit // this would cause SIGPIPE: ofail<<"blahblah"; // does not show failure: print_result(ofail, !ofail.is_open()); pstreambuf* buf = ofail.rdbuf(); print_result(ofail, buf->exited()); int status = buf->status(); print_result( ofail, WIFEXITED(status) && WEXITSTATUS(status) == sh_cmd_not_found ); } { // reading from bad cmd vector<string> argv; argv.push_back("hdhdhd"); argv.push_back("arg1"); argv.push_back("arg2"); ipstream ifail("hdhdhd", argv); check_fail(ifail>>str); } clog << "# Testing behaviour with uninit'ed streams" << endl; { // check eof() works ipstream is; print_result(is, is.get()==EOF); print_result(is, is.eof() ); } { // test writing to no command opstream ofail; check_fail(ofail<<"blahblah"); } clog << "# Testing other member functions\n"; { string cmd("grep re"); opstream s(cmd); print_result(s, cmd == s.command()); } { string cmd("grep re"); opstream s; s.open(cmd); print_result(s, cmd == s.command()); } { string cmd("/bin/ls"); ipstream s(cmd); print_result(s, cmd == s.command()); } { string cmd("/bin/ls"); ipstream s; s.open(cmd); print_result(s, cmd == s.command()); } // TODO more testing of other members clog << "# Testing writing to closed stream\n"; { opstream os("tr '[:lower:]' '[:upper:]' | sed 's/^/STDIN: /'"); os << "foo\n"; os.close(); if (os << "bar\n") cout << "Wrote to closed stream" << endl; check_fail(os << "bar\n"); } clog << "# Testing restricted pstream\n"; { rpstream rs("tr '[:lower:]' '[:upper:]' | sed 's/^/STDIN: /'"); rs << "big\n" << peof; string s; check_pass(rs.out() >> s); print_result(rs, s.size()>0); cout << "STDOUT: " << s << endl; } #if REDI_EVISCERATE_PSTREAMS clog << "# Testing eviscerated pstream\n"; { opstream os("tr '[:lower:]' '[:upper:]' | sed 's/^/STDIN: /'"); FILE *in, *out, *err; size_t res = os.fopen(in, out, err); print_result(os, res & pstreambuf::pstdin); print_result(os, in!=NULL); int i = fputs("flax\n", in); fflush(in); print_result(os, i>=0 && i!=EOF); } { string cmd = "ls /etc/motd /no/such/file"; ipstream is(cmd, pstreambuf::pstdout|pstreambuf::pstderr); FILE *in, *out, *err; size_t res = is.fopen(in, out, err); print_result(is, res & pstreambuf::pstdout); print_result(is, res & pstreambuf::pstderr); print_result(is, out!=NULL); print_result(is, err!=NULL); size_t len = 256; char buf[len]; char* p = fgets(buf, len, out); cout << "STDOUT: " << buf; print_result(is, p!=NULL); p = fgets(buf, len, err); cout << "STDERR: " << buf; print_result(is, p!=NULL); } { string cmd = "grep 127 -- - /etc/hosts /no/such/file"; pstream ps(cmd, all3streams); FILE *in, *out, *err; size_t res = ps.fopen(in, out, err); print_result(ps, res & pstreambuf::pstdin); print_result(ps, res & pstreambuf::pstdout); print_result(ps, res & pstreambuf::pstderr); print_result(ps, in!=NULL); print_result(ps, out!=NULL); print_result(ps, err!=NULL); // ps << "12345\n1112777\n0000" << EOF; #if 0 size_t len = 256; char buf[len]; char* p = fgets(buf, len, out); cout << "STDOUT: " << buf; print_result(ps, p!=NULL); p = fgets(buf, len, err); cout << "STDERR: " << buf; print_result(ps, p!=NULL); #endif } #endif return 0; } <|endoftext|>
<commit_before> #pragma once #include "geometry/named_quantities.hpp" #include "quantities/si.hpp" // |geometry::Instant| represents instants of Terrestrial Time (TT). The // utilities in this file provide its standard epoch and two ways of specifying // TT dates. namespace principia { using geometry::Instant; using quantities::si::Second; namespace astronomy { // |J2000| represents to the standard epoch J2000.0. // According to Resolution B1 (On the Use of Julian Dates) of the XXIIIrd IAU // general assembly, "it is recommended that JD be specified as SI seconds in // Terrestrial Time (TT)", see http://goo.gl/oPemRm. J2000.0 is by definition // JD 2451545.0, i.e., noon on the first of January, 2000 (TT). // "2000-01-01T12:00:00"_TT // "2000-01-01T11:59:27,816"_TAI // "2000-01-01T11:58:55,816"_UTC constexpr Instant J2000; constexpr Instant InfinitePast = J2000 - std::numeric_limits<double>::infinity() * Second; constexpr Instant InfiniteFuture = J2000 + std::numeric_limits<double>::infinity() * Second; // The Julian Date JD |days|. J2000.0 is JD 2451545.0. |days| is the number of // days since -4712-01-01T12:00:00,000 (Terrestrial Time, Julian calendar). constexpr Instant JulianDate(double const days); // The Modified Julian Date MJD |days|. MJD is defined as JD - 2400000.5 days, // so |ModifiedJulianDate(0)| is "1858-11-17T00:00:00"_TT. constexpr Instant ModifiedJulianDate(double const days); } // namespace astronomy } // namespace principia #include "astronomy/epoch_body.hpp" <commit_msg>Lint.<commit_after> #pragma once #include <limits> #include "geometry/named_quantities.hpp" #include "quantities/si.hpp" // |geometry::Instant| represents instants of Terrestrial Time (TT). The // utilities in this file provide its standard epoch and two ways of specifying // TT dates. namespace principia { using geometry::Instant; using quantities::si::Second; namespace astronomy { // |J2000| represents to the standard epoch J2000.0. // According to Resolution B1 (On the Use of Julian Dates) of the XXIIIrd IAU // general assembly, "it is recommended that JD be specified as SI seconds in // Terrestrial Time (TT)", see http://goo.gl/oPemRm. J2000.0 is by definition // JD 2451545.0, i.e., noon on the first of January, 2000 (TT). // "2000-01-01T12:00:00"_TT // "2000-01-01T11:59:27,816"_TAI // "2000-01-01T11:58:55,816"_UTC constexpr Instant J2000; constexpr Instant InfinitePast = J2000 - std::numeric_limits<double>::infinity() * Second; constexpr Instant InfiniteFuture = J2000 + std::numeric_limits<double>::infinity() * Second; // The Julian Date JD |days|. J2000.0 is JD 2451545.0. |days| is the number of // days since -4712-01-01T12:00:00,000 (Terrestrial Time, Julian calendar). constexpr Instant JulianDate(double const days); // The Modified Julian Date MJD |days|. MJD is defined as JD - 2400000.5 days, // so |ModifiedJulianDate(0)| is "1858-11-17T00:00:00"_TT. constexpr Instant ModifiedJulianDate(double const days); } // namespace astronomy } // namespace principia #include "astronomy/epoch_body.hpp" <|endoftext|>
<commit_before>#include <iostream> #include "gtest/gtest.h" #include "sigs.h" TEST(General, instantiate) { sigs::Signal<void()> s; sigs::Signal<void(int)> s2; sigs::Signal<int()> s3; } inline void addOne(int &i) { i++; } TEST(General, function) { sigs::Signal<void(int &)> s; s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, multipleFunctions) { sigs::Signal<void(int &)> s; s.connect(addOne); s.connect(addOne); s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 3); } TEST(General, functor) { class AddOneFunctor { public: void operator()(int &i) const { i++; } }; sigs::Signal<void(int &)> s; s.connect(AddOneFunctor()); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, instanceMethod) { class Foo { public: void test(int &i) const { i++; } }; sigs::Signal<void(int &)> s; Foo foo; s.connect(&foo, &Foo::test); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, lambda) { sigs::Signal<void(int &)> s; s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectDirectly) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); conn->disconnect(); s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectOnSignal) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); s.disconnect(conn); s(i); EXPECT_EQ(i, 1); } TEST(General, connectSignalToSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); int i = 0; s2(i); EXPECT_EQ(i, 1); } TEST(General, disconnectSignalFromSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); s2.disconnect(s1); int i = 0; s2(i); EXPECT_EQ(i, 0); } // Check for debug assertion. #ifndef NDEBUG TEST(General, disconnectSignalFromSelf) { sigs::Signal<void()> s; EXPECT_DEATH(s.disconnect(s), "Disconnecting from self has no effect."); } #endif TEST(General, ambiguousMembers) { class Ambiguous { public: void foo(int i) { value += i; } void foo(float j) { value += static_cast<int>(j); } int value = 0; }; sigs::Signal<void(int)> s; Ambiguous amb; auto conn = s.connect(&amb, sigs::Use<int>::overloadOf(&Ambiguous::foo)); s(42); EXPECT_EQ(amb.value, 42); conn->disconnect(); // This one only works because int can be coerced into float. s.connect(&amb, sigs::Use<float>::overloadOf(&Ambiguous::foo)); s(1); EXPECT_EQ(amb.value, 43); } TEST(General, returnValues) { sigs::Signal<int()> s; s.connect([] { return 1; }); s.connect([] { return 2; }); s.connect([] { return 3; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3); } TEST(General, sameSlotManyConnections) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; s.connect(slot); s(); EXPECT_EQ(calls, 1); s.connect(slot); s(); EXPECT_EQ(calls, 3); // This yielded 4 calls when eraseEntries() didn't clear correctly. s.clear(); s(); EXPECT_EQ(calls, 3); } TEST(General, clearEquivalentToAllDisconnects) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.clear(); s(); EXPECT_EQ(calls, 2); } { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.disconnect(conn1); s.disconnect(conn2); s(); EXPECT_EQ(calls, 2); } } TEST(General, size) { sigs::Signal<void()> s; ASSERT_EQ(0UL, s.size()); s.connect([] {}); s.connect([] {}); ASSERT_EQ(2UL, s.size()); s.clear(); ASSERT_EQ(0UL, s.size()); } TEST(General, empty) { sigs::Signal<void()> s; ASSERT_TRUE(s.empty()); s.connect([] {}); ASSERT_FALSE(s.empty()); s.clear(); ASSERT_TRUE(s.empty()); } TEST(General, disconnectWithNoSlotClearsAll) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.disconnect(); ASSERT_TRUE(s.empty()); } <commit_msg>100% code coverage<commit_after>#include <iostream> #include "gtest/gtest.h" #include "sigs.h" TEST(General, instantiate) { sigs::Signal<void()> s; sigs::Signal<void(int)> s2; sigs::Signal<int()> s3; } inline void addOne(int &i) { i++; } TEST(General, function) { sigs::Signal<void(int &)> s; s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, multipleFunctions) { sigs::Signal<void(int &)> s; s.connect(addOne); s.connect(addOne); s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 3); } TEST(General, functor) { class AddOneFunctor { public: void operator()(int &i) const { i++; } }; sigs::Signal<void(int &)> s; s.connect(AddOneFunctor()); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, instanceMethod) { class Foo { public: void test(int &i) const { i++; } }; sigs::Signal<void(int &)> s; Foo foo; s.connect(&foo, &Foo::test); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, lambda) { sigs::Signal<void(int &)> s; s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectDirectly) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); conn->disconnect(); s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectOnSignal) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); s.disconnect(conn); s(i); EXPECT_EQ(i, 1); } TEST(General, connectSignalToSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); int i = 0; s2(i); EXPECT_EQ(i, 1); } TEST(General, disconnectSignalFromSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); s2.disconnect(s1); int i = 0; s2(i); EXPECT_EQ(i, 0); } // Check for debug assertion. #ifndef NDEBUG TEST(General, disconnectSignalFromSelf) { sigs::Signal<void()> s; EXPECT_DEATH(s.disconnect(s), "Disconnecting from self has no effect."); } #endif TEST(General, ambiguousMembers) { class Ambiguous { public: void foo(int i) { value += i; } void foo(float j) { value += static_cast<int>(j); } int value = 0; }; sigs::Signal<void(int)> s; Ambiguous amb; auto conn = s.connect(&amb, sigs::Use<int>::overloadOf(&Ambiguous::foo)); s(42); EXPECT_EQ(amb.value, 42); conn->disconnect(); // This one only works because int can be coerced into float. s.connect(&amb, sigs::Use<float>::overloadOf(&Ambiguous::foo)); s(1); EXPECT_EQ(amb.value, 43); } TEST(General, returnValues) { sigs::Signal<int()> s; s.connect([] { return 1; }); s.connect([] { return 2; }); s.connect([] { return 3; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3); } TEST(General, returnValuesWithSignals) { sigs::Signal<int()> s, s2, s3; s3.connect([] { return 1; }); s2.connect([] { return 2; }); s2.connect([] { return 3; }); s.connect(s2); s.connect(s3); s.connect([] { return 4; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3 + 4); } TEST(General, sameSlotManyConnections) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; s.connect(slot); s(); EXPECT_EQ(calls, 1); s.connect(slot); s(); EXPECT_EQ(calls, 3); // This yielded 4 calls when eraseEntries() didn't clear correctly. s.clear(); s(); EXPECT_EQ(calls, 3); } TEST(General, clearEquivalentToAllDisconnects) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.clear(); s(); EXPECT_EQ(calls, 2); } { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.disconnect(conn1); s.disconnect(conn2); s(); EXPECT_EQ(calls, 2); } } TEST(General, size) { sigs::Signal<void()> s; ASSERT_EQ(0UL, s.size()); s.connect([] {}); s.connect([] {}); ASSERT_EQ(2UL, s.size()); s.clear(); ASSERT_EQ(0UL, s.size()); } TEST(General, empty) { sigs::Signal<void()> s; ASSERT_TRUE(s.empty()); s.connect([] {}); ASSERT_FALSE(s.empty()); s.clear(); ASSERT_TRUE(s.empty()); } TEST(General, disconnectWithNoSlotClearsAll) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.disconnect(); ASSERT_TRUE(s.empty()); } <|endoftext|>
<commit_before><commit_msg>Testing rounded rectangle.<commit_after><|endoftext|>
<commit_before>#include "MdTest.h" #include "MemStream.h" void CMdTest::Compile(Jitter::CJitter& jitter) { Framework::CMemStream codeStream; jitter.SetStream(&codeStream); jitter.Begin(); { jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.MD_PullRel(offsetof(CONTEXT, dstMov)); //Shifts jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.PushCst(48); jitter.MD_Srl256(); jitter.MD_PullRel(offsetof(CONTEXT, dstSrl256_1)); jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.MD_Srl256(); jitter.MD_PullRel(offsetof(CONTEXT, dstSrl256_2)); //Packs jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.MD_PackHB(); jitter.MD_PullRel(offsetof(CONTEXT, dstPackHB)); jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.MD_PackWH(); jitter.MD_PullRel(offsetof(CONTEXT, dstPackWH)); } jitter.End(); m_function = CMemoryFunction(codeStream.GetBuffer(), codeStream.GetSize()); } void CMdTest::Run() { CONTEXT ALIGN16 context; memset(&context, 0, sizeof(CONTEXT)); for(unsigned int i = 0; i < 16; i++) { context.src0[i] = i; context.src1[i] = (i << 4); if((i % 8) < 4) { context.src2[i] = context.src0[i]; } else { context.src2[i] = context.src1[i]; } context.src3[i] = 0xC0; } context.shiftAmount = 16; m_function(&context); static const uint8 dstMovRes[16] = { 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0 }; static const uint8 dstSrlH[16] = { 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, }; static const uint8 dstSraH[16] = { 0x10, 0x00, //0x1000 >> 8 0x30, 0x00, //0x3020 0x50, 0x00, //0x5040 0x70, 0x00, //0x7060 0x90, 0xFF, //0x9080 0xB0, 0xFF, //0xB0A0 0xD0, 0xFF, //0xD0C0 0xF0, 0xFF, //0xF0E0 }; static const uint8 dstSllH[16] = { 0x00, 0x00, //0x0100 << 12 0x00, 0x20, //0x0302 0x00, 0x40, //0x0504 0x00, 0x60, //0x0706 0x00, 0x80, //0x0908 0x00, 0xA0, //0x0B0A 0x00, 0xC0, //0x0D0C 0x00, 0xE0, //0x0F0E }; static const uint8 dstSrlW[16] = { 0x04, 0x06, 0x00, 0x00, 0x0C, 0x0E, 0x00, 0x00, 0x14, 0x16, 0x00, 0x00, 0x1C, 0x1E, 0x00, 0x00, }; static const uint8 dstSraW[16] = { 0x01, 0x02, 0x03, 0x00, 0x05, 0x06, 0x07, 0x00, 0x09, 0x0A, 0xFB, 0xFF, 0x0D, 0x0E, 0xFF, 0xFF, }; static const uint8 dstSllW[16] = { 0x00, 0x00, 0x10, 0x20, 0x00, 0x40, 0x50, 0x60, 0x00, 0x80, 0x90, 0xA0, 0x00, 0xC0, 0xD0, 0xE0 }; static const uint8 dstSrl256_1[16] = { 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; static const uint8 dstSrl256_2[16] = { 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x00, 0x01 }; static const uint8 dstPackHBRes[16] = { 0x00, 0x20, 0x40, 0x60, 0x80, 0xA0, 0xC0, 0xE0, 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, }; static const uint8 dstPackWHRes[16] = { 0x00, 0x10, 0x40, 0x50, 0x80, 0x90, 0xC0, 0xD0, 0x00, 0x01, 0x04, 0x05, 0x08, 0x09, 0x0C, 0x0D, }; for(unsigned int i = 0; i < 16; i++) { TEST_VERIFY(dstMovRes[i] == context.dstMov[i]); TEST_VERIFY(dstSrl256_1[i] == context.dstSrl256_1[i]); TEST_VERIFY(dstSrl256_2[i] == context.dstSrl256_2[i]); TEST_VERIFY(dstPackHBRes[i] == context.dstPackHB[i]); TEST_VERIFY(dstPackWHRes[i] == context.dstPackWH[i]); } } <commit_msg>Removed dead code.<commit_after>#include "MdTest.h" #include "MemStream.h" void CMdTest::Compile(Jitter::CJitter& jitter) { Framework::CMemStream codeStream; jitter.SetStream(&codeStream); jitter.Begin(); { jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.MD_PullRel(offsetof(CONTEXT, dstMov)); //Shifts jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.PushCst(48); jitter.MD_Srl256(); jitter.MD_PullRel(offsetof(CONTEXT, dstSrl256_1)); jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.PushRel(offsetof(CONTEXT, shiftAmount)); jitter.MD_Srl256(); jitter.MD_PullRel(offsetof(CONTEXT, dstSrl256_2)); //Packs jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.MD_PackHB(); jitter.MD_PullRel(offsetof(CONTEXT, dstPackHB)); jitter.MD_PushRel(offsetof(CONTEXT, src0)); jitter.MD_PushRel(offsetof(CONTEXT, src1)); jitter.MD_PackWH(); jitter.MD_PullRel(offsetof(CONTEXT, dstPackWH)); } jitter.End(); m_function = CMemoryFunction(codeStream.GetBuffer(), codeStream.GetSize()); } void CMdTest::Run() { CONTEXT ALIGN16 context; memset(&context, 0, sizeof(CONTEXT)); for(unsigned int i = 0; i < 16; i++) { context.src0[i] = i; context.src1[i] = (i << 4); if((i % 8) < 4) { context.src2[i] = context.src0[i]; } else { context.src2[i] = context.src1[i]; } context.src3[i] = 0xC0; } context.shiftAmount = 16; m_function(&context); static const uint8 dstMovRes[16] = { 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0 }; static const uint8 dstSrl256_1[16] = { 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; static const uint8 dstSrl256_2[16] = { 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x00, 0x01 }; static const uint8 dstPackHBRes[16] = { 0x00, 0x20, 0x40, 0x60, 0x80, 0xA0, 0xC0, 0xE0, 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, }; static const uint8 dstPackWHRes[16] = { 0x00, 0x10, 0x40, 0x50, 0x80, 0x90, 0xC0, 0xD0, 0x00, 0x01, 0x04, 0x05, 0x08, 0x09, 0x0C, 0x0D, }; for(unsigned int i = 0; i < 16; i++) { TEST_VERIFY(dstMovRes[i] == context.dstMov[i]); TEST_VERIFY(dstSrl256_1[i] == context.dstSrl256_1[i]); TEST_VERIFY(dstSrl256_2[i] == context.dstSrl256_2[i]); TEST_VERIFY(dstPackHBRes[i] == context.dstPackHB[i]); TEST_VERIFY(dstPackWHRes[i] == context.dstPackWH[i]); } } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GLBench.h" #if SK_SUPPORT_GPU #include "GrTest.h" #include <stdio.h> const GrGLContext* GLBench::getGLContext(SkCanvas* canvas) { // This bench exclusively tests GL calls directly if (nullptr == canvas->getGrContext()) { return nullptr; } GrContext* context = canvas->getGrContext(); GrGpu* gpu = context->getGpu(); if (!gpu) { SkDebugf("Couldn't get Gr gpu."); return nullptr; } const GrGLContext* ctx = gpu->glContextForTesting(); if (!ctx) { SkDebugf("Couldn't get an interface\n"); return nullptr; } return this->onGetGLContext(ctx); } void GLBench::onPreDraw(SkCanvas* canvas) { // This bench exclusively tests GL calls directly const GrGLContext* ctx = this->getGLContext(canvas); if (!ctx) { return; } this->setup(ctx); } void GLBench::onPostDraw(SkCanvas* canvas) { // This bench exclusively tests GL calls directly const GrGLContext* ctx = this->getGLContext(canvas); if (!ctx) { return; } this->teardown(ctx->interface()); } void GLBench::onDraw(int loops, SkCanvas* canvas) { const GrGLContext* ctx = this->getGLContext(canvas); if (!ctx) { return; } this->glDraw(loops, ctx); } GrGLuint GLBench::CompileShader(const GrGLInterface* gl, const char* shaderSrc, GrGLenum type) { GrGLuint shader; // Create the shader object GR_GL_CALL_RET(gl, shader, CreateShader(type)); // Load the shader source GR_GL_CALL(gl, ShaderSource(shader, 1, &shaderSrc, nullptr)); // Compile the shader GR_GL_CALL(gl, CompileShader(shader)); // Check for compile time errors GrGLint success = GR_GL_INIT_ZERO; GrGLchar infoLog[512]; GR_GL_CALL(gl, GetShaderiv(shader, GR_GL_COMPILE_STATUS, &success)); if (!success) { GR_GL_CALL(gl, GetShaderInfoLog(shader, 512, nullptr, infoLog)); SkDebugf("ERROR::SHADER::COMPLIATION_FAILED: %s\n", infoLog); } return shader; } GrGLuint GLBench::CreateProgram(const GrGLInterface* gl, const char* vshader, const char* fshader) { GrGLuint vertexShader = CompileShader(gl, vshader, GR_GL_VERTEX_SHADER); GrGLuint fragmentShader = CompileShader(gl, fshader, GR_GL_FRAGMENT_SHADER); GrGLuint shaderProgram; GR_GL_CALL_RET(gl, shaderProgram, CreateProgram()); GR_GL_CALL(gl, AttachShader(shaderProgram, vertexShader)); GR_GL_CALL(gl, AttachShader(shaderProgram, fragmentShader)); GR_GL_CALL(gl, LinkProgram(shaderProgram)); // Check for linking errors GrGLint success = GR_GL_INIT_ZERO; GrGLchar infoLog[512]; GR_GL_CALL(gl, GetProgramiv(shaderProgram, GR_GL_LINK_STATUS, &success)); if (!success) { GR_GL_CALL(gl, GetProgramInfoLog(shaderProgram, 512, nullptr, infoLog)); SkDebugf("Linker Error: %s\n", infoLog); } GR_GL_CALL(gl, DeleteShader(vertexShader)); GR_GL_CALL(gl, DeleteShader(fragmentShader)); return shaderProgram; } GrGLuint GLBench::SetupFramebuffer(const GrGLInterface* gl, int screenWidth, int screenHeight) { //Setup framebuffer GrGLuint texture; GR_GL_CALL(gl, GenTextures(1, &texture)); GR_GL_CALL(gl, ActiveTexture(GR_GL_TEXTURE7)); GR_GL_CALL(gl, BindTexture(GR_GL_TEXTURE_2D, texture)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MAG_FILTER, GR_GL_NEAREST)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MIN_FILTER, GR_GL_NEAREST)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_S, GR_GL_CLAMP_TO_EDGE)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_T, GR_GL_CLAMP_TO_EDGE)); GR_GL_CALL(gl, TexImage2D(GR_GL_TEXTURE_2D, 0, //level GR_GL_RGBA, //internal format screenWidth, // width screenHeight, // height 0, //border GR_GL_RGBA, //format GR_GL_UNSIGNED_BYTE, // type nullptr)); // bind framebuffer GrGLuint framebuffer; GR_GL_CALL(gl, BindTexture(GR_GL_TEXTURE_2D, 0)); GR_GL_CALL(gl, GenFramebuffers(1, &framebuffer)); GR_GL_CALL(gl, BindFramebuffer(GR_GL_FRAMEBUFFER, framebuffer)); GR_GL_CALL(gl, FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0, GR_GL_TEXTURE_2D, texture, 0)); GR_GL_CALL(gl, CheckFramebufferStatus(GR_GL_FRAMEBUFFER)); GR_GL_CALL(gl, Viewport(0, 0, screenWidth, screenHeight)); return texture; } void GLBench::DumpImage(const GrGLInterface* gl, uint32_t screenWidth, uint32_t screenHeight, const char* filename) { // read back pixels SkAutoTArray<uint32_t> readback(screenWidth * screenHeight); GR_GL_CALL(gl, ReadPixels(0, // x 0, // y screenWidth, // width screenHeight, // height GR_GL_RGBA, //format GR_GL_UNSIGNED_BYTE, //type readback.get())); // dump png SkBitmap bm; if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(screenWidth, screenHeight))) { SkDebugf("couldn't allocate bitmap\n"); return; } bm.setPixels(readback.get()); if (!SkImageEncoder::EncodeFile(filename, bm, SkImageEncoder::kPNG_Type, 100)) { SkDebugf("------ failed to encode %s\n", filename); remove(filename); // remove any partial file return; } } #endif <commit_msg>Reset context after doing non-Skia GL rendering.<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GLBench.h" #if SK_SUPPORT_GPU #include "GrTest.h" #include <stdio.h> const GrGLContext* GLBench::getGLContext(SkCanvas* canvas) { // This bench exclusively tests GL calls directly if (nullptr == canvas->getGrContext()) { return nullptr; } GrContext* context = canvas->getGrContext(); GrGpu* gpu = context->getGpu(); if (!gpu) { SkDebugf("Couldn't get Gr gpu."); return nullptr; } const GrGLContext* ctx = gpu->glContextForTesting(); if (!ctx) { SkDebugf("Couldn't get an interface\n"); return nullptr; } return this->onGetGLContext(ctx); } void GLBench::onPreDraw(SkCanvas* canvas) { // This bench exclusively tests GL calls directly const GrGLContext* ctx = this->getGLContext(canvas); if (!ctx) { return; } this->setup(ctx); } void GLBench::onPostDraw(SkCanvas* canvas) { // This bench exclusively tests GL calls directly const GrGLContext* ctx = this->getGLContext(canvas); if (!ctx) { return; } this->teardown(ctx->interface()); } void GLBench::onDraw(int loops, SkCanvas* canvas) { const GrGLContext* ctx = this->getGLContext(canvas); if (!ctx) { return; } this->glDraw(loops, ctx); canvas->getGrContext()->resetContext(); } GrGLuint GLBench::CompileShader(const GrGLInterface* gl, const char* shaderSrc, GrGLenum type) { GrGLuint shader; // Create the shader object GR_GL_CALL_RET(gl, shader, CreateShader(type)); // Load the shader source GR_GL_CALL(gl, ShaderSource(shader, 1, &shaderSrc, nullptr)); // Compile the shader GR_GL_CALL(gl, CompileShader(shader)); // Check for compile time errors GrGLint success = GR_GL_INIT_ZERO; GrGLchar infoLog[512]; GR_GL_CALL(gl, GetShaderiv(shader, GR_GL_COMPILE_STATUS, &success)); if (!success) { GR_GL_CALL(gl, GetShaderInfoLog(shader, 512, nullptr, infoLog)); SkDebugf("ERROR::SHADER::COMPLIATION_FAILED: %s\n", infoLog); } return shader; } GrGLuint GLBench::CreateProgram(const GrGLInterface* gl, const char* vshader, const char* fshader) { GrGLuint vertexShader = CompileShader(gl, vshader, GR_GL_VERTEX_SHADER); GrGLuint fragmentShader = CompileShader(gl, fshader, GR_GL_FRAGMENT_SHADER); GrGLuint shaderProgram; GR_GL_CALL_RET(gl, shaderProgram, CreateProgram()); GR_GL_CALL(gl, AttachShader(shaderProgram, vertexShader)); GR_GL_CALL(gl, AttachShader(shaderProgram, fragmentShader)); GR_GL_CALL(gl, LinkProgram(shaderProgram)); // Check for linking errors GrGLint success = GR_GL_INIT_ZERO; GrGLchar infoLog[512]; GR_GL_CALL(gl, GetProgramiv(shaderProgram, GR_GL_LINK_STATUS, &success)); if (!success) { GR_GL_CALL(gl, GetProgramInfoLog(shaderProgram, 512, nullptr, infoLog)); SkDebugf("Linker Error: %s\n", infoLog); } GR_GL_CALL(gl, DeleteShader(vertexShader)); GR_GL_CALL(gl, DeleteShader(fragmentShader)); return shaderProgram; } GrGLuint GLBench::SetupFramebuffer(const GrGLInterface* gl, int screenWidth, int screenHeight) { //Setup framebuffer GrGLuint texture; GR_GL_CALL(gl, GenTextures(1, &texture)); GR_GL_CALL(gl, ActiveTexture(GR_GL_TEXTURE7)); GR_GL_CALL(gl, BindTexture(GR_GL_TEXTURE_2D, texture)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MAG_FILTER, GR_GL_NEAREST)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MIN_FILTER, GR_GL_NEAREST)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_S, GR_GL_CLAMP_TO_EDGE)); GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_T, GR_GL_CLAMP_TO_EDGE)); GR_GL_CALL(gl, TexImage2D(GR_GL_TEXTURE_2D, 0, //level GR_GL_RGBA, //internal format screenWidth, // width screenHeight, // height 0, //border GR_GL_RGBA, //format GR_GL_UNSIGNED_BYTE, // type nullptr)); // bind framebuffer GrGLuint framebuffer; GR_GL_CALL(gl, BindTexture(GR_GL_TEXTURE_2D, 0)); GR_GL_CALL(gl, GenFramebuffers(1, &framebuffer)); GR_GL_CALL(gl, BindFramebuffer(GR_GL_FRAMEBUFFER, framebuffer)); GR_GL_CALL(gl, FramebufferTexture2D(GR_GL_FRAMEBUFFER, GR_GL_COLOR_ATTACHMENT0, GR_GL_TEXTURE_2D, texture, 0)); GR_GL_CALL(gl, CheckFramebufferStatus(GR_GL_FRAMEBUFFER)); GR_GL_CALL(gl, Viewport(0, 0, screenWidth, screenHeight)); return texture; } void GLBench::DumpImage(const GrGLInterface* gl, uint32_t screenWidth, uint32_t screenHeight, const char* filename) { // read back pixels SkAutoTArray<uint32_t> readback(screenWidth * screenHeight); GR_GL_CALL(gl, ReadPixels(0, // x 0, // y screenWidth, // width screenHeight, // height GR_GL_RGBA, //format GR_GL_UNSIGNED_BYTE, //type readback.get())); // dump png SkBitmap bm; if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(screenWidth, screenHeight))) { SkDebugf("couldn't allocate bitmap\n"); return; } bm.setPixels(readback.get()); if (!SkImageEncoder::EncodeFile(filename, bm, SkImageEncoder::kPNG_Type, 100)) { SkDebugf("------ failed to encode %s\n", filename); remove(filename); // remove any partial file return; } } #endif <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <math.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; const int limit = 200; const int is_line = 100; typedef struct xyz { int x; int y; int z; } xyz; void gen_coord(string file_path); xyz find_dot(xyz circle, bool &map, int width, int height); int main() { gen_coord("../data/img/sketch.jpg"); return 0; } void gen_coord(string file_path) { Mat src = imread(file_path, 1); ofstream out("out.txt"); int width = src.cols; int height = src.rows; int cp_img[height][width]; bool tag[height][width]; bool &map = tag; //初始化标签 for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { tag[h][w] = 0; } } } xyz find_dot(xyz circle, bool &map, int width, int height) { int x = circle.x; int y = circle.y; xyz next_dot; int max_cr = max(max(max(x, y), abs(x - width - 1)), abs(y - height - 1)); for (int cr = 1; cr < max_cr + 1; cr++) { //分层找点 for (int dn = -cr + 1; dn < cr + 1; dn++) { //下面的边 if (y + cr + 1 > height) break; if (x + dn < 0) continue; if (x + dn + 1 > width) break; if (!map[x + dn][y + cr]) { next_dot = {x + dn, y + cr, cr}; map[x + dn][y + cr] = 1; return next_dot; } } for (int rt = -cr + 1; rt < cr + 1; rt++) { //右面的边 if (x + cr + 1 > width) break; if (y - rt + 1 > height) continue; if (y - rt < 0) break; if (!map[x + cr][y - rt]) { next_dot = {x + cr, y - rt, cr}; map[x + cr][y - rt] = 1; return next_dot; } } for (int up = -cr + 1; up < cr + 1; up++) { //上面的边 if (y - cr < 0) break; if (x - up + 1 > width) continue; if (x - up < 0) break; if (!map[x - up][y - cr]) { next_dot = {x - up, y - cr, cr}; map[x - up][y - cr] = 1; return next_dot; } } for (int lt = -cr + 1; lt < cr + 1; lt++) { //左面的边 if (x - cr < 0) break; if (y + lt < 0) continue; if (y + lt + 1 > height) break; if (!map[x - cr][y + lt]) { next_dot = {x - cr, y + lt, cr}; map[x - cr][y + lt] = 1; return next_dot; } } } next_dot = {-1, -1, -1}; return next_dot; } /* int direction = 0; int diff = 0; for (i = 1; i < height - 2; i += 2) { for (j = 1; j < width - 2; j += 2) { if (cp_img[i][j] > limit) { //颜色深度不够 tag[i][j] = 1; continue; } diff0 = abs(cp_img[i][j] - cp_img[i + 1][j]); //下 diff1 = abs(cp_img[i][j] - cp_img[i + 1][j + 1]); //右下 diff2 = abs(cp_img[i][j] - cp_img[i][j + 1]); //右 diff3 = abs(cp_img[i][j] - cp_img[i + 1][j - 1]); //左下 diff = diff0; direction = 0; if (diff1 < diff) { diff = diff1; direction = 1; } if (diff2 < diff) { diff = diff2; direction = 2; } if (diff3 < diff) { diff = diff3; direction = 3; } if (diff > is_line) { tag[i][j] = 1; continue; } out << "(" << i << "," << j << ",0" << ")"; switch (drection) { case 0: case 1: case 2: case 3: default: } } } */<commit_msg>image to dierection and steps<commit_after>#include <fstream> #include <iostream> #include <math.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; const double PI = 3.1415926536; const int angle2step = 120; typedef struct angles { float a; float b; float r; } angles; typedef struct xyz { float x; float y; float z; } xyz; angles cal_angle(xyz coord); string f_dirsteps(xyz curr, xyz next); string num2str(int i); void gen_coord(string file_path); xyz find_dot(xyz circle, int *cp_img, int width, int height); int main() { gen_coord("../data/img/sketch.jpg"); return 0; } void gen_coord(string file_path) { Mat src = imread(file_path, 1); ofstream out("out.txt"); int width = src.cols; int height = src.rows; int cp_img[height][width]; for (int h = 0; h < height; h++) { uchar *P = src.ptr<uchar>(h); for (int w = 0; w < width; w++) { cp_img[h][w] = P[w]; } } xyz center = {0, 0, 0}; xyz next_center = {-1, -1, -1}; int find_tag = 0; for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { if (cp_img[h][w] == 255) { center = {w, h, 0}; find_tag = 1; break; } } if (find_tag == 1) break; } while (1) { next_center = find_dot(center, (int *)cp_img, width, height); if (next_center.z == -1) break; if (next_center.z > 3) { xyz temp1 = center; temp1.z = 1; f_dirsteps(center, temp1); next_center.z = 1; xyz temp2 = next_center; f_dirsteps(temp1, temp2); next_center.z = 0; f_dirsteps(temp2, next_center); center = next_center; } else { next_center.z = 0; f_dirsteps(center, next_center); center = next_center; } cp_img[int(center.y)][int(center.x)] = 0; } out.close(); } xyz find_dot(xyz center, int *cp_img, int width, int height) { int x = center.x; int y = center.y; xyz next_dot; int map[height][width]; for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { map[h][w] = *(cp_img + width * h + w); } } int max_cr = max(max(max(x, y), abs(x - width - 1)), abs(y - height - 1)); for (int cr = 1; cr < max_cr + 1; cr++) { //分层找点 for (int dn = -cr + 1; dn < cr + 1; dn++) { //下面的边 if (y + cr + 1 > height) break; if (x + dn < 0) continue; if (x + dn + 1 > width) break; if (!map[x + dn][y + cr]) { next_dot = {x + dn, y + cr, cr}; map[x + dn][y + cr] = 0; return next_dot; } } for (int rt = -cr + 1; rt < cr + 1; rt++) { //右面的边 if (x + cr + 1 > width) break; if (y - rt + 1 > height) continue; if (y - rt < 0) break; if (!map[x + cr][y - rt]) { next_dot = {x + cr, y - rt, cr}; map[x + cr][y - rt] = 0; return next_dot; } } for (int up = -cr + 1; up < cr + 1; up++) { //上面的边 if (y - cr < 0) break; if (x - up + 1 > width) continue; if (x - up < 0) break; if (!map[x - up][y - cr]) { next_dot = {x - up, y - cr, cr}; map[x - up][y - cr] = 0; return next_dot; } } for (int lt = -cr + 1; lt < cr + 1; lt++) { //左面的边 if (x - cr < 0) break; if (y + lt < 0) continue; if (y + lt + 1 > height) break; if (!map[x - cr][y + lt]) { next_dot = {x - cr, y + lt, cr}; map[x - cr][y + lt] = 0; return next_dot; } } } next_dot = {-1, -1, -1}; return next_dot; } angles cal_angle(xyz coord) { float p = 0.0; angles angle; p = sqrt(coord.x * coord.x + coord.y * coord.y + coord.z * coord.z); if (coord.x <= 0) angle.a = asin(-coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI; else angle.a = asin(coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI + 180; coord.y = coord.y + 80 * sin(angle.a); coord.x = coord.x + 80 * cos(angle.a); p = sqrt(coord.x * coord.x + coord.y * coord.y + coord.z * coord.z); if (coord.x <= 0) angle.a = asin(-coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI; else angle.a = asin(coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI + 180; angle.b = (acos((45 / p) + (p / 500)) + asin(-coord.z / p)) * 180 / PI; angle.r = (acos((p * p - 22500) / (400 * p)) + acos(-coord.z / p)) * 180 / PI; return angle; } string f_dirsteps(xyz curr, xyz next) { string fpath = "$"; angles curr_angles = cal_angle(curr); angles next_angles = cal_angle(next); float angle_a = next_angles.a - curr_angles.a; float angle_b = next_angles.b - curr_angles.b; float angle_r = next_angles.r - curr_angles.r; if (angle_a > 0) fpath = fpath + "1" + num2str(round(angle_a * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_a * angle2step)) + "#"; if (angle_b > 0) fpath = fpath + "1" + num2str(round(angle_b * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_b * angle2step)) + "#"; if (angle_r > 0) fpath = fpath + "1" + num2str(round(angle_r * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_r * angle2step)) + "#"; fpath = fpath + "@"; return fpath; } string num2str(int i) { stringstream ss; ss << i; return ss.str(); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "YetAnotherRegularExpressionEngine.h" #ifdef _DEBUG #include <conio.h> #endif #if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64)) #include <intrin.h> #pragma intrinsic(__rdtsc) #define rdtsc __rdtsc typedef unsigned __int64 rdtsc_t; #else #include <limits> #include <ctime> #endif void expect(const char *expr, bool ex, bool ac){ const char* e = ex ? "true" : "false"; const char *a = ac ? "true" : "false"; if (ex == ac){ std::cout << "passed: " << expr << " = " << e << std::endl; } else{ std::cout << "!!error: expect " << expr << " = " << e << ", get " << a << " instead." << std::endl; } } class TestException{ FA2 fa; std::string re; public: TestException(const char *re) :fa(re), re(re){} TestException& operator ,(const char *p){ using namespace std; try{ fa << p; } catch (FA1::SyntaxErrorException&){ cout << "passed:" " expected exception received for RE /" << re << "/" << endl; return *this; } cout << "!!error: expected exception was not caught." << endl; return *this; } }; class Expect{ bool assert; public: explicit Expect(bool b) :assert(b){} bool GetAssert(){ return assert; } }; class Test{ bool assert; FA1 faCompare; FA2 fa; public: Test(const char *re, Expect e) :fa(re), faCompare(re), assert(e.GetAssert()){ std::cout << "Testing RE /" << re << "/ :" << std::endl; } Test& operator ,(const char*p){ using namespace std; if (*p == '\0'){ expect("<Empty String>", assert, fa << p); } else{ expect(p, assert, fa << p); } #ifdef rdtsc unsigned __int64 start; start = rdtsc(); for (int i = 0; i < 9999; ++i){ faCompare << p; } rdtsc_t time1 = rdtsc() - start; cout << "nfa took " << time1 << " clock cycles to calculate for 9999 times" << endl; start = rdtsc(); for (int i = 0; i < 9999; ++i){ fa << p; } rdtsc_t time2 = rdtsc() - start; cout << "dfa took " << time2 << " clock cycles to calculate for 9999 times" << endl; cout << "factor: " << time1 / time2 << endl; #else time_t tm; tm = time(0); for (int i = 0; i < numeric_limits<int>::max(); ++i){ faCompare << p; } cout << "nfa took " << (time(0) - tm) << " seconds to calculate for " << numeric_limits<int>::max() << " times" << endl; tm = time(0); for (int i = 0; i < numeric_limits<int>::max(); ++i){ fa << p; } cout << "dfa took " << (time(0) - tm) << " seconds to calculate for " << numeric_limits<int>::max() << " times" << endl; #endif return *this; } }; int main(){ Test("", Expect(true)), ""; Test("", Expect(false)), "a"; Test("a", Expect(true)), "a"; Test("a", Expect(false)), "b", "abc", ""; Test("ab", Expect(true)), "ab"; Test("ab", Expect(false)), "", "a", "b", "c"; Test("a|b", Expect(true)), "a", "b"; Test("a|b", Expect(false)), "abc", "ab", ""; Test("ab|c", Expect(true)), "ab", "c"; Test("ab|c", Expect(false)), "a", "b", "abc"; Test("ab|a", Expect(true)), "ab", "a"; Test("ab|a", Expect(false)), "b", "c", "abc"; Test("a|bc", Expect(true)), "a", "bc"; Test("a|bc", Expect(false)), "ab", "c", ""; Test("a*", Expect(true)), "", "a", "aaa"; Test("a*", Expect(false)), "b", "ab", "ba"; Test("ab*", Expect(true)), "a", "abb"; Test("ab*", Expect(false)), "b", "bb", "bc", "abc", ""; Test("a*b", Expect(true)), "b", "aaab", "ab"; Test("a*b", Expect(false)), "aa", "ac", ""; Test("a*ab", Expect(true)), "ab", "aab", "aaaab"; Test("a*ab", Expect(false)), "a", "b", "c"; Test("aa*b", Expect(true)), "ab", "aab", "aaaab"; Test("aa*b", Expect(false)), "a", "b", "c"; Test("a*|b", Expect(true)), "aaa", "b", ""; Test("a*|b", Expect(false)), "abc", "ba", "cb", "ab"; Test("a|b*", Expect(true)), "a", "bb", ""; Test("a|b*", Expect(false)), "aa", "ab", "bc"; Test("a|b|c", Expect(true)), "a", "b", "c"; Test("a|b|c", Expect(false)), "ab", "d", ""; Test("a|", Expect(true)), "a", ""; Test("a|", Expect(false)), "b", "aa"; Test("|a", Expect(true)), "a", ""; Test("|a", Expect(false)), "b"; Test("||", Expect(true)), ""; Test("||", Expect(false)), "a"; TestException("*"), "", "a", "b"; TestException("|*"), "", "a", "b"; TestException("**"), "", "a", "b"; TestException("*|*"), "", "a", "b"; TestException("*||*"), "", "a", "b"; TestException("||*"), "", "a", "b"; #ifdef _DEBUG #ifdef _MSC_VER _CrtCheckMemory(); _CrtDumpMemoryLeaks(); #endif _getch(); #endif return 0; } <commit_msg>Made some cleanning, fixed problem that test takes too long.<commit_after>#include <iostream> #include <string> #include "YetAnotherRegularExpressionEngine.h" #ifdef _DEBUG #include <conio.h> #endif #if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64)) #include <intrin.h> #pragma intrinsic(__rdtsc) #define rdtsc __rdtsc typedef unsigned __int64 rdtsc_t; #else #include <ctime> #endif void expect(const char *expr, bool ex, bool ac){ const char* e = ex ? "true" : "false"; const char *a = ac ? "true" : "false"; if (ex == ac){ std::cout << "passed: " << expr << " = " << e << std::endl; } else{ std::cout << "!!error: expect " << expr << " = " << e << ", get " << a << " instead." << std::endl; } } class TestException{ FA2 fa; std::string re; public: TestException(const char *re) :fa(re), re(re){} TestException& operator ,(const char *p){ using namespace std; try{ fa << p; } catch (FA1::SyntaxErrorException&){ cout << "passed:" " expected exception received for RE /" << re << "/" << endl; return *this; } cout << "!!error: expected exception was not caught." << endl; return *this; } }; class Expect{ bool assert; public: explicit Expect(bool b) :assert(b){} bool GetAssert(){ return assert; } }; class Test{ bool assert; FA1 faCompare; FA2 fa; public: Test(const char *re, Expect e) :fa(re), faCompare(re), assert(e.GetAssert()){ std::cout << "Testing RE /" << re << "/ :" << std::endl; } Test& operator ,(const char*p){ using namespace std; if (*p == '\0'){ expect("<Empty String>", assert, fa << p); } else{ expect(p, assert, fa << p); } #ifdef rdtsc unsigned __int64 start; start = rdtsc(); for (int i = 0; i < 9999; ++i){ faCompare << p; } rdtsc_t time1 = rdtsc() - start; cout << "nfa took " << time1 << " clock cycles to calculate for 9999 times" << endl; start = rdtsc(); for (int i = 0; i < 9999; ++i){ fa << p; } rdtsc_t time2 = rdtsc() - start; cout << "dfa took " << time2 << " clock cycles to calculate for 9999 times" << endl; cout << "factor: " << time1 / time2 << endl; #else time_t tm; tm = time(0); for (int i = 0; i < 9999999; ++i){ faCompare << p; } cout << "nfa took " << (time(0) - tm) << " seconds to calculate for " << 9999999 << " times" << endl; tm = time(0); for (int i = 0; i < 9999999; ++i){ fa << p; } cout << "dfa took " << (time(0) - tm) << " seconds to calculate for " << 9999999 << " times" << endl; #endif return *this; } }; int main(){ Test("", Expect(true)), ""; Test("", Expect(false)), "a"; Test("a", Expect(true)), "a"; Test("a", Expect(false)), "b", "abc", ""; Test("ab", Expect(true)), "ab"; Test("ab", Expect(false)), "", "a", "b", "c"; Test("a|b", Expect(true)), "a", "b"; Test("a|b", Expect(false)), "abc", "ab", ""; Test("ab|c", Expect(true)), "ab", "c"; Test("ab|c", Expect(false)), "a", "b", "abc"; Test("ab|a", Expect(true)), "ab", "a"; Test("ab|a", Expect(false)), "b", "c", "abc"; Test("a|bc", Expect(true)), "a", "bc"; Test("a|bc", Expect(false)), "ab", "c", ""; Test("a*", Expect(true)), "", "a", "aaa"; Test("a*", Expect(false)), "b", "ab", "ba"; Test("ab*", Expect(true)), "a", "abb"; Test("ab*", Expect(false)), "b", "bb", "bc", "abc", ""; Test("a*b", Expect(true)), "b", "aaab", "ab"; Test("a*b", Expect(false)), "aa", "ac", ""; Test("a*ab", Expect(true)), "ab", "aab", "aaaab"; Test("a*ab", Expect(false)), "a", "b", "c"; Test("aa*b", Expect(true)), "ab", "aab", "aaaab"; Test("aa*b", Expect(false)), "a", "b", "c"; Test("a*|b", Expect(true)), "aaa", "b", ""; Test("a*|b", Expect(false)), "abc", "ba", "cb", "ab"; Test("a|b*", Expect(true)), "a", "bb", ""; Test("a|b*", Expect(false)), "aa", "ab", "bc"; Test("a|b|c", Expect(true)), "a", "b", "c"; Test("a|b|c", Expect(false)), "ab", "d", ""; Test("a|", Expect(true)), "a", ""; Test("a|", Expect(false)), "b", "aa"; Test("|a", Expect(true)), "a", ""; Test("|a", Expect(false)), "b"; Test("||", Expect(true)), ""; Test("||", Expect(false)), "a"; TestException("*"), "", "a", "b"; TestException("|*"), "", "a", "b"; TestException("**"), "", "a", "b"; TestException("*|*"), "", "a", "b"; TestException("*||*"), "", "a", "b"; TestException("||*"), "", "a", "b"; #ifdef _DEBUG #ifdef _MSC_VER _CrtCheckMemory(); _CrtDumpMemoryLeaks(); #endif _getch(); #endif return 0; } <|endoftext|>
<commit_before>#include "shader.h" #include <cstring> #include "utils.h" #include <chrono> #include <iostream> Shader::Shader():m_program(0),m_fragmentShader(0),m_vertexShader(0), m_backbuffer(0), m_time(false), m_delta(false), m_date(false), m_mouse(false), m_imouse(false), m_view2d(false) { } Shader::~Shader() { if (m_program != 0) { // Avoid crash when no command line arguments supplied glDeleteProgram(m_program); } } std::string getLineNumber(const std::string& _source, unsigned _lineNumber){ std::string delimiter = "\n"; std::string::const_iterator substart = _source.begin(), subend; unsigned index = 1; while (true) { subend = search(substart, _source.end(), delimiter.begin(), delimiter.end()); std::string sub(substart, subend); if (index == _lineNumber) { return sub; } index++; if (subend == _source.end()) { break; } substart = subend + delimiter.size(); } return "NOT FOUND"; } // Quickly determine if a shader program contains the specified identifier. bool find_id(const std::string& program, const char* id) { return std::strstr(program.c_str(), id) != 0; } bool Shader::load(const std::string* _fragmentPath, const std::string& _fragmentSrc, const std::string* _vertexPath, const std::string& _vertexSrc, bool verbose) { std::chrono::time_point<std::chrono::steady_clock> start_time, end_time; start_time = std::chrono::steady_clock::now(); m_vertexShader = compileShader(_vertexPath, _vertexSrc, GL_VERTEX_SHADER); if(!m_vertexShader) { return false; } m_fragmentShader = compileShader(_fragmentPath, _fragmentSrc, GL_FRAGMENT_SHADER); if(!m_fragmentShader) { return false; } else { m_backbuffer = find_id(_fragmentSrc, "u_backbuffer"); if (!m_time) m_time = find_id(_fragmentSrc, "u_time"); if (!m_delta) m_delta = find_id(_fragmentSrc, "u_delta"); if (!m_date) m_date = find_id(_fragmentSrc, "u_date"); m_mouse = find_id(_fragmentSrc, "u_mouse"); m_view2d = find_id(_fragmentSrc, "u_view2d"); } m_program = glCreateProgram(); glAttachShader(m_program, m_vertexShader); glAttachShader(m_program, m_fragmentShader); glLinkProgram(m_program); end_time = std::chrono::steady_clock::now(); std::chrono::duration<double> load_time = end_time - start_time; GLint isLinked; glGetProgramiv(m_program, GL_LINK_STATUS, &isLinked); if (isLinked == GL_FALSE) { GLint infoLength = 0; glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &infoLength); if (infoLength > 1) { std::vector<GLchar> infoLog(infoLength); glGetProgramInfoLog(m_program, infoLength, NULL, &infoLog[0]); std::string error(infoLog.begin(),infoLog.end()); // printf("Error linking shader:\n%s\n", error); std::cerr << "Error linking shader: " << error << std::endl; std::size_t start = error.find("line ")+5; std::size_t end = error.find_last_of(")"); std::string lineNum = error.substr(start,end-start); std::cerr << (unsigned)getInt(lineNum) << ": " << getLineNumber(_fragmentSrc,(unsigned)getInt(lineNum)) << std::endl; } glDeleteProgram(m_program); return false; } else { glDeleteShader(m_vertexShader); glDeleteShader(m_fragmentShader); #ifndef PLATFORM_RPI if (verbose) { std::cerr << "shader load time: " << load_time.count() << "s"; GLint proglen = 0; glGetProgramiv(m_program, GL_PROGRAM_BINARY_LENGTH, &proglen); if (proglen > 0) std::cerr << " size: " << proglen; GLint icount = 0; glGetProgramivARB(m_program, GL_PROGRAM_INSTRUCTIONS_ARB, &icount); if (icount > 0) std::cerr << " #instructions: " << icount; std::cerr << "\n"; } #endif return true; } } const GLint Shader::getAttribLocation(const std::string& _attribute) const { return glGetAttribLocation(m_program, _attribute.c_str()); } void Shader::use() const { if(!isInUse()) { glUseProgram(getProgram()); } } bool Shader::isInUse() const { GLint currentProgram = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &currentProgram); return (getProgram() == (GLuint)currentProgram); } GLuint Shader::compileShader(const std::string* _path, const std::string& _src, GLenum _type) { std::string prolog; const char* epilog = ""; if (_path) { prolog += "#define __GLSLVIEWER__ 1\n"; #ifdef PLATFORM_OSX prolog += "#define PLATFORM_OSX\n"; #endif #ifdef PLATFORM_LINUX prolog += "#define PLATFORM_LINUX\n"; #endif #ifdef PLATFORM_RPI prolog += "#define PLATFORM_RPI\n"; #endif } // Test if this is a shadertoy.com image shader. If it is, we need to // define some uniforms with different names than the glslViewer standard, // and we need to add prolog and epilog code. if (_path && _type == GL_FRAGMENT_SHADER && find_id(_src, "mainImage")) { epilog = "\n" "void main(void) {\n" " mainImage(gl_FragColor, gl_FragCoord.st);\n" "}\n"; prolog += "uniform vec2 u_resolution;\n" "#define iResolution vec3(u_resolution, 1.0)\n" "\n"; m_time = find_id(_src, "iGlobalTime"); if (m_time) { prolog += "uniform float u_time;\n" "#define iGlobalTime u_time\n" "\n"; } m_delta = find_id(_src, "iTimeDelta"); if (m_delta) { prolog += "uniform float u_delta;\n" "#define iTimeDelta u_delta\n" "\n"; } m_date = find_id(_src, "iDate"); if (m_date) { prolog += "uniform vec4 u_date;\n" "#define iDate u_date\n" "\n"; } m_imouse = find_id(_src, "iMouse"); if (m_imouse) { prolog += "uniform vec4 iMouse;\n" "\n"; } } if (_path) { prolog += "#line 1\n"; } const GLchar* sources[3] = { (const GLchar*) prolog.c_str(), (const GLchar*) _src.c_str(), (const GLchar*) epilog, }; GLuint shader = glCreateShader(_type); glShaderSource(shader, 3, sources, NULL); glCompileShader(shader); GLint isCompiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); GLint infoLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLength); if (infoLength > 1) { std::vector<GLchar> infoLog(infoLength); glGetShaderInfoLog(shader, infoLength, NULL, &infoLog[0]); std::cerr << (isCompiled ? "Warnings" : "Errors"); std::cerr << " while compiling "; std::cerr << (_path ? *_path : "shader"); std::cerr << ":\n" << &infoLog[0]; } if (isCompiled == GL_FALSE) { glDeleteShader(shader); return 0; } return shader; } void Shader::detach(GLenum _type) { bool vert = (GL_VERTEX_SHADER & _type) == GL_VERTEX_SHADER; bool frag = (GL_FRAGMENT_SHADER & _type) == GL_FRAGMENT_SHADER; if(vert) { glDeleteShader(m_vertexShader); glDetachShader(m_vertexShader, GL_VERTEX_SHADER); } if(frag) { glDeleteShader(m_fragmentShader); glDetachShader(m_fragmentShader, GL_FRAGMENT_SHADER); } } GLint Shader::getUniformLocation(const std::string& _uniformName) const { GLint loc = glGetUniformLocation(m_program, _uniformName.c_str()); if(loc == -1){ // std::cerr << "Uniform " << _uniformName << " not found" << std::endl; } return loc; } void Shader::setUniform(const std::string& _name, const float *_array, unsigned int _size) { GLint loc = getUniformLocation(_name); if(isInUse()) { if (_size == 1) { glUniform1f(loc, _array[0]); } else if (_size == 2) { glUniform2f(loc, _array[0], _array[1]); } else if (_size == 3) { glUniform3f(loc, _array[0], _array[1], _array[2]); } else if (_size == 4) { glUniform4f(loc, _array[0], _array[1], _array[2], _array[2]); } else { std::cout << "Passing matrix uniform as array, not supported yet" << std::endl; } } } void Shader::setUniform(const std::string& _name, float _x) { if(isInUse()) { glUniform1f(getUniformLocation(_name), _x); // std::cout << "Uniform " << _name << ": float(" << _x << ")" << std::endl; } } void Shader::setUniform(const std::string& _name, float _x, float _y) { if(isInUse()) { glUniform2f(getUniformLocation(_name), _x, _y); // std::cout << "Uniform " << _name << ": vec2(" << _x << "," << _y << ")" << std::endl; } } void Shader::setUniform(const std::string& _name, float _x, float _y, float _z) { if(isInUse()) { glUniform3f(getUniformLocation(_name), _x, _y, _z); // std::cout << "Uniform " << _name << ": vec3(" << _x << "," << _y << "," << _z <<")" << std::endl; } } void Shader::setUniform(const std::string& _name, float _x, float _y, float _z, float _w) { if(isInUse()) { glUniform4f(getUniformLocation(_name), _x, _y, _z, _w); // std::cout << "Uniform " << _name << ": vec3(" << _x << "," << _y << "," << _z <<")" << std::endl; } } void Shader::setUniform(const std::string& _name, const Texture* _tex, unsigned int _texLoc){ if(isInUse()) { glActiveTexture(GL_TEXTURE0 + _texLoc); glBindTexture(GL_TEXTURE_2D, _tex->getId()); glUniform1i(getUniformLocation(_name), _texLoc); } } void Shader::setUniform(const std::string& _name, const Fbo* _fbo, unsigned int _texLoc){ if(isInUse()) { glActiveTexture(GL_TEXTURE0 + _texLoc); glBindTexture(GL_TEXTURE_2D, _fbo->getTextureId()); glUniform1i(getUniformLocation(_name), _texLoc); } } void Shader::setUniform(const std::string& _name, const glm::mat2& _value, bool _transpose){ if(isInUse()) { glUniformMatrix2fv(getUniformLocation(_name), 1, _transpose, &_value[0][0]); } } void Shader::setUniform(const std::string& _name, const glm::mat3& _value, bool _transpose){ if(isInUse()) { glUniformMatrix3fv(getUniformLocation(_name), 1, _transpose, &_value[0][0]); } } void Shader::setUniform(const std::string& _name, const glm::mat4& _value, bool _transpose){ if(isInUse()) { glUniformMatrix4fv(getUniformLocation(_name), 1, _transpose, &_value[0][0]); } } <commit_msg>more elegant and generalize way to adapt out puts to platforms<commit_after>#include "shader.h" #include <cstring> #include "utils.h" #include <chrono> #include <iostream> Shader::Shader():m_program(0),m_fragmentShader(0),m_vertexShader(0), m_backbuffer(0), m_time(false), m_delta(false), m_date(false), m_mouse(false), m_imouse(false), m_view2d(false) { } Shader::~Shader() { if (m_program != 0) { // Avoid crash when no command line arguments supplied glDeleteProgram(m_program); } } std::string getLineNumber(const std::string& _source, unsigned _lineNumber){ std::string delimiter = "\n"; std::string::const_iterator substart = _source.begin(), subend; unsigned index = 1; while (true) { subend = search(substart, _source.end(), delimiter.begin(), delimiter.end()); std::string sub(substart, subend); if (index == _lineNumber) { return sub; } index++; if (subend == _source.end()) { break; } substart = subend + delimiter.size(); } return "NOT FOUND"; } // Quickly determine if a shader program contains the specified identifier. bool find_id(const std::string& program, const char* id) { return std::strstr(program.c_str(), id) != 0; } bool Shader::load(const std::string* _fragmentPath, const std::string& _fragmentSrc, const std::string* _vertexPath, const std::string& _vertexSrc, bool verbose) { std::chrono::time_point<std::chrono::steady_clock> start_time, end_time; start_time = std::chrono::steady_clock::now(); m_vertexShader = compileShader(_vertexPath, _vertexSrc, GL_VERTEX_SHADER); if(!m_vertexShader) { return false; } m_fragmentShader = compileShader(_fragmentPath, _fragmentSrc, GL_FRAGMENT_SHADER); if(!m_fragmentShader) { return false; } else { m_backbuffer = find_id(_fragmentSrc, "u_backbuffer"); if (!m_time) m_time = find_id(_fragmentSrc, "u_time"); if (!m_delta) m_delta = find_id(_fragmentSrc, "u_delta"); if (!m_date) m_date = find_id(_fragmentSrc, "u_date"); m_mouse = find_id(_fragmentSrc, "u_mouse"); m_view2d = find_id(_fragmentSrc, "u_view2d"); } m_program = glCreateProgram(); glAttachShader(m_program, m_vertexShader); glAttachShader(m_program, m_fragmentShader); glLinkProgram(m_program); end_time = std::chrono::steady_clock::now(); std::chrono::duration<double> load_time = end_time - start_time; GLint isLinked; glGetProgramiv(m_program, GL_LINK_STATUS, &isLinked); if (isLinked == GL_FALSE) { GLint infoLength = 0; glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &infoLength); if (infoLength > 1) { std::vector<GLchar> infoLog(infoLength); glGetProgramInfoLog(m_program, infoLength, NULL, &infoLog[0]); std::string error(infoLog.begin(),infoLog.end()); // printf("Error linking shader:\n%s\n", error); std::cerr << "Error linking shader: " << error << std::endl; std::size_t start = error.find("line ")+5; std::size_t end = error.find_last_of(")"); std::string lineNum = error.substr(start,end-start); std::cerr << (unsigned)getInt(lineNum) << ": " << getLineNumber(_fragmentSrc,(unsigned)getInt(lineNum)) << std::endl; } glDeleteProgram(m_program); return false; } else { glDeleteShader(m_vertexShader); glDeleteShader(m_fragmentShader); if (verbose) { std::cerr << "shader load time: " << load_time.count() << "s"; #ifdef GL_PROGRAM_BINARY_LENGTH GLint proglen = 0; glGetProgramiv(m_program, GL_PROGRAM_BINARY_LENGTH, &proglen); if (proglen > 0) std::cerr << " size: " << proglen; #endif #ifdef GL_PROGRAM_INSTRUCTIONS_ARB GLint icount = 0; glGetProgramivARB(m_program, GL_PROGRAM_INSTRUCTIONS_ARB, &icount); if (icount > 0) std::cerr << " #instructions: " << icount; #endif } return true; } } const GLint Shader::getAttribLocation(const std::string& _attribute) const { return glGetAttribLocation(m_program, _attribute.c_str()); } void Shader::use() const { if(!isInUse()) { glUseProgram(getProgram()); } } bool Shader::isInUse() const { GLint currentProgram = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &currentProgram); return (getProgram() == (GLuint)currentProgram); } GLuint Shader::compileShader(const std::string* _path, const std::string& _src, GLenum _type) { std::string prolog; const char* epilog = ""; if (_path) { prolog += "#define __GLSLVIEWER__ 1\n"; #ifdef PLATFORM_OSX prolog += "#define PLATFORM_OSX\n"; #endif #ifdef PLATFORM_LINUX prolog += "#define PLATFORM_LINUX\n"; #endif #ifdef PLATFORM_RPI prolog += "#define PLATFORM_RPI\n"; #endif } // Test if this is a shadertoy.com image shader. If it is, we need to // define some uniforms with different names than the glslViewer standard, // and we need to add prolog and epilog code. if (_path && _type == GL_FRAGMENT_SHADER && find_id(_src, "mainImage")) { epilog = "\n" "void main(void) {\n" " mainImage(gl_FragColor, gl_FragCoord.st);\n" "}\n"; prolog += "uniform vec2 u_resolution;\n" "#define iResolution vec3(u_resolution, 1.0)\n" "\n"; m_time = find_id(_src, "iGlobalTime"); if (m_time) { prolog += "uniform float u_time;\n" "#define iGlobalTime u_time\n" "\n"; } m_delta = find_id(_src, "iTimeDelta"); if (m_delta) { prolog += "uniform float u_delta;\n" "#define iTimeDelta u_delta\n" "\n"; } m_date = find_id(_src, "iDate"); if (m_date) { prolog += "uniform vec4 u_date;\n" "#define iDate u_date\n" "\n"; } m_imouse = find_id(_src, "iMouse"); if (m_imouse) { prolog += "uniform vec4 iMouse;\n" "\n"; } } if (_path) { prolog += "#line 1\n"; } const GLchar* sources[3] = { (const GLchar*) prolog.c_str(), (const GLchar*) _src.c_str(), (const GLchar*) epilog, }; GLuint shader = glCreateShader(_type); glShaderSource(shader, 3, sources, NULL); glCompileShader(shader); GLint isCompiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); GLint infoLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLength); if (infoLength > 1) { std::vector<GLchar> infoLog(infoLength); glGetShaderInfoLog(shader, infoLength, NULL, &infoLog[0]); std::cerr << (isCompiled ? "Warnings" : "Errors"); std::cerr << " while compiling "; std::cerr << (_path ? *_path : "shader"); std::cerr << ":\n" << &infoLog[0]; } if (isCompiled == GL_FALSE) { glDeleteShader(shader); return 0; } return shader; } void Shader::detach(GLenum _type) { bool vert = (GL_VERTEX_SHADER & _type) == GL_VERTEX_SHADER; bool frag = (GL_FRAGMENT_SHADER & _type) == GL_FRAGMENT_SHADER; if(vert) { glDeleteShader(m_vertexShader); glDetachShader(m_vertexShader, GL_VERTEX_SHADER); } if(frag) { glDeleteShader(m_fragmentShader); glDetachShader(m_fragmentShader, GL_FRAGMENT_SHADER); } } GLint Shader::getUniformLocation(const std::string& _uniformName) const { GLint loc = glGetUniformLocation(m_program, _uniformName.c_str()); if(loc == -1){ // std::cerr << "Uniform " << _uniformName << " not found" << std::endl; } return loc; } void Shader::setUniform(const std::string& _name, const float *_array, unsigned int _size) { GLint loc = getUniformLocation(_name); if(isInUse()) { if (_size == 1) { glUniform1f(loc, _array[0]); } else if (_size == 2) { glUniform2f(loc, _array[0], _array[1]); } else if (_size == 3) { glUniform3f(loc, _array[0], _array[1], _array[2]); } else if (_size == 4) { glUniform4f(loc, _array[0], _array[1], _array[2], _array[2]); } else { std::cout << "Passing matrix uniform as array, not supported yet" << std::endl; } } } void Shader::setUniform(const std::string& _name, float _x) { if(isInUse()) { glUniform1f(getUniformLocation(_name), _x); // std::cout << "Uniform " << _name << ": float(" << _x << ")" << std::endl; } } void Shader::setUniform(const std::string& _name, float _x, float _y) { if(isInUse()) { glUniform2f(getUniformLocation(_name), _x, _y); // std::cout << "Uniform " << _name << ": vec2(" << _x << "," << _y << ")" << std::endl; } } void Shader::setUniform(const std::string& _name, float _x, float _y, float _z) { if(isInUse()) { glUniform3f(getUniformLocation(_name), _x, _y, _z); // std::cout << "Uniform " << _name << ": vec3(" << _x << "," << _y << "," << _z <<")" << std::endl; } } void Shader::setUniform(const std::string& _name, float _x, float _y, float _z, float _w) { if(isInUse()) { glUniform4f(getUniformLocation(_name), _x, _y, _z, _w); // std::cout << "Uniform " << _name << ": vec3(" << _x << "," << _y << "," << _z <<")" << std::endl; } } void Shader::setUniform(const std::string& _name, const Texture* _tex, unsigned int _texLoc){ if(isInUse()) { glActiveTexture(GL_TEXTURE0 + _texLoc); glBindTexture(GL_TEXTURE_2D, _tex->getId()); glUniform1i(getUniformLocation(_name), _texLoc); } } void Shader::setUniform(const std::string& _name, const Fbo* _fbo, unsigned int _texLoc){ if(isInUse()) { glActiveTexture(GL_TEXTURE0 + _texLoc); glBindTexture(GL_TEXTURE_2D, _fbo->getTextureId()); glUniform1i(getUniformLocation(_name), _texLoc); } } void Shader::setUniform(const std::string& _name, const glm::mat2& _value, bool _transpose){ if(isInUse()) { glUniformMatrix2fv(getUniformLocation(_name), 1, _transpose, &_value[0][0]); } } void Shader::setUniform(const std::string& _name, const glm::mat3& _value, bool _transpose){ if(isInUse()) { glUniformMatrix3fv(getUniformLocation(_name), 1, _transpose, &_value[0][0]); } } void Shader::setUniform(const std::string& _name, const glm::mat4& _value, bool _transpose){ if(isInUse()) { glUniformMatrix4fv(getUniformLocation(_name), 1, _transpose, &_value[0][0]); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gtest/gtest.h" #include "base/common.h" TEST(CheckTest, CheckTrueSucceedsTest) { CHECK(1); CHECK(42); } TEST(CheckTest, AssertionsAndChecksTest) { CHECK(2 + 2 == 4); // NOLINT ASSERT_TRUE(2 + 2 == 4); // NOLINT ASSERT_EQ(4, 2 + 2); ASSERT_LE(2 + 2, 5); printf("Passed all ASSERT macros, now EXPECT macros\n"); EXPECT_EQ(4, 2 + 2); printf("End of test\n"); } // C preprocessor magic, see // http://www.decompile.com/cpp/faq/file_and_line_error_string.htm #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define __FILE_LINE__ __FILE__ ":" TOSTRING(__LINE__) TEST(CheckTest, CheckFalseDeathTest) { ASSERT_DEATH(CHECK(0), "CHECK failed: .* at " __FILE_LINE__); } TEST(CheckTest, DCheckFalseDeathTest) { ASSERT_DEBUG_DEATH(DCHECK(0), "CHECK failed: .* at " __FILE_LINE__); } <commit_msg>Intentionally break the build<commit_after>// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gtest/gtest.h" #include "base/common.h" TEST(CheckTest, CheckTrueSucceedsTest) { CHECK(1); CHECK(42); } TEST(CheckTest, AssertionsAndChecksTest) { CHECK(2 + 2 == 4); // NOLINT ASSERT_TRUE(2 + 2 == 4); // NOLINT ASSERT_EQ(5, 2 + 2); ASSERT_LE(2 + 2, 5); printf("Passed all ASSERT macros, now EXPECT macros\n"); EXPECT_EQ(4, 2 + 2); printf("End of test\n"); } // C preprocessor magic, see // http://www.decompile.com/cpp/faq/file_and_line_error_string.htm #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define __FILE_LINE__ __FILE__ ":" TOSTRING(__LINE__) TEST(CheckTest, CheckFalseDeathTest) { ASSERT_DEATH(CHECK(0), "CHECK failed: .* at " __FILE_LINE__); } TEST(CheckTest, DCheckFalseDeathTest) { ASSERT_DEBUG_DEATH(DCHECK(0), "CHECK failed: .* at " __FILE_LINE__); } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Telmo Menezes. * [email protected] */ #include <stdlib.h> #include <stdio.h> #include <sstream> #include "gpnode.h" using namespace std; namespace syn { GPNode::GPNode(gpnode_type nodetype, gpnode_fun fun, gpval val, unsigned int var, GPNode* parent) { init(nodetype, fun, val, var, parent); } GPNode::~GPNode() { } void GPNode::init(gpnode_type nodetype, gpnode_fun fun, gpval val, unsigned int var, GPNode* parent) { this->type = nodetype; this->parent = parent; if (nodetype == FUN) { this->fun = fun; this->arity = fun_arity(fun); this->condpos = fun_condpos(fun); } else if (nodetype == VAR) { this->var = var; this->arity = 0; this->condpos = -1; } else { this->val = val; this->arity = 0; this->condpos = -1; } this->stoppos = this->arity; this->dyn_status = UNUSED; } void GPNode::clone(GPNode* node) { init(node->type, node->fun, node->val, node->var, node->parent); } int GPNode::fun_condpos(gpnode_fun fun) { switch(fun) { case ZER: return 1; case EQ: case GRT: case LRT: return 2; default: return -1; } } unsigned int GPNode::fun_arity(gpnode_fun fun) { switch(fun) { case EXP: case LOG: case SIN: case ABS: return 1; case SUM: case SUB: case MUL: case DIV: case MIN: case MAX: return 2; case ZER: return 3; case EQ: case GRT: case LRT: return 4; default: return 0; } } string GPNode::to_string() { if (this->type == VAL) { std::stringstream sstm; sstm << "" << this->val; return sstm.str(); } if (this->type == VAR) { std::stringstream sstm; sstm << "$" << this->val; return sstm.str(); } if (this->type != FUN) { return "???"; } switch(this->fun) { case SUM: return "+"; case SUB: return "-"; case MUL: return "*"; case DIV: return "/"; case ZER: return "ZER"; case EQ: return "=="; case GRT: return ">"; case LRT: return "<"; case EXP: return "EXP"; case LOG: return "LOG"; case SIN: return "SIN"; case ABS: return "ABS"; case MIN: return "MIN"; case MAX: return "MAX"; default: return "F??"; } } } <commit_msg>correcting bug with program output<commit_after>/* * Copyright (C) 2010 Telmo Menezes. * [email protected] */ #include <stdlib.h> #include <stdio.h> #include <sstream> #include "gpnode.h" using namespace std; namespace syn { GPNode::GPNode(gpnode_type nodetype, gpnode_fun fun, gpval val, unsigned int var, GPNode* parent) { init(nodetype, fun, val, var, parent); } GPNode::~GPNode() { } void GPNode::init(gpnode_type nodetype, gpnode_fun fun, gpval val, unsigned int var, GPNode* parent) { this->type = nodetype; this->parent = parent; if (nodetype == FUN) { this->fun = fun; this->arity = fun_arity(fun); this->condpos = fun_condpos(fun); } else if (nodetype == VAR) { this->var = var; this->arity = 0; this->condpos = -1; } else { this->val = val; this->arity = 0; this->condpos = -1; } this->stoppos = this->arity; this->dyn_status = UNUSED; } void GPNode::clone(GPNode* node) { init(node->type, node->fun, node->val, node->var, node->parent); } int GPNode::fun_condpos(gpnode_fun fun) { switch(fun) { case ZER: return 1; case EQ: case GRT: case LRT: return 2; default: return -1; } } unsigned int GPNode::fun_arity(gpnode_fun fun) { switch(fun) { case EXP: case LOG: case SIN: case ABS: return 1; case SUM: case SUB: case MUL: case DIV: case MIN: case MAX: return 2; case ZER: return 3; case EQ: case GRT: case LRT: return 4; default: return 0; } } string GPNode::to_string() { if (this->type == VAL) { std::stringstream sstm; sstm << "" << this->val; return sstm.str(); } if (this->type == VAR) { std::stringstream sstm; sstm << "$" << this->var; return sstm.str(); } if (this->type != FUN) { return "???"; } switch(this->fun) { case SUM: return "+"; case SUB: return "-"; case MUL: return "*"; case DIV: return "/"; case ZER: return "ZER"; case EQ: return "=="; case GRT: return ">"; case LRT: return "<"; case EXP: return "EXP"; case LOG: return "LOG"; case SIN: return "SIN"; case ABS: return "ABS"; case MIN: return "MIN"; case MAX: return "MAX"; default: return "F??"; } } } <|endoftext|>
<commit_before> #include "input.h" #include <QDebug> namespace NeovimQt { InputConv Input; InputConv::InputConv() { // see :h key-notation // special keys i.e. no textual representation specialKeys.insert(Qt::Key_Up, "Up"); specialKeys.insert(Qt::Key_Down, "Down"); specialKeys.insert(Qt::Key_Left, "Left"); specialKeys.insert(Qt::Key_Right, "Right"); specialKeys.insert(Qt::Key_F1, "F1"); specialKeys.insert(Qt::Key_F2, "F2"); specialKeys.insert(Qt::Key_F3, "F3"); specialKeys.insert(Qt::Key_F4, "F4"); specialKeys.insert(Qt::Key_F5, "F5"); specialKeys.insert(Qt::Key_F6, "F6"); specialKeys.insert(Qt::Key_F7, "F7"); specialKeys.insert(Qt::Key_F8, "F8"); specialKeys.insert(Qt::Key_F9, "F9"); specialKeys.insert(Qt::Key_F10, "F10"); specialKeys.insert(Qt::Key_F11, "F11"); specialKeys.insert(Qt::Key_F12, "F12"); specialKeys.insert(Qt::Key_Backspace, "BS"); specialKeys.insert(Qt::Key_Delete, "Del"); specialKeys.insert(Qt::Key_Insert, "Insert"); specialKeys.insert(Qt::Key_Home, "Home"); specialKeys.insert(Qt::Key_End, "End"); specialKeys.insert(Qt::Key_PageUp, "PageUp"); specialKeys.insert(Qt::Key_PageDown, "PageDown"); specialKeys.insert(Qt::Key_Return, "Enter"); specialKeys.insert(Qt::Key_Enter, "Enter"); specialKeys.insert(Qt::Key_Tab, "Tab"); specialKeys.insert(Qt::Key_Backtab, "Tab"); specialKeys.insert(Qt::Key_Escape, "Esc"); specialKeys.insert(Qt::Key_Backslash, "Bslash"); specialKeys.insert(Qt::Key_Space, "Space"); } /** * Return keyboard modifier prefix * * e.g. C-, A- or C-S-A- * * WIN32: Ctrl+Alt are never passed together, since we can't distinguish * between Ctrl+Alt and AltGr (see Vim/os_win32.c). */ QString InputConv::modPrefix(Qt::KeyboardModifiers mod) { QString modprefix; #if defined(Q_OS_MAC) || defined(Q_OS_UNIX) if ( mod & CmdModifier ) { modprefix += "D-"; // like MacVim does } #endif if ( mod & ControlModifier #ifdef Q_OS_WIN32 && !(mod & AltModifier) #endif ) { modprefix += "C-"; } if ( mod & ShiftModifier ) { modprefix += "S-"; } if ( mod & AltModifier #ifdef Q_OS_WIN32 && !(mod & ControlModifier) #endif ) { modprefix += "A-"; } if ( mod & Qt::KeypadModifier ) { modprefix += "k"; } return modprefix; } /** * Convert mouse event information into Neovim key notation * * @type is one of the Qt mouse event types * @pos is in Neovim Coordinates * @clickCount is the number of consecutive mouse clicks * 1 for a single click, 2 for a double click, up to 4. * This value is only used for LeftMouse events. * * see QMouseEvent * * If the event is not valid for Neovim, returns an empty string */ QString InputConv::convertMouse(Qt::MouseButton bt, QEvent::Type type, Qt::KeyboardModifiers mod, QPoint pos, short clickCount) { QString buttonName; switch(bt) { case Qt::LeftButton: // In practice Neovim only supports the clickcount for Left // mouse presses, even if our shell can support other buttons if (clickCount > 1 && clickCount <= 4) { buttonName = QString("%1-Left").arg(clickCount); } else { buttonName += "Left"; } break; case Qt::RightButton: buttonName += "Right"; break; case Qt::MidButton: buttonName += "Middle"; break; case Qt::NoButton: break; default: return ""; } QString evType; switch(type) { case QEvent::MouseButtonDblClick: // Treat this as a regular MouseButtonPress. Repeated // clicks are handled above. case QEvent::MouseButtonPress: evType += "Mouse"; break; case QEvent::MouseButtonRelease: evType += "Release"; break; case QEvent::MouseMove: evType += "Drag"; break; default: return ""; } QString inp = QString("<%1%2%3><%4,%5>").arg(modPrefix(mod)).arg(buttonName).arg(evType).arg(pos.x()).arg(pos.y()); return inp; } /** * Convert Qt key input into Neovim key-notation * * see QKeyEvent */ QString InputConv::convertKey(const QString& text, int k, Qt::KeyboardModifiers mod) { if (specialKeys.contains(k)) { return QString("<%1%2>").arg(modPrefix(mod)).arg(specialKeys.value(k)); } QChar c; // Escape < and backslash if (text == "<") { return QString("<lt>"); } else if (text == "\\") { return QString("<%1%2>").arg(modPrefix(mod)).arg("Bslash"); } else if (text.isEmpty()) { // on macs, text is empty for ctrl+key and cmd+key combos (with or without alt) if (mod & ControlModifier || mod & CmdModifier) { // ignore ctrl, alt and cmd key combos by themselves QList<Qt::Key> keys = { Key_Control, Key_Alt, Key_Cmd }; if (keys.contains((Qt::Key)k)) { return QString(); } else { // key code will be the value of the char (hopefully) c = QChar(k); } } else { // This is a special key we can't handle return QString(); } } else { // Key event compression is disabled, text has one char c = text.at(0); } // Remove SHIFT if (c.unicode() < 0x100 && !c.isLetterOrNumber() && c.isPrint()) { mod &= ~ShiftModifier; } // Remove CTRL empty characters at the start of the ASCII range if (c.unicode() < 0x20) { mod &= ~ControlModifier; } // Format with prefix if necessary QString prefix = modPrefix(mod); if (!prefix.isEmpty()) { return QString("<%1%2>").arg(prefix).arg(c); } return QString(c); } } // Namespace <commit_msg>Add explicit check for keypad keys<commit_after> #include "input.h" #include <QDebug> namespace NeovimQt { InputConv Input; InputConv::InputConv() { // see :h key-notation // special keys i.e. no textual representation specialKeys.insert(Qt::Key_Up, "Up"); specialKeys.insert(Qt::Key_Down, "Down"); specialKeys.insert(Qt::Key_Left, "Left"); specialKeys.insert(Qt::Key_Right, "Right"); specialKeys.insert(Qt::Key_F1, "F1"); specialKeys.insert(Qt::Key_F2, "F2"); specialKeys.insert(Qt::Key_F3, "F3"); specialKeys.insert(Qt::Key_F4, "F4"); specialKeys.insert(Qt::Key_F5, "F5"); specialKeys.insert(Qt::Key_F6, "F6"); specialKeys.insert(Qt::Key_F7, "F7"); specialKeys.insert(Qt::Key_F8, "F8"); specialKeys.insert(Qt::Key_F9, "F9"); specialKeys.insert(Qt::Key_F10, "F10"); specialKeys.insert(Qt::Key_F11, "F11"); specialKeys.insert(Qt::Key_F12, "F12"); specialKeys.insert(Qt::Key_Backspace, "BS"); specialKeys.insert(Qt::Key_Delete, "Del"); specialKeys.insert(Qt::Key_Insert, "Insert"); specialKeys.insert(Qt::Key_Home, "Home"); specialKeys.insert(Qt::Key_End, "End"); specialKeys.insert(Qt::Key_PageUp, "PageUp"); specialKeys.insert(Qt::Key_PageDown, "PageDown"); specialKeys.insert(Qt::Key_Return, "Enter"); specialKeys.insert(Qt::Key_Enter, "Enter"); specialKeys.insert(Qt::Key_Tab, "Tab"); specialKeys.insert(Qt::Key_Backtab, "Tab"); specialKeys.insert(Qt::Key_Escape, "Esc"); specialKeys.insert(Qt::Key_Backslash, "Bslash"); specialKeys.insert(Qt::Key_Space, "Space"); } /** * Return keyboard modifier prefix * * e.g. C-, A- or C-S-A- * * WIN32: Ctrl+Alt are never passed together, since we can't distinguish * between Ctrl+Alt and AltGr (see Vim/os_win32.c). */ QString InputConv::modPrefix(Qt::KeyboardModifiers mod) { QString modprefix; #if defined(Q_OS_MAC) || defined(Q_OS_UNIX) if ( mod & CmdModifier ) { modprefix += "D-"; // like MacVim does } #endif if ( mod & ControlModifier #ifdef Q_OS_WIN32 && !(mod & AltModifier) #endif ) { modprefix += "C-"; } if ( mod & ShiftModifier ) { modprefix += "S-"; } if ( mod & AltModifier #ifdef Q_OS_WIN32 && !(mod & ControlModifier) #endif ) { modprefix += "A-"; } return modprefix; } /** * Convert mouse event information into Neovim key notation * * @type is one of the Qt mouse event types * @pos is in Neovim Coordinates * @clickCount is the number of consecutive mouse clicks * 1 for a single click, 2 for a double click, up to 4. * This value is only used for LeftMouse events. * * see QMouseEvent * * If the event is not valid for Neovim, returns an empty string */ QString InputConv::convertMouse(Qt::MouseButton bt, QEvent::Type type, Qt::KeyboardModifiers mod, QPoint pos, short clickCount) { QString buttonName; switch(bt) { case Qt::LeftButton: // In practice Neovim only supports the clickcount for Left // mouse presses, even if our shell can support other buttons if (clickCount > 1 && clickCount <= 4) { buttonName = QString("%1-Left").arg(clickCount); } else { buttonName += "Left"; } break; case Qt::RightButton: buttonName += "Right"; break; case Qt::MidButton: buttonName += "Middle"; break; case Qt::NoButton: break; default: return ""; } QString evType; switch(type) { case QEvent::MouseButtonDblClick: // Treat this as a regular MouseButtonPress. Repeated // clicks are handled above. case QEvent::MouseButtonPress: evType += "Mouse"; break; case QEvent::MouseButtonRelease: evType += "Release"; break; case QEvent::MouseMove: evType += "Drag"; break; default: return ""; } QString inp = QString("<%1%2%3><%4,%5>").arg(modPrefix(mod)).arg(buttonName).arg(evType).arg(pos.x()).arg(pos.y()); return inp; } /** * Convert Qt key input into Neovim key-notation * * see QKeyEvent */ QString InputConv::convertKey(const QString& text, int k, Qt::KeyboardModifiers mod) { if ( mod & Qt::KeypadModifier ) { switch (k) { case Qt::Key_Home: return QString("<%1kHome>").arg(modPrefix(mod)); case Qt::Key_End: return QString("<%1kEnd>").arg(modPrefix(mod)); case Qt::Key_PageUp: return QString("<%1kPageUp>").arg(modPrefix(mod)); case Qt::Key_PageDown: return QString("<%1kPageDown>").arg(modPrefix(mod)); case Qt::Key_Plus: return QString("<%1kPlus>").arg(modPrefix(mod)); case Qt::Key_Minus: return QString("<%1kMinus>").arg(modPrefix(mod)); case Qt::Key_multiply: return QString("<%1kMultiply>").arg(modPrefix(mod)); case Qt::Key_division: return QString("<%1kDivide>").arg(modPrefix(mod)); case Qt::Key_Enter: return QString("<%1kEnter>").arg(modPrefix(mod)); case Qt::Key_Period: return QString("<%1kPoint>").arg(modPrefix(mod)); case Qt::Key_0: return QString("<%1k0>").arg(modPrefix(mod)); case Qt::Key_1: return QString("<%1k1>").arg(modPrefix(mod)); case Qt::Key_2: return QString("<%1k2>").arg(modPrefix(mod)); case Qt::Key_3: return QString("<%1k3>").arg(modPrefix(mod)); case Qt::Key_4: return QString("<%1k4>").arg(modPrefix(mod)); case Qt::Key_5: return QString("<%1k5>").arg(modPrefix(mod)); case Qt::Key_6: return QString("<%1k6>").arg(modPrefix(mod)); case Qt::Key_7: return QString("<%1k7>").arg(modPrefix(mod)); case Qt::Key_8: return QString("<%1k8>").arg(modPrefix(mod)); case Qt::Key_9: return QString("<%1k9>").arg(modPrefix(mod)); } } if (specialKeys.contains(k)) { return QString("<%1%2>").arg(modPrefix(mod)).arg(specialKeys.value(k)); } QChar c; // Escape < and backslash if (text == "<") { return QString("<lt>"); } else if (text == "\\") { return QString("<%1%2>").arg(modPrefix(mod)).arg("Bslash"); } else if (text.isEmpty()) { // on macs, text is empty for ctrl+key and cmd+key combos (with or without alt) if (mod & ControlModifier || mod & CmdModifier) { // ignore ctrl, alt and cmd key combos by themselves QList<Qt::Key> keys = { Key_Control, Key_Alt, Key_Cmd }; if (keys.contains((Qt::Key)k)) { return QString(); } else { // key code will be the value of the char (hopefully) c = QChar(k); } } else { // This is a special key we can't handle return QString(); } } else { // Key event compression is disabled, text has one char c = text.at(0); } // Remove SHIFT if (c.unicode() < 0x100 && !c.isLetterOrNumber() && c.isPrint()) { mod &= ~ShiftModifier; } // Remove CTRL empty characters at the start of the ASCII range if (c.unicode() < 0x20) { mod &= ~ControlModifier; } // Format with prefix if necessary QString prefix = modPrefix(mod); if (!prefix.isEmpty()) { return QString("<%1%2>").arg(prefix).arg(c); } return QString(c); } } // Namespace <|endoftext|>
<commit_before>// Maintains all the hands rooted at a given street and a given board. // For small games you can maintain all possible hands by rooting at the // preflop. For large games, you might create the HandTree for all hands // rooted at a particular flop board. #include <stdio.h> #include <stdlib.h> #include <vector> #include "board_tree.h" #include "canonical_cards.h" #include "cards.h" #include "game.h" #include "hand_tree.h" #include "hand_value_tree.h" using std::vector; HandTree::HandTree(int root_st, int root_bd, int final_st) { root_st_ = root_st; root_bd_ = root_bd; final_st_ = final_st; hands_ = new CanonicalCards **[final_st_ + 1]; for (int st = 0; st < root_st_; ++st) { hands_[st] = NULL; } BoardTree::Create(); int max_street = Game::MaxStreet(); // if (final_st == max_street) HandValueTree::Create(); // Used to lazily instantiate, but that doesn't currently work in // multi-threaded environment because HandValueTree::Create() is not // threadsafe. Fix that? May not be trivial. if (! HandValueTree::Created()) { fprintf(stderr, "Hand value tree has not been created\n"); exit(-1); } for (int st = root_st_; st <= final_st_; ++st) { int num_local_boards = BoardTree::NumLocalBoards(root_st_, root_bd_, st); int num_board_cards = Game::NumBoardCards(st); hands_[st] = new CanonicalCards *[num_local_boards]; for (int lbd = 0; lbd < num_local_boards; ++lbd) { int gbd = BoardTree::GlobalIndex(root_st_, root_bd_, st, lbd); const Card *board = BoardTree::Board(st, gbd); int sg = BoardTree::SuitGroups(st, gbd); hands_[st][lbd] = new CanonicalCards(2, board, num_board_cards, sg, false); if (st == max_street) { hands_[st][lbd]->SortByHandStrength(board); } } } } HandTree::~HandTree(void) { for (int st = root_st_; st <= final_st_; ++st) { int num_local_boards = BoardTree::NumLocalBoards(root_st_, root_bd_, st); for (int lbd = 0; lbd < num_local_boards; ++lbd) { delete hands_[st][lbd]; } delete [] hands_[st]; } delete [] hands_; } // Assumes hole cards are ordered int HCPIndex(int st, const Card *cards) { int num_hole_cards = Game::NumCardsForStreet(0); const Card *board = cards + num_hole_cards; int num_board_cards = Game::NumBoardCards(st); if (num_hole_cards == 1) { int c = cards[0]; int num_board_lower = 0; for (int i = 0; i < num_board_cards; ++i) { if ((int)board[i] < c) ++num_board_lower; } return c - num_board_lower; } else { Card hi = cards[0]; Card lo = cards[1]; int num_lower_lo = 0, num_lower_hi = 0; for (int i = 0; i < num_board_cards; ++i) { Card c = board[i]; if (c < lo) { ++num_lower_lo; ++num_lower_hi; } else if (c < hi) { ++num_lower_hi; } } int hi_index = hi - num_lower_hi; int lo_index = lo - num_lower_lo; // The sum from 1... hi_index - 1 is the number of hole card pairs // containing a high card less than hi. return (hi_index - 1) * hi_index / 2 + lo_index; } } // Assumes hole cards are ordered int HCPIndex(int st, const Card *board, const Card *hole_cards) { int num_hole_cards = Game::NumCardsForStreet(0); int num_board_cards = Game::NumBoardCards(st); if (num_hole_cards == 1) { int c = hole_cards[0]; int num_board_lower = 0; for (int i = 0; i < num_board_cards; ++i) { if ((int)board[i] < c) ++num_board_lower; } return c - num_board_lower; } else { Card hi = hole_cards[0]; Card lo = hole_cards[1]; int num_lower_lo = 0, num_lower_hi = 0; for (int i = 0; i < num_board_cards; ++i) { Card c = board[i]; if (c < lo) { ++num_lower_lo; ++num_lower_hi; } else if (c < hi) { ++num_lower_hi; } } int hi_index = hi - num_lower_hi; int lo_index = lo - num_lower_lo; // The sum from 1... hi_index - 1 is the number of hole card pairs // containing a high card less than hi. return (hi_index - 1) * hi_index / 2 + lo_index; } } <commit_msg>Stuff<commit_after>// Maintains all the hands rooted at a given street and a given board. // For small games you can maintain all possible hands by rooting at the // preflop. For large games, you might create the HandTree for all hands // rooted at a particular flop board. #include <stdio.h> #include <stdlib.h> #include <vector> #include "board_tree.h" #include "canonical_cards.h" #include "cards.h" #include "game.h" #include "hand_tree.h" #include "hand_value_tree.h" using std::vector; HandTree::HandTree(int root_st, int root_bd, int final_st) { root_st_ = root_st; root_bd_ = root_bd; final_st_ = final_st; hands_ = new CanonicalCards **[final_st_ + 1]; for (int st = 0; st < root_st_; ++st) { hands_[st] = NULL; } BoardTree::Create(); int max_street = Game::MaxStreet(); // if (final_st == max_street) HandValueTree::Create(); // Used to lazily instantiate, but that doesn't currently work in // multi-threaded environment because HandValueTree::Create() is not // threadsafe. Fix that? May not be trivial. if (final_st >= max_street && ! HandValueTree::Created()) { fprintf(stderr, "Hand value tree has not been created\n"); exit(-1); } for (int st = root_st_; st <= final_st_; ++st) { int num_local_boards = BoardTree::NumLocalBoards(root_st_, root_bd_, st); int num_board_cards = Game::NumBoardCards(st); hands_[st] = new CanonicalCards *[num_local_boards]; for (int lbd = 0; lbd < num_local_boards; ++lbd) { int gbd = BoardTree::GlobalIndex(root_st_, root_bd_, st, lbd); const Card *board = BoardTree::Board(st, gbd); int sg = BoardTree::SuitGroups(st, gbd); hands_[st][lbd] = new CanonicalCards(2, board, num_board_cards, sg, false); if (st == max_street) { hands_[st][lbd]->SortByHandStrength(board); } } } } HandTree::~HandTree(void) { for (int st = root_st_; st <= final_st_; ++st) { int num_local_boards = BoardTree::NumLocalBoards(root_st_, root_bd_, st); for (int lbd = 0; lbd < num_local_boards; ++lbd) { delete hands_[st][lbd]; } delete [] hands_[st]; } delete [] hands_; } // Assumes hole cards are ordered int HCPIndex(int st, const Card *cards) { int num_hole_cards = Game::NumCardsForStreet(0); const Card *board = cards + num_hole_cards; int num_board_cards = Game::NumBoardCards(st); if (num_hole_cards == 1) { int c = cards[0]; int num_board_lower = 0; for (int i = 0; i < num_board_cards; ++i) { if ((int)board[i] < c) ++num_board_lower; } return c - num_board_lower; } else { Card hi = cards[0]; Card lo = cards[1]; int num_lower_lo = 0, num_lower_hi = 0; for (int i = 0; i < num_board_cards; ++i) { Card c = board[i]; if (c < lo) { ++num_lower_lo; ++num_lower_hi; } else if (c < hi) { ++num_lower_hi; } } int hi_index = hi - num_lower_hi; int lo_index = lo - num_lower_lo; // The sum from 1... hi_index - 1 is the number of hole card pairs // containing a high card less than hi. return (hi_index - 1) * hi_index / 2 + lo_index; } } // Assumes hole cards are ordered int HCPIndex(int st, const Card *board, const Card *hole_cards) { int num_hole_cards = Game::NumCardsForStreet(0); int num_board_cards = Game::NumBoardCards(st); if (num_hole_cards == 1) { int c = hole_cards[0]; int num_board_lower = 0; for (int i = 0; i < num_board_cards; ++i) { if ((int)board[i] < c) ++num_board_lower; } return c - num_board_lower; } else { Card hi = hole_cards[0]; Card lo = hole_cards[1]; int num_lower_lo = 0, num_lower_hi = 0; for (int i = 0; i < num_board_cards; ++i) { Card c = board[i]; if (c < lo) { ++num_lower_lo; ++num_lower_hi; } else if (c < hi) { ++num_lower_hi; } } int hi_index = hi - num_lower_hi; int lo_index = lo - num_lower_lo; // The sum from 1... hi_index - 1 is the number of hole card pairs // containing a high card less than hi. return (hi_index - 1) * hi_index / 2 + lo_index; } } <|endoftext|>
<commit_before>/* * Utilities for reading a HTTP body, either request or response. * * author: Max Kellermann <[email protected]> */ #ifndef BENG_PROXY_HTTP_BODY_HXX #define BENG_PROXY_HTTP_BODY_HXX #include "istream/istream_dechunk.hxx" #include "istream/istream_oo.hxx" #include "istream/istream.hxx" #include <inline/compiler.h> #include <stddef.h> struct pool; struct FilteredSocket; class HttpBodyReader : public Istream, DechunkHandler { /** * The remaining size is unknown. */ static constexpr off_t REST_UNKNOWN = -1; /** * EOF chunk has been seen. */ static constexpr off_t REST_EOF_CHUNK = -2; /** * Chunked response. Will flip to #REST_EOF_CHUNK as soon * as the EOF chunk is seen. */ static constexpr off_t REST_CHUNKED = -3; /** * The remaining number of bytes. * * @see #REST_UNKNOWN, #REST_EOF_CHUNK, * #REST_CHUNKED */ off_t rest; bool end_seen; public: explicit HttpBodyReader(struct pool &_pool) :Istream(_pool) {} Istream &Init(off_t content_length, bool chunked); using Istream::GetPool; using Istream::Destroy; void InvokeEof() { assert(IsEOF()); /* suppress InvokeEof() if rest==REST_EOF_CHUNK because in that case, the dechunker has already emitted that event */ if (rest == 0) Istream::InvokeEof(); } void DestroyEof() { InvokeEof(); Destroy(); } using Istream::InvokeError; using Istream::DestroyError; bool IsChunked() const { return rest == REST_CHUNKED; } /** * Do we know the remaining length of the body? */ bool KnownLength() const { return rest >= 0; } bool IsEOF() const { return rest == 0 || rest == REST_EOF_CHUNK; } bool GotEndChunk() const { return rest == REST_EOF_CHUNK; } /** * Do we require more data to finish the body? */ bool RequireMore() const { return rest > 0 || (rest == REST_CHUNKED && !end_seen); } gcc_pure off_t GetAvailable(const FilteredSocket &s, bool partial) const; void FillBucketList(const FilteredSocket &s, IstreamBucketList &list); size_t ConsumeBucketList(FilteredSocket &s, size_t nbytes); size_t FeedBody(const void *data, size_t length); using Istream::CheckDirect; ssize_t TryDirect(int fd, FdType fd_type); /** * Determines whether the socket can be released now. This is true if * the body is empty, or if the data in the buffer contains enough for * the full response. */ gcc_pure bool IsSocketDone(const FilteredSocket &s) const; /** * The underlying socket has been closed by the remote. * * @return true if there is data left in the buffer, false if the body * has been finished (with or without error) */ bool SocketEOF(size_t remaining); private: gcc_pure size_t GetMaxRead(size_t length) const; void Consumed(size_t nbytes); /* virtual methods from class DechunkHandler */ void OnDechunkEndSeen() override; void OnDechunkEnd(Istream *input) override; }; #endif <commit_msg>http_body: allow overriding DechunkHandler methods<commit_after>/* * Utilities for reading a HTTP body, either request or response. * * author: Max Kellermann <[email protected]> */ #ifndef BENG_PROXY_HTTP_BODY_HXX #define BENG_PROXY_HTTP_BODY_HXX #include "istream/istream_dechunk.hxx" #include "istream/istream_oo.hxx" #include "istream/istream.hxx" #include <inline/compiler.h> #include <stddef.h> struct pool; struct FilteredSocket; class HttpBodyReader : public Istream, DechunkHandler { /** * The remaining size is unknown. */ static constexpr off_t REST_UNKNOWN = -1; /** * EOF chunk has been seen. */ static constexpr off_t REST_EOF_CHUNK = -2; /** * Chunked response. Will flip to #REST_EOF_CHUNK as soon * as the EOF chunk is seen. */ static constexpr off_t REST_CHUNKED = -3; /** * The remaining number of bytes. * * @see #REST_UNKNOWN, #REST_EOF_CHUNK, * #REST_CHUNKED */ off_t rest; bool end_seen; public: explicit HttpBodyReader(struct pool &_pool) :Istream(_pool) {} Istream &Init(off_t content_length, bool chunked); using Istream::GetPool; using Istream::Destroy; void InvokeEof() { assert(IsEOF()); /* suppress InvokeEof() if rest==REST_EOF_CHUNK because in that case, the dechunker has already emitted that event */ if (rest == 0) Istream::InvokeEof(); } void DestroyEof() { InvokeEof(); Destroy(); } using Istream::InvokeError; using Istream::DestroyError; bool IsChunked() const { return rest == REST_CHUNKED; } /** * Do we know the remaining length of the body? */ bool KnownLength() const { return rest >= 0; } bool IsEOF() const { return rest == 0 || rest == REST_EOF_CHUNK; } bool GotEndChunk() const { return rest == REST_EOF_CHUNK; } /** * Do we require more data to finish the body? */ bool RequireMore() const { return rest > 0 || (rest == REST_CHUNKED && !end_seen); } gcc_pure off_t GetAvailable(const FilteredSocket &s, bool partial) const; void FillBucketList(const FilteredSocket &s, IstreamBucketList &list); size_t ConsumeBucketList(FilteredSocket &s, size_t nbytes); size_t FeedBody(const void *data, size_t length); using Istream::CheckDirect; ssize_t TryDirect(int fd, FdType fd_type); /** * Determines whether the socket can be released now. This is true if * the body is empty, or if the data in the buffer contains enough for * the full response. */ gcc_pure bool IsSocketDone(const FilteredSocket &s) const; /** * The underlying socket has been closed by the remote. * * @return true if there is data left in the buffer, false if the body * has been finished (with or without error) */ bool SocketEOF(size_t remaining); private: gcc_pure size_t GetMaxRead(size_t length) const; void Consumed(size_t nbytes); protected: /* virtual methods from class DechunkHandler */ void OnDechunkEndSeen() override; void OnDechunkEnd(Istream *input) override; }; #endif <|endoftext|>
<commit_before>/* * int_matrix.h * Copyright 2014-2015 John Lawson * * 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 "int_matrix.h" #include <algorithm> #include <cstring> #include <functional> #include <sstream> /* * Cygwin std libc++ is broken and does not contain std::stoi. * There are some possible workarounds online involving modifying the lib * headers to remove the define guards preventing the function being declared. * However I could not get these to work, so instead specify a preprocessor * definition in the Makefile if running on Cygwin which enable the following * definition of std::stoi using the old fashioned strtol method. */ #ifdef CYGWIN_STOI #include <cstdlib> namespace std { int stoi(const std::string & s) { return (int)strtol(s.c_str(),nullptr,10); } } #endif namespace cluster { IntMatrix::IntMatrix() : num_rows_(0), num_cols_(0), data_(0), hashcode_(113) {} IntMatrix::IntMatrix(const int rows, const int cols) : num_rows_(rows), num_cols_(cols), data_(rows *cols, 0), hashcode_(113) {} IntMatrix::IntMatrix(const int rows, const int cols, const int values[]) : num_rows_(rows), num_cols_(cols), data_(rows *cols), hashcode_(0) { for (int i = 0; i < rows * cols; i++) { data_[i] = values[i]; } hashcode_=compute_hash(); } IntMatrix::IntMatrix(std::string str) { std::stringstream ss; ss << str; std::string buf; IntVector data; data.reserve((str.size()/2) -4); int row_size = 0; int col_size = 0; bool start = false; bool end = false; bool in_row = false; bool row_done = false; while(!end) { ss >> buf; if(!start) { if("{"==buf) { start = true; } continue; } if("{"==buf){ /* Started new row. */ in_row = true; } else if("}"==buf){ /* Reached end of row. */ if(!in_row) { /* End of matrix */ end = true; } else { row_done = true; in_row = false; ++col_size; } } else { /* Should be integer. */ if(!row_done) { ++row_size; } data.push_back(std::stoi(buf)); } } data.shrink_to_fit(); num_rows_ = row_size; num_cols_ = col_size; data_ = std::move(data); hashcode_ = compute_hash(); } /* Public methods */ const std::vector<int> IntMatrix::get_row(const int row) const { std::vector<int> result(num_cols_); get_row(row, result); return std::move(result); } void IntMatrix::get_row(const int row, std::vector<int>& result) const { int count = row * num_cols_; for (int j = 0; j < num_cols_; j++) { result[j] = data_[count++]; } } const std::vector<int> IntMatrix::get_col(const int col) const { std::vector<int> result(num_rows_); get_col(col, result); return std::move(result); } void IntMatrix::get_col(const int col, std::vector<int>& result) const{ int count = col; for (int j = 0; j < num_rows_; j++) { result[j] = data_[count]; count += num_cols_; } } void IntMatrix::set_matrix(const IntMatrix& mat) { if(mat.num_rows_ == num_rows_ && mat.num_cols_ == num_cols_) { /* Don't need to allocate a new array */ for(int i = 0; i < num_rows_ * num_cols_; i++) { data_[i] = mat.data_[i]; } } else { data_ = IntVector(mat.data_); num_rows_ = mat.num_rows_; num_cols_ = mat.num_cols_; } reset(); } int IntMatrix::zero_row() const { bool isZero = false; int row = -1; for (int ind = 0; ind < num_rows_ * num_cols_; ind++) { if (ind % num_cols_ == 0) { if (isZero) { return row; } row++; isZero = true; } if (data_[ind] != 0) { isZero = false; } } if (isZero) { return row; } return -1; } /* * Cannot check hashcode here, as implementing classes can change the way the * hashcode is computed. This means that two matrices with the same entries * can have different hashcodes if they are instances of different classes. */ bool IntMatrix::are_equal(const IntMatrix &lhs, const IntMatrix &rhs) { return lhs.data_ == rhs.data_; } void IntMatrix::submatrix(const int row, const int col, IntMatrix &result) const { int resInd = 0; int origInd = 0; while (resInd < result.num_rows_ * result.num_cols_) { bool changed; do { changed = false; if (origInd == row * num_cols_) { origInd += num_cols_; changed = true; } if (origInd % num_cols_ == col) { origInd++; changed = true; } } while (changed); result.data_[resInd++] = data_[origInd++]; } result.reset(); } void IntMatrix::submatrix(std::vector<int> rows, std::vector<int> cols, IntMatrix& result) const { using std::size_t; int row_ind = 0; int col_ind = 0; size_t rows_vec_ind = 0; size_t cols_vec_ind = 0; int this_index = 0; int result_index = 0; /* Sort the vectors and keep track of the current index to avoid searching * through the arrays continuously. */ std::sort(rows.begin(), rows.end()); std::sort(cols.begin(), cols.end()); while(row_ind < num_rows_) { if(rows_vec_ind < rows.size() && rows[rows_vec_ind] == row_ind) { rows_vec_ind++; col_ind = 0; cols_vec_ind = 0; while(col_ind < num_cols_) { if(cols_vec_ind < cols.size() && cols[cols_vec_ind] == col_ind) { cols_vec_ind++; result.data_[result_index++] = data_[this_index++]; } else { this_index++; } col_ind++; } } else { this_index += num_cols_; } row_ind++; } result.reset(); } void IntMatrix::enlarge_matrix(IntMatrix &result) const { int sub = 0; for (int index = 0; index < result.num_rows_ * result.num_cols_; index++) { if (index % result.num_cols_ >= num_cols_) { result.data_[index] = 0; sub++; } else if (index >= num_rows_ * result.num_cols_) { result.data_[index] = 0; } else { result.data_[index] = data_[index - sub]; } } result.reset(); } void IntMatrix::permute_rows(const std::vector<int>& vec, IntMatrix& result) const { int ind = 0; for(int i = 0; i < num_rows_; ++i) { int offset = vec[i] * num_cols_; std::memcpy(result.data_.data() + offset, data_.data() + ind, num_cols_ * sizeof(int)); ind += num_cols_; } result.reset(); } void IntMatrix::permute_columns(const std::vector<int>& vec, IntMatrix& result) const { int ind = -1; for(int i = 0; i < num_rows_; ++i) { int offset = i * num_cols_; for(int j = 0; j < num_cols_; ++j) { result.data_[offset + vec[j]] = data_[++ind]; } } result.reset(); } /* Private methods */ int IntMatrix::get_index(const int row, const int col) const { return row * num_cols_ + col; } std::size_t IntMatrix::compute_hash() const { std::size_t hash = 113; int_fast16_t max = num_rows_ * num_cols_; for (int_fast16_t i = 0; i < max; i++) { hash *= 31; hash += data_[i]; } return hash; } void IntMatrix::mult(const IntMatrix &left, const IntMatrix &right, IntMatrix &result) const { int col_inc = right.num_rows_; int leftInd; int leftIndStart = 0; int rightInd; int calcInd = 0; for (int i = 0; i < left.num_rows_; i++) { for (int j = 0; j < right.num_cols_; j++) { leftInd = leftIndStart; rightInd = j; result.data_[calcInd] = 0; while (leftInd < leftIndStart + left.num_cols_) { result.data_[calcInd] += left.data_[leftInd] * right.data_[rightInd]; leftInd++; rightInd += col_inc; } calcInd++; } leftIndStart += left.num_cols_; } result.reset(); } /* Friends */ std::ostream &operator<< (std::ostream &os, const IntMatrix &mat) { os << "{ "; for (int i = 0; i < mat.num_rows_; i++) { os << "{ "; for (int j = 0; j < mat.num_cols_; j++) { os << mat.data_[i * mat.num_cols_ + j] << " "; } os << "} "; } os << "}"; return os; } void swap(IntMatrix &first, IntMatrix &second) { using std::swap; swap(first.data_, second.data_); swap(first.num_rows_, second.num_rows_); swap(first.num_cols_, second.num_cols_); swap(first.hashcode_, second.hashcode_); } } <commit_msg>Changes some vector copies to memcpy<commit_after>/* * int_matrix.h * Copyright 2014-2015 John Lawson * * 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 "int_matrix.h" #include <algorithm> #include <cstring> #include <functional> #include <sstream> /* * Cygwin std libc++ is broken and does not contain std::stoi. * There are some possible workarounds online involving modifying the lib * headers to remove the define guards preventing the function being declared. * However I could not get these to work, so instead specify a preprocessor * definition in the Makefile if running on Cygwin which enable the following * definition of std::stoi using the old fashioned strtol method. */ #ifdef CYGWIN_STOI #include <cstdlib> namespace std { int stoi(const std::string & s) { return (int)strtol(s.c_str(),nullptr,10); } } #endif namespace cluster { IntMatrix::IntMatrix() : num_rows_(0), num_cols_(0), data_(0), hashcode_(113) {} IntMatrix::IntMatrix(const int rows, const int cols) : num_rows_(rows), num_cols_(cols), data_(rows *cols, 0), hashcode_(113) {} IntMatrix::IntMatrix(const int rows, const int cols, const int values[]) : num_rows_(rows), num_cols_(cols), data_(rows *cols), hashcode_(0) { std::memcpy(data_.data(), values, rows * cols * sizeof(int)); hashcode_=compute_hash(); } IntMatrix::IntMatrix(std::string str) { std::stringstream ss; ss << str; std::string buf; IntVector data; data.reserve((str.size()/2) -4); int row_size = 0; int col_size = 0; bool start = false; bool end = false; bool in_row = false; bool row_done = false; while(!end) { ss >> buf; if(!start) { if("{"==buf) { start = true; } continue; } if("{"==buf){ /* Started new row. */ in_row = true; } else if("}"==buf){ /* Reached end of row. */ if(!in_row) { /* End of matrix */ end = true; } else { row_done = true; in_row = false; ++col_size; } } else { /* Should be integer. */ if(!row_done) { ++row_size; } data.push_back(std::stoi(buf)); } } data.shrink_to_fit(); num_rows_ = row_size; num_cols_ = col_size; data_ = std::move(data); hashcode_ = compute_hash(); } /* Public methods */ const std::vector<int> IntMatrix::get_row(const int row) const { std::vector<int> result(num_cols_); get_row(row, result); return std::move(result); } void IntMatrix::get_row(const int row, std::vector<int>& result) const { int count = row * num_cols_; for (int j = 0; j < num_cols_; j++) { result[j] = data_[count++]; } } const std::vector<int> IntMatrix::get_col(const int col) const { std::vector<int> result(num_rows_); get_col(col, result); return std::move(result); } void IntMatrix::get_col(const int col, std::vector<int>& result) const{ int count = col; for (int j = 0; j < num_rows_; j++) { result[j] = data_[count]; count += num_cols_; } } void IntMatrix::set_matrix(const IntMatrix& mat) { if(mat.num_rows_ == num_rows_ && mat.num_cols_ == num_cols_) { /* Don't need to allocate a new array */ std::memcpy(data_.data(), mat.data_.data(), num_rows_ * num_cols_ * sizeof(int)); } else { data_ = IntVector(mat.data_); num_rows_ = mat.num_rows_; num_cols_ = mat.num_cols_; } reset(); } int IntMatrix::zero_row() const { bool isZero = false; int row = -1; for (int ind = 0; ind < num_rows_ * num_cols_; ind++) { if (ind % num_cols_ == 0) { if (isZero) { return row; } row++; isZero = true; } if (data_[ind] != 0) { isZero = false; } } if (isZero) { return row; } return -1; } /* * Cannot check hashcode here, as implementing classes can change the way the * hashcode is computed. This means that two matrices with the same entries * can have different hashcodes if they are instances of different classes. */ bool IntMatrix::are_equal(const IntMatrix &lhs, const IntMatrix &rhs) { return lhs.data_ == rhs.data_; } void IntMatrix::submatrix(const int row, const int col, IntMatrix &result) const { int resInd = 0; int origInd = 0; while (resInd < result.num_rows_ * result.num_cols_) { bool changed; do { changed = false; if (origInd == row * num_cols_) { origInd += num_cols_; changed = true; } if (origInd % num_cols_ == col) { origInd++; changed = true; } } while (changed); result.data_[resInd++] = data_[origInd++]; } result.reset(); } void IntMatrix::submatrix(std::vector<int> rows, std::vector<int> cols, IntMatrix& result) const { using std::size_t; int row_ind = 0; int col_ind = 0; size_t rows_vec_ind = 0; size_t cols_vec_ind = 0; int this_index = 0; int result_index = 0; /* Sort the vectors and keep track of the current index to avoid searching * through the arrays continuously. */ std::sort(rows.begin(), rows.end()); std::sort(cols.begin(), cols.end()); while(row_ind < num_rows_) { if(rows_vec_ind < rows.size() && rows[rows_vec_ind] == row_ind) { rows_vec_ind++; col_ind = 0; cols_vec_ind = 0; while(col_ind < num_cols_) { if(cols_vec_ind < cols.size() && cols[cols_vec_ind] == col_ind) { cols_vec_ind++; result.data_[result_index++] = data_[this_index++]; } else { this_index++; } col_ind++; } } else { this_index += num_cols_; } row_ind++; } result.reset(); } void IntMatrix::enlarge_matrix(IntMatrix &result) const { int sub = 0; for (int index = 0; index < result.num_rows_ * result.num_cols_; index++) { if (index % result.num_cols_ >= num_cols_) { result.data_[index] = 0; sub++; } else if (index >= num_rows_ * result.num_cols_) { result.data_[index] = 0; } else { result.data_[index] = data_[index - sub]; } } result.reset(); } void IntMatrix::permute_rows(const std::vector<int>& vec, IntMatrix& result) const { int ind = 0; for(int i = 0; i < num_rows_; ++i) { int offset = vec[i] * num_cols_; std::memcpy(result.data_.data() + offset, data_.data() + ind, num_cols_ * sizeof(int)); ind += num_cols_; } result.reset(); } void IntMatrix::permute_columns(const std::vector<int>& vec, IntMatrix& result) const { int ind = -1; for(int i = 0; i < num_rows_; ++i) { int offset = i * num_cols_; for(int j = 0; j < num_cols_; ++j) { result.data_[offset + vec[j]] = data_[++ind]; } } result.reset(); } /* Private methods */ int IntMatrix::get_index(const int row, const int col) const { return row * num_cols_ + col; } std::size_t IntMatrix::compute_hash() const { std::size_t hash = 113; int_fast16_t max = num_rows_ * num_cols_; for (int_fast16_t i = 0; i < max; i++) { hash *= 31; hash += data_[i]; } return hash; } void IntMatrix::mult(const IntMatrix &left, const IntMatrix &right, IntMatrix &result) const { int col_inc = right.num_rows_; int leftInd; int leftIndStart = 0; int rightInd; int calcInd = 0; for (int i = 0; i < left.num_rows_; i++) { for (int j = 0; j < right.num_cols_; j++) { leftInd = leftIndStart; rightInd = j; result.data_[calcInd] = 0; while (leftInd < leftIndStart + left.num_cols_) { result.data_[calcInd] += left.data_[leftInd] * right.data_[rightInd]; leftInd++; rightInd += col_inc; } calcInd++; } leftIndStart += left.num_cols_; } result.reset(); } /* Friends */ std::ostream &operator<< (std::ostream &os, const IntMatrix &mat) { os << "{ "; for (int i = 0; i < mat.num_rows_; i++) { os << "{ "; for (int j = 0; j < mat.num_cols_; j++) { os << mat.data_[i * mat.num_cols_ + j] << " "; } os << "} "; } os << "}"; return os; } void swap(IntMatrix &first, IntMatrix &second) { using std::swap; swap(first.data_, second.data_); swap(first.num_rows_, second.num_rows_); swap(first.num_cols_, second.num_cols_); swap(first.hashcode_, second.hashcode_); } } <|endoftext|>
<commit_before>/* This file is part of the E_Rendering library. Copyright (C) 2009-2012 Benjamin Eikel <[email protected]> Copyright (C) 2009-2012 Claudius Jähn <[email protected]> Copyright (C) 2009-2012 Ralf Petring <[email protected]> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "E_Shader.h" #include <Util/IO/FileName.h> #include <Util/Macros.h> #include "../E_RenderingContext.h" #include "E_Uniform.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> using namespace Rendering; using namespace EScript; namespace E_Rendering { //! (static) EScript::Type * E_Shader::getTypeObject() { // E_Shader ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! initMembers void E_Shader::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); declareConstant(&lib,getClassName(),typeObject); declareConstant(typeObject, "USE_GL", Number::create(Shader::USE_GL)); declareConstant(typeObject, "USE_UNIFORMS", Number::create(Shader::USE_UNIFORMS)); declareConstant(&lib, "SHADER_STAGE_VERTEX", Number::create(ShaderObjectInfo::SHADER_STAGE_VERTEX)); declareConstant(&lib, "SHADER_STAGE_FRAGMENT", Number::create(ShaderObjectInfo::SHADER_STAGE_FRAGMENT)); declareConstant(&lib, "SHADER_STAGE_GEOMETRY", Number::create(ShaderObjectInfo::SHADER_STAGE_GEOMETRY)); declareConstant(&lib, "SHADER_STAGE_TESS_CONTROL", Number::create(ShaderObjectInfo::SHADER_STAGE_TESS_CONTROL)); declareConstant(&lib, "SHADER_STAGE_TESS_EVALUATION", Number::create(ShaderObjectInfo::SHADER_STAGE_TESS_EVALUATION)); declareConstant(&lib, "SHADER_STAGE_COMPUTE", Number::create(ShaderObjectInfo::SHADER_STAGE_COMPUTE)); //! [ESF] (static) Shader Shader.loadShader(string vsFile, string fsFile, flag usage) ES_FUNCTION(typeObject,"loadShader",2,3,{ const Util::FileName vsFile(parameter[0].toString()); const Util::FileName fsFile(parameter[1].toString()); const Shader::flag_t flag = parameter[2].toInt(Shader::USE_GL | Shader::USE_UNIFORMS); Shader * s=Shader::loadShader(vsFile, fsFile, flag); if(s) return new E_Shader(s); else return EScript::create(nullptr); }) //! [ESF] (static) Shader Shader.createShader( [usage] | string vs, string fs[, flag usage]) ES_FUNCTION(typeObject,"createShader",0,3,{ if(parameter.size()>1){ return EScript::create( Shader::createShader(parameter[0].toString().c_str(), parameter[1].toString().c_str(), parameter[2].to<uint32_t>(rt,Shader::USE_GL | Shader::USE_UNIFORMS))); }else{ return EScript::create( Shader::createShader(parameter[0].to<uint32_t>(rt,Shader::USE_GL | Shader::USE_UNIFORMS))); } }) // ------------- //! [ESF] thisEObj Shader.attachFS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachFS",1,2, { auto info = Rendering::ShaderObjectInfo::createFragment(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachFSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachFSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadFragment(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachGS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachGS",1,2, { auto info = Rendering::ShaderObjectInfo::createGeometry(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachGSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachGSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadGeometry(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachVS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachVS",1,2, { auto info = Rendering::ShaderObjectInfo::createVertex(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachVSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachVSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadVertex(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachCS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachCS",1,2, { auto info = Rendering::ShaderObjectInfo::createCompute(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachCSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachCSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadCompute(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESMF] thisEObj Shader.defineVertexAttribute(name,index) ES_MFUN(typeObject,Shader,"defineVertexAttribute",2,2, (thisObj->defineVertexAttribute( parameter[0].toString() , parameter[1].to<uint32_t>(rt)),thisEObj)) //! [ESF] Unfiform* Shader Shader.getActiveUniforms() ES_MFUNCTION(typeObject,Shader, "getActiveUniforms", 0, 0, { std::vector<Uniform> u; thisObj->getActiveUniforms(u); Array * a = Array::create(); for(const auto & uniform : u) { a->pushBack(EScript::create(uniform)); } return a; }) //! [ESMF] Uniform|Void Shader.getUniform( Name ) ES_MFUNCTION(typeObject,Shader,"getUniform",1,1,{ const Uniform & u = thisObj->getUniform(parameter[0].toString()); if(u.isNull()) return EScript::create(nullptr); return EScript::create(u); }) //! [ESF] Bool Shader.isInvalid() ES_MFUN(typeObject,Shader,"isInvalid",0,0, thisObj->getStatus()==Shader::INVALID); //! [ESMF] thisEObj Shader.setUniform( RenderingContext rc,Uniform ,bool warnIfUnused = true, bool forced = false ) ES_MFUN(typeObject,Shader,"setUniform",2,4, (thisObj->setUniform(parameter[0].to<RenderingContext&>(rt), parameter[1].to<const Rendering::Uniform&>(rt), parameter[2].toBool(true),parameter[3].toBool(false)),thisEObj)) //! [ESMF] Number|false Shader.getSubroutineIndex( Number stage, String name ) ES_MFUNCTION(typeObject,Shader,"getSubroutineIndex",2,2,{ auto index = thisObj->getSubroutineIndex(parameter[0].toUInt(), parameter[1].toString()); if(index < 0) return EScript::create(false); return EScript::create(index); }) } } <commit_msg>bindings for Shader.isActive<commit_after>/* This file is part of the E_Rendering library. Copyright (C) 2009-2012 Benjamin Eikel <[email protected]> Copyright (C) 2009-2012 Claudius Jähn <[email protected]> Copyright (C) 2009-2012 Ralf Petring <[email protected]> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "E_Shader.h" #include <Util/IO/FileName.h> #include <Util/Macros.h> #include "../E_RenderingContext.h" #include "E_Uniform.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> using namespace Rendering; using namespace EScript; namespace E_Rendering { //! (static) EScript::Type * E_Shader::getTypeObject() { // E_Shader ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! initMembers void E_Shader::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); declareConstant(&lib,getClassName(),typeObject); declareConstant(typeObject, "USE_GL", Number::create(Shader::USE_GL)); declareConstant(typeObject, "USE_UNIFORMS", Number::create(Shader::USE_UNIFORMS)); declareConstant(&lib, "SHADER_STAGE_VERTEX", Number::create(ShaderObjectInfo::SHADER_STAGE_VERTEX)); declareConstant(&lib, "SHADER_STAGE_FRAGMENT", Number::create(ShaderObjectInfo::SHADER_STAGE_FRAGMENT)); declareConstant(&lib, "SHADER_STAGE_GEOMETRY", Number::create(ShaderObjectInfo::SHADER_STAGE_GEOMETRY)); declareConstant(&lib, "SHADER_STAGE_TESS_CONTROL", Number::create(ShaderObjectInfo::SHADER_STAGE_TESS_CONTROL)); declareConstant(&lib, "SHADER_STAGE_TESS_EVALUATION", Number::create(ShaderObjectInfo::SHADER_STAGE_TESS_EVALUATION)); declareConstant(&lib, "SHADER_STAGE_COMPUTE", Number::create(ShaderObjectInfo::SHADER_STAGE_COMPUTE)); //! [ESF] (static) Shader Shader.loadShader(string vsFile, string fsFile, flag usage) ES_FUNCTION(typeObject,"loadShader",2,3,{ const Util::FileName vsFile(parameter[0].toString()); const Util::FileName fsFile(parameter[1].toString()); const Shader::flag_t flag = parameter[2].toInt(Shader::USE_GL | Shader::USE_UNIFORMS); Shader * s=Shader::loadShader(vsFile, fsFile, flag); if(s) return new E_Shader(s); else return EScript::create(nullptr); }) //! [ESF] (static) Shader Shader.createShader( [usage] | string vs, string fs[, flag usage]) ES_FUNCTION(typeObject,"createShader",0,3,{ if(parameter.size()>1){ return EScript::create( Shader::createShader(parameter[0].toString().c_str(), parameter[1].toString().c_str(), parameter[2].to<uint32_t>(rt,Shader::USE_GL | Shader::USE_UNIFORMS))); }else{ return EScript::create( Shader::createShader(parameter[0].to<uint32_t>(rt,Shader::USE_GL | Shader::USE_UNIFORMS))); } }) // ------------- //! [ESF] thisEObj Shader.attachFS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachFS",1,2, { auto info = Rendering::ShaderObjectInfo::createFragment(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachFSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachFSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadFragment(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachGS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachGS",1,2, { auto info = Rendering::ShaderObjectInfo::createGeometry(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachGSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachGSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadGeometry(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachVS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachVS",1,2, { auto info = Rendering::ShaderObjectInfo::createVertex(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachVSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachVSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadVertex(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachCS(string code[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachCS",1,2, { auto info = Rendering::ShaderObjectInfo::createCompute(parameter[0].toString()); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESF] thisEObj Shader.attachCSFile(string file[, Map defines]) ES_MFUNCTION(typeObject,Shader,"attachCSFile",1,2, { auto info = Rendering::ShaderObjectInfo::loadCompute(Util::FileName(parameter[0].toString())); if(parameter.size()>1){ auto* m = parameter[1].toType<EScript::Map>(); for(auto it=m->begin(); it != m->end(); ++it) { info.addDefine(it->second.key.toString(), it->second.value.toString()); } } thisObj->attachShaderObject(std::move(info)); return thisEObj; }) //! [ESMF] thisEObj Shader.defineVertexAttribute(name,index) ES_MFUN(typeObject,Shader,"defineVertexAttribute",2,2, (thisObj->defineVertexAttribute( parameter[0].toString() , parameter[1].to<uint32_t>(rt)),thisEObj)) //! [ESF] Unfiform* Shader Shader.getActiveUniforms() ES_MFUNCTION(typeObject,Shader, "getActiveUniforms", 0, 0, { std::vector<Uniform> u; thisObj->getActiveUniforms(u); Array * a = Array::create(); for(const auto & uniform : u) { a->pushBack(EScript::create(uniform)); } return a; }) //! [ESMF] Uniform|Void Shader.getUniform( Name ) ES_MFUNCTION(typeObject,Shader,"getUniform",1,1,{ const Uniform & u = thisObj->getUniform(parameter[0].toString()); if(u.isNull()) return EScript::create(nullptr); return EScript::create(u); }) //! [ESF] Bool Shader.isInvalid() ES_MFUN(typeObject,Shader,"isInvalid",0,0, thisObj->getStatus()==Shader::INVALID); //! [ESF] Bool Shader.isActive(RenderingContext rc) ES_MFUN(typeObject,Shader,"isActive",1,1, thisObj->isActive(parameter[0].to<RenderingContext&>(rt))); //! [ESMF] thisEObj Shader.setUniform( RenderingContext rc,Uniform ,bool warnIfUnused = true, bool forced = false ) ES_MFUN(typeObject,Shader,"setUniform",2,4, (thisObj->setUniform(parameter[0].to<RenderingContext&>(rt), parameter[1].to<const Rendering::Uniform&>(rt), parameter[2].toBool(true),parameter[3].toBool(false)),thisEObj)) //! [ESMF] Number|false Shader.getSubroutineIndex( Number stage, String name ) ES_MFUNCTION(typeObject,Shader,"getSubroutineIndex",2,2,{ auto index = thisObj->getSubroutineIndex(parameter[0].toUInt(), parameter[1].toString()); if(index < 0) return EScript::create(false); return EScript::create(index); }) } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/camera/lib/obstacle/postprocessor/location_refiner/location_refiner_obstacle_postprocessor.h" // NOLINT #include <assert.h> #include <algorithm> #include "cyber/common/log.h" #include "modules/common/util/file.h" #include "modules/perception/camera/common/global_config.h" #include "modules/perception/camera/lib/interface/base_calibration_service.h" // TODO(Xun): code completion namespace apollo { namespace perception { namespace camera { bool LocationRefinerObstaclePostprocessor::Init( const ObstaclePostprocessorInitOptions &options) { std::string postprocessor_config = apollo::common::util::GetAbsolutePath( options.root_dir, options.conf_file); if (!apollo::common::util::GetProtoFromFile(postprocessor_config, &location_refiner_param_)) { AERROR << "Read config failed: " << postprocessor_config; return false; } AINFO << "Load postprocessor parameters from " << postprocessor_config << " \nmin_dist_to_camera: " << location_refiner_param_.min_dist_to_camera() << " \nroi_h2bottom_scale: " << location_refiner_param_.roi_h2bottom_scale(); return true; } bool LocationRefinerObstaclePostprocessor::Process( const ObstaclePostprocessorOptions &options, CameraFrame *frame) { if (frame->detected_objects.empty() || frame->calibration_service == nullptr || !options.do_refinement_with_calibration_service) { ADEBUG << "Do not run obstacle postprocessor."; return true; } Eigen::Vector4d plane; if (options.do_refinement_with_calibration_service == true && !frame->calibration_service->QueryGroundPlaneInCameraFrame(&plane) ) { AINFO << "No valid ground plane in the service."; return false; } float query_plane[4] = {static_cast<float>(plane(0)), static_cast<float>(plane(1)), static_cast<float>(plane(2)), static_cast<float>(plane(3))}; const auto &camera_k_matrix = frame->camera_k_matrix; float k_mat[9] = {0}; for (size_t i = 0; i < 3; i++) { size_t i3 = i * 3; for (size_t j = 0; j < 3; j++) { k_mat[i3 + j] = camera_k_matrix(i, j); } } AINFO << "Camera k matrix input to obstacle postprocessor: \n" << k_mat[0] << ", " << k_mat[1] << ", " << k_mat[2] << "\n" << k_mat[3] << ", " << k_mat[4] << ", " << k_mat[5] << "\n" << k_mat[6] << ", " << k_mat[7] << ", " << k_mat[8] << "\n"; const int width_image = frame->data_provider->src_width(); const int height_image = frame->data_provider->src_height(); postprocessor_->Init(k_mat, width_image, height_image); ObjPostProcessorOptions obj_postprocessor_options; int nr_valid_obj = 0; for (auto &obj : frame->detected_objects) { ++nr_valid_obj; float object_center[3] = {obj->camera_supplement.local_center(0), obj->camera_supplement.local_center(1), obj->camera_supplement.local_center(2)}; float bbox2d[4] = { obj->camera_supplement.box.xmin, obj->camera_supplement.box.ymin, obj->camera_supplement.box.xmax, obj->camera_supplement.box.ymax}; float bottom_center[2] = {(bbox2d[0] + bbox2d[2]) / 2, bbox2d[3]}; float h_down = (static_cast<float>(height_image) - k_mat[5]) * location_refiner_param_.roi_h2bottom_scale(); bool is_in_rule_roi = is_in_roi(bottom_center, static_cast<float>(width_image), static_cast<float>(height_image), k_mat[5], h_down); float dist2camera = common::ISqrt( common::ISqr(object_center[0]) + common::ISqr(object_center[2])); if (dist2camera > location_refiner_param_.min_dist_to_camera() || !is_in_rule_roi) { ADEBUG << "Pass for obstacle postprocessor."; continue; } float dimension_hwl[3] = {obj->size(2), obj->size(1), obj->size(0)}; float box_cent_x = (bbox2d[0] + bbox2d[2]) / 2; Eigen::Vector3f image_point_low_center(box_cent_x, bbox2d[3], 1); Eigen::Vector3f point_in_camera = static_cast<Eigen::Matrix<float, 3, 1, 0, 3, 1>> (camera_k_matrix.inverse() * image_point_low_center); float theta_ray = static_cast<float>(atan2(point_in_camera.x(), point_in_camera.z())); float rotation_y = theta_ray + static_cast<float>(obj->camera_supplement.alpha); // enforce the ry to be in the range [-pi, pi) const float PI = common::Constant<float>::PI(); if (rotation_y < -PI) { rotation_y += 2 * PI; } else if (rotation_y >= PI) { rotation_y -= 2 * PI; } // process memcpy(obj_postprocessor_options.bbox, bbox2d, sizeof(float) * 4); obj_postprocessor_options.check_lowerbound = true; camera::LineSegment2D<float> line_seg(bbox2d[0], bbox2d[3], bbox2d[2], bbox2d[3]); obj_postprocessor_options.line_segs.push_back(line_seg); memcpy(obj_postprocessor_options.hwl, dimension_hwl, sizeof(float) * 3); obj_postprocessor_options.ry = rotation_y; // refine with calibration service, support ground plane model currently // {0.0f, cos(tilt), -sin(tilt), -camera_ground_height} memcpy(obj_postprocessor_options.plane, query_plane, sizeof(float) * 4); // changed to touching-ground center object_center[1] += dimension_hwl[0] / 2; postprocessor_->PostProcessObjWithGround(obj_postprocessor_options, object_center, dimension_hwl, &rotation_y); object_center[1] -= dimension_hwl[0] / 2; float z_diff_camera = object_center[2] - obj->camera_supplement.local_center(2); // fill back results obj->camera_supplement.local_center(0) = object_center[0]; obj->camera_supplement.local_center(1) = object_center[1]; obj->camera_supplement.local_center(2) = object_center[2]; obj->center(0) = static_cast<double>(object_center[0]); obj->center(1) = static_cast<double>(object_center[1]); obj->center(2) = static_cast<double>(object_center[2]); obj->center = frame->camera2world_pose * obj->center; AINFO << "diff on camera z: " << z_diff_camera; AINFO << "Obj center from postprocessor: " << obj->center.transpose(); } return true; } std::string LocationRefinerObstaclePostprocessor::Name() const { return "LocationRefinerObstaclePostprocessor"; } // Register plugin. REGISTER_OBSTACLE_POSTPROCESSOR(LocationRefinerObstaclePostprocessor); } // namespace camera } // namespace perception } // namespace apollo <commit_msg>Perception: Fixed Camera object module crash<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/camera/lib/obstacle/postprocessor/location_refiner/location_refiner_obstacle_postprocessor.h" // NOLINT #include <assert.h> #include <algorithm> #include "cyber/common/log.h" #include "modules/common/util/file.h" #include "modules/perception/camera/common/global_config.h" #include "modules/perception/camera/lib/interface/base_calibration_service.h" // TODO(Xun): code completion namespace apollo { namespace perception { namespace camera { bool LocationRefinerObstaclePostprocessor::Init( const ObstaclePostprocessorInitOptions &options) { std::string postprocessor_config = apollo::common::util::GetAbsolutePath( options.root_dir, options.conf_file); if (!apollo::common::util::GetProtoFromFile(postprocessor_config, &location_refiner_param_)) { AERROR << "Read config failed: " << postprocessor_config; return false; } AINFO << "Load postprocessor parameters from " << postprocessor_config << " \nmin_dist_to_camera: " << location_refiner_param_.min_dist_to_camera() << " \nroi_h2bottom_scale: " << location_refiner_param_.roi_h2bottom_scale(); return true; } bool LocationRefinerObstaclePostprocessor::Process( const ObstaclePostprocessorOptions &options, CameraFrame *frame) { if (frame->detected_objects.empty() || frame->calibration_service == nullptr || !options.do_refinement_with_calibration_service) { ADEBUG << "Do not run obstacle postprocessor."; return true; } Eigen::Vector4d plane; if (options.do_refinement_with_calibration_service == true && !frame->calibration_service->QueryGroundPlaneInCameraFrame(&plane) ) { AINFO << "No valid ground plane in the service."; } float query_plane[4] = {static_cast<float>(plane(0)), static_cast<float>(plane(1)), static_cast<float>(plane(2)), static_cast<float>(plane(3))}; const auto &camera_k_matrix = frame->camera_k_matrix; float k_mat[9] = {0}; for (size_t i = 0; i < 3; i++) { size_t i3 = i * 3; for (size_t j = 0; j < 3; j++) { k_mat[i3 + j] = camera_k_matrix(i, j); } } AINFO << "Camera k matrix input to obstacle postprocessor: \n" << k_mat[0] << ", " << k_mat[1] << ", " << k_mat[2] << "\n" << k_mat[3] << ", " << k_mat[4] << ", " << k_mat[5] << "\n" << k_mat[6] << ", " << k_mat[7] << ", " << k_mat[8] << "\n"; const int width_image = frame->data_provider->src_width(); const int height_image = frame->data_provider->src_height(); postprocessor_->Init(k_mat, width_image, height_image); ObjPostProcessorOptions obj_postprocessor_options; int nr_valid_obj = 0; for (auto &obj : frame->detected_objects) { ++nr_valid_obj; float object_center[3] = {obj->camera_supplement.local_center(0), obj->camera_supplement.local_center(1), obj->camera_supplement.local_center(2)}; float bbox2d[4] = { obj->camera_supplement.box.xmin, obj->camera_supplement.box.ymin, obj->camera_supplement.box.xmax, obj->camera_supplement.box.ymax}; float bottom_center[2] = {(bbox2d[0] + bbox2d[2]) / 2, bbox2d[3]}; float h_down = (static_cast<float>(height_image) - k_mat[5]) * location_refiner_param_.roi_h2bottom_scale(); bool is_in_rule_roi = is_in_roi(bottom_center, static_cast<float>(width_image), static_cast<float>(height_image), k_mat[5], h_down); float dist2camera = common::ISqrt( common::ISqr(object_center[0]) + common::ISqr(object_center[2])); if (dist2camera > location_refiner_param_.min_dist_to_camera() || !is_in_rule_roi) { ADEBUG << "Pass for obstacle postprocessor."; continue; } float dimension_hwl[3] = {obj->size(2), obj->size(1), obj->size(0)}; float box_cent_x = (bbox2d[0] + bbox2d[2]) / 2; Eigen::Vector3f image_point_low_center(box_cent_x, bbox2d[3], 1); Eigen::Vector3f point_in_camera = static_cast<Eigen::Matrix<float, 3, 1, 0, 3, 1>> (camera_k_matrix.inverse() * image_point_low_center); float theta_ray = static_cast<float>(atan2(point_in_camera.x(), point_in_camera.z())); float rotation_y = theta_ray + static_cast<float>(obj->camera_supplement.alpha); // enforce the ry to be in the range [-pi, pi) const float PI = common::Constant<float>::PI(); if (rotation_y < -PI) { rotation_y += 2 * PI; } else if (rotation_y >= PI) { rotation_y -= 2 * PI; } // process memcpy(obj_postprocessor_options.bbox, bbox2d, sizeof(float) * 4); obj_postprocessor_options.check_lowerbound = true; camera::LineSegment2D<float> line_seg(bbox2d[0], bbox2d[3], bbox2d[2], bbox2d[3]); obj_postprocessor_options.line_segs.push_back(line_seg); memcpy(obj_postprocessor_options.hwl, dimension_hwl, sizeof(float) * 3); obj_postprocessor_options.ry = rotation_y; // refine with calibration service, support ground plane model currently // {0.0f, cos(tilt), -sin(tilt), -camera_ground_height} memcpy(obj_postprocessor_options.plane, query_plane, sizeof(float) * 4); // changed to touching-ground center object_center[1] += dimension_hwl[0] / 2; postprocessor_->PostProcessObjWithGround(obj_postprocessor_options, object_center, dimension_hwl, &rotation_y); object_center[1] -= dimension_hwl[0] / 2; float z_diff_camera = object_center[2] - obj->camera_supplement.local_center(2); // fill back results obj->camera_supplement.local_center(0) = object_center[0]; obj->camera_supplement.local_center(1) = object_center[1]; obj->camera_supplement.local_center(2) = object_center[2]; obj->center(0) = static_cast<double>(object_center[0]); obj->center(1) = static_cast<double>(object_center[1]); obj->center(2) = static_cast<double>(object_center[2]); obj->center = frame->camera2world_pose * obj->center; AINFO << "diff on camera z: " << z_diff_camera; AINFO << "Obj center from postprocessor: " << obj->center.transpose(); } return true; } std::string LocationRefinerObstaclePostprocessor::Name() const { return "LocationRefinerObstaclePostprocessor"; } // Register plugin. REGISTER_OBSTACLE_POSTPROCESSOR(LocationRefinerObstaclePostprocessor); } // namespace camera } // namespace perception } // namespace apollo <|endoftext|>
<commit_before>#include <LightGBM/config.h> #include <LightGBM/utils/common.h> #include <LightGBM/utils/log.h> #include <vector> #include <string> #include <unordered_map> #include <algorithm> namespace LightGBM { void OverallConfig::Set(const std::unordered_map<std::string, std::string>& params) { // load main config types GetInt(params, "num_threads", &num_threads); GetTaskType(params); GetBoostingType(params); GetObjectiveType(params); GetMetricType(params); // construct boosting configs if (boosting_type == BoostingType::kGBDT) { boosting_config = new GBDTConfig(); } // sub-config setup network_config.Set(params); io_config.Set(params); boosting_config->Set(params); objective_config.Set(params); metric_config.Set(params); // check for conflicts CheckParamConflict(); if (io_config.verbosity == 1) { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Info); } else if (io_config.verbosity == 0) { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Error); } else if (io_config.verbosity >= 2) { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Debug); } else { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Fatal); } } void OverallConfig::GetBoostingType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "boosting_type", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); if (value == std::string("gbdt") || value == std::string("gbrt")) { boosting_type = BoostingType::kGBDT; } else { Log::Fatal("Boosting type %s error", value.c_str()); } } } void OverallConfig::GetObjectiveType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "objective", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); objective_type = value; } } void OverallConfig::GetMetricType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "metric", &value)) { // clear old metrics metric_types.clear(); // to lower std::transform(value.begin(), value.end(), value.begin(), ::tolower); // split std::vector<std::string> metrics = Common::Split(value.c_str(), ','); // remove dumplicate std::unordered_map<std::string, int> metric_maps; for (auto& metric : metrics) { std::transform(metric.begin(), metric.end(), metric.begin(), ::tolower); if (metric_maps.count(metric) <= 0) { metric_maps[metric] = 1; } } for (auto& pair : metric_maps) { std::string sub_metric_str = pair.first; metric_types.push_back(sub_metric_str); } } } void OverallConfig::GetTaskType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "task", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); if (value == std::string("train") || value == std::string("training")) { task_type = TaskType::kTrain; } else if (value == std::string("predict") || value == std::string("prediction") || value == std::string("test")) { task_type = TaskType::kPredict; } else { Log::Fatal("Task type error"); } } } void OverallConfig::CheckParamConflict() { GBDTConfig* gbdt_config = dynamic_cast<GBDTConfig*>(boosting_config); if (network_config.num_machines > 1) { is_parallel = true; } else { is_parallel = false; gbdt_config->tree_learner_type = TreeLearnerType::kSerialTreeLearner; } if (gbdt_config->tree_learner_type == TreeLearnerType::kSerialTreeLearner) { is_parallel = false; network_config.num_machines = 1; } if (gbdt_config->tree_learner_type == TreeLearnerType::kSerialTreeLearner || gbdt_config->tree_learner_type == TreeLearnerType::kFeatureParallelTreelearner) { is_parallel_find_bin = false; } else if (gbdt_config->tree_learner_type == TreeLearnerType::kDataParallelTreeLearner) { is_parallel_find_bin = true; if (gbdt_config->tree_config.histogram_pool_size >= 0) { Log::Error("Auto set histogram_pool_size to non-limit, to reduce communication cost"); // To reduce communication cost, not limit pool size when using data parallel gbdt_config->tree_config.histogram_pool_size = -1; } } } void IOConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "max_bin", &max_bin); CHECK(max_bin > 0); GetInt(params, "data_random_seed", &data_random_seed); if (!GetString(params, "data", &data_filename)) { Log::Fatal("No training/prediction data, application quit"); } GetInt(params, "verbose", &verbosity); GetInt(params, "num_model_predict", &num_model_predict); GetBool(params, "is_pre_partition", &is_pre_partition); GetBool(params, "is_enable_sparse", &is_enable_sparse); GetBool(params, "use_two_round_loading", &use_two_round_loading); GetBool(params, "is_save_binary_file", &is_save_binary_file); GetBool(params, "is_sigmoid", &is_sigmoid); GetString(params, "output_model", &output_model); GetString(params, "input_model", &input_model); GetString(params, "output_result", &output_result); GetString(params, "input_init_score", &input_init_score); GetString(params, "log_file", &log_file); std::string tmp_str = ""; if (GetString(params, "valid_data", &tmp_str)) { valid_data_filenames = Common::Split(tmp_str.c_str(), ','); } } void ObjectiveConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetBool(params, "is_unbalance", &is_unbalance); GetDouble(params, "sigmoid", &sigmoid); GetInt(params, "max_position", &max_position); CHECK(max_position > 0); std::string tmp_str = ""; if (GetString(params, "label_gain", &tmp_str)) { label_gain = Common::StringToDoubleArray(tmp_str, ','); } else { // label_gain = 2^i - 1, may overflow, so we use 31 here const int max_label = 31; label_gain.push_back(0.0); for (int i = 1; i < max_label; ++i) { label_gain.push_back((1 << i) - 1); } } } void MetricConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "early_stopping_round", &early_stopping_round); GetInt(params, "metric_freq", &output_freq); CHECK(output_freq >= 0); GetDouble(params, "sigmoid", &sigmoid); GetBool(params, "is_training_metric", &is_provide_training_metric); std::string tmp_str = ""; if (GetString(params, "label_gain", &tmp_str)) { label_gain = Common::StringToDoubleArray(tmp_str, ','); } else { // label_gain = 2^i - 1, may overflow, so we use 31 here const int max_label = 31; label_gain.push_back(0.0); for (int i = 1; i < max_label; ++i) { label_gain.push_back((1 << i) - 1); } } if (GetString(params, "ndcg_eval_at", &tmp_str)) { eval_at = Common::StringToIntArray(tmp_str, ','); std::sort(eval_at.begin(), eval_at.end()); for (size_t i = 0; i < eval_at.size(); ++i) { CHECK(eval_at[i] > 0); } } else { // default eval ndcg @[1-5] for (int i = 1; i <= 5; ++i) { eval_at.push_back(i); } } } void TreeConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "min_data_in_leaf", &min_data_in_leaf); GetDouble(params, "min_sum_hessian_in_leaf", &min_sum_hessian_in_leaf); CHECK(min_sum_hessian_in_leaf > 1.0f || min_data_in_leaf > 0); GetInt(params, "num_leaves", &num_leaves); CHECK(num_leaves > 1); GetInt(params, "feature_fraction_seed", &feature_fraction_seed); GetDouble(params, "feature_fraction", &feature_fraction); CHECK(feature_fraction > 0.0 && feature_fraction <= 1.0); GetDouble(params, "histogram_pool_size", &histogram_pool_size); } void BoostingConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "num_iterations", &num_iterations); CHECK(num_iterations >= 0); GetInt(params, "bagging_seed", &bagging_seed); GetInt(params, "bagging_freq", &bagging_freq); CHECK(bagging_freq >= 0); GetDouble(params, "bagging_fraction", &bagging_fraction); CHECK(bagging_fraction > 0.0 && bagging_fraction <= 1.0); GetDouble(params, "learning_rate", &learning_rate); CHECK(learning_rate > 0.0); GetInt(params, "early_stopping_round", &early_stopping_round); CHECK(early_stopping_round >= 0); } void GBDTConfig::GetTreeLearnerType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "tree_learner", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); if (value == std::string("serial")) { tree_learner_type = TreeLearnerType::kSerialTreeLearner; } else if (value == std::string("feature") || value == std::string("feature_parallel")) { tree_learner_type = TreeLearnerType::kFeatureParallelTreelearner; } else if (value == std::string("data") || value == std::string("data_parallel")) { tree_learner_type = TreeLearnerType::kDataParallelTreeLearner; } else { Log::Fatal("Tree learner type error"); } } } void GBDTConfig::Set(const std::unordered_map<std::string, std::string>& params) { BoostingConfig::Set(params); GetTreeLearnerType(params); tree_config.Set(params); } void NetworkConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "num_machines", &num_machines); CHECK(num_machines >= 1); GetInt(params, "local_listen_port", &local_listen_port); CHECK(local_listen_port > 0); GetInt(params, "time_out", &time_out); CHECK(time_out > 0); GetString(params, "machine_list_file", &machine_list_filename); } } // namespace LightGBM <commit_msg>alert output and comment<commit_after>#include <LightGBM/config.h> #include <LightGBM/utils/common.h> #include <LightGBM/utils/log.h> #include <vector> #include <string> #include <unordered_map> #include <algorithm> namespace LightGBM { void OverallConfig::Set(const std::unordered_map<std::string, std::string>& params) { // load main config types GetInt(params, "num_threads", &num_threads); GetTaskType(params); GetBoostingType(params); GetObjectiveType(params); GetMetricType(params); // construct boosting configs if (boosting_type == BoostingType::kGBDT) { boosting_config = new GBDTConfig(); } // sub-config setup network_config.Set(params); io_config.Set(params); boosting_config->Set(params); objective_config.Set(params); metric_config.Set(params); // check for conflicts CheckParamConflict(); if (io_config.verbosity == 1) { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Info); } else if (io_config.verbosity == 0) { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Error); } else if (io_config.verbosity >= 2) { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Debug); } else { LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Fatal); } } void OverallConfig::GetBoostingType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "boosting_type", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); if (value == std::string("gbdt") || value == std::string("gbrt")) { boosting_type = BoostingType::kGBDT; } else { Log::Fatal("Boosting type %s error", value.c_str()); } } } void OverallConfig::GetObjectiveType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "objective", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); objective_type = value; } } void OverallConfig::GetMetricType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "metric", &value)) { // clear old metrics metric_types.clear(); // to lower std::transform(value.begin(), value.end(), value.begin(), ::tolower); // split std::vector<std::string> metrics = Common::Split(value.c_str(), ','); // remove dumplicate std::unordered_map<std::string, int> metric_maps; for (auto& metric : metrics) { std::transform(metric.begin(), metric.end(), metric.begin(), ::tolower); if (metric_maps.count(metric) <= 0) { metric_maps[metric] = 1; } } for (auto& pair : metric_maps) { std::string sub_metric_str = pair.first; metric_types.push_back(sub_metric_str); } } } void OverallConfig::GetTaskType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "task", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); if (value == std::string("train") || value == std::string("training")) { task_type = TaskType::kTrain; } else if (value == std::string("predict") || value == std::string("prediction") || value == std::string("test")) { task_type = TaskType::kPredict; } else { Log::Fatal("Task type error"); } } } void OverallConfig::CheckParamConflict() { GBDTConfig* gbdt_config = dynamic_cast<GBDTConfig*>(boosting_config); if (network_config.num_machines > 1) { is_parallel = true; } else { is_parallel = false; gbdt_config->tree_learner_type = TreeLearnerType::kSerialTreeLearner; } if (gbdt_config->tree_learner_type == TreeLearnerType::kSerialTreeLearner) { is_parallel = false; network_config.num_machines = 1; } if (gbdt_config->tree_learner_type == TreeLearnerType::kSerialTreeLearner || gbdt_config->tree_learner_type == TreeLearnerType::kFeatureParallelTreelearner) { is_parallel_find_bin = false; } else if (gbdt_config->tree_learner_type == TreeLearnerType::kDataParallelTreeLearner) { is_parallel_find_bin = true; if (gbdt_config->tree_config.histogram_pool_size >= 0) { Log::Error("Histogram LRU queue was enabled (histogram_pool_size=%f). Will disable this for reducing communication cost." , tree_config.histogram_pool_size); // Change pool size to -1(not limit) when using data parallel for reducing communication cost gbdt_config->tree_config.histogram_pool_size = -1; } } } void IOConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "max_bin", &max_bin); CHECK(max_bin > 0); GetInt(params, "data_random_seed", &data_random_seed); if (!GetString(params, "data", &data_filename)) { Log::Fatal("No training/prediction data, application quit"); } GetInt(params, "verbose", &verbosity); GetInt(params, "num_model_predict", &num_model_predict); GetBool(params, "is_pre_partition", &is_pre_partition); GetBool(params, "is_enable_sparse", &is_enable_sparse); GetBool(params, "use_two_round_loading", &use_two_round_loading); GetBool(params, "is_save_binary_file", &is_save_binary_file); GetBool(params, "is_sigmoid", &is_sigmoid); GetString(params, "output_model", &output_model); GetString(params, "input_model", &input_model); GetString(params, "output_result", &output_result); GetString(params, "input_init_score", &input_init_score); GetString(params, "log_file", &log_file); std::string tmp_str = ""; if (GetString(params, "valid_data", &tmp_str)) { valid_data_filenames = Common::Split(tmp_str.c_str(), ','); } } void ObjectiveConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetBool(params, "is_unbalance", &is_unbalance); GetDouble(params, "sigmoid", &sigmoid); GetInt(params, "max_position", &max_position); CHECK(max_position > 0); std::string tmp_str = ""; if (GetString(params, "label_gain", &tmp_str)) { label_gain = Common::StringToDoubleArray(tmp_str, ','); } else { // label_gain = 2^i - 1, may overflow, so we use 31 here const int max_label = 31; label_gain.push_back(0.0); for (int i = 1; i < max_label; ++i) { label_gain.push_back((1 << i) - 1); } } } void MetricConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "early_stopping_round", &early_stopping_round); GetInt(params, "metric_freq", &output_freq); CHECK(output_freq >= 0); GetDouble(params, "sigmoid", &sigmoid); GetBool(params, "is_training_metric", &is_provide_training_metric); std::string tmp_str = ""; if (GetString(params, "label_gain", &tmp_str)) { label_gain = Common::StringToDoubleArray(tmp_str, ','); } else { // label_gain = 2^i - 1, may overflow, so we use 31 here const int max_label = 31; label_gain.push_back(0.0); for (int i = 1; i < max_label; ++i) { label_gain.push_back((1 << i) - 1); } } if (GetString(params, "ndcg_eval_at", &tmp_str)) { eval_at = Common::StringToIntArray(tmp_str, ','); std::sort(eval_at.begin(), eval_at.end()); for (size_t i = 0; i < eval_at.size(); ++i) { CHECK(eval_at[i] > 0); } } else { // default eval ndcg @[1-5] for (int i = 1; i <= 5; ++i) { eval_at.push_back(i); } } } void TreeConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "min_data_in_leaf", &min_data_in_leaf); GetDouble(params, "min_sum_hessian_in_leaf", &min_sum_hessian_in_leaf); CHECK(min_sum_hessian_in_leaf > 1.0f || min_data_in_leaf > 0); GetInt(params, "num_leaves", &num_leaves); CHECK(num_leaves > 1); GetInt(params, "feature_fraction_seed", &feature_fraction_seed); GetDouble(params, "feature_fraction", &feature_fraction); CHECK(feature_fraction > 0.0 && feature_fraction <= 1.0); GetDouble(params, "histogram_pool_size", &histogram_pool_size); } void BoostingConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "num_iterations", &num_iterations); CHECK(num_iterations >= 0); GetInt(params, "bagging_seed", &bagging_seed); GetInt(params, "bagging_freq", &bagging_freq); CHECK(bagging_freq >= 0); GetDouble(params, "bagging_fraction", &bagging_fraction); CHECK(bagging_fraction > 0.0 && bagging_fraction <= 1.0); GetDouble(params, "learning_rate", &learning_rate); CHECK(learning_rate > 0.0); GetInt(params, "early_stopping_round", &early_stopping_round); CHECK(early_stopping_round >= 0); } void GBDTConfig::GetTreeLearnerType(const std::unordered_map<std::string, std::string>& params) { std::string value; if (GetString(params, "tree_learner", &value)) { std::transform(value.begin(), value.end(), value.begin(), ::tolower); if (value == std::string("serial")) { tree_learner_type = TreeLearnerType::kSerialTreeLearner; } else if (value == std::string("feature") || value == std::string("feature_parallel")) { tree_learner_type = TreeLearnerType::kFeatureParallelTreelearner; } else if (value == std::string("data") || value == std::string("data_parallel")) { tree_learner_type = TreeLearnerType::kDataParallelTreeLearner; } else { Log::Fatal("Tree learner type error"); } } } void GBDTConfig::Set(const std::unordered_map<std::string, std::string>& params) { BoostingConfig::Set(params); GetTreeLearnerType(params); tree_config.Set(params); } void NetworkConfig::Set(const std::unordered_map<std::string, std::string>& params) { GetInt(params, "num_machines", &num_machines); CHECK(num_machines >= 1); GetInt(params, "local_listen_port", &local_listen_port); CHECK(local_listen_port > 0); GetInt(params, "time_out", &time_out); CHECK(time_out > 0); GetString(params, "machine_list_file", &machine_list_filename); } } // namespace LightGBM <|endoftext|>
<commit_before>/**\file * * \copyright * Copyright (c) 2015, ef.gy Project Members * \copyright * 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: * \copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \copyright * 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. * * \see Project Documentation: https://ef.gy/documentation/libefgy * \see Project Source Code: https://github.com/ef-gy/libefgy */ #define ASIO_DISABLE_THREADS #include <ef.gy/irc.h> using namespace efgy; using asio::ip::tcp; /**\brief Main function for the IRC demo * * This is the main function for the IRC Hello World demo. * * \param[in] argc Process argument count. * \param[in] argv Process argument vector * * \returns 0 when nothing bad happened, 1 otherwise. */ int main(int argc, char *argv[]) { try { if (argc != 3) { std::cerr << "Usage: irc-hello <host> <port>\n"; return 1; } asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; if (endpoint_iterator != end) { tcp::endpoint endpoint = *endpoint_iterator; net::irc::server<tcp> s(io_service, endpoint); io_service.run(); } return 0; } catch (std::exception & e) { std::cerr << "Exception: " << e.what() << "\n"; } catch (std::system_error & e) { std::cerr << "System Error: " << e.what() << "\n"; } return 1; } <commit_msg>implement PING message response; add server name and version to default server<commit_after>/**\file * * \copyright * Copyright (c) 2015, ef.gy Project Members * \copyright * 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: * \copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \copyright * 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. * * \see Project Documentation: https://ef.gy/documentation/libefgy * \see Project Source Code: https://github.com/ef-gy/libefgy */ #define ASIO_DISABLE_THREADS #include <ef.gy/irc.h> using namespace efgy; using asio::ip::tcp; /**\brief Main function for the IRC demo * * This is the main function for the IRC Hello World demo. * * \param[in] argc Process argument count. * \param[in] argv Process argument vector * * \returns 0 when nothing bad happened, 1 otherwise. */ int main(int argc, char *argv[]) { try { if (argc != 3) { std::cerr << "Usage: irc-hello <host> <port>\n"; return 1; } asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; if (endpoint_iterator != end) { tcp::endpoint endpoint = *endpoint_iterator; net::irc::server<tcp> s(io_service, endpoint); s.name = argv[1]; io_service.run(); } return 0; } catch (std::exception & e) { std::cerr << "Exception: " << e.what() << "\n"; } catch (std::system_error & e) { std::cerr << "System Error: " << e.what() << "\n"; } return 1; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007, P.F.Peterson <[email protected]> * Spallation Neutron Source at Oak Ridge National Laboratory * * 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 "nxsummary.hpp" #include "string_util.hpp" #include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <napi.h> #include <stdexcept> #include <string> #include <vector> //#include "nxconfig.h" #include "data_util.hpp" // use STDINT if possible, otherwise define the types here #ifdef HAVE_STDINT_H #include <stdint.h> #else typedef signed char int8_t; typedef short int int16_t; typedef int int32_t; typedef unsigned char uint8_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; #ifdef _MSC_VER typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #endif //_MSC_VER #endif //HAVE_STDINT_H using std::runtime_error; using std::string; using std::ostringstream; using std::vector; static const size_t NX_MAX_RANK = 25; namespace nxsum { template <typename NumT> string toString(const NumT thing) { ostringstream s; s << thing; return s.str(); } // explicit instantiations so they get compiled in template string toString<uint32_t>(const uint32_t thing); template string toString<int>(const int thing); template <typename NumT> string toString(const NumT *data, const int dims[], const int rank) { int num_ele = 1; for (size_t i = 0; i < rank; ++i ) { num_ele *= dims[i]; } if (num_ele == 1) { return toString(data[0]); } if ((rank == 1) && (num_ele < NX_MAX_RANK)) { ostringstream s; s << '['; size_t length = dims[0]; for (size_t i = 0; i < length; ++i) { s << toString(data[i]); if (i+1 < length) { s << ','; } } s << ']'; return s.str(); } else { throw runtime_error("Do not know how to work with arrays"); } } string toString(const void *data, const int dims[], const int rank, const int type) { if (type == NX_CHAR) { return (char *) data; } else if (type == NX_FLOAT32) { return toString((float *)data, dims, rank); } else if (type == NX_FLOAT64) { return toString((double *)data, dims, rank); } else if (type == NX_INT32) { return toString((int32_t *)data, dims, rank); } else { ostringstream s; s << "Do not know how to work with type=" << nxtypeAsString(type); throw runtime_error(s.str()); } } string toString(const void *data, const int length, const int type) { int dims[1] = {length}; return toString(data, dims, 1, type); } string toUpperCase(const string &orig) { string result = orig; std::transform(orig.begin(), orig.end(), result.begin(), (int(*)(int))std::toupper); return result; } } <commit_msg>Added all of the other integer types. Fixes #266.<commit_after>/* * Copyright (c) 2007, P.F.Peterson <[email protected]> * Spallation Neutron Source at Oak Ridge National Laboratory * * 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 "nxsummary.hpp" #include "string_util.hpp" #include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <napi.h> #include <stdexcept> #include <string> #include <vector> //#include "nxconfig.h" #include "data_util.hpp" // use STDINT if possible, otherwise define the types here #ifdef HAVE_STDINT_H #include <stdint.h> #else typedef signed char int8_t; typedef short int int16_t; typedef int int32_t; typedef unsigned char uint8_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; #ifdef _MSC_VER typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #endif //_MSC_VER #endif //HAVE_STDINT_H using std::runtime_error; using std::string; using std::ostringstream; using std::vector; static const size_t NX_MAX_RANK = 25; namespace nxsum { template <typename NumT> string toString(const NumT thing) { ostringstream s; s << thing; return s.str(); } // explicit instantiations so they get compiled in template string toString<uint32_t>(const uint32_t thing); template string toString<int>(const int thing); template <typename NumT> string toString(const NumT *data, const int dims[], const int rank) { int num_ele = 1; for (size_t i = 0; i < rank; ++i ) { num_ele *= dims[i]; } if (num_ele == 1) { return toString(data[0]); } if ((rank == 1) && (num_ele < NX_MAX_RANK)) { ostringstream s; s << '['; size_t length = dims[0]; for (size_t i = 0; i < length; ++i) { s << toString(data[i]); if (i+1 < length) { s << ','; } } s << ']'; return s.str(); } else { throw runtime_error("Do not know how to work with arrays"); } } string toString(const void *data, const int dims[], const int rank, const int type) { if (type == NX_CHAR) { return (char *) data; } else if (type == NX_FLOAT32) { return toString((float *)data, dims, rank); } else if (type == NX_FLOAT64) { return toString((double *)data, dims, rank); } else if (type == NX_INT8) { return toString((int8_t *)data, dims, rank); } else if (type == NX_UINT8) { return toString((uint8_t *)data, dims, rank); } else if (type == NX_INT16) { return toString((int16_t *)data, dims, rank); } else if (type == NX_UINT16) { return toString((uint16_t *)data, dims, rank); } else if (type == NX_INT32) { return toString((int32_t *)data, dims, rank); } else if (type == NX_UINT32) { return toString((uint32_t *)data, dims, rank); } else if (type == NX_INT64) { return toString((int64_t *)data, dims, rank); } else if (type == NX_UINT64) { return toString((uint64_t *)data, dims, rank); } else { ostringstream s; s << "Do not know how to work with type=" << nxtypeAsString(type); throw runtime_error(s.str()); } } string toString(const void *data, const int length, const int type) { int dims[1] = {length}; return toString(data, dims, 1, type); } string toUpperCase(const string &orig) { string result = orig; std::transform(orig.begin(), orig.end(), result.begin(), (int(*)(int))std::toupper); return result; } } <|endoftext|>
<commit_before>/* * This test creates one raw (untyped) subgroup consisting of all the nodes. * The number of nodes is given as a parameter. After joning, each node sends * a fixed number of messages of fixed size, where the content of the messages * is generated at random. */ #include <iostream> #include <map> #include <set> #include <time.h> #include "derecho/derecho.h" using std::cout; using std::endl; using namespace derecho; int main(int argc, char* argv[]) { pthread_setname_np(pthread_self(), "random_messages"); srand(time(0)); if(argc < 2) { cout << "Usage: " << argv[0] << " <num_nodes> [configuration options...]" << endl; return -1; } // the number of nodes for this test const uint32_t num_nodes = std::stoi(argv[1]); // Read configurations from the command line options as well as the default config file Conf::initialize(argc, argv); // variable 'done' tracks the end of the test volatile bool done = false; // callback into the application code at each message delivery auto stability_callback = [&done, num_nodes, finished_nodes = std::set<uint32_t>()](uint32_t subgroup, int sender_id, long long int index, char* buf, long long int msg_size) mutable { // terminal message is of size 1. This signals that the sender has finished sending if(msg_size == 1) { // add the sender to the list of finished nodes finished_nodes.insert(sender_id); if(finished_nodes.size() == num_nodes) { done = true; } return; } // print the sender id and message contents cout << "sender id " << sender_id << ": "; for(auto i = 0; i < msg_size; ++i) { cout << buf[i]; } cout << endl; }; auto membership_function = [num_nodes](const View& curr_view, int& next_unassigned_rank) { subgroup_shard_layout_t subgroup_vector(1); auto num_members = curr_view.members.size(); // wait for all nodes to join if(num_members < num_nodes) { throw subgroup_provisioning_exception(); } // just one subgroup consisting of all the members of the top-level view subgroup_vector[0].emplace_back(curr_view.make_subview(curr_view.members)); next_unassigned_rank = curr_view.members.size(); return subgroup_vector; }; std::map<std::type_index, shard_view_generator_t> subgroup_map = { {std::type_index(typeid(RawObject)), membership_function}}; SubgroupInfo one_raw_group(subgroup_map); // join the group Group<> group(CallbackSet{stability_callback}, one_raw_group); cout << "Finished constructing/joining Group" << endl; auto members_order = group.get_members(); cout << "The order of members is :" << endl; for(uint i = 0; i < num_nodes; ++i) { cout << members_order[i] << " "; } cout << endl; RawSubgroup& raw_subgroup = group.get_subgroup<RawObject>(); uint32_t num_msgs = 10; uint32_t msg_size = 10; for(uint i = 0; i < num_msgs; ++i) { // the lambda function writes the message contents into the provided memory buffer // message content is generated at random raw_subgroup.send(msg_size, [msg_size](char* buf) { for(uint i = 0; i < msg_size; ++i) { buf[i] = 'a' + rand() % 26; } }); } // send a 1-byte message to signal completion raw_subgroup.send(1, [](char* buf) {}); // wait for delivery of all messages while(!done) { } // wait for all nodes to be done group.barrier_sync(); group.leave(); } <commit_msg>Minor<commit_after>/* * This test creates one raw (untyped) subgroup consisting of all the nodes. * The number of nodes is given as a parameter. After joning, each node sends * a fixed number of messages of fixed size, where the content of the messages * is generated at random. */ #include <iostream> #include <map> #include <set> #include <time.h> #include "derecho/derecho.h" using std::cout; using std::endl; using namespace derecho; int main(int argc, char* argv[]) { pthread_setname_np(pthread_self(), "random_messages"); srand(getpid()); if(argc < 2) { cout << "Usage: " << argv[0] << " <num_nodes> [configuration options...]" << endl; return -1; } // the number of nodes for this test const uint32_t num_nodes = std::stoi(argv[1]); // Read configurations from the command line options as well as the default config file Conf::initialize(argc, argv); // variable 'done' tracks the end of the test volatile bool done = false; // callback into the application code at each message delivery auto stability_callback = [&done, num_nodes, finished_nodes = std::set<uint32_t>()](uint32_t subgroup, int sender_id, long long int index, char* buf, long long int msg_size) mutable { // terminal message is of size 1. This signals that the sender has finished sending if(msg_size == 1) { // add the sender to the list of finished nodes finished_nodes.insert(sender_id); if(finished_nodes.size() == num_nodes) { done = true; } return; } // print the sender id and message contents cout << "sender id " << sender_id << ": "; for(auto i = 0; i < msg_size; ++i) { cout << buf[i]; } cout << endl; }; auto membership_function = [num_nodes](const View& curr_view, int& next_unassigned_rank) { subgroup_shard_layout_t subgroup_vector(1); auto num_members = curr_view.members.size(); // wait for all nodes to join if(num_members < num_nodes) { throw subgroup_provisioning_exception(); } // just one subgroup consisting of all the members of the top-level view subgroup_vector[0].emplace_back(curr_view.make_subview(curr_view.members)); next_unassigned_rank = curr_view.members.size(); return subgroup_vector; }; std::map<std::type_index, shard_view_generator_t> subgroup_map = { {std::type_index(typeid(RawObject)), membership_function}}; SubgroupInfo one_raw_group(subgroup_map); // join the group Group<> group(CallbackSet{stability_callback}, one_raw_group); cout << "Finished constructing/joining Group" << endl; auto members_order = group.get_members(); cout << "The order of members is :" << endl; for(uint i = 0; i < num_nodes; ++i) { cout << members_order[i] << " "; } cout << endl; RawSubgroup& raw_subgroup = group.get_subgroup<RawObject>(); uint32_t num_msgs = 10; uint32_t msg_size = 10; for(uint i = 0; i < num_msgs; ++i) { // the lambda function writes the message contents into the provided memory buffer // message content is generated at random raw_subgroup.send(msg_size, [msg_size](char* buf) { for(uint i = 0; i < msg_size; ++i) { buf[i] = 'a' + rand() % 26; } }); } // send a 1-byte message to signal completion raw_subgroup.send(1, [](char* buf) {}); // wait for delivery of all messages while(!done) { } // wait for all nodes to be done group.barrier_sync(); group.leave(); } <|endoftext|>
<commit_before>#include "Database.h" #include "Defines.h" #include <QDebug> #include <QSqlError> /** Database constructor * Constructs the local database. * Currently no interface to handle remote databases, just creates one in the * current working directory. */ Database::Database(QObject* parent) { this->path = QDir(CONFIG_FOLDER).filePath("horizon.db"); } Database::Database(QString path, QObject* parent) { this->path = path; } /** Initialize the actual database, if it hasn't been done already. * \return Success/failure of the operation. */ bool Database::init() { db = QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE")); db.setHostName("localhost"); db.setDatabaseName(this->path); bool status = db.open(); qDebug() << db.lastError(); if (!status) { qDebug("Couldn't connect to the database!"); return false; } QSqlQuery createQuery(db); bool rtn = createQuery.exec("CREATE TABLE IF NOT EXISTS games(ID INTEGER PRIMARY KEY ASC, GAMENAME TEXT NOT NULL, GAMEDIRECTORY TEXT NOT NULL, GAMEEXECUTABLE TEXT NOT NULL, ARGUMENTS TEXT NOT NULL, DRM INT DEFAULT 0);"); if (rtn) { emit dbChanged(); } return rtn; } /** Remove every table in the database. * \return Success/failure of the operation. */ bool Database::reset() { QSqlQuery query(db); bool rtn = query.exec("DROP TABLE IF EXISTS games"); if (rtn) { emit dbChanged(); } return rtn; } /** Add a game to the database and repopulate the games list. * \param gameName The name of the game. * \param gameDirectory Working directory of the game. * \param executablePath The location of the executable on the filesystem. * \param arguments List of arguments to launch with. * \param drm The DRM the game came from, where 0 = None, 1 = Steam, 2 = Origin, 3 = uPlay * \return Success/failure of the operation. */ bool Database::addGame(QString gameName, QString gameDirectory, QString executablePath, QString arguments, int drm) { QSqlQuery query(db); query.prepare("INSERT OR IGNORE INTO GAMES(GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM) VALUES (:gameName, :gameDirectory, :executablePath, :arguments, :drm);"); query.bindValue(":gameName", gameName); query.bindValue(":gameDirectory", gameDirectory); query.bindValue(":executablePath", executablePath); query.bindValue(":arguments", arguments); query.bindValue(":drm", drm); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } } /** Add games to the database and repopulate the games list. * \param games GameList of games to add. * \return Success/failure of the operation. */ void Database::addGames(GameList games) { for (auto& game : games) { addGame(game.gameName, game.gameDirectory, game.executablePath, game.arguments, game.drm); } emit dbChanged(); } /** Remove a game from the database by their ID. * \param id ID of the game to remove. * \return Success/failure of the operation. */ bool Database::removeGameById(unsigned int id) { if (std::get<0>(isExistant(id))) { QSqlQuery query(db); query.prepare("DELETE FROM games WHERE ID = :id;"); query.bindValue(":id", id); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } /** Remove a game from the database by their name. * \param name Name of the game to remove. */ bool Database::removeGameByName(QString name) { if (std::get<0>(isExistant(name))) { QSqlQuery query(db); query.prepare("DELETE FROM GAMES WHERE GAMENAME = :name;"); query.bindValue(":name", name); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } /** Wrapper to access the Game object from the ID. * \param id ID to find. * \return A Game object, empty upon failure. */ Game Database::getGameById(unsigned int id) { return std::get<1>(isExistant(id)); } /** Wrapper to access the Game object from the name. * \param id ID to find. * \return A Game object, empty upon failure. */ Game Database::getGameByName(QString name) { return std::get<1>(isExistant(name)); } /** Perform a query to find a specific game in the database by their ID. Unsafe at the * moment. * \param id ID of the game to find. * \return A Game object upon success, 0 upon failure. */ std::pair<bool, Game> Database::isExistant(unsigned int id) { QSqlQuery query(db); query.prepare("SELECT ID, GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM FROM GAMES WHERE ID = :id;"); query.bindValue(":id", id); query.exec(); if (query.next()) { QString name = query.value(1).toString(); QString path = query.value(2).toString(); QString exe = query.value(3).toString(); QString args = query.value(4).toString(); int drm = query.value(5).toInt(); return std::make_pair(true, Game {id, name, path, exe, args, drm}); } else { return std::make_pair(false, Game{}); } } /** Perform a query to find a specific game by their name (soon to be * deprecated). * * \param name Name of the game to find. * \return A Game object upon success, 0 upon failure. */ std::pair<bool, Game> Database::isExistant(QString name) { QSqlQuery query(db); query.prepare("SELECT ID, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM FROM GAMES WHERE GAMENAME = :name;"); query.bindValue(":name", name); query.exec(); if (query.next()) { unsigned int id = query.value(0).toUInt(); QString path = query.value(1).toString(); QString exe = query.value(2).toString(); QString args = query.value(3).toString(); int drm = query.value(4).toInt(); return std::make_pair(true, Game {id, name, path, exe, args, drm}); } else { return std::make_pair(false, Game{}); } } /** Perform a query to find every game in the database. * \return A QList of Game objects containing everything in the database. */ QList<Game> Database::getGames() { QList<Game> games; QSqlQuery query; query.exec("SELECT ID, GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM FROM GAMES;"); while (query.next()) { unsigned int id = query.value(0).toUInt(); QString name = query.value(1).toString(); QString path = query.value(2).toString(); QString exe = query.value(3).toString(); QString args = query.value(4).toString(); int drm = query.value(5).toInt(); games.append({id, name, path, exe, args, drm}); } return games; } /** Queries the database to find the number of games. * \return Total number of games stored so far. */ unsigned int Database::getGameCount() const { QSqlQuery query(db); query.exec("SELECT count() FROM GAMES;"); if (!query.next()) { return 0; } return query.value(0).toUInt(); } /** Sets the launch options of a game by ID. * \param id The ID of the game * \param launchOpts The new launch options * \return Success (true)/Failure (false) of the operation. */ bool Database::setLaunchOptionsById(unsigned int id, QString launchOpts) { if (std::get<0>(isExistant(id))) { QSqlQuery query(db); query.prepare("UPDATE games SET `ARGUMENTS` = :newOpts WHERE ID = :id;"); query.bindValue(":newOpts", launchOpts); query.bindValue(":id", id); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } /** Sets the launch options of a game by name. * \param name The name of the game (as stored in the database) * \param launchOpts The new launch options * \return Success (true)/Failure (false) of the operation. */ bool Database::setLaunchOptionsByName(QString name, QString launchOpts) { if (std::get<0>(isExistant(name))) { QSqlQuery query(db); query.prepare("UPDATE games SET `ARGUMENTS` = :newOpts WHERE GAMENAME = :name;"); query.bindValue(":newOpts", launchOpts); query.bindValue(":name", name); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } <commit_msg>Proper database reset by recreating the 'games' table after dropping it<commit_after>#include "Database.h" #include "Defines.h" #include <QDebug> #include <QSqlError> /** Database constructor * Constructs the local database. * Currently no interface to handle remote databases, just creates one in the * current working directory. */ Database::Database(QObject* parent) { this->path = QDir(CONFIG_FOLDER).filePath("horizon.db"); } Database::Database(QString path, QObject* parent) { this->path = path; } /** Initialize the actual database, if it hasn't been done already. * \return Success/failure of the operation. */ bool Database::init() { db = QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE")); db.setHostName("localhost"); db.setDatabaseName(this->path); bool status = db.open(); qDebug() << db.lastError(); if (!status) { qDebug("Couldn't connect to the database!"); return false; } QSqlQuery createQuery(db); bool rtn = createQuery.exec("CREATE TABLE IF NOT EXISTS games(ID INTEGER PRIMARY KEY ASC, GAMENAME TEXT NOT NULL, GAMEDIRECTORY TEXT NOT NULL, GAMEEXECUTABLE TEXT NOT NULL, ARGUMENTS TEXT NOT NULL, DRM INT DEFAULT 0);"); if (rtn) { emit dbChanged(); } return rtn; } /** Remove every table in the database. * \return Success/failure of the operation. */ bool Database::reset() { QSqlQuery query(db); bool rtn = query.exec("DROP TABLE IF EXISTS games") && query.exec("CREATE TABLE IF NOT EXISTS games(ID INTEGER PRIMARY KEY ASC, GAMENAME TEXT NOT NULL, GAMEDIRECTORY TEXT NOT NULL, GAMEEXECUTABLE TEXT NOT NULL, ARGUMENTS TEXT NOT NULL, DRM INT DEFAULT 0);"); if (rtn) { emit dbChanged(); } return rtn; } /** Add a game to the database and repopulate the games list. * \param gameName The name of the game. * \param gameDirectory Working directory of the game. * \param executablePath The location of the executable on the filesystem. * \param arguments List of arguments to launch with. * \param drm The DRM the game came from, where 0 = None, 1 = Steam, 2 = Origin, 3 = uPlay * \return Success/failure of the operation. */ bool Database::addGame(QString gameName, QString gameDirectory, QString executablePath, QString arguments, int drm) { QSqlQuery query(db); query.prepare("INSERT OR IGNORE INTO GAMES(GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM) VALUES (:gameName, :gameDirectory, :executablePath, :arguments, :drm);"); query.bindValue(":gameName", gameName); query.bindValue(":gameDirectory", gameDirectory); query.bindValue(":executablePath", executablePath); query.bindValue(":arguments", arguments); query.bindValue(":drm", drm); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } } /** Add games to the database and repopulate the games list. * \param games GameList of games to add. * \return Success/failure of the operation. */ void Database::addGames(GameList games) { for (auto& game : games) { addGame(game.gameName, game.gameDirectory, game.executablePath, game.arguments, game.drm); } emit dbChanged(); } /** Remove a game from the database by their ID. * \param id ID of the game to remove. * \return Success/failure of the operation. */ bool Database::removeGameById(unsigned int id) { if (std::get<0>(isExistant(id))) { QSqlQuery query(db); query.prepare("DELETE FROM games WHERE ID = :id;"); query.bindValue(":id", id); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } /** Remove a game from the database by their name. * \param name Name of the game to remove. */ bool Database::removeGameByName(QString name) { if (std::get<0>(isExistant(name))) { QSqlQuery query(db); query.prepare("DELETE FROM GAMES WHERE GAMENAME = :name;"); query.bindValue(":name", name); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } /** Wrapper to access the Game object from the ID. * \param id ID to find. * \return A Game object, empty upon failure. */ Game Database::getGameById(unsigned int id) { return std::get<1>(isExistant(id)); } /** Wrapper to access the Game object from the name. * \param id ID to find. * \return A Game object, empty upon failure. */ Game Database::getGameByName(QString name) { return std::get<1>(isExistant(name)); } /** Perform a query to find a specific game in the database by their ID. Unsafe at the * moment. * \param id ID of the game to find. * \return A Game object upon success, 0 upon failure. */ std::pair<bool, Game> Database::isExistant(unsigned int id) { QSqlQuery query(db); query.prepare("SELECT ID, GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM FROM GAMES WHERE ID = :id;"); query.bindValue(":id", id); query.exec(); if (query.next()) { QString name = query.value(1).toString(); QString path = query.value(2).toString(); QString exe = query.value(3).toString(); QString args = query.value(4).toString(); int drm = query.value(5).toInt(); return std::make_pair(true, Game {id, name, path, exe, args, drm}); } else { return std::make_pair(false, Game{}); } } /** Perform a query to find a specific game by their name (soon to be * deprecated). * * \param name Name of the game to find. * \return A Game object upon success, 0 upon failure. */ std::pair<bool, Game> Database::isExistant(QString name) { QSqlQuery query(db); query.prepare("SELECT ID, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM FROM GAMES WHERE GAMENAME = :name;"); query.bindValue(":name", name); query.exec(); if (query.next()) { unsigned int id = query.value(0).toUInt(); QString path = query.value(1).toString(); QString exe = query.value(2).toString(); QString args = query.value(3).toString(); int drm = query.value(4).toInt(); return std::make_pair(true, Game {id, name, path, exe, args, drm}); } else { return std::make_pair(false, Game{}); } } /** Perform a query to find every game in the database. * \return A QList of Game objects containing everything in the database. */ QList<Game> Database::getGames() { QList<Game> games; QSqlQuery query; query.exec("SELECT ID, GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE, ARGUMENTS, DRM FROM GAMES;"); while (query.next()) { unsigned int id = query.value(0).toUInt(); QString name = query.value(1).toString(); QString path = query.value(2).toString(); QString exe = query.value(3).toString(); QString args = query.value(4).toString(); int drm = query.value(5).toInt(); games.append({id, name, path, exe, args, drm}); } return games; } /** Queries the database to find the number of games. * \return Total number of games stored so far. */ unsigned int Database::getGameCount() const { QSqlQuery query(db); query.exec("SELECT count() FROM GAMES;"); if (!query.next()) { return 0; } return query.value(0).toUInt(); } /** Sets the launch options of a game by ID. * \param id The ID of the game * \param launchOpts The new launch options * \return Success (true)/Failure (false) of the operation. */ bool Database::setLaunchOptionsById(unsigned int id, QString launchOpts) { if (std::get<0>(isExistant(id))) { QSqlQuery query(db); query.prepare("UPDATE games SET `ARGUMENTS` = :newOpts WHERE ID = :id;"); query.bindValue(":newOpts", launchOpts); query.bindValue(":id", id); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } /** Sets the launch options of a game by name. * \param name The name of the game (as stored in the database) * \param launchOpts The new launch options * \return Success (true)/Failure (false) of the operation. */ bool Database::setLaunchOptionsByName(QString name, QString launchOpts) { if (std::get<0>(isExistant(name))) { QSqlQuery query(db); query.prepare("UPDATE games SET `ARGUMENTS` = :newOpts WHERE GAMENAME = :name;"); query.bindValue(":newOpts", launchOpts); query.bindValue(":name", name); bool rtn = query.exec(); if (rtn) { emit dbChanged(); } return rtn; } else { return false; } } <|endoftext|>
<commit_before>/* * gtgtrace * * Performs the core loop of the program: propagating satellite position * forward for the specified number of steps from the specified start time. */ #include <stdio.h> #include <string.h> #include <math.h> #include "SGP4.h" #include "Julian.h" #include "Timespan.h" #include "Tle.h" #include "gtg.h" #include "gtgutil.h" #include "gtgtle.h" #include "gtgshp.h" #include "gtgattr.h" #include "gtgtrace.h" /* InitTime Parameters: desc, string to read time specification from. Accepts four formats: now[OFFSET] - current time epoch[OFFSET] - reference time of orbit info If specified, OFFSET is number (positive or negative) followed by a character indicating units - s seconds, m minutes, h hours, d days. YYYY-MM-DD HH:MM:SS.SSSSSS UTC S - UNIX time (seconds since 1970-01-01 00:00:00) now, reference date to use if "now" time is specified epoch, reference date to use if orbit "epoch" is specified Returns: MFE (minutes from TLE epoch) of the described time */ double InitTime(const char *desc, const Julian& now, const Julian& epoch) { double mfe = 0; double offset; char unit; if (0 == strcmp("now", desc)) { mfe = (now - epoch).GetTotalMinutes(); } else if (2 == sscanf(desc, "now%lf%c", &offset, &unit)) { /* start with mfe of "now", then apply offset to that */ mfe = (now - epoch).GetTotalMinutes(); switch (unit) { case 's': mfe += offset / 60.0; break; case 'm': mfe += offset; break; case 'h': mfe += offset * 60.0; break; case 'd': mfe += offset * 1440.0; break; default: Fail("invalid current time offset unit: %c\n", unit); break; } } else if (0 == strcmp("epoch", desc)) { mfe = 0.0; } else if (2 == sscanf(desc, "epoch%lf%c", &offset, &unit)) { switch (unit) { case 's': mfe = offset / 60.0; break; case 'm': mfe = offset; break; case 'h': mfe = offset * 60.0; break; case 'd': mfe = offset * 1440.0; break; default: Fail("invalid epoch time offset unit: %c\n", unit); break; } } else { int year, month, day, hour, minute; double second; if (6 == sscanf(desc, "%4d-%2d-%2d %2d:%2d:%9lf UTC", &year, &month, &day, &hour, &minute, &second)) { Julian time(year, month, day, hour, minute, second); mfe = (time - epoch).GetTotalMinutes(); } else { double unixtime; if (3 == sscanf(desc, "%lf%lf%c", &unixtime, &offset, &unit)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes(); switch (unit) { case 's': mfe += offset / 60.0; break; case 'm': mfe += offset; break; case 'h': mfe += offset * 60.0; break; case 'd': mfe += offset * 1440.0; break; default: Fail("invalid unix timestamp offset unit: %c\n", unit); break; } } else if (1 == sscanf(desc, "%lf", &unixtime)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes(); } else { Fail("cannot parse time: %s\n", desc); } } } return mfe; } /* * Construct the output filename, minus shapefile file extensions. * The general format is: <basepath>/<prefix>rootname<suffix> * * If this is the only output file and basepath is specified, * the format is simply basepath and other elements are ignored. */ std::string BuildBasepath(const std::string& rootname, const GTGConfiguration& cfg) { std::string shpbase; /* if only one TLE was specified, we use --output as the unmodified basepath, and ignore --prefix and --suffix, and do not insert any ID. This only applies if --output is defined! Otherwise, use id/prefix/suffix. */ if (cfg.single && (cfg.basepath != NULL)) { shpbase += cfg.basepath; return shpbase; } if (NULL != cfg.basepath) { shpbase += cfg.basepath; if ('/' != shpbase[shpbase.length() - 1]) { shpbase += '/'; } } if (NULL != cfg.prefix) { shpbase += cfg.prefix; } shpbase += rootname; if (NULL != cfg.suffix) { shpbase += cfg.suffix; } return shpbase; } /* * Do some initialization that may be specific to this track (output start time, * name, etc.) and do the main orbit propagation loop, outputting at each step. */ void GenerateGroundTrack(Tle& tle, SGP4& model, Julian& now, const GTGConfiguration& cfg, const Timespan& interval) { int step = 0; Eci eci(now, 0, 0, 0); bool stop = false; CoordGeodetic geo; double minutes; double startMFE; double endMFE; double intervalMinutes; ShapefileWriter *shpwriter = NULL; AttributeWriter *attrwriter = NULL; int shpindex = 0; intervalMinutes = interval.GetTotalMinutes(); /* for line output mode */ Eci prevEci(eci); int prevSet = 0; /* Initialize the starting timestamp; default to epoch */ startMFE = InitTime(cfg.start == NULL ? "epoch" : cfg.start, now, tle.Epoch()); minutes = startMFE; Note("TLE epoch: %s\n", tle.Epoch().ToString().c_str()); Note("Start MFE: %.9lf\n", startMFE); /* Initialize the ending timestamp, if needed */ if (NULL != cfg.end) { endMFE = InitTime(cfg.end, now, tle.Epoch()); /* Sanity check 1 */ if (startMFE >= endMFE) { Fail("end time (%.9lf MFE) not after start time (%.9lf MFE)\n", endMFE, startMFE); } /* Sanity check 2 */ if (intervalMinutes > endMFE - startMFE) { Fail("interval (%.9lf minutes) exceeds period between start time and end time (%.9lf minutes).\n", intervalMinutes, endMFE - startMFE); } Note("End MFE: %.9lf\n", endMFE); } std::ostringstream ns; ns << tle.NoradNumber(); std::string basepath(BuildBasepath(ns.str(), cfg)); if (!(cfg.csvMode && (cfg.basepath == NULL))) { Note("Output basepath: %s\n", basepath.c_str()); } if (!cfg.csvMode) { shpwriter = new ShapefileWriter(basepath.c_str(), cfg.features, cfg.prj); } attrwriter = new AttributeWriter( cfg.csvMode && (cfg.basepath == NULL) ? NULL : basepath.c_str(), cfg.has_observer, cfg.obslat, cfg.obslon, cfg.obsalt, cfg.csvMode, cfg.csvHeader); while (1) { /* where is the satellite now? */ try { eci = model.FindPosition(minutes); } catch (SatelliteException &e) { Warn("satellite exception (stopping at step %d): %s\n", step, e.what()); break; } catch (DecayedException &e) { Warn("satellite decayed (stopping at step %d).\n", step); break; } if (line == cfg.features) { if (prevSet) { geo = prevEci.ToGeodetic(); if (cfg.csvMode) { // increment shpindex ourselves in csvMode attrwriter->output(shpindex++, minutes, prevEci, geo); } else { shpindex = shpwriter->output(prevEci, geo, &eci, cfg.split); attrwriter->output(shpindex, minutes, prevEci, geo); } step++; } else { /* prevSet is only false on the first pass, which yields an extra interval not counted against step count - needed since line segments imply n+1 intervals for n steps */ prevSet = 1; } prevEci = eci; } else { geo = eci.ToGeodetic(); if (cfg.csvMode) { attrwriter->output(shpindex++, minutes, eci, geo); } else { shpindex = shpwriter->output(eci, geo); attrwriter->output(shpindex, minutes, eci, geo); } step++; } /* increment time interval */ minutes += intervalMinutes; /* stop ground track once we've exceeded step count or end time */ if ((0 != cfg.steps) && (step >= cfg.steps)) { break; } else if ((NULL != cfg.end) && (minutes >= endMFE) ) { if (!cfg.forceend or stop) { break; } else { /* force output of the exact end time, then stop next time */ minutes = endMFE; stop = true; } } } if (shpwriter != NULL) { shpwriter->close(); delete shpwriter; } if (attrwriter != NULL) { attrwriter->close(); delete attrwriter; } } /* * Create an SGP4 model for the specified satellite two-line element set * and start generating its ground track. */ void InitGroundTrace(Tle& tle, Julian& now, const GTGConfiguration &cfg, const Timespan& interval) { try { SGP4 model(tle); GenerateGroundTrack(tle, model, now, cfg, interval); } catch (SatelliteException &e) { Fail("cannot initialize satellite model: %s\n", e.what()); } } <commit_msg>Moved duplicate time offset calculator into a separate function<commit_after>/* * gtgtrace * * Performs the core loop of the program: propagating satellite position * forward for the specified number of steps from the specified start time. */ #include <stdio.h> #include <string.h> #include <math.h> #include "SGP4.h" #include "Julian.h" #include "Timespan.h" #include "Tle.h" #include "gtg.h" #include "gtgutil.h" #include "gtgtle.h" #include "gtgshp.h" #include "gtgattr.h" #include "gtgtrace.h" /* * Given an offset value and a unit, calculate the offset in minutes. */ double OffsetInMinutes(double offset, char unit) { double offsetMinutes; switch (unit) { case 's': offsetMinutes = offset / 60.0; break; case 'm': offsetMinutes = offset; break; case 'h': offsetMinutes = offset * 60.0; break; case 'd': offsetMinutes = offset * 1440.0; break; default: Fail("invalid time offset unit: %c\n", unit); break; } return offsetMinutes; } /* InitTime Parameters: desc, string to read time specification from. Accepts four formats: now[OFFSET] - current time epoch[OFFSET] - reference time of orbit info If specified, OFFSET is number (positive or negative) followed by a character indicating units - s seconds, m minutes, h hours, d days. YYYY-MM-DD HH:MM:SS.SSSSSS UTC S - UNIX time (seconds since 1970-01-01 00:00:00) now, reference date to use if "now" time is specified epoch, reference date to use if orbit "epoch" is specified Returns: MFE (minutes from TLE epoch) of the described time */ double InitTime(const char *desc, const Julian& now, const Julian& epoch) { double mfe = 0; double offset; char unit; if (0 == strcmp("now", desc)) { mfe = (now - epoch).GetTotalMinutes(); } else if (2 == sscanf(desc, "now%lf%c", &offset, &unit)) { mfe = (now - epoch).GetTotalMinutes() + OffsetInMinutes(offset, unit); } else if (0 == strcmp("epoch", desc)) { mfe = 0.0; } else if (2 == sscanf(desc, "epoch%lf%c", &offset, &unit)) { mfe = OffsetInMinutes(offset, unit); } else { int year, month, day, hour, minute; double second; if (6 == sscanf(desc, "%4d-%2d-%2d %2d:%2d:%9lf UTC", &year, &month, &day, &hour, &minute, &second)) { Julian time(year, month, day, hour, minute, second); mfe = (time - epoch).GetTotalMinutes(); } else { double unixtime; if (3 == sscanf(desc, "%lf%lf%c", &unixtime, &offset, &unit)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes() + OffsetInMinutes(offset, unit); } else if (1 == sscanf(desc, "%lf", &unixtime)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes(); } else { Fail("cannot parse time: %s\n", desc); } } } return mfe; } /* * Construct the output filename, minus shapefile file extensions. * The general format is: <basepath>/<prefix>rootname<suffix> * * If this is the only output file and basepath is specified, * the format is simply basepath and other elements are ignored. */ std::string BuildBasepath(const std::string& rootname, const GTGConfiguration& cfg) { std::string shpbase; /* if only one TLE was specified, we use --output as the unmodified basepath, and ignore --prefix and --suffix, and do not insert any ID. This only applies if --output is defined! Otherwise, use id/prefix/suffix. */ if (cfg.single && (cfg.basepath != NULL)) { shpbase += cfg.basepath; return shpbase; } if (NULL != cfg.basepath) { shpbase += cfg.basepath; if ('/' != shpbase[shpbase.length() - 1]) { shpbase += '/'; } } if (NULL != cfg.prefix) { shpbase += cfg.prefix; } shpbase += rootname; if (NULL != cfg.suffix) { shpbase += cfg.suffix; } return shpbase; } /* * Do some initialization that may be specific to this track (output start time, * name, etc.) and do the main orbit propagation loop, outputting at each step. */ void GenerateGroundTrack(Tle& tle, SGP4& model, Julian& now, const GTGConfiguration& cfg, const Timespan& interval) { int step = 0; Eci eci(now, 0, 0, 0); bool stop = false; CoordGeodetic geo; double minutes; double startMFE; double endMFE; double intervalMinutes; ShapefileWriter *shpwriter = NULL; AttributeWriter *attrwriter = NULL; int shpindex = 0; intervalMinutes = interval.GetTotalMinutes(); /* for line output mode */ Eci prevEci(eci); int prevSet = 0; /* Initialize the starting timestamp; default to epoch */ startMFE = InitTime(cfg.start == NULL ? "epoch" : cfg.start, now, tle.Epoch()); minutes = startMFE; Note("TLE epoch: %s\n", tle.Epoch().ToString().c_str()); Note("Start MFE: %.9lf\n", startMFE); /* Initialize the ending timestamp, if needed */ if (NULL != cfg.end) { endMFE = InitTime(cfg.end, now, tle.Epoch()); /* Sanity check 1 */ if (startMFE >= endMFE) { Fail("end time (%.9lf MFE) not after start time (%.9lf MFE)\n", endMFE, startMFE); } /* Sanity check 2 */ if (intervalMinutes > endMFE - startMFE) { Fail("interval (%.9lf minutes) exceeds period between start time and end time (%.9lf minutes).\n", intervalMinutes, endMFE - startMFE); } Note("End MFE: %.9lf\n", endMFE); } std::ostringstream ns; ns << tle.NoradNumber(); std::string basepath(BuildBasepath(ns.str(), cfg)); if (!(cfg.csvMode && (cfg.basepath == NULL))) { Note("Output basepath: %s\n", basepath.c_str()); } if (!cfg.csvMode) { shpwriter = new ShapefileWriter(basepath.c_str(), cfg.features, cfg.prj); } attrwriter = new AttributeWriter( cfg.csvMode && (cfg.basepath == NULL) ? NULL : basepath.c_str(), cfg.has_observer, cfg.obslat, cfg.obslon, cfg.obsalt, cfg.csvMode, cfg.csvHeader); while (1) { /* where is the satellite now? */ try { eci = model.FindPosition(minutes); } catch (SatelliteException &e) { Warn("satellite exception (stopping at step %d): %s\n", step, e.what()); break; } catch (DecayedException &e) { Warn("satellite decayed (stopping at step %d).\n", step); break; } if (line == cfg.features) { if (prevSet) { geo = prevEci.ToGeodetic(); if (cfg.csvMode) { // increment shpindex ourselves in csvMode attrwriter->output(shpindex++, minutes, prevEci, geo); } else { shpindex = shpwriter->output(prevEci, geo, &eci, cfg.split); attrwriter->output(shpindex, minutes, prevEci, geo); } step++; } else { /* prevSet is only false on the first pass, which yields an extra interval not counted against step count - needed since line segments imply n+1 intervals for n steps */ prevSet = 1; } prevEci = eci; } else { geo = eci.ToGeodetic(); if (cfg.csvMode) { attrwriter->output(shpindex++, minutes, eci, geo); } else { shpindex = shpwriter->output(eci, geo); attrwriter->output(shpindex, minutes, eci, geo); } step++; } /* increment time interval */ minutes += intervalMinutes; /* stop ground track once we've exceeded step count or end time */ if ((0 != cfg.steps) && (step >= cfg.steps)) { break; } else if ((NULL != cfg.end) && (minutes >= endMFE) ) { if (!cfg.forceend or stop) { break; } else { /* force output of the exact end time, then stop next time */ minutes = endMFE; stop = true; } } } if (shpwriter != NULL) { shpwriter->close(); delete shpwriter; } if (attrwriter != NULL) { attrwriter->close(); delete attrwriter; } } /* * Create an SGP4 model for the specified satellite two-line element set * and start generating its ground track. */ void InitGroundTrace(Tle& tle, Julian& now, const GTGConfiguration &cfg, const Timespan& interval) { try { SGP4 model(tle); GenerateGroundTrack(tle, model, now, cfg, interval); } catch (SatelliteException &e) { Fail("cannot initialize satellite model: %s\n", e.what()); } } <|endoftext|>
<commit_before>/* * qimp2rage.cpp * * Created by Tobias Wood on 2015/08/24. * Copyright (c) 2015 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <string> #include <complex> #include <getopt.h> #include "Types.h" #include "Util.h" #include "itkBinaryFunctorImageFilter.h" #include "itkImageToHistogramFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkComplexToRealImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkMaskImageFilter.h" using namespace std; const string usage{ "A tool to process MP3-RAGE images\n\ Usage is: qimp2rage [options] input \n\ \ Input must contain three volumes and be complex-valued\n\ Output will be files with _CXY where X & Y are inversion times\n\ Options:\n\ --verbose, -v : Print more messages.\n\ --mask, -m file : Mask input with specified file.\n\ --out, -o path : Add a prefix to the output filenames.\n\ --threshold, -t N : Threshold at Nth quantile.\n\ --complex, -x : Output complex contast images.\n\ --threads, -T N : Use a maximum of N threads.\n" }; static struct option long_options[] = { {"verbose", required_argument, 0, 'v'}, {"mask", required_argument, 0, 'm'}, {"threshold", required_argument, 0, 't'}, {"out", required_argument, 0, 'o'}, {"complex", no_argument, 0, 'x'}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; static const char *short_options = "vm:o:t:xT:h"; template<class T> class MP2Contrast { public: MP2Contrast() {} ~MP2Contrast() {} bool operator!=(const MP2Contrast &) const { return false; } bool operator==(const MP2Contrast &other) const { return !(*this != other); } inline complex<T> operator()(const complex<T> &ti1, const complex<T> &ti2) const { const T a1 = abs(ti1); const T a2 = abs(ti2); return (conj(ti1)*ti2)/(a1*a1 + a2*a2); } }; int main(int argc, char **argv) { int indexptr = 0, c; string outPrefix = ""; bool verbose = false, complex_output = false; float thresh_quantile = 0.0; QI::ImageF::Pointer mask = ITK_NULLPTR; while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'm': { cout << "Reading mask." << endl; auto maskFile = QI::ReadImageF::New(); maskFile->SetFileName(optarg); maskFile->Update(); mask = maskFile->GetOutput(); mask->DisconnectPipeline(); } break; case 'o': outPrefix = optarg; cout << "Output prefix will be: " << outPrefix << endl; break; case 't': thresh_quantile = atof(optarg); break; case 'x': complex_output = true; break; case 'T': itk::MultiThreader::SetGlobalDefaultNumberOfThreads(atoi(optarg)); break; case 'h': cout << usage << endl; return EXIT_SUCCESS; case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << usage << endl; return EXIT_FAILURE; } string fname(argv[optind]); if (verbose) cout << "Opening input file " << fname << endl; if (outPrefix == "") outPrefix = fname.substr(0, fname.find(".nii")); auto inFile = QI::ReadTimeseriesXF::New(); inFile->SetFileName(fname); inFile->Update(); vector<itk::ExtractImageFilter<QI::TimeseriesXF, QI::ImageXF>::Pointer> vols(3); auto region = inFile->GetOutput()->GetLargestPossibleRegion(); region.GetModifiableSize()[3] = 0; for (int i = 0; i < 3; i++) { region.GetModifiableIndex()[3] = i; vols[i] = itk::ExtractImageFilter<QI::TimeseriesXF, QI::ImageXF>::New(); vols[i]->SetExtractionRegion(region); vols[i]->SetInput(inFile->GetOutput()); vols[i]->SetDirectionCollapseToSubmatrix(); } if (!mask) { // Threshold the last volume to automatically generate a mask auto magFilter = itk::ComplexToModulusImageFilter<QI::ImageXF, QI::ImageF>::New(); auto histFilter = itk::Statistics::ImageToHistogramFilter<QI::ImageF>::New(); auto threshFilter = itk::BinaryThresholdImageFilter<QI::ImageF, QI::ImageF>::New(); magFilter->SetInput(vols[2]->GetOutput()); histFilter->SetInput(magFilter->GetOutput()); itk::Statistics::ImageToHistogramFilter<QI::ImageF>::HistogramSizeType size(1); size.Fill(100); histFilter->SetHistogramSize(size); histFilter->SetAutoMinimumMaximum(true); histFilter->Update(); float threshold = histFilter->GetOutput()->Quantile(0, thresh_quantile); threshFilter->SetInput(magFilter->GetOutput()); threshFilter->SetLowerThreshold(threshold); threshFilter->SetInsideValue(1); threshFilter->SetOutsideValue(0); threshFilter->Update(); mask = threshFilter->GetOutput(); mask->DisconnectPipeline(); } for (int i1 = 0; i1 < 3; i1++) { for (int i2 = (i1 + 1); i2 < 3; i2++) { auto mp2rage_filter = itk::BinaryFunctorImageFilter<QI::ImageXF, QI::ImageXF, QI::ImageXF, MP2Contrast<float>>::New(); mp2rage_filter->SetInput1(vols[i1]->GetOutput()); mp2rage_filter->SetInput2(vols[i2]->GetOutput()); auto mask_filter = itk::MaskImageFilter<QI::ImageXF, QI::ImageF, QI::ImageXF>::New(); mask_filter->SetInput1(mp2rage_filter->GetOutput()); mask_filter->SetMaskImage(mask); mask_filter->Update(); string outName = outPrefix + "_C" + to_string(i1) + to_string(i2) + QI::OutExt(); if (complex_output) { QI::writeResult<QI::ImageXF>(mask_filter->GetOutput(), outName); } else { auto realFilter = itk::ComplexToRealImageFilter<QI::ImageXF, QI::ImageF>::New(); realFilter->SetInput(mask_filter->GetOutput()); QI::writeResult<QI::ImageF>(realFilter->GetOutput(), outName); } } } if (verbose) cout << "Finished." << endl; return EXIT_SUCCESS; } <commit_msg>Hacked together T1&B1 fitting for MP3RAGE. Seems to fit T1 okay, B1 poorly and inversion efficiency (eta) not at all.<commit_after>/* * qimp2rage.cpp * * Created by Tobias Wood on 2015/08/24. * Copyright (c) 2015 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <string> #include <complex> #include <getopt.h> #include "itkBinaryFunctorImageFilter.h" #include "itkImageToHistogramFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkComplexToRealImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkMaskImageFilter.h" #include "Filters/ApplyAlgorithmFilter.h" #include "Types.h" #include "Util.h" #include "Sequence.h" using namespace std; const string usage{ "A tool to process MP3-RAGE images\n\ Usage is: qimp2rage [options] input \n\ \ Input must contain three volumes and be complex-valued\n\ Output will be files with _CXY where X & Y are inversion times\n\ Options:\n\ --verbose, -v : Print more messages.\n\ --mask, -m file : Mask input with specified file.\n\ --out, -o path : Add a prefix to the output filenames.\n\ --threshold, -t N : Threshold at Nth quantile.\n\ --complex, -x : Output complex contast images.\n\ --threads, -T N : Use a maximum of N threads.\n" }; static struct option long_options[] = { {"verbose", required_argument, 0, 'v'}, {"mask", required_argument, 0, 'm'}, {"threshold", required_argument, 0, 't'}, {"out", required_argument, 0, 'o'}, {"complex", no_argument, 0, 'x'}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; static const char *short_options = "vm:o:t:xT:h"; template<class T> class MP2Contrast { public: MP2Contrast() {} ~MP2Contrast() {} bool operator!=(const MP2Contrast &) const { return false; } bool operator==(const MP2Contrast &other) const { return !(*this != other); } inline complex<T> operator()(const complex<T> &ti1, const complex<T> &ti2) const { const T a1 = abs(ti1); const T a2 = abs(ti2); return (conj(ti1)*ti2)/(a1*a1 + a2*a2); } }; class MP3LookupAlgo : public Algorithm<double> { protected: std::vector<Array3d> m_pars, m_cons; public: size_t numInputs() const override { return 1; } size_t numConsts() const override { return 0; } size_t numOutputs() const override { return 3; } size_t dataSize() const override { return 3; } virtual TArray defaultConsts() { // B1 TArray def = TArray::Ones(0); return def; } MP3LookupAlgo() { cout << "Build lookup table" << endl; MP3RAGE sequence(true); MP2Contrast<double> con; m_pars.clear(); m_cons.clear(); for (float T1 = 0.5; T1 < 4.3; T1 += 0.005) { for (float B1 = 0.75; B1 < 1.25; B1 += 0.01) { for (float eta = 1.0; eta < 1.25; eta += 1.0) { Array3d tp; tp << T1, B1, eta; m_pars.push_back(tp); Array3cd sig = sequence.signal(1., T1, B1, eta); Array3d tc; tc[0] = con(sig[0], sig[1]).real(); tc[1] = con(sig[0], sig[2]).real(); tc[2] = con(sig[1], sig[2]).real(); m_cons.push_back(tc); //cout << m_pars.back().transpose() << " : " << m_cons.back().transpose() << endl; } } } cout << "Lookup table has " << m_pars.size() << " entries" << endl; } virtual void apply(const TInput &data_inputs, const TArray &const_inputs, TArray &outputs, TArray &resids, TIterations &its) const override { double best_distance = numeric_limits<double>::max(); int best_index = 0; for (int i = 0; i < m_pars.size(); i++) { double distance = (m_cons[i] - data_inputs).matrix().norm(); if (distance < best_distance) { best_distance = distance; best_index = i; } } outputs = m_pars[best_index]; //cout << "Best index " << best_index << " distance " << best_distance << " pars " << outputs.transpose() << " data " << data_inputs.transpose() << " cons" << m_cons[best_index].transpose() << endl; its = 1; } }; int main(int argc, char **argv) { int indexptr = 0, c; string outPrefix = ""; bool verbose = false, complex_output = false; float thresh_quantile = 0.0; QI::ImageF::Pointer mask = ITK_NULLPTR; while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'm': { cout << "Reading mask." << endl; auto maskFile = QI::ReadImageF::New(); maskFile->SetFileName(optarg); maskFile->Update(); mask = maskFile->GetOutput(); mask->DisconnectPipeline(); } break; case 'o': outPrefix = optarg; cout << "Output prefix will be: " << outPrefix << endl; break; case 't': thresh_quantile = atof(optarg); break; case 'x': complex_output = true; break; case 'T': itk::MultiThreader::SetGlobalDefaultNumberOfThreads(atoi(optarg)); break; case 'h': cout << usage << endl; return EXIT_SUCCESS; case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << usage << endl; return EXIT_FAILURE; } string fname(argv[optind]); if (verbose) cout << "Opening input file " << fname << endl; if (outPrefix == "") outPrefix = fname.substr(0, fname.find(".nii")); auto inFile = QI::ReadTimeseriesXF::New(); inFile->SetFileName(fname); inFile->Update(); vector<itk::ExtractImageFilter<QI::TimeseriesXF, QI::ImageXF>::Pointer> vols(3); auto region = inFile->GetOutput()->GetLargestPossibleRegion(); region.GetModifiableSize()[3] = 0; for (int i = 0; i < 3; i++) { region.GetModifiableIndex()[3] = i; vols[i] = itk::ExtractImageFilter<QI::TimeseriesXF, QI::ImageXF>::New(); vols[i]->SetExtractionRegion(region); vols[i]->SetInput(inFile->GetOutput()); vols[i]->SetDirectionCollapseToSubmatrix(); } if (!mask) { // Threshold the last volume to automatically generate a mask auto magFilter = itk::ComplexToModulusImageFilter<QI::ImageXF, QI::ImageF>::New(); auto histFilter = itk::Statistics::ImageToHistogramFilter<QI::ImageF>::New(); auto threshFilter = itk::BinaryThresholdImageFilter<QI::ImageF, QI::ImageF>::New(); magFilter->SetInput(vols[2]->GetOutput()); histFilter->SetInput(magFilter->GetOutput()); itk::Statistics::ImageToHistogramFilter<QI::ImageF>::HistogramSizeType size(1); size.Fill(100); histFilter->SetHistogramSize(size); histFilter->SetAutoMinimumMaximum(true); histFilter->Update(); float threshold = histFilter->GetOutput()->Quantile(0, thresh_quantile); threshFilter->SetInput(magFilter->GetOutput()); threshFilter->SetLowerThreshold(threshold); threshFilter->SetInsideValue(1); threshFilter->SetOutsideValue(0); threshFilter->Update(); mask = threshFilter->GetOutput(); mask->DisconnectPipeline(); } cout << "Generating contrast images" << endl; vector<QI::ImageF::Pointer> conImages(3, ITK_NULLPTR); int ind = 0; for (int i1 = 0; i1 < 3; i1++) { for (int i2 = (i1 + 1); i2 < 3; i2++) { auto mp2rage_filter = itk::BinaryFunctorImageFilter<QI::ImageXF, QI::ImageXF, QI::ImageXF, MP2Contrast<float>>::New(); mp2rage_filter->SetInput1(vols[i1]->GetOutput()); mp2rage_filter->SetInput2(vols[i2]->GetOutput()); auto mask_filter = itk::MaskImageFilter<QI::ImageXF, QI::ImageF, QI::ImageXF>::New(); mask_filter->SetInput1(mp2rage_filter->GetOutput()); mask_filter->SetMaskImage(mask); mask_filter->Update(); string outName = outPrefix + "MP3_C" + to_string(i1) + to_string(i2) + QI::OutExt(); auto realFilter = itk::ComplexToRealImageFilter<QI::ImageXF, QI::ImageF>::New(); realFilter->SetInput(mask_filter->GetOutput()); realFilter->Update(); conImages[ind] = realFilter->GetOutput(); conImages[ind]->DisconnectPipeline(); if (complex_output) { QI::writeResult<QI::ImageXF>(mask_filter->GetOutput(), outName); } else { QI::writeResult<QI::ImageF>(realFilter->GetOutput(), outName); } ind++; } } cout << "Attempting quantitative bit" << endl; auto apply = itk::ApplyAlgorithmFilter<MP3LookupAlgo>::New(); auto lookup = make_shared<MP3LookupAlgo>(); apply->SetAlgorithm(lookup); typedef itk::ComposeImageFilter<QI::ImageF, QI::VectorImageF> ComposeType; auto composer = ComposeType::New(); composer->SetInput(0, conImages[0]); composer->SetInput(1, conImages[1]); composer->SetInput(2, conImages[2]); apply->SetInput(0, composer->GetOutput()); apply->SetMask(mask); apply->Update(); QI::writeResult(apply->GetOutput(0), outPrefix + "MP3_T1" + QI::OutExt()); QI::writeResult(apply->GetOutput(1), outPrefix + "MP3_B1" + QI::OutExt()); QI::writeResult(apply->GetOutput(2), outPrefix + "MP3_eta" + QI::OutExt()); if (verbose) cout << "Finished." << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#pragma once #include <boost/hana/ext/boost/mpl/vector.hpp> #include <boost/hana/for_each.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/map.hpp> #include <boost/hana/not_equal.hpp> #include <boost/hana/pair.hpp> #include <boost/hana/second.hpp> #include <boost/hana/size.hpp> #include <boost/hana/take_while.hpp> #include <boost/hana/transform.hpp> #include <boost/hana/tuple.hpp> #include <boost/hana/type.hpp> #include <boost/hana/zip.hpp> #include <boost/lexical_cast.hpp> #include <boost/variant.hpp> #include <algorithm> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> namespace opossum { namespace hana = boost::hana; using ChunkID = uint32_t; using ChunkOffset = uint32_t; struct RowID { ChunkID chunk_id; ChunkOffset chunk_offset; bool operator<(const RowID &rhs) const { return std::tie(chunk_id, chunk_offset) < std::tie(rhs.chunk_id, rhs.chunk_offset); } }; constexpr ChunkOffset INVALID_CHUNK_OFFSET = std::numeric_limits<ChunkOffset>::max(); using ColumnID = uint16_t; using ValueID = uint32_t; // Cannot be larger than ChunkOffset using WorkerID = uint32_t; using NodeID = uint32_t; using TaskID = uint32_t; using CpuID = uint32_t; using CommitID = uint32_t; using TransactionID = uint32_t; using StringLength = uint16_t; // The length of column value strings must fit in this type. using ColumnNameLength = uint8_t; // The length of column names must fit in this type. using AttributeVectorWidth = uint8_t; using PosList = std::vector<RowID>; class ColumnName { public: explicit ColumnName(const std::string &name) : _name(name) {} operator std::string() const { return _name; } protected: const std::string _name; }; constexpr NodeID INVALID_NODE_ID = std::numeric_limits<NodeID>::max(); constexpr TaskID INVALID_TASK_ID = std::numeric_limits<TaskID>::max(); constexpr CpuID INVALID_CPU_ID = std::numeric_limits<CpuID>::max(); constexpr WorkerID INVALID_WORKER_ID = std::numeric_limits<WorkerID>::max(); constexpr NodeID CURRENT_NODE_ID = std::numeric_limits<NodeID>::max() - 1; // The Scheduler currently supports just these 2 priorities, subject to change. enum class SchedulePriority { Normal = 1, // Schedule task at the end of the queue High = 0 // Schedule task at the beginning of the queue }; /** * Only the following three lines are needed wherever AllTypeVariant is used. * This could be one header file. * @{ */ // This holds all possible data types. static constexpr auto types = hana::make_tuple(hana::type_c<int32_t>, hana::type_c<int64_t>, hana::type_c<float>, hana::type_c<double>, hana::type_c<std::string>); // Convert tuple to mpl vector using TypesAsMplVector = decltype(hana::to<hana::ext::boost::mpl::vector_tag>(types)); // Create boost::variant from mpl vector using AllTypeVariant = typename boost::make_variant_over<TypesAsMplVector>::type; /** @} */ /** * AllParameterVariant holds either an AllTypeVariant or a ColumnName. * It should be used to generalize Opossum operator calls. */ static auto parameter_types = hana::make_tuple(hana::make_pair("AllTypeVariant", AllTypeVariant(123)), hana::make_pair("ColumnName", ColumnName("column_name"))); // convert tuple of all types to sequence by first extracting the prototypes only and then applying decltype_ static auto parameter_types_as_hana_sequence = hana::transform(hana::transform(parameter_types, hana::second), hana::decltype_); // convert hana sequence to mpl vector using ParameterTypesAsMplVector = decltype(hana::to<hana::ext::boost::mpl::vector_tag>(parameter_types_as_hana_sequence)); // create boost::variant from mpl vector using AllParameterVariant = typename boost::make_variant_over<ParameterTypesAsMplVector>::type; /** * This is everything needed for type_cast * @{ */ namespace { // Returns the index of type T in an Iterable template <typename Sequence, typename T> constexpr auto index_of(Sequence const &sequence, T const &element) { constexpr auto size = decltype(hana::size(hana::take_while(sequence, hana::not_equal.to(element)))){}; return decltype(size)::value; } // Negates a type trait template <bool Condition> struct _neg : public std::true_type {}; template <> struct _neg<true> : public std::false_type {}; template <typename Condition> struct neg : public _neg<Condition::value> {}; // Wrapper that makes std::enable_if a bit more readable template <typename Condition, typename Type = void> using enable_if = typename std::enable_if<Condition::value, Type>::type; } // namespace // Retrieves the value stored in an AllTypeVariant without conversion template <typename T> const T &get(const AllTypeVariant &value) { static_assert(hana::contains(types, hana::type_c<T>), "Type not in AllTypeVariant"); return boost::get<T>(value); } // cast methods - from variant to specific type // Template specialization for everything but integral types template <typename T> enable_if<neg<std::is_integral<T>>, T> type_cast(const AllTypeVariant &value) { if (value.which() == index_of(types, hana::type_c<T>)) return get<T>(value); return boost::lexical_cast<T>(value); } // Template specialization for integral types template <typename T> enable_if<std::is_integral<T>, T> type_cast(const AllTypeVariant &value) { if (value.which() == index_of(types, hana::type_c<T>)) return get<T>(value); try { return boost::lexical_cast<T>(value); } catch (...) { return boost::numeric_cast<T>(boost::lexical_cast<double>(value)); } } std::string to_string(const AllTypeVariant &x); /** @} */ /** * This is everything needed for make_*_by_column_type to work. * It needs to include the AllVariantType header and could also * be moved into a separate header. * @{ */ namespace { // Functor that converts tuples with size two into pairs struct to_pair_t { template <typename Tuple> constexpr decltype(auto) operator()(Tuple &&tuple) const { return hana::make_pair(hana::at_c<0>(tuple), hana::at_c<1>(tuple)); } }; constexpr to_pair_t to_pair{}; } // namespace static constexpr auto type_strings = hana::make_tuple("int", "long", "float", "double", "string"); // “Zips” the types and type_strings tuples creating a tuple of string-type pairs static constexpr auto column_types = hana::transform(hana::zip(type_strings, types), to_pair); template <class base, template <typename...> class impl, class... TemplateArgs, typename... ConstructorArgs> std::unique_ptr<base> make_unique_by_column_type(const std::string &type, ConstructorArgs &&... args) { std::unique_ptr<base> ret = nullptr; hana::for_each(column_types, [&](auto x) { if (std::string(hana::first(x)) == type) { // The + before hana::second - which returns a reference - converts its return value // into a value so that we can access ::type using column_type = typename decltype(+hana::second(x))::type; ret = std::make_unique<impl<column_type, TemplateArgs...>>(std::forward<ConstructorArgs>(args)...); return; } }); if (IS_DEBUG && !ret) throw std::runtime_error("unknown type " + type); return ret; } /** * We need to pass parameter packs explicitly for GCC due to the following bug: * http://stackoverflow.com/questions/41769851/gcc-causes-segfault-for-lambda-captured-parameter-pack */ template <class base, template <typename...> class impl, class... TemplateArgs, typename... ConstructorArgs> std::unique_ptr<base> make_unique_by_column_types(const std::string &type1, const std::string &type2, ConstructorArgs &&... args) { std::unique_ptr<base> ret = nullptr; hana::for_each(column_types, [&ret, &type1, &type2, &args...](auto x) { if (std::string(hana::first(x)) == type1) { hana::for_each(column_types, [&ret, &type1, &type2, &args...](auto y) { if (std::string(hana::first(y)) == type2) { using column_type1 = typename decltype(+hana::second(x))::type; using column_type2 = typename decltype(+hana::second(y))::type; ret = std::make_unique<impl<column_type1, column_type2, TemplateArgs...>>( std::forward<ConstructorArgs>(args)...); return; } }); return; } }); if (IS_DEBUG && !ret) throw std::runtime_error("unknown type " + type1 + " or " + type2); return ret; } template <class base, template <typename...> class impl, class... TemplateArgs, class... ConstructorArgs> std::shared_ptr<base> make_shared_by_column_type(const std::string &type, ConstructorArgs &&... args) { return make_unique_by_column_type<base, impl, TemplateArgs...>(type, std::forward<ConstructorArgs>(args)...); } /** @} */ } // namespace opossum <commit_msg>Put column types and string representation into explicitly declared tuple of pairs<commit_after>#pragma once #include <boost/hana/ext/boost/mpl/vector.hpp> #include <boost/hana/for_each.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/map.hpp> #include <boost/hana/not_equal.hpp> #include <boost/hana/pair.hpp> #include <boost/hana/second.hpp> #include <boost/hana/size.hpp> #include <boost/hana/take_while.hpp> #include <boost/hana/transform.hpp> #include <boost/hana/tuple.hpp> #include <boost/hana/type.hpp> #include <boost/hana/zip.hpp> #include <boost/lexical_cast.hpp> #include <boost/variant.hpp> #include <algorithm> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> namespace opossum { namespace hana = boost::hana; using ChunkID = uint32_t; using ChunkOffset = uint32_t; struct RowID { ChunkID chunk_id; ChunkOffset chunk_offset; bool operator<(const RowID &rhs) const { return std::tie(chunk_id, chunk_offset) < std::tie(rhs.chunk_id, rhs.chunk_offset); } }; constexpr ChunkOffset INVALID_CHUNK_OFFSET = std::numeric_limits<ChunkOffset>::max(); using ColumnID = uint16_t; using ValueID = uint32_t; // Cannot be larger than ChunkOffset using WorkerID = uint32_t; using NodeID = uint32_t; using TaskID = uint32_t; using CpuID = uint32_t; using CommitID = uint32_t; using TransactionID = uint32_t; using StringLength = uint16_t; // The length of column value strings must fit in this type. using ColumnNameLength = uint8_t; // The length of column names must fit in this type. using AttributeVectorWidth = uint8_t; using PosList = std::vector<RowID>; class ColumnName { public: explicit ColumnName(const std::string &name) : _name(name) {} operator std::string() const { return _name; } protected: const std::string _name; }; constexpr NodeID INVALID_NODE_ID = std::numeric_limits<NodeID>::max(); constexpr TaskID INVALID_TASK_ID = std::numeric_limits<TaskID>::max(); constexpr CpuID INVALID_CPU_ID = std::numeric_limits<CpuID>::max(); constexpr WorkerID INVALID_WORKER_ID = std::numeric_limits<WorkerID>::max(); constexpr NodeID CURRENT_NODE_ID = std::numeric_limits<NodeID>::max() - 1; // The Scheduler currently supports just these 2 priorities, subject to change. enum class SchedulePriority { Normal = 1, // Schedule task at the end of the queue High = 0 // Schedule task at the beginning of the queue }; /** * Only the following lines are needed wherever AllTypeVariant is used. * This could be one header file. * @{ */ // This holds pairs of all types and their respective string representation static constexpr auto column_types = hana::make_tuple(hana::make_pair("int", hana::type_c<int32_t>), hana::make_pair("long", hana::type_c<int64_t>), hana::make_pair("float", hana::type_c<float>), hana::make_pair("double", hana::type_c<double>), hana::make_pair("string", hana::type_c<std::string>)); // This holds only the possible data types. static constexpr auto types = hana::transform(column_types, hana::second); // Convert tuple to mpl vector using TypesAsMplVector = decltype(hana::to<hana::ext::boost::mpl::vector_tag>(types)); // Create boost::variant from mpl vector using AllTypeVariant = typename boost::make_variant_over<TypesAsMplVector>::type; /** @} */ /** * AllParameterVariant holds either an AllTypeVariant or a ColumnName. * It should be used to generalize Opossum operator calls. */ static auto parameter_types = hana::make_tuple(hana::make_pair("AllTypeVariant", AllTypeVariant(123)), hana::make_pair("ColumnName", ColumnName("column_name"))); // convert tuple of all types to sequence by first extracting the prototypes only and then applying decltype_ static auto parameter_types_as_hana_sequence = hana::transform(hana::transform(parameter_types, hana::second), hana::decltype_); // convert hana sequence to mpl vector using ParameterTypesAsMplVector = decltype(hana::to<hana::ext::boost::mpl::vector_tag>(parameter_types_as_hana_sequence)); // create boost::variant from mpl vector using AllParameterVariant = typename boost::make_variant_over<ParameterTypesAsMplVector>::type; /** * This is everything needed for type_cast * @{ */ namespace { // Returns the index of type T in an Iterable template <typename Sequence, typename T> constexpr auto index_of(Sequence const &sequence, T const &element) { constexpr auto size = decltype(hana::size(hana::take_while(sequence, hana::not_equal.to(element)))){}; return decltype(size)::value; } // Negates a type trait template <bool Condition> struct _neg : public std::true_type {}; template <> struct _neg<true> : public std::false_type {}; template <typename Condition> struct neg : public _neg<Condition::value> {}; // Wrapper that makes std::enable_if a bit more readable template <typename Condition, typename Type = void> using enable_if = typename std::enable_if<Condition::value, Type>::type; } // namespace // Retrieves the value stored in an AllTypeVariant without conversion template <typename T> const T &get(const AllTypeVariant &value) { static_assert(hana::contains(types, hana::type_c<T>), "Type not in AllTypeVariant"); return boost::get<T>(value); } // cast methods - from variant to specific type // Template specialization for everything but integral types template <typename T> enable_if<neg<std::is_integral<T>>, T> type_cast(const AllTypeVariant &value) { if (value.which() == index_of(types, hana::type_c<T>)) return get<T>(value); return boost::lexical_cast<T>(value); } // Template specialization for integral types template <typename T> enable_if<std::is_integral<T>, T> type_cast(const AllTypeVariant &value) { if (value.which() == index_of(types, hana::type_c<T>)) return get<T>(value); try { return boost::lexical_cast<T>(value); } catch (...) { return boost::numeric_cast<T>(boost::lexical_cast<double>(value)); } } std::string to_string(const AllTypeVariant &x); /** @} */ /** * This is everything needed for make_*_by_column_type to work. * It needs to include the AllVariantType header and could also * be moved into a separate header. * @{ */ template <class base, template <typename...> class impl, class... TemplateArgs, typename... ConstructorArgs> std::unique_ptr<base> make_unique_by_column_type(const std::string &type, ConstructorArgs &&... args) { std::unique_ptr<base> ret = nullptr; hana::for_each(column_types, [&](auto x) { if (std::string(hana::first(x)) == type) { // The + before hana::second - which returns a reference - converts its return value // into a value so that we can access ::type using column_type = typename decltype(+hana::second(x))::type; ret = std::make_unique<impl<column_type, TemplateArgs...>>(std::forward<ConstructorArgs>(args)...); return; } }); if (IS_DEBUG && !ret) throw std::runtime_error("unknown type " + type); return ret; } /** * We need to pass parameter packs explicitly for GCC due to the following bug: * http://stackoverflow.com/questions/41769851/gcc-causes-segfault-for-lambda-captured-parameter-pack */ template <class base, template <typename...> class impl, class... TemplateArgs, typename... ConstructorArgs> std::unique_ptr<base> make_unique_by_column_types(const std::string &type1, const std::string &type2, ConstructorArgs &&... args) { std::unique_ptr<base> ret = nullptr; hana::for_each(column_types, [&ret, &type1, &type2, &args...](auto x) { if (std::string(hana::first(x)) == type1) { hana::for_each(column_types, [&ret, &type1, &type2, &args...](auto y) { if (std::string(hana::first(y)) == type2) { using column_type1 = typename decltype(+hana::second(x))::type; using column_type2 = typename decltype(+hana::second(y))::type; ret = std::make_unique<impl<column_type1, column_type2, TemplateArgs...>>( std::forward<ConstructorArgs>(args)...); return; } }); return; } }); if (IS_DEBUG && !ret) throw std::runtime_error("unknown type " + type1 + " or " + type2); return ret; } template <class base, template <typename...> class impl, class... TemplateArgs, class... ConstructorArgs> std::shared_ptr<base> make_shared_by_column_type(const std::string &type, ConstructorArgs &&... args) { return make_unique_by_column_type<base, impl, TemplateArgs...>(type, std::forward<ConstructorArgs>(args)...); } /** @} */ } // namespace opossum <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan [email protected] Contact: Nokia Corporation [email protected] Contact: Nokia Corporation [email protected] You may use this file under the terms of the BSD license as follows: 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 Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #include <QApplication> #include <QNetworkProxy> #include <QNetworkConfigurationManager> #include <QNetworkSession> #include "qtsingleapplication.h" #include "mainwindow.h" #include "mediaserver.h" #include "qmh-config.h" static QNetworkSession *g_networkSession = 0; static void setupNetwork() { QNetworkProxy proxy; if (Config::isEnabled("proxy", false)) { QString proxyHost(Config::value("proxy-host", "localhost").toString()); int proxyPort = Config::value("proxy-port", 8080); proxy.setType(QNetworkProxy::HttpProxy); proxy.setHostName(proxyHost); proxy.setPort(proxyPort); QNetworkProxy::setApplicationProxy(proxy); qWarning() << "Using proxy host" << proxyHost << "on port" << proxyPort; } // Set Internet Access Point QNetworkConfigurationManager mgr; QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations(); if (activeConfigs.count() <= 0) return; QNetworkConfiguration cfg = activeConfigs.at(0); foreach(QNetworkConfiguration config, activeConfigs) { if (config.type() == QNetworkConfiguration::UserChoice) { cfg = config; break; } } g_networkSession = new QNetworkSession(cfg); g_networkSession->open(); g_networkSession->waitForOpened(-1); } int main(int argc, char** argv) { QApplication::setGraphicsSystem("raster"); QtSingleApplication app(argc, argv); app.setApplicationName("qtmediahub"); app.setOrganizationName("Nokia"); app.setOrganizationDomain("nokia.com"); setupNetwork(); bool primarySession = !app.isRunning(); if (!(Config::isEnabled("multi-instance", false) || primarySession)) { qWarning() << app.applicationName() << "is already running, aborting"; return false; } Config::init(argc, argv); MainWindow *mainWindow = 0; MediaServer *mediaServer = 0; if (!Config::isEnabled("headless", qgetenv("DISPLAY").isEmpty())) { mainWindow = new MainWindow; mainWindow->setAttribute(Qt::WA_DeleteOnClose); mainWindow->setSkin(Config::value("skin", "").toString()); mainWindow->show(); } else { mediaServer = new MediaServer; } int ret = app.exec(); g_networkSession->close(); delete mainWindow; delete mediaServer; return ret; } <commit_msg>Revert "Destroy MainWindow correctly"<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan [email protected] Contact: Nokia Corporation [email protected] Contact: Nokia Corporation [email protected] You may use this file under the terms of the BSD license as follows: 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 Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #include <QApplication> #include <QNetworkProxy> #include <QNetworkConfigurationManager> #include <QNetworkSession> #include "qtsingleapplication.h" #include "mainwindow.h" #include "mediaserver.h" #include "qmh-config.h" static QNetworkSession *g_networkSession = 0; static void setupNetwork() { QNetworkProxy proxy; if (Config::isEnabled("proxy", false)) { QString proxyHost(Config::value("proxy-host", "localhost").toString()); int proxyPort = Config::value("proxy-port", 8080); proxy.setType(QNetworkProxy::HttpProxy); proxy.setHostName(proxyHost); proxy.setPort(proxyPort); QNetworkProxy::setApplicationProxy(proxy); qWarning() << "Using proxy host" << proxyHost << "on port" << proxyPort; } // Set Internet Access Point QNetworkConfigurationManager mgr; QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations(); if (activeConfigs.count() <= 0) return; QNetworkConfiguration cfg = activeConfigs.at(0); foreach(QNetworkConfiguration config, activeConfigs) { if (config.type() == QNetworkConfiguration::UserChoice) { cfg = config; break; } } g_networkSession = new QNetworkSession(cfg); g_networkSession->open(); g_networkSession->waitForOpened(-1); } int main(int argc, char** argv) { QApplication::setGraphicsSystem("raster"); QtSingleApplication app(argc, argv); app.setApplicationName("qtmediahub"); app.setOrganizationName("Nokia"); app.setOrganizationDomain("nokia.com"); setupNetwork(); bool primarySession = !app.isRunning(); if (!(Config::isEnabled("multi-instance", false) || primarySession)) { qWarning() << app.applicationName() << "is already running, aborting"; return false; } Config::init(argc, argv); MediaServer *mediaServer = 0; if (!Config::isEnabled("headless", qgetenv("DISPLAY").isEmpty())) { MainWindow *mainWindow = new MainWindow; mainWindow->setAttribute(Qt::WA_DeleteOnClose); mainWindow->setSkin(Config::value("skin", "").toString()); mainWindow->show(); } else { mediaServer = new MediaServer; } int ret = app.exec(); g_networkSession->close(); delete mediaServer; return ret; } <|endoftext|>
<commit_before>#include "mainframe.hpp" #include "constants.hpp" #include "menubar.hpp" #include "notebook.hpp" #include "preferences/preferencespagepaths.hpp" MainFrame::MainFrame(Settings *settings) : wxFrame(NULL, wxID_ANY, PROGRAM_NAME, wxDefaultPosition, wxSize(WINDOW_WIDTH, WINDOW_HEIGHT)) { m_preferencesEditor = NULL; m_settings = settings; CreateStatusBar(); SetStatusText("Welcome"); MenuBar *menuBar = new MenuBar(); menuBar->Bind(wxEVT_MENU, &MainFrame::OnMenuBarItemClicked, this); SetMenuBar(menuBar); wxPanel *notebookPanel = new wxPanel(this); wxBoxSizer *notebookPanelSizer = new wxBoxSizer(wxVERTICAL); m_notebook = new Notebook(notebookPanel, *this); m_notebook->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, &MainFrame::OnNotebookPageChanged, this); m_displayFrame = new DisplayFrame(this); m_displayFrame->Show(); // When the frame is closed, we want to update menu bar. m_displayFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); // When a checkbox belonging to this frame gets (un)checked, we want to update what is being drawn in the current workspace. m_displayFrame->Bind(wxEVT_CHECKBOX, &MainFrame::OnDisplayFrameCheckBoxClicked, this); m_paletteFrame = new PaletteFrame(this); m_paletteFrame->Show(); m_paletteFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); m_toolbarFrame = new ToolbarFrame(this, [&](int toolId) { m_notebook->OnToolSelected(toolId); }); m_toolbarFrame->Show(); m_toolbarFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); m_sceneryFrame = new SceneryFrame(this); m_sceneryFrame->Show(); m_sceneryFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); notebookPanelSizer->Add(m_notebook, 1, wxEXPAND); notebookPanel->SetSizer(notebookPanelSizer); AddWorkspace(m_settings->GetSoldatPath() + "maps/test.pms"); } MainFrame::~MainFrame() { // Fix for segmentation fault after closing the program with at least 2 tabs opened. m_notebook->Unbind(wxEVT_NOTEBOOK_PAGE_CHANGED, &MainFrame::OnNotebookPageChanged, this); if (m_preferencesEditor) { m_preferencesEditor->Dismiss(); } } void MainFrame::AddWorkspace(wxString mapPath) { try { m_notebook->AddWorkspace(*m_settings, mapPath); } catch (const std::runtime_error& error) { wxMessageBox(error.what(), "Workspace construction failed."); Close(true); return; } } void MainFrame::OnBackgroundColorChanged(wxColourPickerEvent &event) { m_notebook->SetBackgroundColors(m_mapSettingsDialog->GetBackgroundBottomColor(), m_mapSettingsDialog->GetBackgroundTopColor()); } void MainFrame::OnDisplayFrameCheckBoxClicked(wxCommandEvent &event) { int displaySetting = event.GetId(); bool isChecked = event.IsChecked(); m_notebook->SetCurrentDisplaySetting(displaySetting, isChecked); } void MainFrame::OnMenuBarItemClicked(wxCommandEvent &event) { wxWindowID menuBarItemId = event.GetId(); switch (menuBarItemId) { case ID_MENU_FILE_NEW: AddWorkspace(wxEmptyString); break; case ID_MENU_FILE_OPEN_COMPILED: { wxString path = wxFileSelector(wxT("Open PMS file"), wxEmptyString, wxEmptyString, wxEmptyString, wxT("*.pms"), wxFD_FILE_MUST_EXIST); if (!path.IsEmpty()) { AddWorkspace(path); } } break; case ID_MENU_FILE_SAVE_AS_PMS: { wxString path = wxFileSelector(wxT("Save as PMS"), m_settings->GetSoldatPath() + "maps/", wxEmptyString, wxT(".pms"), wxT("*.pms"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (!path.IsEmpty()) { m_notebook->SaveCurrentMapAsPMS(path); } } break; case ID_MENU_EDIT_SELECT_ALL: m_notebook->SelectAll(); break; case ID_MENU_EDIT_MAP_SETTINGS: { m_mapSettingsDialog = new MapSettingsDialog(this, m_notebook->GetCurrentMap(), m_settings->GetSoldatPath()); m_mapSettingsDialog->GetBackgroundBottomColorPicker()->Bind(wxEVT_COLOURPICKER_CHANGED, &MainFrame::OnBackgroundColorChanged, this); m_mapSettingsDialog->GetBackgroundTopColorPicker()->Bind(wxEVT_COLOURPICKER_CHANGED, &MainFrame::OnBackgroundColorChanged, this); m_mapSettingsDialog->GetTextureChoice()->Bind(wxEVT_CHOICE, &MainFrame::OnPolygonsTextureChanged, this); m_mapSettingsDialog->ShowModal(); } break; case ID_MENU_EDIT_PREFERENCES: m_preferencesEditor = new wxPreferencesEditor(); m_preferencesEditor->AddPage(new PreferencesPagePaths(m_settings)); m_preferencesEditor->Show(this); break; case ID_MENU_WINDOWS_SHOW_ALL: ShowAllMiniFrames(true); break; case ID_MENU_WINDOWS_HIDE_ALL: ShowAllMiniFrames(false); break; case ID_MENU_WINDOWS_DISPLAY: m_displayFrame->ToggleVisibility(); break; case ID_MENU_WINDOWS_PALETTE: m_paletteFrame->ToggleVisibility(); break; case ID_MENU_WINDOWS_TOOLBAR: m_toolbarFrame->ToggleVisibility(); break; case ID_MENU_WINDOWS_SCENERY: m_sceneryFrame->ToggleVisibility(); break; } // Pass the event to following event handler. event.Skip(); } void MainFrame::OnNotebookPageChanged(wxBookCtrlEvent &event) { m_displayFrame->UpdateCheckBoxes(m_notebook->GetCurrentDisplaySettings()); event.Skip(); } void MainFrame::OnPolygonsTextureChanged(wxCommandEvent &event) { wxString textureFilename = event.GetString(); m_notebook->SetPolygonsTexture(textureFilename); } void MainFrame::ShowAllMiniFrames(bool show) { m_displayFrame->Show(show); m_paletteFrame->Show(show); m_toolbarFrame->Show(show); m_sceneryFrame->Show(show); } <commit_msg>Loading blank map on first opening instead of test.pms<commit_after>#include "mainframe.hpp" #include "constants.hpp" #include "menubar.hpp" #include "notebook.hpp" #include "preferences/preferencespagepaths.hpp" MainFrame::MainFrame(Settings *settings) : wxFrame(NULL, wxID_ANY, PROGRAM_NAME, wxDefaultPosition, wxSize(WINDOW_WIDTH, WINDOW_HEIGHT)) { m_preferencesEditor = NULL; m_settings = settings; CreateStatusBar(); SetStatusText("Welcome"); MenuBar *menuBar = new MenuBar(); menuBar->Bind(wxEVT_MENU, &MainFrame::OnMenuBarItemClicked, this); SetMenuBar(menuBar); wxPanel *notebookPanel = new wxPanel(this); wxBoxSizer *notebookPanelSizer = new wxBoxSizer(wxVERTICAL); m_notebook = new Notebook(notebookPanel, *this); m_notebook->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, &MainFrame::OnNotebookPageChanged, this); m_displayFrame = new DisplayFrame(this); m_displayFrame->Show(); // When the frame is closed, we want to update menu bar. m_displayFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); // When a checkbox belonging to this frame gets (un)checked, we want to update what is being drawn in the current workspace. m_displayFrame->Bind(wxEVT_CHECKBOX, &MainFrame::OnDisplayFrameCheckBoxClicked, this); m_paletteFrame = new PaletteFrame(this); m_paletteFrame->Show(); m_paletteFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); m_toolbarFrame = new ToolbarFrame(this, [&](int toolId) { m_notebook->OnToolSelected(toolId); }); m_toolbarFrame->Show(); m_toolbarFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); m_sceneryFrame = new SceneryFrame(this); m_sceneryFrame->Show(); m_sceneryFrame->Bind(wxEVT_CLOSE_WINDOW, &MenuBar::OnFrameClosed, menuBar); notebookPanelSizer->Add(m_notebook, 1, wxEXPAND); notebookPanel->SetSizer(notebookPanelSizer); AddWorkspace(wxString()); } MainFrame::~MainFrame() { // Fix for segmentation fault after closing the program with at least 2 tabs opened. m_notebook->Unbind(wxEVT_NOTEBOOK_PAGE_CHANGED, &MainFrame::OnNotebookPageChanged, this); if (m_preferencesEditor) { m_preferencesEditor->Dismiss(); } } void MainFrame::AddWorkspace(wxString mapPath) { try { m_notebook->AddWorkspace(*m_settings, mapPath); } catch (const std::runtime_error& error) { wxMessageBox(error.what(), "Workspace construction failed."); Close(true); return; } } void MainFrame::OnBackgroundColorChanged(wxColourPickerEvent &event) { m_notebook->SetBackgroundColors(m_mapSettingsDialog->GetBackgroundBottomColor(), m_mapSettingsDialog->GetBackgroundTopColor()); } void MainFrame::OnDisplayFrameCheckBoxClicked(wxCommandEvent &event) { int displaySetting = event.GetId(); bool isChecked = event.IsChecked(); m_notebook->SetCurrentDisplaySetting(displaySetting, isChecked); } void MainFrame::OnMenuBarItemClicked(wxCommandEvent &event) { wxWindowID menuBarItemId = event.GetId(); switch (menuBarItemId) { case ID_MENU_FILE_NEW: AddWorkspace(wxEmptyString); break; case ID_MENU_FILE_OPEN_COMPILED: { wxString path = wxFileSelector(wxT("Open PMS file"), wxEmptyString, wxEmptyString, wxEmptyString, wxT("*.pms"), wxFD_FILE_MUST_EXIST); if (!path.IsEmpty()) { AddWorkspace(path); } } break; case ID_MENU_FILE_SAVE_AS_PMS: { wxString path = wxFileSelector(wxT("Save as PMS"), m_settings->GetSoldatPath() + "maps/", wxEmptyString, wxT(".pms"), wxT("*.pms"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (!path.IsEmpty()) { m_notebook->SaveCurrentMapAsPMS(path); } } break; case ID_MENU_EDIT_SELECT_ALL: m_notebook->SelectAll(); break; case ID_MENU_EDIT_MAP_SETTINGS: { m_mapSettingsDialog = new MapSettingsDialog(this, m_notebook->GetCurrentMap(), m_settings->GetSoldatPath()); m_mapSettingsDialog->GetBackgroundBottomColorPicker()->Bind(wxEVT_COLOURPICKER_CHANGED, &MainFrame::OnBackgroundColorChanged, this); m_mapSettingsDialog->GetBackgroundTopColorPicker()->Bind(wxEVT_COLOURPICKER_CHANGED, &MainFrame::OnBackgroundColorChanged, this); m_mapSettingsDialog->GetTextureChoice()->Bind(wxEVT_CHOICE, &MainFrame::OnPolygonsTextureChanged, this); m_mapSettingsDialog->ShowModal(); } break; case ID_MENU_EDIT_PREFERENCES: m_preferencesEditor = new wxPreferencesEditor(); m_preferencesEditor->AddPage(new PreferencesPagePaths(m_settings)); m_preferencesEditor->Show(this); break; case ID_MENU_WINDOWS_SHOW_ALL: ShowAllMiniFrames(true); break; case ID_MENU_WINDOWS_HIDE_ALL: ShowAllMiniFrames(false); break; case ID_MENU_WINDOWS_DISPLAY: m_displayFrame->ToggleVisibility(); break; case ID_MENU_WINDOWS_PALETTE: m_paletteFrame->ToggleVisibility(); break; case ID_MENU_WINDOWS_TOOLBAR: m_toolbarFrame->ToggleVisibility(); break; case ID_MENU_WINDOWS_SCENERY: m_sceneryFrame->ToggleVisibility(); break; } // Pass the event to following event handler. event.Skip(); } void MainFrame::OnNotebookPageChanged(wxBookCtrlEvent &event) { m_displayFrame->UpdateCheckBoxes(m_notebook->GetCurrentDisplaySettings()); event.Skip(); } void MainFrame::OnPolygonsTextureChanged(wxCommandEvent &event) { wxString textureFilename = event.GetString(); m_notebook->SetPolygonsTexture(textureFilename); } void MainFrame::ShowAllMiniFrames(bool show) { m_displayFrame->Show(show); m_paletteFrame->Show(show); m_toolbarFrame->Show(show); m_sceneryFrame->Show(show); } <|endoftext|>
<commit_before>#include <stdint.h> namespace moonsniff { uint8_t test_ctr = 0; static uint8_t getCtr(){ return test_ctr; } static void incrementCtr(){ ++test_ctr; } } extern "C" { uint8_t ms_getCtr(){ return moonsniff::getCtr(); } void ms_incrementCtr(){ moonsniff::incrementCtr(); } } <commit_msg>implement basic ring_buffer<commit_after>#include <stdint.h> #define BUFFER_SIZE 256 namespace moonsniff { uint8_t test_ctr = 0; static uint8_t getCtr(){ return test_ctr; } static void incrementCtr(){ ++test_ctr; } // buffer holds the idetification values of packets // value 0 is reserved as unused/invalid uint16_t ring_buffer[BUFFER_SIZE] = {0}; // next free entry in ring_buffer uint8_t head; // last entry which is currently part of the window uint8_t tail; // size of the active window uint8_t window uint32_t hits = 0; uint32_t misses = 0; static void init_buffer(uint8_t window_size){ tail = 0; head = window_size; } static void advance_window(){ ++head; ++tail; } static void add_entry(uint16_t identification){ ring_buffer[head] = identification; advance_window(); } static void test_for(uint16_t identification){ if(tail < head){ for(uint8_t i = tail; i < head; ++i){ if(ring_buffer[i] == identification){ ring_buffer[i] = 0; ++hits; return; } } }else if(head < tail){ for(uint8_t i = tail; i < BUFFER_SIZE; ++i){ if(ring_buffer[i] == identification){ ring_buffer[i] = 0; ++hits; return; } } for(uint8_t i = 0; i < head; ++i){ if(ring_buffer[i] == identification){ ring_buffer[i] = 0; ++hits; return; } } } // the identification is not part of the current window ++misses; } } extern "C" { uint8_t ms_getCtr(){ return moonsniff::getCtr(); } void ms_incrementCtr(){ moonsniff::incrementCtr(); } void ms_init_buffer(uint8_t window_size){ moonsniff::init_buffer(window_size); } void ms_add_entry(uint16_t identification){ moonsniff::add_entry(identification); } void ms_test_for(uint16_t identification){ moonsniff::test_for(identification); } } <|endoftext|>
<commit_before>#include "mpd_client.h" #include <iostream> #include <absl/strings/str_format.h> #include <mpd/capabilities.h> #include <mpd/connection.h> #include <mpd/database.h> #include <mpd/error.h> #include <mpd/idle.h> #include <mpd/pair.h> #include <mpd/password.h> #include <mpd/player.h> #include <mpd/protocol.h> #include <mpd/queue.h> #include <mpd/recv.h> #include <mpd/search.h> #include <mpd/song.h> #include <mpd/status.h> #include "mpd.h" #include "util.h" namespace ashuffle { namespace mpd { namespace client { namespace { using Authorization = mpd::MPD::Authorization; class TagParserImpl : public TagParser { public: // Parse parses the given tag, and returns the appropriate tag type. // If no matching tag is found, then an empty optional is returned. std::optional<enum mpd_tag_type> Parse( const std::string_view tag) const override; }; std::optional<enum mpd_tag_type> TagParserImpl::Parse( const std::string_view tag_name) const { std::string name_with_null(tag_name); enum mpd_tag_type tag = mpd_tag_name_iparse(name_with_null.data()); if (tag == MPD_TAG_UNKNOWN) { return std::nullopt; } return tag; } class SongImpl : public Song { public: // Create a new song based on the given mpd_song. SongImpl(struct mpd_song* song) : song_(song){}; // Song is pointer owning. We do not support copies. SongImpl(Song&) = delete; SongImpl& operator=(SongImpl&) = delete; // However, moves are OK, because the "old" owner no longer exists. SongImpl(SongImpl&&) = default; // Free the wrapped struct mpd_song; ~SongImpl() override; std::optional<std::string> Tag(enum mpd_tag_type tag) const override; std::string URI() const override; private: // The wrapped song. struct mpd_song* song_; }; SongImpl::~SongImpl() { mpd_song_free(song_); } std::optional<std::string> SongImpl::Tag(enum mpd_tag_type tag) const { const char* raw_value = mpd_song_get_tag(song_, tag, 0); if (raw_value == nullptr) { return std::nullopt; } return std::string(raw_value); } std::string SongImpl::URI() const { return mpd_song_get_uri(song_); } class StatusImpl : public Status { public: // Wrap the given mpd_status. StatusImpl(struct mpd_status* status) : status_(status){}; // StatusImpl is pointer owning. We do not support copies. StatusImpl(StatusImpl&) = delete; StatusImpl& operator=(StatusImpl&) = delete; // Moves are OK, because the "old" owner no longer exists. StatusImpl(StatusImpl&&) = default; StatusImpl& operator=(StatusImpl&&) = default; // Free the wrapped status. ~StatusImpl() override; unsigned QueueLength() const override; bool Single() const override; std::optional<int> SongPosition() const override; bool IsPlaying() const override; private: struct mpd_status* status_; }; StatusImpl::~StatusImpl() { mpd_status_free(status_); } unsigned StatusImpl::QueueLength() const { return mpd_status_get_queue_length(status_); } bool StatusImpl::Single() const { return mpd_status_get_single(status_); } std::optional<int> StatusImpl::SongPosition() const { int pos = mpd_status_get_song_pos(status_); if (pos == -1) { return std::nullopt; } return pos; } bool StatusImpl::IsPlaying() const { return mpd_status_get_state(status_) == MPD_STATE_PLAY; } // Forward declare SongReaderImpl for MPDImpl; class SongReaderImpl; class MPDImpl : public MPD { public: MPDImpl(struct mpd_connection* conn) : mpd_(conn){}; // MPDImpl owns the connection pointer, no copies possible. MPDImpl(MPDImpl&) = delete; MPDImpl& operator=(MPDImpl&) = delete; MPDImpl(MPDImpl&&) = default; MPDImpl& operator=(MPDImpl&&) = default; ~MPDImpl() override; void Pause() override; void Play() override; void PlayAt(unsigned position) override; std::unique_ptr<Status> CurrentStatus() override; std::unique_ptr<SongReader> ListAll() override; std::optional<std::unique_ptr<Song>> Search(std::string_view uri) override; IdleEventSet Idle(const IdleEventSet&) override; void Add(const std::string& uri) override; MPD::PasswordStatus ApplyPassword(const std::string& password) override; Authorization CheckCommands( const std::vector<std::string_view>& cmds) override; private: friend SongReaderImpl; struct mpd_connection* mpd_; // Exits the program, printing the current MPD connection error message. void Fail(); // Checks to see if the MPD connection has an error. If it does, it // calls Fail. void CheckFail(); }; class SongReaderImpl : public SongReader { public: SongReaderImpl(MPDImpl& mpd) : mpd_(mpd), song_(std::nullopt), has_song_(false){}; // SongReaderImpl is also pointer owning (the pointer to the next song_). SongReaderImpl(SongReaderImpl&) = delete; SongReaderImpl& operator=(SongReaderImpl&) = delete; // As with the other types, moves are OK. SongReaderImpl(SongReaderImpl&&) = default; // Default destructor should work fine, since the std::optional owns // a unique_ptr to an actual Song. The generated destructor will destruct // that type correctly. ~SongReaderImpl() override = default; std::optional<std::unique_ptr<Song>> Next() override; bool Done() override; private: // Fetch the next song, and if there is a song store it in song_. If a song // has already been fetched (even if no song was returned), take no action. void FetchNext(); MPDImpl& mpd_; std::optional<std::unique_ptr<Song>> song_; bool has_song_; }; void SongReaderImpl::FetchNext() { if (has_song_) { return; } struct mpd_song* raw_song = mpd_recv_song(mpd_.mpd_); const enum mpd_error err = mpd_connection_get_error(mpd_.mpd_); if (err == MPD_ERROR_CLOSED) { std::cerr << "MPD server closed the connection while getting the list of\n" << "all songs. If MPD error logs say \"Output buffer is full\",\n" << "consider setting max_output_buffer_size to a higher value\n" << "(e.g. 32768) in your MPD config." << std::endl; } mpd_.CheckFail(); if (raw_song == nullptr) { song_ = std::nullopt; return; } has_song_ = true; song_ = std::unique_ptr<Song>(new SongImpl(raw_song)); } std::optional<std::unique_ptr<Song>> SongReaderImpl::Next() { FetchNext(); has_song_ = false; return std::exchange(song_, std::nullopt); } bool SongReaderImpl::Done() { FetchNext(); return !song_.has_value(); } MPDImpl::~MPDImpl() { mpd_connection_free(mpd_); } void MPDImpl::Fail() { assert(mpd_connection_get_error(mpd_) != MPD_ERROR_SUCCESS && "must be an error present"); Die("MPD error: %s", mpd_connection_get_error_message(mpd_)); } void MPDImpl::CheckFail() { if (mpd_connection_get_error(mpd_) != MPD_ERROR_SUCCESS) { Fail(); } } void MPDImpl::Pause() { if (!mpd_run_pause(mpd_, true)) { Fail(); } } void MPDImpl::Play() { if (!mpd_run_pause(mpd_, false)) { Fail(); } } void MPDImpl::PlayAt(unsigned position) { if (!mpd_run_play_pos(mpd_, position)) { Fail(); } } std::unique_ptr<SongReader> MPDImpl::ListAll() { if (!mpd_send_list_all_meta(mpd_, NULL)) { Fail(); } return std::unique_ptr<SongReader>(new SongReaderImpl(*this)); } std::optional<std::unique_ptr<Song>> MPDImpl::Search(std::string_view uri) { // Copy to ensure URI buffer is null-terminated. std::string uri_copy(uri); mpd_search_db_songs(mpd_, true); mpd_search_add_uri_constraint(mpd_, MPD_OPERATOR_DEFAULT, uri_copy.data()); if (!mpd_search_commit(mpd_)) { Fail(); } struct mpd_song* raw_song = mpd_recv_song(mpd_); CheckFail(); if (raw_song == nullptr) { return std::nullopt; } std::unique_ptr<Song> song = std::unique_ptr<Song>(new SongImpl(raw_song)); /* even though we're searching for a single song, libmpdclient * still acts like we're reading a song list. We read an aditional * element to convince MPD this is the end of the song list. */ raw_song = mpd_recv_song(mpd_); assert(raw_song == nullptr && "search by URI should only ever find one song"); return std::optional<std::unique_ptr<Song>>(std::move(song)); } IdleEventSet MPDImpl::Idle(const IdleEventSet& events) { enum mpd_idle occured = mpd_run_idle_mask(mpd_, events.Enum()); CheckFail(); return {static_cast<int>(occured)}; } void MPDImpl::Add(const std::string& uri) { if (!mpd_run_add(mpd_, uri.data())) { Fail(); } } std::unique_ptr<Status> MPDImpl::CurrentStatus() { struct mpd_status* status = mpd_run_status(mpd_); if (status == nullptr) { Fail(); } return std::unique_ptr<Status>(new StatusImpl(status)); } MPD::PasswordStatus MPDImpl::ApplyPassword(const std::string& password) { mpd_run_password(mpd_, password.data()); const enum mpd_error err = mpd_connection_get_error(mpd_); if (err == MPD_ERROR_SUCCESS) { return MPD::PasswordStatus::kAccepted; } if (err != MPD_ERROR_SERVER) { Fail(); } enum mpd_server_error serr = mpd_connection_get_server_error(mpd_); if (serr != MPD_SERVER_ERROR_PASSWORD) { Fail(); } mpd_connection_clear_error(mpd_); return MPD::PasswordStatus::kRejected; } Authorization MPDImpl::CheckCommands( const std::vector<std::string_view>& cmds) { Authorization result; if (cmds.size() < 1) { // Empty command list is always allowed, and we don't need a round // trip to the server. result.authorized = true; return result; } // Fetch a list of the commands we're not allowed to run. In most // installs, this should be empty. if (!mpd_send_disallowed_commands(mpd_)) { CheckFail(); } std::vector<std::string> disallowed; struct mpd_pair* command_pair = mpd_recv_command_pair(mpd_); while (command_pair != nullptr) { disallowed.push_back(command_pair->value); mpd_return_pair(mpd_, command_pair); command_pair = mpd_recv_command_pair(mpd_); } CheckFail(); for (std::string_view cmd : cmds) { if (std::find(disallowed.begin(), disallowed.end(), cmd) != disallowed.end()) { result.missing.emplace_back(cmd); } } // We're authorized as long as we are not missing any required commands. result.authorized = result.missing.size() == 0; return result; } class DialerImpl : public Dialer { public: ~DialerImpl() override = default; // Dial connects to the MPD instance at the given Address, optionally, // with the given timeout. On success a variant with a unique_ptr to // an MPD instance is returned. On failure, a string is returned with // a human-readable description of the error. Dialer::result Dial( const Address&, unsigned timeout_ms = Dialer::kDefaultTimeout) const override; }; Dialer::result DialerImpl::Dial(const Address& addr, unsigned timeout_ms) const { /* Create a new connection to mpd */ struct mpd_connection* mpd = mpd_connection_new(addr.host.data(), addr.port, timeout_ms); if (mpd == nullptr) { return "could not connect to mpd: out of memory"; } if (mpd_connection_get_error(mpd) != MPD_ERROR_SUCCESS) { return absl::StrFormat("could not connect to mpd at %s:%u: %s", addr.host, addr.port, mpd_connection_get_error_message(mpd)); } return std::unique_ptr<MPD>(new MPDImpl(mpd)); } } // namespace std::unique_ptr<mpd::TagParser> Parser() { return std::unique_ptr<mpd::TagParser>(new TagParserImpl()); } std::unique_ptr<mpd::Dialer> Dialer() { return std::unique_ptr<mpd::Dialer>(new DialerImpl()); } } // namespace client } // namespace mpd } // namespace ashuffle <commit_msg>Make SongReaderImpl a bit cleaner<commit_after>#include "mpd_client.h" #include <iostream> #include <absl/strings/str_format.h> #include <mpd/capabilities.h> #include <mpd/connection.h> #include <mpd/database.h> #include <mpd/error.h> #include <mpd/idle.h> #include <mpd/pair.h> #include <mpd/password.h> #include <mpd/player.h> #include <mpd/protocol.h> #include <mpd/queue.h> #include <mpd/recv.h> #include <mpd/search.h> #include <mpd/song.h> #include <mpd/status.h> #include "mpd.h" #include "util.h" namespace ashuffle { namespace mpd { namespace client { namespace { using Authorization = mpd::MPD::Authorization; class TagParserImpl : public TagParser { public: // Parse parses the given tag, and returns the appropriate tag type. // If no matching tag is found, then an empty optional is returned. std::optional<enum mpd_tag_type> Parse( const std::string_view tag) const override; }; std::optional<enum mpd_tag_type> TagParserImpl::Parse( const std::string_view tag_name) const { std::string name_with_null(tag_name); enum mpd_tag_type tag = mpd_tag_name_iparse(name_with_null.data()); if (tag == MPD_TAG_UNKNOWN) { return std::nullopt; } return tag; } class SongImpl : public Song { public: // Create a new song based on the given mpd_song. SongImpl(struct mpd_song* song) : song_(song){}; // Song is pointer owning. We do not support copies. SongImpl(Song&) = delete; SongImpl& operator=(SongImpl&) = delete; // However, moves are OK, because the "old" owner no longer exists. SongImpl(SongImpl&&) = default; // Free the wrapped struct mpd_song; ~SongImpl() override; std::optional<std::string> Tag(enum mpd_tag_type tag) const override; std::string URI() const override; private: // The wrapped song. struct mpd_song* song_; }; SongImpl::~SongImpl() { mpd_song_free(song_); } std::optional<std::string> SongImpl::Tag(enum mpd_tag_type tag) const { const char* raw_value = mpd_song_get_tag(song_, tag, 0); if (raw_value == nullptr) { return std::nullopt; } return std::string(raw_value); } std::string SongImpl::URI() const { return mpd_song_get_uri(song_); } class StatusImpl : public Status { public: // Wrap the given mpd_status. StatusImpl(struct mpd_status* status) : status_(status){}; // StatusImpl is pointer owning. We do not support copies. StatusImpl(StatusImpl&) = delete; StatusImpl& operator=(StatusImpl&) = delete; // Moves are OK, because the "old" owner no longer exists. StatusImpl(StatusImpl&&) = default; StatusImpl& operator=(StatusImpl&&) = default; // Free the wrapped status. ~StatusImpl() override; unsigned QueueLength() const override; bool Single() const override; std::optional<int> SongPosition() const override; bool IsPlaying() const override; private: struct mpd_status* status_; }; StatusImpl::~StatusImpl() { mpd_status_free(status_); } unsigned StatusImpl::QueueLength() const { return mpd_status_get_queue_length(status_); } bool StatusImpl::Single() const { return mpd_status_get_single(status_); } std::optional<int> StatusImpl::SongPosition() const { int pos = mpd_status_get_song_pos(status_); if (pos == -1) { return std::nullopt; } return pos; } bool StatusImpl::IsPlaying() const { return mpd_status_get_state(status_) == MPD_STATE_PLAY; } // Forward declare SongReaderImpl for MPDImpl; class SongReaderImpl; class MPDImpl : public MPD { public: MPDImpl(struct mpd_connection* conn) : mpd_(conn){}; // MPDImpl owns the connection pointer, no copies possible. MPDImpl(MPDImpl&) = delete; MPDImpl& operator=(MPDImpl&) = delete; MPDImpl(MPDImpl&&) = default; MPDImpl& operator=(MPDImpl&&) = default; ~MPDImpl() override; void Pause() override; void Play() override; void PlayAt(unsigned position) override; std::unique_ptr<Status> CurrentStatus() override; std::unique_ptr<SongReader> ListAll() override; std::optional<std::unique_ptr<Song>> Search(std::string_view uri) override; IdleEventSet Idle(const IdleEventSet&) override; void Add(const std::string& uri) override; MPD::PasswordStatus ApplyPassword(const std::string& password) override; Authorization CheckCommands( const std::vector<std::string_view>& cmds) override; private: friend SongReaderImpl; struct mpd_connection* mpd_; // Exits the program, printing the current MPD connection error message. void Fail(); // Checks to see if the MPD connection has an error. If it does, it // calls Fail. void CheckFail(); }; class SongReaderImpl : public SongReader { public: SongReaderImpl(MPDImpl& mpd) : mpd_(mpd), song_(std::nullopt){}; // SongReaderImpl is also pointer owning (the pointer to the next song_). SongReaderImpl(SongReaderImpl&) = delete; SongReaderImpl& operator=(SongReaderImpl&) = delete; // As with the other types, moves are OK. SongReaderImpl(SongReaderImpl&&) = default; // Default destructor should work fine, since the std::optional owns // a unique_ptr to an actual Song. The generated destructor will destruct // that type correctly. ~SongReaderImpl() override = default; std::optional<std::unique_ptr<Song>> Next() override; bool Done() override; private: // Fetch the next song, and if there is a song store it in song_. If a song // has already been fetched (even if no song was returned), take no action. void FetchNext(); MPDImpl& mpd_; std::optional<std::unique_ptr<Song>> song_; }; void SongReaderImpl::FetchNext() { if (song_) { return; } struct mpd_song* raw_song = mpd_recv_song(mpd_.mpd_); const enum mpd_error err = mpd_connection_get_error(mpd_.mpd_); if (err == MPD_ERROR_CLOSED) { std::cerr << "MPD server closed the connection while getting the list of\n" << "all songs. If MPD error logs say \"Output buffer is full\",\n" << "consider setting max_output_buffer_size to a higher value\n" << "(e.g. 32768) in your MPD config." << std::endl; } mpd_.CheckFail(); if (raw_song == nullptr) { song_ = std::nullopt; return; } song_ = std::unique_ptr<Song>(new SongImpl(raw_song)); } std::optional<std::unique_ptr<Song>> SongReaderImpl::Next() { FetchNext(); return std::exchange(song_, std::nullopt); } bool SongReaderImpl::Done() { FetchNext(); return !song_.has_value(); } MPDImpl::~MPDImpl() { mpd_connection_free(mpd_); } void MPDImpl::Fail() { assert(mpd_connection_get_error(mpd_) != MPD_ERROR_SUCCESS && "must be an error present"); Die("MPD error: %s", mpd_connection_get_error_message(mpd_)); } void MPDImpl::CheckFail() { if (mpd_connection_get_error(mpd_) != MPD_ERROR_SUCCESS) { Fail(); } } void MPDImpl::Pause() { if (!mpd_run_pause(mpd_, true)) { Fail(); } } void MPDImpl::Play() { if (!mpd_run_pause(mpd_, false)) { Fail(); } } void MPDImpl::PlayAt(unsigned position) { if (!mpd_run_play_pos(mpd_, position)) { Fail(); } } std::unique_ptr<SongReader> MPDImpl::ListAll() { if (!mpd_send_list_all_meta(mpd_, NULL)) { Fail(); } return std::unique_ptr<SongReader>(new SongReaderImpl(*this)); } std::optional<std::unique_ptr<Song>> MPDImpl::Search(std::string_view uri) { // Copy to ensure URI buffer is null-terminated. std::string uri_copy(uri); mpd_search_db_songs(mpd_, true); mpd_search_add_uri_constraint(mpd_, MPD_OPERATOR_DEFAULT, uri_copy.data()); if (!mpd_search_commit(mpd_)) { Fail(); } struct mpd_song* raw_song = mpd_recv_song(mpd_); CheckFail(); if (raw_song == nullptr) { return std::nullopt; } std::unique_ptr<Song> song = std::unique_ptr<Song>(new SongImpl(raw_song)); /* even though we're searching for a single song, libmpdclient * still acts like we're reading a song list. We read an aditional * element to convince MPD this is the end of the song list. */ raw_song = mpd_recv_song(mpd_); assert(raw_song == nullptr && "search by URI should only ever find one song"); return std::optional<std::unique_ptr<Song>>(std::move(song)); } IdleEventSet MPDImpl::Idle(const IdleEventSet& events) { enum mpd_idle occured = mpd_run_idle_mask(mpd_, events.Enum()); CheckFail(); return {static_cast<int>(occured)}; } void MPDImpl::Add(const std::string& uri) { if (!mpd_run_add(mpd_, uri.data())) { Fail(); } } std::unique_ptr<Status> MPDImpl::CurrentStatus() { struct mpd_status* status = mpd_run_status(mpd_); if (status == nullptr) { Fail(); } return std::unique_ptr<Status>(new StatusImpl(status)); } MPD::PasswordStatus MPDImpl::ApplyPassword(const std::string& password) { mpd_run_password(mpd_, password.data()); const enum mpd_error err = mpd_connection_get_error(mpd_); if (err == MPD_ERROR_SUCCESS) { return MPD::PasswordStatus::kAccepted; } if (err != MPD_ERROR_SERVER) { Fail(); } enum mpd_server_error serr = mpd_connection_get_server_error(mpd_); if (serr != MPD_SERVER_ERROR_PASSWORD) { Fail(); } mpd_connection_clear_error(mpd_); return MPD::PasswordStatus::kRejected; } Authorization MPDImpl::CheckCommands( const std::vector<std::string_view>& cmds) { Authorization result; if (cmds.size() < 1) { // Empty command list is always allowed, and we don't need a round // trip to the server. result.authorized = true; return result; } // Fetch a list of the commands we're not allowed to run. In most // installs, this should be empty. if (!mpd_send_disallowed_commands(mpd_)) { CheckFail(); } std::vector<std::string> disallowed; struct mpd_pair* command_pair = mpd_recv_command_pair(mpd_); while (command_pair != nullptr) { disallowed.push_back(command_pair->value); mpd_return_pair(mpd_, command_pair); command_pair = mpd_recv_command_pair(mpd_); } CheckFail(); for (std::string_view cmd : cmds) { if (std::find(disallowed.begin(), disallowed.end(), cmd) != disallowed.end()) { result.missing.emplace_back(cmd); } } // We're authorized as long as we are not missing any required commands. result.authorized = result.missing.size() == 0; return result; } class DialerImpl : public Dialer { public: ~DialerImpl() override = default; // Dial connects to the MPD instance at the given Address, optionally, // with the given timeout. On success a variant with a unique_ptr to // an MPD instance is returned. On failure, a string is returned with // a human-readable description of the error. Dialer::result Dial( const Address&, unsigned timeout_ms = Dialer::kDefaultTimeout) const override; }; Dialer::result DialerImpl::Dial(const Address& addr, unsigned timeout_ms) const { /* Create a new connection to mpd */ struct mpd_connection* mpd = mpd_connection_new(addr.host.data(), addr.port, timeout_ms); if (mpd == nullptr) { return "could not connect to mpd: out of memory"; } if (mpd_connection_get_error(mpd) != MPD_ERROR_SUCCESS) { return absl::StrFormat("could not connect to mpd at %s:%u: %s", addr.host, addr.port, mpd_connection_get_error_message(mpd)); } return std::unique_ptr<MPD>(new MPDImpl(mpd)); } } // namespace std::unique_ptr<mpd::TagParser> Parser() { return std::unique_ptr<mpd::TagParser>(new TagParserImpl()); } std::unique_ptr<mpd::Dialer> Dialer() { return std::unique_ptr<mpd::Dialer>(new DialerImpl()); } } // namespace client } // namespace mpd } // namespace ashuffle <|endoftext|>
<commit_before>#include "command.hh" #include "globals.hh" #include "eval.hh" #include "eval-inline.hh" #include "names.hh" #include "get-drvs.hh" #include "common-args.hh" #include "json.hh" #include "json-to-value.hh" #include "shared.hh" #include <regex> #include <fstream> using namespace nix; std::string wrap(std::string prefix, std::string s) { return prefix + s + ANSI_NORMAL; } std::string hilite(const std::string & s, const std::smatch & m, std::string postfix) { return m.empty() ? s : std::string(m.prefix()) + ANSI_RED + std::string(m.str()) + postfix + std::string(m.suffix()); } struct CmdSearch : SourceExprCommand, MixJSON { std::vector<std::string> res; bool writeCache = true; bool useCache = true; bool attrPathOnly = false; CmdSearch() { expectArgs("regex", &res); mkFlag() .longName("update-cache") .shortName('u') .description("update the package search cache") .handler([&]() { writeCache = true; useCache = false; }); mkFlag() .longName("no-cache") .description("do not use or update the package search cache") .handler([&]() { writeCache = false; useCache = false; }); mkFlag() .longName("attr-path") .shortName('A') .description("Only search for attribute paths") .handler([&]() { attrPathOnly = true; }); } std::string name() override { return "search"; } std::string description() override { return "query available packages"; } Examples examples() override { return { Example{ "To show all available packages:", "nix search" }, Example{ "To show any packages containing 'blender' in its name or description:", "nix search blender" }, Example{ "To search for Firefox or Chromium:", "nix search 'firefox|chromium'" }, Example{ "To search for git and frontend or gui:", "nix search git 'frontend|gui'" }, Example{ "Only search for attribute paths:", "nix search -A git" } }; } void run(ref<Store> store) override { settings.readOnlyMode = true; // Empty search string should match all packages // Use "^" here instead of ".*" due to differences in resulting highlighting // (see #1893 -- libc++ claims empty search string is not in POSIX grammar) if (res.empty()) { res.push_back("^"); } std::vector<std::regex> regexes; regexes.reserve(res.size()); for (auto &re : res) { regexes.push_back(std::regex(re, std::regex::extended | std::regex::icase)); } auto state = getEvalState(); auto jsonOut = json ? std::make_unique<JSONObject>(std::cout) : nullptr; auto sToplevel = state->symbols.create("_toplevel"); auto sRecurse = state->symbols.create("recurseForDerivations"); bool fromCache = false; std::map<std::string, std::string> results; std::function<void(Value *, std::string, bool, JSONObject *)> doExpr; doExpr = [&](Value * v, std::string attrPath, bool toplevel, JSONObject * cache) { debug("at attribute '%s'", attrPath); try { uint found = 0; state->forceValue(*v); if (v->type == tLambda && toplevel) { Value * v2 = state->allocValue(); state->autoCallFunction(*state->allocBindings(1), *v, *v2); v = v2; state->forceValue(*v); } if (state->isDerivation(*v)) { DrvInfo drv(*state, attrPath, v->attrs); std::string description; std::smatch attrPathMatch; std::smatch descriptionMatch; std::smatch nameMatch; std::string name; DrvName parsed(drv.queryName()); for (auto &regex : regexes) { description = drv.queryMetaString("description"); std::regex_search(attrPath, attrPathMatch, regex); if (attrPathOnly) { if (!attrPathMatch.empty()) found++; continue; } name = parsed.name; std::regex_search(name, nameMatch, regex); std::replace(description.begin(), description.end(), '\n', ' '); std::regex_search(description, descriptionMatch, regex); if (!attrPathMatch.empty() || !nameMatch.empty() || !descriptionMatch.empty()) { found++; } } if (found == res.size()) { if (json) { auto jsonElem = jsonOut->object(attrPath); jsonElem.attr("pkgName", parsed.name); jsonElem.attr("version", parsed.version); jsonElem.attr("description", description); } else { auto display_description = description.empty() ? "\e[3mNo description\e[23m" : description; auto name = hilite(parsed.name, nameMatch, "\e[0;2m") + std::string(parsed.fullName, parsed.name.length()); results[attrPath] = fmt( "* %s (%s)\n %s\n", wrap("\e[0;1m", hilite(attrPath, attrPathMatch, "\e[0;1m")), wrap("\e[0;2m", name), hilite(display_description, descriptionMatch, ANSI_NORMAL)); } } if (cache) { cache->attr("type", "derivation"); cache->attr("name", drv.queryName()); cache->attr("system", drv.querySystem()); if (description != "") { auto meta(cache->object("meta")); meta.attr("description", description); } } } else if (v->type == tAttrs) { if (!toplevel) { auto attrs = v->attrs; Bindings::iterator j = attrs->find(sRecurse); if (j == attrs->end() || !state->forceBool(*j->value, *j->pos)) { debug("skip attribute '%s'", attrPath); return; } } bool toplevel2 = false; if (!fromCache) { Bindings::iterator j = v->attrs->find(sToplevel); toplevel2 = j != v->attrs->end() && state->forceBool(*j->value, *j->pos); } for (auto & i : *v->attrs) { auto cache2 = cache ? std::make_unique<JSONObject>(cache->object(i.name)) : nullptr; doExpr(i.value, attrPath == "" ? (std::string) i.name : attrPath + "." + (std::string) i.name, toplevel2 || fromCache, cache2 ? cache2.get() : nullptr); } } } catch (AssertionError & e) { } catch (Error & e) { if (!toplevel) { e.addPrefix(fmt("While evaluating the attribute '%s':\n", attrPath)); throw; } } }; Path jsonCacheFileName = getCacheDir() + "/nix/package-search.json"; if (useCache && pathExists(jsonCacheFileName)) { warn("using cached results; pass '-u' to update the cache"); Value vRoot; parseJSON(*state, readFile(jsonCacheFileName), vRoot); fromCache = true; doExpr(&vRoot, "", true, nullptr); } else { createDirs(dirOf(jsonCacheFileName)); Path tmpFile = fmt("%s.tmp.%d", jsonCacheFileName, getpid()); std::ofstream jsonCacheFile; try { // iostream considered harmful jsonCacheFile.exceptions(std::ofstream::failbit); jsonCacheFile.open(tmpFile); auto cache = writeCache ? std::make_unique<JSONObject>(jsonCacheFile, false) : nullptr; doExpr(getSourceExpr(*state), "", true, cache.get()); } catch (std::exception &) { /* Fun fact: catching std::ios::failure does not work due to C++11 ABI shenanigans. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145 */ if (!jsonCacheFile) throw Error("error writing to %s", tmpFile); } if (writeCache && rename(tmpFile.c_str(), jsonCacheFileName.c_str()) == -1) throw SysError("cannot rename '%s' to '%s'", tmpFile, jsonCacheFileName); } if (!json) { if (results.size() == 0) throw Error("no results for the given search term(s)!"); RunPager pager; for (auto el : results) std::cout << el.second << "\n"; } } }; static RegisterCommand r1(make_ref<CmdSearch>()); <commit_msg>search: don't abandon entire eval if something happens<commit_after>#include "command.hh" #include "globals.hh" #include "eval.hh" #include "eval-inline.hh" #include "names.hh" #include "get-drvs.hh" #include "common-args.hh" #include "json.hh" #include "json-to-value.hh" #include "shared.hh" #include <regex> #include <fstream> using namespace nix; std::string wrap(std::string prefix, std::string s) { return prefix + s + ANSI_NORMAL; } std::string hilite(const std::string & s, const std::smatch & m, std::string postfix) { return m.empty() ? s : std::string(m.prefix()) + ANSI_RED + std::string(m.str()) + postfix + std::string(m.suffix()); } struct CmdSearch : SourceExprCommand, MixJSON { std::vector<std::string> res; bool writeCache = true; bool useCache = true; bool attrPathOnly = false; CmdSearch() { expectArgs("regex", &res); mkFlag() .longName("update-cache") .shortName('u') .description("update the package search cache") .handler([&]() { writeCache = true; useCache = false; }); mkFlag() .longName("no-cache") .description("do not use or update the package search cache") .handler([&]() { writeCache = false; useCache = false; }); mkFlag() .longName("attr-path") .shortName('A') .description("Only search for attribute paths") .handler([&]() { attrPathOnly = true; }); } std::string name() override { return "search"; } std::string description() override { return "query available packages"; } Examples examples() override { return { Example{ "To show all available packages:", "nix search" }, Example{ "To show any packages containing 'blender' in its name or description:", "nix search blender" }, Example{ "To search for Firefox or Chromium:", "nix search 'firefox|chromium'" }, Example{ "To search for git and frontend or gui:", "nix search git 'frontend|gui'" }, Example{ "Only search for attribute paths:", "nix search -A git" } }; } void run(ref<Store> store) override { settings.readOnlyMode = true; // Empty search string should match all packages // Use "^" here instead of ".*" due to differences in resulting highlighting // (see #1893 -- libc++ claims empty search string is not in POSIX grammar) if (res.empty()) { res.push_back("^"); } std::vector<std::regex> regexes; regexes.reserve(res.size()); for (auto &re : res) { regexes.push_back(std::regex(re, std::regex::extended | std::regex::icase)); } auto state = getEvalState(); auto jsonOut = json ? std::make_unique<JSONObject>(std::cout) : nullptr; auto sToplevel = state->symbols.create("_toplevel"); auto sRecurse = state->symbols.create("recurseForDerivations"); bool fromCache = false; std::map<std::string, std::string> results; std::function<void(Value *, std::string, bool, JSONObject *)> doExpr; doExpr = [&](Value * v, std::string attrPath, bool toplevel, JSONObject * cache) { debug("at attribute '%s'", attrPath); try { uint found = 0; state->forceValue(*v); if (v->type == tLambda && toplevel) { Value * v2 = state->allocValue(); state->autoCallFunction(*state->allocBindings(1), *v, *v2); v = v2; state->forceValue(*v); } if (state->isDerivation(*v)) { DrvInfo drv(*state, attrPath, v->attrs); std::string description; std::smatch attrPathMatch; std::smatch descriptionMatch; std::smatch nameMatch; std::string name; DrvName parsed(drv.queryName()); for (auto &regex : regexes) { description = drv.queryMetaString("description"); std::regex_search(attrPath, attrPathMatch, regex); if (attrPathOnly) { if (!attrPathMatch.empty()) found++; continue; } name = parsed.name; std::regex_search(name, nameMatch, regex); std::replace(description.begin(), description.end(), '\n', ' '); std::regex_search(description, descriptionMatch, regex); if (!attrPathMatch.empty() || !nameMatch.empty() || !descriptionMatch.empty()) { found++; } } if (found == res.size()) { if (json) { auto jsonElem = jsonOut->object(attrPath); jsonElem.attr("pkgName", parsed.name); jsonElem.attr("version", parsed.version); jsonElem.attr("description", description); } else { auto display_description = description.empty() ? "\e[3mNo description\e[23m" : description; auto name = hilite(parsed.name, nameMatch, "\e[0;2m") + std::string(parsed.fullName, parsed.name.length()); results[attrPath] = fmt( "* %s (%s)\n %s\n", wrap("\e[0;1m", hilite(attrPath, attrPathMatch, "\e[0;1m")), wrap("\e[0;2m", name), hilite(display_description, descriptionMatch, ANSI_NORMAL)); } } if (cache) { cache->attr("type", "derivation"); cache->attr("name", drv.queryName()); cache->attr("system", drv.querySystem()); if (description != "") { auto meta(cache->object("meta")); meta.attr("description", description); } } } else if (v->type == tAttrs) { if (!toplevel) { auto attrs = v->attrs; Bindings::iterator j = attrs->find(sRecurse); if (j == attrs->end() || !state->forceBool(*j->value, *j->pos)) { debug("skip attribute '%s'", attrPath); return; } } bool toplevel2 = false; if (!fromCache) { Bindings::iterator j = v->attrs->find(sToplevel); toplevel2 = j != v->attrs->end() && state->forceBool(*j->value, *j->pos); } for (auto & i : *v->attrs) { auto cache2 = cache ? std::make_unique<JSONObject>(cache->object(i.name)) : nullptr; doExpr(i.value, attrPath == "" ? (std::string) i.name : attrPath + "." + (std::string) i.name, toplevel2 || fromCache, cache2 ? cache2.get() : nullptr); } } } catch (AssertionError & e) { } catch (Error & e) { if (!toplevel) { e.addPrefix(fmt("While evaluating the attribute '%s':\n", attrPath)); printError("warning: %s", e.what()); // don't throw, try other attrs } } }; Path jsonCacheFileName = getCacheDir() + "/nix/package-search.json"; if (useCache && pathExists(jsonCacheFileName)) { warn("using cached results; pass '-u' to update the cache"); Value vRoot; parseJSON(*state, readFile(jsonCacheFileName), vRoot); fromCache = true; doExpr(&vRoot, "", true, nullptr); } else { createDirs(dirOf(jsonCacheFileName)); Path tmpFile = fmt("%s.tmp.%d", jsonCacheFileName, getpid()); std::ofstream jsonCacheFile; try { // iostream considered harmful jsonCacheFile.exceptions(std::ofstream::failbit); jsonCacheFile.open(tmpFile); auto cache = writeCache ? std::make_unique<JSONObject>(jsonCacheFile, false) : nullptr; doExpr(getSourceExpr(*state), "", true, cache.get()); } catch (std::exception &) { /* Fun fact: catching std::ios::failure does not work due to C++11 ABI shenanigans. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145 */ if (!jsonCacheFile) throw Error("error writing to %s", tmpFile); throw; } if (writeCache && rename(tmpFile.c_str(), jsonCacheFileName.c_str()) == -1) throw SysError("cannot rename '%s' to '%s'", tmpFile, jsonCacheFileName); } if (!json) { if (results.size() == 0) throw Error("no results for the given search term(s)!"); RunPager pager; for (auto el : results) std::cout << el.second << "\n"; } } }; static RegisterCommand r1(make_ref<CmdSearch>()); <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_object_wrap.h> #include <queue> #include <uv.h> #include "lib/RtMidi/RtMidi.h" #include "lib/RtMidi/RtMidi.cpp" using namespace node; class NodeMidiOutput : ObjectWrap { private: RtMidiOut* out; public: static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiOutput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "sendMessage", SendMessage); target->Set(v8::String::NewSymbol("output"), s_ct->GetFunction()); } NodeMidiOutput() { out = new RtMidiOut(); } ~NodeMidiOutput() { delete out; } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = new NodeMidiOutput(); output->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(output->out->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(output->out->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); output->out->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); output->out->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); output->out->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> SendMessage(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsArray()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an array"))); } v8::Local<v8::Object> message = args[0]->ToObject(); size_t messageLength = message->Get(v8::String::New("length"))->Int32Value(); std::vector<unsigned char> messageOutput; for (size_t i = 0; i != messageLength; ++i) { messageOutput.push_back(message->Get(v8::Integer::New(i))->Int32Value()); } output->out->sendMessage(&messageOutput); return scope.Close(v8::Undefined()); } }; static v8::Persistent<v8::String> emit_symbol; class NodeMidiInput : public ObjectWrap { private: RtMidiIn* in; public: uv_async_t message_async; pthread_mutex_t message_mutex; struct MidiMessage { double deltaTime; std::vector<unsigned char> message; }; std::queue<MidiMessage*> message_queue; static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); emit_symbol = v8::Persistent<v8::String>::New(v8::String::NewSymbol("emit")); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiInput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "ignoreTypes", IgnoreTypes); target->Set(v8::String::NewSymbol("input"), s_ct->GetFunction()); } NodeMidiInput() { in = new RtMidiIn(); pthread_mutex_init(&message_mutex, NULL); } ~NodeMidiInput() { in->closePort(); // not sure im doing the right thing here for uv the two next lines // ev_async_stop(EV_DEFAULT_UC_ message_async); delete &message_async; delete in; pthread_mutex_destroy(&message_mutex); } static void EmitMessage(uv_async_t *w, int status) { assert(status == 0); v8::HandleScope scope; NodeMidiInput *input = static_cast<NodeMidiInput*>(w->data); pthread_mutex_lock(&input->message_mutex); while (!input->message_queue.empty()) { MidiMessage* message = input->message_queue.front(); v8::Local<v8::Value> args[3]; args[0]= v8::String::New("message"); args[1] = v8::Local<v8::Value>::New(v8::Number::New(message->deltaTime)); size_t count = message->message.size(); v8::Local<v8::Array> data = v8::Array::New(count); for (size_t i = 0; i < count; ++i) { data->Set(v8::Number::New(i), v8::Integer::New(message->message[i])); } args[2] = v8::Local<v8::Value>::New(data); v8::Local<v8::Value> emit_v = input->handle_->Get(emit_symbol); if (emit_v->IsFunction()) { v8::Local<v8::Function> emit=v8::Local<v8::Function>::Cast(emit_v); v8::TryCatch tc; emit->Call(input->handle_,3,args); if (tc.HasCaught()){ node::FatalException(tc); } } input->message_queue.pop(); delete message; } pthread_mutex_unlock(&input->message_mutex); } static void Callback(double deltaTime, std::vector<unsigned char> *message, void *userData) { NodeMidiInput *input = static_cast<NodeMidiInput*>(userData); MidiMessage* data = new MidiMessage(); data->deltaTime = deltaTime; data->message = *message; pthread_mutex_lock(&input->message_mutex); input->message_queue.push(data); pthread_mutex_unlock(&input->message_mutex); uv_async_send(&input->message_async); } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = new NodeMidiInput(); input->message_async.data = input; uv_async_init(uv_default_loop(),&input->message_async, NodeMidiInput::EmitMessage); uv_unref(uv_default_loop()); input->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(input->in->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(input->in->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); input->Unref(); input->in->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> IgnoreTypes(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() != 3 || !args[0]->IsBoolean() || !args[1]->IsBoolean() || !args[2]->IsBoolean()) { return ThrowException(v8::Exception::TypeError( v8::String::New("Arguments must be boolean"))); } bool filter_sysex = args[0]->BooleanValue(); bool filter_timing = args[1]->BooleanValue(); bool filter_sensing = args[2]->BooleanValue(); input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing); return scope.Close(v8::Undefined()); } }; v8::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct; v8::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct; extern "C" { void init (v8::Handle<v8::Object> target) { NodeMidiOutput::Init(target); NodeMidiInput::Init(target); } NODE_MODULE(nodemidi, init); } <commit_msg>Tidy up some spaces<commit_after>#include <v8.h> #include <node.h> #include <node_object_wrap.h> #include <queue> #include <uv.h> #include "lib/RtMidi/RtMidi.h" #include "lib/RtMidi/RtMidi.cpp" using namespace node; class NodeMidiOutput : ObjectWrap { private: RtMidiOut* out; public: static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiOutput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "sendMessage", SendMessage); target->Set(v8::String::NewSymbol("output"), s_ct->GetFunction()); } NodeMidiOutput() { out = new RtMidiOut(); } ~NodeMidiOutput() { delete out; } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = new NodeMidiOutput(); output->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(output->out->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(output->out->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); output->out->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); output->out->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); output->out->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> SendMessage(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsArray()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an array"))); } v8::Local<v8::Object> message = args[0]->ToObject(); size_t messageLength = message->Get(v8::String::New("length"))->Int32Value(); std::vector<unsigned char> messageOutput; for (size_t i = 0; i != messageLength; ++i) { messageOutput.push_back(message->Get(v8::Integer::New(i))->Int32Value()); } output->out->sendMessage(&messageOutput); return scope.Close(v8::Undefined()); } }; static v8::Persistent<v8::String> emit_symbol; class NodeMidiInput : public ObjectWrap { private: RtMidiIn* in; public: uv_async_t message_async; pthread_mutex_t message_mutex; struct MidiMessage { double deltaTime; std::vector<unsigned char> message; }; std::queue<MidiMessage*> message_queue; static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); emit_symbol = v8::Persistent<v8::String>::New(v8::String::NewSymbol("emit")); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiInput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "ignoreTypes", IgnoreTypes); target->Set(v8::String::NewSymbol("input"), s_ct->GetFunction()); } NodeMidiInput() { in = new RtMidiIn(); pthread_mutex_init(&message_mutex, NULL); } ~NodeMidiInput() { in->closePort(); // not sure im doing the right thing here for uv the two next lines // ev_async_stop(EV_DEFAULT_UC_ message_async); delete &message_async; delete in; pthread_mutex_destroy(&message_mutex); } static void EmitMessage(uv_async_t *w, int status) { assert(status == 0); v8::HandleScope scope; NodeMidiInput *input = static_cast<NodeMidiInput*>(w->data); pthread_mutex_lock(&input->message_mutex); while (!input->message_queue.empty()) { MidiMessage* message = input->message_queue.front(); v8::Local<v8::Value> args[3]; args[0]= v8::String::New("message"); args[1] = v8::Local<v8::Value>::New(v8::Number::New(message->deltaTime)); size_t count = message->message.size(); v8::Local<v8::Array> data = v8::Array::New(count); for (size_t i = 0; i < count; ++i) { data->Set(v8::Number::New(i), v8::Integer::New(message->message[i])); } args[2] = v8::Local<v8::Value>::New(data); v8::Local<v8::Value> emit_v = input->handle_->Get(emit_symbol); if (emit_v->IsFunction()) { v8::Local<v8::Function> emit=v8::Local<v8::Function>::Cast(emit_v); v8::TryCatch tc; emit->Call(input->handle_,3,args); if (tc.HasCaught()){ node::FatalException(tc); } } input->message_queue.pop(); delete message; } pthread_mutex_unlock(&input->message_mutex); } static void Callback(double deltaTime, std::vector<unsigned char> *message, void *userData) { NodeMidiInput *input = static_cast<NodeMidiInput*>(userData); MidiMessage* data = new MidiMessage(); data->deltaTime = deltaTime; data->message = *message; pthread_mutex_lock(&input->message_mutex); input->message_queue.push(data); pthread_mutex_unlock(&input->message_mutex); uv_async_send(&input->message_async); } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = new NodeMidiInput(); input->message_async.data = input; uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage); uv_unref(uv_default_loop()); input->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(input->in->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(input->in->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); input->Unref(); input->in->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> IgnoreTypes(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() != 3 || !args[0]->IsBoolean() || !args[1]->IsBoolean() || !args[2]->IsBoolean()) { return ThrowException(v8::Exception::TypeError( v8::String::New("Arguments must be boolean"))); } bool filter_sysex = args[0]->BooleanValue(); bool filter_timing = args[1]->BooleanValue(); bool filter_sensing = args[2]->BooleanValue(); input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing); return scope.Close(v8::Undefined()); } }; v8::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct; v8::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct; extern "C" { void init (v8::Handle<v8::Object> target) { NodeMidiOutput::Init(target); NodeMidiInput::Init(target); } NODE_MODULE(nodemidi, init); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QObject> #include <qmobilityglobal.h> #include <qtorganizer.h> #include <QtTest/QtTest> #include <QDebug> #include <QColor> QTM_USE_NAMESPACE const QString managerNameSymbian("symbian"); const int KTimeToWait = 1000; class tst_symbianasynchcollections : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); private slots: void saveCollection(); void removeCollection(); void collectionIds(); void fetchCollection(); public slots: void requestStateChanged(QOrganizerItemAbstractRequest::State currentState); void requestResultsAvailable(); private: QOrganizerItemManager* m_om; QOrganizerItemAbstractRequest* m_itemRequest; QList<QOrganizerCollectionId> m_collectionIds; }; void tst_symbianasynchcollections::initTestCase() { m_om = new QOrganizerItemManager(managerNameSymbian); m_itemRequest = 0; } void tst_symbianasynchcollections::cleanupTestCase() { delete m_om; m_om = 0; delete m_itemRequest; m_itemRequest = 0; } void tst_symbianasynchcollections::collectionIds() {/* // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionLocalIdFetchRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionLocalIdFetchRequest * collectionLocalIdFetchRequest( (QOrganizerCollectionLocalIdFetchRequest*)m_itemRequest); // Start the request collectionLocalIdFetchRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionLocalIdFetchRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionLocalIdFetchRequest->isFinished()); // Get all collection ids QList<QOrganizerCollectionLocalId> ids = collectionLocalIdFetchRequest->collectionIds(); QVERIFY(collectionLocalIdFetchRequest->error() == QOrganizerItemManager::NoError); */} void tst_symbianasynchcollections::fetchCollection() {/* // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionFetchRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionFetchRequest * collectionFetchRequest( (QOrganizerCollectionFetchRequest*)m_itemRequest); // Set collections QList<QOrganizerCollectionId> collectionIds; collectionFetchRequest->setCollectionIds(collectionIds); // Start the request collectionFetchRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionFetchRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionFetchRequest->isFinished()); */} void tst_symbianasynchcollections::saveCollection() { // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionSaveRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionSaveRequest * collectionSaveRequest( (QOrganizerCollectionSaveRequest*)m_itemRequest); // Set collections QList<QOrganizerCollection> collections; // Create a collection QOrganizerCollection collection; collection.setMetaData("Name", "saveCollection"); collection.setMetaData("FileName", "c:saveCollection"); collection.setMetaData("Description", "saveCollection test"); collection.setMetaData("Color", QColor(Qt::red)); collection.setMetaData("Enabled", true); //collections.append(collections); // Set collection collectionSaveRequest->setCollection(collection); // Start the request collectionSaveRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionSaveRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionSaveRequest->isFinished()); } void tst_symbianasynchcollections::removeCollection() { // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionRemoveRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionRemoveRequest * collectionRemoveRequest( (QOrganizerCollectionRemoveRequest*)m_itemRequest); // Set collections collectionRemoveRequest->setCollectionIds(m_collectionIds); // Start the request collectionRemoveRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionRemoveRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionRemoveRequest->isFinished()); } void tst_symbianasynchcollections::requestStateChanged( QOrganizerItemAbstractRequest::State currentState) { switch(currentState) { case QOrganizerItemAbstractRequest::InactiveState: { // Verify if the request is in inactive state QVERIFY(m_itemRequest->isInactive()); // Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::InactiveState); // Operation not yet started start the operation m_itemRequest->start(); } break; case QOrganizerItemAbstractRequest::ActiveState: { // Verify if the request is in active state QVERIFY(m_itemRequest->isActive()); // Operation started, not yet finished operation already started // Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::ActiveState); } break; case QOrganizerItemAbstractRequest::CanceledState: { // Verify if the request is in canceled state QVERIFY(m_itemRequest->isCanceled()); // Operation is finished due to cancellation test not completed, // failed Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::CanceledState); } break; case QOrganizerItemAbstractRequest::FinishedState: { // Verify if the request is in finished state QVERIFY(m_itemRequest->isFinished()); // Operation either completed successfully or failed. // No further results will be available. // test completed, compare the results // Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::FinishedState); } break; default: { // Not handled } break; } } void tst_symbianasynchcollections::requestResultsAvailable() { QOrganizerItemAbstractRequest::RequestType reqType(m_itemRequest->type()); switch (reqType) { case QOrganizerItemAbstractRequest::CollectionSaveRequest : { QList<QOrganizerCollection> savedCollections( ((QOrganizerCollectionSaveRequest*)(m_itemRequest))->collections()); int count(savedCollections.count()); for (int index(0); index < count; index++) { m_collectionIds.append(savedCollections.at(index).id()); QOrganizerCollectionLocalId id(m_collectionIds[index]); } // Check the number of requests saved. magic number to be changed to a // constant QCOMPARE(count, 1); QMap<int, QOrganizerItemManager::Error> errorMap( ((QOrganizerCollectionSaveRequest*)(m_itemRequest))->errorMap()); // Error map should contain zero errors to indicate successful saving // of all the collections QCOMPARE(0, errorMap.count()); } break; case QOrganizerItemAbstractRequest::CollectionRemoveRequest : { // Check error map QMap<int, QOrganizerItemManager::Error> erroMap( ((QOrganizerCollectionRemoveRequest*)(m_itemRequest))->errorMap()); // Error map should contain zero errors to indicate successful deletion // of all the items int count(erroMap.count()); QCOMPARE(0, count); } break; } } QTEST_MAIN(tst_symbianasynchcollections); #include "tst_symbianasynchcollections.moc" <commit_msg>test case updated to test asynch collectionsfetch api<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QObject> #include <qmobilityglobal.h> #include <qtorganizer.h> #include <QtTest/QtTest> #include <QDebug> #include <QColor> QTM_USE_NAMESPACE const QString managerNameSymbian("symbian"); const int KTimeToWait = 1000; class tst_symbianasynchcollections : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); private slots: void saveCollection(); void collectionIds(); void removeCollection(); void fetchCollection(); public slots: void requestStateChanged(QOrganizerItemAbstractRequest::State currentState); void requestResultsAvailable(); private: QOrganizerItemManager* m_om; QOrganizerItemAbstractRequest* m_itemRequest; QList<QOrganizerCollectionId> m_collectionIds; }; void tst_symbianasynchcollections::initTestCase() { m_om = new QOrganizerItemManager(managerNameSymbian); m_itemRequest = 0; } void tst_symbianasynchcollections::cleanupTestCase() { delete m_om; m_om = 0; delete m_itemRequest; m_itemRequest = 0; } void tst_symbianasynchcollections::collectionIds() { // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionLocalIdFetchRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionLocalIdFetchRequest * collectionLocalIdFetchRequest( (QOrganizerCollectionLocalIdFetchRequest*)m_itemRequest); // Start the request collectionLocalIdFetchRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionLocalIdFetchRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionLocalIdFetchRequest->isFinished()); } void tst_symbianasynchcollections::fetchCollection() {/* // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionFetchRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionFetchRequest * collectionFetchRequest( (QOrganizerCollectionFetchRequest*)m_itemRequest); // Set collections QList<QOrganizerCollectionId> collectionIds; collectionFetchRequest->setCollectionIds(collectionIds); // Start the request collectionFetchRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionFetchRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionFetchRequest->isFinished()); */} void tst_symbianasynchcollections::saveCollection() { // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionSaveRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionSaveRequest * collectionSaveRequest( (QOrganizerCollectionSaveRequest*)m_itemRequest); // Set collections QList<QOrganizerCollection> collections; // Create a collection QOrganizerCollection collection; collection.setMetaData("Name", "saveCollection"); collection.setMetaData("FileName", "c:saveCollection"); collection.setMetaData("Description", "saveCollection test"); collection.setMetaData("Color", QColor(Qt::red)); collection.setMetaData("Enabled", true); //collections.append(collections); // Set collection collectionSaveRequest->setCollection(collection); // Start the request collectionSaveRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionSaveRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionSaveRequest->isFinished()); } void tst_symbianasynchcollections::removeCollection() { // Make sure to delete the old request, if any delete m_itemRequest; // Create new request m_itemRequest = new QOrganizerCollectionRemoveRequest(this); // Set manager m_itemRequest->setManager(m_om); // Connect for the state change signal connect(m_itemRequest, SIGNAL(stateChanged(QOrganizerItemAbstractRequest::State)), this, SLOT(requestStateChanged(QOrganizerItemAbstractRequest::State))); connect(m_itemRequest, SIGNAL(resultsAvailable()), this, SLOT(requestResultsAvailable())); // Type cast the new request to appropriate type QOrganizerCollectionRemoveRequest * collectionRemoveRequest( (QOrganizerCollectionRemoveRequest*)m_itemRequest); // Set collections collectionRemoveRequest->setCollectionIds(m_collectionIds); // Start the request collectionRemoveRequest->start(); // Wait for KTimeToWait millisecs or until request is finished collectionRemoveRequest->waitForFinished(KTimeToWait); // Verify if the request is finished QVERIFY(collectionRemoveRequest->isFinished()); } void tst_symbianasynchcollections::requestStateChanged( QOrganizerItemAbstractRequest::State currentState) { switch(currentState) { case QOrganizerItemAbstractRequest::InactiveState: { // Verify if the request is in inactive state QVERIFY(m_itemRequest->isInactive()); // Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::InactiveState); // Operation not yet started start the operation m_itemRequest->start(); } break; case QOrganizerItemAbstractRequest::ActiveState: { // Verify if the request is in active state QVERIFY(m_itemRequest->isActive()); // Operation started, not yet finished operation already started // Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::ActiveState); } break; case QOrganizerItemAbstractRequest::CanceledState: { // Verify if the request is in canceled state QVERIFY(m_itemRequest->isCanceled()); // Operation is finished due to cancellation test not completed, // failed Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::CanceledState); } break; case QOrganizerItemAbstractRequest::FinishedState: { // Verify if the request is in finished state QVERIFY(m_itemRequest->isFinished()); // Operation either completed successfully or failed. // No further results will be available. // test completed, compare the results // Compare the request state is set rightly QCOMPARE(m_itemRequest->state(), QOrganizerItemAbstractRequest::FinishedState); } break; default: { // Not handled } break; } } void tst_symbianasynchcollections::requestResultsAvailable() { QOrganizerItemAbstractRequest::RequestType reqType(m_itemRequest->type()); switch (reqType) { case QOrganizerItemAbstractRequest::CollectionLocalIdFetchRequest : { // Get all collection ids QList<QOrganizerCollectionLocalId> collectionIds( ((QOrganizerCollectionLocalIdFetchRequest*)(m_itemRequest)) ->collectionIds()); QVERIFY(m_itemRequest->error() == QOrganizerItemManager::NoError); qWarning() << collectionIds.count() << "calendar/s are present currently"; } break; case QOrganizerItemAbstractRequest::CollectionSaveRequest : { QList<QOrganizerCollection> savedCollections( ((QOrganizerCollectionSaveRequest*)(m_itemRequest))->collections()); int count(savedCollections.count()); for (int index(0); index < count; index++) { m_collectionIds.append(savedCollections.at(index).id()); } // Check the number of requests saved. magic number to be changed to a // constant QCOMPARE(count, 1); QMap<int, QOrganizerItemManager::Error> errorMap( ((QOrganizerCollectionSaveRequest*)(m_itemRequest))->errorMap()); // Error map should contain zero errors to indicate successful saving // of all the collections QCOMPARE(0, errorMap.count()); } break; case QOrganizerItemAbstractRequest::CollectionRemoveRequest : { // Check error map QMap<int, QOrganizerItemManager::Error> erroMap( ((QOrganizerCollectionRemoveRequest*)(m_itemRequest))->errorMap()); // Error map should contain zero errors to indicate successful deletion // of all the items int count(erroMap.count()); QCOMPARE(0, count); } break; } } QTEST_MAIN(tst_symbianasynchcollections); #include "tst_symbianasynchcollections.moc" <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This 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. See file COPYING. * */ #include "OSDMap.h" #include "config.h" void OSDMap::print(ostream& out) { out << "epoch " << get_epoch() << "\n" << "fsid " << get_fsid() << "\n" << "ctime " << get_ctime() << "\n" << "mtime " << get_mtime() << "\n" << std::endl; out << "pg_num " << get_pg_num() << "\n" << "pgp_num " << get_pgp_num() << "\n" << "lpg_num " << get_lpg_num() << "\n" << "lpgp_num " << get_lpgp_num() << "\n" << "last_pg_change " << get_last_pg_change() << "\n" << std::endl; out << "max_osd " << get_max_osd() << "\n"; for (int i=0; i<get_max_osd(); i++) { if (exists(i)) { out << "osd" << i; out << (is_up(i) ? " up":" down"); if (is_up(i)) out << " " << get_addr(i); osd_info_t& info = get_info(i); out << " (up_from " << info.up_from << " up_thru " << info.up_thru << " down_at " << info.down_at << " last_clean " << info.last_clean_first << "-" << info.last_clean_last << ")"; out << (is_in(i) ? " in":" out"); if (is_in(i)) out << " weight " << get_weightf(i); out << "\n"; } } out << std::endl; for (hash_map<entity_addr_t,utime_t>::iterator p = blacklist.begin(); p != blacklist.end(); p++) out << "blacklist " << p->first << " expires " << p->second << "\n"; // ignore pg_swap_primary out << "max_snap " << get_max_snap() << "\n" << "removed_snaps " << get_removed_snaps() << "\n" << std::endl; } void OSDMap::print_summary(ostream& out) { out << "e" << get_epoch() << ": " << get_num_osds() << " osds: " << get_num_up_osds() << " up, " << get_num_in_osds() << " in"; if (blacklist.size()) out << ", " << blacklist.size() << " blacklisted"; } void OSDMap::build_simple(epoch_t e, ceph_fsid_t &fsid, int num_osd, int num_dom, int pg_bits, int lpg_bits, int mds_local_osd) { dout(10) << "build_simple on " << num_osd << " osds with " << pg_bits << " pg bits per osd, " << lpg_bits << " lpg bits" << dendl; epoch = e; set_fsid(fsid); mtime = ctime = g_clock.now(); set_max_osd(num_osd); pg_num = pgp_num = num_osd << pg_bits; lpg_num = lpgp_num = lpg_bits ? (1 << (lpg_bits-1)) : 0; // crush map build_simple_crush_map(crush, num_osd, num_dom); for (int i=0; i<num_osd; i++) { set_state(i, CEPH_OSD_EXISTS); set_weight(i, CEPH_OSD_OUT); } if (mds_local_osd) { set_max_osd(mds_local_osd+num_osd); // add mds local osds, but don't put them in the crush mapping func for (int i=0; i<mds_local_osd; i++) { set_state(i+num_osd, CEPH_OSD_EXISTS); set_weight(i+num_osd, CEPH_OSD_OUT); } } } void OSDMap::build_simple_crush_map(CrushWrapper& crush, int num_osd, int num_dom) { // new crush.create(); crush.set_type_name(1, "domain"); crush.set_type_name(2, "pool"); int npools = 3; int minrep = g_conf.osd_min_rep; int ndom = num_dom; if (!ndom) ndom = MAX(g_conf.osd_max_rep, g_conf.osd_max_raid_width); if (num_osd >= ndom*3 && num_osd > 8) { int ritems[ndom]; int rweights[ndom]; int nper = ((num_osd - 1) / ndom) + 1; derr(0) << ndom << " failure domains, " << nper << " osds each" << dendl; int o = 0; for (int i=0; i<ndom; i++) { int items[nper]; //int w[nper]; int j; rweights[i] = 0; for (j=0; j<nper; j++, o++) { if (o == num_osd) break; dout(20) << "added osd" << o << dendl; items[j] = o; //w[j] = weights[o] ? (0x10000 - (int)(weights[o] * 0x10000)):0x10000; //rweights[i] += w[j]; rweights[i] += 0x10000; } crush_bucket *domain = (crush_bucket *)crush_make_uniform_bucket(1, j, items, 0x10000); ritems[i] = crush_add_bucket(crush.crush, 0, domain); dout(20) << "added domain bucket i " << ritems[i] << " of size " << j << dendl; char bname[10]; sprintf(bname, "dom%d", i); crush.set_item_name(ritems[i], bname); } // root crush_bucket *root = (crush_bucket *)crush_make_straw_bucket(2, ndom, ritems, rweights); int rootid = crush_add_bucket(crush.crush, 0, root); crush.set_item_name(rootid, "root"); // rules // replication for (int pool=0; pool<npools; pool++) { // size minrep..ndom crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_REP, minrep, g_conf.osd_max_rep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_FIRSTN, CRUSH_CHOOSE_N, 1); // choose N domains crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, get_pool_name(pool)); } // raid if (false && g_conf.osd_min_raid_width <= g_conf.osd_max_raid_width) for (int pool=0; pool<npools; pool++) { crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_RAID4, g_conf.osd_min_raid_width, g_conf.osd_max_raid_width); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_INDEP, CRUSH_CHOOSE_N, 1); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); crush_add_rule(crush.crush, rule, -1); } } else { // one bucket int items[num_osd]; int weights[num_osd]; for (int i=0; i<num_osd; i++) { items[i] = i; weights[i] = 0x10000; } crush_bucket *b = (crush_bucket *)crush_make_straw_bucket(1, num_osd, items, weights); int rootid = crush_add_bucket(crush.crush, 0, b); crush.set_item_name(rootid, "root"); // replication for (int pool=0; pool<npools; pool++) { crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_REP, g_conf.osd_min_rep, g_conf.osd_max_rep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_FIRSTN, CRUSH_CHOOSE_N, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, get_pool_name(pool)); } // raid4 if (false && g_conf.osd_min_raid_width <= g_conf.osd_max_raid_width) for (int pool=0; pool<npools; pool++) { crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_RAID4, g_conf.osd_min_raid_width, g_conf.osd_max_raid_width); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_INDEP, CRUSH_CHOOSE_N, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); crush_add_rule(crush.crush, rule, -1); } } crush.finalize(); dout(20) << "crush max_devices " << crush.crush->max_devices << dendl; } <commit_msg>osdmap: use generic crush_build_bucket<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This 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. See file COPYING. * */ #include "OSDMap.h" #include "config.h" void OSDMap::print(ostream& out) { out << "epoch " << get_epoch() << "\n" << "fsid " << get_fsid() << "\n" << "ctime " << get_ctime() << "\n" << "mtime " << get_mtime() << "\n" << std::endl; out << "pg_num " << get_pg_num() << "\n" << "pgp_num " << get_pgp_num() << "\n" << "lpg_num " << get_lpg_num() << "\n" << "lpgp_num " << get_lpgp_num() << "\n" << "last_pg_change " << get_last_pg_change() << "\n" << std::endl; out << "max_osd " << get_max_osd() << "\n"; for (int i=0; i<get_max_osd(); i++) { if (exists(i)) { out << "osd" << i; out << (is_up(i) ? " up":" down"); if (is_up(i)) out << " " << get_addr(i); osd_info_t& info = get_info(i); out << " (up_from " << info.up_from << " up_thru " << info.up_thru << " down_at " << info.down_at << " last_clean " << info.last_clean_first << "-" << info.last_clean_last << ")"; out << (is_in(i) ? " in":" out"); if (is_in(i)) out << " weight " << get_weightf(i); out << "\n"; } } out << std::endl; for (hash_map<entity_addr_t,utime_t>::iterator p = blacklist.begin(); p != blacklist.end(); p++) out << "blacklist " << p->first << " expires " << p->second << "\n"; // ignore pg_swap_primary out << "max_snap " << get_max_snap() << "\n" << "removed_snaps " << get_removed_snaps() << "\n" << std::endl; } void OSDMap::print_summary(ostream& out) { out << "e" << get_epoch() << ": " << get_num_osds() << " osds: " << get_num_up_osds() << " up, " << get_num_in_osds() << " in"; if (blacklist.size()) out << ", " << blacklist.size() << " blacklisted"; } void OSDMap::build_simple(epoch_t e, ceph_fsid_t &fsid, int num_osd, int num_dom, int pg_bits, int lpg_bits, int mds_local_osd) { dout(10) << "build_simple on " << num_osd << " osds with " << pg_bits << " pg bits per osd, " << lpg_bits << " lpg bits" << dendl; epoch = e; set_fsid(fsid); mtime = ctime = g_clock.now(); set_max_osd(num_osd); pg_num = pgp_num = num_osd << pg_bits; lpg_num = lpgp_num = lpg_bits ? (1 << (lpg_bits-1)) : 0; // crush map build_simple_crush_map(crush, num_osd, num_dom); for (int i=0; i<num_osd; i++) { set_state(i, CEPH_OSD_EXISTS); set_weight(i, CEPH_OSD_OUT); } if (mds_local_osd) { set_max_osd(mds_local_osd+num_osd); // add mds local osds, but don't put them in the crush mapping func for (int i=0; i<mds_local_osd; i++) { set_state(i+num_osd, CEPH_OSD_EXISTS); set_weight(i+num_osd, CEPH_OSD_OUT); } } } void OSDMap::build_simple_crush_map(CrushWrapper& crush, int num_osd, int num_dom) { // new crush.create(); crush.set_type_name(1, "domain"); crush.set_type_name(2, "pool"); int npools = 3; int minrep = g_conf.osd_min_rep; int ndom = num_dom; if (!ndom) ndom = MAX(g_conf.osd_max_rep, g_conf.osd_max_raid_width); if (num_osd >= ndom*3 && num_osd > 8) { int ritems[ndom]; int rweights[ndom]; int nper = ((num_osd - 1) / ndom) + 1; derr(0) << ndom << " failure domains, " << nper << " osds each" << dendl; int o = 0; for (int i=0; i<ndom; i++) { int items[nper], weights[nper]; int j; rweights[i] = 0; for (j=0; j<nper; j++, o++) { if (o == num_osd) break; dout(20) << "added osd" << o << dendl; items[j] = o; weights[j] = 0x10000; //w[j] = weights[o] ? (0x10000 - (int)(weights[o] * 0x10000)):0x10000; //rweights[i] += w[j]; rweights[i] += 0x10000; } crush_bucket *domain = crush_make_bucket(CRUSH_BUCKET_UNIFORM, 1, j, items, weights); ritems[i] = crush_add_bucket(crush.crush, 0, domain); dout(20) << "added domain bucket i " << ritems[i] << " of size " << j << dendl; char bname[10]; sprintf(bname, "dom%d", i); crush.set_item_name(ritems[i], bname); } // root crush_bucket *root = crush_make_bucket(CRUSH_BUCKET_STRAW, 2, ndom, ritems, rweights); int rootid = crush_add_bucket(crush.crush, 0, root); crush.set_item_name(rootid, "root"); // rules // replication for (int pool=0; pool<npools; pool++) { // size minrep..ndom crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_REP, minrep, g_conf.osd_max_rep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_FIRSTN, CRUSH_CHOOSE_N, 1); // choose N domains crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, get_pool_name(pool)); } // raid if (false && g_conf.osd_min_raid_width <= g_conf.osd_max_raid_width) for (int pool=0; pool<npools; pool++) { crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_RAID4, g_conf.osd_min_raid_width, g_conf.osd_max_raid_width); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_INDEP, CRUSH_CHOOSE_N, 1); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); crush_add_rule(crush.crush, rule, -1); } } else { // one bucket int items[num_osd]; int weights[num_osd]; for (int i=0; i<num_osd; i++) { items[i] = i; weights[i] = 0x10000; } crush_bucket *b = crush_make_bucket(CRUSH_BUCKET_STRAW, 1, num_osd, items, weights); int rootid = crush_add_bucket(crush.crush, 0, b); crush.set_item_name(rootid, "root"); // replication for (int pool=0; pool<npools; pool++) { crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_REP, g_conf.osd_min_rep, g_conf.osd_max_rep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_FIRSTN, CRUSH_CHOOSE_N, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, get_pool_name(pool)); } // raid4 if (false && g_conf.osd_min_raid_width <= g_conf.osd_max_raid_width) for (int pool=0; pool<npools; pool++) { crush_rule *rule = crush_make_rule(3, pool, CEPH_PG_TYPE_RAID4, g_conf.osd_min_raid_width, g_conf.osd_max_raid_width); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_INDEP, CRUSH_CHOOSE_N, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); crush_add_rule(crush.crush, rule, -1); } } crush.finalize(); dout(20) << "crush max_devices " << crush.crush->max_devices << dendl; } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DISABLE_ENCRYPTION #include <cassert> #include <algorithm> #include <openssl/dh.h> #include <openssl/engine.h> #include "libtorrent/pe_crypto.hpp" namespace libtorrent { // Set the prime P and the generator, generate local public key DH_key_exchange::DH_key_exchange () { m_DH = DH_new (); m_DH->p = BN_bin2bn (m_dh_prime, sizeof(m_dh_prime), NULL); m_DH->g = BN_bin2bn (m_dh_generator, sizeof(m_dh_generator), NULL); assert (sizeof(m_dh_prime) == DH_size(m_DH)); DH_generate_key (m_DH); // TODO Check != 0 assert (m_DH->pub_key); // DH can generate key sizes that are smaller than the size of // P with exponentially decreasing probability, in which case // the msb's of m_dh_local_key need to be zeroed // appropriately. int key_size = get_local_key_size(); int len_dh = sizeof(m_dh_prime); // must equal DH_size(m_DH) if (key_size != len_dh) { assert(key_size > 0 && key_size < len_dh); int pad_zero_size = len_dh - key_size; std::fill(m_dh_local_key, m_dh_local_key + pad_zero_size, 0); BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key + pad_zero_size); } else BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key); // TODO Check return value } DH_key_exchange::~DH_key_exchange () { assert (m_DH); DH_free (m_DH); } char const* DH_key_exchange::get_local_key () const { return m_dh_local_key; } // compute shared secret given remote public key void DH_key_exchange::compute_secret (char const* remote_pubkey) { assert (remote_pubkey); BIGNUM* bn_remote_pubkey = BN_bin2bn ((unsigned char*)remote_pubkey, 96, NULL); int ret = DH_compute_key ( (unsigned char*)m_dh_secret, bn_remote_pubkey, m_DH); // TODO Check for errors BN_free (bn_remote_pubkey); } char const* DH_key_exchange::get_secret () const { return m_dh_secret; } const unsigned char DH_key_exchange::m_dh_prime[96] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x05, 0x63 }; const unsigned char DH_key_exchange::m_dh_generator[1] = { 2 }; } // namespace libtorrent #endif // #ifndef TORRENT_DISABLE_ENCRYPTION <commit_msg>fixed bug in shared secret generation<commit_after>/* Copyright (c) 2007, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DISABLE_ENCRYPTION #include <cassert> #include <algorithm> #include <openssl/dh.h> #include <openssl/engine.h> #include "libtorrent/pe_crypto.hpp" namespace libtorrent { // Set the prime P and the generator, generate local public key DH_key_exchange::DH_key_exchange () { m_DH = DH_new (); m_DH->p = BN_bin2bn (m_dh_prime, sizeof(m_dh_prime), NULL); m_DH->g = BN_bin2bn (m_dh_generator, sizeof(m_dh_generator), NULL); m_DH->length = 160l; assert (sizeof(m_dh_prime) == DH_size(m_DH)); DH_generate_key (m_DH); // TODO Check != 0 assert (m_DH->pub_key); // DH can generate key sizes that are smaller than the size of // P with exponentially decreasing probability, in which case // the msb's of m_dh_local_key need to be zeroed // appropriately. int key_size = get_local_key_size(); int len_dh = sizeof(m_dh_prime); // must equal DH_size(m_DH) if (key_size != len_dh) { assert(key_size > 0 && key_size < len_dh); int pad_zero_size = len_dh - key_size; std::fill(m_dh_local_key, m_dh_local_key + pad_zero_size, 0); BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key + pad_zero_size); } else BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key); // TODO Check return value } DH_key_exchange::~DH_key_exchange () { assert (m_DH); DH_free (m_DH); } char const* DH_key_exchange::get_local_key () const { return m_dh_local_key; } // compute shared secret given remote public key void DH_key_exchange::compute_secret (char const* remote_pubkey) { assert (remote_pubkey); BIGNUM* bn_remote_pubkey = BN_bin2bn ((unsigned char*)remote_pubkey, 96, NULL); char dh_secret[96]; int secret_size = DH_compute_key ( (unsigned char*)dh_secret, bn_remote_pubkey, m_DH); // TODO Check for errors if (secret_size != 96) { assert(secret_size < 96 && secret_size > 0); std::fill(m_dh_secret, m_dh_secret + 96 - secret_size, 0); } std::copy(dh_secret, dh_secret + secret_size, m_dh_secret + 96 - secret_size); BN_free (bn_remote_pubkey); } char const* DH_key_exchange::get_secret () const { return m_dh_secret; } const unsigned char DH_key_exchange::m_dh_prime[96] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x05, 0x63 }; const unsigned char DH_key_exchange::m_dh_generator[1] = { 2 }; } // namespace libtorrent #endif // #ifndef TORRENT_DISABLE_ENCRYPTION <|endoftext|>
<commit_before>/* Copyright (c) 2007, Un Shyam & Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DISABLE_ENCRYPTION #include <algorithm> #include <openssl/dh.h> #include <openssl/engine.h> #include "libtorrent/pe_crypto.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { // Set the prime P and the generator, generate local public key DH_key_exchange::DH_key_exchange() { m_DH = DH_new(); if (m_DH == 0) throw std::bad_alloc(); m_DH->p = BN_bin2bn(m_dh_prime, sizeof(m_dh_prime), NULL); m_DH->g = BN_bin2bn(m_dh_generator, sizeof(m_dh_generator), NULL); if (m_DH->p == 0 || m_DH->g == 0) { DH_free(m_DH); throw std::bad_alloc(); } m_DH->length = 160l; TORRENT_ASSERT(sizeof(m_dh_prime) == DH_size(m_DH)); DH_generate_key(m_DH); if (m_DH->pub_key == 0) { DH_free(m_DH); throw std::bad_alloc(); } // DH can generate key sizes that are smaller than the size of // P with exponentially decreasing probability, in which case // the msb's of m_dh_local_key need to be zeroed // appropriately. int key_size = get_local_key_size(); int len_dh = sizeof(m_dh_prime); // must equal DH_size(m_DH) if (key_size != len_dh) { TORRENT_ASSERT(key_size > 0 && key_size < len_dh); int pad_zero_size = len_dh - key_size; std::fill(m_dh_local_key, m_dh_local_key + pad_zero_size, 0); BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key + pad_zero_size); } else BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key); // TODO Check return value } DH_key_exchange::~DH_key_exchange() { TORRENT_ASSERT(m_DH); DH_free(m_DH); } char const* DH_key_exchange::get_local_key() const { return m_dh_local_key; } // compute shared secret given remote public key void DH_key_exchange::compute_secret(char const* remote_pubkey) { TORRENT_ASSERT(remote_pubkey); BIGNUM* bn_remote_pubkey = BN_bin2bn ((unsigned char*)remote_pubkey, 96, NULL); if (bn_remote_pubkey == 0) throw std::bad_alloc(); char dh_secret[96]; int secret_size = DH_compute_key((unsigned char*)dh_secret , bn_remote_pubkey, m_DH); if (secret_size < 0 || secret_size > 96) throw std::bad_alloc(); if (secret_size != 96) { TORRENT_ASSERT(secret_size < 96 && secret_size > 0); std::fill(m_dh_secret, m_dh_secret + 96 - secret_size, 0); } std::copy(dh_secret, dh_secret + secret_size, m_dh_secret + 96 - secret_size); BN_free(bn_remote_pubkey); } char const* DH_key_exchange::get_secret() const { return m_dh_secret; } const unsigned char DH_key_exchange::m_dh_prime[96] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x05, 0x63 }; const unsigned char DH_key_exchange::m_dh_generator[1] = { 2 }; } // namespace libtorrent #endif // #ifndef TORRENT_DISABLE_ENCRYPTION <commit_msg>fixed error handling in pe-crypto<commit_after>/* Copyright (c) 2007, Un Shyam & Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DISABLE_ENCRYPTION #include <algorithm> #include <openssl/dh.h> #include <openssl/engine.h> #include "libtorrent/pe_crypto.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { // Set the prime P and the generator, generate local public key DH_key_exchange::DH_key_exchange() { m_DH = DH_new(); if (m_DH == 0) throw std::bad_alloc(); m_DH->p = BN_bin2bn(m_dh_prime, sizeof(m_dh_prime), NULL); m_DH->g = BN_bin2bn(m_dh_generator, sizeof(m_dh_generator), NULL); if (m_DH->p == 0 || m_DH->g == 0) { DH_free(m_DH); throw std::bad_alloc(); } m_DH->length = 160l; TORRENT_ASSERT(sizeof(m_dh_prime) == DH_size(m_DH)); if (DH_generate_key(m_DH) == 0 || m_DH->pub_key == 0) { DH_free(m_DH); throw std::bad_alloc(); } // DH can generate key sizes that are smaller than the size of // P with exponentially decreasing probability, in which case // the msb's of m_dh_local_key need to be zeroed // appropriately. int key_size = get_local_key_size(); int len_dh = sizeof(m_dh_prime); // must equal DH_size(m_DH) if (key_size != len_dh) { TORRENT_ASSERT(key_size > 0 && key_size < len_dh); int pad_zero_size = len_dh - key_size; std::fill(m_dh_local_key, m_dh_local_key + pad_zero_size, 0); BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key + pad_zero_size); } else BN_bn2bin(m_DH->pub_key, (unsigned char*)m_dh_local_key); // TODO Check return value } DH_key_exchange::~DH_key_exchange() { TORRENT_ASSERT(m_DH); DH_free(m_DH); } char const* DH_key_exchange::get_local_key() const { return m_dh_local_key; } // compute shared secret given remote public key void DH_key_exchange::compute_secret(char const* remote_pubkey) { TORRENT_ASSERT(remote_pubkey); BIGNUM* bn_remote_pubkey = BN_bin2bn ((unsigned char*)remote_pubkey, 96, NULL); if (bn_remote_pubkey == 0) throw std::bad_alloc(); char dh_secret[96]; int secret_size = DH_compute_key((unsigned char*)dh_secret , bn_remote_pubkey, m_DH); if (secret_size < 0 || secret_size > 96) throw std::bad_alloc(); if (secret_size != 96) { TORRENT_ASSERT(secret_size < 96 && secret_size > 0); std::fill(m_dh_secret, m_dh_secret + 96 - secret_size, 0); } std::copy(dh_secret, dh_secret + secret_size, m_dh_secret + 96 - secret_size); BN_free(bn_remote_pubkey); } char const* DH_key_exchange::get_secret() const { return m_dh_secret; } const unsigned char DH_key_exchange::m_dh_prime[96] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x05, 0x63 }; const unsigned char DH_key_exchange::m_dh_generator[1] = { 2 }; } // namespace libtorrent #endif // #ifndef TORRENT_DISABLE_ENCRYPTION <|endoftext|>
<commit_before>/** * Copyright (c) 2007-2012, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. * * @file piper_proc.cc */ #include "config.h" #include <stdio.h> #include <string.h> #include <errno.h> #include <paths.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/param.h> #include <sys/time.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include "lnav_log.hh" #include "piper_proc.hh" #include "line_buffer.hh" using namespace std; static const char *STDIN_EOF_MSG = "---- END-OF-STDIN ----"; static ssize_t write_timestamp(int fd, off_t woff) { char time_str[64]; struct timeval tv; char ms_str[8]; gettimeofday(&tv, NULL); strftime(time_str, sizeof(time_str), "%FT%T", localtime(&tv.tv_sec)); snprintf(ms_str, sizeof(ms_str), ".%03d", (int)(tv.tv_usec / 1000)); strcat(time_str, ms_str); strcat(time_str, " "); return pwrite(fd, time_str, strlen(time_str), woff); } piper_proc::piper_proc(int pipefd, bool timestamp, const char *filename) : pp_fd(-1), pp_child(-1) { require(pipefd >= 0); if (filename) { if ((this->pp_fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0600)) == -1) { perror("Unable to open output file for stdin"); throw error(errno); } } else { char piper_tmpname[PATH_MAX]; const char *tmpdir; if ((tmpdir = getenv("TMPDIR")) == NULL) { tmpdir = _PATH_VARTMP; } snprintf(piper_tmpname, sizeof(piper_tmpname), "%s/lnav.piper.XXXXXX", tmpdir); if ((this->pp_fd = mkstemp(piper_tmpname)) == -1) { throw error(errno); } unlink(piper_tmpname); } fcntl(this->pp_fd.get(), F_SETFD, FD_CLOEXEC); this->pp_child = fork(); switch (this->pp_child) { case -1: throw error(errno); case 0: { auto_fd infd(pipefd); line_buffer lb; off_t woff = 0, last_woff = 0; off_t off = 0, last_off = 0; int nullfd; nullfd = open("/dev/null", O_RDWR); dup2(nullfd, STDIN_FILENO); dup2(nullfd, STDOUT_FILENO); for (int fd_to_close = 0; fd_to_close < 1024; fd_to_close++) { int flags; if (fd_to_close == this->pp_fd.get()) { continue; } if ((flags = fcntl(fd_to_close, F_GETFD)) == -1) { continue; } if (flags & FD_CLOEXEC) { close(fd_to_close); } } fcntl(infd.get(), F_SETFL, O_NONBLOCK); lb.set_fd(infd); do { line_value lv; fd_set rready; FD_ZERO(&rready); FD_SET(lb.get_fd(), &rready); select(lb.get_fd() + 1, &rready, NULL, NULL, NULL); last_off = off; while (lb.read_line(off, lv, true)) { ssize_t wrc; last_woff = woff; if (timestamp) { wrc = write_timestamp(this->pp_fd, woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } woff += wrc; } /* Need to do pwrite here since the fd is used by the main * lnav process as well. */ wrc = pwrite(this->pp_fd, lv.lv_start, lv.lv_len, woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } woff += wrc; if (lv.lv_start[lv.lv_len - 1] != '\n') { off = last_off; woff = last_woff; } last_off = off; } } while (lb.get_file_size() == (ssize_t)-1); if (timestamp) { ssize_t wrc; wrc = write_timestamp(this->pp_fd, woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } woff += wrc; wrc = pwrite(this->pp_fd, STDIN_EOF_MSG, strlen(STDIN_EOF_MSG), woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } } } _exit(0); break; default: break; } } bool piper_proc::has_exited() { if (this->pp_child > 0) { int rc, status; rc = waitpid(this->pp_child, &status, WNOHANG); if (rc == -1 || rc == 0) { return false; } this->pp_child = -1; } return true; } piper_proc::~piper_proc() { if (this->pp_child > 0) { int status; kill(this->pp_child, SIGTERM); while (waitpid(this->pp_child, &status, 0) < 0 && (errno == EINTR)) { ; } this->pp_child = -1; } } <commit_msg>fix piping lnav<commit_after>/** * Copyright (c) 2007-2012, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. * * @file piper_proc.cc */ #include "config.h" #include <stdio.h> #include <string.h> #include <errno.h> #include <paths.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/param.h> #include <sys/time.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include "lnav_log.hh" #include "piper_proc.hh" #include "line_buffer.hh" using namespace std; static const char *STDIN_EOF_MSG = "---- END-OF-STDIN ----"; static ssize_t write_timestamp(int fd, off_t woff) { char time_str[64]; struct timeval tv; char ms_str[8]; gettimeofday(&tv, NULL); strftime(time_str, sizeof(time_str), "%FT%T", localtime(&tv.tv_sec)); snprintf(ms_str, sizeof(ms_str), ".%03d", (int)(tv.tv_usec / 1000)); strcat(time_str, ms_str); strcat(time_str, " "); return pwrite(fd, time_str, strlen(time_str), woff); } piper_proc::piper_proc(int pipefd, bool timestamp, const char *filename) : pp_fd(-1), pp_child(-1) { require(pipefd >= 0); if (filename) { if ((this->pp_fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0600)) == -1) { perror("Unable to open output file for stdin"); throw error(errno); } } else { char piper_tmpname[PATH_MAX]; const char *tmpdir; if ((tmpdir = getenv("TMPDIR")) == NULL) { tmpdir = _PATH_VARTMP; } snprintf(piper_tmpname, sizeof(piper_tmpname), "%s/lnav.piper.XXXXXX", tmpdir); if ((this->pp_fd = mkstemp(piper_tmpname)) == -1) { throw error(errno); } unlink(piper_tmpname); } fcntl(this->pp_fd.get(), F_SETFD, FD_CLOEXEC); this->pp_child = fork(); switch (this->pp_child) { case -1: throw error(errno); case 0: { auto_fd infd(pipefd); line_buffer lb; off_t woff = 0, last_woff = 0; off_t off = 0, last_off = 0; int nullfd; nullfd = open("/dev/null", O_RDWR); if (pipefd != STDIN_FILENO) { dup2(nullfd, STDIN_FILENO); } dup2(nullfd, STDOUT_FILENO); for (int fd_to_close = 0; fd_to_close < 1024; fd_to_close++) { int flags; if (fd_to_close == this->pp_fd.get()) { continue; } if ((flags = fcntl(fd_to_close, F_GETFD)) == -1) { continue; } if (flags & FD_CLOEXEC) { close(fd_to_close); } } fcntl(infd.get(), F_SETFL, O_NONBLOCK); lb.set_fd(infd); do { line_value lv; fd_set rready; FD_ZERO(&rready); FD_SET(lb.get_fd(), &rready); select(lb.get_fd() + 1, &rready, NULL, NULL, NULL); last_off = off; while (lb.read_line(off, lv, true)) { ssize_t wrc; last_woff = woff; if (timestamp) { wrc = write_timestamp(this->pp_fd, woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } woff += wrc; } /* Need to do pwrite here since the fd is used by the main * lnav process as well. */ wrc = pwrite(this->pp_fd, lv.lv_start, lv.lv_len, woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } woff += wrc; if (lv.lv_start[lv.lv_len - 1] != '\n') { off = last_off; woff = last_woff; } last_off = off; } } while (lb.get_file_size() == (ssize_t)-1); if (timestamp) { ssize_t wrc; wrc = write_timestamp(this->pp_fd, woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } woff += wrc; wrc = pwrite(this->pp_fd, STDIN_EOF_MSG, strlen(STDIN_EOF_MSG), woff); if (wrc == -1) { perror("Unable to write to output file for stdin"); break; } } } _exit(0); break; default: break; } } bool piper_proc::has_exited() { if (this->pp_child > 0) { int rc, status; rc = waitpid(this->pp_child, &status, WNOHANG); if (rc == -1 || rc == 0) { return false; } this->pp_child = -1; } return true; } piper_proc::~piper_proc() { if (this->pp_child > 0) { int status; kill(this->pp_child, SIGTERM); while (waitpid(this->pp_child, &status, 0) < 0 && (errno == EINTR)) { ; } this->pp_child = -1; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "pyinterp.h" namespace ledger { using namespace boost::python; #define EXC_TRANSLATOR(type) \ void exc_translate_ ## type(const type& err) { \ PyErr_SetString(PyExc_ArithmeticError, err.what()); \ } //EXC_TRANSLATOR(journal_error) void export_journal() { #if 0 class_< journal_t > ("Journal") ; #endif //register_optional_to_python<amount_t>(); //implicitly_convertible<string, amount_t>(); #define EXC_TRANSLATE(type) \ register_exception_translator<type>(&exc_translate_ ## type); //EXC_TRANSLATE(journal_error); } } // namespace ledger #if 0 xact_t& post_xact(const post_t& post) { return *post.xact; } unsigned int posts_len(xact_base_t& xact) { return xact.posts.size(); } post_t& posts_getitem(xact_base_t& xact, int i) { static int last_index = 0; static xact_base_t * last_xact = NULL; static posts_list::iterator elem; std::size_t len = xact.posts.size(); if (abs(i) >= len) { PyErr_SetString(PyExc_IndexError, _("Index out of range")); throw_error_already_set(); } if (&xact == last_xact && i == last_index + 1) { last_index = i; return **++elem; } int x = i < 0 ? len + i : i; elem = xact.posts.begin(); while (--x >= 0) elem++; last_xact = &xact; last_index = i; return **elem; } unsigned int xacts_len(journal_t& journal) { return journal.xacts.size(); } xact_t& xacts_getitem(journal_t& journal, int i) { static int last_index = 0; static journal_t * last_journal = NULL; static xacts_list::iterator elem; std::size_t len = journal.xacts.size(); if (abs(i) >= len) { PyErr_SetString(PyExc_IndexError, _("Index out of range")); throw_error_already_set(); } if (&journal == last_journal && i == last_index + 1) { last_index = i; return **++elem; } int x = i < 0 ? len + i : i; elem = journal.xacts.begin(); while (--x >= 0) elem++; last_journal = &journal; last_index = i; return **elem; } unsigned int accounts_len(account_t& account) { return account.accounts.size(); } account_t& accounts_getitem(account_t& account, int i) { static int last_index = 0; static account_t * last_account = NULL; static accounts_map::iterator elem; std::size_t len = account.accounts.size(); if (abs(i) >= len) { PyErr_SetString(PyExc_IndexError, _("Index out of range")); throw_error_already_set(); } if (&account == last_account && i == last_index + 1) { last_index = i; return *(*++elem).second; } int x = i < 0 ? len + i : i; elem = account.accounts.begin(); while (--x >= 0) elem++; last_account = &account; last_index = i; return *(*elem).second; } account_t * py_find_account_1(journal_t& journal, const string& name) { return journal.find_account(name); } account_t * py_find_account_2(journal_t& journal, const string& name, const bool auto_create) { return journal.find_account(name, auto_create); } bool py_add_xact(journal_t& journal, xact_t * xact) { return journal.add_xact(new xact_t(*xact)); } void py_add_post(xact_base_t& xact, post_t * post) { return xact.add_post(new post_t(*post)); } struct xact_base_wrap : public xact_base_t { PyObject * self; xact_base_wrap(PyObject * self_) : self(self_) {} virtual bool valid() const { return call_method<bool>(self, "valid"); } }; struct py_xact_finalizer_t : public xact_finalizer_t { object pyobj; py_xact_finalizer_t() {} py_xact_finalizer_t(object obj) : pyobj(obj) {} py_xact_finalizer_t(const py_xact_finalizer_t& other) : pyobj(other.pyobj) {} virtual bool operator()(xact_t& xact, bool post) { return call<bool>(pyobj.ptr(), xact, post); } }; std::list<py_xact_finalizer_t> py_finalizers; void py_add_xact_finalizer(journal_t& journal, object x) { py_finalizers.push_back(py_xact_finalizer_t(x)); journal.add_xact_finalizer(&py_finalizers.back()); } void py_remove_xact_finalizer(journal_t& journal, object x) { for (std::list<py_xact_finalizer_t>::iterator i = py_finalizers.begin(); i != py_finalizers.end(); i++) if ((*i).pyobj == x) { journal.remove_xact_finalizer(&(*i)); py_finalizers.erase(i); return; } } void py_run_xact_finalizers(journal_t& journal, xact_t& xact, bool post) { run_hooks(journal.xact_finalize_hooks, xact, post); } #define EXC_TRANSLATOR(type) \ void exc_translate_ ## type(const type& err) { \ PyErr_SetString(PyExc_RuntimeError, err.what()); \ } EXC_TRANSLATOR(balance_error) EXC_TRANSLATOR(interval_expr_error) EXC_TRANSLATOR(format_error) EXC_TRANSLATOR(parse_error) value_t py_post_amount(post_t * post) { return value_t(post->amount); } post_t::state_t py_xact_state(xact_t * xact) { post_t::state_t state; if (xact->get_state(&state)) return state; else return post_t::UNCLEARED; } void export_journal() { scope().attr("POST_NORMAL") = POST_NORMAL; scope().attr("POST_VIRTUAL") = POST_VIRTUAL; scope().attr("POST_BALANCE") = POST_BALANCE; scope().attr("POST_AUTO") = POST_AUTO; scope().attr("POST_BULK_ALLOC") = POST_BULK_ALLOC; scope().attr("POST_CALCULATED") = POST_CALCULATED; enum_< post_t::state_t > ("State") .value("Uncleared", post_t::UNCLEARED) .value("Cleared", post_t::CLEARED) .value("Pending", post_t::PENDING) ; class_< post_t > ("Post") .def(init<optional<account_t *> >()) .def(init<account_t *, amount_t, optional<unsigned int, const string&> >()) .def(self == self) .def(self != self) .add_property("xact", make_getter(&post_t::xact, return_value_policy<reference_existing_object>())) .add_property("account", make_getter(&post_t::account, return_value_policy<reference_existing_object>())) .add_property("amount", &py_post_amount) .def_readonly("amount_expr", &post_t::amount_expr) .add_property("cost", make_getter(&post_t::cost, return_internal_reference<1>())) .def_readonly("cost_expr", &post_t::cost_expr) .def_readwrite("state", &post_t::state) .def_readwrite("flags", &post_t::flags) .def_readwrite("note", &post_t::note) .def_readonly("beg_pos", &post_t::beg_pos) .def_readonly("beg_line", &post_t::beg_line) .def_readonly("end_pos", &post_t::end_pos) .def_readonly("end_line", &post_t::end_line) .def("actual_date", &post_t::actual_date) .def("effective_date", &post_t::effective_date) .def("date", &post_t::date) .def("use_effective_date", &post_t::use_effective_date) .def("valid", &post_t::valid) ; class_< account_t > ("Account", init<optional<account_t *, string, string> >() [with_custodian_and_ward<1, 2>()]) .def(self == self) .def(self != self) .def(self_ns::str(self)) .def("__len__", accounts_len) .def("__getitem__", accounts_getitem, return_internal_reference<1>()) .add_property("journal", make_getter(&account_t::journal, return_value_policy<reference_existing_object>())) .add_property("parent", make_getter(&account_t::parent, return_value_policy<reference_existing_object>())) .def_readwrite("name", &account_t::name) .def_readwrite("note", &account_t::note) .def_readonly("depth", &account_t::depth) .def_readonly("ident", &account_t::ident) .def("fullname", &account_t::fullname) .def("add_account", &account_t::add_account) .def("remove_account", &account_t::remove_account) .def("find_account", &account_t::find_account, return_value_policy<reference_existing_object>()) .def("valid", &account_t::valid) ; class_< journal_t > ("Journal") .def(self == self) .def(self != self) .def("__len__", xacts_len) .def("__getitem__", xacts_getitem, return_internal_reference<1>()) .add_property("master", make_getter(&journal_t::master, return_internal_reference<1>())) .add_property("basket", make_getter(&journal_t::basket, return_internal_reference<1>())) .def_readonly("sources", &journal_t::sources) .def_readwrite("price_db", &journal_t::price_db) .def("add_account", &journal_t::add_account) .def("remove_account", &journal_t::remove_account) .def("find_account", py_find_account_1, return_internal_reference<1>()) .def("find_account", py_find_account_2, return_internal_reference<1>()) .def("find_account_re", &journal_t::find_account_re, return_internal_reference<1>()) .def("add_xact", py_add_xact) .def("remove_xact", &journal_t::remove_xact) .def("add_xact_finalizer", py_add_xact_finalizer) .def("remove_xact_finalizer", py_remove_xact_finalizer) .def("run_xact_finalizers", py_run_xact_finalizers) .def("valid", &journal_t::valid) ; class_< xact_base_t, xact_base_wrap, boost::noncopyable > ("XactBase") .def("__len__", posts_len) .def("__getitem__", posts_getitem, return_internal_reference<1>()) .def_readonly("journal", &xact_base_t::journal) .def_readonly("src_idx", &xact_base_t::src_idx) .def_readonly("beg_pos", &xact_base_t::beg_pos) .def_readonly("beg_line", &xact_base_t::beg_line) .def_readonly("end_pos", &xact_base_t::end_pos) .def_readonly("end_line", &xact_base_t::end_line) .def("add_post", py_add_post) .def("remove_post", &xact_base_t::remove_post) .def(self == self) .def(self != self) .def("finalize", &xact_base_t::finalize) .def("valid", &xact_base_t::valid) ; class_< xact_t, bases<xact_base_t> > ("Xact") .add_property("date", &xact_t::date) .add_property("effective_date", &xact_t::effective_date) .add_property("actual_date", &xact_t::actual_date) .def_readwrite("code", &xact_t::code) .def_readwrite("payee", &xact_t::payee) .add_property("state", &py_xact_state) .def("valid", &xact_t::valid) ; #define EXC_TRANSLATE(type) \ register_error_translator<type>(&exc_translate_ ## type); EXC_TRANSLATE(balance_error); EXC_TRANSLATE(interval_expr_error); EXC_TRANSLATE(format_error); EXC_TRANSLATE(parse_error); } #endif <commit_msg>Added Python interface for journal_t<commit_after>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "pyinterp.h" #include "pyutils.h" #include "hooks.h" #include "journal.h" #include "xact.h" namespace ledger { using namespace boost::python; namespace { account_t& py_account_master(journal_t& journal) { return *journal.master; } commodity_pool_t& py_commodity_pool(journal_t& journal) { return *journal.commodity_pool; } long xacts_len(journal_t& journal) { return journal.xacts.size(); } xact_t& xacts_getitem(journal_t& journal, long i) { static long last_index = 0; static journal_t * last_journal = NULL; static xacts_list::iterator elem; long len = journal.xacts.size(); if (labs(i) >= len) { PyErr_SetString(PyExc_IndexError, _("Index out of range")); throw_error_already_set(); } if (&journal == last_journal && i == last_index + 1) { last_index = i; return **++elem; } long x = i < 0 ? len + i : i; elem = journal.xacts.begin(); while (--x >= 0) elem++; last_journal = &journal; last_index = i; return **elem; } long accounts_len(account_t& account) { return account.accounts.size(); } account_t& accounts_getitem(account_t& account, long i) { static long last_index = 0; static account_t * last_account = NULL; static accounts_map::iterator elem; long len = account.accounts.size(); if (labs(i) >= len) { PyErr_SetString(PyExc_IndexError, _("Index out of range")); throw_error_already_set(); } if (&account == last_account && i == last_index + 1) { last_index = i; return *(*++elem).second; } long x = i < 0 ? len + i : i; elem = account.accounts.begin(); while (--x >= 0) elem++; last_account = &account; last_index = i; return *(*elem).second; } account_t * py_find_account_1(journal_t& journal, const string& name) { return journal.find_account(name); } account_t * py_find_account_2(journal_t& journal, const string& name, const bool auto_create) { return journal.find_account(name, auto_create); } struct py_xact_finalizer_t : public xact_finalizer_t { object pyobj; py_xact_finalizer_t() {} py_xact_finalizer_t(object obj) : pyobj(obj) {} py_xact_finalizer_t(const py_xact_finalizer_t& other) : pyobj(other.pyobj) {} virtual bool operator()(xact_t& xact, bool post) { return call<bool>(pyobj.ptr(), xact, post); } }; std::list<py_xact_finalizer_t> py_finalizers; void py_add_xact_finalizer(journal_t& journal, object x) { py_finalizers.push_back(py_xact_finalizer_t(x)); journal.add_xact_finalizer(&py_finalizers.back()); } void py_remove_xact_finalizer(journal_t& journal, object x) { for (std::list<py_xact_finalizer_t>::iterator i = py_finalizers.begin(); i != py_finalizers.end(); i++) if ((*i).pyobj == x) { journal.remove_xact_finalizer(&(*i)); py_finalizers.erase(i); return; } } void py_run_xact_finalizers(journal_t& journal, xact_t& xact, bool post) { journal.xact_finalize_hooks.run_hooks(xact, post); } } // unnamed namespace void export_journal() { class_< journal_t::fileinfo_t > ("FileInfo") .add_property("filename", make_getter(&journal_t::fileinfo_t::filename), make_setter(&journal_t::fileinfo_t::filename)) .add_property("size", make_getter(&journal_t::fileinfo_t::size), make_setter(&journal_t::fileinfo_t::size)) .add_property("modtime", make_getter(&journal_t::fileinfo_t::modtime), make_setter(&journal_t::fileinfo_t::modtime)) .add_property("from_stream", make_getter(&journal_t::fileinfo_t::from_stream), make_setter(&journal_t::fileinfo_t::from_stream)) ; class_< journal_t, boost::noncopyable > ("Journal") .add_property("master", make_getter(&journal_t::master, return_internal_reference<1>())) .add_property("basket", make_getter(&journal_t::basket, return_internal_reference<1>()), make_setter(&journal_t::basket)) .add_property("sources", make_getter(&journal_t::sources)) .add_property("was_loaded", make_getter(&journal_t::was_loaded)) .add_property("commodity_pool", make_getter(&journal_t::commodity_pool, return_internal_reference<1>())) #if 0 .add_property("xact_finalize_hooks", make_getter(&journal_t::xact_finalize_hooks), make_setter(&journal_t::xact_finalize_hooks)) #endif .def("add_account", &journal_t::add_account) .def("remove_account", &journal_t::remove_account) .def("find_account", py_find_account_1, return_internal_reference<1>()) .def("find_account", py_find_account_2, return_internal_reference<1>()) .def("find_account_re", &journal_t::find_account_re, return_internal_reference<1>()) .def("add_xact", &journal_t::add_xact) .def("remove_xact", &journal_t::remove_xact) .def("add_xact_finalizer", py_add_xact_finalizer) .def("remove_xact_finalizer", py_remove_xact_finalizer) .def("run_xact_finalizers", py_run_xact_finalizers) .def("__len__", xacts_len) .def("__getitem__", xacts_getitem, return_internal_reference<1>()) .def("valid", &journal_t::valid) ; } } // namespace ledger <|endoftext|>
<commit_before>#include "../NULLC/nullc.h" #if defined(_MSC_VER) #pragma warning(disable: 4996) #endif #include <stdio.h> #include <string.h> #include <stdlib.h> const char* translationDependencies[128]; unsigned translationDependencyCount = 0; void AddDependency(const char *fileName) { if(translationDependencyCount < 128) translationDependencies[translationDependencyCount++] = fileName; } bool AddSourceFile(char *&buf, const char *name) { if(FILE *file = fopen(name, "r")) { *(buf++) = ' '; strcpy(buf, name); buf += strlen(buf); fclose(file); return true; } return false; } bool SearchAndAddSourceFile(char*& buf, const char* name) { char tmp[256]; sprintf(tmp, "%s", name); if(AddSourceFile(buf, tmp)) return true; sprintf(tmp, "translation/%s", name); if(AddSourceFile(buf, tmp)) return true; sprintf(tmp, "../NULLC/translation/%s", name); if(AddSourceFile(buf, tmp)) return true; return false; } int main(int argc, char** argv) { nullcInit(); nullcAddImportPath("Modules/"); if(argc == 1) { printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n"); printf("usage: nullcl -c output.cpp file.nc\n"); printf("usage: nullcl -x output.exe file.nc\n"); return 1; } int argIndex = 1; FILE *mergeFile = NULL; bool verbose = false; if(strcmp("-v", argv[argIndex]) == 0) { argIndex++; verbose = true; } if(strcmp("-o", argv[argIndex]) == 0) { argIndex++; if(argIndex == argc) { printf("Output file name not found after -o\n"); nullcTerminate(); return 1; } mergeFile = fopen(argv[argIndex], "wb"); if(!mergeFile) { printf("Cannot create output file %s\n", argv[argIndex]); nullcTerminate(); return 1; } argIndex++; }else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){ bool link = strcmp("-x", argv[argIndex]) == 0; argIndex++; if(argIndex == argc) { printf("Output file name not found after -o\n"); nullcTerminate(); return 1; } const char *outputName = argv[argIndex++]; if(argIndex == argc) { printf("Input file name not found\n"); nullcTerminate(); return 1; } const char *fileName = argv[argIndex++]; FILE *ncFile = fopen(fileName, "rb"); if(!ncFile) { printf("Cannot open file %s\n", fileName); nullcTerminate(); return 1; } fseek(ncFile, 0, SEEK_END); unsigned int textSize = ftell(ncFile); fseek(ncFile, 0, SEEK_SET); char *fileContent = new char[textSize+1]; fread(fileContent, 1, textSize, ncFile); fileContent[textSize] = 0; fclose(ncFile); if(!nullcCompile(fileContent)) { printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError()); delete[] fileContent; return 1; } if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency)) { printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError()); delete[] fileContent; return 1; } if(link) { // $$$ move this to a dependency file? char cmdLine[4096]; char *pos = cmdLine; strcpy(pos, "gcc -g -o "); pos += strlen(pos); strcpy(pos, outputName); pos += strlen(pos); strcpy(pos, " __temp.cpp"); pos += strlen(pos); strcpy(pos, " -lstdc++"); pos += strlen(pos); strcpy(pos, " -Itranslation"); pos += strlen(pos); strcpy(pos, " -I../NULLC/translation"); pos += strlen(pos); strcpy(pos, " -O2"); pos += strlen(pos); if(!SearchAndAddSourceFile(pos, "runtime.cpp")) printf("Failed to find 'runtime.cpp' input file"); for(unsigned i = 0; i < translationDependencyCount; i++) { const char *dependency = translationDependencies[i]; *(pos++) = ' '; strcpy(pos, dependency); pos += strlen(pos); if(strstr(dependency, "import_")) { char tmp[256]; sprintf(tmp, "%s", dependency + strlen("import_")); if(char *pos = strstr(tmp, "_nc.cpp")) strcpy(pos, "_bind.cpp"); if(!SearchAndAddSourceFile(pos, tmp)) printf("Failed to find '%s' input file", tmp); } } if (verbose) printf("Command line: %s\n", cmdLine); system(cmdLine); } delete[] fileContent; nullcTerminate(); return 0; } int currIndex = argIndex; while(argIndex < argc) { const char *fileName = argv[argIndex++]; FILE *ncFile = fopen(fileName, "rb"); if(!ncFile) { printf("Cannot open file %s\n", fileName); break; } fseek(ncFile, 0, SEEK_END); unsigned int textSize = ftell(ncFile); fseek(ncFile, 0, SEEK_SET); char *fileContent = new char[textSize+1]; fread(fileContent, 1, textSize, ncFile); fileContent[textSize] = 0; fclose(ncFile); if(!nullcCompile(fileContent)) { printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError()); delete[] fileContent; nullcTerminate(); return 1; } unsigned int *bytecode = NULL; nullcGetBytecode((char**)&bytecode); delete[] fileContent; // Create module name char moduleName[1024]; if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0) { argIndex++; if(argIndex == argc) { printf("Module name not found after -m\n"); delete[] bytecode; break; } if(strlen(argv[argIndex]) + 1 >= 1024) { printf("Module name is too long\n"); delete[] bytecode; break; } strcpy(moduleName, argv[argIndex]); argIndex++; } else { if(strlen(fileName) + 1 >= 1024) { printf("File name is too long\n"); delete[] bytecode; break; } strcpy(moduleName, fileName); if(char *extensionPos = strchr(moduleName, '.')) *extensionPos = '\0'; char *pos = moduleName; while(*pos) { if(*pos++ == '\\' || *pos++ == '/') pos[-1] = '.'; } } nullcLoadModuleByBinary(moduleName, (const char*)bytecode); if(!mergeFile) { char newName[1024]; // Ont extra character for 'm' appended at the end if(strlen(fileName) + 1 >= 1024 - 1) { printf("File name is too long\n"); delete[] bytecode; break; } strcpy(newName, fileName); strcat(newName, "m"); FILE *nmcFile = fopen(newName, "wb"); if(!nmcFile) { printf("Cannot create output file %s\n", newName); delete[] bytecode; break; } fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile); fwrite(bytecode, 1, *bytecode, nmcFile); fclose(nmcFile); }else{ fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile); fwrite(bytecode, 1, *bytecode, mergeFile); } delete[] bytecode; } if(currIndex == argIndex) printf("None of the input files were found\n"); if(mergeFile) fclose(mergeFile); nullcTerminate(); return argIndex != argc; } <commit_msg>Improve translation usability in nullcl, link in missing math library<commit_after>#include "../NULLC/nullc.h" #if defined(_MSC_VER) #pragma warning(disable: 4996) #endif #include <stdio.h> #include <string.h> #include <stdlib.h> const char* translationDependencies[128]; unsigned translationDependencyCount = 0; void AddDependency(const char *fileName) { if(translationDependencyCount < 128) translationDependencies[translationDependencyCount++] = fileName; } bool AddSourceFile(char *&buf, const char *name) { if(FILE *file = fopen(name, "r")) { *(buf++) = ' '; strcpy(buf, name); buf += strlen(buf); fclose(file); return true; } return false; } bool SearchAndAddSourceFile(char*& buf, const char* name) { char tmp[256]; sprintf(tmp, "%s", name); if(AddSourceFile(buf, tmp)) return true; sprintf(tmp, "translation/%s", name); if(AddSourceFile(buf, tmp)) return true; sprintf(tmp, "NULLC/translation/%s", name); if(AddSourceFile(buf, tmp)) return true; sprintf(tmp, "../NULLC/translation/%s", name); if(AddSourceFile(buf, tmp)) return true; return false; } int main(int argc, char** argv) { nullcInit(); nullcAddImportPath("Modules/"); if(argc == 1) { printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n"); printf("usage: nullcl -c output.cpp file.nc\n"); printf("usage: nullcl -x output.exe file.nc\n"); return 1; } int argIndex = 1; FILE *mergeFile = NULL; bool verbose = false; if(strcmp("-v", argv[argIndex]) == 0) { argIndex++; verbose = true; } if(strcmp("-o", argv[argIndex]) == 0) { argIndex++; if(argIndex == argc) { printf("Output file name not found after -o\n"); nullcTerminate(); return 1; } mergeFile = fopen(argv[argIndex], "wb"); if(!mergeFile) { printf("Cannot create output file %s\n", argv[argIndex]); nullcTerminate(); return 1; } argIndex++; }else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){ bool link = strcmp("-x", argv[argIndex]) == 0; argIndex++; if(argIndex == argc) { printf("Output file name not found after -o\n"); nullcTerminate(); return 1; } const char *outputName = argv[argIndex++]; if(argIndex == argc) { printf("Input file name not found\n"); nullcTerminate(); return 1; } const char *fileName = argv[argIndex++]; FILE *ncFile = fopen(fileName, "rb"); if(!ncFile) { printf("Cannot open file %s\n", fileName); nullcTerminate(); return 1; } fseek(ncFile, 0, SEEK_END); unsigned int textSize = ftell(ncFile); fseek(ncFile, 0, SEEK_SET); char *fileContent = new char[textSize+1]; fread(fileContent, 1, textSize, ncFile); fileContent[textSize] = 0; fclose(ncFile); if(!nullcCompile(fileContent)) { printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError()); delete[] fileContent; return 1; } if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency)) { printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError()); delete[] fileContent; return 1; } if(link) { // $$$ move this to a dependency file? char cmdLine[4096]; char *pos = cmdLine; strcpy(pos, "gcc -g -o "); pos += strlen(pos); strcpy(pos, outputName); pos += strlen(pos); strcpy(pos, " __temp.cpp"); pos += strlen(pos); strcpy(pos, " -Itranslation"); pos += strlen(pos); strcpy(pos, " -INULLC/translation"); pos += strlen(pos); strcpy(pos, " -I../NULLC/translation"); pos += strlen(pos); strcpy(pos, " -O2"); pos += strlen(pos); if(!SearchAndAddSourceFile(pos, "runtime.cpp")) printf("Failed to find 'runtime.cpp' input file\n"); for(unsigned i = 0; i < translationDependencyCount; i++) { const char *dependency = translationDependencies[i]; *(pos++) = ' '; strcpy(pos, dependency); pos += strlen(pos); if(strstr(dependency, "import_")) { char tmp[256]; sprintf(tmp, "%s", dependency + strlen("import_")); if(char *pos = strstr(tmp, "_nc.cpp")) strcpy(pos, "_bind.cpp"); if(!SearchAndAddSourceFile(pos, tmp)) printf("Failed to find '%s' input file\n", tmp); } } strcpy(pos, " -lstdc++ -lm"); pos += strlen(pos); if (verbose) printf("Command line: %s\n", cmdLine); system(cmdLine); } delete[] fileContent; nullcTerminate(); return 0; } int currIndex = argIndex; while(argIndex < argc) { const char *fileName = argv[argIndex++]; FILE *ncFile = fopen(fileName, "rb"); if(!ncFile) { printf("Cannot open file %s\n", fileName); break; } fseek(ncFile, 0, SEEK_END); unsigned int textSize = ftell(ncFile); fseek(ncFile, 0, SEEK_SET); char *fileContent = new char[textSize+1]; fread(fileContent, 1, textSize, ncFile); fileContent[textSize] = 0; fclose(ncFile); if(!nullcCompile(fileContent)) { printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError()); delete[] fileContent; nullcTerminate(); return 1; } unsigned int *bytecode = NULL; nullcGetBytecode((char**)&bytecode); delete[] fileContent; // Create module name char moduleName[1024]; if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0) { argIndex++; if(argIndex == argc) { printf("Module name not found after -m\n"); delete[] bytecode; break; } if(strlen(argv[argIndex]) + 1 >= 1024) { printf("Module name is too long\n"); delete[] bytecode; break; } strcpy(moduleName, argv[argIndex]); argIndex++; } else { if(strlen(fileName) + 1 >= 1024) { printf("File name is too long\n"); delete[] bytecode; break; } strcpy(moduleName, fileName); if(char *extensionPos = strchr(moduleName, '.')) *extensionPos = '\0'; char *pos = moduleName; while(*pos) { if(*pos++ == '\\' || *pos++ == '/') pos[-1] = '.'; } } nullcLoadModuleByBinary(moduleName, (const char*)bytecode); if(!mergeFile) { char newName[1024]; // Ont extra character for 'm' appended at the end if(strlen(fileName) + 1 >= 1024 - 1) { printf("File name is too long\n"); delete[] bytecode; break; } strcpy(newName, fileName); strcat(newName, "m"); FILE *nmcFile = fopen(newName, "wb"); if(!nmcFile) { printf("Cannot create output file %s\n", newName); delete[] bytecode; break; } fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile); fwrite(bytecode, 1, *bytecode, nmcFile); fclose(nmcFile); }else{ fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile); fwrite(bytecode, 1, *bytecode, mergeFile); } delete[] bytecode; } if(currIndex == argIndex) printf("None of the input files were found\n"); if(mergeFile) fclose(mergeFile); nullcTerminate(); return argIndex != argc; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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. */ #include "config.h" #include "memcached.h" #include "runtime.h" #include "statemachine_mcbp.h" #include <exception> #include <utilities/protocol2text.h> #include <platform/strerror.h> const char* to_string(const Connection::Priority& priority) { switch (priority) { case Connection::Priority::High: return "High"; case Connection::Priority::Medium: return "Medium"; case Connection::Priority::Low: return "Low"; } throw std::invalid_argument("No such priority: " + std::to_string(int(priority))); } Connection::Connection(SOCKET sfd, event_base* b) : socketDescriptor(sfd), base(b), sasl_conn(nullptr), admin(false), authenticated(false), username("unknown"), nodelay(false), refcount(0), engine_storage(nullptr), next(nullptr), thread(nullptr), parent_port(0), auth_context(nullptr), bucketIndex(0), bucketEngine(nullptr), peername("unknown"), sockname("unknown"), priority(Priority::Medium) { MEMCACHED_CONN_CREATE(this); } Connection::Connection(SOCKET sock, event_base* b, const struct listening_port& interface) : Connection(sock, b) { parent_port = interface.port; resolveConnectionName(false); setAuthContext(auth_create(NULL, peername.c_str(), sockname.c_str())); setTcpNoDelay(interface.tcp_nodelay); } Connection::~Connection() { MEMCACHED_CONN_DESTROY(this); auth_destroy(auth_context); cbsasl_dispose(&sasl_conn); if (socketDescriptor != INVALID_SOCKET) { LOG_INFO(this, "%u - Closing socket descriptor", getId()); safe_close(socketDescriptor); } } /** * Convert a sockaddr_storage to a textual string (no name lookup). * * @param addr the sockaddr_storage received from getsockname or * getpeername * @param addr_len the current length used by the sockaddr_storage * @return a textual string representing the connection. or NULL * if an error occurs (caller takes ownership of the buffer and * must call free) */ static std::string sockaddr_to_string(const struct sockaddr_storage* addr, socklen_t addr_len) { char host[50]; char port[50]; int err = getnameinfo(reinterpret_cast<const struct sockaddr*>(addr), addr_len, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV); if (err != 0) { LOG_WARNING(NULL, "getnameinfo failed with error %d", err); return NULL; } if (addr->ss_family == AF_INET6) { return "[" + std::string(host) + "]:" + std::string(port); } else { return std::string(host) + ":" + std::string(port); } } void Connection::resolveConnectionName(bool listening) { int err; try { if (listening) { peername = "*"; } else { struct sockaddr_storage peer; socklen_t peer_len = sizeof(peer); if ((err = getpeername(socketDescriptor, reinterpret_cast<struct sockaddr*>(&peer), &peer_len)) != 0) { LOG_WARNING(NULL, "getpeername for socket %d with error %d", socketDescriptor, err); } else { peername = sockaddr_to_string(&peer, peer_len); } } struct sockaddr_storage sock; socklen_t sock_len = sizeof(sock); if ((err = getsockname(socketDescriptor, reinterpret_cast<struct sockaddr*>(&sock), &sock_len)) != 0) { LOG_WARNING(NULL, "getsockname for socket %d with error %d", socketDescriptor, err); } else { sockname = sockaddr_to_string(&sock, sock_len); } } catch (std::bad_alloc& e) { LOG_WARNING(NULL, "Connection::resolveConnectionName: failed to allocate memory: %s", e.what()); } } bool Connection::setTcpNoDelay(bool enable) { int flags = enable ? 1 : 0; #if defined(WIN32) char* flags_ptr = reinterpret_cast<char*>(&flags); #else void* flags_ptr = reinterpret_cast<void*>(&flags); #endif int error = setsockopt(socketDescriptor, IPPROTO_TCP, TCP_NODELAY, flags_ptr, sizeof(flags)); if (error != 0) { std::string errmsg = cb_strerror(GetLastNetworkError()); LOG_WARNING(this, "setsockopt(TCP_NODELAY): %s", errmsg.c_str()); nodelay = false; return false; } else { nodelay = enable; } return true; } /* cJSON uses double for all numbers, so only has 53 bits of precision. * Therefore encode 64bit integers as string. */ static cJSON* json_create_uintptr(uintptr_t value) { char buffer[32]; if (snprintf(buffer, sizeof(buffer), "0x%" PRIxPTR, value) >= int(sizeof(buffer))) { return cJSON_CreateString("<too long>"); } else { return cJSON_CreateString(buffer); } } static void json_add_uintptr_to_object(cJSON* obj, const char* name, uintptr_t value) { cJSON_AddItemToObject(obj, name, json_create_uintptr(value)); } static void json_add_bool_to_object(cJSON* obj, const char* name, bool value) { if (value) { cJSON_AddTrueToObject(obj, name); } else { cJSON_AddFalseToObject(obj, name); } } const char* to_string(const Protocol& protocol) { if (protocol == Protocol::Memcached) { return "memcached"; } else if (protocol == Protocol::Greenstack) { return "greenstack"; } else { return "unknown"; } } const char* to_string(const ConnectionState& connectionState) { switch (connectionState) { case ConnectionState::ESTABLISHED: return "established"; case ConnectionState::OPEN: return "open"; case ConnectionState::AUTHENTICATED: return "authenticated"; } throw std::logic_error( "Unknown connection state: " + std::to_string(int(connectionState))); } cJSON* Connection::toJSON() const { cJSON* obj = cJSON_CreateObject(); json_add_uintptr_to_object(obj, "connection", (uintptr_t)this); if (socketDescriptor == INVALID_SOCKET) { cJSON_AddStringToObject(obj, "socket", "disconnected"); } else { cJSON_AddNumberToObject(obj, "socket", (double)socketDescriptor); cJSON_AddStringToObject(obj, "protocol", to_string(getProtocol())); cJSON_AddStringToObject(obj, "peername", getPeername().c_str()); cJSON_AddStringToObject(obj, "sockname", getSockname().c_str()); json_add_bool_to_object(obj, "admin", isAdmin()); if (sasl_conn != NULL) { json_add_uintptr_to_object(obj, "sasl_conn", (uintptr_t)sasl_conn); } json_add_bool_to_object(obj, "nodelay", nodelay); cJSON_AddNumberToObject(obj, "refcount", refcount); { cJSON* features = cJSON_CreateObject(); json_add_bool_to_object(features, "datatype", isSupportsDatatype()); json_add_bool_to_object(features, "mutation_extras", isSupportsMutationExtras()); cJSON_AddItemToObject(obj, "features", features); } json_add_uintptr_to_object(obj, "engine_storage", (uintptr_t)engine_storage); json_add_uintptr_to_object(obj, "next", (uintptr_t)next); json_add_uintptr_to_object(obj, "thread", (uintptr_t)thread.load( std::memory_order::memory_order_relaxed)); cJSON_AddNumberToObject(obj, "parent_port", parent_port); cJSON_AddStringToObject(obj, "priority", to_string(priority)); } return obj; } std::string Connection::getDescription() const { std::string descr("[ " + getPeername() + " - " + getSockname()); if (isAdmin()) { descr += " (Admin)"; } descr += " ]"; return descr; } <commit_msg>Add missing information to the connection dump<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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. */ #include "config.h" #include "memcached.h" #include "runtime.h" #include "statemachine_mcbp.h" #include <exception> #include <utilities/protocol2text.h> #include <platform/strerror.h> const char* to_string(const Connection::Priority& priority) { switch (priority) { case Connection::Priority::High: return "High"; case Connection::Priority::Medium: return "Medium"; case Connection::Priority::Low: return "Low"; } throw std::invalid_argument("No such priority: " + std::to_string(int(priority))); } Connection::Connection(SOCKET sfd, event_base* b) : socketDescriptor(sfd), base(b), sasl_conn(nullptr), admin(false), authenticated(false), username("unknown"), nodelay(false), refcount(0), engine_storage(nullptr), next(nullptr), thread(nullptr), parent_port(0), auth_context(nullptr), bucketIndex(0), bucketEngine(nullptr), peername("unknown"), sockname("unknown"), priority(Priority::Medium) { MEMCACHED_CONN_CREATE(this); } Connection::Connection(SOCKET sock, event_base* b, const struct listening_port& interface) : Connection(sock, b) { parent_port = interface.port; resolveConnectionName(false); setAuthContext(auth_create(NULL, peername.c_str(), sockname.c_str())); setTcpNoDelay(interface.tcp_nodelay); } Connection::~Connection() { MEMCACHED_CONN_DESTROY(this); auth_destroy(auth_context); cbsasl_dispose(&sasl_conn); if (socketDescriptor != INVALID_SOCKET) { LOG_INFO(this, "%u - Closing socket descriptor", getId()); safe_close(socketDescriptor); } } /** * Convert a sockaddr_storage to a textual string (no name lookup). * * @param addr the sockaddr_storage received from getsockname or * getpeername * @param addr_len the current length used by the sockaddr_storage * @return a textual string representing the connection. or NULL * if an error occurs (caller takes ownership of the buffer and * must call free) */ static std::string sockaddr_to_string(const struct sockaddr_storage* addr, socklen_t addr_len) { char host[50]; char port[50]; int err = getnameinfo(reinterpret_cast<const struct sockaddr*>(addr), addr_len, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV); if (err != 0) { LOG_WARNING(NULL, "getnameinfo failed with error %d", err); return NULL; } if (addr->ss_family == AF_INET6) { return "[" + std::string(host) + "]:" + std::string(port); } else { return std::string(host) + ":" + std::string(port); } } void Connection::resolveConnectionName(bool listening) { int err; try { if (listening) { peername = "*"; } else { struct sockaddr_storage peer; socklen_t peer_len = sizeof(peer); if ((err = getpeername(socketDescriptor, reinterpret_cast<struct sockaddr*>(&peer), &peer_len)) != 0) { LOG_WARNING(NULL, "getpeername for socket %d with error %d", socketDescriptor, err); } else { peername = sockaddr_to_string(&peer, peer_len); } } struct sockaddr_storage sock; socklen_t sock_len = sizeof(sock); if ((err = getsockname(socketDescriptor, reinterpret_cast<struct sockaddr*>(&sock), &sock_len)) != 0) { LOG_WARNING(NULL, "getsockname for socket %d with error %d", socketDescriptor, err); } else { sockname = sockaddr_to_string(&sock, sock_len); } } catch (std::bad_alloc& e) { LOG_WARNING(NULL, "Connection::resolveConnectionName: failed to allocate memory: %s", e.what()); } } bool Connection::setTcpNoDelay(bool enable) { int flags = enable ? 1 : 0; #if defined(WIN32) char* flags_ptr = reinterpret_cast<char*>(&flags); #else void* flags_ptr = reinterpret_cast<void*>(&flags); #endif int error = setsockopt(socketDescriptor, IPPROTO_TCP, TCP_NODELAY, flags_ptr, sizeof(flags)); if (error != 0) { std::string errmsg = cb_strerror(GetLastNetworkError()); LOG_WARNING(this, "setsockopt(TCP_NODELAY): %s", errmsg.c_str()); nodelay = false; return false; } else { nodelay = enable; } return true; } /* cJSON uses double for all numbers, so only has 53 bits of precision. * Therefore encode 64bit integers as string. */ static cJSON* json_create_uintptr(uintptr_t value) { char buffer[32]; if (snprintf(buffer, sizeof(buffer), "0x%" PRIxPTR, value) >= int(sizeof(buffer))) { return cJSON_CreateString("<too long>"); } else { return cJSON_CreateString(buffer); } } static void json_add_uintptr_to_object(cJSON* obj, const char* name, uintptr_t value) { cJSON_AddItemToObject(obj, name, json_create_uintptr(value)); } static void json_add_bool_to_object(cJSON* obj, const char* name, bool value) { if (value) { cJSON_AddTrueToObject(obj, name); } else { cJSON_AddFalseToObject(obj, name); } } const char* to_string(const Protocol& protocol) { if (protocol == Protocol::Memcached) { return "memcached"; } else if (protocol == Protocol::Greenstack) { return "greenstack"; } else { return "unknown"; } } const char* to_string(const ConnectionState& connectionState) { switch (connectionState) { case ConnectionState::ESTABLISHED: return "established"; case ConnectionState::OPEN: return "open"; case ConnectionState::AUTHENTICATED: return "authenticated"; } throw std::logic_error( "Unknown connection state: " + std::to_string(int(connectionState))); } cJSON* Connection::toJSON() const { cJSON* obj = cJSON_CreateObject(); json_add_uintptr_to_object(obj, "connection", (uintptr_t)this); if (socketDescriptor == INVALID_SOCKET) { cJSON_AddStringToObject(obj, "socket", "disconnected"); } else { cJSON_AddNumberToObject(obj, "socket", (double)socketDescriptor); cJSON_AddStringToObject(obj, "protocol", to_string(getProtocol())); cJSON_AddStringToObject(obj, "peername", getPeername().c_str()); cJSON_AddStringToObject(obj, "sockname", getSockname().c_str()); cJSON_AddNumberToObject(obj, "parent_port", parent_port); cJSON_AddNumberToObject(obj, "bucket_index", bucketIndex); json_add_bool_to_object(obj, "admin", isAdmin()); if (authenticated) { cJSON_AddStringToObject(obj, "username", username.c_str()); } if (sasl_conn != NULL) { json_add_uintptr_to_object(obj, "sasl_conn", (uintptr_t)sasl_conn); } json_add_bool_to_object(obj, "nodelay", nodelay); cJSON_AddNumberToObject(obj, "refcount", refcount); cJSON* features = cJSON_CreateObject(); json_add_bool_to_object(features, "datatype", isSupportsDatatype()); json_add_bool_to_object(features, "mutation_extras", isSupportsMutationExtras()); cJSON_AddItemToObject(obj, "features", features); json_add_uintptr_to_object(obj, "engine_storage", (uintptr_t)engine_storage); json_add_uintptr_to_object(obj, "next", (uintptr_t)next); json_add_uintptr_to_object(obj, "thread", (uintptr_t)thread.load( std::memory_order::memory_order_relaxed)); cJSON_AddStringToObject(obj, "priority", to_string(priority)); } return obj; } std::string Connection::getDescription() const { std::string descr("[ " + getPeername() + " - " + getSockname()); if (isAdmin()) { descr += " (Admin)"; } descr += " ]"; return descr; } <|endoftext|>
<commit_before>// Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gmock/gmock.h> #include <gtest/gtest.h> #include <QCoreApplication> #include <QEventLoop> #include <QObject> #include <QTimer> #include <chrono> #include "QtUtils/Throttle.h" namespace orbit_qt_utils { // This Wait function uses QTimer for waiting and therefore relies on the OS to wake the thread back // up when the timer expired. This ensures that `Wait` doesn't return earlier than the internal // QTimer used in `Throttle`. static void Wait(std::chrono::milliseconds interval) { QTimer timer{}; timer.setSingleShot(true); QEventLoop loop{}; QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); timer.start(interval); loop.exec(); } class MockReceiver : public QObject { public: MOCK_METHOD(void, Execute, (), (const)); }; constexpr std::chrono::milliseconds kStandardDelay{10}; TEST(Throttle, TriggersImmediatelyOnFirstFire) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // The first call leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); } TEST(Throttle, SecondImmediateFireLeadsToDelayedTrigger) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // The first call leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); // The second call will start the timer. The trigger will be expected after the interval has // passed. throttle.Fire(); EXPECT_CALL(receiver, Execute()).Times(1); Wait(kStandardDelay); QCoreApplication::processEvents(); } TEST(Throttle, SecondDelayedFireLeadsToImmediateTrigger) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // The first call leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); Wait(kStandardDelay); QCoreApplication::processEvents(); // The interval has passed, so the second call also leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); } TEST(Throttle, ThirdImmediateFireGetsConsumed) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // We fire 3 times. The first calls leads to an immediate trigger. The second starts the timer. // The third gets consumed and combined with the second. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); throttle.Fire(); throttle.Fire(); EXPECT_CALL(receiver, Execute()).Times(1); Wait(kStandardDelay); QCoreApplication::processEvents(); } TEST(Throttle, ThirdSlightlyDelayedFireGetsConsumed) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // We fire two times. The first triggers immediately, the second starts the timer. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); throttle.Fire(); // We wait half the interval and call again. This call will be consumed by the throttle and // combined with the previous delayed trigger. Wait(kStandardDelay / 2); QCoreApplication::processEvents(); throttle.Fire(); // After waiting for the interval, we expect the throttle to have triggered. EXPECT_CALL(receiver, Execute()).Times(1); Wait(kStandardDelay); QCoreApplication::processEvents(); } } // namespace orbit_qt_utils<commit_msg>Fix flaky Throttle test (#3989)<commit_after>// Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gmock/gmock.h> #include <gtest/gtest.h> #include <QCoreApplication> #include <QEventLoop> #include <QObject> #include <QTimer> #include <chrono> #include "QtUtils/Throttle.h" namespace orbit_qt_utils { // This Wait function uses QTimer for waiting and therefore relies on the OS to wake the thread back // up when the timer expired. This ensures that `Wait` doesn't return earlier than the internal // QTimer used in `Throttle`. static void Wait(std::chrono::milliseconds interval) { QTimer timer{}; timer.setSingleShot(true); QEventLoop loop{}; QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); // QTimer only guarantees an accuracy of 1 millisecond, which means the timer could // potentially time out 1 millisecond earlier than the requested delay. By waiting // 1 millisecond longer we avoid potential test failures. timer.start(interval + std::chrono::milliseconds{1}); loop.exec(); } class MockReceiver : public QObject { public: MOCK_METHOD(void, Execute, (), (const)); }; constexpr std::chrono::milliseconds kStandardDelay{10}; TEST(Throttle, TriggersImmediatelyOnFirstFire) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // The first call leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); } TEST(Throttle, SecondImmediateFireLeadsToDelayedTrigger) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // The first call leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); // The second call will start the timer. The trigger will be expected after the interval has // passed. throttle.Fire(); EXPECT_CALL(receiver, Execute()).Times(1); Wait(kStandardDelay); QCoreApplication::processEvents(); } TEST(Throttle, SecondDelayedFireLeadsToImmediateTrigger) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // The first call leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); Wait(kStandardDelay); QCoreApplication::processEvents(); // The interval has passed, so the second call also leads to an immediate trigger. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); } TEST(Throttle, ThirdImmediateFireGetsConsumed) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // We fire 3 times. The first calls leads to an immediate trigger. The second starts the timer. // The third gets consumed and combined with the second. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); throttle.Fire(); throttle.Fire(); EXPECT_CALL(receiver, Execute()).Times(1); Wait(kStandardDelay); QCoreApplication::processEvents(); } TEST(Throttle, ThirdSlightlyDelayedFireGetsConsumed) { Throttle throttle{kStandardDelay}; MockReceiver receiver{}; QObject::connect(&throttle, &Throttle::Triggered, &receiver, &MockReceiver::Execute); // We fire two times. The first triggers immediately, the second starts the timer. EXPECT_CALL(receiver, Execute()).Times(1); throttle.Fire(); throttle.Fire(); // We call processEvents here to ensure that it does NOT call MockReceiver::Execute. QCoreApplication::processEvents(); throttle.Fire(); // After waiting for the interval, we expect the throttle to have triggered. EXPECT_CALL(receiver, Execute()).Times(1); Wait(kStandardDelay); QCoreApplication::processEvents(); } } // namespace orbit_qt_utils<|endoftext|>
<commit_before>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include "logging.hpp" #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <sstream> #include <thread> #include <sys/time.h> namespace kurento { static std::string debug_object (GObject *object) { if (object == NULL) { return ""; } if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) { boost::format fmt ("<%s:%s> "); fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT ( object) ) : "''") % GST_OBJECT_NAME (object); return fmt.str(); } if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) { boost::format fmt ("<%s> "); fmt % GST_OBJECT_NAME (object); return fmt.str(); } if (G_IS_OBJECT (object) ) { boost::format fmt ("<%s@%p> "); fmt % G_OBJECT_TYPE_NAME (object) % object; return fmt.str(); } boost::format fmt ("<%p> "); fmt % object; return fmt.str(); } static std::string expand_string (std::string str, int len) { std::string ret = str; int sp = len - str.size (); for (int i = sp; i > 0; i--) { str.append (" "); } return str; } #define LOG expand_string(category->name, 25) << " " << \ boost::filesystem::path(file).filename().string() \ << ":" << line << " " << function << "() " << \ debug_object(object) << \ gst_debug_message_get(message) static std::string getDateTime () { timeval curTime; struct tm *timeinfo; char buffer[22]; gettimeofday (&curTime, NULL);; timeinfo = localtime (&curTime.tv_sec); strftime (buffer, 22, "%Y-%m-%d %H:%M:%S", timeinfo); std::string datetime (buffer); datetime.append ("."); std::string micros = std::to_string (curTime.tv_usec); while (micros.size() < 6) { micros = "0" + micros; } datetime.append (micros); return datetime; } void simple_log_function (GstDebugCategory *category, GstDebugLevel level, const gchar *file, const gchar *function, gint line, GObject *object, GstDebugMessage *message, gpointer user_data) { std::stringstream ss; if (level > gst_debug_category_get_threshold (category) ) { return; } ss << getDateTime() << " "; ss << getpid() << " "; ss << "[" << std::this_thread::get_id () << "]"; switch (level) { case GST_LEVEL_ERROR: ss << " error "; break; case GST_LEVEL_WARNING: ss << " warning "; break; case GST_LEVEL_FIXME: ss << " fixme "; break; case GST_LEVEL_INFO: ss << " info "; break; case GST_LEVEL_DEBUG: ss << " debug "; break; case GST_LEVEL_LOG: ss << " log "; break; case GST_LEVEL_TRACE: ss << " trace "; break; default: return; } ss << LOG << std::endl; std::cout << ss.str(); } } /* kurento */ <commit_msg>logging.cpp: Flush stdout after writing to ensure writing when redirected to a file<commit_after>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include "logging.hpp" #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <sstream> #include <thread> #include <sys/time.h> namespace kurento { static std::string debug_object (GObject *object) { if (object == NULL) { return ""; } if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) { boost::format fmt ("<%s:%s> "); fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT ( object) ) : "''") % GST_OBJECT_NAME (object); return fmt.str(); } if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) { boost::format fmt ("<%s> "); fmt % GST_OBJECT_NAME (object); return fmt.str(); } if (G_IS_OBJECT (object) ) { boost::format fmt ("<%s@%p> "); fmt % G_OBJECT_TYPE_NAME (object) % object; return fmt.str(); } boost::format fmt ("<%p> "); fmt % object; return fmt.str(); } static std::string expand_string (std::string str, int len) { std::string ret = str; int sp = len - str.size (); for (int i = sp; i > 0; i--) { str.append (" "); } return str; } #define LOG expand_string(category->name, 25) << " " << \ boost::filesystem::path(file).filename().string() \ << ":" << line << " " << function << "() " << \ debug_object(object) << \ gst_debug_message_get(message) static std::string getDateTime () { timeval curTime; struct tm *timeinfo; char buffer[22]; gettimeofday (&curTime, NULL);; timeinfo = localtime (&curTime.tv_sec); strftime (buffer, 22, "%Y-%m-%d %H:%M:%S", timeinfo); std::string datetime (buffer); datetime.append ("."); std::string micros = std::to_string (curTime.tv_usec); while (micros.size() < 6) { micros = "0" + micros; } datetime.append (micros); return datetime; } void simple_log_function (GstDebugCategory *category, GstDebugLevel level, const gchar *file, const gchar *function, gint line, GObject *object, GstDebugMessage *message, gpointer user_data) { std::stringstream ss; if (level > gst_debug_category_get_threshold (category) ) { return; } ss << getDateTime() << " "; ss << getpid() << " "; ss << "[" << std::this_thread::get_id () << "]"; switch (level) { case GST_LEVEL_ERROR: ss << " error "; break; case GST_LEVEL_WARNING: ss << " warning "; break; case GST_LEVEL_FIXME: ss << " fixme "; break; case GST_LEVEL_INFO: ss << " info "; break; case GST_LEVEL_DEBUG: ss << " debug "; break; case GST_LEVEL_LOG: ss << " log "; break; case GST_LEVEL_TRACE: ss << " trace "; break; default: return; } ss << LOG << std::endl; std::cout << ss.str(); std::cout.flush (); } } /* kurento */ <|endoftext|>
<commit_before>#include "TileCollideableGroup.hpp" #include "Tilemap.hpp" #include "comp/TileCollisionComponent.hpp" #include "Logfile.hpp" #include <unordered_set> #include <array> #include <algorithm> #include <functional> #include <compsys/Entity.hpp> TileCollideableInfo::TileCollideableInfo(jd::Tilemap& tilemap): m_tilemap(tilemap) { } void TileCollideableInfo::setProxy(unsigned tileId, TileCollisionComponent* proxy) { if (!proxy) { std::size_t const erasedCount = m_proxyEntities.erase(tileId); assert(erasedCount < 2); if (!erasedCount) LOG_W("Attempt to unset a proxy, which was not set."); } else if (!m_proxyEntities.insert(std::make_pair(tileId, proxy)).second) throw std::logic_error( __FUNCTION__ ": cannot assign proxy entity: already assigned"); } TileCollisionComponent* TileCollideableInfo::proxy(unsigned tileId) { auto const it = m_proxyEntities.find(tileId); if (it != m_proxyEntities.end()) return it->second.get(); return nullptr; } void TileCollideableInfo::setColliding(Vector3u pos, TileCollisionComponent* e) { auto const it = m_entities.find(pos); bool const found = it != m_entities.end(); if (e) { if (found) { it->second->notifyOverride(pos, *e); it->second = e; } else { bool const success = m_entities.insert(std::make_pair(pos, e)).second; assert(success); } } else if (found) { m_entities.erase(pos); } else { LOG_W("Attempt to unregister a TileCollisionComponent which was not registered."); } } TileCollisionComponent* TileCollideableInfo::colliding(Vector3u pos) { auto const it = m_entities.find(pos); if (it != m_entities.end()) return it->second.get(); return nullptr; } Vector3u TileCollideableInfo::mapsize() const { return m_tilemap.size(); } Collision TileCollideableInfo::makeCollision( Vector3u pos, Entity* e, sf::FloatRect const& r) { auto const iEntity = m_entities.find(pos); if (iEntity != m_entities.end()) { if (e) iEntity->second->notifyCollision(pos, *e, r); return Collision( iEntity->second->parent(), m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))); } else { unsigned const tileId = m_tilemap[pos]; auto const iProxy = m_proxyEntities.find(tileId); if (iProxy != m_proxyEntities.end()) { if (e) iProxy->second->notifyCollision(pos, *e, r); return Collision( iProxy->second->parent(), m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))); } } // if no entity at pos registered return Collision(); } std::vector<Collision> TileCollideableInfo::colliding( sf::FloatRect const& r, Entity* e, std::vector<Vector3u>* positions) { sf::Vector2u begin; sf::Vector2u last; std::size_t const intersectingCount = mapCorners(r, begin, last); std::vector<Collision> result; if (intersectingCount <= 0) return result; result.reserve(intersectingCount); Vector3u pos; for (pos.z = 0; pos.z < m_tilemap.size().z; ++pos.z) { for (pos.x = begin.x; pos.x <= last.x; ++pos.x) { for (pos.y = begin.y; pos.y <= last.y; ++pos.y) { auto const c = makeCollision(pos, e, r); if (c.entity) { if (positions) positions->push_back(pos); result.push_back(c); } } // for y } // for x } // for z return result; } namespace { std::array<sf::Vector2i, 8> surroundingTiles(sf::Vector2i p) { std::array<sf::Vector2i, 8> result; std::fill(result.begin(), result.end(), p); // 012 // 3p4 // 567 --result[0].x; --result[0].y; --result[1].y; ++result[2].x; --result[2].y; --result[3].x; ++result[4].x; --result[5].x; ++result[5].y; ++result[6].y; ++result[7].x; ++result[7].y; return result; } } std::vector<Collision> TileCollideableInfo::colliding( sf::Vector2f gp1, sf::Vector2f gp2, std::vector<Vector3u>* positions) { sf::Vector2u p1; sf::Vector2u p2; std::vector<Collision> result; if (!clipToMap(gp1, gp2, p1, p2)) return result; result.reserve(static_cast<std::size_t>( jd::math::abs(static_cast<sf::Vector2f>(p2 - p1)) * mapsize().z)); sf::Vector2u pos = p1; sf::Vector2u lastPos = p1; do { Vector3u idx(pos.x, pos.y, 0); for (; idx.z < m_tilemap.size().z; ++idx.z) { auto const c = makeCollision(idx, nullptr, sf::FloatRect()); if (c.entity) { if (positions) positions->push_back(idx); result.push_back(c); } } bool found; sf::Vector2u const nextPos = findNext(pos, lastPos, p1, p2, &found); assert(found); lastPos = pos; pos = nextPos; } while (pos != p2); return result; } bool TileCollideableInfo::clipToMap( sf::Vector2f lineStart, sf::Vector2f lineEnd, sf::Vector2u& clipStart, sf::Vector2u& clipEnd) { clipStart = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(lineStart)); clipEnd = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(lineEnd)); if (!jd::clipLine(clipStart, clipEnd, sf::Rect<unsigned>( 0, 0, m_tilemap.size().x, m_tilemap.size().y))) return false; return true; } sf::Vector2u TileCollideableInfo::findNext( sf::Vector2u pos, sf::Vector2u oldPos_, sf::Vector2u lineStart, sf::Vector2u lineEnd, bool* found) { sf::Vector2i const oldPos(oldPos_); auto const surrounding(surroundingTiles(static_cast<sf::Vector2i>(pos))); for (sf::Vector2i next : surrounding) { if (next != oldPos && m_tilemap.isValidPosition(jd::vec2to3(next, 0)) && jd::intersection( lineStart, lineEnd, sf::Rect<unsigned>( static_cast<sf::Vector2u>(next), sf::Vector2u(1, 1))) ) { if (found) *found = true; return static_cast<sf::Vector2u>(next); } } if (found) *found = false; return pos; } std::size_t TileCollideableInfo::mapCorners( sf::FloatRect const& r, sf::Vector2u& begin, sf::Vector2u& last) { begin = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(jd::topLeft(r))); begin.x = std::max(begin.x, 0u); begin.y = std::max(begin.y, 0u); last = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(jd::bottomRight(r))); last.x = std::min(last.x, m_tilemap.size().x - 1); last.y = std::min(last.y, m_tilemap.size().y - 1); int intersectingPerLayer = (last.x - begin.x + 1) * (last.y - begin.y + 1); if (intersectingPerLayer <= 0) { return 0; } return intersectingPerLayer * m_tilemap.size().z; } template <typename Pred> std::vector<Collision> filter( std::vector<Collision>&& collisions, std::vector<Vector3u>&& positions, Pred pred) { std::size_t i = 0; while (i < collisions.size()) { if (!pred(positions[i].z)) { collisions.erase(collisions.begin() + i); positions.erase(positions.begin() + i); } else { ++i; } } return collisions; } TileLayersCollideableGroup::TileLayersCollideableGroup( TileCollideableInfo* data, unsigned firstLayer, unsigned endLayer): m_data(data), m_firstLayer(firstLayer), m_endLayer(endLayer) { // must call setEndLayer before setFirstLayer // to check if map has enough layers setEndLayer(endLayer); setFirstLayer(firstLayer); } void TileLayersCollideableGroup::setFirstLayer(unsigned layer) { if (layer >= m_endLayer) throw std::out_of_range("layer >= end-layer"); assert(layer < m_data->mapsize().z); m_firstLayer = layer; } void TileLayersCollideableGroup::setEndLayer(unsigned layer) { if (layer <= m_firstLayer) throw std::out_of_range("layer <= first layer"); if (layer >= m_data->mapsize().z) throw std::out_of_range("layer >= count of layers"); m_endLayer = layer; } std::vector<Collision> TileLayersCollideableGroup::colliding( sf::FloatRect const& r, Entity* e) { if (m_firstLayer == m_endLayer) // was clear() called? return std::vector<Collision>(); if (isUnfiltered()) return m_data->colliding(r, e); std::vector<Vector3u> positions; return filter( m_data->colliding(r, e, &positions), std::move(positions), std::bind(&TileLayersCollideableGroup::layerInRange, this, std::placeholders::_1)); } std::vector<Collision> TileLayersCollideableGroup::colliding( sf::Vector2f lineStart, sf::Vector2f lineEnd) { if (m_firstLayer == m_endLayer) // was clear() called? return std::vector<Collision>(); if (isUnfiltered()) return m_data->colliding(lineStart, lineEnd); std::vector<Vector3u> positions; return filter( m_data->colliding(lineStart, lineEnd, &positions), std::move(positions), std::bind(&TileLayersCollideableGroup::layerInRange, this, std::placeholders::_1)); } bool TileLayersCollideableGroup::isUnfiltered() const { return m_firstLayer == 0 && m_endLayer == m_data->mapsize().z; } std::vector<Collision> TileStackCollideableGroup::colliding( sf::FloatRect const& r, Entity* e) { std::vector<Collision> result; if (!m_filter) return result; sf::Vector2u begin; sf::Vector2u last; std::size_t const intersectingCount = m_data->mapCorners(r, begin, last); if (intersectingCount <= 0) return result; result.reserve(intersectingCount); Vector3u pos; for (pos.x = begin.x; pos.x <= last.x; ++pos.x) { for (pos.y = begin.y; pos.y <= last.y; ++pos.y) { std::vector<Info> stack; auto const pos2 = jd::vec3to2(pos); for (pos.z = 0; pos.z < m_data->mapsize().z; ++pos.z) { auto c = m_data->makeCollision(pos, e, r); if (c.entity) stack.emplace_back(m_data->tilemap()[pos], c.entity); else stack.emplace_back(); } // for z m_filter(pos2, stack); processStack( stack, result, m_data->tilemap().globalTileRect(sf::Vector2i(pos2))); } // for y } // for x return result; } void TileStackCollideableGroup::processStack( std::vector<Info>& stack, std::vector<Collision>& result, sf::FloatRect const& r) const { for (auto const& info: stack) { if (!info.discard && info.entity.valid()) result.emplace_back(info.entity.getOpt(), r); } // for info: stack } std::vector<Collision> TileStackCollideableGroup::colliding( sf::Vector2f gp1, sf::Vector2f gp2) { std::vector<Collision> result; if (!m_filter) return result; sf::Vector2u p1; sf::Vector2u p2; if (!m_data->clipToMap(gp1, gp2, p1, p2)) return result; result.reserve(static_cast<std::size_t>( jd::math::abs(static_cast<sf::Vector2f>(p2 - p1)) * m_data->mapsize().z)); sf::Vector2u pos = p1; sf::Vector2u lastPos = p1; do { std::vector<Info> stack; Vector3u idx(pos.x, pos.y, 0); for (; idx.z < m_data->mapsize().z; ++idx.z) { auto const c = m_data->makeCollision(idx, nullptr, sf::FloatRect()); if (c.entity) stack.emplace_back(m_data->tilemap()[idx], c.entity); else stack.emplace_back(); } m_filter(pos, stack); processStack(stack, result, sf::FloatRect()); bool found; sf::Vector2u const nextPos = m_data->findNext(pos, lastPos, p1, p2, &found); assert(found); lastPos = pos; pos = nextPos; } while (pos != p2); return result; } TileStackCollideableGroup::FilterCallback TileStackCollideableGroup::setFilter(FilterCallback filter) { auto oldfilter = m_filter; m_filter = filter; return oldfilter; } <commit_msg>TileCollideableGroup: Fix colliding().<commit_after>#include "TileCollideableGroup.hpp" #include "Tilemap.hpp" #include "comp/TileCollisionComponent.hpp" #include "Logfile.hpp" #include <unordered_set> #include <array> #include <algorithm> #include <functional> #include <compsys/Entity.hpp> TileCollideableInfo::TileCollideableInfo(jd::Tilemap& tilemap): m_tilemap(tilemap) { } void TileCollideableInfo::setProxy(unsigned tileId, TileCollisionComponent* proxy) { if (!proxy) { std::size_t const erasedCount = m_proxyEntities.erase(tileId); assert(erasedCount < 2); if (!erasedCount) LOG_W("Attempt to unset a proxy, which was not set."); } else if (!m_proxyEntities.insert(std::make_pair(tileId, proxy)).second) throw std::logic_error( __FUNCTION__ ": cannot assign proxy entity: already assigned"); } TileCollisionComponent* TileCollideableInfo::proxy(unsigned tileId) { auto const it = m_proxyEntities.find(tileId); if (it != m_proxyEntities.end()) return it->second.get(); return nullptr; } void TileCollideableInfo::setColliding(Vector3u pos, TileCollisionComponent* e) { auto const it = m_entities.find(pos); bool const found = it != m_entities.end(); if (e) { if (found) { it->second->notifyOverride(pos, *e); it->second = e; } else { bool const success = m_entities.insert(std::make_pair(pos, e)).second; assert(success); } } else if (found) { m_entities.erase(pos); } else { LOG_W("Attempt to unregister a TileCollisionComponent which was not registered."); } } TileCollisionComponent* TileCollideableInfo::colliding(Vector3u pos) { auto const it = m_entities.find(pos); if (it != m_entities.end()) return it->second.get(); return nullptr; } Vector3u TileCollideableInfo::mapsize() const { return m_tilemap.size(); } Collision TileCollideableInfo::makeCollision( Vector3u pos, Entity* e, sf::FloatRect const& r) { auto const iEntity = m_entities.find(pos); if (iEntity != m_entities.end()) { if (e) iEntity->second->notifyCollision(pos, *e, r); return Collision( iEntity->second->parent(), m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))); } else { unsigned const tileId = m_tilemap[pos]; auto const iProxy = m_proxyEntities.find(tileId); if (iProxy != m_proxyEntities.end()) { if (e) iProxy->second->notifyCollision(pos, *e, r); return Collision( iProxy->second->parent(), m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))); } } // if no entity at pos registered return Collision(); } std::vector<Collision> TileCollideableInfo::colliding( sf::FloatRect const& r, Entity* e, std::vector<Vector3u>* positions) { sf::Vector2u begin; sf::Vector2u last; std::size_t const intersectingCount = mapCorners(r, begin, last); std::vector<Collision> result; if (intersectingCount <= 0) return result; result.reserve(intersectingCount); Vector3u pos; for (pos.z = 0; pos.z < m_tilemap.size().z; ++pos.z) { for (pos.x = begin.x; pos.x <= last.x; ++pos.x) { for (pos.y = begin.y; pos.y <= last.y; ++pos.y) { auto const c = makeCollision(pos, e, r); if (c.entity) { if (positions) positions->push_back(pos); result.push_back(c); } } // for y } // for x } // for z return result; } namespace { std::array<sf::Vector2i, 8> surroundingTiles(sf::Vector2i p) { std::array<sf::Vector2i, 8> result; std::fill(result.begin(), result.end(), p); // 012 // 3p4 // 567 --result[0].x; --result[0].y; --result[1].y; ++result[2].x; --result[2].y; --result[3].x; ++result[4].x; --result[5].x; ++result[5].y; ++result[6].y; ++result[7].x; ++result[7].y; return result; } } std::vector<Collision> TileCollideableInfo::colliding( sf::Vector2f gp1, sf::Vector2f gp2, std::vector<Vector3u>* positions) { sf::Vector2u p1; sf::Vector2u p2; std::vector<Collision> result; if (!clipToMap(gp1, gp2, p1, p2)) return result; result.reserve(static_cast<std::size_t>( jd::math::abs(static_cast<sf::Vector2f>(p2 - p1)) * mapsize().z)); sf::Vector2u pos = p1; sf::Vector2u lastPos = p1; for (;;) { Vector3u idx(pos.x, pos.y, 0); for (; idx.z < m_tilemap.size().z; ++idx.z) { auto const c = makeCollision(idx, nullptr, sf::FloatRect()); if (c.entity) { if (positions) positions->push_back(idx); result.push_back(c); } } bool found; sf::Vector2u const nextPos = findNext(pos, lastPos, p1, p2, &found); if (!found) break; lastPos = pos; pos = nextPos; } return result; } bool TileCollideableInfo::clipToMap( sf::Vector2f lineStart, sf::Vector2f lineEnd, sf::Vector2u& clipStart, sf::Vector2u& clipEnd) { clipStart = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(lineStart)); clipEnd = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(lineEnd)); if (!jd::clipLine(clipStart, clipEnd, sf::Rect<unsigned>( 0, 0, m_tilemap.size().x - 1, m_tilemap.size().y - 1))) return false; return true; } sf::Vector2u TileCollideableInfo::findNext( sf::Vector2u pos, sf::Vector2u oldPos_, sf::Vector2u lineStart, sf::Vector2u lineEnd, bool* found) { sf::Vector2i const oldPos(oldPos_); auto const surrounding(surroundingTiles(static_cast<sf::Vector2i>(pos))); for (sf::Vector2i next : surrounding) { using jd::vec_cast; if (next != oldPos && m_tilemap.isValidPosition(jd::vec2to3(next, 0)) && jd::onLine(vec_cast<int>(lineStart), vec_cast<int>(lineEnd), next) ) { if (found) *found = true; return static_cast<sf::Vector2u>(next); } } if (found) *found = false; return pos; } std::size_t TileCollideableInfo::mapCorners( sf::FloatRect const& r, sf::Vector2u& begin, sf::Vector2u& last) { begin = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(jd::topLeft(r))); begin.x = std::max(begin.x, 0u); begin.y = std::max(begin.y, 0u); last = static_cast<sf::Vector2u>( m_tilemap.tilePosFromGlobal(jd::bottomRight(r))); last.x = std::min(last.x, m_tilemap.size().x - 1); last.y = std::min(last.y, m_tilemap.size().y - 1); int intersectingPerLayer = (last.x - begin.x + 1) * (last.y - begin.y + 1); if (intersectingPerLayer <= 0) { return 0; } return intersectingPerLayer * m_tilemap.size().z; } template <typename Pred> std::vector<Collision> filter( std::vector<Collision>&& collisions, std::vector<Vector3u>&& positions, Pred pred) { std::size_t i = 0; while (i < collisions.size()) { if (!pred(positions[i].z)) { collisions.erase(collisions.begin() + i); positions.erase(positions.begin() + i); } else { ++i; } } return collisions; } TileLayersCollideableGroup::TileLayersCollideableGroup( TileCollideableInfo* data, unsigned firstLayer, unsigned endLayer): m_data(data), m_firstLayer(firstLayer), m_endLayer(endLayer) { // must call setEndLayer before setFirstLayer // to check if map has enough layers setEndLayer(endLayer); setFirstLayer(firstLayer); } void TileLayersCollideableGroup::setFirstLayer(unsigned layer) { if (layer >= m_endLayer) throw std::out_of_range("layer >= end-layer"); assert(layer < m_data->mapsize().z); m_firstLayer = layer; } void TileLayersCollideableGroup::setEndLayer(unsigned layer) { if (layer <= m_firstLayer) throw std::out_of_range("layer <= first layer"); if (layer >= m_data->mapsize().z) throw std::out_of_range("layer >= count of layers"); m_endLayer = layer; } std::vector<Collision> TileLayersCollideableGroup::colliding( sf::FloatRect const& r, Entity* e) { if (m_firstLayer == m_endLayer) // was clear() called? return std::vector<Collision>(); if (isUnfiltered()) return m_data->colliding(r, e); std::vector<Vector3u> positions; return filter( m_data->colliding(r, e, &positions), std::move(positions), std::bind(&TileLayersCollideableGroup::layerInRange, this, std::placeholders::_1)); } std::vector<Collision> TileLayersCollideableGroup::colliding( sf::Vector2f lineStart, sf::Vector2f lineEnd) { if (m_firstLayer == m_endLayer) // was clear() called? return std::vector<Collision>(); if (isUnfiltered()) return m_data->colliding(lineStart, lineEnd); std::vector<Vector3u> positions; return filter( m_data->colliding(lineStart, lineEnd, &positions), std::move(positions), std::bind(&TileLayersCollideableGroup::layerInRange, this, std::placeholders::_1)); } bool TileLayersCollideableGroup::isUnfiltered() const { return m_firstLayer == 0 && m_endLayer == m_data->mapsize().z; } std::vector<Collision> TileStackCollideableGroup::colliding( sf::FloatRect const& r, Entity* e) { std::vector<Collision> result; if (!m_filter) return result; sf::Vector2u begin; sf::Vector2u last; std::size_t const intersectingCount = m_data->mapCorners(r, begin, last); if (intersectingCount <= 0) return result; result.reserve(intersectingCount); Vector3u pos; for (pos.x = begin.x; pos.x <= last.x; ++pos.x) { for (pos.y = begin.y; pos.y <= last.y; ++pos.y) { std::vector<Info> stack; auto const pos2 = jd::vec3to2(pos); for (pos.z = 0; pos.z < m_data->mapsize().z; ++pos.z) { auto c = m_data->makeCollision(pos, e, r); if (c.entity) stack.emplace_back(m_data->tilemap()[pos], c.entity); else stack.emplace_back(); } // for z m_filter(pos2, stack); processStack( stack, result, m_data->tilemap().globalTileRect(sf::Vector2i(pos2))); } // for y } // for x return result; } void TileStackCollideableGroup::processStack( std::vector<Info>& stack, std::vector<Collision>& result, sf::FloatRect const& r) const { for (auto const& info: stack) { if (!info.discard && info.entity.valid()) result.emplace_back(info.entity.getOpt(), r); } // for info: stack } std::vector<Collision> TileStackCollideableGroup::colliding( sf::Vector2f gp1, sf::Vector2f gp2) { std::vector<Collision> result; if (!m_filter) return result; sf::Vector2u p1; sf::Vector2u p2; if (!m_data->clipToMap(gp1, gp2, p1, p2)) return result; result.reserve(static_cast<std::size_t>( jd::math::abs( jd::vec_cast<float>(p2) - jd::vec_cast<float>(p1) ) * m_data->mapsize().z)); sf::Vector2u pos = p1; sf::Vector2u lastPos = p1; for (;;) { std::vector<Info> stack; Vector3u idx(pos.x, pos.y, 0); for (; idx.z < m_data->mapsize().z; ++idx.z) { auto const c = m_data->makeCollision(idx, nullptr, sf::FloatRect()); if (c.entity) stack.emplace_back(m_data->tilemap()[idx], c.entity); else stack.emplace_back(); } m_filter(pos, stack); processStack( stack, result, m_data->tilemap().globalTileRect(sf::Vector2i(pos))); bool found; sf::Vector2u const nextPos = m_data->findNext(pos, lastPos, p1, p2, &found); if (!found) break; lastPos = pos; pos = nextPos; } return result; } TileStackCollideableGroup::FilterCallback TileStackCollideableGroup::setFilter(FilterCallback filter) { auto oldfilter = m_filter; m_filter = filter; return oldfilter; } <|endoftext|>
<commit_before>#include "resources.h" #include <SFML/System.hpp> #ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dirent.h> #endif #include <cstdio> #include <filesystem> PVector<ResourceProvider> resourceProviders; ResourceProvider::ResourceProvider() { resourceProviders.push_back(this); } bool ResourceProvider::searchMatch(const string name, const string searchPattern) { std::vector<string> parts = searchPattern.split("*"); int pos = 0; if (parts[0].length() > 0) { if (name.find(parts[0]) != 0) return false; } for(unsigned int n=1; n<parts.size(); n++) { int offset = name.find(parts[n], pos); if (offset < 0) return false; pos = offset + parts[n].length(); } return pos == int(name.length()); } string ResourceStream::readLine() { string ret; char c; while(true) { if (read(&c, 1) < 1) return ret; if (c == '\n') return ret; ret += string(c); } } class FileResourceStream : public ResourceStream { sf::FileInputStream stream; bool open_success; public: FileResourceStream(string filename) { #ifndef ANDROID std::error_code ec; if(!std::filesystem::is_regular_file(filename.c_str()), ec) { if(ec) { LOG(ERROR) << "OS error on file check : " << ec.message(); } open_success = false; } else open_success = stream.open(filename); #else //Android reads from the assets bundle, so we cannot check if the file exists and is a regular file open_success = stream.open(filename); #endif } virtual ~FileResourceStream() { } bool isOpen() { return open_success; } virtual sf::Int64 read(void* data, sf::Int64 size) { return stream.read(data, size); } virtual sf::Int64 seek(sf::Int64 position) { return stream.seek(position); } virtual sf::Int64 tell() { return stream.tell(); } virtual sf::Int64 getSize() { return stream.getSize(); } }; DirectoryResourceProvider::DirectoryResourceProvider(string basepath) : basepath(basepath) { } P<ResourceStream> DirectoryResourceProvider::getResourceStream(string filename) { P<FileResourceStream> stream = new FileResourceStream(basepath + filename); if (stream->isOpen()) return stream; return nullptr; } std::vector<string> DirectoryResourceProvider::findResources(string searchPattern) { std::vector<string> found_files; findResources(found_files, "", searchPattern); return found_files; } void DirectoryResourceProvider::findResources(std::vector<string>& found_files, const string path, const string searchPattern) { #ifdef _MSC_VER WIN32_FIND_DATAA data; string search_root(basepath + path); if (!search_root.endswith("/")) { search_root += "/"; } HANDLE handle = FindFirstFileA((search_root + "*").c_str(), &data); if (handle == INVALID_HANDLE_VALUE) return; do { if (data.cFileName[0] == '.') continue; string name = path + string(data.cFileName); if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { findResources(found_files, name + "/", searchPattern); } else { if (searchMatch(name, searchPattern)) found_files.push_back(name); } } while (FindNextFileA(handle, &data)); FindClose(handle); #else DIR* dir = opendir((basepath + path).c_str()); if (!dir) return; struct dirent *entry; while ((entry = readdir(dir)) != nullptr) { if (entry->d_name[0] == '.') continue; string name = path + string(entry->d_name); if (searchMatch(name, searchPattern)) found_files.push_back(name); findResources(found_files, path + string(entry->d_name) + "/", searchPattern); } closedir(dir); #endif } P<ResourceStream> getResourceStream(string filename) { foreach(ResourceProvider, rp, resourceProviders) { P<ResourceStream> stream = rp->getResourceStream(filename); if (stream) return stream; } return NULL; } std::vector<string> findResources(string searchPattern) { std::vector<string> foundFiles; foreach(ResourceProvider, rp, resourceProviders) { std::vector<string> res = rp->findResources(searchPattern); foundFiles.insert(foundFiles.end(), res.begin(), res.end()); } return foundFiles; } <commit_msg>Fixes blunder on if test (#83)<commit_after>#include "resources.h" #include <SFML/System.hpp> #ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dirent.h> #endif #include <cstdio> #include <filesystem> PVector<ResourceProvider> resourceProviders; ResourceProvider::ResourceProvider() { resourceProviders.push_back(this); } bool ResourceProvider::searchMatch(const string name, const string searchPattern) { std::vector<string> parts = searchPattern.split("*"); int pos = 0; if (parts[0].length() > 0) { if (name.find(parts[0]) != 0) return false; } for(unsigned int n=1; n<parts.size(); n++) { int offset = name.find(parts[n], pos); if (offset < 0) return false; pos = offset + parts[n].length(); } return pos == int(name.length()); } string ResourceStream::readLine() { string ret; char c; while(true) { if (read(&c, 1) < 1) return ret; if (c == '\n') return ret; ret += string(c); } } class FileResourceStream : public ResourceStream { sf::FileInputStream stream; bool open_success; public: FileResourceStream(string filename) { #ifndef ANDROID std::error_code ec; if(!std::filesystem::is_regular_file(filename.c_str(), ec)) { if(ec) { LOG(ERROR) << "OS error on file check : " << ec.message(); } open_success = false; } else open_success = stream.open(filename); #else //Android reads from the assets bundle, so we cannot check if the file exists and is a regular file open_success = stream.open(filename); #endif } virtual ~FileResourceStream() { } bool isOpen() { return open_success; } virtual sf::Int64 read(void* data, sf::Int64 size) { return stream.read(data, size); } virtual sf::Int64 seek(sf::Int64 position) { return stream.seek(position); } virtual sf::Int64 tell() { return stream.tell(); } virtual sf::Int64 getSize() { return stream.getSize(); } }; DirectoryResourceProvider::DirectoryResourceProvider(string basepath) : basepath(basepath) { } P<ResourceStream> DirectoryResourceProvider::getResourceStream(string filename) { P<FileResourceStream> stream = new FileResourceStream(basepath + filename); if (stream->isOpen()) return stream; return nullptr; } std::vector<string> DirectoryResourceProvider::findResources(string searchPattern) { std::vector<string> found_files; findResources(found_files, "", searchPattern); return found_files; } void DirectoryResourceProvider::findResources(std::vector<string>& found_files, const string path, const string searchPattern) { #ifdef _MSC_VER WIN32_FIND_DATAA data; string search_root(basepath + path); if (!search_root.endswith("/")) { search_root += "/"; } HANDLE handle = FindFirstFileA((search_root + "*").c_str(), &data); if (handle == INVALID_HANDLE_VALUE) return; do { if (data.cFileName[0] == '.') continue; string name = path + string(data.cFileName); if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { findResources(found_files, name + "/", searchPattern); } else { if (searchMatch(name, searchPattern)) found_files.push_back(name); } } while (FindNextFileA(handle, &data)); FindClose(handle); #else DIR* dir = opendir((basepath + path).c_str()); if (!dir) return; struct dirent *entry; while ((entry = readdir(dir)) != nullptr) { if (entry->d_name[0] == '.') continue; string name = path + string(entry->d_name); if (searchMatch(name, searchPattern)) found_files.push_back(name); findResources(found_files, path + string(entry->d_name) + "/", searchPattern); } closedir(dir); #endif } P<ResourceStream> getResourceStream(string filename) { foreach(ResourceProvider, rp, resourceProviders) { P<ResourceStream> stream = rp->getResourceStream(filename); if (stream) return stream; } return NULL; } std::vector<string> findResources(string searchPattern) { std::vector<string> foundFiles; foreach(ResourceProvider, rp, resourceProviders) { std::vector<string> res = rp->findResources(searchPattern); foundFiles.insert(foundFiles.end(), res.begin(), res.end()); } return foundFiles; } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "scheduler.h" #include <assert.h> #include <boost/bind.hpp> #include <utility> CScheduler::CScheduler() : nThreadsServicingQueue(0) { } CScheduler::~CScheduler() { assert(nThreadsServicingQueue == 0); } #if BOOST_VERSION < 105000 static boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t) { boost::chrono::system_clock::duration d = t.time_since_epoch(); boost::chrono::microseconds usecs = boost::chrono::duration_cast<boost::chrono::microseconds>(d); boost::system_time result = boost::posix_time::from_time_t(0) + boost::posix_time::microseconds(usecs.count()); return result; } #endif void CScheduler::serviceQueue() { boost::unique_lock<boost::mutex> lock(newTaskMutex); ++nThreadsServicingQueue; // newTaskMutex is locked throughout this loop EXCEPT // when the thread is waiting or when the user's function // is called. while (1) { try { while (taskQueue.empty()) { // Wait until there is something to do. newTaskScheduled.wait(lock); } // Wait until either there is a new task, or until // the time of the first item on the queue: // wait_until needs boost 1.50 or later; older versions have timed_wait: #if BOOST_VERSION < 105000 while (!taskQueue.empty() && newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) { // Keep waiting until timeout } #else while (!taskQueue.empty() && newTaskScheduled.wait_until(lock, taskQueue.begin()->first) != boost::cv_status::timeout) { // Keep waiting until timeout } #endif // If there are multiple threads, the queue can empty while we're waiting (another // thread may service the task we were waiting on). if (taskQueue.empty()) continue; Function f = taskQueue.begin()->second; taskQueue.erase(taskQueue.begin()); // Unlock before calling f, so it can reschedule itself or another task // without deadlocking: lock.unlock(); f(); lock.lock(); } catch (...) { --nThreadsServicingQueue; throw; } } } void CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t) { { boost::unique_lock<boost::mutex> lock(newTaskMutex); taskQueue.insert(std::make_pair(t, f)); } newTaskScheduled.notify_one(); } void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaSeconds) { schedule(f, boost::chrono::system_clock::now() + boost::chrono::seconds(deltaSeconds)); } static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaSeconds) { f(); s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaSeconds), deltaSeconds); } void CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaSeconds) { scheduleFromNow(boost::bind(&Repeat, this, f, deltaSeconds), deltaSeconds); } <commit_msg>scheduler: fix with boost <= 1.50<commit_after>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "scheduler.h" #include <assert.h> #include <boost/bind.hpp> #include <utility> CScheduler::CScheduler() : nThreadsServicingQueue(0) { } CScheduler::~CScheduler() { assert(nThreadsServicingQueue == 0); } #if BOOST_VERSION < 105000 static boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t) { return boost::posix_time::from_time_t(boost::chrono::system_clock::to_time_t(t)); } #endif void CScheduler::serviceQueue() { boost::unique_lock<boost::mutex> lock(newTaskMutex); ++nThreadsServicingQueue; // newTaskMutex is locked throughout this loop EXCEPT // when the thread is waiting or when the user's function // is called. while (1) { try { while (taskQueue.empty()) { // Wait until there is something to do. newTaskScheduled.wait(lock); } // Wait until either there is a new task, or until // the time of the first item on the queue: // wait_until needs boost 1.50 or later; older versions have timed_wait: #if BOOST_VERSION < 105000 while (!taskQueue.empty() && newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) { // Keep waiting until timeout } #else while (!taskQueue.empty() && newTaskScheduled.wait_until(lock, taskQueue.begin()->first) != boost::cv_status::timeout) { // Keep waiting until timeout } #endif // If there are multiple threads, the queue can empty while we're waiting (another // thread may service the task we were waiting on). if (taskQueue.empty()) continue; Function f = taskQueue.begin()->second; taskQueue.erase(taskQueue.begin()); // Unlock before calling f, so it can reschedule itself or another task // without deadlocking: lock.unlock(); f(); lock.lock(); } catch (...) { --nThreadsServicingQueue; throw; } } } void CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t) { { boost::unique_lock<boost::mutex> lock(newTaskMutex); taskQueue.insert(std::make_pair(t, f)); } newTaskScheduled.notify_one(); } void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaSeconds) { schedule(f, boost::chrono::system_clock::now() + boost::chrono::seconds(deltaSeconds)); } static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaSeconds) { f(); s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaSeconds), deltaSeconds); } void CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaSeconds) { scheduleFromNow(boost::bind(&Repeat, this, f, deltaSeconds), deltaSeconds); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../../../src/http/server/request.h" #include "../../../src/http/server/response.h" #include "../../mocks/mock_connector/mock_connector.h" #include "../src/http2/session.h" #include "../src/http2/stream.h" #include <memory> #include <utility> // TODO this is a duplicate - bring it out static std::unique_ptr<char[]> make_data_ptr(const std::string& s) { auto ptr = std::make_unique<char[]>(s.size()); std::copy(s.begin(), s.end(), ptr.get()); return std::move(ptr); } using server_connection_t = http2::session; class http2_test : public ::testing::Test { public: void SetUp() { _write_cb = [](dstring) {}; mock_connector = std::make_shared<MockConnector>(io, _write_cb); _handler = std::make_shared<server_connection_t>(); mock_connector->handler(_handler); response = ""; } boost::asio::io_service io; std::shared_ptr<MockConnector> mock_connector; std::shared_ptr<server_connection_t> _handler; MockConnector::wcb _write_cb; std::string response; }; TEST_F(http2_test, randomdata) { // This should not throw! const char raw_request[] = "\x00\x05\x06\x04\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x64\x50" "\x52\x49\x20\x2A\x20\x48\x54\x54\x50\x2F\x32\x2E\x30\x0D\x0A\x0D" "\x00\x00\x00\x00\x00\x00\x00\x00"; std::size_t len = sizeof( raw_request ); _handler = std::make_shared<http2::session>(); _handler->start(); bool error = _handler->on_read(raw_request, len); ASSERT_FALSE( error ); } TEST_F(http2_test, getting_200_at_once) { _handler->on_request([&](auto conn, auto req, auto res) { req->on_finished([res](auto req) { http::http_response r; r.protocol(http::proto_version::HTTP20); std::string body{"Ave client, dummy node says hello"}; r.status(200); r.header("content-type", "text/plain"); r.header("date", "Tue, 17 May 2016 14:53:09 GMT"); r.content_len(body.size()); res->headers(std::move(r)); res->body(make_data_ptr(body), body.size()); res->end(); }); }); constexpr const char raw_response[] = "\x00\x00\x00\x04\x01\x00\x00\x00" "\x00\x00\x00\x27\x01\x04\x00\x00" "\x00\x0d\x88\x0f\x0d\x02\x33\x33" "\x5f\x87\x49\x7c\xa5\x8a\xe8\x19" "\xaa\x61\x96\xdf\x69\x7e\x94\x0b" "\xaa\x68\x1f\xa5\x04\x00\xb8\xa0" "\x5a\xb8\xdb\x37\x00\xfa\x98\xb4" "\x6f\x00\x00\x21\x00\x00\x00\x00" "\x00\x0d\x41\x76\x65\x20\x63\x6c" "\x69\x65\x6e\x74\x2c\x20\x64\x75" "\x6d\x6d\x79\x20\x6e\x6f\x64\x65" "\x20\x73\x61\x79\x73\x20\x68\x65" "\x6c\x6c\x6f\x00\x00\x00\x00\x01" "\x00\x00\x00"; constexpr const std::size_t len_resp = sizeof ( raw_response ); bool done{false}; dstring actual_res; _write_cb = [&]( dstring w ) { actual_res.append( w ); if ( actual_res.size() == len_resp ) // Not the best way to do this { bool eq{true}; for ( std::size_t i = 0; i < len_resp && eq; ++i ) eq = actual_res.cdata()[i] == raw_response[i]; done = true; } }; mock_connector->io_service().post([this]() { const char raw_request[] = "\x50\x52\x49\x20\x2A\x20\x48\x54\x54\x50\x2F\x32\x2E\x30\x0D\x0A" "\x0D\x0A\x53\x4D\x0D\x0A\x0D\x0A\x00\x00\x0C\x04\x00\x00\x00\x00" "\x00\x00\x03\x00\x00\x00\x64\x00\x04\x00\x00\xFF\xFF\x00\x00\x05" "\x02\x00\x00\x00\x00\x03\x00\x00\x00\x00\xC8\x00\x00\x05\x02\x00" "\x00\x00\x00\x05\x00\x00\x00\x00\x64\x00\x00\x05\x02\x00\x00\x00" "\x00\x07\x00\x00\x00\x00\x00\x00\x00\x05\x02\x00\x00\x00\x00\x09" "\x00\x00\x00\x07\x00\x00\x00\x05\x02\x00\x00\x00\x00\x0B\x00\x00" "\x00\x03\x00\x00\x00\x26\x01\x25\x00\x00\x00\x0D\x00\x00\x00\x0B" "\x0F\x82\x84\x86\x41\x8A\xA0\xE4\x1D\x13\x9D\x09\xB8\xF3\xCF\x3D" "\x53\x03\x2A\x2F\x2A\x90\x7A\x8A\xAA\x69\xD2\x9A\xC4\xC0\x57\x08" "\x17\x07"; std::size_t len = sizeof( raw_request ); std::string pd{ raw_request, len }; mock_connector->read(pd); }); mock_connector->io_service().run(); ASSERT_TRUE(done); // TODO GO AWAY IS MISSING // ASSERT_TRUE(_handler->should_stop()); } <commit_msg>WIP HTTP2 test<commit_after>#include <nghttp2/nghttp2.h> #include <gtest/gtest.h> #include "../../../src/http/server/request.h" #include "../../../src/http/server/response.h" #include "../../mocks/mock_connector/mock_connector.h" #include "../src/http2/session.h" #include "../src/http2/stream.h" // #include "../../../deps/nghttp2/build/include/nghttp2/nghttp2.h" #include <memory> #include <utility> // Sorry man! #define MAKE_NV(NAME, VALUE) \ { \ (uint8_t *) NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, sizeof(VALUE) - 1, \ NGHTTP2_NV_FLAG_NONE \ } #define MAKE_NV_CS(NAME, VALUE) \ { \ (uint8_t *) NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, strlen(VALUE), \ NGHTTP2_NV_FLAG_NONE \ } static void diec(const char *func, int error_code) { fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code, nghttp2_strerror(error_code)); //FAIL(); } using server_connection_t = http2::session; class http2_test : public ::testing::Test { static http2_test* tx; public: http2_test() { tx = this; } void SetUp() { _write_cb = [](dstring) {}; mock_connector = std::make_shared<MockConnector>(io, _write_cb); _handler = std::make_shared<server_connection_t>(); mock_connector->handler(_handler); response_raw.clear(); request_raw.clear(); go_away = false; } boost::asio::io_service io; std::shared_ptr<MockConnector> mock_connector; std::shared_ptr<server_connection_t> _handler; MockConnector::wcb _write_cb; std::string response_raw; std::string request_raw; bool go_away{false}; ~http2_test() { tx = nullptr; } static ssize_t read( char* buf, std::size_t len ) { ssize_t r = tx->response_raw.size(); r = len < r ? len : r; memcpy(buf, tx->response_raw.data(), r ); if ( r > 0 ) // TODO SEGMENTTION FAULT HERE, WHY? tx->response_raw = tx->response_raw.erase(0, r); return r; } static ssize_t write( const char* buf, std::size_t len ) { std::string local_buf{buf, len}; tx->request_raw += local_buf; // Append truncates nulls! return len; } }; http2_test* http2_test::tx; struct Connection { nghttp2_session *session; }; struct Request { const char *host; /* In this program, path contains query component as well. */ const char *path; /* This is the concatenation of host and port with ":" in between. */ const char *hostport; /* Stream ID for this request. */ int32_t stream_id; uint16_t port; }; int test_read(char* buf, std::size_t len ) { fprintf(stderr, "Reading"); return http2_test::read( buf, len ); } int test_write( const char* buf, std::size_t len ) { fprintf(stderr, "Writing"); return http2_test::write( buf, len ); } static ssize_t send_callback( nghttp2_session *session, const uint8_t *data, size_t length, int flags, void * user_data ) { int rv = test_write( (const char*)data, length ); return rv; } static ssize_t recv_callback(nghttp2_session *session , uint8_t *buf, size_t length, int flags, void *user_data) { int rv = test_read( (char*)buf, length ); return rv; } static int on_stream_close_callback(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *user_data) { struct Request *req; req = static_cast<Request*> ( nghttp2_session_get_stream_user_data(session, stream_id) ); if (req) { int rv = nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR); if (rv != 0) diec("nghttp2_session_terminate_session", rv); } return 0; } static int on_frame_send_callback(nghttp2_session *session, const nghttp2_frame *frame, void *user_data) { size_t i; switch (frame->hd.type) { case NGHTTP2_HEADERS: if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) { const nghttp2_nv *nva = frame->headers.nva; printf("[INFO] C ----------------------------> S (HEADERS)\n"); for (i = 0; i < frame->headers.nvlen; ++i) { fwrite(nva[i].name, nva[i].namelen, 1, stdout); printf(": "); fwrite(nva[i].value, nva[i].valuelen, 1, stdout); printf("\n"); } } break; case NGHTTP2_RST_STREAM: printf("[INFO] C ----------------------------> S (RST_STREAM)\n"); break; case NGHTTP2_GOAWAY: printf("[INFO] C ----------------------------> S (GOAWAY)\n"); break; } return 0; } static int on_frame_recv_callback(nghttp2_session *session, const nghttp2_frame *frame, void *user_data ) { size_t i; switch (frame->hd.type) { case NGHTTP2_HEADERS: if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE) { const nghttp2_nv *nva = frame->headers.nva; Request *req; req = static_cast<Request*>( nghttp2_session_get_stream_user_data(session, frame->hd.stream_id) ); if (req) { printf("[INFO] C <---------------------------- S (HEADERS)\n"); for (i = 0; i < frame->headers.nvlen; ++i) { fwrite(nva[i].name, nva[i].namelen, 1, stdout); printf(": "); fwrite(nva[i].value, nva[i].valuelen, 1, stdout); printf("\n"); } } } break; case NGHTTP2_RST_STREAM: printf("[INFO] C <---------------------------- S (RST_STREAM)\n"); break; case NGHTTP2_GOAWAY: printf("[INFO] C <---------------------------- S (GOAWAY)\n"); break; } return 0; } /* * The implementation of nghttp2_on_data_chunk_recv_callback type. We * use this function to print the received response body. */ static int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, void *user_data) { Request *req; req = static_cast<Request *>( nghttp2_session_get_stream_user_data(session, stream_id) ); if (req) { printf("[INFO] C <---------------------------- S (DATA chunk)\n" "%lu bytes\n", (unsigned long int)len); fwrite(data, 1, len, stdout); printf("\n"); } return 0; } static void setup_nghttp2_callbacks(nghttp2_session_callbacks *callbacks) { nghttp2_session_callbacks_set_send_callback(callbacks, send_callback); nghttp2_session_callbacks_set_recv_callback(callbacks, recv_callback); nghttp2_session_callbacks_set_on_frame_send_callback(callbacks, on_frame_send_callback); nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, on_frame_recv_callback); nghttp2_session_callbacks_set_on_stream_close_callback( callbacks, on_stream_close_callback); nghttp2_session_callbacks_set_on_data_chunk_recv_callback( callbacks, on_data_chunk_recv_callback); } static void exec_io(struct Connection *connection) { int rv = nghttp2_session_recv(connection->session); if (rv != 0) diec("nghttp2_session_recv", rv); rv = nghttp2_session_send(connection->session); if (rv != 0) diec("nghttp2_session_send", rv); } static std::unique_ptr<Connection> start_client() { nghttp2_session_callbacks *callbacks; std::unique_ptr<Connection> c{ new Connection }; Connection* connection = c.get(); ssize_t rv = nghttp2_session_callbacks_new(&callbacks); if ( rv > 0 ) return std::unique_ptr<Connection>{}; setup_nghttp2_callbacks(callbacks); rv = nghttp2_session_client_new(&(connection->session), callbacks, &connection); if ( rv > 0 ) return std::unique_ptr<Connection>{}; nghttp2_session_callbacks_del(callbacks); return c; } /* * Submits the request |req| to the connection |connection|. This * function does not send packets; just append the request to the * internal queue in |connection->session|. */ static void submit_request(struct Connection *connection, struct Request *req) { int32_t stream_id; /* Make sure that the last item is NULL */ const nghttp2_nv nva[] = { MAKE_NV(":method", "GET"), MAKE_NV_CS(":path", req->path), MAKE_NV(":scheme", "https"), MAKE_NV_CS(":authority", req->hostport), MAKE_NV("accept", "*/*"), MAKE_NV("user-agent", "nghttp2/" NGHTTP2_VERSION)}; stream_id = nghttp2_submit_request(connection->session, NULL, nva, sizeof(nva) / sizeof(nva[0]), NULL, req); if (stream_id < 0) diec("nghttp2_submit_request", stream_id); req->stream_id = stream_id; printf("[INFO] Stream ID = %d\n", stream_id); } static void submit_settings(struct Connection* connection) { nghttp2_submit_settings(connection->session, NGHTTP2_FLAG_NONE, NULL, 0); } // TODO this is a duplicate - bring it out static std::unique_ptr<char[]> make_data_ptr(const std::string& s) { auto ptr = std::make_unique<char[]>(s.size()); std::copy(s.begin(), s.end(), ptr.get()); return std::move(ptr); } TEST_F(http2_test, connection) { // pass this as answer to http2 stuff _write_cb = [this](dstring d) { std::string chunk = d; response_raw += chunk; }; _handler->on_request([&](auto conn, auto req, auto res) { req->on_finished([res](auto req) { http::http_response r; r.protocol(http::proto_version::HTTP20); std::string body{"Ave client, dummy node says hello"}; r.status(200); r.header("content-type", "text/plain"); r.header("date", "Tue, 17 May 2016 14:53:09 GMT"); r.content_len(body.size()); res->headers(std::move(r)); res->body(make_data_ptr(body), body.size()); res->end(); }); }); bool terminated{false}; mock_connector->io_service().post([this, &terminated]() { Request req; Request* greq = &req; greq->host = "www.cristo.it"; greq->port = 80; greq->path = "/"; greq->stream_id = -1; std::unique_ptr<Connection> c = start_client(); Connection* cnx = c.get(); submit_settings(cnx); submit_request(cnx, greq); while (nghttp2_session_want_read(cnx->session) || nghttp2_session_want_write(cnx->session)) { exec_io( cnx ); mock_connector->read( request_raw ); request_raw = ""; } nghttp2_session_del( cnx->session ); }); mock_connector->io_service().run(); ASSERT_TRUE( terminated ); } TEST_F(http2_test, randomdata) { // This should not throw! const char raw_request[] = "\x00\x05\x06\x04\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x64\x50" "\x52\x49\x20\x2A\x20\x48\x54\x54\x50\x2F\x32\x2E\x30\x0D\x0A\x0D" "\x00\x00\x00\x00\x00\x00\x00\x00"; std::size_t len = sizeof( raw_request ); _handler = std::make_shared<http2::session>(); _handler->start(); bool error = _handler->on_read(raw_request, len); ASSERT_FALSE( error ); } TEST_F(http2_test, getting_200_at_once) { _handler->on_request([&](auto conn, auto req, auto res) { req->on_finished([res](auto req) { http::http_response r; r.protocol(http::proto_version::HTTP20); std::string body{"Ave client, dummy node says hello"}; r.status(200); r.header("content-type", "text/plain"); r.header("date", "Tue, 17 May 2016 14:53:09 GMT"); r.content_len(body.size()); res->headers(std::move(r)); res->body(make_data_ptr(body), body.size()); res->end(); }); }); constexpr const char raw_response[] = "\x00\x00\x00\x04\x01\x00\x00\x00" "\x00\x00\x00\x27\x01\x04\x00\x00" "\x00\x0d\x88\x0f\x0d\x02\x33\x33" "\x5f\x87\x49\x7c\xa5\x8a\xe8\x19" "\xaa\x61\x96\xdf\x69\x7e\x94\x0b" "\xaa\x68\x1f\xa5\x04\x00\xb8\xa0" "\x5a\xb8\xdb\x37\x00\xfa\x98\xb4" "\x6f\x00\x00\x21\x00\x00\x00\x00" "\x00\x0d\x41\x76\x65\x20\x63\x6c" "\x69\x65\x6e\x74\x2c\x20\x64\x75" "\x6d\x6d\x79\x20\x6e\x6f\x64\x65" "\x20\x73\x61\x79\x73\x20\x68\x65" "\x6c\x6c\x6f\x00\x00\x00\x00\x01" "\x00\x00\x00"; constexpr const std::size_t len_resp = sizeof ( raw_response ); bool done{false}; dstring actual_res; _write_cb = [&]( dstring w ) { actual_res.append( w ); if ( actual_res.size() == len_resp ) // Not the best way to do this { bool eq{true}; for ( std::size_t i = 0; i < len_resp && eq; ++i ) eq |= actual_res.cdata()[i] == raw_response[i]; done = true; } }; mock_connector->io_service().post([this]() { const char raw_request[] = "\x50\x52\x49\x20\x2A\x20\x48\x54\x54\x50\x2F\x32\x2E\x30\x0D\x0A" "\x0D\x0A\x53\x4D\x0D\x0A\x0D\x0A\x00\x00\x0C\x04\x00\x00\x00\x00" "\x00\x00\x03\x00\x00\x00\x64\x00\x04\x00\x00\xFF\xFF\x00\x00\x05" "\x02\x00\x00\x00\x00\x03\x00\x00\x00\x00\xC8\x00\x00\x05\x02\x00" "\x00\x00\x00\x05\x00\x00\x00\x00\x64\x00\x00\x05\x02\x00\x00\x00" "\x00\x07\x00\x00\x00\x00\x00\x00\x00\x05\x02\x00\x00\x00\x00\x09" "\x00\x00\x00\x07\x00\x00\x00\x05\x02\x00\x00\x00\x00\x0B\x00\x00" "\x00\x03\x00\x00\x00\x26\x01\x25\x00\x00\x00\x0D\x00\x00\x00\x0B" "\x0F\x82\x84\x86\x41\x8A\xA0\xE4\x1D\x13\x9D\x09\xB8\xF3\xCF\x3D" "\x53\x03\x2A\x2F\x2A\x90\x7A\x8A\xAA\x69\xD2\x9A\xC4\xC0\x57\x08" "\x17\x07"; std::size_t len = sizeof( raw_request ); std::string pd{ raw_request, len }; mock_connector->read(pd); }); mock_connector->io_service().run(); ASSERT_TRUE(done); // TODO GO AWAY IS MISSING // ASSERT_TRUE(_handler->should_stop()); } <|endoftext|>
<commit_before>#include "siteeditor.h" #include <gdk/gdkkeysyms-compat.h> #include <glibmm/i18n.h> using namespace AhoViewer; using namespace AhoViewer::Booru; #include "booru/site.h" #include "settings.h" #include "util.h" SiteEditor::SiteEditor(BaseObjectType* cobj, const Glib::RefPtr<Gtk::Builder>& bldr) : Gtk::TreeView(cobj), m_Model(Gtk::ListStore::create(m_Columns)), m_NameColumn(Gtk::manage(new Gtk::TreeView::Column(_("Name"), m_Columns.name))), m_UrlColumn(Gtk::manage(new Gtk::TreeView::Column(_("Url"), m_Columns.url))), m_SampleColumn(Gtk::manage(new Gtk::TreeView::Column(_("Samples"), m_Columns.samples))), m_Sites(Settings.get_sites()) { bldr->get_widget("BooruRegisterLinkButton", m_RegisterButton); bldr->get_widget("BooruUsernameEntry", m_UsernameEntry); bldr->get_widget("BooruPasswordEntry", m_PasswordEntry); bldr->get_widget("BooruPasswordLabel", m_PasswordLabel); m_SignalSiteChecked.connect(sigc::mem_fun(*this, &SiteEditor::on_site_checked)); for (const std::shared_ptr<Site>& s : m_Sites) { Gtk::TreeIter iter{ m_Model->append() }; iter->set_value(m_Columns.icon, s->get_icon_pixbuf()); s->signal_icon_downloaded().connect( [&, iter, s]() { iter->set_value(m_Columns.icon, s->get_icon_pixbuf()); }); iter->set_value(m_Columns.name, s->get_name()); iter->set_value(m_Columns.url, s->get_url()); iter->set_value(m_Columns.samples, s->use_samples()); iter->set_value(m_Columns.site, s); } try { m_ErrorPixbuf = Gtk::IconTheme::get_default()->load_icon( "edit-delete", Gtk::ICON_SIZE_MENU, Gtk::ICON_LOOKUP_USE_BUILTIN | Gtk::ICON_LOOKUP_GENERIC_FALLBACK); // TODO: Capture and print something useful } catch (...) { } CellRendererIcon* icon_renderer{ Gtk::manage(new CellRendererIcon(this)) }; icon_renderer->property_xpad() = 2; icon_renderer->property_ypad() = 2; append_column("", *icon_renderer); get_column(0)->add_attribute(icon_renderer->property_loading(), m_Columns.loading); get_column(0)->add_attribute(icon_renderer->property_pulse(), m_Columns.pulse); get_column(0)->add_attribute(icon_renderer->property_pixbuf(), m_Columns.icon); Gtk::CellRendererText* text_renderer{ nullptr }; text_renderer = static_cast<Gtk::CellRendererText*>(m_NameColumn->get_first_cell()); text_renderer->property_editable() = true; text_renderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_name_edited)); append_column(*m_NameColumn); text_renderer = static_cast<Gtk::CellRendererText*>(m_UrlColumn->get_first_cell()); text_renderer->property_editable() = true; text_renderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_url_edited)); m_UrlColumn->set_expand(true); append_column(*m_UrlColumn); auto* toggle_renderer = static_cast<Gtk::CellRendererToggle*>(m_SampleColumn->get_first_cell()); toggle_renderer->signal_toggled().connect( sigc::mem_fun(*this, &SiteEditor::on_samples_toggled)); toggle_renderer->set_activatable(true); append_column(*m_SampleColumn); set_model(m_Model); get_selection()->select(m_Model->children().begin()); Gtk::ToolButton* tool_button{ nullptr }; bldr->get_widget("DeleteSiteButton", tool_button); tool_button->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::delete_site)); bldr->get_widget("AddSiteButton", tool_button); tool_button->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::add_row)); m_UsernameConn = m_UsernameEntry->signal_changed().connect( sigc::mem_fun(*this, &SiteEditor::on_username_edited)); m_PasswordConn = m_PasswordEntry->signal_changed().connect( sigc::mem_fun(*this, &SiteEditor::on_password_edited)); m_CursorConn = signal_cursor_changed().connect( sigc::mem_fun(*this, &SiteEditor::on_my_cursor_changed), false); #ifdef HAVE_LIBSECRET // Make sure the initially selected site's password gets set in the entry once it's loaded const std::shared_ptr<Site>& s{ get_selection()->get_selected()->get_value(m_Columns.site) }; if (s) s->signal_password_lookup().connect([&, s]() { m_PasswordConn.block(); m_PasswordEntry->set_text(s->get_password()); m_PasswordConn.unblock(); }); #endif // HAVE_LIBSECRET m_PasswordEntry->set_visibility(false); // Set initial values for entries and linkbutton on_my_cursor_changed(); // Set a flag to let the on_row_changed signal handler know that the change // is from a DND'ing m_RowInsertedConn = m_Model->signal_row_inserted().connect( [&](const Gtk::TreePath&, const Gtk::TreeIter& iter) { m_LastAddFromDND = true; }); m_Model->signal_row_changed().connect(sigc::mem_fun(*this, &SiteEditor::on_row_changed)); } SiteEditor::~SiteEditor() { if (m_SiteCheckThread.joinable()) m_SiteCheckThread.join(); } bool SiteEditor::on_key_release_event(GdkEventKey* e) { if (e->keyval == GDK_Return || e->keyval == GDK_ISO_Enter || e->keyval == GDK_KP_Enter || e->keyval == GDK_Tab) { Gtk::TreeIter iter{ get_selection()->get_selected() }; Gtk::TreePath p(iter); if (iter->get_value(m_Columns.url).empty()) set_cursor(p, *m_UrlColumn, true); else if (iter->get_value(m_Columns.name).empty()) set_cursor(p, *m_NameColumn, true); } return false; } void SiteEditor::on_my_cursor_changed() { std::shared_ptr<Site> s{ nullptr }; if (get_selection()->get_selected()) s = get_selection()->get_selected()->get_value(m_Columns.site); m_UsernameConn.block(); m_PasswordConn.block(); if (s) { m_RegisterButton->set_label(_("Register account on ") + s->get_name()); m_RegisterButton->set_uri(s->get_register_uri()); m_UsernameEntry->set_text(s->get_username()); m_PasswordEntry->set_text(s->get_password()); } else { m_RegisterButton->set_label(_("Register account")); m_UsernameEntry->set_text(""); m_PasswordEntry->set_text(""); } m_UsernameConn.unblock(); m_PasswordConn.unblock(); m_RegisterButton->set_sensitive(!!s); m_UsernameEntry->set_sensitive(!!s); m_PasswordEntry->set_sensitive(!!s); if (!s || s->get_type() == Type::GELBOORU) m_PasswordLabel->set_text(_("Password:")); else m_PasswordLabel->set_text(_("API Key:")); } void SiteEditor::add_row() { m_RowInsertedConn.block(); Gtk::TreePath path(m_Model->append()); m_RowInsertedConn.unblock(); set_cursor(path, *m_NameColumn, true); scroll_to_row(path); } void SiteEditor::delete_site() { Gtk::TreeIter o{ get_selection()->get_selected() }; if (o) { m_Sites.erase(std::remove(m_Sites.begin(), m_Sites.end(), o->get_value(m_Columns.site)), m_Sites.end()); m_SignalEdited(); Gtk::TreeIter n{ m_Model->erase(o) }; if (m_Model->children().size()) get_selection()->select(n ? n : --n); on_my_cursor_changed(); } } void SiteEditor::on_name_edited(const std::string& p, const std::string& text) { Gtk::TreePath path{ p }; Gtk::TreeIter iter{ m_Model->get_iter(path) }; std::string name{ text }; // make sure the site name is unique for (size_t i{ 1 }; !is_name_unique(iter, name); ++i) name = text + std::to_string(i); iter->set_value(m_Columns.name, name); if (!iter->get_value(m_Columns.url).empty()) add_edit_site(iter); } void SiteEditor::on_url_edited(const std::string& p, const std::string& text) { Gtk::TreePath path{ p }; Gtk::TreeIter iter{ m_Model->get_iter(path) }; std::string url{ text }; if (url.back() == '/') url = text.substr(0, text.size() - 1); iter->set_value(m_Columns.url, url); add_edit_site(iter); } void SiteEditor::on_samples_toggled(const std::string& p) { Gtk::TreePath path{ p }; Gtk::TreeIter iter{ m_Model->get_iter(path) }; bool active{ iter->get_value(m_Columns.samples) }; iter->set_value(m_Columns.samples, !active); std::shared_ptr<Site> s{ iter->get_value(m_Columns.site) }; if (s) s->set_use_samples(iter->get_value(m_Columns.samples)); } void SiteEditor::on_row_changed(const Gtk::TreePath& path, const Gtk::TreeIter& iter) { if (!m_LastAddFromDND) return; m_CursorConn.block(); m_LastAddFromDND = false; std::shared_ptr<Site> s{ iter->get_value(m_Columns.site) }; if (s) { Gtk::TreePath other_path{ iter }; bool after{ false }; if (other_path.prev()) after = true; else other_path.next(); std::shared_ptr<Site> s2{ m_Model->get_iter(other_path)->get_value(m_Columns.site) }; if (s != s2) { auto i{ std::find(m_Sites.begin(), m_Sites.end(), s) }, i2{ std::find(m_Sites.begin(), m_Sites.end(), s2) }; // Insert after s2 if (after) ++i2; if (i < i2) std::rotate(i, i + 1, i2); else std::rotate(i2, i, i + 1); // Update the combobox m_SignalEdited(); // Calling this directly doesn't work, something handling this // signal later one might be setting the selection? Either way // queuing it works fine. Glib::signal_idle().connect_once([&, iter]() { get_selection()->select(iter); m_CursorConn.unblock(); }); } } } bool SiteEditor::is_name_unique(const Gtk::TreeIter& iter, const std::string& name) const { for (const Gtk::TreeIter& i : m_Model->children()) if (i->get_value(m_Columns.name) == name && iter != i) return false; return true; } void SiteEditor::add_edit_site(const Gtk::TreeIter& iter) { std::string name{ iter->get_value(m_Columns.name) }, url{ iter->get_value(m_Columns.url) }; if (name.empty() || url.empty()) { iter->set_value(m_Columns.icon, m_ErrorPixbuf); return; } if (m_SiteCheckThread.joinable()) m_SiteCheckThread.join(); m_SiteCheckIter = iter; std::vector<std::shared_ptr<Site>>::iterator i{ std::find( m_Sites.begin(), m_Sites.end(), iter->get_value(m_Columns.site)) }; std::shared_ptr<Site> site{ i != m_Sites.end() ? *i : nullptr }; // editting if (site) { if (name == site->get_name() && url == site->get_url()) { if (iter->get_value(m_Columns.icon) == m_ErrorPixbuf) iter->set_value(m_Columns.icon, site->get_icon_pixbuf()); return; } m_SiteCheckEdit = true; m_SiteCheckSite = site; m_SiteCheckIter->set_value(m_Columns.loading, true); m_SiteCheckThread = std::thread([&, name, url]() { m_SiteCheckSite->set_name(name); m_SiteCheckEditSuccess = m_SiteCheckSite->set_url(url); if (m_SiteCheckEditSuccess) update_edited_site_icon(); m_SignalSiteChecked(); }); } else { m_SiteCheckEdit = false; m_SiteCheckIter->set_value(m_Columns.loading, true); m_SiteCheckThread = std::thread([&, name, url]() { m_SiteCheckSite = Site::create(name, url); if (m_SiteCheckSite) update_edited_site_icon(); m_SignalSiteChecked(); }); } } void SiteEditor::update_edited_site_icon() { m_SiteCheckIter->set_value(m_Columns.icon, m_SiteCheckSite->get_icon_pixbuf(true)); m_SiteCheckIter->set_value(m_Columns.loading, false); } void SiteEditor::on_site_checked() { if ((m_SiteCheckEdit && !m_SiteCheckEditSuccess) || (!m_SiteCheckEdit && !m_SiteCheckSite)) { m_SiteCheckIter->set_value(m_Columns.icon, m_ErrorPixbuf); m_SiteCheckIter->set_value(m_Columns.loading, false); } else if (m_SiteCheckSite && !m_SiteCheckEdit) { // In case this was set before the site was actually created m_SiteCheckSite->set_use_samples(m_SiteCheckIter->get_value(m_Columns.samples)); m_Sites.push_back(m_SiteCheckSite); m_SiteCheckIter->set_value(m_Columns.site, m_SiteCheckSite); // Make the username/password entries sensitive on_my_cursor_changed(); } if (m_SiteCheckEdit || m_SiteCheckSite) m_SignalEdited(); if (m_SiteCheckThread.joinable()) m_SiteCheckThread.join(); } void SiteEditor::on_username_edited() { const std::shared_ptr<Site>& s{ get_selection()->get_selected()->get_value(m_Columns.site) }; if (s) s->set_username(m_UsernameEntry->get_text()); } void SiteEditor::on_password_edited() { const std::shared_ptr<Site>& s{ get_selection()->get_selected()->get_value(m_Columns.site) }; if (s) s->set_password(m_PasswordEntry->get_text()); } <commit_msg>siteeditor: My cursor changed doesn't need to be before the default handler<commit_after>#include "siteeditor.h" #include <gdk/gdkkeysyms-compat.h> #include <glibmm/i18n.h> using namespace AhoViewer; using namespace AhoViewer::Booru; #include "booru/site.h" #include "settings.h" #include "util.h" SiteEditor::SiteEditor(BaseObjectType* cobj, const Glib::RefPtr<Gtk::Builder>& bldr) : Gtk::TreeView(cobj), m_Model(Gtk::ListStore::create(m_Columns)), m_NameColumn(Gtk::manage(new Gtk::TreeView::Column(_("Name"), m_Columns.name))), m_UrlColumn(Gtk::manage(new Gtk::TreeView::Column(_("Url"), m_Columns.url))), m_SampleColumn(Gtk::manage(new Gtk::TreeView::Column(_("Samples"), m_Columns.samples))), m_Sites(Settings.get_sites()) { bldr->get_widget("BooruRegisterLinkButton", m_RegisterButton); bldr->get_widget("BooruUsernameEntry", m_UsernameEntry); bldr->get_widget("BooruPasswordEntry", m_PasswordEntry); bldr->get_widget("BooruPasswordLabel", m_PasswordLabel); m_SignalSiteChecked.connect(sigc::mem_fun(*this, &SiteEditor::on_site_checked)); for (const std::shared_ptr<Site>& s : m_Sites) { Gtk::TreeIter iter{ m_Model->append() }; iter->set_value(m_Columns.icon, s->get_icon_pixbuf()); s->signal_icon_downloaded().connect( [&, iter, s]() { iter->set_value(m_Columns.icon, s->get_icon_pixbuf()); }); iter->set_value(m_Columns.name, s->get_name()); iter->set_value(m_Columns.url, s->get_url()); iter->set_value(m_Columns.samples, s->use_samples()); iter->set_value(m_Columns.site, s); } try { m_ErrorPixbuf = Gtk::IconTheme::get_default()->load_icon( "edit-delete", Gtk::ICON_SIZE_MENU, Gtk::ICON_LOOKUP_USE_BUILTIN | Gtk::ICON_LOOKUP_GENERIC_FALLBACK); // TODO: Capture and print something useful } catch (...) { } CellRendererIcon* icon_renderer{ Gtk::manage(new CellRendererIcon(this)) }; icon_renderer->property_xpad() = 2; icon_renderer->property_ypad() = 2; append_column("", *icon_renderer); get_column(0)->add_attribute(icon_renderer->property_loading(), m_Columns.loading); get_column(0)->add_attribute(icon_renderer->property_pulse(), m_Columns.pulse); get_column(0)->add_attribute(icon_renderer->property_pixbuf(), m_Columns.icon); Gtk::CellRendererText* text_renderer{ nullptr }; text_renderer = static_cast<Gtk::CellRendererText*>(m_NameColumn->get_first_cell()); text_renderer->property_editable() = true; text_renderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_name_edited)); append_column(*m_NameColumn); text_renderer = static_cast<Gtk::CellRendererText*>(m_UrlColumn->get_first_cell()); text_renderer->property_editable() = true; text_renderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_url_edited)); m_UrlColumn->set_expand(true); append_column(*m_UrlColumn); auto* toggle_renderer = static_cast<Gtk::CellRendererToggle*>(m_SampleColumn->get_first_cell()); toggle_renderer->signal_toggled().connect( sigc::mem_fun(*this, &SiteEditor::on_samples_toggled)); toggle_renderer->set_activatable(true); append_column(*m_SampleColumn); set_model(m_Model); get_selection()->select(m_Model->children().begin()); Gtk::ToolButton* tool_button{ nullptr }; bldr->get_widget("DeleteSiteButton", tool_button); tool_button->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::delete_site)); bldr->get_widget("AddSiteButton", tool_button); tool_button->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::add_row)); m_UsernameConn = m_UsernameEntry->signal_changed().connect( sigc::mem_fun(*this, &SiteEditor::on_username_edited)); m_PasswordConn = m_PasswordEntry->signal_changed().connect( sigc::mem_fun(*this, &SiteEditor::on_password_edited)); m_CursorConn = signal_cursor_changed().connect(sigc::mem_fun(*this, &SiteEditor::on_my_cursor_changed)); #ifdef HAVE_LIBSECRET // Make sure the initially selected site's password gets set in the entry once it's loaded const std::shared_ptr<Site>& s{ get_selection()->get_selected()->get_value(m_Columns.site) }; if (s) s->signal_password_lookup().connect([&, s]() { m_PasswordConn.block(); m_PasswordEntry->set_text(s->get_password()); m_PasswordConn.unblock(); }); #endif // HAVE_LIBSECRET m_PasswordEntry->set_visibility(false); // Set initial values for entries and linkbutton on_my_cursor_changed(); // Set a flag to let the on_row_changed signal handler know that the change // is from a DND'ing m_RowInsertedConn = m_Model->signal_row_inserted().connect( [&](const Gtk::TreePath&, const Gtk::TreeIter& iter) { m_LastAddFromDND = true; }); m_Model->signal_row_changed().connect(sigc::mem_fun(*this, &SiteEditor::on_row_changed)); } SiteEditor::~SiteEditor() { if (m_SiteCheckThread.joinable()) m_SiteCheckThread.join(); } bool SiteEditor::on_key_release_event(GdkEventKey* e) { if (e->keyval == GDK_Return || e->keyval == GDK_ISO_Enter || e->keyval == GDK_KP_Enter || e->keyval == GDK_Tab) { Gtk::TreeIter iter{ get_selection()->get_selected() }; Gtk::TreePath p(iter); if (iter->get_value(m_Columns.url).empty()) set_cursor(p, *m_UrlColumn, true); else if (iter->get_value(m_Columns.name).empty()) set_cursor(p, *m_NameColumn, true); } return false; } void SiteEditor::on_my_cursor_changed() { std::shared_ptr<Site> s{ nullptr }; if (get_selection()->get_selected()) s = get_selection()->get_selected()->get_value(m_Columns.site); m_UsernameConn.block(); m_PasswordConn.block(); if (s) { m_RegisterButton->set_label(_("Register account on ") + s->get_name()); m_RegisterButton->set_uri(s->get_register_uri()); m_UsernameEntry->set_text(s->get_username()); m_PasswordEntry->set_text(s->get_password()); } else { m_RegisterButton->set_label(_("Register account")); m_UsernameEntry->set_text(""); m_PasswordEntry->set_text(""); } m_UsernameConn.unblock(); m_PasswordConn.unblock(); m_RegisterButton->set_sensitive(!!s); m_UsernameEntry->set_sensitive(!!s); m_PasswordEntry->set_sensitive(!!s); if (!s || s->get_type() == Type::GELBOORU) m_PasswordLabel->set_text(_("Password:")); else m_PasswordLabel->set_text(_("API Key:")); } void SiteEditor::add_row() { m_RowInsertedConn.block(); Gtk::TreePath path(m_Model->append()); m_RowInsertedConn.unblock(); set_cursor(path, *m_NameColumn, true); scroll_to_row(path); } void SiteEditor::delete_site() { Gtk::TreeIter o{ get_selection()->get_selected() }; if (o) { m_Sites.erase(std::remove(m_Sites.begin(), m_Sites.end(), o->get_value(m_Columns.site)), m_Sites.end()); m_SignalEdited(); Gtk::TreeIter n{ m_Model->erase(o) }; if (m_Model->children().size()) get_selection()->select(n ? n : --n); on_my_cursor_changed(); } } void SiteEditor::on_name_edited(const std::string& p, const std::string& text) { Gtk::TreePath path{ p }; Gtk::TreeIter iter{ m_Model->get_iter(path) }; std::string name{ text }; // make sure the site name is unique for (size_t i{ 1 }; !is_name_unique(iter, name); ++i) name = text + std::to_string(i); iter->set_value(m_Columns.name, name); if (!iter->get_value(m_Columns.url).empty()) add_edit_site(iter); } void SiteEditor::on_url_edited(const std::string& p, const std::string& text) { Gtk::TreePath path{ p }; Gtk::TreeIter iter{ m_Model->get_iter(path) }; std::string url{ text }; if (url.back() == '/') url = text.substr(0, text.size() - 1); iter->set_value(m_Columns.url, url); add_edit_site(iter); } void SiteEditor::on_samples_toggled(const std::string& p) { Gtk::TreePath path{ p }; Gtk::TreeIter iter{ m_Model->get_iter(path) }; bool active{ iter->get_value(m_Columns.samples) }; iter->set_value(m_Columns.samples, !active); std::shared_ptr<Site> s{ iter->get_value(m_Columns.site) }; if (s) s->set_use_samples(iter->get_value(m_Columns.samples)); } void SiteEditor::on_row_changed(const Gtk::TreePath& path, const Gtk::TreeIter& iter) { if (!m_LastAddFromDND) return; m_CursorConn.block(); m_LastAddFromDND = false; std::shared_ptr<Site> s{ iter->get_value(m_Columns.site) }; if (s) { Gtk::TreePath other_path{ iter }; bool after{ false }; if (other_path.prev()) after = true; else other_path.next(); std::shared_ptr<Site> s2{ m_Model->get_iter(other_path)->get_value(m_Columns.site) }; if (s != s2) { auto i{ std::find(m_Sites.begin(), m_Sites.end(), s) }, i2{ std::find(m_Sites.begin(), m_Sites.end(), s2) }; // Insert after s2 if (after) ++i2; if (i < i2) std::rotate(i, i + 1, i2); else std::rotate(i2, i, i + 1); // Update the combobox m_SignalEdited(); // Calling this directly doesn't work, something handling this // signal later one might be setting the selection? Either way // queuing it works fine. Glib::signal_idle().connect_once([&, iter]() { get_selection()->select(iter); m_CursorConn.unblock(); }); } } } bool SiteEditor::is_name_unique(const Gtk::TreeIter& iter, const std::string& name) const { for (const Gtk::TreeIter& i : m_Model->children()) if (i->get_value(m_Columns.name) == name && iter != i) return false; return true; } void SiteEditor::add_edit_site(const Gtk::TreeIter& iter) { std::string name{ iter->get_value(m_Columns.name) }, url{ iter->get_value(m_Columns.url) }; if (name.empty() || url.empty()) { iter->set_value(m_Columns.icon, m_ErrorPixbuf); return; } if (m_SiteCheckThread.joinable()) m_SiteCheckThread.join(); m_SiteCheckIter = iter; std::vector<std::shared_ptr<Site>>::iterator i{ std::find( m_Sites.begin(), m_Sites.end(), iter->get_value(m_Columns.site)) }; std::shared_ptr<Site> site{ i != m_Sites.end() ? *i : nullptr }; // editting if (site) { if (name == site->get_name() && url == site->get_url()) { if (iter->get_value(m_Columns.icon) == m_ErrorPixbuf) iter->set_value(m_Columns.icon, site->get_icon_pixbuf()); return; } m_SiteCheckEdit = true; m_SiteCheckSite = site; m_SiteCheckIter->set_value(m_Columns.loading, true); m_SiteCheckThread = std::thread([&, name, url]() { m_SiteCheckSite->set_name(name); m_SiteCheckEditSuccess = m_SiteCheckSite->set_url(url); if (m_SiteCheckEditSuccess) update_edited_site_icon(); m_SignalSiteChecked(); }); } else { m_SiteCheckEdit = false; m_SiteCheckIter->set_value(m_Columns.loading, true); m_SiteCheckThread = std::thread([&, name, url]() { m_SiteCheckSite = Site::create(name, url); if (m_SiteCheckSite) update_edited_site_icon(); m_SignalSiteChecked(); }); } } void SiteEditor::update_edited_site_icon() { m_SiteCheckIter->set_value(m_Columns.icon, m_SiteCheckSite->get_icon_pixbuf(true)); m_SiteCheckIter->set_value(m_Columns.loading, false); } void SiteEditor::on_site_checked() { if ((m_SiteCheckEdit && !m_SiteCheckEditSuccess) || (!m_SiteCheckEdit && !m_SiteCheckSite)) { m_SiteCheckIter->set_value(m_Columns.icon, m_ErrorPixbuf); m_SiteCheckIter->set_value(m_Columns.loading, false); } else if (m_SiteCheckSite && !m_SiteCheckEdit) { // In case this was set before the site was actually created m_SiteCheckSite->set_use_samples(m_SiteCheckIter->get_value(m_Columns.samples)); m_Sites.push_back(m_SiteCheckSite); m_SiteCheckIter->set_value(m_Columns.site, m_SiteCheckSite); // Make the username/password entries sensitive on_my_cursor_changed(); } if (m_SiteCheckEdit || m_SiteCheckSite) m_SignalEdited(); if (m_SiteCheckThread.joinable()) m_SiteCheckThread.join(); } void SiteEditor::on_username_edited() { const std::shared_ptr<Site>& s{ get_selection()->get_selected()->get_value(m_Columns.site) }; if (s) s->set_username(m_UsernameEntry->get_text()); } void SiteEditor::on_password_edited() { const std::shared_ptr<Site>& s{ get_selection()->get_selected()->get_value(m_Columns.site) }; if (s) s->set_password(m_PasswordEntry->get_text()); } <|endoftext|>
<commit_before>/* Copyright (c) 2012-2014 The SSDB Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "t_kv.h" int SSDBImpl::multi_set(const std::vector<Bytes> &kvs, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = kvs.begin() + offset; for(; it != kvs.end(); it += 2){ const Bytes &key = *it; if(key.empty()){ log_error("empty key!"); return 0; //return -1; } const Bytes &val = *(it + 1); std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_set error: %s", s.ToString().c_str()); return -1; } return (kvs.size() - offset)/2; } int SSDBImpl::multi_del(const std::vector<Bytes> &keys, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = keys.begin() + offset; for(; it != keys.end(); it++){ const Bytes &key = *it; std::string buf = encode_kv_key(key); binlogs->Delete(buf); binlogs->add_log(log_type, BinlogCommand::KDEL, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_del error: %s", s.ToString().c_str()); return -1; } return keys.size() - offset; } int SSDBImpl::set(const Bytes &key, const Bytes &val, char log_type){ if(key.empty()){ log_error("empty key!"); //return -1; return 0; } Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::setnx(const Bytes &key, const Bytes &val, char log_type){ if(key.empty()){ log_error("empty key!"); //return -1; return 0; } Transaction trans(binlogs); std::string tmp; int found = this->get(key, &tmp); if(found != 0){ return 0; } std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::getset(const Bytes &key, std::string *val, const Bytes &newval, char log_type){ if(key.empty()){ log_error("empty key!"); //return -1; return 0; } Transaction trans(binlogs); int found = this->get(key, val); std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(newval)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return found; } int SSDBImpl::del(const Bytes &key, char log_type){ Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->begin(); binlogs->Delete(buf); binlogs->add_log(log_type, BinlogCommand::KDEL, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::incr(const Bytes &key, int64_t by, int64_t *new_val, char log_type){ Transaction trans(binlogs); std::string old; int ret = this->get(key, &old); if(ret == -1){ return -1; }else if(ret == 0){ *new_val = by; }else{ *new_val = str_to_int64(old) + by; if(errno != 0){ return 0; } } std::string buf = encode_kv_key(key); binlogs->Put(buf, str(*new_val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::get(const Bytes &key, std::string *val){ std::string buf = encode_kv_key(key); leveldb::Status s = ldb->Get(leveldb::ReadOptions(), buf, val); if(s.IsNotFound()){ return 0; } if(!s.ok()){ log_error("get error: %s", s.ToString().c_str()); return -1; } return 1; } KIterator* SSDBImpl::scan(const Bytes &start, const Bytes &end, uint64_t limit){ std::string key_start, key_end; key_start = encode_kv_key(start); if(end.empty()){ key_end = ""; }else{ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->iterator(key_start, key_end, limit)); } KIterator* SSDBImpl::rscan(const Bytes &start, const Bytes &end, uint64_t limit){ std::string key_start, key_end; key_start = encode_kv_key(start); if(start.empty()){ key_start.append(1, 255); } if(!end.empty()){ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->rev_iterator(key_start, key_end, limit)); } int SSDBImpl::setbit(const Bytes &key, int bitoffset, int on, char log_type){ if(key.empty()){ log_error("empty key!"); return 0; } Transaction trans(binlogs); std::string val; int ret = this->get(key, &val); if(ret == -1){ return -1; } int len = bitoffset / 8; int bit = bitoffset % 8; if(len >= val.size()){ val.resize(len + 1, 0); } int orig = val[len] & (1 << bit); if(on == 1){ val[len] |= (1 << bit); }else{ val[len] &= ~(1 << bit); } std::string buf = encode_kv_key(key); binlogs->Put(buf, val); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return orig; } int SSDBImpl::getbit(const Bytes &key, int bitoffset){ std::string val; int ret = this->get(key, &val); if(ret == -1){ return -1; } int len = bitoffset / 8; int bit = bitoffset % 8; if(len >= val.size()){ return 0; } return (val[len] & (1 << bit)) == 0? 0 : 1; } <commit_msg>重复begin binlog<commit_after>/* Copyright (c) 2012-2014 The SSDB Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "t_kv.h" int SSDBImpl::multi_set(const std::vector<Bytes> &kvs, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = kvs.begin() + offset; for(; it != kvs.end(); it += 2){ const Bytes &key = *it; if(key.empty()){ log_error("empty key!"); return 0; //return -1; } const Bytes &val = *(it + 1); std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_set error: %s", s.ToString().c_str()); return -1; } return (kvs.size() - offset)/2; } int SSDBImpl::multi_del(const std::vector<Bytes> &keys, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = keys.begin() + offset; for(; it != keys.end(); it++){ const Bytes &key = *it; std::string buf = encode_kv_key(key); binlogs->Delete(buf); binlogs->add_log(log_type, BinlogCommand::KDEL, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_del error: %s", s.ToString().c_str()); return -1; } return keys.size() - offset; } int SSDBImpl::set(const Bytes &key, const Bytes &val, char log_type){ if(key.empty()){ log_error("empty key!"); //return -1; return 0; } Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::setnx(const Bytes &key, const Bytes &val, char log_type){ if(key.empty()){ log_error("empty key!"); //return -1; return 0; } Transaction trans(binlogs); std::string tmp; int found = this->get(key, &tmp); if(found != 0){ return 0; } std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::getset(const Bytes &key, std::string *val, const Bytes &newval, char log_type){ if(key.empty()){ log_error("empty key!"); //return -1; return 0; } Transaction trans(binlogs); int found = this->get(key, val); std::string buf = encode_kv_key(key); binlogs->Put(buf, slice(newval)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return found; } int SSDBImpl::del(const Bytes &key, char log_type){ Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->Delete(buf); binlogs->add_log(log_type, BinlogCommand::KDEL, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::incr(const Bytes &key, int64_t by, int64_t *new_val, char log_type){ Transaction trans(binlogs); std::string old; int ret = this->get(key, &old); if(ret == -1){ return -1; }else if(ret == 0){ *new_val = by; }else{ *new_val = str_to_int64(old) + by; if(errno != 0){ return 0; } } std::string buf = encode_kv_key(key); binlogs->Put(buf, str(*new_val)); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDBImpl::get(const Bytes &key, std::string *val){ std::string buf = encode_kv_key(key); leveldb::Status s = ldb->Get(leveldb::ReadOptions(), buf, val); if(s.IsNotFound()){ return 0; } if(!s.ok()){ log_error("get error: %s", s.ToString().c_str()); return -1; } return 1; } KIterator* SSDBImpl::scan(const Bytes &start, const Bytes &end, uint64_t limit){ std::string key_start, key_end; key_start = encode_kv_key(start); if(end.empty()){ key_end = ""; }else{ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->iterator(key_start, key_end, limit)); } KIterator* SSDBImpl::rscan(const Bytes &start, const Bytes &end, uint64_t limit){ std::string key_start, key_end; key_start = encode_kv_key(start); if(start.empty()){ key_start.append(1, 255); } if(!end.empty()){ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->rev_iterator(key_start, key_end, limit)); } int SSDBImpl::setbit(const Bytes &key, int bitoffset, int on, char log_type){ if(key.empty()){ log_error("empty key!"); return 0; } Transaction trans(binlogs); std::string val; int ret = this->get(key, &val); if(ret == -1){ return -1; } int len = bitoffset / 8; int bit = bitoffset % 8; if(len >= val.size()){ val.resize(len + 1, 0); } int orig = val[len] & (1 << bit); if(on == 1){ val[len] |= (1 << bit); }else{ val[len] &= ~(1 << bit); } std::string buf = encode_kv_key(key); binlogs->Put(buf, val); binlogs->add_log(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return orig; } int SSDBImpl::getbit(const Bytes &key, int bitoffset){ std::string val; int ret = this->get(key, &val); if(ret == -1){ return -1; } int len = bitoffset / 8; int bit = bitoffset % 8; if(len >= val.size()){ return 0; } return (val[len] & (1 << bit)) == 0? 0 : 1; } <|endoftext|>
<commit_before>#include "config.h" #include <sys/resource.h> #include <sys/time.h> #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <memory> #include <sstream> #include <string> #include <thread> #include "regexbench.h" using namespace regexbench; static std::map<std::string, size_t> make_statistic(const uint32_t sec, const size_t usec, const struct ResultInfo& stat, const struct ResultInfo& total); static struct ResultInfo realtime(std::vector<MatchResult>& results); static struct ResultInfo total(std::vector<MatchResult>& results); void regexbench::statistic(const uint32_t sec, timeval& begin, std::vector<MatchResult>& results, realtimeFunc func, void* p) { struct ResultInfo stat = realtime(results); struct ResultInfo tstat = total(results); size_t usec = 0; timeval diff; for (auto& r : results) { // not ended yet. if (r.endtime.tv_sec == 0 && r.endtime.tv_usec == 0) { usec = 0; break; } timersub(&(r.endtime), &begin, &diff); // if sec is less than 0, then already finished before begin time. if (diff.tv_sec < 0) continue; size_t m_usec = static_cast<size_t>(diff.tv_sec * 1e+6 + diff.tv_usec); if (usec < m_usec) usec = m_usec; } if (usec == 0) { timeval end; gettimeofday(&end, NULL); timersub(&end, &begin, &diff); begin = end; usec = static_cast<size_t>(diff.tv_sec * 1e+6 + diff.tv_usec); } // std::cout << std::fixed << std::setprecision(6) << "usec : " << usec << // std::endl; std::map<std::string, size_t> m = make_statistic(sec, usec, stat, tstat); // if the number of processed packets is 0, then complete. if (func && m["Packets"] != 0) func(m, p); } static struct ResultInfo realtime(std::vector<MatchResult>& results) { struct ResultInfo stat; for (auto& r : results) { const auto cur = r.cur; auto& old = (r.old); stat.nmatches += cur.nmatches - old.nmatches; stat.nmatched_pkts += cur.nmatched_pkts - old.nmatched_pkts; stat.npkts += cur.npkts - old.npkts; stat.nbytes += cur.nbytes - old.nbytes; old = cur; } return stat; } static struct ResultInfo total(std::vector<MatchResult>& results) { struct ResultInfo stat; for (auto& r : results) { const struct ResultInfo& cur = r.cur; stat.nmatches += cur.nmatches; stat.nmatched_pkts += cur.nmatched_pkts; stat.npkts += cur.npkts; stat.nbytes += cur.nbytes; } return stat; } static std::map<std::string, size_t> make_statistic(const uint32_t sec, const size_t usec, const struct ResultInfo& stat, const struct ResultInfo& total) { std::map<std::string, size_t> m; m["Sec"] = sec; m["Usec"] = usec; m["Matches"] = stat.nmatches; m["MatchedPackets"] = stat.nmatched_pkts; m["Packets"] = stat.npkts; m["Bytes"] = stat.nbytes; m["TotalMatches"] = total.nmatches; m["TotalMatchedPackets"] = total.nmatched_pkts; m["TotalPackets"] = total.npkts; m["TotalBytes"] = total.nbytes; return m; } <commit_msg>apply format<commit_after>#include "config.h" #include <sys/resource.h> #include <sys/time.h> #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <memory> #include <sstream> #include <string> #include <thread> #include "regexbench.h" using namespace regexbench; static std::map<std::string, size_t> make_statistic(const uint32_t sec, const size_t usec, const struct ResultInfo& stat, const struct ResultInfo& total); static struct ResultInfo realtime(std::vector<MatchResult>& results); static struct ResultInfo total(std::vector<MatchResult>& results); void regexbench::statistic(const uint32_t sec, timeval& begin, std::vector<MatchResult>& results, realtimeFunc func, void* p) { struct ResultInfo stat = realtime(results); struct ResultInfo tstat = total(results); size_t usec = 0; timeval diff; for (auto& r : results) { // not ended yet. if (r.endtime.tv_sec == 0 && r.endtime.tv_usec == 0) { usec = 0; break; } timersub(&(r.endtime), &begin, &diff); // if sec is less than 0, then already finished before begin time. if (diff.tv_sec < 0) continue; size_t m_usec = static_cast<size_t>(diff.tv_sec * 1e+6 + diff.tv_usec); if (usec < m_usec) usec = m_usec; } if (usec == 0) { timeval end; gettimeofday(&end, NULL); timersub(&end, &begin, &diff); begin = end; usec = static_cast<size_t>(diff.tv_sec * 1e+6 + diff.tv_usec); } // std::cout << std::fixed << std::setprecision(6) << "usec : " << usec << // std::endl; std::map<std::string, size_t> m = make_statistic(sec, usec, stat, tstat); // if the number of processed packets is 0, then complete. if (func && m["Packets"] != 0) func(m, p); } static struct ResultInfo realtime(std::vector<MatchResult>& results) { struct ResultInfo stat; for (auto& r : results) { const auto cur = r.cur; auto& old = (r.old); stat.nmatches += cur.nmatches - old.nmatches; stat.nmatched_pkts += cur.nmatched_pkts - old.nmatched_pkts; stat.npkts += cur.npkts - old.npkts; stat.nbytes += cur.nbytes - old.nbytes; old = cur; } return stat; } static struct ResultInfo total(std::vector<MatchResult>& results) { struct ResultInfo stat; for (auto& r : results) { const struct ResultInfo& cur = r.cur; stat.nmatches += cur.nmatches; stat.nmatched_pkts += cur.nmatched_pkts; stat.npkts += cur.npkts; stat.nbytes += cur.nbytes; } return stat; } static std::map<std::string, size_t> make_statistic(const uint32_t sec, const size_t usec, const struct ResultInfo& stat, const struct ResultInfo& total) { std::map<std::string, size_t> m; m["Sec"] = sec; m["Usec"] = usec; m["Matches"] = stat.nmatches; m["MatchedPackets"] = stat.nmatched_pkts; m["Packets"] = stat.npkts; m["Bytes"] = stat.nbytes; m["TotalMatches"] = total.nmatches; m["TotalMatchedPackets"] = total.nmatched_pkts; m["TotalPackets"] = total.npkts; m["TotalBytes"] = total.nbytes; return m; } <|endoftext|>
<commit_before>// Copyright (C) 2015 team-diana MIT license #define BOOST_TEST_MODULE PdoConfiguration_test #include <iostream> #include <bitset> #include "hlcanopen/sdo_client.hpp" #include "hlcanopen/can_msg.hpp" #include "hlcanopen/types.hpp" #include "hlcanopen/sdo_data_converter.hpp" #include "hlcanopen/pdo_configuration.hpp" #include "hlcanopen/pdo_client.hpp" #include "test_utils.hpp" #include "cansim/bi_pipe.hpp" #include "cansim/bus_less_card.hpp" #include "boost/test/unit_test.hpp" #include "logging/easylogging++.h" using namespace std; using namespace hlcanopen; BOOST_TEST_DONT_PRINT_LOG_VALUE(TransStatus); void print_bytes(CanMsg msg) { size_t i; printf("[ "); for(i = 0; i < 8; i++) { printf("%02x ", msg[i]); } printf("]\n"); } typedef BusLessCard<CanMsg> TestCard; BOOST_AUTO_TEST_CASE(PdoConfigurationTest) { auto pipes = BiPipe<CanMsg>::make(); TestCard card(std::get<1>(pipes)); NodeId nodeId = 1; std::shared_ptr<BiPipe<CanMsg>> testPipe = std::get<0>(pipes); PdoClient<TestCard> client(nodeId, card); PdoConfiguration conf(RPDO, 1); COBIdPdoEntry PdoEntry; PdoEntry.setCobId(COBId(1, 0x182)); PdoEntry.enable29bitId(true); PdoEntry.enablePdo(false); PdoEntry.enableRtr(false); conf.setCobId(PdoEntry); conf.setTransmissionType(ASYNCHRONOUS, 1); conf.setNumberOfEntries(); conf.addMapping(SDOIndex(0x1234, 0x00), SDOIndex(0x2002, 0x00), 0x40); client.writeConfiguration(conf); /* 0x00 */ CanMsg msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x01 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x02 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x03 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x04 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x05 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 1st object mapped */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* Enable PDO */ msg = testPipe->read(); print_bytes(msg); printf("\n"); } <commit_msg>Change include path of easylogging++<commit_after>// Copyright (C) 2015 team-diana MIT license #define BOOST_TEST_MODULE PdoConfiguration_test #include <iostream> #include <bitset> #include "hlcanopen/sdo_client.hpp" #include "hlcanopen/can_msg.hpp" #include "hlcanopen/types.hpp" #include "hlcanopen/sdo_data_converter.hpp" #include "hlcanopen/pdo_configuration.hpp" #include "hlcanopen/pdo_client.hpp" #include "hlcanopen/logging/easylogging++.h" #include "test_utils.hpp" #include "cansim/bi_pipe.hpp" #include "cansim/bus_less_card.hpp" #include "boost/test/unit_test.hpp" using namespace std; using namespace hlcanopen; BOOST_TEST_DONT_PRINT_LOG_VALUE(TransStatus); void print_bytes(CanMsg msg) { size_t i; printf("[ "); for(i = 0; i < 8; i++) { printf("%02x ", msg[i]); } printf("]\n"); } typedef BusLessCard<CanMsg> TestCard; BOOST_AUTO_TEST_CASE(PdoConfigurationTest) { auto pipes = BiPipe<CanMsg>::make(); TestCard card(std::get<1>(pipes)); NodeId nodeId = 1; std::shared_ptr<BiPipe<CanMsg>> testPipe = std::get<0>(pipes); PdoClient<TestCard> client(nodeId, card); PdoConfiguration conf(RPDO, 1); COBIdPdoEntry PdoEntry; PdoEntry.setCobId(COBId(1, 0x182)); PdoEntry.enable29bitId(true); PdoEntry.enablePdo(false); PdoEntry.enableRtr(false); conf.setCobId(PdoEntry); conf.setTransmissionType(ASYNCHRONOUS, 1); conf.setNumberOfEntries(); conf.addMapping(SDOIndex(0x1234, 0x00), SDOIndex(0x2002, 0x00), 0x40); client.writeConfiguration(conf); /* 0x00 */ CanMsg msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x01 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x02 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x03 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x04 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 0x05 */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* 1st object mapped */ msg = testPipe->read(); print_bytes(msg); printf("\n"); /* Enable PDO */ msg = testPipe->read(); print_bytes(msg); printf("\n"); } <|endoftext|>
<commit_before>#include <node_buffer.h> #include <nan.h> extern "C" { #include <string.h> } #include "structures.h" #include "common.h" using namespace v8; using namespace node; static void addHeaderOptions( Local<Object> jsObject, uint8_t optionCount, OCHeaderOption *options ) { uint32_t optionIndex, optionDataIndex; // numRcvdVendorSpecificHeaderOptions jsObject->Set( NanNew<String>( "numRcvdVendorSpecificHeaderOptions" ), NanNew<Number>( optionCount ) ); // rcvdVendorSpecificHeaderOptions Local<Array> headerOptions = NanNew<Array>( optionCount ); // rcvdVendorSpecificHeaderOptions[ index ] for ( optionIndex = 0 ; optionIndex < optionCount ; optionIndex++ ) { Local<Object> headerOption = NanNew<Object>(); // response.rcvdVendorSpecificHeaderOptions[ index ].protocolID headerOption->Set( NanNew<String>( "protocolID" ), NanNew<Number>( options[ optionIndex ].protocolID ) ); // response.rcvdVendorSpecificHeaderOptions[ index ].optionID headerOption->Set( NanNew<String>( "optionID" ), NanNew<Number>( options[ optionIndex ].optionID ) ); // response.rcvdVendorSpecificHeaderOptions[ index ].optionLength headerOption->Set( NanNew<String>( "optionLength" ), NanNew<Number>( options[ optionIndex ].optionLength ) ); // response.rcvdVendorSpecificHeaderOptions[ index ].optionData Local<Array> headerOptionData = NanNew<Array>( options[ optionIndex ].optionLength ); for ( optionDataIndex = 0 ; optionDataIndex < options[ optionIndex ].optionLength ; optionDataIndex++ ) { headerOptionData->Set( optionDataIndex, NanNew<Number>( options[ optionIndex ].optionData[ optionDataIndex ] ) ); } headerOption->Set( NanNew<String>( "optionData" ), headerOptionData ); headerOptions->Set( optionIndex, headerOption ); } jsObject->Set( NanNew<String>( "rcvdVendorSpecificHeaderOptions" ), headerOptions ); } Local<Object> js_OCClientResponse( OCClientResponse *response ) { uint32_t addressIndex; Local<Object> jsResponse = NanNew<Object>(); // jsResponse.addr Local<Object> addr = NanNew<Object>(); // jsResponse.addr.size addr->Set( NanNew<String>( "size" ), NanNew<Number>( response->addr->size ) ); // jsResponse.addr.addr Local<Array> addrAddr = NanNew<Array>( response->addr->size ); for ( addressIndex = 0 ; addressIndex < response->addr->size ; addressIndex++ ) { addrAddr->Set( addressIndex, NanNew<Number>( response->addr->addr[ addressIndex ] ) ); } addr->Set( NanNew<String>( "addr" ), addrAddr ); jsResponse->Set( NanNew<String>( "addr" ), addr ); // jsResponse.connType jsResponse->Set( NanNew<String>( "connType" ), NanNew<Number>( response->connType ) ); // jsResponse.result jsResponse->Set( NanNew<String>( "result" ), NanNew<Number>( response->result ) ); // jsResponse.sequenceNumber jsResponse->Set( NanNew<String>( "sequenceNumber" ), NanNew<Number>( response->sequenceNumber ) ); // jsResponse.resJSONPayload if ( response->resJSONPayload ) { jsResponse->Set( NanNew<String>( "resJSONPayload" ), NanNew<String>( response->resJSONPayload ) ); } addHeaderOptions( jsResponse, response->numRcvdVendorSpecificHeaderOptions, response->rcvdVendorSpecificHeaderOptions ); return jsResponse; } bool c_OCEntityHandlerResponse( OCEntityHandlerResponse *destination, v8::Local<Object> jsOCEntityHandlerResponse ) { // requestHandle Local<Value> requestHandle = jsOCEntityHandlerResponse->Get( NanNew<String>( "requestHandle" ) ); if ( !Buffer::HasInstance( requestHandle ) ) { NanThrowTypeError( "requestHandle is not a Node::Buffer" ); return false; } destination->requestHandle = *( OCRequestHandle * )Buffer::Data( requestHandle->ToObject() ); // responseHandle is filled in by the stack // resourceHandle Local<Value> resourceHandle = jsOCEntityHandlerResponse->Get( NanNew<String>( "resourceHandle" ) ); if ( !Buffer::HasInstance( resourceHandle ) ) { NanThrowTypeError( "resourceHandle is not a Node::Buffer" ); return false; } destination->resourceHandle = *( OCResourceHandle * )Buffer::Data( resourceHandle->ToObject() ); // ehResult Local<Value> ehResult = jsOCEntityHandlerResponse->Get( NanNew<String>( "ehResult" ) ); VALIDATE_VALUE_TYPE( ehResult, IsUint32, "ehResult", false ); destination->ehResult = ( OCEntityHandlerResult )ehResult->Uint32Value(); // payload Local<Value> payload = jsOCEntityHandlerResponse->Get( NanNew<String>( "payload" ) ); VALIDATE_VALUE_TYPE( payload, IsString, "payload", false ); const char *payloadString = ( const char * )*String::Utf8Value( payload ); size_t payloadLength = strlen( payloadString ); if ( payloadLength >= MAX_RESPONSE_LENGTH ) { NanThrowRangeError( "payload is longer than MAX_RESPONSE_LENGTH" ); return false; } strncpy( destination->payload, payloadString, payloadLength ); // payloadSize destination->payloadSize = payloadLength; // numSendVendorSpecificHeaderOptions Local<Value> numSendVendorSpecificHeaderOptions = jsOCEntityHandlerResponse->Get( NanNew<String>( "numSendVendorSpecificHeaderOptions" ) ); VALIDATE_VALUE_TYPE( numSendVendorSpecificHeaderOptions, IsUint32, "numSendVendorSpecificHeaderOptions", false ); uint8_t headerOptionCount = ( uint8_t )numSendVendorSpecificHeaderOptions->Uint32Value(); if ( headerOptionCount > MAX_HEADER_OPTIONS ) { NanThrowRangeError( "numSendVendorSpecificHeaderOptions is larger than MAX_HEADER_OPTIONS" ); return false; } destination->numSendVendorSpecificHeaderOptions = headerOptionCount; // sendVendorSpecificHeaderOptions int headerOptionIndex, optionDataIndex; Local<Value> headerOptionsValue = jsOCEntityHandlerResponse->Get( NanNew<String>( "sendVendorSpecificHeaderOptions" ) ); VALIDATE_VALUE_TYPE( headerOptionsValue, IsArray, "sendVendorSpecificHeaderOptions", false ); Local<Array> headerOptions = Local<Array>::Cast( headerOptionsValue ); for ( headerOptionIndex = 0 ; headerOptionIndex < headerOptionCount; headerOptionIndex++ ) { Local<Value> headerOptionValue = headerOptions->Get( headerOptionIndex ); VALIDATE_VALUE_TYPE( headerOptionValue, IsObject, "sendVendorSpecificHeaderOptions member", false ); Local<Object> headerOption = headerOptionValue->ToObject(); // sendVendorSpecificHeaderOptions[].protocolID Local<Value> protocolIDValue = headerOption->Get( NanNew<String>( "protocolID" ) ); VALIDATE_VALUE_TYPE( protocolIDValue, IsUint32, "protocolID", false ); destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ].protocolID = ( OCTransportProtocolID )protocolIDValue->Uint32Value(); // sendVendorSpecificHeaderOptions[].optionID Local<Value> optionIDValue = headerOption->Get( NanNew<String>( "optionID" ) ); VALIDATE_VALUE_TYPE( optionIDValue, IsUint32, "optionID", false ); destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ].optionID = ( uint16_t )protocolIDValue->Uint32Value(); // sendVendorSpecificHeaderOptions[].optionLength Local<Value> optionLengthValue = headerOption->Get( NanNew<String>( "optionLength" ) ); VALIDATE_VALUE_TYPE( optionLengthValue, IsUint32, "optionLength", false ); uint16_t optionLength = ( uint16_t )optionLengthValue->Uint32Value(); if ( optionLength > MAX_HEADER_OPTION_DATA_LENGTH ) { NanThrowRangeError( "optionLength is larger than MAX_HEADER_OPTION_DATA_LENGTH" ); return false; } destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ].optionLength = optionLength; // sendVendorSpecificHeaderOptions[].optionData Local<Value> optionDataValue = headerOption->Get( NanNew<String>( "optionData" ) ); VALIDATE_VALUE_TYPE( optionDataValue, IsArray, "optionData", false ); Local<Array> optionData = Local<Array>::Cast( optionDataValue ); for ( optionDataIndex = 0 ; optionDataIndex < optionLength ; optionDataIndex++ ) { Local<Value> optionDataItemValue = optionData->Get( optionDataIndex ); VALIDATE_VALUE_TYPE( optionDataItemValue, IsUint32, "optionData item", false ); destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ] .optionData[ optionDataIndex ] = ( uint8_t )optionDataItemValue->Uint32Value(); } } return true; } Local<Object> js_OCResourceHandle( Local<Object> jsHandle, OCResourceHandle handle ) { jsHandle->Set( NanNew<String>( "handle" ), NanNewBufferHandle( ( const char * )&handle, sizeof( OCResourceHandle ) ) ); return jsHandle; } OCResourceHandle c_OCResourceHandle( Local<Object> jsHandle ) { Local<Value> handle = jsHandle->Get( NanNew<String>( "handle" ) ); if ( !Buffer::HasInstance( handle ) ) { NanThrowTypeError( "OCResourceHandle.handle is not a Node::Buffer" ); return 0; } return *( OCResourceHandle * )Buffer::Data( handle->ToObject() ); } // Returns the Local<Object> which was passed in static Local<Object> js_OCRequestHandle( Local<Object> jsHandle, OCRequestHandle handle ) { jsHandle->Set( NanNew<String>( "handle" ), NanNewBufferHandle( ( const char * )&handle, sizeof( OCRequestHandle ) ) ); return jsHandle; } Local<Object> js_OCEntityHandlerRequest( OCEntityHandlerRequest *request ) { Local<Object> jsRequest = NanNew<Object>(); jsRequest->Set( NanNew<String>( "resource" ), js_OCResourceHandle( NanNew<Object>(), request->resource ) ); jsRequest->Set( NanNew<String>( "requestHandle" ), js_OCRequestHandle( NanNew<Object>(), request->requestHandle ) ); jsRequest->Set( NanNew<String>( "method" ), NanNew<Number>( request->method ) ); jsRequest->Set( NanNew<String>( "query" ), NanNew<String>( request->query ) ); Local<Object> obsInfo = NanNew<Object>(); obsInfo->Set( NanNew<String>( "action" ), NanNew<Number>( request->obsInfo.action ) ); obsInfo->Set( NanNew<String>( "obsId" ), NanNew<Number>( request->obsInfo.obsId ) ); jsRequest->Set( NanNew<String>( "obsInfo" ), obsInfo ); jsRequest->Set( NanNew<String>( "reqJSONPayload" ), NanNew<String>( request->reqJSONPayload ) ); addHeaderOptions( jsRequest, request->numRcvdVendorSpecificHeaderOptions, request->rcvdVendorSpecificHeaderOptions ); return jsRequest; } <commit_msg>Structures: Stop using stale payload pointers<commit_after>#include <node_buffer.h> #include <nan.h> extern "C" { #include <string.h> } #include "structures.h" #include "common.h" using namespace v8; using namespace node; static void addHeaderOptions( Local<Object> jsObject, uint8_t optionCount, OCHeaderOption *options ) { uint32_t optionIndex, optionDataIndex; // numRcvdVendorSpecificHeaderOptions jsObject->Set( NanNew<String>( "numRcvdVendorSpecificHeaderOptions" ), NanNew<Number>( optionCount ) ); // rcvdVendorSpecificHeaderOptions Local<Array> headerOptions = NanNew<Array>( optionCount ); // rcvdVendorSpecificHeaderOptions[ index ] for ( optionIndex = 0 ; optionIndex < optionCount ; optionIndex++ ) { Local<Object> headerOption = NanNew<Object>(); // response.rcvdVendorSpecificHeaderOptions[ index ].protocolID headerOption->Set( NanNew<String>( "protocolID" ), NanNew<Number>( options[ optionIndex ].protocolID ) ); // response.rcvdVendorSpecificHeaderOptions[ index ].optionID headerOption->Set( NanNew<String>( "optionID" ), NanNew<Number>( options[ optionIndex ].optionID ) ); // response.rcvdVendorSpecificHeaderOptions[ index ].optionLength headerOption->Set( NanNew<String>( "optionLength" ), NanNew<Number>( options[ optionIndex ].optionLength ) ); // response.rcvdVendorSpecificHeaderOptions[ index ].optionData Local<Array> headerOptionData = NanNew<Array>( options[ optionIndex ].optionLength ); for ( optionDataIndex = 0 ; optionDataIndex < options[ optionIndex ].optionLength ; optionDataIndex++ ) { headerOptionData->Set( optionDataIndex, NanNew<Number>( options[ optionIndex ].optionData[ optionDataIndex ] ) ); } headerOption->Set( NanNew<String>( "optionData" ), headerOptionData ); headerOptions->Set( optionIndex, headerOption ); } jsObject->Set( NanNew<String>( "rcvdVendorSpecificHeaderOptions" ), headerOptions ); } Local<Object> js_OCClientResponse( OCClientResponse *response ) { uint32_t addressIndex; Local<Object> jsResponse = NanNew<Object>(); // jsResponse.addr Local<Object> addr = NanNew<Object>(); // jsResponse.addr.size addr->Set( NanNew<String>( "size" ), NanNew<Number>( response->addr->size ) ); // jsResponse.addr.addr Local<Array> addrAddr = NanNew<Array>( response->addr->size ); for ( addressIndex = 0 ; addressIndex < response->addr->size ; addressIndex++ ) { addrAddr->Set( addressIndex, NanNew<Number>( response->addr->addr[ addressIndex ] ) ); } addr->Set( NanNew<String>( "addr" ), addrAddr ); jsResponse->Set( NanNew<String>( "addr" ), addr ); // jsResponse.connType jsResponse->Set( NanNew<String>( "connType" ), NanNew<Number>( response->connType ) ); // jsResponse.result jsResponse->Set( NanNew<String>( "result" ), NanNew<Number>( response->result ) ); // jsResponse.sequenceNumber jsResponse->Set( NanNew<String>( "sequenceNumber" ), NanNew<Number>( response->sequenceNumber ) ); // jsResponse.resJSONPayload if ( response->resJSONPayload ) { jsResponse->Set( NanNew<String>( "resJSONPayload" ), NanNew<String>( response->resJSONPayload ) ); } addHeaderOptions( jsResponse, response->numRcvdVendorSpecificHeaderOptions, response->rcvdVendorSpecificHeaderOptions ); return jsResponse; } bool c_OCEntityHandlerResponse( OCEntityHandlerResponse *destination, v8::Local<Object> jsOCEntityHandlerResponse ) { // requestHandle Local<Value> requestHandle = jsOCEntityHandlerResponse->Get( NanNew<String>( "requestHandle" ) ); if ( !Buffer::HasInstance( requestHandle ) ) { NanThrowTypeError( "requestHandle is not a Node::Buffer" ); return false; } destination->requestHandle = *( OCRequestHandle * )Buffer::Data( requestHandle->ToObject() ); // responseHandle is filled in by the stack // resourceHandle Local<Value> resourceHandle = jsOCEntityHandlerResponse->Get( NanNew<String>( "resourceHandle" ) ); if ( !Buffer::HasInstance( resourceHandle ) ) { NanThrowTypeError( "resourceHandle is not a Node::Buffer" ); return false; } destination->resourceHandle = *( OCResourceHandle * )Buffer::Data( resourceHandle->ToObject() ); // ehResult Local<Value> ehResult = jsOCEntityHandlerResponse->Get( NanNew<String>( "ehResult" ) ); VALIDATE_VALUE_TYPE( ehResult, IsUint32, "ehResult", false ); destination->ehResult = ( OCEntityHandlerResult )ehResult->Uint32Value(); // payload and payloadSize Local<Value> payload = jsOCEntityHandlerResponse->Get( NanNew<String>( "payload" ) ); VALIDATE_VALUE_TYPE( payload, IsString, "payload", false ); // Make sure the size in bytes of the UTF-8 representation, including the terminating NULL // character, does not exceed MAX_RESPONSE_LENGTH size_t payloadLength = ( size_t )payload->ToString()->Utf8Length(); if ( payloadLength >= MAX_RESPONSE_LENGTH ) { NanThrowRangeError( "payload is longer than MAX_RESPONSE_LENGTH" ); return false; } // Zero out the destination and copy the string into it, and indicate the payload size memset( destination->payload, 0, MAX_RESPONSE_LENGTH ); strncpy( destination->payload, ( const char * )*String::Utf8Value( payload ), MAX_RESPONSE_LENGTH ); destination->payloadSize = payloadLength; // numSendVendorSpecificHeaderOptions Local<Value> numSendVendorSpecificHeaderOptions = jsOCEntityHandlerResponse->Get( NanNew<String>( "numSendVendorSpecificHeaderOptions" ) ); VALIDATE_VALUE_TYPE( numSendVendorSpecificHeaderOptions, IsUint32, "numSendVendorSpecificHeaderOptions", false ); uint8_t headerOptionCount = ( uint8_t )numSendVendorSpecificHeaderOptions->Uint32Value(); if ( headerOptionCount > MAX_HEADER_OPTIONS ) { NanThrowRangeError( "numSendVendorSpecificHeaderOptions is larger than MAX_HEADER_OPTIONS" ); return false; } destination->numSendVendorSpecificHeaderOptions = headerOptionCount; // sendVendorSpecificHeaderOptions int headerOptionIndex, optionDataIndex; Local<Value> headerOptionsValue = jsOCEntityHandlerResponse->Get( NanNew<String>( "sendVendorSpecificHeaderOptions" ) ); VALIDATE_VALUE_TYPE( headerOptionsValue, IsArray, "sendVendorSpecificHeaderOptions", false ); Local<Array> headerOptions = Local<Array>::Cast( headerOptionsValue ); for ( headerOptionIndex = 0 ; headerOptionIndex < headerOptionCount; headerOptionIndex++ ) { Local<Value> headerOptionValue = headerOptions->Get( headerOptionIndex ); VALIDATE_VALUE_TYPE( headerOptionValue, IsObject, "sendVendorSpecificHeaderOptions member", false ); Local<Object> headerOption = headerOptionValue->ToObject(); // sendVendorSpecificHeaderOptions[].protocolID Local<Value> protocolIDValue = headerOption->Get( NanNew<String>( "protocolID" ) ); VALIDATE_VALUE_TYPE( protocolIDValue, IsUint32, "protocolID", false ); destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ].protocolID = ( OCTransportProtocolID )protocolIDValue->Uint32Value(); // sendVendorSpecificHeaderOptions[].optionID Local<Value> optionIDValue = headerOption->Get( NanNew<String>( "optionID" ) ); VALIDATE_VALUE_TYPE( optionIDValue, IsUint32, "optionID", false ); destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ].optionID = ( uint16_t )protocolIDValue->Uint32Value(); // sendVendorSpecificHeaderOptions[].optionLength Local<Value> optionLengthValue = headerOption->Get( NanNew<String>( "optionLength" ) ); VALIDATE_VALUE_TYPE( optionLengthValue, IsUint32, "optionLength", false ); uint16_t optionLength = ( uint16_t )optionLengthValue->Uint32Value(); if ( optionLength > MAX_HEADER_OPTION_DATA_LENGTH ) { NanThrowRangeError( "optionLength is larger than MAX_HEADER_OPTION_DATA_LENGTH" ); return false; } destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ].optionLength = optionLength; // sendVendorSpecificHeaderOptions[].optionData Local<Value> optionDataValue = headerOption->Get( NanNew<String>( "optionData" ) ); VALIDATE_VALUE_TYPE( optionDataValue, IsArray, "optionData", false ); Local<Array> optionData = Local<Array>::Cast( optionDataValue ); for ( optionDataIndex = 0 ; optionDataIndex < optionLength ; optionDataIndex++ ) { Local<Value> optionDataItemValue = optionData->Get( optionDataIndex ); VALIDATE_VALUE_TYPE( optionDataItemValue, IsUint32, "optionData item", false ); destination->sendVendorSpecificHeaderOptions[ headerOptionIndex ] .optionData[ optionDataIndex ] = ( uint8_t )optionDataItemValue->Uint32Value(); } } return true; } Local<Object> js_OCResourceHandle( Local<Object> jsHandle, OCResourceHandle handle ) { jsHandle->Set( NanNew<String>( "handle" ), NanNewBufferHandle( ( const char * )&handle, sizeof( OCResourceHandle ) ) ); return jsHandle; } OCResourceHandle c_OCResourceHandle( Local<Object> jsHandle ) { Local<Value> handle = jsHandle->Get( NanNew<String>( "handle" ) ); if ( !Buffer::HasInstance( handle ) ) { NanThrowTypeError( "OCResourceHandle.handle is not a Node::Buffer" ); return 0; } return *( OCResourceHandle * )Buffer::Data( handle->ToObject() ); } // Returns the Local<Object> which was passed in static Local<Object> js_OCRequestHandle( Local<Object> jsHandle, OCRequestHandle handle ) { jsHandle->Set( NanNew<String>( "handle" ), NanNewBufferHandle( ( const char * )&handle, sizeof( OCRequestHandle ) ) ); return jsHandle; } Local<Object> js_OCEntityHandlerRequest( OCEntityHandlerRequest *request ) { Local<Object> jsRequest = NanNew<Object>(); jsRequest->Set( NanNew<String>( "resource" ), js_OCResourceHandle( NanNew<Object>(), request->resource ) ); jsRequest->Set( NanNew<String>( "requestHandle" ), js_OCRequestHandle( NanNew<Object>(), request->requestHandle ) ); jsRequest->Set( NanNew<String>( "method" ), NanNew<Number>( request->method ) ); jsRequest->Set( NanNew<String>( "query" ), NanNew<String>( request->query ) ); Local<Object> obsInfo = NanNew<Object>(); obsInfo->Set( NanNew<String>( "action" ), NanNew<Number>( request->obsInfo.action ) ); obsInfo->Set( NanNew<String>( "obsId" ), NanNew<Number>( request->obsInfo.obsId ) ); jsRequest->Set( NanNew<String>( "obsInfo" ), obsInfo ); jsRequest->Set( NanNew<String>( "reqJSONPayload" ), NanNew<String>( request->reqJSONPayload ) ); addHeaderOptions( jsRequest, request->numRcvdVendorSpecificHeaderOptions, request->rcvdVendorSpecificHeaderOptions ); return jsRequest; } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d\n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors\n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){//fiber and therefore plate is used A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used //and otherwise the position of plate j in list of used plates inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); if(F.diagnose)diagnostic(M,Secret,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++){ printf(" i=%d interval %d \n",i,F.pass_intervals[i]); } std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size();++i){ printf("i %d update_interval %d\n",i, update_intervals[i]); } for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf("-- interval %d\n",i); for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) { if (0<=jused-F.Analysis) { update_plan_from_one_obs(jused,Secret,M,P,pp,F,A); } else printf("\n no update\n"); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else } printf("-- redistribute %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- improve %d\n",i); improve(M,P,pp,F,A,starter); printf("-- improve again %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- diagnose %d\n",i); if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF printf("-- Checking SS/SF\n"); List SS_hist=initList(11,0); List SF_hist=initList(41,0); for(int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[j][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } SS_hist[count_SS]++; SF_hist[count_SF]++; } } printf(" SS distribution \n"); for(int i=0;i<10;i++)printf("%8d",SS_hist[i]); printf("\n %8d \n",SS_hist[10]); printf(" SF distribution \n"); for(int i=0;i<10;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=10;i<20;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=20;i<30;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=30;i<40;i++)printf("%8d",SF_hist[i]); printf("\n %8d \n",SF_hist[40]); // Results ------------------------------------------------------- //special for clustering group 6/28/16 //for each tile how many fibers free? how many to each type of target? std::vector<int> free(F.NUsedplate,0); for (int jused=0;jused<F.NUsedplate;jused++){ int j=A.suborder[jused]; int this_tile=0; for (int k=0;k<F.Nfiber;++k){ if (A.TF[j][k]==-1){ this_tile+=1; } } free[jused]=this_tile; } FILE * FFREE; FFREE = fopen("free_fibers.txt","w"); int nrows=F.NUsedplate/20 +1; for (int i=0;i<nrows;++i){ for(int j=0;j<20;++j){ fprintf(FFREE," %d ",free[20*i+j]); } } for (int i=nrows*20;i<F.NUsedplate;i++){ fprintf(FFREE," %d ",free[i]); } std::vector<int> tot_free(F.NUsedplate,0); tot_free[0]=free[0]; for (int i=1;i<F.NUsedplate;++i){ tot_free[i]=tot_free[i-1]+free[i]; } for (int i=0;i<nrows;++i){ for(int j=0;j<20;++j){ fprintf(FFREE," %d ",tot_free[20*i+j]); } } for (int i=nrows*20;i<F.NUsedplate;i++){ fprintf(FFREE," %d ",tot_free[i]); } if (F.PrintAscii){ for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A); } } if (F.PrintFits) { for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu } } display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>print number of free fibers at each tile<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d\n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors\n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){//fiber and therefore plate is used A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used //and otherwise the position of plate j in list of used plates inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); if(F.diagnose)diagnostic(M,Secret,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++){ printf(" i=%d interval %d \n",i,F.pass_intervals[i]); } std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size();++i){ printf("i %d update_interval %d\n",i, update_intervals[i]); } for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf("-- interval %d\n",i); for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) { if (0<=jused-F.Analysis) { update_plan_from_one_obs(jused,Secret,M,P,pp,F,A); } else printf("\n no update\n"); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else } printf("-- redistribute %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- improve %d\n",i); improve(M,P,pp,F,A,starter); printf("-- improve again %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- diagnose %d\n",i); if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF printf("-- Checking SS/SF\n"); List SS_hist=initList(11,0); List SF_hist=initList(41,0); for(int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[j][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } SS_hist[count_SS]++; SF_hist[count_SF]++; } } printf(" SS distribution \n"); for(int i=0;i<10;i++)printf("%8d",SS_hist[i]); printf("\n %8d \n",SS_hist[10]); printf(" SF distribution \n"); for(int i=0;i<10;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=10;i<20;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=20;i<30;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=30;i<40;i++)printf("%8d",SF_hist[i]); printf("\n %8d \n",SF_hist[40]); // Results ------------------------------------------------------- //special for clustering group 6/28/16 //for each tile how many fibers free? how many to each type of target? std::vector<int> free(F.NUsedplate,0); for (int jused=0;jused<F.NUsedplate;jused++){ int j=A.suborder[jused]; int this_tile=0; for (int k=0;k<F.Nfiber;++k){ if (A.TF[j][k]==-1){ this_tile+=1; } } free[jused]=this_tile; } FILE * FFREE; FFREE = fopen("free_fibers.txt","w"); int nrows=F.NUsedplate/20 +1; for (int i=0;i<nrows;++i){ for(int j=0;j<20;++j){ fprintf(FFREE," %d ",free[20*i+j]); } fprintf(" \n"); } for (int i=nrows*20;i<F.NUsedplate;i++){ fprintf(FFREE," %d ",free[i]); } fprintf(" \n"); std::vector<int> tot_free(F.NUsedplate,0); tot_free[0]=free[0]; for (int i=1;i<F.NUsedplate;++i){ tot_free[i]=tot_free[i-1]+free[i]; } for (int i=0;i<nrows;++i){ for(int j=0;j<20;++j){ fprintf(FFREE," %d ",tot_free[20*i+j]); } fprintf(" \n"); } for (int i=nrows*20;i<F.NUsedplate;i++){ fprintf(FFREE," %d ",tot_free[i]); } fprintf(" \n"); if (F.PrintAscii){ for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A); } } if (F.PrintFits) { for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu } } display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d\n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors\n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //count number of galaxies in first pass and number not in first pass int inside=0; int outside=0; for(int g=0;g<F.Ntarg;++g){ Plist v=M[g].av_tfs; for(int i=0);i<v.size();++i){ if(v[i].f==0){ ++outside; break; } ++inside; } } printf ("inside = %d outisde = %d\n",inside,outside); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){//fiber and therefore plate is used A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used //and otherwise the position of plate j in list of used plates inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); if(F.diagnose)diagnostic(M,Secret,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++){ printf(" i=%d interval %d \n",i,F.pass_intervals[i]); } std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size();++i){ printf("i %d update_interval %d\n",i, update_intervals[i]); } for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf("-- interval %d\n",i); for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) { if (0<=jused-F.Analysis) { update_plan_from_one_obs(jused,Secret,M,P,pp,F,A); } else printf("\n no update\n"); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else } printf("-- redistribute %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- improve %d\n",i); improve(M,P,pp,F,A,starter); printf("-- improve again %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- diagnose %d\n",i); if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF printf("-- Checking SS/SF\n"); List SS_hist=initList(11,0); List SF_hist=initList(41,0); for(int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[j][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } SS_hist[count_SS]++; SF_hist[count_SF]++; } } printf(" SS distribution \n"); for(int i=0;i<10;i++)printf("%8d",SS_hist[i]); printf("\n %8d \n",SS_hist[10]); printf(" SF distribution \n"); for(int i=0;i<10;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=10;i<20;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=20;i<30;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=30;i<40;i++)printf("%8d",SF_hist[i]); printf("\n %8d \n",SF_hist[40]); // Results ------------------------------------------------------- if (F.PrintAscii){ for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A); } } if (F.PrintFits) { for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu } } display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>count galaxies in first pass<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d\n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors\n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //count number of galaxies in first pass and number not in first pass int inside=0; int outside=0; for(int g=0;g<F.Ntarg;++g){ Plist v=M[g].av_tfs; for(int i=0;i<v.size();++i){ if(v[i].f==0){ ++outside; break; } ++inside; } } printf ("inside = %d outisde = %d\n",inside,outside); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){//fiber and therefore plate is used A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used //and otherwise the position of plate j in list of used plates inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); if(F.diagnose)diagnostic(M,Secret,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++){ printf(" i=%d interval %d \n",i,F.pass_intervals[i]); } std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size();++i){ printf("i %d update_interval %d\n",i, update_intervals[i]); } for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf("-- interval %d\n",i); for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) { if (0<=jused-F.Analysis) { update_plan_from_one_obs(jused,Secret,M,P,pp,F,A); } else printf("\n no update\n"); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else } printf("-- redistribute %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- improve %d\n",i); improve(M,P,pp,F,A,starter); printf("-- improve again %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- diagnose %d\n",i); if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF printf("-- Checking SS/SF\n"); List SS_hist=initList(11,0); List SF_hist=initList(41,0); for(int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[j][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } SS_hist[count_SS]++; SF_hist[count_SF]++; } } printf(" SS distribution \n"); for(int i=0;i<10;i++)printf("%8d",SS_hist[i]); printf("\n %8d \n",SS_hist[10]); printf(" SF distribution \n"); for(int i=0;i<10;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=10;i<20;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=20;i<30;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=30;i<40;i++)printf("%8d",SF_hist[i]); printf("\n %8d \n",SF_hist[40]); // Results ------------------------------------------------------- if (F.PrintAscii){ for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A); } } if (F.PrintFits) { for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu } } display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <sys/ioctl.h> #include <termios.h> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "test/util/capability_util.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/pty_util.h" namespace gvisor { namespace testing { // These tests should be run as root. namespace { TEST(JobControlRootTest, StealTTY) { SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN))); // Make this a session leader, which also drops the controlling terminal. // In the gVisor test environment, this test will be run as the session // leader already (as the sentry init process). if (!IsRunningOnGvisor()) { ASSERT_THAT(setsid(), SyscallSucceeds()); } FileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open("/dev/ptmx", O_RDWR | O_NONBLOCK)); FileDescriptor slave = ASSERT_NO_ERRNO_AND_VALUE(OpenSlave(master)); // Make slave the controlling terminal. ASSERT_THAT(ioctl(slave.get(), TIOCSCTTY, 0), SyscallSucceeds()); // Fork, join a new session, and try to steal the parent's controlling // terminal, which should succeed when we have CAP_SYS_ADMIN and pass an arg // of 1. pid_t child = fork(); if (!child) { ASSERT_THAT(setsid(), SyscallSucceeds()); // We shouldn't be able to steal the terminal with the wrong arg value. TEST_PCHECK(ioctl(slave.get(), TIOCSCTTY, 0)); // We should be able to steal it here. TEST_PCHECK(!ioctl(slave.get(), TIOCSCTTY, 1)); _exit(0); } int wstatus; ASSERT_THAT(waitpid(child, &wstatus, 0), SyscallSucceedsWithValue(child)); ASSERT_EQ(wstatus, 0); } } // namespace } // namespace testing } // namespace gvisor <commit_msg>Remove ASSERT from fork child<commit_after>// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <sys/ioctl.h> #include <termios.h> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "test/util/capability_util.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/pty_util.h" namespace gvisor { namespace testing { // These tests should be run as root. namespace { TEST(JobControlRootTest, StealTTY) { SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN))); // Make this a session leader, which also drops the controlling terminal. // In the gVisor test environment, this test will be run as the session // leader already (as the sentry init process). if (!IsRunningOnGvisor()) { ASSERT_THAT(setsid(), SyscallSucceeds()); } FileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open("/dev/ptmx", O_RDWR | O_NONBLOCK)); FileDescriptor slave = ASSERT_NO_ERRNO_AND_VALUE(OpenSlave(master)); // Make slave the controlling terminal. ASSERT_THAT(ioctl(slave.get(), TIOCSCTTY, 0), SyscallSucceeds()); // Fork, join a new session, and try to steal the parent's controlling // terminal, which should succeed when we have CAP_SYS_ADMIN and pass an arg // of 1. pid_t child = fork(); if (!child) { TEST_PCHECK(setsid() >= 0); // We shouldn't be able to steal the terminal with the wrong arg value. TEST_PCHECK(ioctl(slave.get(), TIOCSCTTY, 0)); // We should be able to steal it here. TEST_PCHECK(!ioctl(slave.get(), TIOCSCTTY, 1)); _exit(0); } int wstatus; ASSERT_THAT(waitpid(child, &wstatus, 0), SyscallSucceedsWithValue(child)); ASSERT_EQ(wstatus, 0); } } // namespace } // namespace testing } // namespace gvisor <|endoftext|>
<commit_before>#line 2 "togo/hash.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file hash.hpp @brief Hashing utilities. @ingroup hash */ #pragma once #include <togo/config.hpp> #include <togo/debug_constraints.hpp> #include <togo/types.hpp> #include <togo/string.hpp> #include <am/hash/fnv.hpp> namespace togo { namespace hash { /** @addtogroup hash @{ */ // TODO: Build constexpr version of MurmurHash2 (both lengths) and // use it instead of FNV-1a namespace { static constexpr am::hash::HashLength const hash32_length = am::hash::HashLength::HL32, hash64_length = am::hash::HashLength::HL64; } // anonymous namespace /** @cond INTERNAL */ TOGO_CONSTRAIN_SAME(hash32, am::detail::hash::fnv_hash_type<hash32_length>); TOGO_CONSTRAIN_SAME(hash64, am::detail::hash::fnv_hash_type<hash64_length>); /** @endcond */ /// 32-bit hash identity (hash of nothing). static constexpr hash32 const IDENTITY32{0}; /// 64-bit hash identity (hash of nothing). static constexpr hash64 const IDENTITY64{0}; /** Calculate 32-bit hash. */ inline hash32 calc32( char const* const data, unsigned const size ) { return size != 0 ? am::hash::fnv1a<hash32_length>(data, size) : hash::IDENTITY32 ; } /** Calculate 32-bit hash from string reference. */ inline hash32 calc32(StringRef const& ref) { return hash::calc32(ref.data, ref.size); } /** Calculate 64-bit hash. */ inline hash64 calc64( char const* const data, unsigned const size ) { return size != 0 ? am::hash::fnv1a<hash64_length>(data, size) : hash::IDENTITY64 ; } /** Calculate 64-bit hash from string reference. */ inline hash64 calc64(StringRef const& ref) { return hash::calc64(ref.data, ref.size); } /** @} */ // end of doc-group hash } // namespace hash /** 32-bit hash literal. */ inline constexpr hash32 operator"" _hash32( char const* const data, std::size_t const size ) { return size != 0 ? am::hash::fnv1a_c<hash::hash32_length>(data, size) : hash::IDENTITY32 ; } /** 64-bit hash literal. */ inline constexpr hash64 operator"" _hash64( char const* const data, std::size_t const size ) { return size != 0 ? am::hash::fnv1a_c<hash::hash64_length>(data, size) : hash::IDENTITY64 ; } } // namespace togo <commit_msg>hash: added calc_generic<H>(), rebased calc32() & calc64(); tidy.<commit_after>#line 2 "togo/hash.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file hash.hpp @brief Hashing utilities. @ingroup hash */ #pragma once #include <togo/config.hpp> #include <togo/debug_constraints.hpp> #include <togo/types.hpp> #include <togo/string.hpp> #include <am/hash/fnv.hpp> namespace togo { namespace hash { /** @addtogroup hash @{ */ // TODO: Build constexpr version of MurmurHash2 (both lengths) and // use it instead of FNV-1a /// 32-bit hash identity (hash of nothing). static constexpr hash32 const IDENTITY32{0}; /// 64-bit hash identity (hash of nothing). static constexpr hash64 const IDENTITY64{0}; namespace { static constexpr am::hash::HashLength const hash32_length = am::hash::HashLength::HL32, hash64_length = am::hash::HashLength::HL64; template<class H> struct hash_type_length; template<> struct hash_type_length<hash32> { static constexpr auto const value = hash32_length; }; template<> struct hash_type_length<hash64> { static constexpr auto const value = hash64_length; }; template<class H> struct hash_identity; template<> struct hash_identity<hash32> { static constexpr auto const value = hash::IDENTITY32; }; template<> struct hash_identity<hash64> { static constexpr auto const value = hash::IDENTITY64; }; } // anonymous namespace /** @cond INTERNAL */ TOGO_CONSTRAIN_SAME(hash32, am::detail::hash::fnv_hash_type<hash32_length>); TOGO_CONSTRAIN_SAME(hash64, am::detail::hash::fnv_hash_type<hash64_length>); /** @endcond */ /** Calculate H-bit hash. */ template<class H> inline H calc_generic( char const* const data, unsigned const size ) { return size != 0 ? am::hash::fnv1a<hash_type_length<H>::value>(data, size) : hash_identity<H>::value ; } /** Calculate H-bit hash from string reference. */ template<class H> inline H calc_generic(StringRef const& ref) { return hash::calc_generic<H>(ref.data, ref.size); } /** Calculate 32-bit hash. */ inline hash32 calc32( char const* const data, unsigned const size ) { return hash::calc_generic<hash32>(data, size); } /** Calculate 32-bit hash from string reference. */ inline hash32 calc32(StringRef const& ref) { return hash::calc_generic<hash32>(ref.data, ref.size); } /** Calculate 64-bit hash. */ inline hash64 calc64( char const* const data, unsigned const size ) { return hash::calc_generic<hash64>(data, size); } /** Calculate 64-bit hash from string reference. */ inline hash64 calc64(StringRef const& ref) { return hash::calc_generic<hash64>(ref.data, ref.size); } /** @} */ // end of doc-group hash } // namespace hash /** 32-bit hash literal. */ inline constexpr hash32 operator"" _hash32( char const* const data, std::size_t const size ) { return size != 0 ? am::hash::fnv1a_c<hash::hash32_length>(data, size) : hash::IDENTITY32 ; } /** 64-bit hash literal. */ inline constexpr hash64 operator"" _hash64( char const* const data, std::size_t const size ) { return size != 0 ? am::hash::fnv1a_c<hash::hash64_length>(data, size) : hash::IDENTITY64 ; } } // namespace togo <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <signal.h> #include "occa/base.hpp" #include "occa/tools/io.hpp" #include "occa/tools/env.hpp" #include "occa/tools/sys.hpp" #include "occa/parser/tools.hpp" namespace occa { namespace env { std::string HOME, PWD; std::string PATH, LD_LIBRARY_PATH; std::string OCCA_DIR, OCCA_CACHE_DIR; size_t OCCA_MEM_BYTE_ALIGN; strVector OCCA_PATH; properties& baseSettings() { static properties settings_; return settings_; } std::string var(const std::string &varName) { char *c_varName = getenv(varName.c_str()); if (c_varName != NULL) { return std::string(c_varName); } return ""; } void signalExit(int sig) { // io::clearLocks(); ::exit(sig); } envInitializer_t::envInitializer_t() : isInitialized(false) { if (isInitialized) { return; } // Initialize file locks first to place it last in the destructor list io::fileLocks(); initSettings(); initSignalHandling(); initEnvironment(); registerFileOpeners(); isInitialized = true; } void envInitializer_t::initSettings() { properties &settings_ = baseSettings(); settings_["version"] = OCCA_VERSION_STR; settings_["okl-version"] = OKL_VERSION_STR; const bool isVerbose = env::get("OCCA_VERBOSE", false); if (isVerbose) { settings_["device/verbose"] = true; settings_["kernel/verbose"] = true; settings_["memory/verbose"] = true; } } void envInitializer_t::initSignalHandling() { // Signal handling ::signal(SIGTERM, env::signalExit); ::signal(SIGINT , env::signalExit); ::signal(SIGABRT, env::signalExit); #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) ::signal(SIGKILL, env::signalExit); ::signal(SIGQUIT, env::signalExit); ::signal(SIGUSR1, env::signalExit); ::signal(SIGUSR2, env::signalExit); #endif } void envInitializer_t::initEnvironment() { // Standard environment variables #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) HOME = env::var("HOME"); PWD = env::var("PWD"); PATH = env::var("PATH"); LD_LIBRARY_PATH = env::var("LD_LIBRARY_PATH"); io::endWithSlash(HOME); io::endWithSlash(PWD); io::endWithSlash(PATH); #endif // OCCA environment variables OCCA_DIR = env::var("OCCA_DIR"); if (OCCA_DIR.size() == 0) { OCCA_DIR = io::filename(io::dirname(__FILE__) + "/../.."); } initCachePath(); initIncludePath(); io::endWithSlash(OCCA_DIR); io::endWithSlash(OCCA_CACHE_DIR); OCCA_MEM_BYTE_ALIGN = OCCA_DEFAULT_MEM_BYTE_ALIGN; if (env::var("OCCA_MEM_BYTE_ALIGN").size() > 0) { const size_t align = (size_t) std::atoi(env::var("OCCA_MEM_BYTE_ALIGN").c_str()); if ((align != 0) && ((align & (~align + 1)) == align)) { OCCA_MEM_BYTE_ALIGN = align; } else { std::cout << "Environment variable [OCCA_MEM_BYTE_ALIGN (" << align << ")] is not a power of two, defaulting to " << OCCA_DEFAULT_MEM_BYTE_ALIGN << '\n'; } } } void envInitializer_t::initCachePath() { env::OCCA_CACHE_DIR = env::var("OCCA_CACHE_DIR"); if (env::OCCA_CACHE_DIR.size() == 0) { std::stringstream ss; #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) ss << env::var("HOME") << "/.occa"; #else ss << env::var("USERPROFILE") << "/AppData/Local/OCCA"; # if OCCA_64_BIT ss << "_amd64"; // use different dir's fro 32 and 64 bit # else ss << "_x86"; // use different dir's fro 32 and 64 bit # endif #endif env::OCCA_CACHE_DIR = ss.str(); } const int chars = env::OCCA_CACHE_DIR.size(); OCCA_ERROR("Path to the OCCA caching directory is not set properly, " "unset OCCA_CACHE_DIR to use default directory [~/.occa]", 0 < chars); env::OCCA_CACHE_DIR = io::filename(env::OCCA_CACHE_DIR); if (!sys::dirExists(env::OCCA_CACHE_DIR)) { sys::mkpath(env::OCCA_CACHE_DIR); } } void envInitializer_t::initIncludePath() { strVector &oipVec = env::OCCA_PATH; oipVec.clear(); std::string oip = env::var("OCCA_PATH"); const char *cStart = oip.c_str(); const char *cEnd; while(cStart[0] != '\0') { cEnd = cStart; #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) skipTo(cEnd, ':'); #else skipTo(cEnd, ';'); #endif if (0 < (cEnd - cStart)) { std::string newPath(cStart, cEnd - cStart); newPath = io::filename(newPath); io::endWithSlash(newPath); oipVec.push_back(newPath); } cStart = (cEnd + (cEnd[0] != '\0')); } } void envInitializer_t::registerFileOpeners() { io::fileOpener::add(new io::occaFileOpener()); io::fileOpener::add(new io::headerFileOpener()); io::fileOpener::add(new io::systemHeaderFileOpener()); } void envInitializer_t::cleanFileOpeners() { std::vector<io::fileOpener*> &openers = io::fileOpener::getOpeners(); const int count = (int) openers.size(); for (int i = 0; i < count; ++i) { delete openers[i]; } openers.clear(); } envInitializer_t::~envInitializer_t() { if (isInitialized) { cleanFileOpeners(); } } envInitializer_t envInitializer; } } <commit_msg>[Sys] Remove SIGKILL from exit handler (#100)<commit_after>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <signal.h> #include "occa/base.hpp" #include "occa/tools/io.hpp" #include "occa/tools/env.hpp" #include "occa/tools/sys.hpp" #include "occa/parser/tools.hpp" namespace occa { namespace env { std::string HOME, PWD; std::string PATH, LD_LIBRARY_PATH; std::string OCCA_DIR, OCCA_CACHE_DIR; size_t OCCA_MEM_BYTE_ALIGN; strVector OCCA_PATH; properties& baseSettings() { static properties settings_; return settings_; } std::string var(const std::string &varName) { char *c_varName = getenv(varName.c_str()); if (c_varName != NULL) { return std::string(c_varName); } return ""; } void signalExit(int sig) { // io::clearLocks(); ::exit(sig); } envInitializer_t::envInitializer_t() : isInitialized(false) { if (isInitialized) { return; } // Initialize file locks first to place it last in the destructor list io::fileLocks(); initSettings(); initSignalHandling(); initEnvironment(); registerFileOpeners(); isInitialized = true; } void envInitializer_t::initSettings() { properties &settings_ = baseSettings(); settings_["version"] = OCCA_VERSION_STR; settings_["okl-version"] = OKL_VERSION_STR; const bool isVerbose = env::get("OCCA_VERBOSE", false); if (isVerbose) { settings_["device/verbose"] = true; settings_["kernel/verbose"] = true; settings_["memory/verbose"] = true; } } void envInitializer_t::initSignalHandling() { // Signal handling ::signal(SIGTERM, env::signalExit); ::signal(SIGINT , env::signalExit); ::signal(SIGABRT, env::signalExit); #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) ::signal(SIGQUIT, env::signalExit); ::signal(SIGUSR1, env::signalExit); ::signal(SIGUSR2, env::signalExit); #endif } void envInitializer_t::initEnvironment() { // Standard environment variables #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) HOME = env::var("HOME"); PWD = env::var("PWD"); PATH = env::var("PATH"); LD_LIBRARY_PATH = env::var("LD_LIBRARY_PATH"); io::endWithSlash(HOME); io::endWithSlash(PWD); io::endWithSlash(PATH); #endif // OCCA environment variables OCCA_DIR = env::var("OCCA_DIR"); if (OCCA_DIR.size() == 0) { OCCA_DIR = io::filename(io::dirname(__FILE__) + "/../.."); } initCachePath(); initIncludePath(); io::endWithSlash(OCCA_DIR); io::endWithSlash(OCCA_CACHE_DIR); OCCA_MEM_BYTE_ALIGN = OCCA_DEFAULT_MEM_BYTE_ALIGN; if (env::var("OCCA_MEM_BYTE_ALIGN").size() > 0) { const size_t align = (size_t) std::atoi(env::var("OCCA_MEM_BYTE_ALIGN").c_str()); if ((align != 0) && ((align & (~align + 1)) == align)) { OCCA_MEM_BYTE_ALIGN = align; } else { std::cout << "Environment variable [OCCA_MEM_BYTE_ALIGN (" << align << ")] is not a power of two, defaulting to " << OCCA_DEFAULT_MEM_BYTE_ALIGN << '\n'; } } } void envInitializer_t::initCachePath() { env::OCCA_CACHE_DIR = env::var("OCCA_CACHE_DIR"); if (env::OCCA_CACHE_DIR.size() == 0) { std::stringstream ss; #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) ss << env::var("HOME") << "/.occa"; #else ss << env::var("USERPROFILE") << "/AppData/Local/OCCA"; # if OCCA_64_BIT ss << "_amd64"; // use different dir's fro 32 and 64 bit # else ss << "_x86"; // use different dir's fro 32 and 64 bit # endif #endif env::OCCA_CACHE_DIR = ss.str(); } const int chars = env::OCCA_CACHE_DIR.size(); OCCA_ERROR("Path to the OCCA caching directory is not set properly, " "unset OCCA_CACHE_DIR to use default directory [~/.occa]", 0 < chars); env::OCCA_CACHE_DIR = io::filename(env::OCCA_CACHE_DIR); if (!sys::dirExists(env::OCCA_CACHE_DIR)) { sys::mkpath(env::OCCA_CACHE_DIR); } } void envInitializer_t::initIncludePath() { strVector &oipVec = env::OCCA_PATH; oipVec.clear(); std::string oip = env::var("OCCA_PATH"); const char *cStart = oip.c_str(); const char *cEnd; while(cStart[0] != '\0') { cEnd = cStart; #if (OCCA_OS & (OCCA_LINUX_OS | OCCA_OSX_OS)) skipTo(cEnd, ':'); #else skipTo(cEnd, ';'); #endif if (0 < (cEnd - cStart)) { std::string newPath(cStart, cEnd - cStart); newPath = io::filename(newPath); io::endWithSlash(newPath); oipVec.push_back(newPath); } cStart = (cEnd + (cEnd[0] != '\0')); } } void envInitializer_t::registerFileOpeners() { io::fileOpener::add(new io::occaFileOpener()); io::fileOpener::add(new io::headerFileOpener()); io::fileOpener::add(new io::systemHeaderFileOpener()); } void envInitializer_t::cleanFileOpeners() { std::vector<io::fileOpener*> &openers = io::fileOpener::getOpeners(); const int count = (int) openers.size(); for (int i = 0; i < count; ++i) { delete openers[i]; } openers.clear(); } envInitializer_t::~envInitializer_t() { if (isInitialized) { cleanFileOpeners(); } } envInitializer_t envInitializer; } } <|endoftext|>
<commit_before>#include "test_helpers.hxx" using namespace PGSTD; using namespace pqxx; namespace { binarystring make_binarystring(transaction_base &T, string content) { return binarystring(T.exec("SELECT " + T.quote_raw(content))[0][0]); } void test_binarystring(transaction_base &T) { binarystring b = make_binarystring(T, ""); PQXX_CHECK(b.empty(), "Empty binarystring is not empty."); PQXX_CHECK_EQUAL(b.str(), "", "Empty binarystring doesn't work."); PQXX_CHECK_EQUAL(b.size(), 0u, "Empty binarystring has nonzero size."); PQXX_CHECK_EQUAL(b.length(), 0u, "Length/size mismatch."); PQXX_CHECK(b.begin() == b.end(), "Empty binarystring iterates."); PQXX_CHECK(b.rbegin() == b.rend(), "Empty binarystring reverse-iterates."); PQXX_CHECK_THROWS(b.at(0), out_of_range, "Empty binarystring accepts at()."); b = make_binarystring(T, "z"); PQXX_CHECK_EQUAL(b.str(), "z", "Basic nonempty binarystring is broken."); PQXX_CHECK(!b.empty(), "Nonempty binarystring is empty."); PQXX_CHECK_EQUAL(b.size(), 1u, "Bad binarystring size."); PQXX_CHECK_EQUAL(b.length(), 1u, "Length/size mismatch."); PQXX_CHECK(b.begin() != b.end(), "Nonempty binarystring does not iterate."); PQXX_CHECK( b.rbegin() != b.rend(), "Nonempty binarystring does not reverse-iterate."); PQXX_CHECK(b.begin() + 1 == b.end(), "Bad iteration."); PQXX_CHECK(b.rbegin() + 1 == b.rend(), "Bad reverse iteration."); PQXX_CHECK(b.front() == 'z', "Unexpected front()."); PQXX_CHECK(b.back() == 'z', "Unexpected back()."); PQXX_CHECK(b.at(0) == 'z', "Unexpected data at index 0."); PQXX_CHECK_THROWS(b.at(1), out_of_range, "Failed to catch range error."); const string simple("ab"); b = make_binarystring(T, simple); PQXX_CHECK_EQUAL( b.str(), simple, "Binary (un)escaping went wrong somewhere."); PQXX_CHECK_EQUAL(b.size(), simple.size(), "Escaping confuses length."); const string simple_escaped(T.esc_raw(simple)); for (string::size_type i=0; i<simple_escaped.size(); ++i) { const unsigned char uc = static_cast<unsigned char>(simple_escaped[i]); PQXX_CHECK(uc <= 127, "Non-ASCII byte in escaped string."); } PQXX_CHECK_EQUAL( T.quote_raw( reinterpret_cast<const unsigned char *>(simple.c_str()), simple.size()), T.quote(b), "quote_raw is broken"); PQXX_CHECK_EQUAL( T.quote(b), T.quote_raw(simple), "Binary quoting is broken."); PQXX_CHECK_EQUAL( binarystring(T.exec("SELECT " + T.quote(b))[0][0]).str(), simple, "Binary string is not idempotent."); const string bytes("\x01\x23\x23\xa1\x2b\x0c\xff"); b = make_binarystring(T, bytes); PQXX_CHECK_EQUAL( b.str(), bytes, "Binary data breaks (un)escaping."); const string nully("a\0b", 3); b = make_binarystring(T, nully); PQXX_CHECK_EQUAL(b.str(), nully, "Nul byte broke binary (un)escaping."); PQXX_CHECK_EQUAL(b.size(), 3u, "Nul byte broke binarystring size."); b = make_binarystring(T, "foo"); PQXX_CHECK_EQUAL(string(b.get(), 3), "foo", "get() appears broken."); binarystring b1 = make_binarystring(T, "1"), b2 = make_binarystring(T, "2"); PQXX_CHECK_NOT_EQUAL(b1.get(), b2.get(), "Madness rules."); PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "Logic has no more meaning."); b1.swap(b2); PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "swap() equalized binarystrings."); PQXX_CHECK_NOT_EQUAL(b1.str(), "1", "swap() did not happen."); PQXX_CHECK_EQUAL(b1.str(), "2", "swap() is broken."); PQXX_CHECK_EQUAL(b2.str(), "1", "swap() went insane."); b = make_binarystring(T, "bar"); b.swap(b); PQXX_CHECK_EQUAL(b.str(), "bar", "Self-swap confuses binarystring."); b = make_binarystring(T, "\\x"); PQXX_CHECK_EQUAL(b.str(), "\\x", "Hex-escape header confused (un)escaping."); } } // namespace PQXX_REGISTER_TEST(test_binarystring) <commit_msg>Cosmetic.<commit_after>#include "test_helpers.hxx" using namespace PGSTD; using namespace pqxx; namespace { binarystring make_binarystring(transaction_base &T, string content) { return binarystring(T.exec("SELECT " + T.quote_raw(content))[0][0]); } void test_binarystring(transaction_base &T) { binarystring b = make_binarystring(T, ""); PQXX_CHECK(b.empty(), "Empty binarystring is not empty."); PQXX_CHECK_EQUAL(b.str(), "", "Empty binarystring doesn't work."); PQXX_CHECK_EQUAL(b.size(), 0u, "Empty binarystring has nonzero size."); PQXX_CHECK_EQUAL(b.length(), 0u, "Length/size mismatch."); PQXX_CHECK(b.begin() == b.end(), "Empty binarystring iterates."); PQXX_CHECK(b.rbegin() == b.rend(), "Empty binarystring reverse-iterates."); PQXX_CHECK_THROWS(b.at(0), out_of_range, "Empty binarystring accepts at()."); b = make_binarystring(T, "z"); PQXX_CHECK_EQUAL(b.str(), "z", "Basic nonempty binarystring is broken."); PQXX_CHECK(!b.empty(), "Nonempty binarystring is empty."); PQXX_CHECK_EQUAL(b.size(), 1u, "Bad binarystring size."); PQXX_CHECK_EQUAL(b.length(), 1u, "Length/size mismatch."); PQXX_CHECK(b.begin() != b.end(), "Nonempty binarystring does not iterate."); PQXX_CHECK( b.rbegin() != b.rend(), "Nonempty binarystring does not reverse-iterate."); PQXX_CHECK(b.begin() + 1 == b.end(), "Bad iteration."); PQXX_CHECK(b.rbegin() + 1 == b.rend(), "Bad reverse iteration."); PQXX_CHECK(b.front() == 'z', "Unexpected front()."); PQXX_CHECK(b.back() == 'z', "Unexpected back()."); PQXX_CHECK(b.at(0) == 'z', "Unexpected data at index 0."); PQXX_CHECK_THROWS(b.at(1), out_of_range, "Failed to catch range error."); const string simple("ab"); b = make_binarystring(T, simple); PQXX_CHECK_EQUAL( b.str(), simple, "Binary (un)escaping went wrong somewhere."); PQXX_CHECK_EQUAL(b.size(), simple.size(), "Escaping confuses length."); const string simple_escaped(T.esc_raw(simple)); for (string::size_type i=0; i<simple_escaped.size(); ++i) { const unsigned char uc = static_cast<unsigned char>(simple_escaped[i]); PQXX_CHECK(uc <= 127, "Non-ASCII byte in escaped string."); } PQXX_CHECK_EQUAL( T.quote_raw( reinterpret_cast<const unsigned char *>(simple.c_str()), simple.size()), T.quote(b), "quote_raw is broken"); PQXX_CHECK_EQUAL( T.quote(b), T.quote_raw(simple), "Binary quoting is broken."); PQXX_CHECK_EQUAL( binarystring(T.exec("SELECT " + T.quote(b))[0][0]).str(), simple, "Binary string is not idempotent."); const string bytes("\x01\x23\x23\xa1\x2b\x0c\xff"); b = make_binarystring(T, bytes); PQXX_CHECK_EQUAL(b.str(), bytes, "Binary data breaks (un)escaping."); const string nully("a\0b", 3); b = make_binarystring(T, nully); PQXX_CHECK_EQUAL(b.str(), nully, "Nul byte broke binary (un)escaping."); PQXX_CHECK_EQUAL(b.size(), 3u, "Nul byte broke binarystring size."); b = make_binarystring(T, "foo"); PQXX_CHECK_EQUAL(string(b.get(), 3), "foo", "get() appears broken."); binarystring b1 = make_binarystring(T, "1"), b2 = make_binarystring(T, "2"); PQXX_CHECK_NOT_EQUAL(b1.get(), b2.get(), "Madness rules."); PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "Logic has no more meaning."); b1.swap(b2); PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "swap() equalized binarystrings."); PQXX_CHECK_NOT_EQUAL(b1.str(), "1", "swap() did not happen."); PQXX_CHECK_EQUAL(b1.str(), "2", "swap() is broken."); PQXX_CHECK_EQUAL(b2.str(), "1", "swap() went insane."); b = make_binarystring(T, "bar"); b.swap(b); PQXX_CHECK_EQUAL(b.str(), "bar", "Self-swap confuses binarystring."); b = make_binarystring(T, "\\x"); PQXX_CHECK_EQUAL(b.str(), "\\x", "Hex-escape header confused (un)escaping."); } } // namespace PQXX_REGISTER_TEST(test_binarystring) <|endoftext|>
<commit_before>///===----------------------------------------------------------------------===// // // PelotonDB // // cache.h // // Identification: src/backend/common/cache.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cassert> #include "backend/common/cache.h" #include "backend/planner/abstract_plan.h" namespace peloton { template<class Key, class Value> Cache<Key, Value>::Cache(size_type capacity) : capacity_(capacity) { } template<class Key, class Value> typename Cache<Key, Value>::iterator Cache<Key, Value>::find(const Key& key) { cache_lock_.ReadLock(); auto map_it = map_.find(key); if (map_it != map_.end()) { /* put this at the front of the list */ list_.splice(list_.begin(), list_, map_it->second.second); *(map_it->second.second) = list_.front(); Cache<Key, Value>::iterator ret(map_it); cache_lock_.Unlock(); return ret; } else { cache_lock_.Unlock(); return this->end(); } } template<class Key, class Value> typename Cache<Key, Value>::iterator Cache<Key, Value>::insert( const Entry& entry) { cache_lock_.WriteLock(); assert(list_.size() == map_.size()); assert(list_.size() <= this->capacity_); auto cache_it = this->find(entry.first); if (cache_it == this->end()) { /* new key */ list_.push_front(entry.first); auto map_it = map_.emplace(entry.first, std::make_pair(entry.second, list_.begin())); assert(map_it.second); /* should not fail */ cache_it = iterator(map_it.first); while (map_.size() > this->capacity_) { auto deleted = list_.back(); auto count = this->map_.erase(deleted); assert(count == 1); } } else { /* update value associated with the key * Order has been updated in Cache.find() */ *cache_it = entry.second; } assert(list_.size() == map_.size()); assert(list_.size() <= capacity_); cache_lock_.Unlock(); return cache_it; } template<class Key, class Value> typename Cache<Key, Value>::size_type Cache<Key, Value>::size() const { assert(map_.size() == list_.size()); return map_.size(); } template class Cache<uint32_t, planner::AbstractPlan*>; } <commit_msg>fix lock in cache<commit_after>///===----------------------------------------------------------------------===// // // PelotonDB // // cache.h // // Identification: src/backend/common/cache.cpp // // Copyright (c) 2015, Carnegie Mellon Universitry Database Group // //===----------------------------------------------------------------------===// #include <cassert> #include "backend/common/cache.h" #include "backend/common/logger.h" #include "backend/planner/abstract_plan.h" namespace peloton { template<class Key, class Value> Cache<Key, Value>::Cache(size_type capacitry) : capacity_(capacitry) { } template<class Key, class Value> typename Cache<Key, Value>::iterator Cache<Key, Value>::find(const Key& key) { { cache_lock_.WriteLock(); auto map_itr = map_.find(key); auto cache_itr = end(); if (map_itr != map_.end()) { /* put this at the front of the list */ list_.splice(list_.begin(), list_, map_itr->second.second); *(map_itr->second.second) = list_.front(); cache_itr = iterator(map_itr); LOG_INFO("Found 1 record"); } else { LOG_INFO("Found 0 record"); } cache_lock_.Unlock(); return cache_itr; } } template<class Key, class Value> typename Cache<Key, Value>::iterator Cache<Key, Value>::insert( const Entry& entry) { { cache_lock_.WriteLock(); assert(list_.size() == map_.size()); assert(list_.size() <= this->capacity_); auto map_itr = map_.find(entry.first); auto cache_itr = iterator(map_itr); if (map_itr == map_.end()) { /* new key */ list_.push_front(entry.first); auto ret = map_.emplace(entry.first, std::make_pair(entry.second, list_.begin())); assert(ret.second); /* should not fail */ cache_itr = iterator(ret.first); LOG_INFO("Insert %d", entry.first); while (map_.size() > this->capacity_) { auto deleted = list_.back(); auto count = this->map_.erase(deleted); list_.erase(std::prev(list_.end())); LOG_INFO("Evicted %d", deleted); assert(count == 1); } } else { list_.splice(list_.begin(), list_, map_itr->second.second); map_itr->second = std::make_pair(entry.second, list_.begin()); LOG_INFO("Updated 1 record"); } assert(list_.size() == map_.size()); assert(list_.size() <= capacity_); cache_lock_.Unlock(); return cache_itr; } } template<class Key, class Value> typename Cache<Key, Value>::size_type Cache<Key, Value>::size() const { assert(map_.size() == list_.size()); return map_.size(); } template class Cache<uint32_t, planner::AbstractPlan*> ; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Bernhard Beschow <[email protected]> // #include <QtTest/QtTest> #include <QtCore/qmetatype.h> #include "MarbleModel.h" #include "PluginManager.h" #include "AbstractFloatItem.h" Q_DECLARE_METATYPE( const Marble::AbstractFloatItem * ) namespace Marble { class AbstractFloatItemTest : public QObject { Q_OBJECT public: AbstractFloatItemTest(); private slots: void newInstance_data(); void newInstance(); private: MarbleModel m_model; QList<const AbstractFloatItem *> m_factories; }; AbstractFloatItemTest::AbstractFloatItemTest() { foreach ( const RenderPlugin *plugin, m_model.pluginManager()->renderPlugins() ) { const AbstractFloatItem *const factory = qobject_cast<const AbstractFloatItem *>( plugin ); if ( !factory ) continue; m_factories << factory; } } void AbstractFloatItemTest::newInstance_data() { QTest::addColumn<const AbstractFloatItem *>( "factory" ); foreach ( const AbstractFloatItem *factory, m_factories ) { QTest::newRow( factory->nameId().toAscii() ) << factory; } } void AbstractFloatItemTest::newInstance() { QFETCH( const AbstractFloatItem *, factory ); RenderPlugin *const instance = factory->newInstance( &m_model ); QVERIFY( qobject_cast<AbstractFloatItem *>( instance ) != 0 ); delete instance; } } QTEST_MAIN( Marble::AbstractFloatItemTest ) #include "AbstractFloatItemTest.moc" <commit_msg>add test for default constructor<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Bernhard Beschow <[email protected]> // #include <QtTest/QtTest> #include <QtCore/qmetatype.h> #include "MarbleModel.h" #include "PluginManager.h" #include "AbstractFloatItem.h" Q_DECLARE_METATYPE( const Marble::AbstractFloatItem * ) using namespace Marble; class NullFloatItem : public AbstractFloatItem { public: NullFloatItem() : AbstractFloatItem( 0 ) {} NullFloatItem( const MarbleModel *model ) : AbstractFloatItem( model ) {} QString name() const { return "Null Float Item"; } QString nameId() const { return "null"; } QString version() const { return "0.0"; } QString description() const { return "A null float item just for testing."; } QIcon icon() const { return QIcon(); } QString copyrightYears() const { return "2013"; } QList<PluginAuthor> pluginAuthors() const { return QList<PluginAuthor>() << PluginAuthor( "Bernhard Beschow", "[email protected]" ); } void initialize() {} bool isInitialized() const { return true; } QStringList backendTypes() const { return QStringList() << "null"; } QString guiString() const { return "Null"; } RenderPlugin *newInstance( const MarbleModel * ) const { return 0; } }; class AbstractFloatItemTest : public QObject { Q_OBJECT public: AbstractFloatItemTest(); private slots: void defaultConstructor(); void newInstance_data(); void newInstance(); private: MarbleModel m_model; QList<const AbstractFloatItem *> m_factories; }; AbstractFloatItemTest::AbstractFloatItemTest() { foreach ( const RenderPlugin *plugin, m_model.pluginManager()->renderPlugins() ) { const AbstractFloatItem *const factory = qobject_cast<const AbstractFloatItem *>( plugin ); if ( !factory ) continue; m_factories << factory; } } void AbstractFloatItemTest::defaultConstructor() { NullFloatItem item; QCOMPARE( item.visible(), true ); QCOMPARE( item.positionLocked(), true ); } void AbstractFloatItemTest::newInstance_data() { QTest::addColumn<const AbstractFloatItem *>( "factory" ); foreach ( const AbstractFloatItem *factory, m_factories ) { QTest::newRow( factory->nameId().toAscii() ) << factory; } } void AbstractFloatItemTest::newInstance() { QFETCH( const AbstractFloatItem *, factory ); RenderPlugin *const instance = factory->newInstance( &m_model ); QVERIFY( qobject_cast<AbstractFloatItem *>( instance ) != 0 ); delete instance; } QTEST_MAIN( AbstractFloatItemTest ) #include "AbstractFloatItemTest.moc" <|endoftext|>
<commit_before>#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "scr_proto/DiffCommand.h" // Physical Parameters... What do to with these? float wheel_radius, axle_length // Global values for velocity storage float cmd_vx=0, cmd_vy=0, cmd_vz=0, cmd_wx=0, cmd_wy=0, cmd_wz=0; // Callback to attach to command velocity subscription void commandCallback(const geometry_msgs::Twist::ConstPtr& msg){ // Pull values from message cmd_vx = msg->linear->x; cmd_vy = msg->linear->y; cmd_vz = msg->linear->z; cmd_wx = msg->angular->x; cmd_wy = msg->angular->y; cmd_wz = msg->angular->z; } int main(int argc, char **argv){ // Initialize Node ros::init(argc, argv, "base_controller"); // Create Nodehandle ros::Nodehandle n; // Subscribe to Command Velocity topic ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel", 1000, commandCallback); ros::Publisher motor_pub = n.advertise<scr_proto::DiffCommand>("/motor_command", 1000); ros::Rate loop_rate(10); while(ros::ok()){ // Calculate Motor Commands given command velocity // Need Linear Alg or something to solve aX=b float a[2][2] = {{1.0 1.0}, {1.0/(axle_length/2.0), -1.0/(axle_length/20)}} float b[2][1] = {{cmd_vx}, {cmd_wz}} // Pass to linear Alg to solver or something? // Declare Message scr_proto::DiffCommand motor_com; // Populate Message // Publish Message motor_pub.publish(motor_com); // Handle loop rate ros::spinOnce(); loop_rate.sleep(); } } <commit_msg>Update base_controller_node.cpp<commit_after>#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "scr_proto/DiffCommand.h" #include <Eigen/Dense> // Physical Parameters... What do to with these? float wheel_radius, axle_length // Global values for velocity storage float cmd_vx=0, cmd_vy=0, cmd_vz=0, cmd_wx=0, cmd_wy=0, cmd_wz=0; // Callback to attach to command velocity subscription void commandCallback(const geometry_msgs::Twist::ConstPtr& msg){ // Pull values from message cmd_vx = msg->linear->x; cmd_vy = msg->linear->y; cmd_vz = msg->linear->z; cmd_wx = msg->angular->x; cmd_wy = msg->angular->y; cmd_wz = msg->angular->z; } int main(int argc, char **argv){ // Initialize Node ros::init(argc, argv, "base_controller"); // Create Nodehandle ros::Nodehandle n; // Subscribe to Command Velocity topic ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel", 1000, commandCallback); ros::Publisher motor_pub = n.advertise<scr_proto::DiffCommand>("/motor_command", 1000); ros::Rate loop_rate(10); while(ros::ok()){ // Calculate Motor Commands given command velocity // A matrix based on body parameters Matrix2f A; A << 1.0, 1.0, 1.0/(axle_length/2.0), -1.0/(axle_length/2.0); // b vector for command velocities Vector2f b; b << cmd_vx, cmd_wz; // x vector for storing wheel velocities after solve Vector2f x; // Pass to linear Alg to solver or something? x = A.ldlt().solve(b); // Convert Wheel Velocities to Angular Velocities // Be careful for sing flip, as motors are not mounted symmetrically right_wheel_omega = x(0)/wheel_radius; left_wheel_omega = x(1)/wheel_radius; // Declare Message scr_proto::DiffCommand motor_com; // Populate Message // Need to map omega's to value between -255 and 255. // Publish Message motor_pub.publish(motor_com); // Handle loop rate ros::spinOnce(); loop_rate.sleep(); } } <|endoftext|>
<commit_before>/* * ForageManagerImplementation.cpp * * Created on: Feb 20, 2011 * Author: Anakis */ #include "ForageManager.h" #include "server/zone/managers/loot/LootManager.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/managers/minigames/events/ForagingEvent.h" #include "server/zone/objects/area/ForageArea.h" #include "server/zone/objects/area/ForageAreaCollection.h" #include "server/zone/objects/creature/CreatureAttribute.h" #include "server/zone/objects/area/ActiveArea.h" void ForageManagerImplementation::startForaging(CreatureObject* player, int forageType) { if (player == NULL) return; Locker playerLocker(player); int actionCost = 50; int mindCostShellfish = 100; int actionCostShellfish = 100; //Check if already foraging. Reference<Task*> pendingForage = player->getPendingTask("foraging"); if (pendingForage != NULL) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:busy"); else player->sendSystemMessage("@skl_use:sys_forage_already"); //"You are already foraging." return; } //Check if player is inside a structure. if (player->getParentID() != 0) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:inside"); else player->sendSystemMessage("@skl_use:sys_forage_inside"); //"You can't forage inside a structure." return; } //Check if a player is swimming for shellfish harvesting if (forageType == ForageManager::SHELLFISH && player->isSwimming()){ player->sendSystemMessage("@harvesting:swimming"); return; } //Check if player is in water for shellfish harvesting if (forageType == ForageManager::SHELLFISH && !player->isInWater()){ player->sendSystemMessage("@harvesting:in_water"); return; } //Check for action and deduct cost. if (forageType == ForageManager::SHELLFISH){ if (player->getHAM(CreatureAttribute::MIND) < mindCostShellfish + 1 || player->getHAM(CreatureAttribute::ACTION) < actionCostShellfish + 1) return; else { player->inflictDamage(player, CreatureAttribute::MIND, mindCostShellfish, false, true); player->inflictDamage(player, CreatureAttribute::ACTION, actionCostShellfish, false, true); } } else { if (player->getHAM(CreatureAttribute::ACTION) >= actionCost + 1) player->inflictDamage(player, CreatureAttribute::ACTION, actionCost, false, true); else { player->sendSystemMessage("@skl_use:sys_forage_attrib"); //"You need to rest before you can forage again." return; } } //Collect player's current position. float playerX = player->getPositionX(); float playerY = player->getPositionY(); ManagedReference<ZoneServer*> zoneServer = player->getZoneServer(); //Queue the foraging task. Zone* zone = player->getZone(); if (zone == NULL) return; Reference<Task*> foragingEvent = new ForagingEvent(player, forageType, playerX, playerY, zone->getZoneName()); player->addPendingTask("foraging", foragingEvent, 8500); player->sendSystemMessage("@skl_use:sys_forage_start"); //"You begin to search the area for goods." player->doAnimation("forage"); } void ForageManagerImplementation::finishForaging(CreatureObject* player, int forageType, float forageX, float forageY, const String& zoneName) { if (player == NULL) return; Locker playerLocker(player); Locker forageAreasLocker(_this.get()); player->removePendingTask("foraging"); if (player->getZone() == NULL) return; //Check if player moved. if (forageType != ForageManager::SHELLFISH) { float playerX = player->getPositionX(); float playerY = player->getPositionY(); if ((abs(playerX - forageX) > 2.0) || (abs(playerY - forageY) > 2.0) || player->getZone()->getZoneName() != zoneName) { player->sendSystemMessage("@skl_use:sys_forage_movefail"); //"You fail to forage because you moved." return; } //Check if player is in combat. if (player->isInCombat()) { player->sendSystemMessage("@skl_use:sys_forage_combatfail"); //"Combat distracts you from your foraging attempt." return; } //Check if player is allowed to forage in this area. Reference<ForageAreaCollection*> forageAreaCollection = forageAreas.get(player->getFirstName()); if (forageAreaCollection != NULL) { //Player has foraged before. if (!forageAreaCollection->checkForageAreas(forageX, forageY, zoneName)) { player->sendSystemMessage("@skl_use:sys_forage_empty"); //"There is nothing in this area to forage." return; } } else { //Player has not foraged before. forageAreaCollection = new ForageAreaCollection(player, forageX, forageY, zoneName); forageAreas.put(player->getFirstName(), forageAreaCollection); } } //Calculate the player's chance to find an item. int chance; int skillMod; switch(forageType) { case ForageManager::SCOUT: case ForageManager::LAIR: skillMod = player->getSkillMod("foraging"); chance = (int)(15 + (skillMod * 0.8)); break; case ForageManager::MEDICAL: skillMod = player->getSkillMod("medical_foraging"); chance = (int)(15 + (skillMod * 0.6)); break; default: skillMod = 20; chance = (int)(15 + (skillMod * 0.6)); break; } //Determine if player finds an item. if (chance > 100) //There could possibly be +foraging skill tapes. chance = 100; if (System::random(80) > chance) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:found_nothing"); else if (forageType == ForageManager::LAIR) player->sendSystemMessage("@lair_n:found_nothing"); else player->sendSystemMessage("@skl_use:sys_forage_fail"); //"You failed to find anything worth foraging." } else { forageGiveItems(player, forageType, forageX, forageY, zoneName); } return; } bool ForageManagerImplementation::forageGiveItems(CreatureObject* player, int forageType, float forageX, float forageY, const String& planet) { if (player == NULL) return false; Locker playerLocker(player); ManagedReference<LootManager*> lootManager = player->getZoneServer()->getLootManager(); ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (lootManager == NULL || inventory == NULL) { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } //Check if inventory is full. if (inventory->hasFullContainerObjects()) { player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." return false; } int itemCount = 1; //Determine how many items the player finds. if (forageType == ForageManager::SCOUT) { if (player->hasSkill("outdoors_scout_camp_03") && System::random(5) == 1) itemCount += 1; if (player->hasSkill("outdoors_scout_master") && System::random(5) == 1) itemCount += 1; } //Discard items if player's inventory does not have enough space. int inventorySpace = inventory->getContainerVolumeLimit() - inventory->getContainerObjectsSize(); if (itemCount > inventorySpace) { itemCount = inventorySpace; player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." } //Determine what the player finds. int dice; int level = 1; String lootGroup = ""; String resName = ""; if (forageType == ForageManager::SHELLFISH){ bool mullosks = false; if (System::random(100) > 50) { resName = "seafood_mollusk"; mullosks = true; } else resName = "seafood_crustacean"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { if (mullosks) player->sendSystemMessage("@harvesting:found_mollusks"); else player->sendSystemMessage("@harvesting:found_crustaceans"); return true; } else { player->sendSystemMessage("@harvesting:found_nothing"); return false; } } if (forageType == ForageManager::SCOUT) { for (int i = 0; i < itemCount; i++) { dice = System::random(200); level = 1; if (dice >= 0 && dice < 160) { lootGroup = "forage_food"; } else if (dice > 159 && dice < 200) { lootGroup = "forage_bait"; } else { lootGroup = "forage_rare"; } lootManager->createLoot(inventory, lootGroup, level); } } else if (forageType == ForageManager::MEDICAL) { //Medical Forage dice = System::random(200); level = 1; if (dice >= 0 && dice < 40) { //Forage food. lootGroup = "forage_food"; } else if (dice > 39 && dice < 110) { //Resources. if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } else { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } } else if (dice > 109 && dice < 170) { //Average components. lootGroup = "forage_medical_component"; level = 1; } else if (dice > 169 && dice < 200) { //Good components. lootGroup = "forage_medical_component"; level = 60; } else { //Exceptional Components lootGroup = "forage_medical_component"; level = 200; } lootManager->createLoot(inventory, lootGroup, level); } else if (forageType == ForageManager::LAIR) { //Lair Search dice = System::random(200); level = 1; if (dice >= 0 && dice < 40) { // Live Creatures lootGroup = "forage_live_creatures"; } else if (dice > 39 && dice < 110) { // Eggs resName = "meat_egg"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@lair_n:found_eggs"); return true; } else { player->sendSystemMessage("@lair_n:found_nothing"); return false; } } else {//if (dice > 109 && dice < 200) // Horn resName = "bone_horn"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } else { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } } if(!lootManager->createLoot(inventory, lootGroup, level)) { player->sendSystemMessage("Unable to create loot for lootgroup " + lootGroup); return false; } player->sendSystemMessage("@lair_n:found_bugs"); return true; } player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } bool ForageManagerImplementation::forageGiveResource(CreatureObject* player, float forageX, float forageY, const String& planet, String& resType) { if (player == NULL) return false; ManagedReference<ResourceManager*> resourceManager = player->getZoneServer()->getResourceManager(); if (resourceManager == NULL) return false; ManagedReference<ResourceSpawn*> resource = NULL; if(resType.isEmpty()) { //Get a list of the flora on the planet. Vector<ManagedReference<ResourceSpawn*> > resources; resourceManager->getResourceListByType(resources, 3, planet); if (resources.size() < 1) return false; while (resources.size() > 0) { int key = System::random(resources.size() - 1); float density = resources.get(key)->getDensityAt(planet, forageX, forageY); if (density <= 0.0 && resources.size() > 1) { //No concentration of this resource near the player. resources.remove(key); //Remove and pick another one. } else { //If there is only one left, we give them that one even if density is 0. resource = resources.get(key); break; } } } else { if(player->getZone() == NULL) return false; resType = resType + "_" + player->getZone()->getZoneName(); resource = resourceManager->getCurrentSpawn(resType, player->getZone()->getZoneName()); if(resource == NULL) { StringBuffer message; message << "Resource type not available: " << resType << " on " << player->getZone()->getZoneName(); warning(message.toString()); return false; } } int quantity = System::random(30) + 10; resourceManager->harvestResourceToPlayer(player, resource, quantity); return true; } <commit_msg>(unstable) [added] patch by Galameed: fixed lair foraging.<commit_after>/* * ForageManagerImplementation.cpp * * Created on: Feb 20, 2011 * Author: Anakis */ #include "ForageManager.h" #include "server/zone/managers/loot/LootManager.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/managers/minigames/events/ForagingEvent.h" #include "server/zone/objects/area/ForageArea.h" #include "server/zone/objects/area/ForageAreaCollection.h" #include "server/zone/objects/creature/CreatureAttribute.h" #include "server/zone/objects/area/ActiveArea.h" void ForageManagerImplementation::startForaging(CreatureObject* player, int forageType) { if (player == NULL) return; Locker playerLocker(player); int actionCost = 50; int mindCostShellfish = 100; int actionCostShellfish = 100; //Check if already foraging. Reference<Task*> pendingForage = player->getPendingTask("foraging"); if (pendingForage != NULL) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:busy"); else player->sendSystemMessage("@skl_use:sys_forage_already"); //"You are already foraging." return; } //Check if player is inside a structure. if (player->getParentID() != 0) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:inside"); else player->sendSystemMessage("@skl_use:sys_forage_inside"); //"You can't forage inside a structure." return; } //Check if a player is swimming for shellfish harvesting if (forageType == ForageManager::SHELLFISH && player->isSwimming()){ player->sendSystemMessage("@harvesting:swimming"); return; } //Check if player is in water for shellfish harvesting if (forageType == ForageManager::SHELLFISH && !player->isInWater()){ player->sendSystemMessage("@harvesting:in_water"); return; } //Check for action and deduct cost. if (forageType == ForageManager::SHELLFISH){ if (player->getHAM(CreatureAttribute::MIND) < mindCostShellfish + 1 || player->getHAM(CreatureAttribute::ACTION) < actionCostShellfish + 1) return; else { player->inflictDamage(player, CreatureAttribute::MIND, mindCostShellfish, false, true); player->inflictDamage(player, CreatureAttribute::ACTION, actionCostShellfish, false, true); } } else { if (player->getHAM(CreatureAttribute::ACTION) >= actionCost + 1) player->inflictDamage(player, CreatureAttribute::ACTION, actionCost, false, true); else { player->sendSystemMessage("@skl_use:sys_forage_attrib"); //"You need to rest before you can forage again." return; } } //Collect player's current position. float playerX = player->getPositionX(); float playerY = player->getPositionY(); ManagedReference<ZoneServer*> zoneServer = player->getZoneServer(); //Queue the foraging task. Zone* zone = player->getZone(); if (zone == NULL) return; Reference<Task*> foragingEvent = new ForagingEvent(player, forageType, playerX, playerY, zone->getZoneName()); player->addPendingTask("foraging", foragingEvent, 8500); if(forageType == ForageManager::LAIR){ player->sendSystemMessage("You begin to search the lair for creatures"); //"You begin to search the lair for creatures." } else{ player->sendSystemMessage("@skl_use:sys_forage_start"); //"You begin to search the area for goods." } player->doAnimation("forage"); } void ForageManagerImplementation::finishForaging(CreatureObject* player, int forageType, float forageX, float forageY, const String& zoneName) { if (player == NULL) return; Locker playerLocker(player); Locker forageAreasLocker(_this.get()); player->removePendingTask("foraging"); if (player->getZone() == NULL) return; //Check if player moved. if (forageType != ForageManager::SHELLFISH) { float playerX = player->getPositionX(); float playerY = player->getPositionY(); if ((abs(playerX - forageX) > 2.0) || (abs(playerY - forageY) > 2.0) || player->getZone()->getZoneName() != zoneName) { player->sendSystemMessage("@skl_use:sys_forage_movefail"); //"You fail to forage because you moved." return; } //Check if player is in combat. if (player->isInCombat()) { player->sendSystemMessage("@skl_use:sys_forage_combatfail"); //"Combat distracts you from your foraging attempt." return; } //Check if player is allowed to forage in this area. Reference<ForageAreaCollection*> forageAreaCollection = forageAreas.get(player->getFirstName()); if (forageAreaCollection != NULL) { //Player has foraged before. if (!forageAreaCollection->checkForageAreas(forageX, forageY, zoneName)) { player->sendSystemMessage("@skl_use:sys_forage_empty"); //"There is nothing in this area to forage." return; } } else { //Player has not foraged before. forageAreaCollection = new ForageAreaCollection(player, forageX, forageY, zoneName); forageAreas.put(player->getFirstName(), forageAreaCollection); } } //Calculate the player's chance to find an item. int chance; int skillMod; switch(forageType) { case ForageManager::SCOUT: case ForageManager::LAIR: skillMod = player->getSkillMod("foraging"); chance = (int)(15 + (skillMod * 0.8)); break; case ForageManager::MEDICAL: skillMod = player->getSkillMod("medical_foraging"); chance = (int)(15 + (skillMod * 0.6)); break; default: skillMod = 20; chance = (int)(15 + (skillMod * 0.6)); break; } //Determine if player finds an item. if (chance > 100) //There could possibly be +foraging skill tapes. chance = 100; if (System::random(80) > chance) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:found_nothing"); else if (forageType == ForageManager::LAIR) player->sendSystemMessage("@lair_n:found_nothing"); else player->sendSystemMessage("@skl_use:sys_forage_fail"); //"You failed to find anything worth foraging." } else { forageGiveItems(player, forageType, forageX, forageY, zoneName); } return; } bool ForageManagerImplementation::forageGiveItems(CreatureObject* player, int forageType, float forageX, float forageY, const String& planet) { if (player == NULL) return false; Locker playerLocker(player); ManagedReference<LootManager*> lootManager = player->getZoneServer()->getLootManager(); ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (lootManager == NULL || inventory == NULL) { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } //Check if inventory is full. if (inventory->hasFullContainerObjects()) { player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." return false; } int itemCount = 1; //Determine how many items the player finds. if (forageType == ForageManager::SCOUT) { if (player->hasSkill("outdoors_scout_camp_03") && System::random(5) == 1) itemCount += 1; if (player->hasSkill("outdoors_scout_master") && System::random(5) == 1) itemCount += 1; } //Discard items if player's inventory does not have enough space. int inventorySpace = inventory->getContainerVolumeLimit() - inventory->getContainerObjectsSize(); if (itemCount > inventorySpace) { itemCount = inventorySpace; player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." } //Determine what the player finds. int dice; int level = 1; String lootGroup = ""; String resName = ""; if (forageType == ForageManager::SHELLFISH){ bool mullosks = false; if (System::random(100) > 50) { resName = "seafood_mollusk"; mullosks = true; } else resName = "seafood_crustacean"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { if (mullosks) player->sendSystemMessage("@harvesting:found_mollusks"); else player->sendSystemMessage("@harvesting:found_crustaceans"); return true; } else { player->sendSystemMessage("@harvesting:found_nothing"); return false; } } if (forageType == ForageManager::SCOUT) { for (int i = 0; i < itemCount; i++) { dice = System::random(200); level = 1; if (dice >= 0 && dice < 160) { lootGroup = "forage_food"; } else if (dice > 159 && dice < 200) { lootGroup = "forage_bait"; } else { lootGroup = "forage_rare"; } lootManager->createLoot(inventory, lootGroup, level); } } else if (forageType == ForageManager::MEDICAL) { //Medical Forage dice = System::random(200); level = 1; if (dice >= 0 && dice < 40) { //Forage food. lootGroup = "forage_food"; } else if (dice > 39 && dice < 110) { //Resources. if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } else { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } } else if (dice > 109 && dice < 170) { //Average components. lootGroup = "forage_medical_component"; level = 1; } else if (dice > 169 && dice < 200) { //Good components. lootGroup = "forage_medical_component"; level = 60; } else { //Exceptional Components lootGroup = "forage_medical_component"; level = 200; } lootManager->createLoot(inventory, lootGroup, level); } else if (forageType == ForageManager::LAIR) { //Lair Search dice = System::random(109); level = 1; if (dice >= 0 && dice < 40) { // Live Creatures lootGroup = "forage_live_creatures"; } else if (dice > 39 && dice < 110) { // Eggs resName = "meat_egg"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@lair_n:found_eggs"); return true; } else { player->sendSystemMessage("@lair_n:found_nothing"); return false; } } if(!lootManager->createLoot(inventory, lootGroup, level)) { player->sendSystemMessage("Unable to create loot for lootgroup " + lootGroup); return false; } player->sendSystemMessage("@lair_n:found_bugs"); return true; } player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } bool ForageManagerImplementation::forageGiveResource(CreatureObject* player, float forageX, float forageY, const String& planet, String& resType) { if (player == NULL) return false; ManagedReference<ResourceManager*> resourceManager = player->getZoneServer()->getResourceManager(); if (resourceManager == NULL) return false; ManagedReference<ResourceSpawn*> resource = NULL; if(resType.isEmpty()) { //Get a list of the flora on the planet. Vector<ManagedReference<ResourceSpawn*> > resources; resourceManager->getResourceListByType(resources, 3, planet); if (resources.size() < 1) return false; while (resources.size() > 0) { int key = System::random(resources.size() - 1); float density = resources.get(key)->getDensityAt(planet, forageX, forageY); if (density <= 0.0 && resources.size() > 1) { //No concentration of this resource near the player. resources.remove(key); //Remove and pick another one. } else { //If there is only one left, we give them that one even if density is 0. resource = resources.get(key); break; } } } else { if(player->getZone() == NULL) return false; resType = resType + "_" + player->getZone()->getZoneName(); resource = resourceManager->getCurrentSpawn(resType, player->getZone()->getZoneName()); if(resource == NULL) { StringBuffer message; message << "Resource type not available: " << resType << " on " << player->getZone()->getZoneName(); warning(message.toString()); return false; } } int quantity = System::random(30) + 10; resourceManager->harvestResourceToPlayer(player, resource, quantity); return true; } <|endoftext|>
<commit_before>// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz (døt) ch> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // ======================================================================================== #ifndef TestFunctions_hpp #define TestFunctions_hpp #include <stdlib.h> #include <fstream> #include <functional> #include <gtest/gtest.h> #include "ApproxMVBB/Config/Config.hpp" #include "ApproxMVBB/Common/AssertionDebug.hpp" #include "ApproxMVBB/Common/SfinaeMacros.hpp" #include ApproxMVBB_TypeDefs_INCLUDE_FILE #include "ApproxMVBB/RandomGenerators.hpp" #include "ApproxMVBB/PointFunctions.hpp" #include "ApproxMVBB/OOBB.hpp" #define MY_TEST(name1 , name2 ) TEST(name1, name2) #define MY_TEST_RANDOM_STUFF(name) \ std::string testName = #name ; \ auto seed = hashString(#name); \ std::cout << "Seed for this test: " << seed << std::endl; \ ApproxMVBB::RandomGenerators::DefaultRandomGen rng(seed); \ std::uniform_real_distribution<PREC> uni(0.0,1.0); \ auto f = [&](PREC) { return uni(rng); }; namespace ApproxMVBB{ namespace TestFunctions{ ApproxMVBB_DEFINE_MATRIX_TYPES ApproxMVBB_DEFINE_POINTS_CONFIG_TYPES // TODO not std lib conform! std::size_t hashString(std::string name); template<typename A, typename B> ::testing::AssertionResult assertNearArrays( const A & a, const B & b, PREC absError = 1e-3) { if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} if( (( a - b ).array().abs() >= absError).any() ){ return ::testing::AssertionFailure() <<"not near: absTol:" << absError; } return ::testing::AssertionSuccess(); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == true ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.col(i), b.col(j)); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == false ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.row(i), b.row(j)); } template<bool matchCols = true, typename A, typename B> ::testing::AssertionResult assertNearArrayColsRows(const A & a, const B & b){ if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} // Check all points std::vector<bool> indexMatched; if(matchCols){ indexMatched.resize(a.cols(),false); }else{ indexMatched.resize(a.rows(),false); } auto s = indexMatched.size(); std::size_t nMatched = 0; std::size_t i = 0; std::size_t pointIdx = 0; while( pointIdx < s){ if( i < s){ // check points[pointIdx] against i-th valid one if ( !indexMatched[i] && assertNearArrayColsRows_cr<matchCols>(a,pointIdx,b,i)){ indexMatched[i] = true; ++nMatched; }else{ ++i; continue; } } // all indices i checked go to next point, reset check idx i = 0; ++pointIdx; } if(nMatched != s){ return ::testing::AssertionFailure() << "Matched only " << nMatched << "/" << s ; } return ::testing::AssertionSuccess(); } template<typename Derived> void dumpPointsMatrix(std::string filePath, const MatrixBase<Derived> & v) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(v.cols() != 0){ unsigned int i=0; for(; i<v.cols()-1; i++) { l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } int isBigEndian(void); template <typename T> T swapEndian(T u) { ApproxMVBB_STATIC_ASSERTM(sizeof(char) == 1, "char != 8 bit"); union { T u; unsigned char u8[sizeof(T)]; } source, dest; source.u = u; for (size_t k = 0; k < sizeof(T); k++) dest.u8[k] = source.u8[sizeof(T) - k - 1]; return dest.u; } template<class Matrix> void dumpPointsMatrixBinary(std::string filename, const Matrix& matrix){ std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc); typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = isBigEndian(); out.write((char*) (&bigEndian), sizeof(bool)); out.write((char*) (&rows), sizeof(typename Matrix::Index)); out.write((char*) (&cols), sizeof(typename Matrix::Index)); typename Matrix::Index bytes = sizeof(typename Matrix::Scalar); out.write((char*) (&bytes), sizeof(typename Matrix::Index )); out.write((char*) matrix.data(), rows*cols*sizeof(typename Matrix::Scalar) ); out.close(); } template<class Matrix> void readPointsMatrixBinary(std::string filename, Matrix& matrix, bool withHeader=true){ std::ifstream in(filename,std::ios::in | std::ios::binary); if(!in.is_open()){ ApproxMVBB_ERRORMSG("cannot open file: " << filename); } typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = false; // assume all input files with no headers are little endian! if(withHeader){ in.read((char*) (&bigEndian), sizeof(bool)); in.read((char*) (&rows),sizeof(typename Matrix::Index)); in.read((char*) (&cols),sizeof(typename Matrix::Index)); typename Matrix::Index bytes; in.read((char*) (&bytes), sizeof(typename Matrix::Index )); // swap endianness if file has other type if(isBigEndian() != bigEndian ){ rows = swapEndian(rows); cols = swapEndian(cols); bytes = swapEndian(bytes); } if(bytes != sizeof(typename Matrix::Scalar)){ ApproxMVBB_ERRORMSG("read binary with wrong data type: " << filename << "bigEndian: " << bigEndian << ", rows: " << rows << ", cols: " << cols <<", scalar bytes: " << bytes); } matrix.resize(rows, cols); } in.read( (char *) matrix.data() , rows*cols*sizeof(typename Matrix::Scalar) ); // swap endianness of whole matrix if file has other type if(isBigEndian() != bigEndian ){ auto f = [](const typename Matrix::Scalar & v){return swapEndian(v);}; matrix = matrix.unaryExpr( f ); } in.close(); } template<typename List, typename Derived> void convertMatrixToListRows(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.cols()) { points.resize(M.rows()); for(std::size_t i = 0 ; i < M.rows(); ++i){ points[i] = M.row(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToListCols(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.rows()) { points.resize(M.cols()); for(std::size_t i = 0 ; i < M.cols(); ++i){ points[i] = M.col(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToList_assCols(const MatrixBase<Derived> & M, List& points){ } template<typename Container> void dumpPoints(std::string filePath, Container & c) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(c.size()!=0){ auto e = c.begin() + (c.size() - 1); auto it = c.begin(); for(; it != e; ++it) { l << it->transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << (it)->transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } void readOOBB(std::string filePath, Vector3 & minP, Vector3 & maxP, Matrix33 & R_KI, Vector3List & pointList); void readOOBBAndCheck( OOBB & validOOBB, std::string filePath); void dumpOOBB(std::string filePath, const OOBB & oobb); Vector3List getPointsFromFile3D(std::string filePath); Vector2List getPointsFromFile2D(std::string filePath); // Vector2List generatePoints2D(unsigned int n=4); // // Vector3List generatePoints3D(unsigned int n=4); template<typename Derived, typename IndexSet> Derived filterPoints(MatrixBase<Derived> & v, IndexSet & s){ Derived ret; ret.resize(v.rows(),s.size()); auto size = v.cols(); decltype(size) k = 0; for(auto i : s){ if(i < size && i >=0){ ret.col(k++) = v.col(i); } }; return ret; } template<typename Derived> bool checkPointsInOOBB(const MatrixBase<Derived> & points, OOBB oobb){ Matrix33 A_KI = oobb.m_q_KI.matrix(); A_KI.transposeInPlace(); Vector3 p; bool allInside = true; auto size = points.cols(); decltype(size) i = 0; while(i<size && allInside){ p = A_KI * points.col(i); allInside &= ( p(0) >= oobb.m_minPoint(0) && p(0) <= oobb.m_maxPoint(0) && p(1) >= oobb.m_minPoint(1) && p(1) <= oobb.m_maxPoint(1) && p(2) >= oobb.m_minPoint(2) && p(2) <= oobb.m_maxPoint(2)); ++i; } return allInside; } } } #endif <commit_msg>tests<commit_after>// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz (døt) ch> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // ======================================================================================== #ifndef TestFunctions_hpp #define TestFunctions_hpp #include <stdlib.h> #include <fstream> #include <functional> #include <gtest/gtest.h> #include "ApproxMVBB/Config/Config.hpp" #include "ApproxMVBB/Common/AssertionDebug.hpp" #include "ApproxMVBB/Common/SfinaeMacros.hpp" #include ApproxMVBB_TypeDefs_INCLUDE_FILE #include "ApproxMVBB/RandomGenerators.hpp" #include "ApproxMVBB/PointFunctions.hpp" #include "ApproxMVBB/OOBB.hpp" #define MY_TEST(name1 , name2 ) TEST(name1, name2) #define MY_TEST_RANDOM_STUFF(name) \ std::string testName = #name ; \ auto seed = hashString(#name); \ std::cout << "Seed for this test: " << seed << std::endl; \ ApproxMVBB::RandomGenerators::DefaultRandomGen rng(seed); \ std::uniform_real_distribution<PREC> uni(0.0,1.0); \ auto f = [&](PREC) { return uni(rng); }; namespace ApproxMVBB{ namespace TestFunctions{ ApproxMVBB_DEFINE_MATRIX_TYPES ApproxMVBB_DEFINE_POINTS_CONFIG_TYPES // TODO not std lib conform! std::size_t hashString(std::string name); template<typename A, typename B> ::testing::AssertionResult assertNearArrays( const A & a, const B & b, PREC absError = 1e-6) { if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} if( (( a - b ).array().abs() >= absError).any() ){ return ::testing::AssertionFailure() <<"not near: absTol:" << absError; } return ::testing::AssertionSuccess(); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == true ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.col(i), b.col(j)); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == false ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.row(i), b.row(j)); } template<bool matchCols = true, typename A, typename B> ::testing::AssertionResult assertNearArrayColsRows(const A & a, const B & b){ if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} // Check all points std::vector<bool> indexMatched; if(matchCols){ indexMatched.resize(a.cols(),false); }else{ indexMatched.resize(a.rows(),false); } auto s = indexMatched.size(); std::size_t nMatched = 0; std::size_t i = 0; std::size_t pointIdx = 0; while( pointIdx < s){ if( i < s){ // check points[pointIdx] against i-th valid one if ( !indexMatched[i] && assertNearArrayColsRows_cr<matchCols>(a,pointIdx,b,i)){ indexMatched[i] = true; ++nMatched; }else{ ++i; continue; } } // all indices i checked go to next point, reset check idx i = 0; ++pointIdx; } if(nMatched != s){ return ::testing::AssertionFailure() << "Matched only " << nMatched << "/" << s ; } return ::testing::AssertionSuccess(); } template<typename Derived> void dumpPointsMatrix(std::string filePath, const MatrixBase<Derived> & v) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(v.cols() != 0){ unsigned int i=0; for(; i<v.cols()-1; i++) { l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } int isBigEndian(void); template <typename T> T swapEndian(T u) { ApproxMVBB_STATIC_ASSERTM(sizeof(char) == 1, "char != 8 bit"); union { T u; unsigned char u8[sizeof(T)]; } source, dest; source.u = u; for (size_t k = 0; k < sizeof(T); k++) dest.u8[k] = source.u8[sizeof(T) - k - 1]; return dest.u; } template<class Matrix> void dumpPointsMatrixBinary(std::string filename, const Matrix& matrix){ std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc); typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = isBigEndian(); out.write((char*) (&bigEndian), sizeof(bool)); out.write((char*) (&rows), sizeof(typename Matrix::Index)); out.write((char*) (&cols), sizeof(typename Matrix::Index)); typename Matrix::Index bytes = sizeof(typename Matrix::Scalar); out.write((char*) (&bytes), sizeof(typename Matrix::Index )); out.write((char*) matrix.data(), rows*cols*sizeof(typename Matrix::Scalar) ); out.close(); } template<class Matrix> void readPointsMatrixBinary(std::string filename, Matrix& matrix, bool withHeader=true){ std::ifstream in(filename,std::ios::in | std::ios::binary); if(!in.is_open()){ ApproxMVBB_ERRORMSG("cannot open file: " << filename); } typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = false; // assume all input files with no headers are little endian! if(withHeader){ in.read((char*) (&bigEndian), sizeof(bool)); in.read((char*) (&rows),sizeof(typename Matrix::Index)); in.read((char*) (&cols),sizeof(typename Matrix::Index)); typename Matrix::Index bytes; in.read((char*) (&bytes), sizeof(typename Matrix::Index )); // swap endianness if file has other type if(isBigEndian() != bigEndian ){ rows = swapEndian(rows); cols = swapEndian(cols); bytes = swapEndian(bytes); } if(bytes != sizeof(typename Matrix::Scalar)){ ApproxMVBB_ERRORMSG("read binary with wrong data type: " << filename << "bigEndian: " << bigEndian << ", rows: " << rows << ", cols: " << cols <<", scalar bytes: " << bytes); } matrix.resize(rows, cols); } in.read( (char *) matrix.data() , rows*cols*sizeof(typename Matrix::Scalar) ); // swap endianness of whole matrix if file has other type if(isBigEndian() != bigEndian ){ auto f = [](const typename Matrix::Scalar & v){return swapEndian(v);}; matrix = matrix.unaryExpr( f ); } in.close(); } template<typename List, typename Derived> void convertMatrixToListRows(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.cols()) { points.resize(M.rows()); for(std::size_t i = 0 ; i < M.rows(); ++i){ points[i] = M.row(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToListCols(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.rows()) { points.resize(M.cols()); for(std::size_t i = 0 ; i < M.cols(); ++i){ points[i] = M.col(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToList_assCols(const MatrixBase<Derived> & M, List& points){ } template<typename Container> void dumpPoints(std::string filePath, Container & c) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(c.size()!=0){ auto e = c.begin() + (c.size() - 1); auto it = c.begin(); for(; it != e; ++it) { l << it->transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << (it)->transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } void readOOBB(std::string filePath, Vector3 & minP, Vector3 & maxP, Matrix33 & R_KI, Vector3List & pointList); void readOOBBAndCheck( OOBB & validOOBB, std::string filePath); void dumpOOBB(std::string filePath, const OOBB & oobb); Vector3List getPointsFromFile3D(std::string filePath); Vector2List getPointsFromFile2D(std::string filePath); // Vector2List generatePoints2D(unsigned int n=4); // // Vector3List generatePoints3D(unsigned int n=4); template<typename Derived, typename IndexSet> Derived filterPoints(MatrixBase<Derived> & v, IndexSet & s){ Derived ret; ret.resize(v.rows(),s.size()); auto size = v.cols(); decltype(size) k = 0; for(auto i : s){ if(i < size && i >=0){ ret.col(k++) = v.col(i); } }; return ret; } template<typename Derived> bool checkPointsInOOBB(const MatrixBase<Derived> & points, OOBB oobb){ Matrix33 A_KI = oobb.m_q_KI.matrix(); A_KI.transposeInPlace(); Vector3 p; bool allInside = true; auto size = points.cols(); decltype(size) i = 0; while(i<size && allInside){ p = A_KI * points.col(i); allInside &= ( p(0) >= oobb.m_minPoint(0) && p(0) <= oobb.m_maxPoint(0) && p(1) >= oobb.m_minPoint(1) && p(1) <= oobb.m_maxPoint(1) && p(2) >= oobb.m_minPoint(2) && p(2) <= oobb.m_maxPoint(2)); ++i; } return allInside; } } } #endif <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <memory> #include <uv.h> #include "util.hpp" namespace uvw { // base structures struct BaseEvent { virtual ~BaseEvent() noexcept = 0; static std::size_t next() noexcept { static std::size_t cnt = 0; return cnt++; } }; BaseEvent::~BaseEvent() noexcept { } template<typename E> struct Event: BaseEvent { static std::size_t type() noexcept { static std::size_t val = BaseEvent::next(); return val; } }; // empty events struct DefaultEvent: Event<DefaultEvent> { }; using AsyncEvent = DefaultEvent; using CheckEvent = DefaultEvent; using CloseEvent = DefaultEvent; using ConnectEvent = DefaultEvent; using EndEvent = DefaultEvent; using IdleEvent = DefaultEvent; using ListenEvent = DefaultEvent; using PrepareEvent = DefaultEvent; using SendEvent = DefaultEvent; using ShutdownEvent = DefaultEvent; using TimerEvent = DefaultEvent; using UninitializedEvent = DefaultEvent; using WorkEvent = DefaultEvent; using WriteEvent = DefaultEvent; // specialized events struct DataEvent: Event<DataEvent> { explicit DataEvent(std::unique_ptr<const char[]> ptr, ssize_t l) noexcept : dt{std::move(ptr)}, len{l} { } const char * data() const noexcept { return dt.get(); } ssize_t length() const noexcept { return len; } private: std::unique_ptr<const char[]> dt; const ssize_t len; }; struct ErrorEvent: Event<ErrorEvent> { explicit ErrorEvent(int code = 0) noexcept: ec(code) { } const char * what() const noexcept { return uv_strerror(ec); } int code() const noexcept { return ec; } private: const int ec; }; template<typename E> struct FlagsEvent: Event<FlagsEvent<E>> { explicit FlagsEvent(Flags<E> f) noexcept: flgs{std::move(f)} { } Flags<E> flags() const noexcept { return flgs; } private: Flags<E> flgs; }; struct FsPollEvent: Event<FsPollEvent> { explicit FsPollEvent(const Stat &p, const Stat &c) noexcept : prev(p), curr(c) { } const Stat & previous() const noexcept { return prev; } const Stat & current() const noexcept { return curr; } private: Stat prev; Stat curr; }; struct SignalEvent: Event<SignalEvent> { explicit SignalEvent(int sig) noexcept: signum(sig) { } int signal() const noexcept { return signum; } private: const int signum; }; struct UDPDataEvent: Event<UDPDataEvent> { explicit UDPDataEvent(Addr addr, std::unique_ptr<const char[]> ptr, ssize_t l, bool trunc) noexcept : dt{std::move(ptr)}, len{l}, sndr{addr}, part{trunc} { } const char * data() const noexcept { return dt.get(); } ssize_t length() const noexcept { return len; } Addr sender() const noexcept { return sndr; } bool partial() const noexcept { return part; } private: std::unique_ptr<const char[]> dt; const ssize_t len; Addr sndr; const bool part; }; } <commit_msg>well, the emitter would have not been grateful for that<commit_after>#pragma once #include <cstddef> #include <memory> #include <uv.h> #include "util.hpp" namespace uvw { struct BaseEvent { virtual ~BaseEvent() noexcept = 0; static std::size_t next() noexcept { static std::size_t cnt = 0; return cnt++; } }; BaseEvent::~BaseEvent() noexcept { } template<typename E> struct Event: BaseEvent { static std::size_t type() noexcept { static std::size_t val = BaseEvent::next(); return val; } }; struct AsyncEvent: Event<AsyncEvent> { }; struct CheckEvent: Event<CheckEvent> { }; struct CloseEvent: Event<CloseEvent> { }; struct ConnectEvent: Event<ConnectEvent> { }; struct DataEvent: Event<DataEvent> { explicit DataEvent(std::unique_ptr<const char[]> ptr, ssize_t l) noexcept : dt{std::move(ptr)}, len{l} { } const char * data() const noexcept { return dt.get(); } ssize_t length() const noexcept { return len; } private: std::unique_ptr<const char[]> dt; const ssize_t len; }; struct EndEvent: Event<EndEvent> { }; struct ErrorEvent: Event<ErrorEvent> { explicit ErrorEvent(int code = 0) noexcept: ec(code) { } const char * what() const noexcept { return uv_strerror(ec); } int code() const noexcept { return ec; } private: const int ec; }; template<typename E> struct FlagsEvent: Event<FlagsEvent<E>> { explicit FlagsEvent(Flags<E> f) noexcept: flgs{std::move(f)} { } Flags<E> flags() const noexcept { return flgs; } private: Flags<E> flgs; }; struct FsPollEvent: Event<FsPollEvent> { explicit FsPollEvent(const Stat &p, const Stat &c) noexcept : prev(p), curr(c) { } const Stat & previous() const noexcept { return prev; } const Stat & current() const noexcept { return curr; } private: Stat prev; Stat curr; }; struct IdleEvent: Event<IdleEvent> { }; struct ListenEvent: Event<ListenEvent> { }; struct PrepareEvent: Event<PrepareEvent> { }; struct SendEvent: Event<SendEvent> { }; struct ShutdownEvent: Event<ShutdownEvent> { }; struct SignalEvent: Event<SignalEvent> { explicit SignalEvent(int sig) noexcept: signum(sig) { } int signal() const noexcept { return signum; } private: const int signum; }; struct TimerEvent: Event<TimerEvent> { }; struct UDPDataEvent: Event<UDPDataEvent> { explicit UDPDataEvent(Addr addr, std::unique_ptr<const char[]> ptr, ssize_t l, bool trunc) noexcept : dt{std::move(ptr)}, len{l}, sndr{addr}, part{trunc} { } const char * data() const noexcept { return dt.get(); } ssize_t length() const noexcept { return len; } Addr sender() const noexcept { return sndr; } bool partial() const noexcept { return part; } private: std::unique_ptr<const char[]> dt; const ssize_t len; Addr sndr; const bool part; }; struct UninitializedEvent: Event<UninitializedEvent> { }; struct WorkEvent: Event<WorkEvent> { }; struct WriteEvent: Event<WriteEvent> { }; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the // // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #define L10N // Localization complete. #include <sstream> #include <Context.h> #include <ViewText.h> #include <text.h> #include <i18n.h> #include <main.h> #include <CmdProjects.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdProjects::CmdProjects () { _keyword = "projects"; _usage = "task projects [<filter>]"; _description = STRING_CMD_PROJECTS_USAGE; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdProjects::execute (std::string& output) { int rc = 0; // Get all the tasks. std::vector <Task> tasks; context.tdb.lock (context.config.getBoolean ("locking")); handleRecurrence (); int quantity; if (context.config.getBoolean ("list.all.projects")) quantity = context.tdb.load (tasks); else quantity = context.tdb.loadPending (tasks); context.tdb.commit (); context.tdb.unlock (); // Apply filter. std::vector <Task> filtered; filter (tasks, filtered); std::stringstream out; // Scan all the tasks for their project name, building a map using project // names as keys. std::map <std::string, int> unique; std::map <std::string, int> high; std::map <std::string, int> medium; std::map <std::string, int> low; std::map <std::string, int> none; bool no_project = false; std::string project; std::string priority; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { project = task->get ("project"); priority = task->get ("priority"); unique[project] += 1; if (project == "") no_project = true; if (priority == "H") high[project] += 1; else if (priority == "M") medium[project] += 1; else if (priority == "L") low[project] += 1; else none[project] += 1; } if (unique.size ()) { // Render a list of project names from the map. ViewText view; view.width (context.getWidth ()); view.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT)); view.add (Column::factory ("string.right", STRING_COLUMN_LABEL_TASKS)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_N)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_H)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_M)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_L)); std::map <std::string, int>::iterator project; for (project = unique.begin (); project != unique.end (); ++project) { int row = view.addRow (); view.set (row, 0, (project->first == "" ? STRING_CMD_PROJECTS_NONE : project->first)); view.set (row, 1, project->second); view.set (row, 2, none[project->first]); view.set (row, 3, low[project->first]); view.set (row, 4, medium[project->first]); view.set (row, 5, high[project->first]); } int number_projects = unique.size (); if (no_project) --number_projects; out << optionalBlankLine () << view.render () << optionalBlankLine () << (number_projects == 1 ? format (STRING_CMD_PROJECTS_SUMMARY, number_projects) : format (STRING_CMD_PROJECTS_SUMMARY2, number_projects)) << " " << (quantity == 1 ? format (STRING_CMD_PROJECTS_TASK, quantity) : format (STRING_CMD_PROJECTS_TASKS, quantity)) << "\n"; } else { out << STRING_CMD_PROJECTS_NO << "\n"; rc = 1; } output = out.str (); return rc; } //////////////////////////////////////////////////////////////////////////////// CmdCompletionProjects::CmdCompletionProjects () { _keyword = "_projects"; _usage = "task _projects [<filter>]"; _description = STRING_CMD_PROJECTS_USAGE_2; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdCompletionProjects::execute (std::string& output) { // Get all the tasks. std::vector <Task> tasks; context.tdb.lock (context.config.getBoolean ("locking")); handleRecurrence (); if (context.config.getBoolean ("complete.all.projects")) context.tdb.load (tasks); else context.tdb.loadPending (tasks); context.tdb.commit (); context.tdb.unlock (); // Apply filter. std::vector <Task> filtered; filter (tasks, filtered); // Scan all the tasks for their project name, building a map using project // names as keys. std::map <std::string, int> unique; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) unique[task->get ("project")] = 0; std::map <std::string, int>::iterator project; for (project = unique.begin (); project != unique.end (); ++project) if (project->first.length ()) output += project->first + "\n"; return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>TDB2<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the // // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #define L10N // Localization complete. #include <sstream> #include <Context.h> #include <ViewText.h> #include <text.h> #include <i18n.h> #include <main.h> #include <CmdProjects.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdProjects::CmdProjects () { _keyword = "projects"; _usage = "task projects [<filter>]"; _description = STRING_CMD_PROJECTS_USAGE; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdProjects::execute (std::string& output) { int rc = 0; // Get all the tasks. handleRecurrence (); std::vector <Task> tasks = context.tdb2.pending.get_tasks (); if (context.config.getBoolean ("list.all.projects")) { std::vector <Task> extra = context.tdb2.completed.get_tasks (); std::vector <Task>::iterator task; for (task = extra.begin (); task != extra.end (); ++task) tasks.push_back (*task); } int quantity = tasks.size (); context.tdb2.commit (); // Apply filter. std::vector <Task> filtered; filter (tasks, filtered); std::stringstream out; // Scan all the tasks for their project name, building a map using project // names as keys. std::map <std::string, int> unique; std::map <std::string, int> high; std::map <std::string, int> medium; std::map <std::string, int> low; std::map <std::string, int> none; bool no_project = false; std::string project; std::string priority; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { project = task->get ("project"); priority = task->get ("priority"); unique[project] += 1; if (project == "") no_project = true; if (priority == "H") high[project] += 1; else if (priority == "M") medium[project] += 1; else if (priority == "L") low[project] += 1; else none[project] += 1; } if (unique.size ()) { // Render a list of project names from the map. ViewText view; view.width (context.getWidth ()); view.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT)); view.add (Column::factory ("string.right", STRING_COLUMN_LABEL_TASKS)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_N)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_H)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_M)); view.add (Column::factory ("string.right", STRING_CMD_PROJECTS_PRI_L)); std::map <std::string, int>::iterator project; for (project = unique.begin (); project != unique.end (); ++project) { int row = view.addRow (); view.set (row, 0, (project->first == "" ? STRING_CMD_PROJECTS_NONE : project->first)); view.set (row, 1, project->second); view.set (row, 2, none[project->first]); view.set (row, 3, low[project->first]); view.set (row, 4, medium[project->first]); view.set (row, 5, high[project->first]); } int number_projects = unique.size (); if (no_project) --number_projects; out << optionalBlankLine () << view.render () << optionalBlankLine () << (number_projects == 1 ? format (STRING_CMD_PROJECTS_SUMMARY, number_projects) : format (STRING_CMD_PROJECTS_SUMMARY2, number_projects)) << " " << (quantity == 1 ? format (STRING_CMD_PROJECTS_TASK, quantity) : format (STRING_CMD_PROJECTS_TASKS, quantity)) << "\n"; } else { out << STRING_CMD_PROJECTS_NO << "\n"; rc = 1; } output = out.str (); return rc; } //////////////////////////////////////////////////////////////////////////////// CmdCompletionProjects::CmdCompletionProjects () { _keyword = "_projects"; _usage = "task _projects [<filter>]"; _description = STRING_CMD_PROJECTS_USAGE_2; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdCompletionProjects::execute (std::string& output) { // Get all the tasks. handleRecurrence (); std::vector <Task> tasks = context.tdb2.pending.get_tasks (); if (context.config.getBoolean ("list.all.projects")) { std::vector <Task> extra = context.tdb2.completed.get_tasks (); std::vector <Task>::iterator task; for (task = extra.begin (); task != extra.end (); ++task) tasks.push_back (*task); } context.tdb2.commit (); // Apply filter. std::vector <Task> filtered; filter (tasks, filtered); // Scan all the tasks for their project name, building a map using project // names as keys. std::map <std::string, int> unique; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) unique[task->get ("project")] = 0; std::map <std::string, int>::iterator project; for (project = unique.begin (); project != unique.end (); ++project) if (project->first.length ()) output += project->first + "\n"; return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Lukasz Wojciechowski <[email protected]> * * 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 Backtrace.cpp * @author Adam Malinowski <[email protected]> * @version 1.0 * @brief Implementation of backtrace utility class. */ #include <cxxabi.h> #include <elfutils/libdw.h> #include <inttypes.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sstream> #include <log/log.h> #include "Backtrace.h" namespace Cynara { Backtrace &Backtrace::getInstance(void) { static Backtrace m_instance; return m_instance; } const Dwfl_Callbacks Backtrace::m_callbacks = { dwfl_linux_proc_find_elf, dwfl_standard_find_debuginfo, nullptr, nullptr, }; Backtrace::Backtrace() { init(); } Backtrace::~Backtrace() { dwfl_end(m_dwfl); } void Backtrace::init(void) { m_dwfl = dwfl_begin(&m_callbacks); if (m_dwfl == nullptr) { LOGE("dwfl_begin failed! Source info won't be available in backtrace!"); return; } if (dwfl_linux_proc_report(m_dwfl, getpid())) { LOGE("dwfl_linux_proc_report failed! Source info won't be available in backtrace!"); dwfl_end(m_dwfl); m_dwfl = nullptr; } } void Backtrace::getSourceInfo(unw_word_t address, std::string &fileName, int &lineNumber) { fileName = "??"; lineNumber = 0; if (m_dwfl == nullptr) return; Dwarf_Addr addr = static_cast<Dwarf_Addr>(address); Dwfl_Module *module = dwfl_addrmodule(m_dwfl, addr); if (module == nullptr) return; Dwfl_Line *line = dwfl_module_getsrc(module, addr); if (line == nullptr) return; const char *src = dwfl_lineinfo(line, &addr, &lineNumber, nullptr, nullptr, nullptr); if (src == nullptr) return; const char *compilationDirectory = ""; const char *compilationDirectorySeparator = ""; if (src[0] != '/') { compilationDirectory = dwfl_line_comp_dir(line); if (compilationDirectory != NULL) compilationDirectorySeparator = "/"; } std::ostringstream fileNameStream; fileNameStream << compilationDirectory << compilationDirectorySeparator << src; fileName = fileNameStream.str(); } const std::string Backtrace::buildBacktrace(void) { std::ostringstream backtrace; unw_cursor_t cursor; unw_context_t uc; unw_word_t ip, sp; char proc_name[BUFSIZ]; unw_word_t offp; int status; std::string fileName; int lineNumber; unw_getcontext(&uc); // get rid of previous function: Backtrace::getBacktrace unw_init_local(&cursor, &uc); unw_step(&cursor); while (unw_step(&cursor) > 0) { unw_get_reg(&cursor, UNW_REG_IP, &ip); unw_get_reg(&cursor, UNW_REG_SP, &sp); unw_get_proc_name(&cursor, proc_name, sizeof(proc_name), &offp); char *realname = abi::__cxa_demangle(proc_name, 0, 0, &status); getSourceInfo(ip, fileName, lineNumber); backtrace << std::hex << "ip = 0x" << ip << ", sp = 0x" << sp << ", " << (realname ? realname : proc_name) << ", " << fileName << ":" << std::dec << lineNumber << std::endl; free(realname); } return backtrace.str(); } const std::string Backtrace::getBacktrace(void) { return getInstance().buildBacktrace(); } } /* namespace Cynara */ <commit_msg>Remove instruction & stack pointers from backtrace<commit_after>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Lukasz Wojciechowski <[email protected]> * * 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 Backtrace.cpp * @author Adam Malinowski <[email protected]> * @version 1.0 * @brief Implementation of backtrace utility class. */ #include <cxxabi.h> #include <elfutils/libdw.h> #include <inttypes.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sstream> #include <log/log.h> #include "Backtrace.h" namespace Cynara { Backtrace &Backtrace::getInstance(void) { static Backtrace m_instance; return m_instance; } const Dwfl_Callbacks Backtrace::m_callbacks = { dwfl_linux_proc_find_elf, dwfl_standard_find_debuginfo, nullptr, nullptr, }; Backtrace::Backtrace() { init(); } Backtrace::~Backtrace() { dwfl_end(m_dwfl); } void Backtrace::init(void) { m_dwfl = dwfl_begin(&m_callbacks); if (m_dwfl == nullptr) { LOGE("dwfl_begin failed! Source info won't be available in backtrace!"); return; } if (dwfl_linux_proc_report(m_dwfl, getpid())) { LOGE("dwfl_linux_proc_report failed! Source info won't be available in backtrace!"); dwfl_end(m_dwfl); m_dwfl = nullptr; } } void Backtrace::getSourceInfo(unw_word_t address, std::string &fileName, int &lineNumber) { fileName = "??"; lineNumber = 0; if (m_dwfl == nullptr) return; Dwarf_Addr addr = static_cast<Dwarf_Addr>(address); Dwfl_Module *module = dwfl_addrmodule(m_dwfl, addr); if (module == nullptr) return; Dwfl_Line *line = dwfl_module_getsrc(module, addr); if (line == nullptr) return; const char *src = dwfl_lineinfo(line, &addr, &lineNumber, nullptr, nullptr, nullptr); if (src == nullptr) return; const char *compilationDirectory = ""; const char *compilationDirectorySeparator = ""; if (src[0] != '/') { compilationDirectory = dwfl_line_comp_dir(line); if (compilationDirectory != NULL) compilationDirectorySeparator = "/"; } std::ostringstream fileNameStream; fileNameStream << compilationDirectory << compilationDirectorySeparator << src; fileName = fileNameStream.str(); } const std::string Backtrace::buildBacktrace(void) { std::ostringstream backtrace; unw_cursor_t cursor; unw_context_t uc; unw_word_t ip; char proc_name[BUFSIZ]; unw_word_t offp; int status; std::string fileName; int lineNumber; unw_getcontext(&uc); // get rid of previous function: Backtrace::getBacktrace unw_init_local(&cursor, &uc); unw_step(&cursor); while (unw_step(&cursor) > 0) { unw_get_reg(&cursor, UNW_REG_IP, &ip); unw_get_proc_name(&cursor, proc_name, sizeof(proc_name), &offp); char *realname = abi::__cxa_demangle(proc_name, 0, 0, &status); getSourceInfo(ip, fileName, lineNumber); backtrace << (realname ? realname : proc_name) << ", " << fileName << ":" << std::dec << lineNumber << std::endl; free(realname); } return backtrace.str(); } const std::string Backtrace::getBacktrace(void) { return getInstance().buildBacktrace(); } } /* namespace Cynara */ <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Sumit Jain <[email protected]> * Date: 07/21/2011 * * Geoorgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <[email protected]> <[email protected]> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "Win3D.h" #include "Jitter.h" using namespace Eigen; namespace yui { Win3D::Win3D() :GlutWindow(), mTrans(0.0,0.0,0.0), mEye(0.0,0.0,1.0), mZoom(1.0), mPersp(45.0), mRotate(false), mTranslate(false), mZooming(false) {} void Win3D::initWindow(int w, int h, const char* name) { GlutWindow::initWindow(w,h,name); int smaller = w<h?w:h; mTrackBall.setTrackball(Vector2d(w*0.5,h*0.5), smaller/2.5); } void Win3D::resize(int w, int h) { mWinWidth = w; mWinHeight = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, mWinWidth, mWinHeight); gluPerspective(mPersp, (double)mWinWidth/(double)mWinHeight, 0.1,10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); int small = w<h?w:h; mTrackBall.setCenter(Vector2d(w*0.5,h*0.5)); mTrackBall.setRadius(small/2.5); glutPostRedisplay(); } void Win3D::keyboard(unsigned char key, int x, int y) { switch(key){ case ',': // slow down mDisplayTimeout +=2; break; case '.': // speed up mDisplayTimeout -= 2; if( mDisplayTimeout <1 ) mDisplayTimeout = 1; break; case 'c': case 'C': // screen capture mCapture = !mCapture; break; case 27: //ESC exit(0); } glutPostRedisplay(); //printf("ascii key: %lu\n", key); } void Win3D::click(int button, int state, int x, int y) { mMouseDown = !mMouseDown; int mask = glutGetModifiers(); if(mMouseDown){ if(button == GLUT_LEFT_BUTTON){ if(mask == GLUT_ACTIVE_SHIFT) mZooming = true; else{ mRotate = true; mTrackBall.startBall(x,mWinHeight-y); } }else if(button == GLUT_RIGHT_BUTTON) mTranslate = true; mMouseX = x; mMouseY = y; }else{ mTranslate = false; mRotate = false; mZooming = false; } glutPostRedisplay(); } void Win3D::drag(int x, int y) { double deltaX = x - mMouseX; double deltaY = y - mMouseY; mMouseX = x; mMouseY = y; if(mRotate){ if(deltaX!=0 || deltaY!=0) mTrackBall.updateBall(x,mWinHeight-y); } if(mTranslate){ Matrix3d rot = mTrackBall.getRotationMatrix(); mTrans += rot.transpose()*Vector3d(deltaX, -deltaY, 0.0); } if(mZooming){ mZoom += deltaY*0.01; } glutPostRedisplay(); } void Win3D::render() { if(mCapture){ capturing(); glutSwapBuffers(); screenshot(); return; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(mPersp, (double)mWinWidth/(double)mWinHeight,0.1,10.0); gluLookAt(mEye[0],mEye[1],mEye[2],0.0,0.0,-1.0, 0.0,1.0,0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); initGL(); mTrackBall.applyGLRotation(); glEnable( GL_DEPTH_TEST ); glDisable( GL_TEXTURE_2D ); glDisable( GL_LIGHTING ); glLineWidth(2.0); if(mRotate || mTranslate || mZooming){ glColor3f( 1.0f, 0.0f, 0.0f ); glBegin( GL_LINES ); glVertex3f( -0.1f, 0.0f, -0.0f ); glVertex3f( 0.15f, 0.0f, -0.0f ); glEnd(); glColor3f( 0.0f, 1.0f, 0.0f ); glBegin( GL_LINES ); glVertex3f( 0.0f, -0.1f, 0.0f ); glVertex3f( 0.0f, 0.15f, 0.0f ); glEnd(); glColor3f( 0.0f, 0.0f, 1.0f ); glBegin( GL_LINES ); glVertex3f( 0.0f, 0.0f, -0.1f ); glVertex3f( 0.0f, 0.0f, 0.15f ); glEnd(); } glScalef(mZoom,mZoom,mZoom); glTranslatef(mTrans[0]*0.001, mTrans[1]*0.001, mTrans[2]*0.001); initLights(); draw(); if(mRotate) mTrackBall.draw(mWinWidth,mWinHeight); glutSwapBuffers(); } void Win3D::initGL() { glClearColor(mBackground[0],mBackground[1],mBackground[2],mBackground[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_POLYGON_SMOOTH); glShadeModel(GL_SMOOTH); glPolygonMode(GL_FRONT, GL_FILL); } void Win3D::initLights() { static float ambient[] = {0.2, 0.2, 0.2, 1.0}; static float diffuse[] = {0.6, 0.6, 0.6, 1.0}; static float front_mat_shininess[] = {60.0}; static float front_mat_specular[] = {0.2, 0.2, 0.2, 1.0}; static float front_mat_diffuse[] = {0.5, 0.28, 0.38, 1.0}; static float lmodel_ambient[] = {0.2, 0.2, 0.2, 1.0}; static float lmodel_twoside[] = {GL_FALSE}; GLfloat position[] = {1.0,0.0,0.0,0.0}; GLfloat position1[] = {-1.0,0.0,0.0,0.0}; glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_POSITION, position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside); glEnable( GL_LIGHT1); glLightfv(GL_LIGHT1,GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT1,GL_POSITION, position1); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_mat_shininess); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, front_mat_diffuse); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glDisable(GL_CULL_FACE); glEnable(GL_NORMALIZE); } void accFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearPlane, GLdouble farPlane, GLdouble pixdx, GLdouble pixdy, GLdouble eyedx, GLdouble eyedy, GLdouble focus) { GLdouble xwsize, ywsize; GLdouble dx, dy; GLint viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); xwsize = right - left; ywsize = top - bottom; dx = -(pixdx*xwsize/(GLdouble) viewport[2] + eyedx * nearPlane / focus); dy = -(pixdy*ywsize/(GLdouble) viewport[3] + eyedy*nearPlane/focus); glFrustum (left + dx, right + dx, bottom + dy, top + dy, nearPlane, farPlane); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef (-eyedx, -eyedy, 0.0); } void accPerspective(GLdouble fovy, GLdouble aspect, GLdouble nearPlane, GLdouble farPlane, GLdouble pixdx, GLdouble pixdy, GLdouble eyedx, GLdouble eyedy, GLdouble focus) { GLdouble fov2,left,right,bottom,top; fov2 = ((fovy*M_PI) / 180.0) / 2.0; top = nearPlane / (cosf(fov2) / sinf(fov2)); bottom = -top; right = top * aspect; left = -right; accFrustum (left, right, bottom, top, nearPlane, farPlane, pixdx, pixdy, eyedx, eyedy, focus); } void Win3D::capturing() { glClear(GL_ACCUM_BUFFER_BIT); for(int jitter=0; jitter<4; jitter++){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); accPerspective(mPersp, (double)mWinWidth/mWinHeight,0.1,10.0, j4[jitter].x, j4[jitter].y, 0.0, 0.0, 1.0); gluLookAt(mEye[0], mEye[1], mEye[2],0.0,0.0,-1.0,0.0,1.0,0.0); initGL(); mTrackBall.applyGLRotation(); glScalef(mZoom,mZoom,mZoom); glTranslatef(mTrans[0]*0.001, mTrans[1]*0.001, mTrans[2]*0.001); initLights(); draw(); glAccum(GL_ACCUM, 0.25); } glAccum( GL_RETURN, 1.0); } } // namespace yui <commit_msg>Use middle mouse to translate and mousewheel to zoom<commit_after>/* * Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Sumit Jain <[email protected]> * Date: 07/21/2011 * * Geoorgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <[email protected]> <[email protected]> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "Win3D.h" #include "Jitter.h" using namespace Eigen; namespace yui { Win3D::Win3D() :GlutWindow(), mTrans(0.0,0.0,0.0), mEye(0.0,0.0,1.0), mZoom(1.0), mPersp(45.0), mRotate(false), mTranslate(false), mZooming(false) {} void Win3D::initWindow(int w, int h, const char* name) { GlutWindow::initWindow(w,h,name); int smaller = w<h?w:h; mTrackBall.setTrackball(Vector2d(w*0.5,h*0.5), smaller/2.5); } void Win3D::resize(int w, int h) { mWinWidth = w; mWinHeight = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, mWinWidth, mWinHeight); gluPerspective(mPersp, (double)mWinWidth/(double)mWinHeight, 0.1,10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); int small = w<h?w:h; mTrackBall.setCenter(Vector2d(w*0.5,h*0.5)); mTrackBall.setRadius(small/2.5); glutPostRedisplay(); } void Win3D::keyboard(unsigned char key, int x, int y) { switch(key){ case ',': // slow down mDisplayTimeout +=2; break; case '.': // speed up mDisplayTimeout -= 2; if( mDisplayTimeout <1 ) mDisplayTimeout = 1; break; case 'c': case 'C': // screen capture mCapture = !mCapture; break; case 27: //ESC exit(0); } glutPostRedisplay(); //printf("ascii key: %lu\n", key); } void Win3D::click(int button, int state, int x, int y) { mMouseDown = !mMouseDown; int mask = glutGetModifiers(); if(mMouseDown){ if(button == GLUT_LEFT_BUTTON){ if(mask == GLUT_ACTIVE_SHIFT) mZooming = true; else{ mRotate = true; mTrackBall.startBall(x,mWinHeight-y); } }else if(button == GLUT_RIGHT_BUTTON || button == GLUT_MIDDLE_BUTTON) { mTranslate = true; } else if (button == 3 && state == GLUT_DOWN) { // mouse wheel up // each scroll generates a down and an immediate up, // so ignore ups mZoom += 0.1; } else if (button == 4 && state == GLUT_DOWN) { // mouse wheel down? // each scroll generates a down and an immediate up, // so ignore ups mZoom -= 0.1; } mMouseX = x; mMouseY = y; }else{ mTranslate = false; mRotate = false; mZooming = false; } glutPostRedisplay(); } void Win3D::drag(int x, int y) { double deltaX = x - mMouseX; double deltaY = y - mMouseY; mMouseX = x; mMouseY = y; if(mRotate){ if(deltaX!=0 || deltaY!=0) mTrackBall.updateBall(x,mWinHeight-y); } if(mTranslate){ Matrix3d rot = mTrackBall.getRotationMatrix(); mTrans += rot.transpose()*Vector3d(deltaX, -deltaY, 0.0); } if(mZooming){ mZoom += deltaY*0.01; } glutPostRedisplay(); } void Win3D::render() { if(mCapture){ capturing(); glutSwapBuffers(); screenshot(); return; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(mPersp, (double)mWinWidth/(double)mWinHeight,0.1,10.0); gluLookAt(mEye[0],mEye[1],mEye[2],0.0,0.0,-1.0, 0.0,1.0,0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); initGL(); mTrackBall.applyGLRotation(); glEnable( GL_DEPTH_TEST ); glDisable( GL_TEXTURE_2D ); glDisable( GL_LIGHTING ); glLineWidth(2.0); if(mRotate || mTranslate || mZooming){ glColor3f( 1.0f, 0.0f, 0.0f ); glBegin( GL_LINES ); glVertex3f( -0.1f, 0.0f, -0.0f ); glVertex3f( 0.15f, 0.0f, -0.0f ); glEnd(); glColor3f( 0.0f, 1.0f, 0.0f ); glBegin( GL_LINES ); glVertex3f( 0.0f, -0.1f, 0.0f ); glVertex3f( 0.0f, 0.15f, 0.0f ); glEnd(); glColor3f( 0.0f, 0.0f, 1.0f ); glBegin( GL_LINES ); glVertex3f( 0.0f, 0.0f, -0.1f ); glVertex3f( 0.0f, 0.0f, 0.15f ); glEnd(); } glScalef(mZoom,mZoom,mZoom); glTranslatef(mTrans[0]*0.001, mTrans[1]*0.001, mTrans[2]*0.001); initLights(); draw(); if(mRotate) mTrackBall.draw(mWinWidth,mWinHeight); glutSwapBuffers(); } void Win3D::initGL() { glClearColor(mBackground[0],mBackground[1],mBackground[2],mBackground[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_POLYGON_SMOOTH); glShadeModel(GL_SMOOTH); glPolygonMode(GL_FRONT, GL_FILL); } void Win3D::initLights() { static float ambient[] = {0.2, 0.2, 0.2, 1.0}; static float diffuse[] = {0.6, 0.6, 0.6, 1.0}; static float front_mat_shininess[] = {60.0}; static float front_mat_specular[] = {0.2, 0.2, 0.2, 1.0}; static float front_mat_diffuse[] = {0.5, 0.28, 0.38, 1.0}; static float lmodel_ambient[] = {0.2, 0.2, 0.2, 1.0}; static float lmodel_twoside[] = {GL_FALSE}; GLfloat position[] = {1.0,0.0,0.0,0.0}; GLfloat position1[] = {-1.0,0.0,0.0,0.0}; glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_POSITION, position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside); glEnable( GL_LIGHT1); glLightfv(GL_LIGHT1,GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT1,GL_POSITION, position1); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_mat_shininess); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, front_mat_diffuse); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glDisable(GL_CULL_FACE); glEnable(GL_NORMALIZE); } void accFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearPlane, GLdouble farPlane, GLdouble pixdx, GLdouble pixdy, GLdouble eyedx, GLdouble eyedy, GLdouble focus) { GLdouble xwsize, ywsize; GLdouble dx, dy; GLint viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); xwsize = right - left; ywsize = top - bottom; dx = -(pixdx*xwsize/(GLdouble) viewport[2] + eyedx * nearPlane / focus); dy = -(pixdy*ywsize/(GLdouble) viewport[3] + eyedy*nearPlane/focus); glFrustum (left + dx, right + dx, bottom + dy, top + dy, nearPlane, farPlane); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef (-eyedx, -eyedy, 0.0); } void accPerspective(GLdouble fovy, GLdouble aspect, GLdouble nearPlane, GLdouble farPlane, GLdouble pixdx, GLdouble pixdy, GLdouble eyedx, GLdouble eyedy, GLdouble focus) { GLdouble fov2,left,right,bottom,top; fov2 = ((fovy*M_PI) / 180.0) / 2.0; top = nearPlane / (cosf(fov2) / sinf(fov2)); bottom = -top; right = top * aspect; left = -right; accFrustum (left, right, bottom, top, nearPlane, farPlane, pixdx, pixdy, eyedx, eyedy, focus); } void Win3D::capturing() { glClear(GL_ACCUM_BUFFER_BIT); for(int jitter=0; jitter<4; jitter++){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); accPerspective(mPersp, (double)mWinWidth/mWinHeight,0.1,10.0, j4[jitter].x, j4[jitter].y, 0.0, 0.0, 1.0); gluLookAt(mEye[0], mEye[1], mEye[2],0.0,0.0,-1.0,0.0,1.0,0.0); initGL(); mTrackBall.applyGLRotation(); glScalef(mZoom,mZoom,mZoom); glTranslatef(mTrans[0]*0.001, mTrans[1]*0.001, mTrans[2]*0.001); initLights(); draw(); glAccum(GL_ACCUM, 0.25); } glAccum( GL_RETURN, 1.0); } } // namespace yui <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file TestEvalHeuristic.cpp * @author Peter Schueller <[email protected]> * * @brief Test evaluation heuristics */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex2/EvalGraphBuilder.h" #include "dlvhex2/EvalHeuristicOldDlvhex.h" #include "dlvhex2/HexParser.h" #include "dlvhex2/ProgramCtx.h" #include "dlvhex2/Printer.h" #include "dlvhex2/Registry.h" #include "dlvhex2/PluginInterface.h" #include "dlvhex2/DependencyGraph.h" #include "dlvhex2/ComponentGraph.h" #include "dlvhex2/ASPSolverManager.h" // this must be included before dummytypes! #define BOOST_TEST_MODULE __FILE__ #include <boost/test/unit_test.hpp> #include "fixturesExt1.h" #include "fixturesMCS.h" #include "graphviz.h" #include <iostream> #include <fstream> #include <cstdlib> #define LOG_REGISTRY_PROGRAM(ctx) \ ctx.registry()->logContents(); \ RawPrinter printer(std::cerr, ctx.registry()); \ LOG(INFO,"edb"); \ printer.printmany(ctx.edb,"\n"); \ std::cerr << std::endl; \ LOG(INFO,"edb end"); \ LOG(INFO,"idb"); \ printer.printmany(ctx.idb,"\n"); \ std::cerr << std::endl; \ LOG(INFO,"idb end"); LOG_INIT(Logger::ERROR | Logger::WARNING) DLVHEX_NAMESPACE_USE BOOST_FIXTURE_TEST_CASE(testEvalHeuristicExt1,ProgramExt1ProgramCtxDependencyGraphComponentGraphFixture) { // eval graph FinalEvalGraph eg; // write to dotfile and create pdf { const char* fnamev = "testEvalHeurExt1CGVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurExt1CGTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } // // now the real testing starts // // create "final" (for a lack of a better name) eval graph { LOG(INFO,"starting to build eval graph"); // create builder that supervises the construction of eg ASPSolverManager::SoftwareConfigurationPtr extEvalConfig; EvalGraphBuilder egbuilder(ctx, compgraph, eg, extEvalConfig); { // create heuristic, which sends commands to egbuilder EvalHeuristicOldDlvhex heuristicOldDlvhex; heuristicOldDlvhex.build(egbuilder); LOG(INFO,"building eval graph finished"); // log the (changed) component graph { const char* fnamev = "testEvalHeurExt1Verbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurExt1Terse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } LOG(INFO,"eval heuristic going out of scope"); } LOG(INFO,"eval graph builder going out of scope"); } // TODO check eval graph } // example using MCS-IE encoding from KR 2010 for calculation of equilibria in medical example BOOST_FIXTURE_TEST_CASE(testEvalHeuristicMCSMedEQ,ProgramMCSMedEQProgramCtxDependencyGraphComponentGraphFixture) { // eval graph FinalEvalGraph eg; // write ComponentGraph to dotfile and create pdf { const char* fnamev = "testEvalHeurMCSMedEqCGVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedEqCGTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } // // now the real testing starts // // create "final" (for a lack of a better name) eval graph { LOG(INFO,"starting to build eval graph"); // create builder that supervises the construction of eg ASPSolverManager::SoftwareConfigurationPtr extEvalConfig; EvalGraphBuilder egbuilder(ctx, compgraph, eg, extEvalConfig); { // create heuristic, which sends commands to egbuilder EvalHeuristicOldDlvhex heuristicOldDlvhex; heuristicOldDlvhex.build(egbuilder); LOG(INFO,"building eval graph finished"); // log the (changed) component graph { const char* fnamev = "testEvalHeurMCSMedEqVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedEqTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } LOG(INFO,"eval heuristic going out of scope"); } LOG(INFO,"eval graph builder going out of scope"); } // TODO check eval graph } // example using MCS-IE encoding from KR 2010 for calculation of diagnoses in medical example BOOST_FIXTURE_TEST_CASE(testEvalHeuristicMCSMedD,ProgramMCSMedDProgramCtxDependencyGraphComponentGraphFixture) { // eval graph FinalEvalGraph eg; // write ComponentGraph to dotfile and create pdf { const char* fnamev = "testEvalHeurMCSMedDCGVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedDCGTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } // // now the real testing starts // // create "final" (for a lack of a better name) eval graph { LOG(INFO,"starting to build eval graph"); // create builder that supervises the construction of eg ASPSolverManager::SoftwareConfigurationPtr extEvalConfig; EvalGraphBuilder egbuilder(ctx, compgraph, eg, extEvalConfig); { // create heuristic, which sends commands to egbuilder EvalHeuristicOldDlvhex heuristicOldDlvhex; heuristicOldDlvhex.build(egbuilder); LOG(INFO,"building eval graph finished"); // log the (changed) component graph { const char* fnamev = "testEvalHeurMCSMedDVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedDTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } LOG(INFO,"eval heuristic going out of scope"); } LOG(INFO,"eval graph builder going out of scope"); } // TODO check eval graph } #if 0 // naive test approach: take all leaf components and collapse them, // then take all components "behind" this collapsed component // * this creates a path // * is stupid, but it should be allowed // * this tests the dependency checking mechanism const ComponentGraph::SCCMap& sccMembers = compgraph.getSCCMembers(); const ComponentGraph::ComponentMap& scc = compgraph.getSCC(); while( !egbuilder.getRestLeaves().empty() ) { typedef ComponentGraph::Node Node; std::list<Node> leaves; // go through all nodes and collect components ComponentGraph::LeafContainer::const_iterator itl; for(itl = egbuilder.getRestLeaves().begin(); itl != egbuilder.getRestLeaves().end(); ++itl) { const std::set<Node>& thisSCC = sccMembers[scc[*itl]]; LOG(INFO,"for leaf " << *itl << " adding nodes " << printset(thisSCC)); leaves.insert(leaves.end(), thisSCC.begin(), thisSCC.end()); } LOG(INFO,"got leaves to add: " << printvector(std::vector<Node>(leaves.begin(), leaves.end()))); // enrich set of leaves by taking all nodes in the same component // collect dependencies from leaves to existing eval units assert(false); } #endif <commit_msg>removing deprecated comments<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file TestEvalHeuristic.cpp * @author Peter Schueller <[email protected]> * * @brief Test evaluation heuristics */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex2/EvalGraphBuilder.h" #include "dlvhex2/EvalHeuristicOldDlvhex.h" #include "dlvhex2/HexParser.h" #include "dlvhex2/ProgramCtx.h" #include "dlvhex2/Printer.h" #include "dlvhex2/Registry.h" #include "dlvhex2/PluginInterface.h" #include "dlvhex2/DependencyGraph.h" #include "dlvhex2/ComponentGraph.h" #include "dlvhex2/ASPSolverManager.h" // this must be included before dummytypes! #define BOOST_TEST_MODULE __FILE__ #include <boost/test/unit_test.hpp> #include "fixturesExt1.h" #include "fixturesMCS.h" #include "graphviz.h" #include <iostream> #include <fstream> #include <cstdlib> #define LOG_REGISTRY_PROGRAM(ctx) \ ctx.registry()->logContents(); \ RawPrinter printer(std::cerr, ctx.registry()); \ LOG(INFO,"edb"); \ printer.printmany(ctx.edb,"\n"); \ std::cerr << std::endl; \ LOG(INFO,"edb end"); \ LOG(INFO,"idb"); \ printer.printmany(ctx.idb,"\n"); \ std::cerr << std::endl; \ LOG(INFO,"idb end"); LOG_INIT(Logger::ERROR | Logger::WARNING) DLVHEX_NAMESPACE_USE BOOST_FIXTURE_TEST_CASE(testEvalHeuristicExt1,ProgramExt1ProgramCtxDependencyGraphComponentGraphFixture) { // eval graph FinalEvalGraph eg; // write to dotfile and create pdf { const char* fnamev = "testEvalHeurExt1CGVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurExt1CGTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } // // now the real testing starts // // create "final" (for a lack of a better name) eval graph { LOG(INFO,"starting to build eval graph"); // create builder that supervises the construction of eg ASPSolverManager::SoftwareConfigurationPtr extEvalConfig; EvalGraphBuilder egbuilder(ctx, compgraph, eg, extEvalConfig); { // create heuristic, which sends commands to egbuilder EvalHeuristicOldDlvhex heuristicOldDlvhex; heuristicOldDlvhex.build(egbuilder); LOG(INFO,"building eval graph finished"); // log the (changed) component graph { const char* fnamev = "testEvalHeurExt1Verbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurExt1Terse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } LOG(INFO,"eval heuristic going out of scope"); } LOG(INFO,"eval graph builder going out of scope"); } // TODO check eval graph } // example using MCS-IE encoding from KR 2010 for calculation of equilibria in medical example BOOST_FIXTURE_TEST_CASE(testEvalHeuristicMCSMedEQ,ProgramMCSMedEQProgramCtxDependencyGraphComponentGraphFixture) { // eval graph FinalEvalGraph eg; // write ComponentGraph to dotfile and create pdf { const char* fnamev = "testEvalHeurMCSMedEqCGVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedEqCGTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } // // now the real testing starts // // create "final" (for a lack of a better name) eval graph { LOG(INFO,"starting to build eval graph"); // create builder that supervises the construction of eg ASPSolverManager::SoftwareConfigurationPtr extEvalConfig; EvalGraphBuilder egbuilder(ctx, compgraph, eg, extEvalConfig); { // create heuristic, which sends commands to egbuilder EvalHeuristicOldDlvhex heuristicOldDlvhex; heuristicOldDlvhex.build(egbuilder); LOG(INFO,"building eval graph finished"); // log the (changed) component graph { const char* fnamev = "testEvalHeurMCSMedEqVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedEqTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } LOG(INFO,"eval heuristic going out of scope"); } LOG(INFO,"eval graph builder going out of scope"); } // TODO check eval graph } // example using MCS-IE encoding from KR 2010 for calculation of diagnoses in medical example BOOST_FIXTURE_TEST_CASE(testEvalHeuristicMCSMedD,ProgramMCSMedDProgramCtxDependencyGraphComponentGraphFixture) { // eval graph FinalEvalGraph eg; // write ComponentGraph to dotfile and create pdf { const char* fnamev = "testEvalHeurMCSMedDCGVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedDCGTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } // // now the real testing starts // // create "final" (for a lack of a better name) eval graph { LOG(INFO,"starting to build eval graph"); // create builder that supervises the construction of eg ASPSolverManager::SoftwareConfigurationPtr extEvalConfig; EvalGraphBuilder egbuilder(ctx, compgraph, eg, extEvalConfig); { // create heuristic, which sends commands to egbuilder EvalHeuristicOldDlvhex heuristicOldDlvhex; heuristicOldDlvhex.build(egbuilder); LOG(INFO,"building eval graph finished"); // log the (changed) component graph { const char* fnamev = "testEvalHeurMCSMedDVerbose.dot"; LOG(INFO,"dumping verbose graph to " << fnamev); std::ofstream filev(fnamev); compgraph.writeGraphViz(filev, true); makeGraphVizPdf(fnamev); const char* fnamet = "testEvalHeurMCSMedDTerse.dot"; LOG(INFO,"dumping terse graph to " << fnamet); std::ofstream filet(fnamet); compgraph.writeGraphViz(filet, false); makeGraphVizPdf(fnamet); } LOG(INFO,"eval heuristic going out of scope"); } LOG(INFO,"eval graph builder going out of scope"); } // TODO check eval graph } <|endoftext|>
<commit_before>/** * Touhou Community Reliant Automatic Patcher * Tasogare Frontier support plugin * * ---- * * On-the-fly th175 pl patcher */ #include <thcrap.h> #include "thcrap_tasofro.h" static void copy_line(const char*& file_in, const char *file_in_end, char*& file_out) { const char *search_end = std::find(file_in, file_in_end, '\n'); if (search_end != file_in_end) search_end++; file_out = std::copy(file_in, search_end, file_out); file_in = search_end; } static void copy_text_line(const char*& file_in, const char *file_in_end, char*& file_out) { const char *search_end = std::find(file_in + 1, file_in_end, '"'); if (search_end != file_in_end) search_end++; file_out = std::copy(file_in, search_end, file_out); file_in = search_end; copy_line(file_in, file_in_end, file_out); } static void patch_text_line(const char*& file_in, const char *file_in_end, char*& file_out, const std::string& rep) { // Skip original text in input file_in = std::find(file_in + 1, file_in_end, '"'); if (file_in != file_in_end) file_in++; *file_out = '"'; file_out++; // TODO: escape quotes file_out = std::copy(rep.begin(), rep.end(), file_out); memcpy(file_out, "@\"", 2); file_out += 2; copy_line(file_in, file_in_end, file_out); } int patch_th175_pl(void *file_inout, size_t, size_t size_in, const char *, json_t *patch) { if (!patch) { return 0; } auto file_in_storage = std::make_unique<char[]>(size_in); std::copy((char*)file_inout, ((char*)file_inout) + size_in, file_in_storage.get()); const char *file_in = file_in_storage.get(); const char *file_in_end = file_in + size_in; char *file_out = (char*)file_inout; unsigned int line_num = 1; while (file_in < file_in_end) { if (*file_in != '"') { copy_line(file_in, file_in_end, file_out); continue; } json_t *rep = json_object_numkey_get(patch, line_num); line_num++; rep = json_object_get(rep, "lines"); if (!rep) { copy_text_line(file_in, file_in_end, file_out); continue; } std::string rep_string; json_t *value; json_flex_array_foreach_scoped(size_t, i, rep, value) { if (!rep_string.empty()) { rep_string += '\n'; } rep_string += json_string_value(value); } patch_text_line(file_in, file_in_end, file_out, rep_string); } #if 0 std::filesystem::path dir = std::filesystem::absolute(fn); dir.remove_filename(); std::filesystem::create_directories(dir); std::ofstream f(fn, std::ios::binary); f.write((char*)file_inout, size_out); f.close(); #endif return 1; } <commit_msg>thcrap_tasofro: th175: escape quotes in pl patching<commit_after>/** * Touhou Community Reliant Automatic Patcher * Tasogare Frontier support plugin * * ---- * * On-the-fly th175 pl patcher */ #include <thcrap.h> #include "thcrap_tasofro.h" static void copy_line(const char*& file_in, const char *file_in_end, char*& file_out) { const char *search_end = std::find(file_in, file_in_end, '\n'); if (search_end != file_in_end) search_end++; file_out = std::copy(file_in, search_end, file_out); file_in = search_end; } static void copy_text_line(const char*& file_in, const char *file_in_end, char*& file_out) { const char *search_end = std::find(file_in + 1, file_in_end, '"'); if (search_end != file_in_end) search_end++; file_out = std::copy(file_in, search_end, file_out); file_in = search_end; copy_line(file_in, file_in_end, file_out); } static void patch_text_line(const char*& file_in, const char *file_in_end, char*& file_out, const std::string& rep) { // Skip original text in input file_in = std::find(file_in + 1, file_in_end, '"'); if (file_in != file_in_end) file_in++; *file_out = '"'; file_out++; for (char c : rep) { if (c == '"') { *file_out = '"'; file_out++; } *file_out = c; file_out++; } memcpy(file_out, "@\"", 2); file_out += 2; copy_line(file_in, file_in_end, file_out); } int patch_th175_pl(void *file_inout, size_t, size_t size_in, const char *, json_t *patch) { if (!patch) { return 0; } auto file_in_storage = std::make_unique<char[]>(size_in); std::copy((char*)file_inout, ((char*)file_inout) + size_in, file_in_storage.get()); const char *file_in = file_in_storage.get(); const char *file_in_end = file_in + size_in; char *file_out = (char*)file_inout; unsigned int line_num = 1; while (file_in < file_in_end) { if (*file_in != '"') { copy_line(file_in, file_in_end, file_out); continue; } json_t *rep = json_object_numkey_get(patch, line_num); line_num++; rep = json_object_get(rep, "lines"); if (!rep) { copy_text_line(file_in, file_in_end, file_out); continue; } std::string rep_string; json_t *value; json_flex_array_foreach_scoped(size_t, i, rep, value) { if (!rep_string.empty()) { rep_string += '\n'; } rep_string += json_string_value(value); } patch_text_line(file_in, file_in_end, file_out, rep_string); } #if 0 std::filesystem::path dir = std::filesystem::absolute(fn); dir.remove_filename(); std::filesystem::create_directories(dir); std::ofstream f(fn, std::ios::binary); f.write((char*)file_inout, size_out); f.close(); #endif return 1; } <|endoftext|>
<commit_before>/* libs/graphics/sgl/SkScan_Hairline.cpp ** ** Copyright 2006, The Android Open Source Project ** ** 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 "SkScan.h" #include "SkBlitter.h" #include "SkRegion.h" #include "SkFDot6.h" #include "SkLineClipper.h" static void horiline(int x, int stopx, SkFixed fy, SkFixed dy, SkBlitter* blitter) { SkASSERT(x < stopx); do { blitter->blitH(x, fy >> 16, 1); fy += dy; } while (++x < stopx); } static void vertline(int y, int stopy, SkFixed fx, SkFixed dx, SkBlitter* blitter) { SkASSERT(y < stopy); do { blitter->blitH(fx >> 16, y, 1); fx += dx; } while (++y < stopy); } void SkScan::HairLine(const SkPoint& pt0, const SkPoint& pt1, const SkRegion* clip, SkBlitter* blitter) { SkBlitterClipper clipper; SkRect r; SkIRect clipR, ptsR; SkPoint pts[2] = { pt0, pt1 }; if (clip) { // Perform a clip in scalar space, so we catch huge values which might // be missed after we convert to SkFDot6 (overflow) r.set(clip->getBounds()); if (!SkLineClipper::IntersectLine(pts, r, pts)) { return; } } SkFDot6 x0 = SkScalarToFDot6(pts[0].fX); SkFDot6 y0 = SkScalarToFDot6(pts[0].fY); SkFDot6 x1 = SkScalarToFDot6(pts[1].fX); SkFDot6 y1 = SkScalarToFDot6(pts[1].fY); if (clip) { // now perform clipping again, as the rounding to dot6 can wiggle us // our rects are really dot6 rects, but since we've already used // lineclipper, we know they will fit in 32bits (26.6) const SkIRect& bounds = clip->getBounds(); clipR.set(SkIntToFDot6(bounds.fLeft), SkIntToFDot6(bounds.fTop), SkIntToFDot6(bounds.fRight), SkIntToFDot6(bounds.fBottom)); ptsR.set(x0, y0, x1, y1); ptsR.sort(); // outset the right and bottom, to account for how hairlines are // actually drawn, which may hit the pixel to the right or below of // the coordinate ptsR.fRight += SK_FDot6One; ptsR.fBottom += SK_FDot6One; if (!SkIRect::Intersects(ptsR, clipR)) { return; } if (clip->isRect() && clipR.contains(ptsR)) { clip = NULL; } else { blitter = clipper.apply(blitter, clip); } } SkFDot6 dx = x1 - x0; SkFDot6 dy = y1 - y0; if (SkAbs32(dx) > SkAbs32(dy)) // mostly horizontal { if (x0 > x1) // we want to go left-to-right { SkTSwap<SkFDot6>(x0, x1); SkTSwap<SkFDot6>(y0, y1); } int ix0 = SkFDot6Round(x0); int ix1 = SkFDot6Round(x1); if (ix0 == ix1) // too short to draw return; SkFixed slope = SkFixedDiv(dy, dx); SkFixed startY = SkFDot6ToFixed(y0) + (slope * ((32 - x0) & 63) >> 6); horiline(ix0, ix1, startY, slope, blitter); } else // mostly vertical { if (y0 > y1) // we want to go top-to-bottom { SkTSwap<SkFDot6>(x0, x1); SkTSwap<SkFDot6>(y0, y1); } int iy0 = SkFDot6Round(y0); int iy1 = SkFDot6Round(y1); if (iy0 == iy1) // too short to draw return; SkFixed slope = SkFixedDiv(dx, dy); SkFixed startX = SkFDot6ToFixed(x0) + (slope * ((32 - y0) & 63) >> 6); vertline(iy0, iy1, startX, slope, blitter); } } // we don't just draw 4 lines, 'cause that can leave a gap in the bottom-right // and double-hit the top-left. // TODO: handle huge coordinates on rect (before calling SkScalarToFixed) void SkScan::HairRect(const SkRect& rect, const SkRegion* clip, SkBlitter* blitter) { SkBlitterClipper clipper; SkIRect r; r.set(SkScalarToFixed(rect.fLeft) >> 16, SkScalarToFixed(rect.fTop) >> 16, (SkScalarToFixed(rect.fRight) >> 16) + 1, (SkScalarToFixed(rect.fBottom) >> 16) + 1); if (clip) { if (clip->quickReject(r)) return; if (!clip->quickContains(r)) blitter = clipper.apply(blitter, clip); } int width = r.width(); int height = r.height(); if ((width | height) == 0) return; if (width <= 2 || height <= 2) { blitter->blitRect(r.fLeft, r.fTop, width, height); return; } // if we get here, we know we have 4 segments to draw blitter->blitH(r.fLeft, r.fTop, width); // top blitter->blitRect(r.fLeft, r.fTop + 1, 1, height - 2); // left blitter->blitRect(r.fRight - 1, r.fTop + 1, 1, height - 2); // right blitter->blitH(r.fLeft, r.fBottom - 1, width); // bottom } ///////////////////////////////////////////////////////////////////////////////////////////////// #include "SkPath.h" #include "SkGeometry.h" static bool quad_too_curvy(const SkPoint pts[3]) { return true; } static int compute_int_quad_dist(const SkPoint pts[3]) { // compute the vector between the control point ([1]) and the middle of the // line connecting the start and end ([0] and [2]) SkScalar dx = SkScalarHalf(pts[0].fX + pts[2].fX) - pts[1].fX; SkScalar dy = SkScalarHalf(pts[0].fY + pts[2].fY) - pts[1].fY; // we want everyone to be positive dx = SkScalarAbs(dx); dy = SkScalarAbs(dy); // convert to whole pixel values (use ceiling to be conservative) int idx = SkScalarCeil(dx); int idy = SkScalarCeil(dy); // use the cheap approx for distance if (idx > idy) { return idx + (idy >> 1); } else { return idy + (idx >> 1); } } static void hairquad(const SkPoint pts[3], const SkRegion* clip, SkBlitter* blitter, int level, void (*lineproc)(const SkPoint&, const SkPoint&, const SkRegion* clip, SkBlitter*)) { #if 1 if (level > 0 && quad_too_curvy(pts)) { SkPoint tmp[5]; SkChopQuadAtHalf(pts, tmp); hairquad(tmp, clip, blitter, level - 1, lineproc); hairquad(&tmp[2], clip, blitter, level - 1, lineproc); } else lineproc(pts[0], pts[2], clip, blitter); #else int count = 1 << level; const SkScalar dt = SkFixedToScalar(SK_Fixed1 >> level); SkScalar t = dt; SkPoint prevPt = pts[0]; for (int i = 1; i < count; i++) { SkPoint nextPt; SkEvalQuadAt(pts, t, &nextPt); lineproc(prevPt, nextPt, clip, blitter); t += dt; prevPt = nextPt; } // draw the last line explicitly to 1.0, in case t didn't match that exactly lineproc(prevPt, pts[2], clip, blitter); #endif } static bool cubic_too_curvy(const SkPoint pts[4]) { return true; } static void haircubic(const SkPoint pts[4], const SkRegion* clip, SkBlitter* blitter, int level, void (*lineproc)(const SkPoint&, const SkPoint&, const SkRegion*, SkBlitter*)) { if (level > 0 && cubic_too_curvy(pts)) { SkPoint tmp[7]; SkChopCubicAt(pts, tmp, SK_Scalar1/2); haircubic(tmp, clip, blitter, level - 1, lineproc); haircubic(&tmp[3], clip, blitter, level - 1, lineproc); } else lineproc(pts[0], pts[3], clip, blitter); } #define kMaxCubicSubdivideLevel 6 #define kMaxQuadSubdivideLevel 5 static void hair_path(const SkPath& path, const SkRegion* clip, SkBlitter* blitter, void (*lineproc)(const SkPoint&, const SkPoint&, const SkRegion*, SkBlitter*)) { if (path.isEmpty()) return; const SkIRect* clipR = NULL; if (clip) { SkIRect ibounds; path.getBounds().roundOut(&ibounds); ibounds.inset(-1, -1); if (clip->quickReject(ibounds)) return; if (clip->quickContains(ibounds)) clip = NULL; else clipR = &clip->getBounds(); } SkPath::Iter iter(path, false); SkPoint pts[4]; SkPath::Verb verb; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kLine_Verb: lineproc(pts[0], pts[1], clip, blitter); break; case SkPath::kQuad_Verb: { int d = compute_int_quad_dist(pts); /* quadratics approach the line connecting their start and end points 4x closer with each subdivision, so we compute the number of subdivisions to be the minimum need to get that distance to be less than a pixel. */ int level = (33 - SkCLZ(d)) >> 1; // SkDebugf("----- distance %d computedLevel %d\n", d, computedLevel); // sanity check on level (from the previous version) if (level > kMaxQuadSubdivideLevel) { level = kMaxQuadSubdivideLevel; } hairquad(pts, clip, blitter, level, lineproc); break; } case SkPath::kCubic_Verb: haircubic(pts, clip, blitter, kMaxCubicSubdivideLevel, lineproc); break; default: break; } } } void SkScan::HairPath(const SkPath& path, const SkRegion* clip, SkBlitter* blitter) { hair_path(path, clip, blitter, SkScan::HairLine); } void SkScan::AntiHairPath(const SkPath& path, const SkRegion* clip, SkBlitter* blitter) { hair_path(path, clip, blitter, SkScan::AntiHairLine); } /////////////////////////////////////////////////////////////////////////////// void SkScan::FrameRect(const SkRect& r, const SkPoint& strokeSize, const SkRegion* clip, SkBlitter* blitter) { SkASSERT(strokeSize.fX >= 0 && strokeSize.fY >= 0); if (strokeSize.fX < 0 || strokeSize.fY < 0) { return; } const SkScalar dx = strokeSize.fX; const SkScalar dy = strokeSize.fY; SkScalar rx = SkScalarHalf(dx); SkScalar ry = SkScalarHalf(dy); SkRect outer, tmp; outer.set(r.fLeft - rx, r.fTop - ry, r.fRight + rx, r.fBottom + ry); if (r.width() <= dx || r.height() <= dx) { SkScan::FillRect(outer, clip, blitter); return; } tmp.set(outer.fLeft, outer.fTop, outer.fRight, outer.fTop + dy); SkScan::FillRect(tmp, clip, blitter); tmp.fTop = outer.fBottom - dy; tmp.fBottom = outer.fBottom; SkScan::FillRect(tmp, clip, blitter); tmp.set(outer.fLeft, outer.fTop + dy, outer.fLeft + dx, outer.fBottom - dy); SkScan::FillRect(tmp, clip, blitter); tmp.fLeft = outer.fRight - dx; tmp.fRight = outer.fRight; SkScan::FillRect(tmp, clip, blitter); } <commit_msg>code style<commit_after>/* libs/graphics/sgl/SkScan_Hairline.cpp ** ** Copyright 2006, The Android Open Source Project ** ** 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 "SkScan.h" #include "SkBlitter.h" #include "SkRegion.h" #include "SkFDot6.h" #include "SkLineClipper.h" static void horiline(int x, int stopx, SkFixed fy, SkFixed dy, SkBlitter* blitter) { SkASSERT(x < stopx); do { blitter->blitH(x, fy >> 16, 1); fy += dy; } while (++x < stopx); } static void vertline(int y, int stopy, SkFixed fx, SkFixed dx, SkBlitter* blitter) { SkASSERT(y < stopy); do { blitter->blitH(fx >> 16, y, 1); fx += dx; } while (++y < stopy); } void SkScan::HairLine(const SkPoint& pt0, const SkPoint& pt1, const SkRegion* clip, SkBlitter* blitter) { SkBlitterClipper clipper; SkRect r; SkIRect clipR, ptsR; SkPoint pts[2] = { pt0, pt1 }; if (clip) { // Perform a clip in scalar space, so we catch huge values which might // be missed after we convert to SkFDot6 (overflow) r.set(clip->getBounds()); if (!SkLineClipper::IntersectLine(pts, r, pts)) { return; } } SkFDot6 x0 = SkScalarToFDot6(pts[0].fX); SkFDot6 y0 = SkScalarToFDot6(pts[0].fY); SkFDot6 x1 = SkScalarToFDot6(pts[1].fX); SkFDot6 y1 = SkScalarToFDot6(pts[1].fY); if (clip) { // now perform clipping again, as the rounding to dot6 can wiggle us // our rects are really dot6 rects, but since we've already used // lineclipper, we know they will fit in 32bits (26.6) const SkIRect& bounds = clip->getBounds(); clipR.set(SkIntToFDot6(bounds.fLeft), SkIntToFDot6(bounds.fTop), SkIntToFDot6(bounds.fRight), SkIntToFDot6(bounds.fBottom)); ptsR.set(x0, y0, x1, y1); ptsR.sort(); // outset the right and bottom, to account for how hairlines are // actually drawn, which may hit the pixel to the right or below of // the coordinate ptsR.fRight += SK_FDot6One; ptsR.fBottom += SK_FDot6One; if (!SkIRect::Intersects(ptsR, clipR)) { return; } if (clip->isRect() && clipR.contains(ptsR)) { clip = NULL; } else { blitter = clipper.apply(blitter, clip); } } SkFDot6 dx = x1 - x0; SkFDot6 dy = y1 - y0; if (SkAbs32(dx) > SkAbs32(dy)) { // mostly horizontal if (x0 > x1) { // we want to go left-to-right SkTSwap<SkFDot6>(x0, x1); SkTSwap<SkFDot6>(y0, y1); } int ix0 = SkFDot6Round(x0); int ix1 = SkFDot6Round(x1); if (ix0 == ix1) {// too short to draw return; } SkFixed slope = SkFixedDiv(dy, dx); SkFixed startY = SkFDot6ToFixed(y0) + (slope * ((32 - x0) & 63) >> 6); horiline(ix0, ix1, startY, slope, blitter); } else { // mostly vertical if (y0 > y1) { // we want to go top-to-bottom SkTSwap<SkFDot6>(x0, x1); SkTSwap<SkFDot6>(y0, y1); } int iy0 = SkFDot6Round(y0); int iy1 = SkFDot6Round(y1); if (iy0 == iy1) { // too short to draw return; } SkFixed slope = SkFixedDiv(dx, dy); SkFixed startX = SkFDot6ToFixed(x0) + (slope * ((32 - y0) & 63) >> 6); vertline(iy0, iy1, startX, slope, blitter); } } // we don't just draw 4 lines, 'cause that can leave a gap in the bottom-right // and double-hit the top-left. // TODO: handle huge coordinates on rect (before calling SkScalarToFixed) void SkScan::HairRect(const SkRect& rect, const SkRegion* clip, SkBlitter* blitter) { SkBlitterClipper clipper; SkIRect r; r.set(SkScalarToFixed(rect.fLeft) >> 16, SkScalarToFixed(rect.fTop) >> 16, (SkScalarToFixed(rect.fRight) >> 16) + 1, (SkScalarToFixed(rect.fBottom) >> 16) + 1); if (clip) { if (clip->quickReject(r)) { return; } if (!clip->quickContains(r)) { blitter = clipper.apply(blitter, clip); } } int width = r.width(); int height = r.height(); if ((width | height) == 0) { return; } if (width <= 2 || height <= 2) { blitter->blitRect(r.fLeft, r.fTop, width, height); return; } // if we get here, we know we have 4 segments to draw blitter->blitH(r.fLeft, r.fTop, width); // top blitter->blitRect(r.fLeft, r.fTop + 1, 1, height - 2); // left blitter->blitRect(r.fRight - 1, r.fTop + 1, 1, height - 2); // right blitter->blitH(r.fLeft, r.fBottom - 1, width); // bottom } /////////////////////////////////////////////////////////////////////////////// #include "SkPath.h" #include "SkGeometry.h" static bool quad_too_curvy(const SkPoint pts[3]) { return true; } static int compute_int_quad_dist(const SkPoint pts[3]) { // compute the vector between the control point ([1]) and the middle of the // line connecting the start and end ([0] and [2]) SkScalar dx = SkScalarHalf(pts[0].fX + pts[2].fX) - pts[1].fX; SkScalar dy = SkScalarHalf(pts[0].fY + pts[2].fY) - pts[1].fY; // we want everyone to be positive dx = SkScalarAbs(dx); dy = SkScalarAbs(dy); // convert to whole pixel values (use ceiling to be conservative) int idx = SkScalarCeil(dx); int idy = SkScalarCeil(dy); // use the cheap approx for distance if (idx > idy) { return idx + (idy >> 1); } else { return idy + (idx >> 1); } } static void hairquad(const SkPoint pts[3], const SkRegion* clip, SkBlitter* blitter, int level, void (*lineproc)(const SkPoint&, const SkPoint&, const SkRegion* clip, SkBlitter*)) { #if 1 if (level > 0 && quad_too_curvy(pts)) { SkPoint tmp[5]; SkChopQuadAtHalf(pts, tmp); hairquad(tmp, clip, blitter, level - 1, lineproc); hairquad(&tmp[2], clip, blitter, level - 1, lineproc); } else lineproc(pts[0], pts[2], clip, blitter); #else int count = 1 << level; const SkScalar dt = SkFixedToScalar(SK_Fixed1 >> level); SkScalar t = dt; SkPoint prevPt = pts[0]; for (int i = 1; i < count; i++) { SkPoint nextPt; SkEvalQuadAt(pts, t, &nextPt); lineproc(prevPt, nextPt, clip, blitter); t += dt; prevPt = nextPt; } // draw the last line explicitly to 1.0, in case t didn't match that exactly lineproc(prevPt, pts[2], clip, blitter); #endif } static bool cubic_too_curvy(const SkPoint pts[4]) { return true; } static void haircubic(const SkPoint pts[4], const SkRegion* clip, SkBlitter* blitter, int level, void (*lineproc)(const SkPoint&, const SkPoint&, const SkRegion*, SkBlitter*)) { if (level > 0 && cubic_too_curvy(pts)) { SkPoint tmp[7]; SkChopCubicAt(pts, tmp, SK_Scalar1/2); haircubic(tmp, clip, blitter, level - 1, lineproc); haircubic(&tmp[3], clip, blitter, level - 1, lineproc); } else lineproc(pts[0], pts[3], clip, blitter); } #define kMaxCubicSubdivideLevel 6 #define kMaxQuadSubdivideLevel 5 static void hair_path(const SkPath& path, const SkRegion* clip, SkBlitter* blitter, void (*lineproc)(const SkPoint&, const SkPoint&, const SkRegion*, SkBlitter*)) { if (path.isEmpty()) { return; } const SkIRect* clipR = NULL; if (clip) { SkIRect ibounds; path.getBounds().roundOut(&ibounds); ibounds.inset(-1, -1); if (clip->quickReject(ibounds)) { return; } if (clip->quickContains(ibounds)) { clip = NULL; } else { clipR = &clip->getBounds(); } } SkPath::Iter iter(path, false); SkPoint pts[4]; SkPath::Verb verb; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kLine_Verb: lineproc(pts[0], pts[1], clip, blitter); break; case SkPath::kQuad_Verb: { int d = compute_int_quad_dist(pts); /* quadratics approach the line connecting their start and end points 4x closer with each subdivision, so we compute the number of subdivisions to be the minimum need to get that distance to be less than a pixel. */ int level = (33 - SkCLZ(d)) >> 1; // SkDebugf("----- distance %d computedLevel %d\n", d, computedLevel); // sanity check on level (from the previous version) if (level > kMaxQuadSubdivideLevel) { level = kMaxQuadSubdivideLevel; } hairquad(pts, clip, blitter, level, lineproc); break; } case SkPath::kCubic_Verb: haircubic(pts, clip, blitter, kMaxCubicSubdivideLevel, lineproc); break; default: break; } } } void SkScan::HairPath(const SkPath& path, const SkRegion* clip, SkBlitter* blitter) { hair_path(path, clip, blitter, SkScan::HairLine); } void SkScan::AntiHairPath(const SkPath& path, const SkRegion* clip, SkBlitter* blitter) { hair_path(path, clip, blitter, SkScan::AntiHairLine); } /////////////////////////////////////////////////////////////////////////////// void SkScan::FrameRect(const SkRect& r, const SkPoint& strokeSize, const SkRegion* clip, SkBlitter* blitter) { SkASSERT(strokeSize.fX >= 0 && strokeSize.fY >= 0); if (strokeSize.fX < 0 || strokeSize.fY < 0) { return; } const SkScalar dx = strokeSize.fX; const SkScalar dy = strokeSize.fY; SkScalar rx = SkScalarHalf(dx); SkScalar ry = SkScalarHalf(dy); SkRect outer, tmp; outer.set(r.fLeft - rx, r.fTop - ry, r.fRight + rx, r.fBottom + ry); if (r.width() <= dx || r.height() <= dx) { SkScan::FillRect(outer, clip, blitter); return; } tmp.set(outer.fLeft, outer.fTop, outer.fRight, outer.fTop + dy); SkScan::FillRect(tmp, clip, blitter); tmp.fTop = outer.fBottom - dy; tmp.fBottom = outer.fBottom; SkScan::FillRect(tmp, clip, blitter); tmp.set(outer.fLeft, outer.fTop + dy, outer.fLeft + dx, outer.fBottom - dy); SkScan::FillRect(tmp, clip, blitter); tmp.fLeft = outer.fRight - dx; tmp.fRight = outer.fRight; SkScan::FillRect(tmp, clip, blitter); } <|endoftext|>
<commit_before>#include "resourcemanager.hpp" #include <iostream> using namespace core; ResourceManagerTexture::ResourceManagerTexture() { defaultrenderer = nullptr; } ResourceManagerTexture::~ResourceManagerTexture() { } std::shared_ptr<sdl::Texture> ResourceManagerTexture::get( std::string texturepath, sdl::Renderer* prenderer) { auto search = loadedtextures.find(texturepath); if (search != loadedtextures.end()) { std::cout << "Already loaded texture " << texturepath << std::endl; return search->second; } else { std::cout << "Loading new texture " << texturepath << std::endl; auto ptexture = std::make_shared<sdl::Texture>(texturepath, *prenderer); // Do some checking of ptexture here loadedtextures[texturepath] = ptexture; return ptexture; } } std::shared_ptr<sdl::Texture> ResourceManagerTexture::get( const std::string texturepath) { return get(texturepath, defaultrenderer); } bool ResourceManagerTexture::isLoaded(const std::string texturepath) const { auto search = loadedtextures.find(texturepath); if (search != loadedtextures.end()) { return true; } else { return false; } } void ResourceManagerTexture::setDefaultRenderer(sdl::Renderer* prenderer) { defaultrenderer = prenderer; } void ResourceManagerTexture::unloadUnused(void) { auto it = loadedtextures.begin(); while (it != loadedtextures.end()) { if (it->second.use_count() <= 1) { std::cout << "Unloading texture " << it->first << std::endl; it = loadedtextures.erase(it); } else { std::cout << "Not unloading texture " << it->first << " still used " << it->second.use_count() << " times" << std::endl; it++; } } } <commit_msg>Replace using statement with namespace block<commit_after>#include "resourcemanager.hpp" #include <iostream> namespace core { ResourceManagerTexture::ResourceManagerTexture() { defaultrenderer = nullptr; } ResourceManagerTexture::~ResourceManagerTexture() { } std::shared_ptr<sdl::Texture> ResourceManagerTexture::get( std::string texturepath, sdl::Renderer* prenderer) { auto search = loadedtextures.find(texturepath); if (search != loadedtextures.end()) { std::cout << "Already loaded texture " << texturepath << std::endl; return search->second; } else { std::cout << "Loading new texture " << texturepath << std::endl; auto ptexture = std::make_shared<sdl::Texture>(texturepath, *prenderer); // Do some checking of ptexture here loadedtextures[texturepath] = ptexture; return ptexture; } } std::shared_ptr<sdl::Texture> ResourceManagerTexture::get( const std::string texturepath) { return get(texturepath, defaultrenderer); } bool ResourceManagerTexture::isLoaded(const std::string texturepath) const { auto search = loadedtextures.find(texturepath); if (search != loadedtextures.end()) { return true; } else { return false; } } void ResourceManagerTexture::setDefaultRenderer(sdl::Renderer* prenderer) { defaultrenderer = prenderer; } void ResourceManagerTexture::unloadUnused(void) { auto it = loadedtextures.begin(); while (it != loadedtextures.end()) { if (it->second.use_count() <= 1) { std::cout << "Unloading texture " << it->first << std::endl; it = loadedtextures.erase(it); } else { std::cout << "Not unloading texture " << it->first << " still used " << it->second.use_count() << " times" << std::endl; it++; } } } } <|endoftext|>
<commit_before>/* * Author: Csaszar, Peter <[email protected]> * Copyright (C) 2011 Csaszar, Peter */ #include <cxxabi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <unistd.h> #ifdef DESKTOP #include <execinfo.h> #endif #include "csjp_exception.h" namespace csjp { struct NotesNode { void free() { if(prev){ prev->free(); ::free(prev); } if(msg) ::free(msg); } char * msg; size_t size; NotesNode * prev; }; PrimeException::iterator PrimeException::iterator::operator++() { if(node) node = node->prev; return *this; } const char * PrimeException::iterator::operator*() const { if(node) return node->msg; return NULL; } /* Unique id by an atomic counter. */ static unsigned nextId() { static unsigned id = 0; return __sync_fetch_and_add(&id, 1); } PrimeException::PrimeException(const PrimeException & orig) : std::exception(), id(orig.id), noMem(orig.noMem), name(orig.name), lastNode(orig.lastNode), whatMessage(0) { /* FIXME: hack because I hate deep copies. */ ((PrimeException&)orig).id = 0; ((PrimeException&)orig).noMem = false; ((PrimeException&)orig).name = 0; ((PrimeException&)orig).lastNode = 0; } PrimeException::PrimeException(PrimeException && temp) : std::exception(), id(temp.id), noMem(temp.noMem), name(temp.name), lastNode(temp.lastNode), whatMessage(0) { temp.id = 0; temp.noMem = false; temp.name = 0; temp.lastNode = 0; } PrimeException::PrimeException() : std::exception(), id(nextId()), noMem(false), name("PrimeException"), lastNode(NULL), whatMessage(0) { noteBacktrace(); } PrimeException::PrimeException(const std::exception & e) : std::exception(), id(nextId()), noMem(false), name("PrimeException"), lastNode(NULL), whatMessage(0) { notePrintf("Causing exception was received as std:exception. What: %s", e.what()); } PrimeException::PrimeException(int err) : std::exception(), id(nextId()), noMem(false), name("PrimeException"), lastNode(NULL), whatMessage(0) { noteBacktrace(); char errorMsg[512] = {0}; const char * msg = NULL; #ifdef _GNU_SOURCE msg = strerror_r(err, errorMsg, sizeof(errorMsg)); #else errno = 0; strerror_r(err, errorMsg, sizeof(errorMsg)); int _errNo = errno; if(_errNo) notePrintf("Error in strerror_r: number %d : %s", _errNo, strerror(_errNo)); msg = errorMsg; #endif notePrintf("Error number (errno) %d : %s", err, msg); } PrimeException::~PrimeException() throw() { if(lastNode){ lastNode->free(); free(lastNode); } if(whatMessage) free(whatMessage); } void PrimeException::noteBacktrace() { #ifdef DESKTOP unsigned i; size_t size; void *buffer[100]; char **strings; size = backtrace(buffer, sizeof(buffer)/sizeof(void*)); strings = backtrace_symbols(buffer, size); if (strings == NULL){ int errNo = errno; notePrintf("Failed to get backtrace_symbols. errNo: %d", errNo); return; } for(i = size - 1; i < size; i--){ char * openPos = strchr(strings[i], '('); char * offsetPos = strchr(strings[i], '+'); char * closePos = strchr(strings[i], ')'); if(!openPos || !closePos || !offsetPos || openPos >= offsetPos || offsetPos >= closePos){ notePrintf("%s", strings[i]); continue; } *openPos = 0; openPos++; *offsetPos = 0; offsetPos++; *closePos = 0; closePos++; const char * mangledName = strndup(openPos, offsetPos - openPos - 1); int status; // https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html char * realName = abi::__cxa_demangle(mangledName, 0, 0, &status); if(!realName || status) notePrintf("%s(%s %s)%s", strings[i], openPos, offsetPos, closePos); else notePrintf("%s(%s %s)%s", strings[i], realName, offsetPos, closePos); free((void*)mangledName); free(realName); } notePrintf("Backtrace:"); free(strings); #endif } void PrimeException::notePrintf(const char * format, ...) { va_list args; va_start(args, format); vnotePrintf(format, args); va_end(args); } void PrimeException::vnotePrintf(const char * format, va_list args) { va_list args2; va_copy(args2, args); int size = vsnprintf(NULL, 0, format, args2); size += 1; /* vsnprintf returned value does not contain the terminating zero.*/ char * msg = reinterpret_cast<char *>(malloc(size)); if(!msg){ noMem = true; return; } vsnprintf(msg, size, format, args); NotesNode * node = reinterpret_cast<NotesNode *>(malloc(sizeof(struct NotesNode))); if(!node){ free(msg); noMem = true; return; } node->msg = msg; node->size = size; node->prev = lastNode; lastNode = node; } void PrimeException::note(const char * msg_) { //abort(); int size = strlen(msg_) + 1; char * msg = reinterpret_cast<char *>(malloc(size)); if(!msg){ noMem = true; return; } NotesNode * node = reinterpret_cast<NotesNode *>(malloc(sizeof(struct NotesNode))); if(!node){ free(msg); noMem = true; return; } memcpy(msg, msg_, size); node->msg = msg; node->size = size; node->prev = lastNode; lastNode = node; } const char * PrimeException::what() const throw() { if(!lastNode || !lastNode->msg){ if(noMem) return "There was no enough memory for the 'what' message."; return "No explanation given."; } size_t size = 0; for(NotesNode * iter = lastNode; iter; iter = iter->prev) size += iter->size; if(whatMessage) free(whatMessage); whatMessage = reinterpret_cast<char *>(malloc(size)); if(!whatMessage){ if(lastNode && lastNode->msg) return lastNode->msg; } size = 0; char * msg = whatMessage; for(NotesNode * iter = lastNode; iter; iter = iter->prev){ memcpy(msg + size, iter->msg, iter->size); size += iter->size; msg[size - 1] = '\n'; } msg[size - 1] = 0; return msg; } static void print_backtrace() { #ifdef DESKTOP unsigned i; size_t size; void *buffer[100]; char **strings; size = backtrace(buffer, sizeof(buffer)/sizeof(void*)); strings = backtrace_symbols(buffer, size); if (strings == NULL){ int errNo = errno; fprintf(stderr, "Failed to get backtrace_symbols. errNo: %d", errNo); return; } fprintf(stderr, "Backtrace:\n"); for(i = 0; i < size; i++){ char * openPos = strchr(strings[i], '('); char * offsetPos = strchr(strings[i], '+'); char * closePos = strchr(strings[i], ')'); if(!openPos || !closePos || !offsetPos || openPos >= offsetPos || offsetPos >= closePos){ fprintf(stderr, "%s\n", strings[i]); continue; } *openPos = 0; openPos++; *offsetPos = 0; offsetPos++; *closePos = 0; closePos++; const char * mangledName = strndup(openPos, offsetPos - openPos - 1); int status; char * realName = abi::__cxa_demangle(mangledName, 0, 0, &status); if(!realName || status) fprintf(stderr, "%s(%s %s)%s\n", strings[i], openPos, offsetPos, closePos); else fprintf(stderr, "%s(%s %s)%s\n", strings[i], realName, offsetPos, closePos); free((void*)mangledName); free(realName); } free(strings); #endif } static void segmentation_fault_signal_handler(int signalNumber) { fprintf(stderr, "Error: signal %d:\n", signalNumber); print_backtrace(); exit(1); } void set_segmentation_fault_signal_handler() { // FIXME use sigaction instead signal(SIGSEGV, segmentation_fault_signal_handler); } } <commit_msg>Adding extra process information to exceptions.<commit_after>/* * Author: Csaszar, Peter <[email protected]> * Copyright (C) 2011 Csaszar, Peter */ #include <cxxabi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <unistd.h> #ifdef DESKTOP #include <execinfo.h> #endif #include "csjp_exception.h" namespace csjp { struct NotesNode { void free() { if(prev){ prev->free(); ::free(prev); } if(msg) ::free(msg); } char * msg; size_t size; NotesNode * prev; }; PrimeException::iterator PrimeException::iterator::operator++() { if(node) node = node->prev; return *this; } const char * PrimeException::iterator::operator*() const { if(node) return node->msg; return NULL; } /* Unique id by an atomic counter. */ static unsigned nextId() { static unsigned id = 0; return __sync_fetch_and_add(&id, 1); } PrimeException::PrimeException(const PrimeException & orig) : std::exception(), id(orig.id), noMem(orig.noMem), name(orig.name), lastNode(orig.lastNode), whatMessage(0) { /* FIXME: hack because I hate deep copies. */ ((PrimeException&)orig).id = 0; ((PrimeException&)orig).noMem = false; ((PrimeException&)orig).name = 0; ((PrimeException&)orig).lastNode = 0; } PrimeException::PrimeException(PrimeException && temp) : std::exception(), id(temp.id), noMem(temp.noMem), name(temp.name), lastNode(temp.lastNode), whatMessage(0) { temp.id = 0; temp.noMem = false; temp.name = 0; temp.lastNode = 0; } PrimeException::PrimeException() : std::exception(), id(nextId()), noMem(false), name("PrimeException"), lastNode(NULL), whatMessage(0) { pid_t pid = getpid(); notePrintf("Process pid is %d, session pid is %d.", pid, getsid(pid)); notePrintf("Owner uid: %d, euid: %d, gid: %d, egid: %d", getuid(), geteuid(), getgid(), getegid()); noteBacktrace(); } PrimeException::PrimeException(const std::exception & e) : std::exception(), id(nextId()), noMem(false), name("PrimeException"), lastNode(NULL), whatMessage(0) { pid_t pid = getpid(); notePrintf("Process pid is %d, session pid is %d.", pid, getsid(pid)); notePrintf("Owner uid: %d, euid: %d, gid: %d, egid: %d", getuid(), geteuid(), getgid(), getegid()); notePrintf("Causing exception was received as std:exception. What: %s", e.what()); } PrimeException::PrimeException(int err) : std::exception(), id(nextId()), noMem(false), name("PrimeException"), lastNode(NULL), whatMessage(0) { pid_t pid = getpid(); notePrintf("Process pid is %d, session pid is %d.", pid, getsid(pid)); notePrintf("Owner uid: %d, euid: %d, gid: %d, egid: %d", getuid(), geteuid(), getgid(), getegid()); noteBacktrace(); char errorMsg[512] = {0}; const char * msg = NULL; #ifdef _GNU_SOURCE msg = strerror_r(err, errorMsg, sizeof(errorMsg)); #else errno = 0; strerror_r(err, errorMsg, sizeof(errorMsg)); int _errNo = errno; if(_errNo) notePrintf("Error in strerror_r: number %d : %s", _errNo, strerror(_errNo)); msg = errorMsg; #endif notePrintf("Error number (errno) %d : %s", err, msg); } PrimeException::~PrimeException() throw() { if(lastNode){ lastNode->free(); free(lastNode); } if(whatMessage) free(whatMessage); } void PrimeException::noteBacktrace() { #ifdef DESKTOP unsigned i; size_t size; void *buffer[100]; char **strings; size = backtrace(buffer, sizeof(buffer)/sizeof(void*)); strings = backtrace_symbols(buffer, size); if (strings == NULL){ int errNo = errno; notePrintf("Failed to get backtrace_symbols. errNo: %d", errNo); return; } for(i = size - 1; i < size; i--){ char * openPos = strchr(strings[i], '('); char * offsetPos = strchr(strings[i], '+'); char * closePos = strchr(strings[i], ')'); if(!openPos || !closePos || !offsetPos || openPos >= offsetPos || offsetPos >= closePos){ notePrintf("%s", strings[i]); continue; } *openPos = 0; openPos++; *offsetPos = 0; offsetPos++; *closePos = 0; closePos++; const char * mangledName = strndup(openPos, offsetPos - openPos - 1); int status; // https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html char * realName = abi::__cxa_demangle(mangledName, 0, 0, &status); if(!realName || status) notePrintf("%s(%s %s)%s", strings[i], openPos, offsetPos, closePos); else notePrintf("%s(%s %s)%s", strings[i], realName, offsetPos, closePos); free((void*)mangledName); free(realName); } notePrintf("Backtrace:"); free(strings); #endif } void PrimeException::notePrintf(const char * format, ...) { va_list args; va_start(args, format); vnotePrintf(format, args); va_end(args); } void PrimeException::vnotePrintf(const char * format, va_list args) { va_list args2; va_copy(args2, args); int size = vsnprintf(NULL, 0, format, args2); size += 1; /* vsnprintf returned value does not contain the terminating zero.*/ char * msg = reinterpret_cast<char *>(malloc(size)); if(!msg){ noMem = true; return; } vsnprintf(msg, size, format, args); NotesNode * node = reinterpret_cast<NotesNode *>(malloc(sizeof(struct NotesNode))); if(!node){ free(msg); noMem = true; return; } node->msg = msg; node->size = size; node->prev = lastNode; lastNode = node; } void PrimeException::note(const char * msg_) { //abort(); int size = strlen(msg_) + 1; char * msg = reinterpret_cast<char *>(malloc(size)); if(!msg){ noMem = true; return; } NotesNode * node = reinterpret_cast<NotesNode *>(malloc(sizeof(struct NotesNode))); if(!node){ free(msg); noMem = true; return; } memcpy(msg, msg_, size); node->msg = msg; node->size = size; node->prev = lastNode; lastNode = node; } const char * PrimeException::what() const throw() { if(!lastNode || !lastNode->msg){ if(noMem) return "There was no enough memory for the 'what' message."; return "No explanation given."; } size_t size = 0; for(NotesNode * iter = lastNode; iter; iter = iter->prev) size += iter->size; if(whatMessage) free(whatMessage); whatMessage = reinterpret_cast<char *>(malloc(size)); if(!whatMessage){ if(lastNode && lastNode->msg) return lastNode->msg; } size = 0; char * msg = whatMessage; for(NotesNode * iter = lastNode; iter; iter = iter->prev){ memcpy(msg + size, iter->msg, iter->size); size += iter->size; msg[size - 1] = '\n'; } msg[size - 1] = 0; return msg; } static void print_backtrace() { #ifdef DESKTOP unsigned i; size_t size; void *buffer[100]; char **strings; size = backtrace(buffer, sizeof(buffer)/sizeof(void*)); strings = backtrace_symbols(buffer, size); if (strings == NULL){ int errNo = errno; fprintf(stderr, "Failed to get backtrace_symbols. errNo: %d", errNo); return; } fprintf(stderr, "Backtrace:\n"); for(i = 0; i < size; i++){ char * openPos = strchr(strings[i], '('); char * offsetPos = strchr(strings[i], '+'); char * closePos = strchr(strings[i], ')'); if(!openPos || !closePos || !offsetPos || openPos >= offsetPos || offsetPos >= closePos){ fprintf(stderr, "%s\n", strings[i]); continue; } *openPos = 0; openPos++; *offsetPos = 0; offsetPos++; *closePos = 0; closePos++; const char * mangledName = strndup(openPos, offsetPos - openPos - 1); int status; char * realName = abi::__cxa_demangle(mangledName, 0, 0, &status); if(!realName || status) fprintf(stderr, "%s(%s %s)%s\n", strings[i], openPos, offsetPos, closePos); else fprintf(stderr, "%s(%s %s)%s\n", strings[i], realName, offsetPos, closePos); free((void*)mangledName); free(realName); } free(strings); #endif } static void segmentation_fault_signal_handler(int signalNumber) { fprintf(stderr, "Error: signal %d:\n", signalNumber); print_backtrace(); exit(1); } void set_segmentation_fault_signal_handler() { // FIXME use sigaction instead signal(SIGSEGV, segmentation_fault_signal_handler); } } <|endoftext|>
<commit_before>#include <blackhole/blackhole.hpp> //! This example demonstrates the a bit extended blackhole logging library usage and its features. /*! - detailed formatters and sinks configuration; * - logger usage without macro. */ using namespace blackhole; // As always specify severity enumeration. enum class level { debug }; // Here we are going to configure our string/stream frontend and to register it. void init() { // Configure string formatter. // Pattern syntax behaves like usual substitution for placeholder. For example if attribute // named `severity` has value `2`, then pattern [%(severity)s] will produce: [2]. formatter_config_t formatter("string"); formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s"; // Configure stream sink to write into stdout (also stderr can be configured). sink_config_t sink("stream"); sink["output"] = "stdout"; frontend_config_t frontend = { formatter, sink }; log_config_t config{ "root", { frontend } }; repository_t<level>::instance().add_config(config); } // Here it's an example how to create and handle log events without using any macros at all. template<typename Log> void debug(Log& log, level lvl, const char* message) { // Tries to create log record. Returns invalid record object if created log record couldn't // pass filtering stage. // For our case it will be created anyway, because we don't have any filters registered now. log::record_t record = log.open_record(lvl); if (record.valid()) { // Manually insert message attribute into log record attributes set using keyword API. // Formatter will break up if some attributes it needed don't exist where formatting // occures. record.attributes.insert({ keyword::message() = message }); log.push(std::move(record)); } } int main(int, char**) { init(); verbose_logger_t<level> log = repository_t<level>::instance().root(); BH_LOG(log, level::debug, "log message using macro API"); debug(log, level::debug, "log message using log object directly"); return 0; } <commit_msg>[Documentation] Tiny naming fix.<commit_after>#include <blackhole/blackhole.hpp> //! This example demonstrates the a bit extended blackhole logging library usage and its features. //! - detailed formatters and sinks configuration; //! - logger usage without macro. using namespace blackhole; // As always specify severity enumeration. enum class level { debug }; // Here we are going to configure our string/stream frontend and to register it. void init() { // Configure string formatter. // Pattern syntax behaves like usual substitution for placeholder. For example if attribute // named `severity` has value `2`, then pattern [%(severity)s] will produce: [2]. formatter_config_t formatter("string"); formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s"; // Configure stream sink to write into stdout (also stderr can be configured). sink_config_t sink("stream"); sink["output"] = "stdout"; frontend_config_t frontend = { formatter, sink }; log_config_t config{ "root", { frontend } }; repository_t<level>::instance().add_config(config); } // Here it's an example how to create and handle log events without using any macros at all. template<typename Log> void handle(Log& log, level lvl, const char* message) { // Tries to create log record. Returns invalid record object if created log record couldn't // pass filtering stage. // For our case it will be created anyway, because we don't have any filters registered now. log::record_t record = log.open_record(lvl); if (record.valid()) { // Manually insert message attribute into log record attributes set using keyword API. // Formatter will break up if some attributes it needed don't exist where formatting // occures. record.attributes.insert({ keyword::message() = message }); log.push(std::move(record)); } } int main(int, char**) { init(); verbose_logger_t<level> log = repository_t<level>::instance().root(); BH_LOG(log, level::debug, "log message using macro API"); handle(log, level::debug, "log message using log object directly"); return 0; } <|endoftext|>
<commit_before>#include "quadrigacx.h" #include "parameters.h" #include "utils/restapi.h" #include "utils/base64.h" #include "unique_json.hpp" #include "hex_str.hpp" #include "openssl/sha.h" #include "openssl/hmac.h" #include <vector> #include <iomanip> #include <array> #include <chrono> namespace QuadrigaCX { //forward declarations static std::string getSignature(Parameters& params, const uint64_t nonce); static json_t* authRequest(Parameters& params, std::string request, json_t * options = nullptr); static RestApi& queryHandle(Parameters &params) { static RestApi query ("https://api.quadrigacx.com", params.cacert.c_str(), *params.logFile); return query; } quote_t getQuote(Parameters &params) { auto &exchange = queryHandle(params); auto root = unique_json(exchange.getRequest("/v2/ticker?book=btc_usd")); auto quote = json_string_value(json_object_get(root.get(), "bid")); auto bidValue = quote ? std::stod(quote) : 0.0; quote = json_string_value(json_object_get(root.get(), "ask")); auto askValue = quote ? std::stod(quote) : 0.0; return std::make_pair(bidValue, askValue); } double getAvail(Parameters& params, std::string currency) { unique_json root { authRequest(params, "/v2/balance") }; double available = 0.0; const char * key = nullptr; if (currency.compare("usd") == 0) { key = "usd_available"; } else if (currency.compare("btc") == 0) { key = "btc_available"; } else if (currency.compare("eth") == 0) { key = "eth_available"; } else if (currency.compare("cad") == 0) { key = "cad_available"; } else { *params.logFile << "<QuadrigaCX> Currency " << currency << " not supported" << std::endl; } const char * avail_str = json_string_value(json_object_get(root.get(), key)); available = avail_str ? atof(avail_str) : 0.0; return available; } std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price) { if (direction.compare("buy") != 0 && direction.compare("sell") != 0) { *params.logFile << "<QuadrigaCX> Error: Neither \"buy\" nor \"sell\" selected" << std::endl; return "0"; } *params.logFile << "<QuadrigaCX> Trying to send a \"" << direction << "\" limit order: " << std::setprecision(6) << quantity << " @ $" << std::setprecision(2) << price << "...\n"; std::string pricelimit = std::to_string(price); std::string volume = std::to_string(quantity); unique_json options {json_object()}; json_object_set_new(options.get(), "book", json_string("btc_usd")); json_object_set_new(options.get(), "amount", json_real(quantity)); json_object_set_new(options.get(), "price", json_real(price)); unique_json root { authRequest(params, ("/v2/" + direction), options.get()) }; json_t *res = json_object_get(root.get(), "id"); if (json_is_object(res) == 0) { auto dump = json_dumps(root.get(), 0) ; *params.logFile << "<QuadrigaCX> order failed: " << dump << std::endl; free(dump); return "Order Failed"; } std::string txid = json_string_value(res); *params.logFile << "<QuadrigaCX> Done (transaction ID: " << txid << ")\n" << std::endl; return txid; } bool isOrderComplete(Parameters& params, std::string orderId) { auto ret = false; unique_json options {json_object()}; json_object_set_new(options.get(), "id", json_string(orderId.c_str())); unique_json root { authRequest(params, "/v2/lookup_order", options.get()) }; auto res = json_object_get(json_array_get(root.get(),0), "status"); if( json_is_string(res) ){ auto value = std::string(json_string_value(res)); if(value.compare("2") == 0){ ret = true; } } else{ auto dump = json_dumps(root.get(), 0); *params.logFile << "<QuadrigaCX> Error: failed to get order status for id: " << orderId << ":" << dump << std::endl; free(dump); } return ret; } double getActivePos(Parameters& params) { return getAvail(params, "btc"); } double getLimitPrice(Parameters &params, double volume, bool isBid) { auto &exchange = queryHandle(params); auto root = unique_json(exchange.getRequest("/v2/order_book?book=btc_usd")); auto branch = json_object_get(root.get(), isBid ? "bids" : "asks"); // loop on volume double totVol = 0.0; double currPrice = 0.0; double currVol = 0.0; unsigned int i = 0; // [[<price>, <volume>], [<price>, <volume>], ...] for(i = 0; i < (json_array_size(branch)); i++) { // volumes are added up until the requested volume is reached currVol = atof(json_string_value(json_array_get(json_array_get(branch, i), 1))); currPrice = atof(json_string_value(json_array_get(json_array_get(branch, i), 0))); totVol += currVol; if(totVol >= volume * params.orderBookFactor){ break; } } return currPrice; } static json_t* authRequest(Parameters& params, std::string request, json_t * options) { uint64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); //post data is json unique_json payload {json_object()}; auto root = payload.get(); json_object_set_new(root, "key", json_string(params.quadrigaApi.c_str())); json_object_set_new(root, "nonce", json_integer(json_int_t(nonce))); json_object_set_new(root, "signature", json_string(getSignature(params, nonce).c_str())); if(options != nullptr){ const char * key; json_t * value; json_object_foreach(options, key, value){ if(value != nullptr && key != nullptr) json_object_set_new(root, key, value); } } auto payload_string = json_dumps(root, 0); std::string post_data(payload_string); free(payload_string); std::string headers[1] = { "Content-Type: application/json; charset=utf-8", }; // cURL request auto &exchange = queryHandle(params); auto ret = exchange.postRequest(request, make_slist(std::begin(headers), std::end(headers)), post_data); return ret; } static std::string getSignature(Parameters& params, const uint64_t nonce) { std::string sig_data_str = std::to_string(nonce) + params.quadrigaClientId + params.quadrigaApi; auto data_len = sig_data_str.length(); std::vector<uint8_t> sig_data(data_len); copy(sig_data_str.begin(), sig_data_str.end(), sig_data.begin()); uint8_t * hmac_digest = HMAC(EVP_sha256(), params.quadrigaSecret.c_str(), params.quadrigaSecret.length(), sig_data.data(), data_len, NULL, NULL); return hex_str(hmac_digest, hmac_digest + SHA256_DIGEST_LENGTH); } void testQuadriga(){ Parameters params("blackbird.conf"); params.quadrigaSecret = ""; params.quadrigaClientId = ""; params.quadrigaApi = ""; params.logFile = new std::ofstream("./test.log" , std::ofstream::trunc); std::string orderId; std::cout << "Current value BTC_USD bid: " << getQuote(params).bid() << std::endl; std::cout << "Current value BTC_USD ask: " << getQuote(params).ask() << std::endl; std::cout << "Current balance BTC: " << getAvail(params, "btc") << std::endl; std::cout << "Current balance USD: " << getAvail(params, "usd")<< std::endl; std::cout << "Current balance ETH: " << getAvail(params, "eth")<< std::endl; std::cout << "Current balance CAD: " << getAvail(params, "cad")<< std::endl; std::cout << "current bid limit price for 10 units: " << getLimitPrice(params, 10.0, true) << std::endl; std::cout << "Current ask limit price for 10 units: " << getLimitPrice(params, 10.0, false) << std::endl; std::cout << "Sending buy order for 0.005 BTC @ 1000 USD - TXID: " ; orderId = sendLongOrder(params, "buy", 0.005, 1000); std:: cout << orderId << std::endl; std::cout << "Buy order is complete: " << isOrderComplete(params, orderId) << std::endl; std::cout << "Sending sell order for 0.005 BTC @ 5000 USD - TXID: " ; orderId = sendLongOrder(params, "sell", 0.005, 5000); std:: cout << orderId << std::endl; std::cout << "Sell order is complete: " << isOrderComplete(params, orderId) << std::endl; } } <commit_msg>Minor fix in quadrigacx. 'json_int_t' could be defined as 'long long' which would cause syntax error when creating a temporary.<commit_after>#include "quadrigacx.h" #include "parameters.h" #include "utils/restapi.h" #include "utils/base64.h" #include "unique_json.hpp" #include "hex_str.hpp" #include "openssl/sha.h" #include "openssl/hmac.h" #include <vector> #include <iomanip> #include <array> #include <chrono> namespace QuadrigaCX { //forward declarations static std::string getSignature(Parameters& params, const uint64_t nonce); static json_t* authRequest(Parameters& params, std::string request, json_t * options = nullptr); static RestApi& queryHandle(Parameters &params) { static RestApi query ("https://api.quadrigacx.com", params.cacert.c_str(), *params.logFile); return query; } quote_t getQuote(Parameters &params) { auto &exchange = queryHandle(params); auto root = unique_json(exchange.getRequest("/v2/ticker?book=btc_usd")); auto quote = json_string_value(json_object_get(root.get(), "bid")); auto bidValue = quote ? std::stod(quote) : 0.0; quote = json_string_value(json_object_get(root.get(), "ask")); auto askValue = quote ? std::stod(quote) : 0.0; return std::make_pair(bidValue, askValue); } double getAvail(Parameters& params, std::string currency) { unique_json root { authRequest(params, "/v2/balance") }; double available = 0.0; const char * key = nullptr; if (currency.compare("usd") == 0) { key = "usd_available"; } else if (currency.compare("btc") == 0) { key = "btc_available"; } else if (currency.compare("eth") == 0) { key = "eth_available"; } else if (currency.compare("cad") == 0) { key = "cad_available"; } else { *params.logFile << "<QuadrigaCX> Currency " << currency << " not supported" << std::endl; } const char * avail_str = json_string_value(json_object_get(root.get(), key)); available = avail_str ? atof(avail_str) : 0.0; return available; } std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price) { if (direction.compare("buy") != 0 && direction.compare("sell") != 0) { *params.logFile << "<QuadrigaCX> Error: Neither \"buy\" nor \"sell\" selected" << std::endl; return "0"; } *params.logFile << "<QuadrigaCX> Trying to send a \"" << direction << "\" limit order: " << std::setprecision(6) << quantity << " @ $" << std::setprecision(2) << price << "...\n"; std::string pricelimit = std::to_string(price); std::string volume = std::to_string(quantity); unique_json options {json_object()}; json_object_set_new(options.get(), "book", json_string("btc_usd")); json_object_set_new(options.get(), "amount", json_real(quantity)); json_object_set_new(options.get(), "price", json_real(price)); unique_json root { authRequest(params, ("/v2/" + direction), options.get()) }; json_t *res = json_object_get(root.get(), "id"); if (json_is_object(res) == 0) { auto dump = json_dumps(root.get(), 0) ; *params.logFile << "<QuadrigaCX> order failed: " << dump << std::endl; free(dump); return "Order Failed"; } std::string txid = json_string_value(res); *params.logFile << "<QuadrigaCX> Done (transaction ID: " << txid << ")\n" << std::endl; return txid; } bool isOrderComplete(Parameters& params, std::string orderId) { auto ret = false; unique_json options {json_object()}; json_object_set_new(options.get(), "id", json_string(orderId.c_str())); unique_json root { authRequest(params, "/v2/lookup_order", options.get()) }; auto res = json_object_get(json_array_get(root.get(),0), "status"); if( json_is_string(res) ){ auto value = std::string(json_string_value(res)); if(value.compare("2") == 0){ ret = true; } } else{ auto dump = json_dumps(root.get(), 0); *params.logFile << "<QuadrigaCX> Error: failed to get order status for id: " << orderId << ":" << dump << std::endl; free(dump); } return ret; } double getActivePos(Parameters& params) { return getAvail(params, "btc"); } double getLimitPrice(Parameters &params, double volume, bool isBid) { auto &exchange = queryHandle(params); auto root = unique_json(exchange.getRequest("/v2/order_book?book=btc_usd")); auto branch = json_object_get(root.get(), isBid ? "bids" : "asks"); // loop on volume double totVol = 0.0; double currPrice = 0.0; double currVol = 0.0; unsigned int i = 0; // [[<price>, <volume>], [<price>, <volume>], ...] for(i = 0; i < (json_array_size(branch)); i++) { // volumes are added up until the requested volume is reached currVol = atof(json_string_value(json_array_get(json_array_get(branch, i), 1))); currPrice = atof(json_string_value(json_array_get(json_array_get(branch, i), 0))); totVol += currVol; if(totVol >= volume * params.orderBookFactor){ break; } } return currPrice; } static json_t* authRequest(Parameters& params, std::string request, json_t * options) { json_int_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); //post data is json unique_json payload {json_object()}; auto root = payload.get(); json_object_set_new(root, "key", json_string(params.quadrigaApi.c_str())); json_object_set_new(root, "nonce", json_integer(nonce)); json_object_set_new(root, "signature", json_string(getSignature(params, nonce).c_str())); if(options != nullptr){ const char * key; json_t * value; json_object_foreach(options, key, value){ if(value != nullptr && key != nullptr) json_object_set_new(root, key, value); } } auto payload_string = json_dumps(root, 0); std::string post_data(payload_string); free(payload_string); std::string headers[1] = { "Content-Type: application/json; charset=utf-8", }; // cURL request auto &exchange = queryHandle(params); auto ret = exchange.postRequest(request, make_slist(std::begin(headers), std::end(headers)), post_data); return ret; } static std::string getSignature(Parameters& params, const uint64_t nonce) { std::string sig_data_str = std::to_string(nonce) + params.quadrigaClientId + params.quadrigaApi; auto data_len = sig_data_str.length(); std::vector<uint8_t> sig_data(data_len); copy(sig_data_str.begin(), sig_data_str.end(), sig_data.begin()); uint8_t * hmac_digest = HMAC(EVP_sha256(), params.quadrigaSecret.c_str(), params.quadrigaSecret.length(), sig_data.data(), data_len, NULL, NULL); return hex_str(hmac_digest, hmac_digest + SHA256_DIGEST_LENGTH); } void testQuadriga(){ Parameters params("blackbird.conf"); params.quadrigaSecret = ""; params.quadrigaClientId = ""; params.quadrigaApi = ""; params.logFile = new std::ofstream("./test.log" , std::ofstream::trunc); std::string orderId; std::cout << "Current value BTC_USD bid: " << getQuote(params).bid() << std::endl; std::cout << "Current value BTC_USD ask: " << getQuote(params).ask() << std::endl; std::cout << "Current balance BTC: " << getAvail(params, "btc") << std::endl; std::cout << "Current balance USD: " << getAvail(params, "usd")<< std::endl; std::cout << "Current balance ETH: " << getAvail(params, "eth")<< std::endl; std::cout << "Current balance CAD: " << getAvail(params, "cad")<< std::endl; std::cout << "current bid limit price for 10 units: " << getLimitPrice(params, 10.0, true) << std::endl; std::cout << "Current ask limit price for 10 units: " << getLimitPrice(params, 10.0, false) << std::endl; std::cout << "Sending buy order for 0.005 BTC @ 1000 USD - TXID: " ; orderId = sendLongOrder(params, "buy", 0.005, 1000); std:: cout << orderId << std::endl; std::cout << "Buy order is complete: " << isOrderComplete(params, orderId) << std::endl; std::cout << "Sending sell order for 0.005 BTC @ 5000 USD - TXID: " ; orderId = sendLongOrder(params, "sell", 0.005, 5000); std:: cout << orderId << std::endl; std::cout << "Sell order is complete: " << isOrderComplete(params, orderId) << std::endl; } } <|endoftext|>
<commit_before>#include "oglrenderer.hpp" #include "utils/logger.hpp" #include "graphics/graphics-definitions.hpp" #include "graphics/shaderprogram.hpp" #include <iostream> #include <vector> #include <boost/format.hpp> using std::vector; /** * Load our default shader on creation. */ OGLRenderer::OGLRenderer(shared_ptr<ResourceManager> resourceManager, shared_ptr<Camera> camera) : colorShader(new ShaderProgram()), textureShader(new ShaderProgram()), debugShader(new ShaderProgram()), camera(camera), aspectRatio(16.0f / 9.0f), fov(60.0f), debugGridEnabled(true), debugAxesEnabled(true), debugGridMaterial(resourceManager->getMaterial("debug")), redMaterial(resourceManager->getMaterial("debugRed")), blueMaterial(resourceManager->getMaterial("debugBlue")), greenMaterial(resourceManager->getMaterial("debugGreen")) { debugShader->attachShader(resourceManager->getShader("defaultNoLight.vert")); debugShader->attachShader(resourceManager->getShader("colorNoLight.frag")); debugShader->addEffect(EFFECT_COLOR); debugShader->link(); colorShader->attachShader(resourceManager->getShader("default.vert")); colorShader->attachShader(resourceManager->getShader("color.frag")); colorShader->addEffect(EFFECT_COLOR); colorShader->addEffect(EFFECT_LIGHTING); colorShader->link(); textureShader->attachShader(resourceManager->getShader("default.vert")); textureShader->attachShader(resourceManager->getShader("texture.frag")); textureShader->addEffect(EFFECT_TEXTURE); textureShader->addEffect(EFFECT_LIGHTING); textureShader->link(); updateProjectionMatrix(); initDebugGrid(); initDebugAxes(); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glDepthFunc(GL_LESS); } OGLRenderer::~OGLRenderer() { glDeleteBuffers(1, &debugGridId); glDeleteBuffers(1, &debugAxesId); } void OGLRenderer::renderEntity(shared_ptr<RenderedEntity> entity) { // send model matrix to shaders colorShader->bind(); colorShader->setModelMatrix(entity->getModelMatrix()); textureShader->bind(); textureShader->setModelMatrix(entity->getModelMatrix()); colorShader->bind(); renderMesh(entity->getMesh()); } void OGLRenderer::renderMesh(shared_ptr<Mesh> mesh) { // index 0 => vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, mesh->getVertexBuffer()); glVertexAttribPointer(0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // index 1 => normals glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, mesh->getNormalBuffer()); glVertexAttribPointer(1, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getFaceBuffer()); // index 2 => UV Coordinates glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, mesh->getUvBuffer()); glVertexAttribPointer(2, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getFaceBuffer()); vector<FaceGroup> faceGroups = mesh->getFaceGroups(); vector<FaceGroup>::iterator iter; for (iter = faceGroups.begin(); iter < faceGroups.end(); ++iter) { shared_ptr<Material> mat = mesh->getMaterial(iter->materialName); ShaderProgram * usedShader = 0; if (mat->getType() == MATERIAL_TYPE_COLOR) { usedShader = colorShader.get(); } else if (mat->getType() == MATERIAL_TYPE_TEXTURE) { usedShader = textureShader.get(); } usedShader->bind(); usedShader->setMaterial(*mat); glDrawElements(GL_TRIANGLES, iter->size * 3, GL_UNSIGNED_INT, BUFFER_OFFSET(sizeof(GLuint) *3* iter->start)); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } void OGLRenderer::useMaterial(shared_ptr<Material> material) { if (material->getType() == MATERIAL_TYPE_COLOR) { colorShader->setMaterial(*material); } else if (material->getType() == MATERIAL_TYPE_TEXTURE) { textureShader->setMaterial(*material); } } void OGLRenderer::enableDebugGrid(const bool show) { debugGridEnabled = show; } void OGLRenderer::setWindowSize(const unsigned int width, const unsigned int height) { glViewport(0, 0, width, height); aspectRatio = static_cast<float>(width / height); updateProjectionMatrix(); } void OGLRenderer::startFrame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); colorShader->bind(); colorShader->setViewMatrix(camera->getModelMatrix()); textureShader->bind(); textureShader->setViewMatrix(camera->getModelMatrix()); } void OGLRenderer::endFrame() { if (debugAxesEnabled || debugGridEnabled) { debugShader->bind(); // draw debug stuff always in world coordinates debugShader->setModelMatrix(IDENTITY_MATRIX); debugShader->setViewMatrix(camera->getModelMatrix()); debugShader->setProjectionMatrix(projectionMatrix); if (debugAxesEnabled) { drawDebugAxes(); } if (debugGridEnabled) { drawDebugGrid(); } colorShader->bind(); } GLenum err (glGetError()); while(err!=GL_NO_ERROR) { std::string error; switch(err) { case GL_INVALID_OPERATION: error="INVALID_OPERATION"; break; case GL_INVALID_ENUM: error="INVALID_ENUM"; break; case GL_INVALID_VALUE: error="INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error="OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error="INVALID_FRAMEBUFFER_OPERATION"; break; } std::cerr <<"OGL errrer: GL_" << error << std::endl; err=glGetError(); } } void OGLRenderer::drawDebugGrid() { debugShader->setMaterial(*debugGridMaterial); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, debugGridId); glVertexAttribPointer(0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); glDrawArrays(GL_LINES, 0, numDebugGridVertices); } void OGLRenderer::renderTerrain(shared_ptr<Terrain> terrain) { } void OGLRenderer::addLight(const Light& light) { colorShader->bind(); colorShader->addLight(light); } void OGLRenderer::enableLighting(const bool enable) { // TODO implement } void OGLRenderer::enableWireframe(const bool enable) { if (enable) { glPolygonMode(GL_FRONT, GL_LINE); } else { glPolygonMode(GL_FRONT, GL_FILL); } } void OGLRenderer::enableTextures(const bool enable) { // TODO implement } void OGLRenderer::initDebugGrid() { GLfloat extent = 1000.0f; // How far on the Z-Axis and X-Axis the ground extends GLfloat stepSize = 50.0f; // The size of the separation between points GLfloat groundLevel = -0.05f; // Where on the Y-Axis the ground is drawn std::vector<glm::vec3> debugGridVertices; // Draw our ground grid for (GLint loop = -extent; loop < extent; loop += stepSize) { // Draw lines along Z-Axis debugGridVertices.push_back(glm::vec3(loop, groundLevel, extent)); debugGridVertices.push_back(glm::vec3(loop, groundLevel, -extent)); // Draw lines across X-Axis debugGridVertices.push_back(glm::vec3(-extent, groundLevel, loop)); debugGridVertices.push_back(glm::vec3(extent, groundLevel, loop)); } glGenBuffers(1, &debugGridId); glBindBuffer(GL_ARRAY_BUFFER, debugGridId); glBufferData(GL_ARRAY_BUFFER, debugGridVertices.size() * sizeof(glm::vec3), &debugGridVertices[0], GL_STATIC_DRAW); numDebugGridVertices = debugGridVertices.size(); } void OGLRenderer::drawDebugAxes() { glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, debugAxesId); glVertexAttribPointer(0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); debugShader->setMaterial(*redMaterial); glDrawArrays(GL_LINES, 0, 2); debugShader->setMaterial(*greenMaterial); glDrawArrays(GL_LINES, 2, 2); debugShader->setMaterial(*blueMaterial); glDrawArrays(GL_LINES, 4, 2); } void OGLRenderer::enableDebugAxes(const bool enable) { debugAxesEnabled = enable; } void OGLRenderer::setCamera(shared_ptr<Camera> camera) { this->camera = camera; } void OGLRenderer::initDebugAxes() { std::vector<glm::vec3> debugAxesVertices; // X axis debugAxesVertices.push_back(glm::vec3(-1000.0f, 0.0f, 0.0f)); debugAxesVertices.push_back(glm::vec3(1000.0f, 0.0f, 0.0f)); // Y axis debugAxesVertices.push_back(glm::vec3(0.0f, -1000.0f, 0.0f)); debugAxesVertices.push_back(glm::vec3(0.0f, 1000.0f, 0.0f)); // Z axis debugAxesVertices.push_back(glm::vec3(0.0f, 0.0f, -1000.0f)); debugAxesVertices.push_back(glm::vec3(0.0f, 0.0f, 1000.0f)); glGenBuffers(1, &debugAxesId); glBindBuffer(GL_ARRAY_BUFFER, debugAxesId); glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(glm::vec3), &debugAxesVertices[0], GL_STATIC_DRAW); } <commit_msg>Fix computation of aspect ratio<commit_after>#include "oglrenderer.hpp" #include "utils/logger.hpp" #include "graphics/graphics-definitions.hpp" #include "graphics/shaderprogram.hpp" #include <iostream> #include <vector> #include <boost/format.hpp> using std::vector; /** * Load our default shader on creation. */ OGLRenderer::OGLRenderer(shared_ptr<ResourceManager> resourceManager, shared_ptr<Camera> camera) : colorShader(new ShaderProgram()), textureShader(new ShaderProgram()), debugShader(new ShaderProgram()), camera(camera), aspectRatio(10.0f), fov(45.0f), debugGridEnabled(true), debugAxesEnabled(true), debugGridMaterial(resourceManager->getMaterial("debug")), redMaterial(resourceManager->getMaterial("debugRed")), blueMaterial(resourceManager->getMaterial("debugBlue")), greenMaterial(resourceManager->getMaterial("debugGreen")) { debugShader->attachShader(resourceManager->getShader("defaultNoLight.vert")); debugShader->attachShader(resourceManager->getShader("colorNoLight.frag")); debugShader->addEffect(EFFECT_COLOR); debugShader->link(); colorShader->attachShader(resourceManager->getShader("default.vert")); colorShader->attachShader(resourceManager->getShader("color.frag")); colorShader->addEffect(EFFECT_COLOR); colorShader->addEffect(EFFECT_LIGHTING); colorShader->link(); textureShader->attachShader(resourceManager->getShader("default.vert")); textureShader->attachShader(resourceManager->getShader("texture.frag")); textureShader->addEffect(EFFECT_TEXTURE); textureShader->addEffect(EFFECT_LIGHTING); textureShader->link(); updateProjectionMatrix(); initDebugGrid(); initDebugAxes(); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glDepthFunc(GL_LESS); } OGLRenderer::~OGLRenderer() { glDeleteBuffers(1, &debugGridId); glDeleteBuffers(1, &debugAxesId); } void OGLRenderer::renderEntity(shared_ptr<RenderedEntity> entity) { // send model matrix to shaders colorShader->bind(); colorShader->setModelMatrix(entity->getModelMatrix()); textureShader->bind(); textureShader->setModelMatrix(entity->getModelMatrix()); colorShader->bind(); renderMesh(entity->getMesh()); } void OGLRenderer::renderMesh(shared_ptr<Mesh> mesh) { // index 0 => vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, mesh->getVertexBuffer()); glVertexAttribPointer(0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // index 1 => normals glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, mesh->getNormalBuffer()); glVertexAttribPointer(1, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getFaceBuffer()); // index 2 => UV Coordinates glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, mesh->getUvBuffer()); glVertexAttribPointer(2, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getFaceBuffer()); vector<FaceGroup> faceGroups = mesh->getFaceGroups(); vector<FaceGroup>::iterator iter; for (iter = faceGroups.begin(); iter < faceGroups.end(); ++iter) { shared_ptr<Material> mat = mesh->getMaterial(iter->materialName); ShaderProgram * usedShader = 0; if (mat->getType() == MATERIAL_TYPE_COLOR) { usedShader = colorShader.get(); } else if (mat->getType() == MATERIAL_TYPE_TEXTURE) { usedShader = textureShader.get(); } usedShader->bind(); usedShader->setMaterial(*mat); glDrawElements(GL_TRIANGLES, iter->size * 3, GL_UNSIGNED_INT, BUFFER_OFFSET(sizeof(GLuint) *3* iter->start)); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } void OGLRenderer::useMaterial(shared_ptr<Material> material) { if (material->getType() == MATERIAL_TYPE_COLOR) { colorShader->setMaterial(*material); } else if (material->getType() == MATERIAL_TYPE_TEXTURE) { textureShader->setMaterial(*material); } } void OGLRenderer::enableDebugGrid(const bool show) { debugGridEnabled = show; } void OGLRenderer::setWindowSize(const unsigned int width, const unsigned int height) { glViewport(0, 0, width, height); aspectRatio = (float)width / (float)height; updateProjectionMatrix(); } void OGLRenderer::startFrame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); colorShader->bind(); colorShader->setViewMatrix(camera->getModelMatrix()); textureShader->bind(); textureShader->setViewMatrix(camera->getModelMatrix()); } void OGLRenderer::endFrame() { if (debugAxesEnabled || debugGridEnabled) { debugShader->bind(); // draw debug stuff always in world coordinates debugShader->setModelMatrix(IDENTITY_MATRIX); debugShader->setViewMatrix(camera->getModelMatrix()); debugShader->setProjectionMatrix(projectionMatrix); if (debugAxesEnabled) { drawDebugAxes(); } if (debugGridEnabled) { drawDebugGrid(); } colorShader->bind(); } GLenum err (glGetError()); while(err!=GL_NO_ERROR) { std::string error; switch(err) { case GL_INVALID_OPERATION: error="INVALID_OPERATION"; break; case GL_INVALID_ENUM: error="INVALID_ENUM"; break; case GL_INVALID_VALUE: error="INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error="OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error="INVALID_FRAMEBUFFER_OPERATION"; break; } std::cerr <<"OGL errrer: GL_" << error << std::endl; err=glGetError(); } } void OGLRenderer::drawDebugGrid() { debugShader->setMaterial(*debugGridMaterial); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, debugGridId); glVertexAttribPointer(0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); glDrawArrays(GL_LINES, 0, numDebugGridVertices); } void OGLRenderer::renderTerrain(shared_ptr<Terrain> terrain) { } void OGLRenderer::addLight(const Light& light) { colorShader->bind(); colorShader->addLight(light); } void OGLRenderer::enableLighting(const bool enable) { // TODO implement } void OGLRenderer::enableWireframe(const bool enable) { if (enable) { glPolygonMode(GL_FRONT, GL_LINE); } else { glPolygonMode(GL_FRONT, GL_FILL); } } void OGLRenderer::enableTextures(const bool enable) { // TODO implement } void OGLRenderer::initDebugGrid() { GLfloat extent = 1000.0f; // How far on the Z-Axis and X-Axis the ground extends GLfloat stepSize = 50.0f; // The size of the separation between points GLfloat groundLevel = -0.05f; // Where on the Y-Axis the ground is drawn std::vector<glm::vec3> debugGridVertices; // Draw our ground grid for (GLint loop = -extent; loop < extent; loop += stepSize) { // Draw lines along Z-Axis debugGridVertices.push_back(glm::vec3(loop, groundLevel, extent)); debugGridVertices.push_back(glm::vec3(loop, groundLevel, -extent)); // Draw lines across X-Axis debugGridVertices.push_back(glm::vec3(-extent, groundLevel, loop)); debugGridVertices.push_back(glm::vec3(extent, groundLevel, loop)); } glGenBuffers(1, &debugGridId); glBindBuffer(GL_ARRAY_BUFFER, debugGridId); glBufferData(GL_ARRAY_BUFFER, debugGridVertices.size() * sizeof(glm::vec3), &debugGridVertices[0], GL_STATIC_DRAW); numDebugGridVertices = debugGridVertices.size(); } void OGLRenderer::drawDebugAxes() { glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, debugAxesId); glVertexAttribPointer(0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); debugShader->setMaterial(*redMaterial); glDrawArrays(GL_LINES, 0, 2); debugShader->setMaterial(*greenMaterial); glDrawArrays(GL_LINES, 2, 2); debugShader->setMaterial(*blueMaterial); glDrawArrays(GL_LINES, 4, 2); } void OGLRenderer::enableDebugAxes(const bool enable) { debugAxesEnabled = enable; } void OGLRenderer::setCamera(shared_ptr<Camera> camera) { this->camera = camera; } void OGLRenderer::initDebugAxes() { std::vector<glm::vec3> debugAxesVertices; // X axis debugAxesVertices.push_back(glm::vec3(-1000.0f, 0.0f, 0.0f)); debugAxesVertices.push_back(glm::vec3(1000.0f, 0.0f, 0.0f)); // Y axis debugAxesVertices.push_back(glm::vec3(0.0f, -1000.0f, 0.0f)); debugAxesVertices.push_back(glm::vec3(0.0f, 1000.0f, 0.0f)); // Z axis debugAxesVertices.push_back(glm::vec3(0.0f, 0.0f, -1000.0f)); debugAxesVertices.push_back(glm::vec3(0.0f, 0.0f, 1000.0f)); glGenBuffers(1, &debugAxesId); glBindBuffer(GL_ARRAY_BUFFER, debugAxesId); glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(glm::vec3), &debugAxesVertices[0], GL_STATIC_DRAW); } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "StratumMinerGrin.h" #include "StratumSessionGrin.h" #include "StratumServerGrin.h" #include "DiffController.h" #include <boost/functional/hash.hpp> StratumMinerGrin::StratumMinerGrin( StratumSessionGrin &session, const DiffController &diffController, const std::string &clientAgent, const std::string &workerName, int64_t workerId) : StratumMinerBase( session, diffController, clientAgent, workerName, workerId) { } void StratumMinerGrin::handleRequest( const std::string &idStr, const std::string &method, const JsonNode &jparams, const JsonNode &jroot) { if (method == "submit") { handleRequest_Submit(idStr, jparams); } } void StratumMinerGrin::handleRequest_Submit( const string &idStr, const JsonNode &jparams) { // const type cannot access string indexed object member JsonNode &jsonParams = const_cast<JsonNode &>(jparams); auto &session = getSession(); if (session.getState() != StratumSession::AUTHENTICATED) { handleShare(idStr, StratumStatus::UNAUTHORIZED, 0, session.getChainId()); return; } if (jsonParams["edge_bits"].type() != Utilities::JS::type::Int || jsonParams["height"].type() != Utilities::JS::type::Int || jsonParams["job_id"].type() != Utilities::JS::type::Int || jsonParams["nonce"].type() != Utilities::JS::type::Int || jsonParams["pow"].type() != Utilities::JS::type::Array) { handleShare(idStr, StratumStatus::ILLEGAL_PARARMS, 0, session.getChainId()); return; } uint32_t edgeBits = jsonParams["edge_bits"].uint32(); uint64_t height = jsonParams["height"].uint32(); uint32_t prePowHash = jsonParams["job_id"].uint32(); uint64_t nonce = jsonParams["nonce"].uint64(); vector<uint64_t> proofs; for (auto &p : jsonParams["pow"].array()) { if (p.type() != Utilities::JS::type::Int) { handleShare( idStr, StratumStatus::ILLEGAL_PARARMS, 0, session.getChainId()); return; } else { proofs.push_back(p.uint64()); } } auto localJob = session.findLocalJob(prePowHash); // can't find local job if (localJob == nullptr) { handleShare(idStr, StratumStatus::JOB_NOT_FOUND, 0, session.getChainId()); return; } auto &server = session.getServer(); auto &worker = session.getWorker(); auto sessionId = session.getSessionId(); shared_ptr<StratumJobEx> exjob = server.GetJobRepository(localJob->chainId_) ->getStratumJobEx(localJob->jobId_); // can't find stratum job if (exjob.get() == nullptr) { handleShare(idStr, StratumStatus::JOB_NOT_FOUND, 0, localJob->chainId_); return; } auto sjob = std::static_pointer_cast<StratumJobGrin>(exjob->sjob_); auto iter = jobDiffs_.find(localJob); if (iter == jobDiffs_.end()) { handleShare(idStr, StratumStatus::JOB_NOT_FOUND, 0, localJob->chainId_); LOG(ERROR) << "can't find session's diff, worker: " << worker.fullName_; return; } auto &jobDiff = iter->second; ShareGrin share; share.set_version(ShareGrin::CURRENT_VERSION); share.set_jobid(sjob->jobId_); share.set_workerhashid(workerId_); share.set_userid(worker.userId(localJob->chainId_)); share.set_timestamp((uint64_t)time(nullptr)); share.set_status(StratumStatus::REJECT_NO_REASON); share.set_sharediff(jobDiff.currentJobDiff_); share.set_blockdiff(sjob->difficulty_); share.set_height(height); share.set_nonce(nonce); share.set_sessionid(sessionId); share.set_edgebits(edgeBits); share.set_scaling( PowScalingGrin(height, edgeBits, sjob->prePow_.secondaryScaling.value())); IpAddress ip; ip.fromIpv4Int(session.getClientIp()); share.set_ip(ip.toString()); LocalShare localShare(nonce, boost::hash_value(proofs), edgeBits); // can't add local share if (!localJob->addLocalShare(localShare)) { handleShare( idStr, StratumStatus::DUPLICATE_SHARE, jobDiff.currentJobDiff_, localJob->chainId_); // add invalid share to counter invalidSharesCounter_.insert((int64_t)time(nullptr), 1); return; } uint256 blockHash; server.checkAndUpdateShare( localJob->chainId_, share, exjob, proofs, jobDiff.jobDiffs_, worker.fullName_, blockHash, isNiceHashClient_); if (StratumStatus::isAccepted(share.status())) { DLOG(INFO) << "share reached the diff: " << share.scaledShareDiff(); } else { DLOG(INFO) << "share not reached the diff: " << share.scaledShareDiff(); } // we send share to kafka by default, but if there are lots of invalid // shares in a short time, we just drop them. if (handleShare( idStr, share.status(), share.sharediff(), localJob->chainId_)) { if (StratumStatus::isSolved(share.status())) { server.sendSolvedShare2Kafka( localJob->chainId_, share, exjob, proofs, worker, blockHash, isNiceHashClient_); // mark jobs as stale server.GetJobRepository(localJob->chainId_)->markAllJobsAsStale(); } } else { // check if there is invalid share spamming int64_t invalidSharesNum = invalidSharesCounter_.sum( time(nullptr), INVALID_SHARE_SLIDING_WINDOWS_SIZE); // too much invalid shares, don't send them to kafka if (invalidSharesNum >= INVALID_SHARE_SLIDING_WINDOWS_MAX_LIMIT) { LOG(WARNING) << "invalid share spamming, worker: " << worker.fullName_ << ", " << share.toString(); return; } } DLOG(INFO) << share.toString(); std::string message; uint32_t size = 0; if (!share.SerializeToArrayWithVersion(message, size)) { LOG(ERROR) << "share SerializeToBuffer failed!" << share.toString(); return; } server.sendShare2Kafka(localJob->chainId_, message.data(), size); } <commit_msg>Grin: check submit proof size<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "StratumMinerGrin.h" #include "StratumSessionGrin.h" #include "StratumServerGrin.h" #include "DiffController.h" #include <boost/functional/hash.hpp> StratumMinerGrin::StratumMinerGrin( StratumSessionGrin &session, const DiffController &diffController, const std::string &clientAgent, const std::string &workerName, int64_t workerId) : StratumMinerBase( session, diffController, clientAgent, workerName, workerId) { } void StratumMinerGrin::handleRequest( const std::string &idStr, const std::string &method, const JsonNode &jparams, const JsonNode &jroot) { if (method == "submit") { handleRequest_Submit(idStr, jparams); } } void StratumMinerGrin::handleRequest_Submit( const string &idStr, const JsonNode &jparams) { // const type cannot access string indexed object member JsonNode &jsonParams = const_cast<JsonNode &>(jparams); auto &session = getSession(); if (session.getState() != StratumSession::AUTHENTICATED) { handleShare(idStr, StratumStatus::UNAUTHORIZED, 0, session.getChainId()); return; } if (jsonParams["edge_bits"].type() != Utilities::JS::type::Int || jsonParams["height"].type() != Utilities::JS::type::Int || jsonParams["job_id"].type() != Utilities::JS::type::Int || jsonParams["nonce"].type() != Utilities::JS::type::Int || jsonParams["pow"].type() != Utilities::JS::type::Array || jsonParams["pow"].array().size() != 42) { handleShare(idStr, StratumStatus::ILLEGAL_PARARMS, 0, session.getChainId()); return; } uint32_t edgeBits = jsonParams["edge_bits"].uint32(); uint64_t height = jsonParams["height"].uint32(); uint32_t prePowHash = jsonParams["job_id"].uint32(); uint64_t nonce = jsonParams["nonce"].uint64(); vector<uint64_t> proofs; for (auto &p : jsonParams["pow"].array()) { if (p.type() != Utilities::JS::type::Int) { handleShare( idStr, StratumStatus::ILLEGAL_PARARMS, 0, session.getChainId()); return; } else { proofs.push_back(p.uint64()); } } auto localJob = session.findLocalJob(prePowHash); // can't find local job if (localJob == nullptr) { handleShare(idStr, StratumStatus::JOB_NOT_FOUND, 0, session.getChainId()); return; } auto &server = session.getServer(); auto &worker = session.getWorker(); auto sessionId = session.getSessionId(); shared_ptr<StratumJobEx> exjob = server.GetJobRepository(localJob->chainId_) ->getStratumJobEx(localJob->jobId_); // can't find stratum job if (exjob.get() == nullptr) { handleShare(idStr, StratumStatus::JOB_NOT_FOUND, 0, localJob->chainId_); return; } auto sjob = std::static_pointer_cast<StratumJobGrin>(exjob->sjob_); auto iter = jobDiffs_.find(localJob); if (iter == jobDiffs_.end()) { handleShare(idStr, StratumStatus::JOB_NOT_FOUND, 0, localJob->chainId_); LOG(ERROR) << "can't find session's diff, worker: " << worker.fullName_; return; } auto &jobDiff = iter->second; ShareGrin share; share.set_version(ShareGrin::CURRENT_VERSION); share.set_jobid(sjob->jobId_); share.set_workerhashid(workerId_); share.set_userid(worker.userId(localJob->chainId_)); share.set_timestamp((uint64_t)time(nullptr)); share.set_status(StratumStatus::REJECT_NO_REASON); share.set_sharediff(jobDiff.currentJobDiff_); share.set_blockdiff(sjob->difficulty_); share.set_height(height); share.set_nonce(nonce); share.set_sessionid(sessionId); share.set_edgebits(edgeBits); share.set_scaling( PowScalingGrin(height, edgeBits, sjob->prePow_.secondaryScaling.value())); IpAddress ip; ip.fromIpv4Int(session.getClientIp()); share.set_ip(ip.toString()); LocalShare localShare(nonce, boost::hash_value(proofs), edgeBits); // can't add local share if (!localJob->addLocalShare(localShare)) { handleShare( idStr, StratumStatus::DUPLICATE_SHARE, jobDiff.currentJobDiff_, localJob->chainId_); // add invalid share to counter invalidSharesCounter_.insert((int64_t)time(nullptr), 1); return; } uint256 blockHash; server.checkAndUpdateShare( localJob->chainId_, share, exjob, proofs, jobDiff.jobDiffs_, worker.fullName_, blockHash, isNiceHashClient_); if (StratumStatus::isAccepted(share.status())) { DLOG(INFO) << "share reached the diff: " << share.scaledShareDiff(); } else { DLOG(INFO) << "share not reached the diff: " << share.scaledShareDiff(); } // we send share to kafka by default, but if there are lots of invalid // shares in a short time, we just drop them. if (handleShare( idStr, share.status(), share.sharediff(), localJob->chainId_)) { if (StratumStatus::isSolved(share.status())) { server.sendSolvedShare2Kafka( localJob->chainId_, share, exjob, proofs, worker, blockHash, isNiceHashClient_); // mark jobs as stale server.GetJobRepository(localJob->chainId_)->markAllJobsAsStale(); } } else { // check if there is invalid share spamming int64_t invalidSharesNum = invalidSharesCounter_.sum( time(nullptr), INVALID_SHARE_SLIDING_WINDOWS_SIZE); // too much invalid shares, don't send them to kafka if (invalidSharesNum >= INVALID_SHARE_SLIDING_WINDOWS_MAX_LIMIT) { LOG(WARNING) << "invalid share spamming, worker: " << worker.fullName_ << ", " << share.toString(); return; } } DLOG(INFO) << share.toString(); std::string message; uint32_t size = 0; if (!share.SerializeToArrayWithVersion(message, size)) { LOG(ERROR) << "share SerializeToBuffer failed!" << share.toString(); return; } server.sendShare2Kafka(localJob->chainId_, message.data(), size); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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. #include "scriptWidget.h" #include <errno.h> #include <unistd.h> #include <QCoreApplication> #include <QHBoxLayout> #include <QKeyEvent> #include <QTimer> #include <QVBoxLayout> #include "ord/OpenRoad.hh" #include "utl/Logger.h" #include "spdlog/formatter.h" #include "spdlog/sinks/base_sink.h" namespace gui { ScriptWidget::ScriptWidget(QWidget* parent) : QDockWidget("Scripting", parent), output_(new QTextEdit), input_(new TclCmdInputWidget), pauser_(new QPushButton("Idle")), historyPosition_(0) { setObjectName("scripting"); // for settings output_->setReadOnly(true); pauser_->setEnabled(false); pauser_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); QHBoxLayout* inner_layout = new QHBoxLayout; inner_layout->addWidget(pauser_); inner_layout->addWidget(input_); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(output_, /* stretch */ 1); layout->addLayout(inner_layout); QWidget* container = new QWidget; container->setLayout(layout); QTimer::singleShot(200, this, &ScriptWidget::setupTcl); connect(input_, SIGNAL(completeCommand()), this, SLOT(executeCommand())); connect(this, SIGNAL(commandExecuted(int)), input_, SLOT(commandExecuted(int))); connect(input_, SIGNAL(historyGoBack()), this, SLOT(goBackHistory())); connect(input_, SIGNAL(historyGoForward()), this, SLOT(goForwardHistory())); connect(input_, SIGNAL(textChanged()), this, SLOT(outputChanged())); connect(output_, SIGNAL(textChanged()), this, SLOT(outputChanged())); connect(pauser_, SIGNAL(pressed()), this, SLOT(pauserClicked())); setWidget(container); } int channelClose(ClientData instance_data, Tcl_Interp* interp) { // This channel should never be closed return EINVAL; } int ScriptWidget::channelOutput(ClientData instance_data, const char* buf, int to_write, int* error_code) { // Buffer up the output ScriptWidget* widget = (ScriptWidget*) instance_data; widget->logger_->report(std::string(buf, to_write)); return to_write; } void channelWatch(ClientData instance_data, int mask) { // watch is not supported inside OpenROAD GUI } Tcl_ChannelType ScriptWidget::stdout_channel_type_ = { // Tcl stupidly defines this a non-cost char* ((char*) "stdout_channel"), /* typeName */ TCL_CHANNEL_VERSION_2, /* version */ channelClose, /* closeProc */ nullptr, /* inputProc */ ScriptWidget::channelOutput, /* outputProc */ nullptr, /* seekProc */ nullptr, /* setOptionProc */ nullptr, /* getOptionProc */ channelWatch, /* watchProc */ nullptr, /* getHandleProc */ nullptr, /* close2Proc */ nullptr, /* blockModeProc */ nullptr, /* flushProc */ nullptr, /* handlerProc */ nullptr, /* wideSeekProc */ nullptr, /* threadActionProc */ nullptr /* truncateProc */ }; int ScriptWidget::tclExitHandler(ClientData instance_data, Tcl_Interp *interp, int argc, const char **argv) { ScriptWidget* widget = (ScriptWidget*) instance_data; // announces exit to Qt emit widget->tclExiting(); // does not matter from here on, since GUI is getting ready exit return TCL_OK; } void ScriptWidget::setupTcl() { interp_ = Tcl_CreateInterp(); Tcl_Channel stdout_channel = Tcl_CreateChannel( &stdout_channel_type_, "stdout", (ClientData) this, TCL_WRITABLE); if (stdout_channel) { Tcl_SetChannelOption(nullptr, stdout_channel, "-translation", "lf"); Tcl_SetChannelOption(nullptr, stdout_channel, "-buffering", "none"); Tcl_RegisterChannel(interp_, stdout_channel); // per man page: some tcl bug Tcl_SetStdChannel(stdout_channel, TCL_STDOUT); } // Overwrite exit to allow Qt to handle exit Tcl_CreateCommand(interp_, "exit", ScriptWidget::tclExitHandler, this, nullptr); // Ensures no newlines are present in stdout stream when using logger, but normal behavior in file writing Tcl_Eval(interp_, "rename puts ::tcl::openroad::puts"); Tcl_Eval(interp_, "proc puts { args } { if {[llength $args] == 1} { ::tcl::openroad::puts -nonewline {*}$args } else { ::tcl::openroad::puts {*}$args } }"); pauser_->setText("Running"); pauser_->setStyleSheet("background-color: red"); ord::tclAppInit(interp_); pauser_->setText("Idle"); pauser_->setStyleSheet(""); // TODO: tclAppInit should return the status which we could // pass to updateOutput addTclResultToOutput(TCL_OK); input_->init(interp_); } void ScriptWidget::executeCommand() { pauser_->setText("Running"); pauser_->setStyleSheet("background-color: red"); QString command = input_->text(); // Show the command that we executed addCommandToOutput(command); int return_code = Tcl_Eval(interp_, command.toLatin1().data()); // Show its output addTclResultToOutput(return_code); if (return_code == TCL_OK) { // Update history; ignore repeated commands and keep last 100 const int history_limit = 100; if (history_.empty() || command != history_.last()) { if (history_.size() == history_limit) { history_.pop_front(); } history_.append(command); } historyPosition_ = history_.size(); } pauser_->setText("Idle"); pauser_->setStyleSheet(""); emit commandExecuted(return_code); } void ScriptWidget::addCommandToOutput(const QString& cmd) { const QString first_line_prefix = ">>> "; const QString continue_line_prefix = "... "; QString command = first_line_prefix + cmd; command.replace("\n", "\n" + continue_line_prefix); addToOutput(command, cmd_msg_); } void ScriptWidget::addTclResultToOutput(int return_code) { // Show the return value color-coded by ok/err. const char* result = Tcl_GetString(Tcl_GetObjResult(interp_)); if (result[0] != '\0') { addToOutput(result, (return_code == TCL_OK) ? tcl_ok_msg_ : tcl_error_msg_); } } void ScriptWidget::addLogToOutput(const QString& text, const QColor& color) { addToOutput(text, color); } void ScriptWidget::addReportToOutput(const QString& text) { addToOutput(text, buffer_msg_); } void ScriptWidget::addToOutput(const QString& text, const QColor& color) { // make sure cursor is at the end of the document output_->moveCursor(QTextCursor::End); QString output_text = text; if (text.endsWith('\n')) { // remove last new line output_text.chop(1); } // set new text color output_->setTextColor(color); QStringList output; for (QString& text_line : output_text.split('\n')) { // check for line length limits if (text_line.size() > max_output_line_length_) { text_line = text_line.left(max_output_line_length_-3); text_line += "..."; } output.append(text_line); } // output new text output_->append(output.join("\n")); // ensure changes are updated QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } ScriptWidget::~ScriptWidget() { // TODO: I am being lazy and not cleaning up the tcl interpreter. // We are likely exiting anyways } void ScriptWidget::goForwardHistory() { if (historyPosition_ < history_.size() - 1) { ++historyPosition_; input_->setText(history_[historyPosition_]); } else if (historyPosition_ == history_.size() - 1) { ++historyPosition_; input_->setText(history_buffer_last_); } } void ScriptWidget::goBackHistory() { if (historyPosition_ > 0) { if (historyPosition_ == history_.size()) { // whats in the buffer is the last thing the user was editing history_buffer_last_ = input_->text(); } --historyPosition_; input_->setText(history_[historyPosition_]); } } void ScriptWidget::readSettings(QSettings* settings) { settings->beginGroup("scripting"); history_ = settings->value("history").toStringList(); historyPosition_ = history_.size(); input_->readSettings(settings); settings->endGroup(); } void ScriptWidget::writeSettings(QSettings* settings) { settings->beginGroup("scripting"); settings->setValue("history", history_); input_->writeSettings(settings); settings->endGroup(); } void ScriptWidget::pause() { QString prior_text = pauser_->text(); bool prior_enable = pauser_->isEnabled(); QString prior_style = pauser_->styleSheet(); pauser_->setText("Continue"); pauser_->setStyleSheet("background-color: yellow"); pauser_->setEnabled(true); paused_ = true; // Keep processing events until the user continues while (paused_) { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } pauser_->setText(prior_text); pauser_->setStyleSheet(prior_style); pauser_->setEnabled(prior_enable); // Make changes visible while command runs QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } void ScriptWidget::pauserClicked() { paused_ = false; } void ScriptWidget::outputChanged() { // ensure the new output is visible output_->ensureCursorVisible(); // Make changes visible QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } void ScriptWidget::resizeEvent(QResizeEvent* event) { input_->setMaximumHeight(event->size().height() - output_->sizeHint().height()); QDockWidget::resizeEvent(event); } void ScriptWidget::setFont(const QFont& font) { QDockWidget::setFont(font); output_->setFont(font); input_->setFont(font); } // This class is an spdlog sink that writes the messages into the output // area. template <typename Mutex> class ScriptWidget::GuiSink : public spdlog::sinks::base_sink<Mutex> { public: GuiSink(ScriptWidget* widget) : widget_(widget) {} protected: void sink_it_(const spdlog::details::log_msg& msg) override { // Convert the msg into a formatted string spdlog::memory_buf_t formatted; this->formatter_->format(msg, formatted); std::string formatted_msg = std::string(formatted.data(), formatted.size()); if (msg.level == spdlog::level::level_enum::off) { // this comes from a ->report widget_->addReportToOutput(formatted_msg.c_str()); } else { // select error message color if message level is error or above. const QColor& msg_color = msg.level >= spdlog::level::level_enum::err ? widget_->tcl_error_msg_ : widget_->buffer_msg_; widget_->addLogToOutput(formatted_msg.c_str(), msg_color); } } void flush_() override {} private: ScriptWidget* widget_; }; void ScriptWidget::setLogger(utl::Logger* logger) { logger_ = logger; logger->addSink(std::make_shared<GuiSink<std::mutex>>(this)); } } // namespace gui <commit_msg>gui: add successful commands to tcl history during session<commit_after>/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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. #include "scriptWidget.h" #include <errno.h> #include <unistd.h> #include <QCoreApplication> #include <QHBoxLayout> #include <QKeyEvent> #include <QTimer> #include <QVBoxLayout> #include "ord/OpenRoad.hh" #include "utl/Logger.h" #include "spdlog/formatter.h" #include "spdlog/sinks/base_sink.h" namespace gui { ScriptWidget::ScriptWidget(QWidget* parent) : QDockWidget("Scripting", parent), output_(new QTextEdit), input_(new TclCmdInputWidget), pauser_(new QPushButton("Idle")), historyPosition_(0) { setObjectName("scripting"); // for settings output_->setReadOnly(true); pauser_->setEnabled(false); pauser_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); QHBoxLayout* inner_layout = new QHBoxLayout; inner_layout->addWidget(pauser_); inner_layout->addWidget(input_); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(output_, /* stretch */ 1); layout->addLayout(inner_layout); QWidget* container = new QWidget; container->setLayout(layout); QTimer::singleShot(200, this, &ScriptWidget::setupTcl); connect(input_, SIGNAL(completeCommand()), this, SLOT(executeCommand())); connect(this, SIGNAL(commandExecuted(int)), input_, SLOT(commandExecuted(int))); connect(input_, SIGNAL(historyGoBack()), this, SLOT(goBackHistory())); connect(input_, SIGNAL(historyGoForward()), this, SLOT(goForwardHistory())); connect(input_, SIGNAL(textChanged()), this, SLOT(outputChanged())); connect(output_, SIGNAL(textChanged()), this, SLOT(outputChanged())); connect(pauser_, SIGNAL(pressed()), this, SLOT(pauserClicked())); setWidget(container); } int channelClose(ClientData instance_data, Tcl_Interp* interp) { // This channel should never be closed return EINVAL; } int ScriptWidget::channelOutput(ClientData instance_data, const char* buf, int to_write, int* error_code) { // Buffer up the output ScriptWidget* widget = (ScriptWidget*) instance_data; widget->logger_->report(std::string(buf, to_write)); return to_write; } void channelWatch(ClientData instance_data, int mask) { // watch is not supported inside OpenROAD GUI } Tcl_ChannelType ScriptWidget::stdout_channel_type_ = { // Tcl stupidly defines this a non-cost char* ((char*) "stdout_channel"), /* typeName */ TCL_CHANNEL_VERSION_2, /* version */ channelClose, /* closeProc */ nullptr, /* inputProc */ ScriptWidget::channelOutput, /* outputProc */ nullptr, /* seekProc */ nullptr, /* setOptionProc */ nullptr, /* getOptionProc */ channelWatch, /* watchProc */ nullptr, /* getHandleProc */ nullptr, /* close2Proc */ nullptr, /* blockModeProc */ nullptr, /* flushProc */ nullptr, /* handlerProc */ nullptr, /* wideSeekProc */ nullptr, /* threadActionProc */ nullptr /* truncateProc */ }; int ScriptWidget::tclExitHandler(ClientData instance_data, Tcl_Interp *interp, int argc, const char **argv) { ScriptWidget* widget = (ScriptWidget*) instance_data; // announces exit to Qt emit widget->tclExiting(); // does not matter from here on, since GUI is getting ready exit return TCL_OK; } void ScriptWidget::setupTcl() { interp_ = Tcl_CreateInterp(); Tcl_Channel stdout_channel = Tcl_CreateChannel( &stdout_channel_type_, "stdout", (ClientData) this, TCL_WRITABLE); if (stdout_channel) { Tcl_SetChannelOption(nullptr, stdout_channel, "-translation", "lf"); Tcl_SetChannelOption(nullptr, stdout_channel, "-buffering", "none"); Tcl_RegisterChannel(interp_, stdout_channel); // per man page: some tcl bug Tcl_SetStdChannel(stdout_channel, TCL_STDOUT); } // Overwrite exit to allow Qt to handle exit Tcl_CreateCommand(interp_, "exit", ScriptWidget::tclExitHandler, this, nullptr); // Ensures no newlines are present in stdout stream when using logger, but normal behavior in file writing Tcl_Eval(interp_, "rename puts ::tcl::openroad::puts"); Tcl_Eval(interp_, "proc puts { args } { if {[llength $args] == 1} { ::tcl::openroad::puts -nonewline {*}$args } else { ::tcl::openroad::puts {*}$args } }"); pauser_->setText("Running"); pauser_->setStyleSheet("background-color: red"); ord::tclAppInit(interp_); pauser_->setText("Idle"); pauser_->setStyleSheet(""); // TODO: tclAppInit should return the status which we could // pass to updateOutput addTclResultToOutput(TCL_OK); input_->init(interp_); } void ScriptWidget::executeCommand() { pauser_->setText("Running"); pauser_->setStyleSheet("background-color: red"); QString command = input_->text(); // Show the command that we executed addCommandToOutput(command); int return_code = Tcl_Eval(interp_, command.toLatin1().data()); // Show its output addTclResultToOutput(return_code); if (return_code == TCL_OK) { // record the successful command to tcl history command Tcl_RecordAndEval(interp_, command.toLatin1().data(), TCL_NO_EVAL); // Update history; ignore repeated commands and keep last 100 const int history_limit = 100; if (history_.empty() || command != history_.last()) { if (history_.size() == history_limit) { history_.pop_front(); } history_.append(command); } historyPosition_ = history_.size(); } pauser_->setText("Idle"); pauser_->setStyleSheet(""); emit commandExecuted(return_code); } void ScriptWidget::addCommandToOutput(const QString& cmd) { const QString first_line_prefix = ">>> "; const QString continue_line_prefix = "... "; QString command = first_line_prefix + cmd; command.replace("\n", "\n" + continue_line_prefix); addToOutput(command, cmd_msg_); } void ScriptWidget::addTclResultToOutput(int return_code) { // Show the return value color-coded by ok/err. const char* result = Tcl_GetString(Tcl_GetObjResult(interp_)); if (result[0] != '\0') { addToOutput(result, (return_code == TCL_OK) ? tcl_ok_msg_ : tcl_error_msg_); } } void ScriptWidget::addLogToOutput(const QString& text, const QColor& color) { addToOutput(text, color); } void ScriptWidget::addReportToOutput(const QString& text) { addToOutput(text, buffer_msg_); } void ScriptWidget::addToOutput(const QString& text, const QColor& color) { // make sure cursor is at the end of the document output_->moveCursor(QTextCursor::End); QString output_text = text; if (text.endsWith('\n')) { // remove last new line output_text.chop(1); } // set new text color output_->setTextColor(color); QStringList output; for (QString& text_line : output_text.split('\n')) { // check for line length limits if (text_line.size() > max_output_line_length_) { text_line = text_line.left(max_output_line_length_-3); text_line += "..."; } output.append(text_line); } // output new text output_->append(output.join("\n")); // ensure changes are updated QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } ScriptWidget::~ScriptWidget() { // TODO: I am being lazy and not cleaning up the tcl interpreter. // We are likely exiting anyways } void ScriptWidget::goForwardHistory() { if (historyPosition_ < history_.size() - 1) { ++historyPosition_; input_->setText(history_[historyPosition_]); } else if (historyPosition_ == history_.size() - 1) { ++historyPosition_; input_->setText(history_buffer_last_); } } void ScriptWidget::goBackHistory() { if (historyPosition_ > 0) { if (historyPosition_ == history_.size()) { // whats in the buffer is the last thing the user was editing history_buffer_last_ = input_->text(); } --historyPosition_; input_->setText(history_[historyPosition_]); } } void ScriptWidget::readSettings(QSettings* settings) { settings->beginGroup("scripting"); history_ = settings->value("history").toStringList(); historyPosition_ = history_.size(); input_->readSettings(settings); settings->endGroup(); } void ScriptWidget::writeSettings(QSettings* settings) { settings->beginGroup("scripting"); settings->setValue("history", history_); input_->writeSettings(settings); settings->endGroup(); } void ScriptWidget::pause() { QString prior_text = pauser_->text(); bool prior_enable = pauser_->isEnabled(); QString prior_style = pauser_->styleSheet(); pauser_->setText("Continue"); pauser_->setStyleSheet("background-color: yellow"); pauser_->setEnabled(true); paused_ = true; // Keep processing events until the user continues while (paused_) { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } pauser_->setText(prior_text); pauser_->setStyleSheet(prior_style); pauser_->setEnabled(prior_enable); // Make changes visible while command runs QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } void ScriptWidget::pauserClicked() { paused_ = false; } void ScriptWidget::outputChanged() { // ensure the new output is visible output_->ensureCursorVisible(); // Make changes visible QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } void ScriptWidget::resizeEvent(QResizeEvent* event) { input_->setMaximumHeight(event->size().height() - output_->sizeHint().height()); QDockWidget::resizeEvent(event); } void ScriptWidget::setFont(const QFont& font) { QDockWidget::setFont(font); output_->setFont(font); input_->setFont(font); } // This class is an spdlog sink that writes the messages into the output // area. template <typename Mutex> class ScriptWidget::GuiSink : public spdlog::sinks::base_sink<Mutex> { public: GuiSink(ScriptWidget* widget) : widget_(widget) {} protected: void sink_it_(const spdlog::details::log_msg& msg) override { // Convert the msg into a formatted string spdlog::memory_buf_t formatted; this->formatter_->format(msg, formatted); std::string formatted_msg = std::string(formatted.data(), formatted.size()); if (msg.level == spdlog::level::level_enum::off) { // this comes from a ->report widget_->addReportToOutput(formatted_msg.c_str()); } else { // select error message color if message level is error or above. const QColor& msg_color = msg.level >= spdlog::level::level_enum::err ? widget_->tcl_error_msg_ : widget_->buffer_msg_; widget_->addLogToOutput(formatted_msg.c_str(), msg_color); } } void flush_() override {} private: ScriptWidget* widget_; }; void ScriptWidget::setLogger(utl::Logger* logger) { logger_ = logger; logger->addSink(std::make_shared<GuiSink<std::mutex>>(this)); } } // namespace gui <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qstatictext.h" #include "qstatictext_p.h" #include <private/qtextengine_p.h> #include <private/qfontengine_p.h> #include <QtGui/qapplication.h> QT_BEGIN_NAMESPACE /*! \class QStaticText \brief The QStaticText class enables optimized drawing of text when the text and its layout is updated rarely. \ingroup multimedia \ingroup text \mainclass QStaticText provides a way to cache layout data for a block of text so that it can be drawn more efficiently than by using QPainter::drawText() in which the layout information is recalculated with every call. The class primarily provides an optimization for cases where text and the transformations on the painter are static over several paint events. If the text or its layout is changed regularly, QPainter::drawText() is the more efficient alternative. Translating the painter will not affect the performance of drawStaticText(), but altering any other parts of the painter's transformation will cause the layout of the static text to be recalculated. \code class MyWidget: public QWidget { public: MyWidget(QWidget *parent = 0) : QWidget(parent), m_staticText("This is static text") protected: void paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawStaticText(0, 0, m_staticText); } private: QStaticText m_staticText; }; \endcode The QStaticText class can be used to mimic the behavior of QPainter::drawText() to a specific point with no boundaries, and also when QPainter::drawText() is called with a bounding rectangle. If a bounding rectangle is not required, create a QStaticText object without setting a maximum size. The text will then occupy a single line. If you set a maximum size on the QStaticText object, this will bound the text. The text will be formatted so that no line exceeds the given width. When the object is painted, it will be clipped at the given size. The position of the text is decided by the argument passed to QPainter::drawStaticText() and can change from call to call without affecting performance. \sa QPainter::drawText(), QPainter::drawStaticText(), QTextLayout, QTextDocument */ /*! Constructs an empty QStaticText */ QStaticText::QStaticText() : d_ptr(new QStaticTextPrivate) { } /*! \fn QStaticText::QStaticText(const QString &text, const QFont &font, const QSizeF &maximumSize) Constructs a QStaticText object with the given \a text which is to be rendered in the given \a font and bounded by the given \a maximumSize. If an invalid size is passed for \a maximumSize the text will be unbounded. */ QStaticText::QStaticText(const QString &text, const QSizeF &size) : d_ptr(new QStaticTextPrivate) { d_ptr->text = text; d_ptr->size = size; d_ptr->init(); } /*! Constructs a QStaticText object which is a copy of \a other. */ QStaticText::QStaticText(const QStaticText &other) { d_ptr = other.d_ptr; d_ptr->ref.ref(); } /*! Destroys the QStaticText. */ QStaticText::~QStaticText() { if (!d_ptr->ref.deref()) delete d_ptr; } /*! \internal */ void QStaticText::detach() { if (d_ptr->ref != 1) qAtomicDetach(d_ptr); } /*! Prepares the QStaticText object for being painted with the given \a matrix and the given \a font to avoid overhead when the actual drawStaticText() call is made. When drawStaticText() is called, the layout of the QStaticText will be recalculated if the painter's font or matrix is different from the one used for the currently cached layout. By default, QStaticText will use a default constructed QFont and an identity matrix to create its layout. To avoid the overhead of creating the layout the first time you draw the QStaticText with a painter whose matrix or font are different from the defaults, you can use the prepare() function and pass in the matrix and font you expect to use when drawing the text. \sa QPainter::setFont(), QPainter::setMatrix() */ void QStaticText::prepare(const QTransform &matrix, const QFont &font) { d_ptr->matrix = matrix; d_ptr->font = font; d_ptr->init(); } /*! Assigns \a other to this QStaticText. */ QStaticText &QStaticText::operator=(const QStaticText &other) { qAtomicAssign(d_ptr, other.d_ptr); return *this; } /*! Compares \a other to this QStaticText. Returns true if the texts, fonts and maximum sizes are equal. */ bool QStaticText::operator==(const QStaticText &other) const { return (d_ptr == other.d_ptr || (d_ptr->text == other.d_ptr->text && d_ptr->font == other.d_ptr->font && d_ptr->size == other.d_ptr->size)); } /*! Compares \a other to this QStaticText. Returns true if the texts, fonts or maximum sizes are different. */ bool QStaticText::operator!=(const QStaticText &other) const { return !(*this == other); } /*! Sets the text of the QStaticText to \a text. \note This function will cause the layout of the text to be recalculated. \sa text() */ void QStaticText::setText(const QString &text) { detach(); d_ptr->text = text; d_ptr->init(); } /*! Returns the text of the QStaticText. \sa setText() */ QString QStaticText::text() const { return d_ptr->text; } /*! Sets the maximum size of the QStaticText to \a maximumSize. \note This function will cause the layout of the text to be recalculated. \sa maximumSize() */ void QStaticText::setMaximumSize(const QSizeF &size) { detach(); d_ptr->size = size; d_ptr->init(); } /*! Returns the maximum size of the QStaticText. \sa setMaximumSize() */ QSizeF QStaticText::maximumSize() const { return d_ptr->size; } /*! Returns true if the text of the QStaticText is empty, and false if not. \sa text() */ bool QStaticText::isEmpty() const { return d_ptr->text.isEmpty(); } QStaticTextPrivate::QStaticTextPrivate() : items(0), itemCount(0), glyphPool(0), positionPool(0), needsClipRect(false) { ref = 1; } QStaticTextPrivate::QStaticTextPrivate(const QStaticTextPrivate &other) { ref = 1; text = other.text; font = other.font; size = other.size; init(); } QStaticTextPrivate::~QStaticTextPrivate() { delete[] items; delete[] glyphPool; delete[] positionPool; } QStaticTextPrivate *QStaticTextPrivate::get(const QStaticText *q) { return q->d_ptr; } extern int qt_defaultDpiX(); extern int qt_defaultDpiY(); namespace { class DrawTextItemRecorder: public QPaintEngine { public: DrawTextItemRecorder(int expectedItemCount, QStaticTextItem *items, int expectedGlyphCount, QFixedPoint *positionPool, glyph_t *glyphPool) : m_items(items), m_expectedItemCount(expectedItemCount), m_expectedGlyphCount(expectedGlyphCount), m_itemCount(0), m_glyphCount(0), m_positionPool(positionPool), m_glyphPool(glyphPool) { } virtual void drawTextItem(const QPointF &position, const QTextItem &textItem) { const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem); m_itemCount++; m_glyphCount += ti.glyphs.numGlyphs; if (m_items == 0) return; Q_ASSERT(m_itemCount <= m_expectedItemCount); Q_ASSERT(m_glyphCount <= m_expectedGlyphCount); QStaticTextItem *currentItem = (m_items + (m_itemCount - 1)); currentItem->fontEngine = ti.fontEngine; currentItem->chars = ti.chars; currentItem->numChars = ti.num_chars; currentItem->numGlyphs = ti.glyphs.numGlyphs; currentItem->glyphs = m_glyphPool; currentItem->glyphPositions = m_positionPool; QTransform matrix = state->transform(); matrix.translate(position.x(), position.y()); QVarLengthArray<glyph_t> glyphs; QVarLengthArray<QFixedPoint> positions; ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions); int size = glyphs.size(); Q_ASSERT(size == ti.glyphs.numGlyphs); Q_ASSERT(size == positions.size()); memmove(currentItem->glyphs, glyphs.constData(), sizeof(glyph_t) * size); memmove(currentItem->glyphPositions, positions.constData(), sizeof(QFixedPoint) * size); m_glyphPool += size; m_positionPool += size; } virtual bool begin(QPaintDevice *) { return true; } virtual bool end() { return true; } virtual void updateState(const QPaintEngineState &) {} virtual void drawPixmap(const QRectF &, const QPixmap &, const QRectF &) {} virtual Type type() const { return User; } int itemCount() const { return m_itemCount; } int glyphCount() const { return m_glyphCount; } private: QStaticTextItem *m_items; int m_itemCount; int m_glyphCount; int m_expectedItemCount; int m_expectedGlyphCount; glyph_t *m_glyphPool; QFixedPoint *m_positionPool; }; class DrawTextItemDevice: public QPaintDevice { public: DrawTextItemDevice(int expectedItemCount = -1, QStaticTextItem *items = 0, int expectedGlyphCount = -1, QFixedPoint *positionPool = 0, glyph_t *glyphPool = 0) { m_paintEngine = new DrawTextItemRecorder(expectedItemCount, items, expectedGlyphCount, positionPool, glyphPool); } ~DrawTextItemDevice() { delete m_paintEngine; } int metric(PaintDeviceMetric m) const { int val; switch (m) { case PdmWidth: case PdmHeight: case PdmWidthMM: case PdmHeightMM: val = 0; break; case PdmDpiX: case PdmPhysicalDpiX: val = qt_defaultDpiX(); break; case PdmDpiY: case PdmPhysicalDpiY: val = qt_defaultDpiY(); break; case PdmNumColors: val = 16777216; break; case PdmDepth: val = 24; break; default: val = 0; qWarning("DrawTextItemDevice::metric: Invalid metric command"); } return val; } virtual QPaintEngine *paintEngine() const { return m_paintEngine; } int itemCount() const { return m_paintEngine->itemCount(); } int glyphCount() const { return m_paintEngine->glyphCount(); } private: DrawTextItemRecorder *m_paintEngine; }; } void QStaticTextPrivate::init() { delete[] items; delete[] glyphPool; delete[] positionPool; position = QPointF(0, 0); // Draw once to count number of items and glyphs, so that we can use as little memory // as possible to store the data DrawTextItemDevice counterDevice; { QPainter painter(&counterDevice); painter.setFont(font); painter.setTransform(matrix); if (size.isValid()) painter.drawText(QRectF(QPointF(0, 0), size), text); else painter.drawText(0, 0, text); } itemCount = counterDevice.itemCount(); items = new QStaticTextItem[itemCount]; int glyphCount = counterDevice.glyphCount(); glyphPool = new glyph_t[glyphCount]; positionPool = new QFixedPoint[glyphCount]; // Draw again to actually record the items and glyphs DrawTextItemDevice recorderDevice(itemCount, items, glyphCount, positionPool, glyphPool); { QPainter painter(&recorderDevice); painter.setFont(font); painter.setTransform(matrix); if (size.isValid()) { QRectF boundingRect; painter.drawText(QRectF(QPointF(0, 0), size), Qt::TextWordWrap, text, &boundingRect); needsClipRect = boundingRect.width() > size.width() || boundingRect.height() > size.height(); } else { painter.drawText(0, 0, text); needsClipRect = false; } } } QT_END_NAMESPACE <commit_msg>doc: Add some performance hints to the documentation<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qstatictext.h" #include "qstatictext_p.h" #include <private/qtextengine_p.h> #include <private/qfontengine_p.h> #include <QtGui/qapplication.h> QT_BEGIN_NAMESPACE /*! \class QStaticText \brief The QStaticText class enables optimized drawing of text when the text and its layout is updated rarely. \ingroup multimedia \ingroup text \mainclass QStaticText provides a way to cache layout data for a block of text so that it can be drawn more efficiently than by using QPainter::drawText() in which the layout information is recalculated with every call. The class primarily provides an optimization for cases where text and the transformations on the painter are static over several paint events. If the text or its layout is changed regularly, QPainter::drawText() is the more efficient alternative. Translating the painter will not cause the layout of the text to be recalculated, but will cause a very small performance impact on drawStaticText(). Altering any other parts of the painter's transformation or the painter's font will cause the layout of the static text to be recalculated. This should be avoided as often as possible to maximize the performance benefit of using QStaticText. In addition, only affine transformations are supported by drawStaticText(). Calling drawStaticText() on a projected painter will perform slightly worse than using the regular drawText() call, so this should be avoided. \code class MyWidget: public QWidget { public: MyWidget(QWidget *parent = 0) : QWidget(parent), m_staticText("This is static text") protected: void paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawStaticText(0, 0, m_staticText); } private: QStaticText m_staticText; }; \endcode The QStaticText class can be used to mimic the behavior of QPainter::drawText() to a specific point with no boundaries, and also when QPainter::drawText() is called with a bounding rectangle. If a bounding rectangle is not required, create a QStaticText object without setting a maximum size. The text will then occupy a single line. If you set a maximum size on the QStaticText object, this will bound the text. The text will be formatted so that no line exceeds the given width. When the object is painted, it will be clipped at the given size. The position of the text is decided by the argument passed to QPainter::drawStaticText() and can change from call to call with a minimal impact on performance. \sa QPainter::drawText(), QPainter::drawStaticText(), QTextLayout, QTextDocument */ /*! Constructs an empty QStaticText */ QStaticText::QStaticText() : d_ptr(new QStaticTextPrivate) { } /*! \fn QStaticText::QStaticText(const QString &text, const QFont &font, const QSizeF &maximumSize) Constructs a QStaticText object with the given \a text which is to be rendered in the given \a font and bounded by the given \a maximumSize. If an invalid size is passed for \a maximumSize the text will be unbounded. */ QStaticText::QStaticText(const QString &text, const QSizeF &size) : d_ptr(new QStaticTextPrivate) { d_ptr->text = text; d_ptr->size = size; d_ptr->init(); } /*! Constructs a QStaticText object which is a copy of \a other. */ QStaticText::QStaticText(const QStaticText &other) { d_ptr = other.d_ptr; d_ptr->ref.ref(); } /*! Destroys the QStaticText. */ QStaticText::~QStaticText() { if (!d_ptr->ref.deref()) delete d_ptr; } /*! \internal */ void QStaticText::detach() { if (d_ptr->ref != 1) qAtomicDetach(d_ptr); } /*! Prepares the QStaticText object for being painted with the given \a matrix and the given \a font to avoid overhead when the actual drawStaticText() call is made. When drawStaticText() is called, the layout of the QStaticText will be recalculated if the painter's font or matrix is different from the one used for the currently cached layout. By default, QStaticText will use a default constructed QFont and an identity matrix to create its layout. To avoid the overhead of creating the layout the first time you draw the QStaticText with a painter whose matrix or font are different from the defaults, you can use the prepare() function and pass in the matrix and font you expect to use when drawing the text. \sa QPainter::setFont(), QPainter::setMatrix() */ void QStaticText::prepare(const QTransform &matrix, const QFont &font) { d_ptr->matrix = matrix; d_ptr->font = font; d_ptr->init(); } /*! Assigns \a other to this QStaticText. */ QStaticText &QStaticText::operator=(const QStaticText &other) { qAtomicAssign(d_ptr, other.d_ptr); return *this; } /*! Compares \a other to this QStaticText. Returns true if the texts, fonts and maximum sizes are equal. */ bool QStaticText::operator==(const QStaticText &other) const { return (d_ptr == other.d_ptr || (d_ptr->text == other.d_ptr->text && d_ptr->font == other.d_ptr->font && d_ptr->size == other.d_ptr->size)); } /*! Compares \a other to this QStaticText. Returns true if the texts, fonts or maximum sizes are different. */ bool QStaticText::operator!=(const QStaticText &other) const { return !(*this == other); } /*! Sets the text of the QStaticText to \a text. \note This function will cause the layout of the text to be recalculated. \sa text() */ void QStaticText::setText(const QString &text) { detach(); d_ptr->text = text; d_ptr->init(); } /*! Returns the text of the QStaticText. \sa setText() */ QString QStaticText::text() const { return d_ptr->text; } /*! Sets the maximum size of the QStaticText to \a maximumSize. \note This function will cause the layout of the text to be recalculated. \sa maximumSize() */ void QStaticText::setMaximumSize(const QSizeF &size) { detach(); d_ptr->size = size; d_ptr->init(); } /*! Returns the maximum size of the QStaticText. \sa setMaximumSize() */ QSizeF QStaticText::maximumSize() const { return d_ptr->size; } /*! Returns true if the text of the QStaticText is empty, and false if not. \sa text() */ bool QStaticText::isEmpty() const { return d_ptr->text.isEmpty(); } QStaticTextPrivate::QStaticTextPrivate() : items(0), itemCount(0), glyphPool(0), positionPool(0), needsClipRect(false) { ref = 1; } QStaticTextPrivate::QStaticTextPrivate(const QStaticTextPrivate &other) { ref = 1; text = other.text; font = other.font; size = other.size; init(); } QStaticTextPrivate::~QStaticTextPrivate() { delete[] items; delete[] glyphPool; delete[] positionPool; } QStaticTextPrivate *QStaticTextPrivate::get(const QStaticText *q) { return q->d_ptr; } extern int qt_defaultDpiX(); extern int qt_defaultDpiY(); namespace { class DrawTextItemRecorder: public QPaintEngine { public: DrawTextItemRecorder(int expectedItemCount, QStaticTextItem *items, int expectedGlyphCount, QFixedPoint *positionPool, glyph_t *glyphPool) : m_items(items), m_expectedItemCount(expectedItemCount), m_expectedGlyphCount(expectedGlyphCount), m_itemCount(0), m_glyphCount(0), m_positionPool(positionPool), m_glyphPool(glyphPool) { } virtual void drawTextItem(const QPointF &position, const QTextItem &textItem) { const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem); m_itemCount++; m_glyphCount += ti.glyphs.numGlyphs; if (m_items == 0) return; Q_ASSERT(m_itemCount <= m_expectedItemCount); Q_ASSERT(m_glyphCount <= m_expectedGlyphCount); QStaticTextItem *currentItem = (m_items + (m_itemCount - 1)); currentItem->fontEngine = ti.fontEngine; currentItem->chars = ti.chars; currentItem->numChars = ti.num_chars; currentItem->numGlyphs = ti.glyphs.numGlyphs; currentItem->glyphs = m_glyphPool; currentItem->glyphPositions = m_positionPool; QTransform matrix = state->transform(); matrix.translate(position.x(), position.y()); QVarLengthArray<glyph_t> glyphs; QVarLengthArray<QFixedPoint> positions; ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions); int size = glyphs.size(); Q_ASSERT(size == ti.glyphs.numGlyphs); Q_ASSERT(size == positions.size()); memmove(currentItem->glyphs, glyphs.constData(), sizeof(glyph_t) * size); memmove(currentItem->glyphPositions, positions.constData(), sizeof(QFixedPoint) * size); m_glyphPool += size; m_positionPool += size; } virtual bool begin(QPaintDevice *) { return true; } virtual bool end() { return true; } virtual void updateState(const QPaintEngineState &) {} virtual void drawPixmap(const QRectF &, const QPixmap &, const QRectF &) {} virtual Type type() const { return User; } int itemCount() const { return m_itemCount; } int glyphCount() const { return m_glyphCount; } private: QStaticTextItem *m_items; int m_itemCount; int m_glyphCount; int m_expectedItemCount; int m_expectedGlyphCount; glyph_t *m_glyphPool; QFixedPoint *m_positionPool; }; class DrawTextItemDevice: public QPaintDevice { public: DrawTextItemDevice(int expectedItemCount = -1, QStaticTextItem *items = 0, int expectedGlyphCount = -1, QFixedPoint *positionPool = 0, glyph_t *glyphPool = 0) { m_paintEngine = new DrawTextItemRecorder(expectedItemCount, items, expectedGlyphCount, positionPool, glyphPool); } ~DrawTextItemDevice() { delete m_paintEngine; } int metric(PaintDeviceMetric m) const { int val; switch (m) { case PdmWidth: case PdmHeight: case PdmWidthMM: case PdmHeightMM: val = 0; break; case PdmDpiX: case PdmPhysicalDpiX: val = qt_defaultDpiX(); break; case PdmDpiY: case PdmPhysicalDpiY: val = qt_defaultDpiY(); break; case PdmNumColors: val = 16777216; break; case PdmDepth: val = 24; break; default: val = 0; qWarning("DrawTextItemDevice::metric: Invalid metric command"); } return val; } virtual QPaintEngine *paintEngine() const { return m_paintEngine; } int itemCount() const { return m_paintEngine->itemCount(); } int glyphCount() const { return m_paintEngine->glyphCount(); } private: DrawTextItemRecorder *m_paintEngine; }; } void QStaticTextPrivate::init() { delete[] items; delete[] glyphPool; delete[] positionPool; position = QPointF(0, 0); // Draw once to count number of items and glyphs, so that we can use as little memory // as possible to store the data DrawTextItemDevice counterDevice; { QPainter painter(&counterDevice); painter.setFont(font); painter.setTransform(matrix); if (size.isValid()) painter.drawText(QRectF(QPointF(0, 0), size), text); else painter.drawText(0, 0, text); } itemCount = counterDevice.itemCount(); items = new QStaticTextItem[itemCount]; int glyphCount = counterDevice.glyphCount(); glyphPool = new glyph_t[glyphCount]; positionPool = new QFixedPoint[glyphCount]; // Draw again to actually record the items and glyphs DrawTextItemDevice recorderDevice(itemCount, items, glyphCount, positionPool, glyphPool); { QPainter painter(&recorderDevice); painter.setFont(font); painter.setTransform(matrix); if (size.isValid()) { QRectF boundingRect; painter.drawText(QRectF(QPointF(0, 0), size), Qt::TextWordWrap, text, &boundingRect); needsClipRect = boundingRect.width() > size.width() || boundingRect.height() > size.height(); } else { painter.drawText(0, 0, text); needsClipRect = false; } } } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "bindings.h" #include "FindFile.h" #ifndef DEDICATED_ONLY #include "../gui/lua/bindings-gui.h" #endif #include "bindings-math.h" #include "bindings-network.h" #include "bindings-objects.h" #include "bindings-resources.h" #include "bindings-gfx.h" #include "bindings-game.h" #include "../luaapi/types.h" #include "../luaapi/macros.h" #include "../gusgame.h" //#include "../vec.h" //#include "../gfx.h" #include "../network.h" #include "../glua.h" #include "util/log.h" #include "../gconsole.h" #ifndef DEDICATED_ONLY #include "../menu.h" #include "../blitters/context.h" #include "CViewport.h" #endif #include <cmath> #include <string> #include <list> #include <iostream> #include <fstream> #include <vector> #include "gusanos/allegro.h" using std::cerr; using std::endl; #include <boost/lexical_cast.hpp> #include <boost/bind.hpp> using boost::lexical_cast; namespace LuaBindings { int print(lua_State* L) { cerr << "LUA: "; int c = lua_gettop(L); for(int i = 1; i <= c; ++i) { if(const char* s = lua_tostring(L, i)) { cerr << s; } } cerr << '\n'; return 0; } /*! bindings.afterUpdate() This is called after every logic cycle is complete. */ /*@ bindings.atGameStart() // Not sure if this will be kept This is called at the beginning of a game. */ /*! bindings.afterRender() This is called after a rendering cycle is complete */ /*! bindings.wormRender(x, y, worm, viewport, ownerPlayer) This is called for every worm and viewport combination when it's time to render the worm HUD. (x, y) is the position of the worm in viewport coordinates. //worm// is the Worm object for which HUD should be rendered and //viewport// is the CViewport object it should be rendered to. Use the bitmap() method of CViewport to retrieve the relevant bitmap to draw on. //ownerPlayer// is the CWormHumanInputHandler object that owns //viewport//. */ /*! bindings.viewportRender(viewport, worm) This is called for every viewport when it's time to render the viewport HUD. //viewport// is the CViewport object it should be rendered to and //worm// is the Worm object of the CWormHumanInputHandler object that owns //viewport//. */ /*! bindings.wormDeath(worm) This is called when a worm dies. //worm// is the Worm object that died. */ /*! bindings.wormRemoved(worm) This is called when a worm is removed from the game. //worm// is the Worm object that will be removed. */ /*! bindings.playerUpdate(player) This is called in every logic cycle for every player. //player// is the relevant CWormHumanInputHandler object. */ /*! bindings.playerInit(player) This is called when a new player is added to the game. //player// is the CWormHumanInputHandler object that was added. */ /*! bindings.playerNetworkInit(player, connID) This is called when a player is replicated to a new client. //player// is the player replicated. //connID// is the connection ID of the new client. The connection ID can be passed to the send() method of a NetworkPlayerEvent to send events only to the player on the new client. */ //! version 0.9c /*! bindings.playerRemoved(player) This is called when a player is removed from the game. //player// is the CWormHumanInputHandler object that will be removed. */ /*! bindings.gameNetworkInit(connID) This is called when a new client joins the game. //connID// is the connection ID of the new client. The connection ID can be passed to the send() method of a NetworkGameEvent to send events only to the new client. */ /*! bindings.gameEnded(reason) This is called when the game ended and no new game is pending. //reason// can be one of the following: * EndReason.ServerQuit : The server disconnected. * EndReason.Kicked : You were kicked from the server. * EndReason.IncompatibleProtocol : You are running a protocol incompatible with the server's. * EndReason.IncompatibleData : Your data does not match the server's. */ //! version any int l_bind(lua_State* L) { char const* s = lua_tostring(L, 2); if(!s) return 0; lua_pushvalue(L, 3); LuaReference ref = lua.createReference(); luaCallbacks.bind(s, ref); return 0; } int l_console_set(lua_State* L) { char const* s = lua_tostring(L, 2); if(!s) return 0; char const* v = lua_tostring(L, 3); if(!v) return 0; std::list<std::string> args; args.push_back(v); console.invoke(s, args, false); return 0; } int l_console_get(lua_State* L) { char const* s = lua_tostring(L, 2); if(!s) return 0; std::list<std::string> args; lua_pushstring(L, console.invoke(s, args, false).c_str()); return 1; } LUA_CALLBACK(luaConsoleCommand(LuaReference ref, std::list<std::string> const& args)) for(std::list<std::string>::const_iterator i = args.begin(); i != args.end(); ++i) { lua_pushstring(lua, i->c_str()); ++params; } END_LUA_CALLBACK() /*! console_register_command(name, function) Registers the function //function// as a command in the Vermes console. When it is called, it will be passed each console parameter as a seperate parameter to the function. The command will be removed automatically when a new map is loaded. */ int l_console_register_command(lua_State* L) { char const* name = lua_tostring(L, 1); if(!name) return 0; lua_pushvalue(L, 2); LuaReference ref = lua.createReference(); console.registerCommands() (name, boost::bind(LuaBindings::luaConsoleCommand, ref, _1), true); return 0; } int l_dump(lua_State* L) { LuaContext context(L); lua_pushvalue(context, 2); lua_pushvalue(context, 3); lua_rawset(context, 1); // Set table entry char const* s = lua_tostring(context, 2); if(!s) return 0; // Allow only [A-Za-z0-9\-] for(char const* p = s; *p; ++p) { if(!isalnum(*p) && *p != '-' && *p != '_') { LUA_ELOG("Persistence name '" << s << "' invalid. Data not stored."); return 0; } } try { std::string dumpPath(std::string("persistance") + "/" + std::string(s) + ".lpr"); std::ofstream f(GetWriteFullFileName("gusanos/" + dumpPath, true).c_str(), std::ios::binary); if(!f.is_open()) return 0; context.serializeT(f, 3); } catch(std::exception& e) { cerr << "dump() failed with error: " << e.what() << endl; return 0; } return 0; } int l_undump(lua_State* L) { LuaContext context(L); char const* s = lua_tostring(context, 2); if(!s) return 0; // Allow only [A-Za-z0-9\-_] for(char const* p = s; *p; ++p) { if(!isalnum(*p) && *p != '-' && *p != '_') { LUA_ELOG("Persistence name '" << s << "' invalid. Data not retrieved."); return 0; } } try { std::string dumpPath(std::string("persistance") + "/" + std::string(s) + ".lpr"); std::ifstream f; OpenGameFileR(f, dumpPath, std::ios::binary); if(!f.is_open()) return 0; //context.deserialize(f); int r = context.evalExpression("<persistent value>", f); if(r != 1) return 0; context.pushvalue(2); // Key context.pushvalue(-2); // Value lua_rawset(context, 1); // Set table entry } catch(std::exception& e) { cerr << "undump() failed with error: " << e.what() << endl; return 0; } return 1; } /* std::string runLua(LuaReference ref, std::list<std::string> const& args) { AssertStack as(lua); lua.push(LuaContext::errorReport); lua.pushReference(ref); if(lua_isnil(lua, -1)) { lua.pop(2); return ""; } int params = 0; for(std::list<std::string>::const_iterator i = args.begin(); i != args.end(); ++i) { lua_pushstring(lua, i->c_str()); ++params; } int r = lua.call(params, 1, -params-2); if(r < 0) { lua_pushnil(lua); lua.assignReference(ref); lua.pop(1); return ""; } lua_remove(lua, -1-1); if(char const* s = lua_tostring(lua, -1)) { std::string ret(s); lua.pop(1); return ret; } lua.pop(1); return ""; }*/ #define IMPL_OLD_LUAFUNC(name) \ int name(lua_State* L) \ { warnings << #name << " not implemented" << endl; return 0; } IMPL_OLD_LUAFUNC(l_console_key_for_action); IMPL_OLD_LUAFUNC(l_console_bind); IMPL_OLD_LUAFUNC(l_console_action_for_key); IMPL_OLD_LUAFUNC(l_key_name); void init() { LuaContext& context = lua; initMath(); #ifndef DEDICATED_ONLY initGUI(OmfgGUI::menu, context); #endif initNetwork(context); initObjects(); initResources(); initGfx(); initGame(); context.functions() ("print", print) ("console_register_command", l_console_register_command) ("console_key_for_action", l_console_key_for_action) ("console_bind", l_console_bind) ("console_action_for_key", l_console_action_for_key) ("key_name", l_key_name) //("dump", l_dump) //("undump", l_undump) ; // Bindings table and metatable lua_pushstring(context, "bindings"); lua_newtable(context); // Bindings table lua_newtable(context); // Bindings metatable lua_pushstring(context, "__newindex"); lua_pushcfunction(context, l_bind); lua_rawset(context, -3); lua_setmetatable(context, -2); lua_rawset(context, LUA_GLOBALSINDEX); // Console table and metatable lua_pushstring(context, "console"); lua_newtable(context); // Console table lua_newtable(context); // Console metatable lua_pushstring(context, "__newindex"); lua_pushcfunction(context, l_console_set); lua_rawset(context, -3); lua_pushstring(context, "__index"); lua_pushcfunction(context, l_console_get); lua_rawset(context, -3); lua_setmetatable(context, -2); lua_rawset(context, LUA_GLOBALSINDEX); lua_pushstring(context, "DEDICATED_ONLY"); #ifdef DEDICATED_ONLY lua_pushboolean(context, 1); #else lua_pushboolean(context, 0); #endif lua_rawset(context, LUA_GLOBALSINDEX); SHADOW_TABLE("persistence", l_undump, l_dump); } } <commit_msg>better debug output on old non-implemented deprecated Lua functions<commit_after>#include "bindings.h" #include "FindFile.h" #ifndef DEDICATED_ONLY #include "../gui/lua/bindings-gui.h" #endif #include "bindings-math.h" #include "bindings-network.h" #include "bindings-objects.h" #include "bindings-resources.h" #include "bindings-gfx.h" #include "bindings-game.h" #include "../luaapi/types.h" #include "../luaapi/macros.h" #include "../gusgame.h" //#include "../vec.h" //#include "../gfx.h" #include "../network.h" #include "../glua.h" #include "util/log.h" #include "../gconsole.h" #ifndef DEDICATED_ONLY #include "../menu.h" #include "../blitters/context.h" #include "CViewport.h" #endif #include <cmath> #include <string> #include <list> #include <iostream> #include <fstream> #include <vector> #include "gusanos/allegro.h" using std::cerr; using std::endl; #include <boost/lexical_cast.hpp> #include <boost/bind.hpp> using boost::lexical_cast; namespace LuaBindings { int print(lua_State* L) { cerr << "LUA: "; int c = lua_gettop(L); for(int i = 1; i <= c; ++i) { if(const char* s = lua_tostring(L, i)) { cerr << s; } } cerr << '\n'; return 0; } /*! bindings.afterUpdate() This is called after every logic cycle is complete. */ /*@ bindings.atGameStart() // Not sure if this will be kept This is called at the beginning of a game. */ /*! bindings.afterRender() This is called after a rendering cycle is complete */ /*! bindings.wormRender(x, y, worm, viewport, ownerPlayer) This is called for every worm and viewport combination when it's time to render the worm HUD. (x, y) is the position of the worm in viewport coordinates. //worm// is the Worm object for which HUD should be rendered and //viewport// is the CViewport object it should be rendered to. Use the bitmap() method of CViewport to retrieve the relevant bitmap to draw on. //ownerPlayer// is the CWormHumanInputHandler object that owns //viewport//. */ /*! bindings.viewportRender(viewport, worm) This is called for every viewport when it's time to render the viewport HUD. //viewport// is the CViewport object it should be rendered to and //worm// is the Worm object of the CWormHumanInputHandler object that owns //viewport//. */ /*! bindings.wormDeath(worm) This is called when a worm dies. //worm// is the Worm object that died. */ /*! bindings.wormRemoved(worm) This is called when a worm is removed from the game. //worm// is the Worm object that will be removed. */ /*! bindings.playerUpdate(player) This is called in every logic cycle for every player. //player// is the relevant CWormHumanInputHandler object. */ /*! bindings.playerInit(player) This is called when a new player is added to the game. //player// is the CWormHumanInputHandler object that was added. */ /*! bindings.playerNetworkInit(player, connID) This is called when a player is replicated to a new client. //player// is the player replicated. //connID// is the connection ID of the new client. The connection ID can be passed to the send() method of a NetworkPlayerEvent to send events only to the player on the new client. */ //! version 0.9c /*! bindings.playerRemoved(player) This is called when a player is removed from the game. //player// is the CWormHumanInputHandler object that will be removed. */ /*! bindings.gameNetworkInit(connID) This is called when a new client joins the game. //connID// is the connection ID of the new client. The connection ID can be passed to the send() method of a NetworkGameEvent to send events only to the new client. */ /*! bindings.gameEnded(reason) This is called when the game ended and no new game is pending. //reason// can be one of the following: * EndReason.ServerQuit : The server disconnected. * EndReason.Kicked : You were kicked from the server. * EndReason.IncompatibleProtocol : You are running a protocol incompatible with the server's. * EndReason.IncompatibleData : Your data does not match the server's. */ //! version any int l_bind(lua_State* L) { char const* s = lua_tostring(L, 2); if(!s) return 0; lua_pushvalue(L, 3); LuaReference ref = lua.createReference(); luaCallbacks.bind(s, ref); return 0; } int l_console_set(lua_State* L) { char const* s = lua_tostring(L, 2); if(!s) return 0; char const* v = lua_tostring(L, 3); if(!v) return 0; std::list<std::string> args; args.push_back(v); console.invoke(s, args, false); return 0; } int l_console_get(lua_State* L) { char const* s = lua_tostring(L, 2); if(!s) return 0; std::list<std::string> args; lua_pushstring(L, console.invoke(s, args, false).c_str()); return 1; } LUA_CALLBACK(luaConsoleCommand(LuaReference ref, std::list<std::string> const& args)) for(std::list<std::string>::const_iterator i = args.begin(); i != args.end(); ++i) { lua_pushstring(lua, i->c_str()); ++params; } END_LUA_CALLBACK() /*! console_register_command(name, function) Registers the function //function// as a command in the Vermes console. When it is called, it will be passed each console parameter as a seperate parameter to the function. The command will be removed automatically when a new map is loaded. */ int l_console_register_command(lua_State* L) { char const* name = lua_tostring(L, 1); if(!name) return 0; lua_pushvalue(L, 2); LuaReference ref = lua.createReference(); console.registerCommands() (name, boost::bind(LuaBindings::luaConsoleCommand, ref, _1), true); return 0; } int l_dump(lua_State* L) { LuaContext context(L); lua_pushvalue(context, 2); lua_pushvalue(context, 3); lua_rawset(context, 1); // Set table entry char const* s = lua_tostring(context, 2); if(!s) return 0; // Allow only [A-Za-z0-9\-] for(char const* p = s; *p; ++p) { if(!isalnum(*p) && *p != '-' && *p != '_') { LUA_ELOG("Persistence name '" << s << "' invalid. Data not stored."); return 0; } } try { std::string dumpPath(std::string("persistance") + "/" + std::string(s) + ".lpr"); std::ofstream f(GetWriteFullFileName("gusanos/" + dumpPath, true).c_str(), std::ios::binary); if(!f.is_open()) return 0; context.serializeT(f, 3); } catch(std::exception& e) { cerr << "dump() failed with error: " << e.what() << endl; return 0; } return 0; } int l_undump(lua_State* L) { LuaContext context(L); char const* s = lua_tostring(context, 2); if(!s) return 0; // Allow only [A-Za-z0-9\-_] for(char const* p = s; *p; ++p) { if(!isalnum(*p) && *p != '-' && *p != '_') { LUA_ELOG("Persistence name '" << s << "' invalid. Data not retrieved."); return 0; } } try { std::string dumpPath(std::string("persistance") + "/" + std::string(s) + ".lpr"); std::ifstream f; OpenGameFileR(f, dumpPath, std::ios::binary); if(!f.is_open()) return 0; //context.deserialize(f); int r = context.evalExpression("<persistent value>", f); if(r != 1) return 0; context.pushvalue(2); // Key context.pushvalue(-2); // Value lua_rawset(context, 1); // Set table entry } catch(std::exception& e) { cerr << "undump() failed with error: " << e.what() << endl; return 0; } return 1; } /* std::string runLua(LuaReference ref, std::list<std::string> const& args) { AssertStack as(lua); lua.push(LuaContext::errorReport); lua.pushReference(ref); if(lua_isnil(lua, -1)) { lua.pop(2); return ""; } int params = 0; for(std::list<std::string>::const_iterator i = args.begin(); i != args.end(); ++i) { lua_pushstring(lua, i->c_str()); ++params; } int r = lua.call(params, 1, -params-2); if(r < 0) { lua_pushnil(lua); lua.assignReference(ref); lua.pop(1); return ""; } lua_remove(lua, -1-1); if(char const* s = lua_tostring(lua, -1)) { std::string ret(s); lua.pop(1); return ret; } lua.pop(1); return ""; }*/ static void print_Lua_debug(lua_State* context, const std::string& msg, bool withbacktrace) { lua_Debug info; char const* lastname; for(int i = 1; lua_getstack(context, i, &info); ++i) { lua_getinfo (context, "Snl", &info); char const* name = info.name ? info.name : "N/A"; if(i == 1) cerr << info.source << ":" << info.currentline << ": " << msg << endl; else cerr << info.source << ":" << info.currentline << ": " << lastname << " called from here" << endl; lastname = name; if(!withbacktrace) break; } } static std::string getLuaFuncName(lua_State* context) { lua_Debug info; if(lua_getstack(context, 0, &info)) { lua_getinfo(context, "Snl", &info); if(info.name) return info.name; return "UNKNOWN-LUA-FUNC"; } return "NO-LUA-STACK"; } #define IMPL_OLD_LUAFUNC(name) \ int name(lua_State* L) \ { \ static bool printedWarning = false; \ if(!printedWarning) { \ std::string my_func_name = getLuaFuncName(L); \ print_Lua_debug(L, my_func_name + " not implemented (further warnings omitted)", false); \ printedWarning = true; \ } \ return 0; \ } IMPL_OLD_LUAFUNC(l_console_key_for_action); IMPL_OLD_LUAFUNC(l_console_bind); IMPL_OLD_LUAFUNC(l_console_action_for_key); IMPL_OLD_LUAFUNC(l_key_name); void init() { LuaContext& context = lua; initMath(); #ifndef DEDICATED_ONLY initGUI(OmfgGUI::menu, context); #endif initNetwork(context); initObjects(); initResources(); initGfx(); initGame(); context.functions() ("print", print) ("console_register_command", l_console_register_command) ("console_key_for_action", l_console_key_for_action) ("console_bind", l_console_bind) ("console_action_for_key", l_console_action_for_key) ("key_name", l_key_name) //("dump", l_dump) //("undump", l_undump) ; // Bindings table and metatable lua_pushstring(context, "bindings"); lua_newtable(context); // Bindings table lua_newtable(context); // Bindings metatable lua_pushstring(context, "__newindex"); lua_pushcfunction(context, l_bind); lua_rawset(context, -3); lua_setmetatable(context, -2); lua_rawset(context, LUA_GLOBALSINDEX); // Console table and metatable lua_pushstring(context, "console"); lua_newtable(context); // Console table lua_newtable(context); // Console metatable lua_pushstring(context, "__newindex"); lua_pushcfunction(context, l_console_set); lua_rawset(context, -3); lua_pushstring(context, "__index"); lua_pushcfunction(context, l_console_get); lua_rawset(context, -3); lua_setmetatable(context, -2); lua_rawset(context, LUA_GLOBALSINDEX); lua_pushstring(context, "DEDICATED_ONLY"); #ifdef DEDICATED_ONLY lua_pushboolean(context, 1); #else lua_pushboolean(context, 0); #endif lua_rawset(context, LUA_GLOBALSINDEX); SHADOW_TABLE("persistence", l_undump, l_dump); } } <|endoftext|>
<commit_before>/* * Plans.cpp * * Created on: 08.03.2016 * Author: hartung */ #include "initialization/Plans.hpp" namespace Synchronization { } /* namespace Synchronization */ <commit_msg>Remove empty source file from repository<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */ /* libmwaw * Version: MPL 2.0 / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 2.0 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Alternatively, the contents of this file may be used under the terms of * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the LGPLv2+ are applicable * instead of those above. */ #include <librevenge-stream/librevenge-stream.h> class MWAWStringStreamPrivate; /** internal class used to create a RVNGInputStream from a unsigned char's pointer \note this class (highly inspired from librevenge) does not implement the isStructured's protocol, ie. it only returns false. */ class MWAWStringStream: public librevenge::RVNGInputStream { public: //! constructor MWAWStringStream(const unsigned char *data, const unsigned int dataSize); //! destructor ~MWAWStringStream(); //! append some data at the end of the string void append(const unsigned char *data, const unsigned int dataSize); /**! reads numbytes data. * \return a pointer to the read elements */ const unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead); //! returns actual offset position long tell(); /*! \brief seeks to a offset position, from actual, beginning or ending position * \return 0 if ok */ int seek(long offset, librevenge::RVNG_SEEK_TYPE seekType); //! returns true if we are at the end of the section/file bool isEnd(); /** returns true if the stream is ole \sa returns always false*/ bool isStructured(); /** returns the number of sub streams. \sa returns always 0*/ unsigned subStreamCount(); /** returns the ith sub streams name \sa returns always 0*/ const char *subStreamName(unsigned); /** returns true if a substream with name exists \sa returns always false*/ bool existsSubStream(const char *name); /** return a new stream for a ole zone \sa returns always 0 */ librevenge::RVNGInputStream *getSubStreamByName(const char *name); /** return a new stream for a ole zone \sa returns always 0 */ librevenge::RVNGInputStream *getSubStreamById(unsigned); private: MWAWStringStreamPrivate *d; MWAWStringStream(const MWAWStringStream &); // copy is not allowed MWAWStringStream &operator=(const MWAWStringStream &); // assignment is not allowed }; // vim: set filetype=cpp tabstop=2 shiftwidth=2 cindent autoindent smartindent noexpandtab: <commit_msg>add missing include guard<commit_after>/* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */ /* libmwaw * Version: MPL 2.0 / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 2.0 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Alternatively, the contents of this file may be used under the terms of * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the LGPLv2+ are applicable * instead of those above. */ #ifndef MWAWSTRINGSTREAM_HXX #define MWAWSTRINGSTREAM_HXX #include <librevenge-stream/librevenge-stream.h> class MWAWStringStreamPrivate; /** internal class used to create a RVNGInputStream from a unsigned char's pointer \note this class (highly inspired from librevenge) does not implement the isStructured's protocol, ie. it only returns false. */ class MWAWStringStream: public librevenge::RVNGInputStream { public: //! constructor MWAWStringStream(const unsigned char *data, const unsigned int dataSize); //! destructor ~MWAWStringStream(); //! append some data at the end of the string void append(const unsigned char *data, const unsigned int dataSize); /**! reads numbytes data. * \return a pointer to the read elements */ const unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead); //! returns actual offset position long tell(); /*! \brief seeks to a offset position, from actual, beginning or ending position * \return 0 if ok */ int seek(long offset, librevenge::RVNG_SEEK_TYPE seekType); //! returns true if we are at the end of the section/file bool isEnd(); /** returns true if the stream is ole \sa returns always false*/ bool isStructured(); /** returns the number of sub streams. \sa returns always 0*/ unsigned subStreamCount(); /** returns the ith sub streams name \sa returns always 0*/ const char *subStreamName(unsigned); /** returns true if a substream with name exists \sa returns always false*/ bool existsSubStream(const char *name); /** return a new stream for a ole zone \sa returns always 0 */ librevenge::RVNGInputStream *getSubStreamByName(const char *name); /** return a new stream for a ole zone \sa returns always 0 */ librevenge::RVNGInputStream *getSubStreamById(unsigned); private: MWAWStringStreamPrivate *d; MWAWStringStream(const MWAWStringStream &); // copy is not allowed MWAWStringStream &operator=(const MWAWStringStream &); // assignment is not allowed }; #endif // vim: set filetype=cpp tabstop=2 shiftwidth=2 cindent autoindent smartindent noexpandtab: <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]> // Copyright 2007-2008 Inge Wallin <[email protected]> // #include "PlacemarkPainter.h" #include <QtCore/QModelIndex> #include <QtCore/QPoint> #include <QtGui/QItemSelectionModel> #include <QtGui/QPainter> #include <QtGui/QPixmap> #include "MarbleDebug.h" #include "AbstractProjection.h" #include "GeoDataStyle.h" #include "MarblePlacemarkModel.h" #include "ViewportParams.h" #include "VisiblePlacemark.h" using namespace Marble; PlacemarkPainter::PlacemarkPainter( QObject* parent ) : QObject( parent ) { m_useXWorkaround = testXBug(); mDebug() << "Use workaround: " << ( m_useXWorkaround ? "1" : "0" ); m_defaultLabelColor = Qt::black; } PlacemarkPainter::~PlacemarkPainter() { } void PlacemarkPainter::setDefaultLabelColor( const QColor& color ) { m_defaultLabelColor = color; } void PlacemarkPainter::drawPlacemarks( QPainter* painter, QVector<VisiblePlacemark*> visiblePlacemarks, const QItemSelection &selection, ViewportParams *viewport ) { QVector<VisiblePlacemark*>::const_iterator visit = visiblePlacemarks.constEnd(); QVector<VisiblePlacemark*>::const_iterator itEnd = visiblePlacemarks.constBegin(); VisiblePlacemark *mark = 0; int imageWidth = viewport->width(); while ( visit != itEnd ) { --visit; mark = *visit; if ( mark->labelPixmap().isNull() ) { bool isSelected = false; foreach ( QModelIndex index, selection.indexes() ) { GeoDataPlacemark *placemark = dynamic_cast<GeoDataPlacemark*>(qvariant_cast<GeoDataObject*>(index.data( MarblePlacemarkModel::ObjectPointerRole ) )); if (mark->placemark() == placemark ) { isSelected = true; break; } } drawLabelPixmap( mark, isSelected ); } painter->drawPixmap( mark->symbolPosition(), mark->symbolPixmap() ); painter->drawPixmap( mark->labelRect(), mark->labelPixmap() ); if ( ! viewport->currentProjection()->repeatX() ) continue; int tempSymbol = mark->symbolPosition().x(); int tempText = mark->labelRect().x(); for ( int i = tempSymbol - 4 * viewport->radius(); i >= 0; i -= 4 * viewport->radius() ) { QRect labelRect( mark->labelRect() ); labelRect.moveLeft(i - tempSymbol + tempText ); mark->setLabelRect( labelRect ); QPoint symbolPos( mark->symbolPosition() ); symbolPos.setX( i ); mark->setSymbolPosition( symbolPos ); painter->drawPixmap( mark->symbolPosition(), mark->symbolPixmap() ); painter->drawPixmap( mark->labelRect(), mark->labelPixmap() ); } for ( int i = tempSymbol; i <= imageWidth; i += 4 * viewport->radius() ) { QRect labelRect( mark->labelRect() ); labelRect.moveLeft(i - tempSymbol + tempText ); mark->setLabelRect( labelRect ); QPoint symbolPos( mark->symbolPosition() ); symbolPos.setX( i ); mark->setSymbolPosition( symbolPos ); painter->drawPixmap( mark->symbolPosition(), mark->symbolPixmap() ); painter->drawPixmap( mark->labelRect(), mark->labelPixmap() ); } } } inline void PlacemarkPainter::drawLabelText(QPainter& labelPainter, const QString &name, const QFont &labelFont ) { QFont font = labelFont; font.setWeight( 75 ); QPen outlinepen( Qt::white ); outlinepen.setWidthF( s_labelOutlineWidth ); QBrush outlinebrush( Qt::black ); QPainterPath outlinepath; int fontascent = QFontMetrics( font ).ascent(); const QPointF baseline( s_labelOutlineWidth / 2.0, fontascent ); outlinepath.addText( baseline, font, name ); labelPainter.setRenderHint( QPainter::Antialiasing, true ); labelPainter.setPen( outlinepen ); labelPainter.setBrush( outlinebrush ); labelPainter.drawPath( outlinepath ); labelPainter.setPen( Qt::NoPen ); labelPainter.drawPath( outlinepath ); labelPainter.setRenderHint( QPainter::Antialiasing, false ); } inline void PlacemarkPainter::drawLabelPixmap( VisiblePlacemark *mark, bool isSelected ) { QPainter labelPainter; QPixmap labelPixmap; const GeoDataPlacemark *placemark = mark->placemark(); GeoDataStyle* style = placemark->style(); QString labelName = mark->name(); QRect labelRect = mark->labelRect(); QFont labelFont = style->labelStyle().font(); QColor labelColor = style->labelStyle().color(); // FIXME: To be removed after MapTheme / KML refactoring if ( ( labelColor == Qt::black || labelColor == QColor( "#404040" ) ) && m_defaultLabelColor != Qt::black ) labelColor = m_defaultLabelColor; // Due to some XOrg bug this requires a workaround via // QImage in some cases (at least with Qt 4.2). if ( !m_useXWorkaround ) { labelPixmap = QPixmap( labelRect.size() ); labelPixmap.fill( Qt::transparent ); labelPainter.begin( &labelPixmap ); if ( !isSelected ) { labelPainter.setFont( labelFont ); labelPainter.setPen( labelColor ); int fontascent = QFontMetrics( labelFont ).ascent(); labelPainter.drawText( 0, fontascent, labelName ); } else { drawLabelText( labelPainter, labelName, labelFont ); } labelPainter.end(); } else { QImage image( labelRect.size(), QImage::Format_ARGB32_Premultiplied ); image.fill( 0 ); labelPainter.begin( &image ); if ( !isSelected ) { labelPainter.setFont( labelFont ); labelPainter.setPen( labelColor ); int fontascent = QFontMetrics( labelFont ).ascent(); labelPainter.drawText( 0, fontascent, labelName ); } else { drawLabelText( labelPainter, labelName, labelFont ); } labelPainter.end(); labelPixmap = QPixmap::fromImage( image ); } mark->setLabelPixmap( labelPixmap ); } // Test if there a bug in the X server which makes // text fully transparent if it gets written on // QPixmaps that were initialized by filling them // with Qt::transparent bool PlacemarkPainter::testXBug() { QString testchar( "K" ); QFont font( "Sans Serif", 10 ); int fontheight = QFontMetrics( font ).height(); int fontwidth = QFontMetrics( font ).width(testchar); int fontascent = QFontMetrics( font ).ascent(); QPixmap pixmap( fontwidth, fontheight ); pixmap.fill( Qt::transparent ); QPainter textpainter; textpainter.begin( &pixmap ); textpainter.setPen( QColor( 0, 0, 0, 255 ) ); textpainter.setFont( font ); textpainter.drawText( 0, fontascent, testchar ); textpainter.end(); QImage image = pixmap.toImage(); for ( int x = 0; x < fontwidth; ++x ) { for ( int y = 0; y < fontheight; ++y ) { if ( qAlpha( image.pixel( x, y ) ) > 0 ) return false; } } return true; } #include "PlacemarkPainter.moc" <commit_msg>Changes: Don't draw on label pixmaps with invalid rect.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]> // Copyright 2007-2008 Inge Wallin <[email protected]> // #include "PlacemarkPainter.h" #include <QtCore/QModelIndex> #include <QtCore/QPoint> #include <QtGui/QItemSelectionModel> #include <QtGui/QPainter> #include <QtGui/QPixmap> #include "MarbleDebug.h" #include "AbstractProjection.h" #include "GeoDataStyle.h" #include "MarblePlacemarkModel.h" #include "ViewportParams.h" #include "VisiblePlacemark.h" using namespace Marble; PlacemarkPainter::PlacemarkPainter( QObject* parent ) : QObject( parent ) { m_useXWorkaround = testXBug(); mDebug() << "Use workaround: " << ( m_useXWorkaround ? "1" : "0" ); m_defaultLabelColor = Qt::black; } PlacemarkPainter::~PlacemarkPainter() { } void PlacemarkPainter::setDefaultLabelColor( const QColor& color ) { m_defaultLabelColor = color; } void PlacemarkPainter::drawPlacemarks( QPainter* painter, QVector<VisiblePlacemark*> visiblePlacemarks, const QItemSelection &selection, ViewportParams *viewport ) { QVector<VisiblePlacemark*>::const_iterator visit = visiblePlacemarks.constEnd(); QVector<VisiblePlacemark*>::const_iterator itEnd = visiblePlacemarks.constBegin(); VisiblePlacemark *mark = 0; int imageWidth = viewport->width(); while ( visit != itEnd ) { --visit; mark = *visit; if ( mark->labelPixmap().isNull() ) { bool isSelected = false; foreach ( QModelIndex index, selection.indexes() ) { GeoDataPlacemark *placemark = dynamic_cast<GeoDataPlacemark*>(qvariant_cast<GeoDataObject*>(index.data( MarblePlacemarkModel::ObjectPointerRole ) )); if (mark->placemark() == placemark ) { isSelected = true; break; } } drawLabelPixmap( mark, isSelected ); } painter->drawPixmap( mark->symbolPosition(), mark->symbolPixmap() ); painter->drawPixmap( mark->labelRect(), mark->labelPixmap() ); if ( ! viewport->currentProjection()->repeatX() ) continue; int tempSymbol = mark->symbolPosition().x(); int tempText = mark->labelRect().x(); for ( int i = tempSymbol - 4 * viewport->radius(); i >= 0; i -= 4 * viewport->radius() ) { QRect labelRect( mark->labelRect() ); labelRect.moveLeft(i - tempSymbol + tempText ); mark->setLabelRect( labelRect ); QPoint symbolPos( mark->symbolPosition() ); symbolPos.setX( i ); mark->setSymbolPosition( symbolPos ); painter->drawPixmap( mark->symbolPosition(), mark->symbolPixmap() ); painter->drawPixmap( mark->labelRect(), mark->labelPixmap() ); } for ( int i = tempSymbol; i <= imageWidth; i += 4 * viewport->radius() ) { QRect labelRect( mark->labelRect() ); labelRect.moveLeft(i - tempSymbol + tempText ); mark->setLabelRect( labelRect ); QPoint symbolPos( mark->symbolPosition() ); symbolPos.setX( i ); mark->setSymbolPosition( symbolPos ); painter->drawPixmap( mark->symbolPosition(), mark->symbolPixmap() ); painter->drawPixmap( mark->labelRect(), mark->labelPixmap() ); } } } inline void PlacemarkPainter::drawLabelText(QPainter& labelPainter, const QString &name, const QFont &labelFont ) { QFont font = labelFont; font.setWeight( 75 ); QPen outlinepen( Qt::white ); outlinepen.setWidthF( s_labelOutlineWidth ); QBrush outlinebrush( Qt::black ); QPainterPath outlinepath; int fontascent = QFontMetrics( font ).ascent(); const QPointF baseline( s_labelOutlineWidth / 2.0, fontascent ); outlinepath.addText( baseline, font, name ); labelPainter.setRenderHint( QPainter::Antialiasing, true ); labelPainter.setPen( outlinepen ); labelPainter.setBrush( outlinebrush ); labelPainter.drawPath( outlinepath ); labelPainter.setPen( Qt::NoPen ); labelPainter.drawPath( outlinepath ); labelPainter.setRenderHint( QPainter::Antialiasing, false ); } inline void PlacemarkPainter::drawLabelPixmap( VisiblePlacemark *mark, bool isSelected ) { QPainter labelPainter; QPixmap labelPixmap; const GeoDataPlacemark *placemark = mark->placemark(); GeoDataStyle* style = placemark->style(); QString labelName = mark->name(); QRect labelRect = mark->labelRect(); if ( !labelRect.isValid() ) { mark->setLabelPixmap( QPixmap() ); return; } QFont labelFont = style->labelStyle().font(); QColor labelColor = style->labelStyle().color(); // FIXME: To be removed after MapTheme / KML refactoring if ( ( labelColor == Qt::black || labelColor == QColor( "#404040" ) ) && m_defaultLabelColor != Qt::black ) labelColor = m_defaultLabelColor; // Due to some XOrg bug this requires a workaround via // QImage in some cases (at least with Qt 4.2). if ( !m_useXWorkaround ) { labelPixmap = QPixmap( labelRect.size() ); labelPixmap.fill( Qt::transparent ); labelPainter.begin( &labelPixmap ); if ( !isSelected ) { labelPainter.setFont( labelFont ); labelPainter.setPen( labelColor ); int fontascent = QFontMetrics( labelFont ).ascent(); labelPainter.drawText( 0, fontascent, labelName ); } else { drawLabelText( labelPainter, labelName, labelFont ); } labelPainter.end(); } else { QImage image( labelRect.size(), QImage::Format_ARGB32_Premultiplied ); image.fill( 0 ); labelPainter.begin( &image ); if ( !isSelected ) { labelPainter.setFont( labelFont ); labelPainter.setPen( labelColor ); int fontascent = QFontMetrics( labelFont ).ascent(); labelPainter.drawText( 0, fontascent, labelName ); } else { drawLabelText( labelPainter, labelName, labelFont ); } labelPainter.end(); labelPixmap = QPixmap::fromImage( image ); } mark->setLabelPixmap( labelPixmap ); } // Test if there a bug in the X server which makes // text fully transparent if it gets written on // QPixmaps that were initialized by filling them // with Qt::transparent bool PlacemarkPainter::testXBug() { QString testchar( "K" ); QFont font( "Sans Serif", 10 ); int fontheight = QFontMetrics( font ).height(); int fontwidth = QFontMetrics( font ).width(testchar); int fontascent = QFontMetrics( font ).ascent(); QPixmap pixmap( fontwidth, fontheight ); pixmap.fill( Qt::transparent ); QPainter textpainter; textpainter.begin( &pixmap ); textpainter.setPen( QColor( 0, 0, 0, 255 ) ); textpainter.setFont( font ); textpainter.drawText( 0, fontascent, testchar ); textpainter.end(); QImage image = pixmap.toImage(); for ( int x = 0; x < fontwidth; ++x ) { for ( int y = 0; y < fontheight; ++y ) { if ( qAlpha( image.pixel( x, y ) ) > 0 ) return false; } } return true; } #include "PlacemarkPainter.moc" <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <iostream> #include <sstream> #include <string> #include <utility> #include <vector> #include <gtest/gtest.h> #include "bit_index_storage.hpp" #include "../framework/stream_writer.hpp" using std::pair; using std::stringstream; using std::string; using std::vector; namespace jubatus { namespace core { namespace storage { bit_vector make_vector(const string& b) { bit_vector v; v.resize_and_clear(b.size()); for (size_t i = 0; i < b.size(); ++i) { if (b[i] == '1') { v.set_bit(i); } } return v; } TEST(bit_index_storage, trivial) { bit_index_storage s; EXPECT_EQ("bit_index_storage", s.name()); s.set_row("r1", make_vector("0101")); s.set_row("r2", make_vector("1010")); s.set_row("r3", make_vector("1110")); s.set_row("r4", make_vector("1100")); vector<pair<string, float> > ids; s.similar_row(make_vector("1100"), ids, 2); ASSERT_EQ(2u, ids.size()); EXPECT_EQ("r4", ids[0].first); EXPECT_FLOAT_EQ(1.0, ids[0].second); EXPECT_EQ("r3", ids[1].first); EXPECT_FLOAT_EQ(0.75, ids[1].second); msgpack::sbuffer buf; framework::stream_writer<msgpack::sbuffer> st(buf); framework::jubatus_packer jp(st); framework::packer packer(jp); s.pack(packer); bit_index_storage t; msgpack::unpacked unpacked; msgpack::unpack(&unpacked, buf.data(), buf.size()); t.unpack(unpacked.get()); ids.clear(); t.similar_row(make_vector("1100"), ids, 2); ASSERT_EQ(2u, ids.size()); EXPECT_EQ("r4", ids[0].first); s.remove_row("r4"); ids.clear(); s.similar_row(make_vector("1100"), ids, 2); EXPECT_NE("r4", ids[0].first); s.clear(); ids.clear(); s.similar_row(make_vector("1100"), ids, 2); EXPECT_TRUE(ids.empty()); } TEST(bit_index_storage, row_operations) { std::vector<std::string> ids; bit_index_storage s1; s1.set_row("r1", make_vector("0101")); s1.set_row("r2", make_vector("1010")); s1.set_row("r3", make_vector("1100")); s1.get_all_row_ids(ids); EXPECT_EQ(3u, ids.size()); s1.remove_row("r1"); s1.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); // do MIX bit_table_t d1; s1.get_diff(d1); s1.put_diff(d1); s1.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); s1.remove_row("r2"); s1.get_all_row_ids(ids); EXPECT_EQ(1u, ids.size()); // do MIX bit_table_t d2; s1.get_diff(d2); s1.put_diff(d2); s1.get_all_row_ids(ids); ASSERT_EQ(1u, ids.size()); EXPECT_EQ("r3", ids[0]); } TEST(bit_index_storage, diff) { bit_index_storage s1, s2; s1.set_row("r1", make_vector("0101")); s1.set_row("r2", make_vector("1010")); bit_table_t d1; s1.get_diff(d1); s2.put_diff(d1); bit_vector v; s2.get_row("r1", v); EXPECT_TRUE(make_vector("0101") == v); v.resize_and_clear(4); s2.get_row("r2", v); EXPECT_TRUE(make_vector("1010") == v); } TEST(bit_index_storage, mix) { bit_index_storage s1, s2, s3; s1.set_row("r1", make_vector("0101")); s1.set_row("r2", make_vector("1010")); bit_table_t d1; s1.get_diff(d1); s2.set_row("r1", make_vector("1110")); s2.set_row("r3", make_vector("1100")); bit_table_t d2; s2.get_diff(d2); s1.mix(d1, d2); // d2 is // r1: 0101 (s1) // r2: 1010 (s1) // r3: 1100 (s2) s3.set_row("r1", make_vector("1111")); s3.set_row("r2", make_vector("1111")); s3.set_row("r3", make_vector("1111")); s3.set_row("r4", make_vector("1111")); s3.put_diff(d2); // r1, r2 and r3 are overwritten by d2 // r4 is no longer retained bit_vector v; s3.get_row("r1", v); EXPECT_TRUE(v == make_vector("0101")); s3.get_row("r2", v); EXPECT_TRUE(v == make_vector("1010")); s3.get_row("r3", v); EXPECT_TRUE(v == make_vector("1100")); s3.get_row("r4", v); EXPECT_TRUE(v == bit_vector()); vector<string> ids; s3.get_all_row_ids(ids); EXPECT_EQ(3u, ids.size()); s3.remove_row("r3"); s3.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); // do MIX bit_table_t d3; s3.get_diff(d3); s3.put_diff(d3); s3.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); } } // namespace storage } // namespace core } // namespace jubatus <commit_msg>add test code for 0-bit vector issue (refs #211)<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <iostream> #include <sstream> #include <string> #include <utility> #include <vector> #include <gtest/gtest.h> #include "bit_index_storage.hpp" #include "../framework/stream_writer.hpp" using std::pair; using std::stringstream; using std::string; using std::vector; namespace jubatus { namespace core { namespace storage { bit_vector make_vector(const string& b) { bit_vector v; v.resize_and_clear(b.size()); for (size_t i = 0; i < b.size(); ++i) { if (b[i] == '1') { v.set_bit(i); } } return v; } TEST(bit_index_storage, trivial) { bit_index_storage s; EXPECT_EQ("bit_index_storage", s.name()); s.set_row("r1", make_vector("0101")); s.set_row("r2", make_vector("1010")); s.set_row("r3", make_vector("1110")); s.set_row("r4", make_vector("1100")); vector<pair<string, float> > ids; s.similar_row(make_vector("1100"), ids, 2); ASSERT_EQ(2u, ids.size()); EXPECT_EQ("r4", ids[0].first); EXPECT_FLOAT_EQ(1.0, ids[0].second); EXPECT_EQ("r3", ids[1].first); EXPECT_FLOAT_EQ(0.75, ids[1].second); msgpack::sbuffer buf; framework::stream_writer<msgpack::sbuffer> st(buf); framework::jubatus_packer jp(st); framework::packer packer(jp); s.pack(packer); bit_index_storage t; msgpack::unpacked unpacked; msgpack::unpack(&unpacked, buf.data(), buf.size()); t.unpack(unpacked.get()); ids.clear(); t.similar_row(make_vector("1100"), ids, 2); ASSERT_EQ(2u, ids.size()); EXPECT_EQ("r4", ids[0].first); s.remove_row("r4"); ids.clear(); s.similar_row(make_vector("1100"), ids, 2); EXPECT_NE("r4", ids[0].first); s.clear(); ids.clear(); s.similar_row(make_vector("1100"), ids, 2); EXPECT_TRUE(ids.empty()); } TEST(bit_index_storage, row_operations) { std::vector<std::string> ids; bit_index_storage s1; s1.set_row("r1", make_vector("0101")); s1.set_row("r2", make_vector("1010")); s1.set_row("r3", make_vector("1100")); s1.get_all_row_ids(ids); EXPECT_EQ(3u, ids.size()); s1.remove_row("r1"); s1.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); // do MIX bit_table_t d1; s1.get_diff(d1); s1.put_diff(d1); s1.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); s1.remove_row("r2"); s1.get_all_row_ids(ids); EXPECT_EQ(1u, ids.size()); std::vector<std::pair<std::string, float> > similar_result; s1.similar_row(make_vector("0101"), similar_result, 10); EXPECT_EQ(1u, similar_result.size()); // do MIX bit_table_t d2; s1.get_diff(d2); s1.put_diff(d2); s1.get_all_row_ids(ids); ASSERT_EQ(1u, ids.size()); EXPECT_EQ("r3", ids[0]); } TEST(bit_index_storage, diff) { bit_index_storage s1, s2; s1.set_row("r1", make_vector("0101")); s1.set_row("r2", make_vector("1010")); bit_table_t d1; s1.get_diff(d1); s2.put_diff(d1); bit_vector v; s2.get_row("r1", v); EXPECT_TRUE(make_vector("0101") == v); v.resize_and_clear(4); s2.get_row("r2", v); EXPECT_TRUE(make_vector("1010") == v); } TEST(bit_index_storage, mix) { bit_index_storage s1, s2, s3; s1.set_row("r1", make_vector("0101")); s1.set_row("r2", make_vector("1010")); bit_table_t d1; s1.get_diff(d1); s2.set_row("r1", make_vector("1110")); s2.set_row("r3", make_vector("1100")); bit_table_t d2; s2.get_diff(d2); s1.mix(d1, d2); // d2 is // r1: 0101 (s1) // r2: 1010 (s1) // r3: 1100 (s2) s3.set_row("r1", make_vector("1111")); s3.set_row("r2", make_vector("1111")); s3.set_row("r3", make_vector("1111")); s3.set_row("r4", make_vector("1111")); s3.put_diff(d2); // r1, r2 and r3 are overwritten by d2 // r4 is no longer retained bit_vector v; s3.get_row("r1", v); EXPECT_TRUE(v == make_vector("0101")); s3.get_row("r2", v); EXPECT_TRUE(v == make_vector("1010")); s3.get_row("r3", v); EXPECT_TRUE(v == make_vector("1100")); s3.get_row("r4", v); EXPECT_TRUE(v == bit_vector()); vector<string> ids; s3.get_all_row_ids(ids); EXPECT_EQ(3u, ids.size()); s3.remove_row("r3"); s3.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); // do MIX bit_table_t d3; s3.get_diff(d3); s3.put_diff(d3); s3.get_all_row_ids(ids); EXPECT_EQ(2u, ids.size()); } } // namespace storage } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2008 Nikolaj Hald Nielsen <[email protected]> * * Copyright (c) 2009 Roman Jarosz <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "contactlistlayoutmanager.h" #include <KMessageBox> #include <KStandardDirs> #include <KUrl> #include <KGlobal> #include <KConfig> #include <KConfigGroup> #include <KDebug> #include <KLocale> #include <KStandardDirs> #include <kio/global.h> #include <QDir> #include <QDomDocument> #include <QFile> #include <QStringList> #include "kopeteitembase.h" namespace ContactList { LayoutManager * LayoutManager::s_instance = 0; const QString DefaultStyleName = "Default"; LayoutManager * LayoutManager::instance() { if ( s_instance == 0 ) s_instance = new LayoutManager(); return s_instance; } LayoutManager::LayoutManager() : QObject() { m_tokens << ContactListTokenConfig( -1, "Placeholder", i18n("Placeholder"), "" ); m_tokens << ContactListTokenConfig( Qt::DisplayRole, "DisplayName", i18n("Display Name"), "user-identity" ); m_tokens << ContactListTokenConfig( Kopete::Items::StatusTitleRole, "StatusTitle", i18n("Status Title"), "im-status-message-edit" ); m_tokens << ContactListTokenConfig( Kopete::Items::StatusMessageRole, "StatusMessage", i18n("Status Message"), "im-status-message-edit" ); m_tokens << ContactListTokenConfig( -1, "ContactIcons", i18n("Contact Icons"), "user-online" ); loadDefaultLayouts(); loadUserLayouts(); KConfigGroup config( KGlobal::config(), "ContactList Layout" ); m_activeLayout = config.readEntry( "CurrentLayout", DefaultStyleName ); // Fallback to default if ( !m_layouts.contains( m_activeLayout ) ) setActiveLayout( DefaultStyleName ); } LayoutManager::~LayoutManager() {} QStringList LayoutManager::layouts() { return m_layouts.keys(); } void LayoutManager::setActiveLayout( const QString &layout ) { kDebug() << layout; m_activeLayout = layout; KConfigGroup config(KGlobal::config(), "ContactList Layout"); config.writeEntry( "CurrentLayout", m_activeLayout ); emit( activeLayoutChanged() ); } void LayoutManager::setPreviewLayout( const ContactListLayout &layout ) { m_activeLayout = "%%PREVIEW%%"; m_previewLayout = layout; emit( activeLayoutChanged() ); } ContactListLayout LayoutManager::activeLayout() { if ( m_activeLayout == "%%PREVIEW%%" ) return m_previewLayout; return m_layouts.value( m_activeLayout ); } void LayoutManager::loadUserLayouts() { QDir layoutsDir = QDir( KStandardDirs::locateLocal( "appdata", QString::fromUtf8("contactlistlayouts") ) ); layoutsDir.setSorting( QDir::Name ); QStringList filters; filters << "*.xml" << "*.XML"; layoutsDir.setNameFilters(filters); layoutsDir.setSorting( QDir::Name ); QFileInfoList list = layoutsDir.entryInfoList(); for ( int i = 0; i < list.size(); ++i ) { QFileInfo fileInfo = list.at(i); kDebug() << "found user file: " << fileInfo.fileName(); loadLayouts( layoutsDir.filePath( fileInfo.fileName() ), true ); } } void LayoutManager::loadDefaultLayouts() { loadLayouts( KStandardDirs::locate( "data", "kopete/DefaultContactListLayouts.xml" ), false ); loadLayouts( KStandardDirs::locate( "data", "kopete/CompactContactListLayouts.xml" ), false ); } void LayoutManager::loadLayouts( const QString &fileName, bool user ) { QDomDocument doc( "layouts" ); if ( !QFile::exists( fileName ) ) { kDebug() << "file " << fileName << "does not exist"; return; } QFile file( fileName ); if( !file.open( QIODevice::ReadOnly ) ) { kDebug() << "error reading file " << fileName; return; } if ( !doc.setContent( &file ) ) { kDebug() << "error parsing file " << fileName; return; } file.close(); QDomElement layouts_element = doc.firstChildElement( "contactlist_layouts" ); QDomNodeList layouts = layouts_element.elementsByTagName("layout"); int index = 0; while ( index < layouts.size() ) { QDomNode layout = layouts.item( index ); index++; QString layoutName = layout.toElement().attribute( "name", "" ); ContactListLayout currentLayout; currentLayout.setIsEditable( user ); currentLayout.setLayout( parseItemConfig( layout.toElement() ) ); if ( !layoutName.isEmpty() ) m_layouts.insert( layoutName, currentLayout ); } } LayoutItemConfig LayoutManager::parseItemConfig( const QDomElement &elem ) { const bool showMetaContactIcon = ( elem.attribute( "show_metacontact_icon", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); LayoutItemConfig config; config.setShowIcon( showMetaContactIcon ); QDomNodeList rows = elem.elementsByTagName("row"); int index = 0; while ( index < rows.size() ) { QDomNode rowNode = rows.item( index ); index++; LayoutItemConfigRow row; QDomNodeList elements = rowNode.toElement().elementsByTagName("element"); int index2 = 0; while ( index2 < elements.size() ) { QDomNode elementNode = elements.item( index2 ); index2++; int value = 0; // Placeholder as default QString configName = elementNode.toElement().attribute( "value" ); if ( !configName.isEmpty() ) { for ( int i = 0; i < m_tokens.size(); i++) { if ( m_tokens.at(i).mConfigName == configName ) { value = i; break; } } } QString prefix = elementNode.toElement().attribute( "prefix", QString() ); QString sufix = elementNode.toElement().attribute( "suffix", QString() ); qreal size = elementNode.toElement().attribute( "size", "0.0" ).toDouble(); bool bold = ( elementNode.toElement().attribute( "bold", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); bool italic = ( elementNode.toElement().attribute( "italic", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); bool small = ( elementNode.toElement().attribute( "small", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); bool optimalSize = ( elementNode.toElement().attribute( "optimalSize", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); QString alignmentString = elementNode.toElement().attribute( "alignment", "left" ); Qt::Alignment alignment; if ( alignmentString.compare( "left", Qt::CaseInsensitive ) == 0 ) alignment = Qt::AlignLeft | Qt::AlignVCenter; else if ( alignmentString.compare( "right", Qt::CaseInsensitive ) == 0 ) alignment = Qt::AlignRight| Qt::AlignVCenter; else alignment = Qt::AlignCenter| Qt::AlignVCenter; row.addElement( LayoutItemConfigRowElement( value, size, bold, italic, small, optimalSize, alignment, prefix, sufix ) ); } config.addRow( row ); } return config; } ContactListLayout LayoutManager::layout( const QString &layout ) { return m_layouts.value( layout ); } bool LayoutManager::addUserLayout( const QString &name, ContactListLayout layout ) { layout.setIsEditable( true ); QDomDocument doc( "layouts" ); QDomElement layouts_element = doc.createElement( "contactlist_layouts" ); QDomElement newLayout = createItemElement( doc, "layout", layout.layout() ); newLayout.setAttribute( "name", name ); doc.appendChild( layouts_element ); layouts_element.appendChild( newLayout ); QString dirName = KStandardDirs::locateLocal( "appdata", QString::fromUtf8("contactlistlayouts") ); QDir layoutsDir = QDir( dirName ); //make sure that this dir exists if ( !layoutsDir.exists() ) { if ( !layoutsDir.mkpath( dirName ) ) { KMessageBox::sorry( 0, KIO::buildErrorString( KIO::ERR_COULD_NOT_MKDIR, dirName ) ); return false; } } QFile file( layoutsDir.filePath( name + ".xml" ) ); if ( !file.open(QIODevice::WriteOnly | QIODevice::Text) ) { KMessageBox::sorry( 0, KIO::buildErrorString( KIO::ERR_CANNOT_OPEN_FOR_WRITING, file.fileName() ) ); return false; } QTextStream out( &file ); out << doc.toString(); file.close(); m_layouts.insert( name, layout ); emit( layoutListChanged() ); return true; } QDomElement LayoutManager::createItemElement( QDomDocument doc, const QString &name, const LayoutItemConfig & item ) const { QDomElement element = doc.createElement( name ); QString showIcon = item.showIcon() ? "true" : "false"; element.setAttribute ( "show_metacontact_icon", showIcon ); for( int i = 0; i < item.rows(); i++ ) { LayoutItemConfigRow row = item.row( i ); QDomElement rowElement = doc.createElement( "row" ); element.appendChild( rowElement ); for( int j = 0; j < row.count(); j++ ) { LayoutItemConfigRowElement element = row.element( j ); QDomElement elementElement = doc.createElement( "element" ); elementElement.setAttribute ( "value", m_tokens.at(element.value()).mConfigName ); elementElement.setAttribute ( "size", QString::number( element.size() ) ); elementElement.setAttribute ( "bold", element.bold() ? "true" : "false" ); elementElement.setAttribute ( "italic", element.italic() ? "true" : "false" ); elementElement.setAttribute ( "small", element.small() ? "true" : "false" ); elementElement.setAttribute ( "optimalSize", element.optimalSize() ? "true" : "false" ); QString alignmentString; if ( element.alignment() & Qt::AlignLeft ) alignmentString = "left"; else if ( element.alignment() & Qt::AlignRight ) alignmentString = "right"; else alignmentString = "center"; elementElement.setAttribute ( "alignment", alignmentString ); rowElement.appendChild( elementElement ); } } return element; } bool LayoutManager::isDefaultLayout( const QString & layout ) const { if ( m_layouts.keys().contains( layout ) ) return !m_layouts.value( layout ).isEditable(); return false; } QString LayoutManager::activeLayoutName() { return m_activeLayout; } bool LayoutManager::deleteLayout( const QString & layout ) { //check if layout is editable if ( m_layouts.value( layout ).isEditable() ) { QDir layoutsDir = QDir( KStandardDirs::locateLocal( "appdata", QString::fromUtf8("contactlistlayouts") ) ); QString xmlFile = layoutsDir.path() + '/' + layout + ".xml"; kDebug() << "deleting file: " << xmlFile; if ( !QFile::remove( xmlFile ) ) { KMessageBox::sorry( 0, KIO::buildErrorString( KIO::ERR_CANNOT_DELETE, xmlFile ) ); return false; } m_layouts.remove( layout ); emit( layoutListChanged() ); if ( layout == m_activeLayout ) setActiveLayout( DefaultStyleName ); return true; } KMessageBox::sorry( 0, i18n( "The layout '%1' is one of the default layouts and cannot be deleted.", layout ), i18n( "Cannot Delete Default Layouts" ) ); return false; } } //namespace ContactList #include "contactlistlayoutmanager.moc" <commit_msg>Fix a missing icon<commit_after>/*************************************************************************** * Copyright (c) 2008 Nikolaj Hald Nielsen <[email protected]> * * Copyright (c) 2009 Roman Jarosz <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "contactlistlayoutmanager.h" #include <KMessageBox> #include <KStandardDirs> #include <KUrl> #include <KGlobal> #include <KConfig> #include <KConfigGroup> #include <KDebug> #include <KLocale> #include <KStandardDirs> #include <kio/global.h> #include <QDir> #include <QDomDocument> #include <QFile> #include <QStringList> #include "kopeteitembase.h" namespace ContactList { LayoutManager * LayoutManager::s_instance = 0; const QString DefaultStyleName = "Default"; LayoutManager * LayoutManager::instance() { if ( s_instance == 0 ) s_instance = new LayoutManager(); return s_instance; } LayoutManager::LayoutManager() : QObject() { m_tokens << ContactListTokenConfig( -1, "Placeholder", i18n("Placeholder"), "transform-move" ); m_tokens << ContactListTokenConfig( Qt::DisplayRole, "DisplayName", i18n("Display Name"), "user-identity" ); m_tokens << ContactListTokenConfig( Kopete::Items::StatusTitleRole, "StatusTitle", i18n("Status Title"), "im-status-message-edit" ); m_tokens << ContactListTokenConfig( Kopete::Items::StatusMessageRole, "StatusMessage", i18n("Status Message"), "im-status-message-edit" ); m_tokens << ContactListTokenConfig( -1, "ContactIcons", i18n("Contact Icons"), "user-online" ); loadDefaultLayouts(); loadUserLayouts(); KConfigGroup config( KGlobal::config(), "ContactList Layout" ); m_activeLayout = config.readEntry( "CurrentLayout", DefaultStyleName ); // Fallback to default if ( !m_layouts.contains( m_activeLayout ) ) setActiveLayout( DefaultStyleName ); } LayoutManager::~LayoutManager() {} QStringList LayoutManager::layouts() { return m_layouts.keys(); } void LayoutManager::setActiveLayout( const QString &layout ) { kDebug() << layout; m_activeLayout = layout; KConfigGroup config(KGlobal::config(), "ContactList Layout"); config.writeEntry( "CurrentLayout", m_activeLayout ); emit( activeLayoutChanged() ); } void LayoutManager::setPreviewLayout( const ContactListLayout &layout ) { m_activeLayout = "%%PREVIEW%%"; m_previewLayout = layout; emit( activeLayoutChanged() ); } ContactListLayout LayoutManager::activeLayout() { if ( m_activeLayout == "%%PREVIEW%%" ) return m_previewLayout; return m_layouts.value( m_activeLayout ); } void LayoutManager::loadUserLayouts() { QDir layoutsDir = QDir( KStandardDirs::locateLocal( "appdata", QString::fromUtf8("contactlistlayouts") ) ); layoutsDir.setSorting( QDir::Name ); QStringList filters; filters << "*.xml" << "*.XML"; layoutsDir.setNameFilters(filters); layoutsDir.setSorting( QDir::Name ); QFileInfoList list = layoutsDir.entryInfoList(); for ( int i = 0; i < list.size(); ++i ) { QFileInfo fileInfo = list.at(i); kDebug() << "found user file: " << fileInfo.fileName(); loadLayouts( layoutsDir.filePath( fileInfo.fileName() ), true ); } } void LayoutManager::loadDefaultLayouts() { loadLayouts( KStandardDirs::locate( "data", "kopete/DefaultContactListLayouts.xml" ), false ); loadLayouts( KStandardDirs::locate( "data", "kopete/CompactContactListLayouts.xml" ), false ); } void LayoutManager::loadLayouts( const QString &fileName, bool user ) { QDomDocument doc( "layouts" ); if ( !QFile::exists( fileName ) ) { kDebug() << "file " << fileName << "does not exist"; return; } QFile file( fileName ); if( !file.open( QIODevice::ReadOnly ) ) { kDebug() << "error reading file " << fileName; return; } if ( !doc.setContent( &file ) ) { kDebug() << "error parsing file " << fileName; return; } file.close(); QDomElement layouts_element = doc.firstChildElement( "contactlist_layouts" ); QDomNodeList layouts = layouts_element.elementsByTagName("layout"); int index = 0; while ( index < layouts.size() ) { QDomNode layout = layouts.item( index ); index++; QString layoutName = layout.toElement().attribute( "name", "" ); ContactListLayout currentLayout; currentLayout.setIsEditable( user ); currentLayout.setLayout( parseItemConfig( layout.toElement() ) ); if ( !layoutName.isEmpty() ) m_layouts.insert( layoutName, currentLayout ); } } LayoutItemConfig LayoutManager::parseItemConfig( const QDomElement &elem ) { const bool showMetaContactIcon = ( elem.attribute( "show_metacontact_icon", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); LayoutItemConfig config; config.setShowIcon( showMetaContactIcon ); QDomNodeList rows = elem.elementsByTagName("row"); int index = 0; while ( index < rows.size() ) { QDomNode rowNode = rows.item( index ); index++; LayoutItemConfigRow row; QDomNodeList elements = rowNode.toElement().elementsByTagName("element"); int index2 = 0; while ( index2 < elements.size() ) { QDomNode elementNode = elements.item( index2 ); index2++; int value = 0; // Placeholder as default QString configName = elementNode.toElement().attribute( "value" ); if ( !configName.isEmpty() ) { for ( int i = 0; i < m_tokens.size(); i++) { if ( m_tokens.at(i).mConfigName == configName ) { value = i; break; } } } QString prefix = elementNode.toElement().attribute( "prefix", QString() ); QString sufix = elementNode.toElement().attribute( "suffix", QString() ); qreal size = elementNode.toElement().attribute( "size", "0.0" ).toDouble(); bool bold = ( elementNode.toElement().attribute( "bold", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); bool italic = ( elementNode.toElement().attribute( "italic", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); bool small = ( elementNode.toElement().attribute( "small", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); bool optimalSize = ( elementNode.toElement().attribute( "optimalSize", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 ); QString alignmentString = elementNode.toElement().attribute( "alignment", "left" ); Qt::Alignment alignment; if ( alignmentString.compare( "left", Qt::CaseInsensitive ) == 0 ) alignment = Qt::AlignLeft | Qt::AlignVCenter; else if ( alignmentString.compare( "right", Qt::CaseInsensitive ) == 0 ) alignment = Qt::AlignRight| Qt::AlignVCenter; else alignment = Qt::AlignCenter| Qt::AlignVCenter; row.addElement( LayoutItemConfigRowElement( value, size, bold, italic, small, optimalSize, alignment, prefix, sufix ) ); } config.addRow( row ); } return config; } ContactListLayout LayoutManager::layout( const QString &layout ) { return m_layouts.value( layout ); } bool LayoutManager::addUserLayout( const QString &name, ContactListLayout layout ) { layout.setIsEditable( true ); QDomDocument doc( "layouts" ); QDomElement layouts_element = doc.createElement( "contactlist_layouts" ); QDomElement newLayout = createItemElement( doc, "layout", layout.layout() ); newLayout.setAttribute( "name", name ); doc.appendChild( layouts_element ); layouts_element.appendChild( newLayout ); QString dirName = KStandardDirs::locateLocal( "appdata", QString::fromUtf8("contactlistlayouts") ); QDir layoutsDir = QDir( dirName ); //make sure that this dir exists if ( !layoutsDir.exists() ) { if ( !layoutsDir.mkpath( dirName ) ) { KMessageBox::sorry( 0, KIO::buildErrorString( KIO::ERR_COULD_NOT_MKDIR, dirName ) ); return false; } } QFile file( layoutsDir.filePath( name + ".xml" ) ); if ( !file.open(QIODevice::WriteOnly | QIODevice::Text) ) { KMessageBox::sorry( 0, KIO::buildErrorString( KIO::ERR_CANNOT_OPEN_FOR_WRITING, file.fileName() ) ); return false; } QTextStream out( &file ); out << doc.toString(); file.close(); m_layouts.insert( name, layout ); emit( layoutListChanged() ); return true; } QDomElement LayoutManager::createItemElement( QDomDocument doc, const QString &name, const LayoutItemConfig & item ) const { QDomElement element = doc.createElement( name ); QString showIcon = item.showIcon() ? "true" : "false"; element.setAttribute ( "show_metacontact_icon", showIcon ); for( int i = 0; i < item.rows(); i++ ) { LayoutItemConfigRow row = item.row( i ); QDomElement rowElement = doc.createElement( "row" ); element.appendChild( rowElement ); for( int j = 0; j < row.count(); j++ ) { LayoutItemConfigRowElement element = row.element( j ); QDomElement elementElement = doc.createElement( "element" ); elementElement.setAttribute ( "value", m_tokens.at(element.value()).mConfigName ); elementElement.setAttribute ( "size", QString::number( element.size() ) ); elementElement.setAttribute ( "bold", element.bold() ? "true" : "false" ); elementElement.setAttribute ( "italic", element.italic() ? "true" : "false" ); elementElement.setAttribute ( "small", element.small() ? "true" : "false" ); elementElement.setAttribute ( "optimalSize", element.optimalSize() ? "true" : "false" ); QString alignmentString; if ( element.alignment() & Qt::AlignLeft ) alignmentString = "left"; else if ( element.alignment() & Qt::AlignRight ) alignmentString = "right"; else alignmentString = "center"; elementElement.setAttribute ( "alignment", alignmentString ); rowElement.appendChild( elementElement ); } } return element; } bool LayoutManager::isDefaultLayout( const QString & layout ) const { if ( m_layouts.keys().contains( layout ) ) return !m_layouts.value( layout ).isEditable(); return false; } QString LayoutManager::activeLayoutName() { return m_activeLayout; } bool LayoutManager::deleteLayout( const QString & layout ) { //check if layout is editable if ( m_layouts.value( layout ).isEditable() ) { QDir layoutsDir = QDir( KStandardDirs::locateLocal( "appdata", QString::fromUtf8("contactlistlayouts") ) ); QString xmlFile = layoutsDir.path() + '/' + layout + ".xml"; kDebug() << "deleting file: " << xmlFile; if ( !QFile::remove( xmlFile ) ) { KMessageBox::sorry( 0, KIO::buildErrorString( KIO::ERR_CANNOT_DELETE, xmlFile ) ); return false; } m_layouts.remove( layout ); emit( layoutListChanged() ); if ( layout == m_activeLayout ) setActiveLayout( DefaultStyleName ); return true; } KMessageBox::sorry( 0, i18n( "The layout '%1' is one of the default layouts and cannot be deleted.", layout ), i18n( "Cannot Delete Default Layouts" ) ); return false; } } //namespace ContactList #include "contactlistlayoutmanager.moc" <|endoftext|>
<commit_before><commit_msg>lightfields::MRF - commented out an unused variable to fix build errors on Travis<commit_after><|endoftext|>
<commit_before>#pragma once #include <cmath> #include <string> #include "base/macros.hpp" namespace principia { namespace quantities { template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent, int64_t CurrentExponent, int64_t TemperatureExponent, int64_t AmountExponent, int64_t LuminousIntensityExponent, int64_t WindingExponent, int64_t AngleExponent, int64_t SolidAngleExponent> struct Dimensions { enum { Length = LengthExponent, Mass = MassExponent, Time = TimeExponent, Current = CurrentExponent, Temperature = TemperatureExponent, Amount = AmountExponent, LuminousIntensity = LuminousIntensityExponent, Winding = WindingExponent, Angle = AngleExponent, SolidAngle = SolidAngleExponent }; static int const kMinExponent = -16; static int const kMaxExponent = 15; static int const kExponentBits = 5; static int const kExponentMask = 0x1F; static_assert(LengthExponent >= kMinExponent && LengthExponent <= kMaxExponent, "Invalid length exponent"); static_assert(MassExponent >= kMinExponent && MassExponent <= kMaxExponent, "Invalid mass exponent"); static_assert(TimeExponent >= kMinExponent && TimeExponent <= kMaxExponent, "Invalid time exponent"); static_assert(CurrentExponent >= kMinExponent && CurrentExponent <= kMaxExponent, "Invalid current exponent"); static_assert(TemperatureExponent >= kMinExponent && TemperatureExponent <= kMaxExponent, "Invalid temperature exponent"); static_assert(AmountExponent >= kMinExponent && AmountExponent <= kMaxExponent, "Invalid amount exponent"); static_assert(LuminousIntensityExponent >= kMinExponent && LuminousIntensityExponent <= kMaxExponent, "Invalid luminous intensity exponent"); static_assert(AngleExponent >= kMinExponent && AngleExponent <= kMaxExponent, "Invalid angle exponent"); static_assert(SolidAngleExponent >= kMinExponent && SolidAngleExponent <= kMaxExponent, "Invalid solid angle exponent"); static_assert(WindingExponent >= kMinExponent && WindingExponent <= kMaxExponent, "Invalid winding exponent"); // The NOLINT are because glint is confused by the binary and. I kid you not. static int64_t const representation = (LengthExponent & kExponentMask) | // NOLINT (MassExponent & kExponentMask) << 1 * kExponentBits | // NOLINT (TimeExponent & kExponentMask) << 2 * kExponentBits | // NOLINT (CurrentExponent & kExponentMask) << 3 * kExponentBits | // NOLINT (TemperatureExponent & kExponentMask) << 4 * kExponentBits | // NOLINT (AmountExponent & kExponentMask) << 5 * kExponentBits | // NOLINT (LuminousIntensityExponent & kExponentMask) << 6 * kExponentBits | // NOLINT (AngleExponent & kExponentMask) << 7 * kExponentBits | // NOLINT (SolidAngleExponent & kExponentMask) << 8 * kExponentBits | // NOLINT (WindingExponent & kExponentMask) << 9 * kExponentBits; // NOLINT }; namespace type_generators { template<typename Q> struct Collapse { using ResultType = Q; }; template<> struct Collapse<Quantity<NoDimensions>> { using ResultType = double; }; template<typename Left, typename Right> struct ProductGenerator { enum { Length = Left::Dimensions::Length + Right::Dimensions::Length, Mass = Left::Dimensions::Mass + Right::Dimensions::Mass, Time = Left::Dimensions::Time + Right::Dimensions::Time, Current = Left::Dimensions::Current + Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature + Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount + Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity + Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding + Right::Dimensions::Winding, Angle = Left::Dimensions::Angle + Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle + Right::Dimensions::SolidAngle }; using ResultType = typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType; }; template<typename Left> struct ProductGenerator<Left, double> { using ResultType = Left; }; template<typename Right> struct ProductGenerator<double, Right> { using ResultType = Right; }; template<> struct ProductGenerator<double, double> { using ResultType = double; }; template<typename Left, typename Right> struct QuotientGenerator { enum { Length = Left::Dimensions::Length - Right::Dimensions::Length, Mass = Left::Dimensions::Mass - Right::Dimensions::Mass, Time = Left::Dimensions::Time - Right::Dimensions::Time, Current = Left::Dimensions::Current - Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature - Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount - Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity - Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding - Right::Dimensions::Winding, Angle = Left::Dimensions::Angle - Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle - Right::Dimensions::SolidAngle }; using ResultType = typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType; }; template<typename Left> struct QuotientGenerator<Left, double> { using ResultType = Left; }; template<> struct QuotientGenerator<double, double> { using ResultType = double; }; template<typename Right> struct QuotientGenerator<double, Right> { enum { Length = -Right::Dimensions::Length, Mass = -Right::Dimensions::Mass, Time = -Right::Dimensions::Time, Current = -Right::Dimensions::Current, Temperature = -Right::Dimensions::Temperature, Amount = -Right::Dimensions::Amount, LuminousIntensity = -Right::Dimensions::LuminousIntensity, Winding = -Right::Dimensions::Winding, Angle = -Right::Dimensions::Angle, SolidAngle = -Right::Dimensions::SolidAngle }; using ResultType = Quantity< Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>; }; template<typename Q, int Exponent, typename> struct PowerGenerator {}; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent > 1)>> { using ResultType = Product<typename PowerGenerator<Q, Exponent - 1>::ResultType, Q>; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent < 1)>>{ using ResultType = Quotient<typename PowerGenerator<Q, Exponent + 1>::ResultType, Q>; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent == 1)>>{ using ResultType = Q; }; } // namespace type_generators template<typename D> inline Quantity<D>::Quantity() : magnitude_(0) {} template<typename D> inline Quantity<D>::Quantity(double const magnitude) : magnitude_(magnitude) {} template<typename D> inline Quantity<D>& Quantity<D>::operator+=(Quantity const& right) { magnitude_ += right.magnitude_; return *this; } template<typename D> inline Quantity<D>& Quantity<D>::operator-=(Quantity const& right) { magnitude_ -= right.magnitude_; return *this; } template<typename D> inline Quantity<D>& Quantity<D>::operator*=(double const right) { magnitude_ *= right; return *this; } template<typename D> inline Quantity<D>& Quantity<D>::operator/=(double const right) { magnitude_ /= right; return *this; } // Additive group template<typename D> inline Quantity<D> Quantity<D>::operator+() const { return *this; } template<typename D> inline Quantity<D> Quantity<D>::operator-() const { return Quantity(-magnitude_); } template<typename D> inline Quantity<D> Quantity<D>::operator+(Quantity const& right) const { return Quantity(magnitude_ + right.magnitude_); } template<typename D> inline Quantity<D> Quantity<D>::operator-(Quantity const& right) const { return Quantity(magnitude_ - right.magnitude_); } // Comparison operators template<typename D> inline bool Quantity<D>::operator>(Quantity const& right) const { return magnitude_ > right.magnitude_; } template<typename D> inline bool Quantity<D>::operator<(Quantity const& right) const { return magnitude_ < right.magnitude_; } template<typename D> inline bool Quantity<D>::operator>=(Quantity const& right) const { return magnitude_ >= right.magnitude_; } template<typename D> inline bool Quantity<D>::operator<=(Quantity const& right) const { return magnitude_ <= right.magnitude_; } template<typename D> inline bool Quantity<D>::operator==(Quantity const& right) const { return magnitude_ == right.magnitude_; } template<typename D> inline bool Quantity<D>::operator!=(Quantity const& right) const { return magnitude_ != right.magnitude_; } template<typename D> void Quantity<D>::WriteToMessage( not_null<serialization::Quantity*> const message) const { message->set_dimensions(D::representation); message->set_magnitude(magnitude_); } template<typename D> Quantity<D> Quantity<D>::ReadFromMessage( serialization::Quantity const& message) { CHECK_EQ(D::representation, message.dimensions()); return Quantity(message.magnitude()); } // Multiplicative group template<typename D> inline Quantity<D> Quantity<D>::operator/(double const right) const { return Quantity(magnitude_ / right); } template<typename D> inline Quantity<D> Quantity<D>::operator*(double const right) const { return Quantity(magnitude_ * right); } template<typename LDimensions, typename RDimensions> inline Product<Quantity<LDimensions>, Quantity<RDimensions>> operator*( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right) { return Product<Quantity<LDimensions>, Quantity<RDimensions>>(left.magnitude_ * right.magnitude_); } template<typename LDimensions, typename RDimensions> inline Quotient<Quantity<LDimensions>, Quantity<RDimensions>> operator/( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right) { return Quotient<Quantity<LDimensions>, Quantity<RDimensions>>(left.magnitude_ / right.magnitude_); } template<typename RDimensions> FORCE_INLINE Quantity<RDimensions> operator*( double const left, Quantity<RDimensions> const& right) { return Quantity<RDimensions>(left * right.magnitude_); } template<typename RDimensions> inline typename Quantity<RDimensions>::Inverse operator/( double const left, Quantity<RDimensions> const& right) { return typename Quantity<RDimensions>::Inverse(left / right.magnitude_); } template<int exponent> inline double Pow(double x) { return std::pow(x, exponent); } // Static specializations for frequently-used exponents, so that this gets // turned into multiplications at compile time. template<> inline double Pow<-3>(double x) { return 1 / (x * x * x); } template<> inline double Pow<-2>(double x) { return 1 / (x * x); } template<> inline double Pow<-1>(double x) { return 1 / x; } template<> inline double Pow<0>(double x) { return 1; } template<> inline double Pow<1>(double x) { return x; } template<> inline double Pow<2>(double x) { return x * x; } template<> inline double Pow<3>(double x) { return x * x * x; } template<int exponent, typename D> Exponentiation<Quantity<D>, exponent> Pow( Quantity<D> const& x) { return Exponentiation<Quantity<D>, exponent>( Pow<exponent>(x.magnitude_)); } inline double Abs(double const x) { return std::abs(x); } template<typename D> Quantity<D> Abs(Quantity<D> const& quantity) { return Quantity<D>(std::abs(quantity.magnitude_)); } template<typename Q> inline Q SIUnit() { return Q(1); } template<> inline double SIUnit<double>() { return 1; } inline std::string FormatUnit(std::string const& name, int const exponent) { switch (exponent) { case 0: return ""; break; case 1: return " " + name; default: return " " + name + "^" + std::to_string(exponent); } } inline std::string DebugString(double const number, int const precision) { char result[50]; #ifdef _MSC_VER unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT); sprintf_s(result, ("%+."+ std::to_string(precision) + "e").c_str(), number); _set_output_format(old_exponent_format); #else snprintf(result, sizeof(result), ("%."+ std::to_string(precision) + "e").c_str(), number); #endif return result; } template<typename D> std::string DebugString(Quantity<D> const& quantity, int const precision) { return DebugString(quantity.magnitude_, precision) + FormatUnit("m", D::Length) + FormatUnit("kg", D::Mass) + FormatUnit("s", D::Time) + FormatUnit("A", D::Current) + FormatUnit("K", D::Temperature) + FormatUnit("mol", D::Amount) + FormatUnit("cd", D::LuminousIntensity) + FormatUnit("cycle", D::Winding) + FormatUnit("rad", D::Angle) + FormatUnit("sr", D::SolidAngle); } template<typename D> std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity) { return out << DebugString(quantity); } } // namespace quantities } // namespace principia <commit_msg>Unforce.<commit_after>#pragma once #include <cmath> #include <string> #include "base/macros.hpp" namespace principia { namespace quantities { template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent, int64_t CurrentExponent, int64_t TemperatureExponent, int64_t AmountExponent, int64_t LuminousIntensityExponent, int64_t WindingExponent, int64_t AngleExponent, int64_t SolidAngleExponent> struct Dimensions { enum { Length = LengthExponent, Mass = MassExponent, Time = TimeExponent, Current = CurrentExponent, Temperature = TemperatureExponent, Amount = AmountExponent, LuminousIntensity = LuminousIntensityExponent, Winding = WindingExponent, Angle = AngleExponent, SolidAngle = SolidAngleExponent }; static int const kMinExponent = -16; static int const kMaxExponent = 15; static int const kExponentBits = 5; static int const kExponentMask = 0x1F; static_assert(LengthExponent >= kMinExponent && LengthExponent <= kMaxExponent, "Invalid length exponent"); static_assert(MassExponent >= kMinExponent && MassExponent <= kMaxExponent, "Invalid mass exponent"); static_assert(TimeExponent >= kMinExponent && TimeExponent <= kMaxExponent, "Invalid time exponent"); static_assert(CurrentExponent >= kMinExponent && CurrentExponent <= kMaxExponent, "Invalid current exponent"); static_assert(TemperatureExponent >= kMinExponent && TemperatureExponent <= kMaxExponent, "Invalid temperature exponent"); static_assert(AmountExponent >= kMinExponent && AmountExponent <= kMaxExponent, "Invalid amount exponent"); static_assert(LuminousIntensityExponent >= kMinExponent && LuminousIntensityExponent <= kMaxExponent, "Invalid luminous intensity exponent"); static_assert(AngleExponent >= kMinExponent && AngleExponent <= kMaxExponent, "Invalid angle exponent"); static_assert(SolidAngleExponent >= kMinExponent && SolidAngleExponent <= kMaxExponent, "Invalid solid angle exponent"); static_assert(WindingExponent >= kMinExponent && WindingExponent <= kMaxExponent, "Invalid winding exponent"); // The NOLINT are because glint is confused by the binary and. I kid you not. static int64_t const representation = (LengthExponent & kExponentMask) | // NOLINT (MassExponent & kExponentMask) << 1 * kExponentBits | // NOLINT (TimeExponent & kExponentMask) << 2 * kExponentBits | // NOLINT (CurrentExponent & kExponentMask) << 3 * kExponentBits | // NOLINT (TemperatureExponent & kExponentMask) << 4 * kExponentBits | // NOLINT (AmountExponent & kExponentMask) << 5 * kExponentBits | // NOLINT (LuminousIntensityExponent & kExponentMask) << 6 * kExponentBits | // NOLINT (AngleExponent & kExponentMask) << 7 * kExponentBits | // NOLINT (SolidAngleExponent & kExponentMask) << 8 * kExponentBits | // NOLINT (WindingExponent & kExponentMask) << 9 * kExponentBits; // NOLINT }; namespace type_generators { template<typename Q> struct Collapse { using ResultType = Q; }; template<> struct Collapse<Quantity<NoDimensions>> { using ResultType = double; }; template<typename Left, typename Right> struct ProductGenerator { enum { Length = Left::Dimensions::Length + Right::Dimensions::Length, Mass = Left::Dimensions::Mass + Right::Dimensions::Mass, Time = Left::Dimensions::Time + Right::Dimensions::Time, Current = Left::Dimensions::Current + Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature + Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount + Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity + Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding + Right::Dimensions::Winding, Angle = Left::Dimensions::Angle + Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle + Right::Dimensions::SolidAngle }; using ResultType = typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType; }; template<typename Left> struct ProductGenerator<Left, double> { using ResultType = Left; }; template<typename Right> struct ProductGenerator<double, Right> { using ResultType = Right; }; template<> struct ProductGenerator<double, double> { using ResultType = double; }; template<typename Left, typename Right> struct QuotientGenerator { enum { Length = Left::Dimensions::Length - Right::Dimensions::Length, Mass = Left::Dimensions::Mass - Right::Dimensions::Mass, Time = Left::Dimensions::Time - Right::Dimensions::Time, Current = Left::Dimensions::Current - Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature - Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount - Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity - Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding - Right::Dimensions::Winding, Angle = Left::Dimensions::Angle - Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle - Right::Dimensions::SolidAngle }; using ResultType = typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType; }; template<typename Left> struct QuotientGenerator<Left, double> { using ResultType = Left; }; template<> struct QuotientGenerator<double, double> { using ResultType = double; }; template<typename Right> struct QuotientGenerator<double, Right> { enum { Length = -Right::Dimensions::Length, Mass = -Right::Dimensions::Mass, Time = -Right::Dimensions::Time, Current = -Right::Dimensions::Current, Temperature = -Right::Dimensions::Temperature, Amount = -Right::Dimensions::Amount, LuminousIntensity = -Right::Dimensions::LuminousIntensity, Winding = -Right::Dimensions::Winding, Angle = -Right::Dimensions::Angle, SolidAngle = -Right::Dimensions::SolidAngle }; using ResultType = Quantity< Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>; }; template<typename Q, int Exponent, typename> struct PowerGenerator {}; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent > 1)>> { using ResultType = Product<typename PowerGenerator<Q, Exponent - 1>::ResultType, Q>; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent < 1)>>{ using ResultType = Quotient<typename PowerGenerator<Q, Exponent + 1>::ResultType, Q>; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent == 1)>>{ using ResultType = Q; }; } // namespace type_generators template<typename D> inline Quantity<D>::Quantity() : magnitude_(0) {} template<typename D> inline Quantity<D>::Quantity(double const magnitude) : magnitude_(magnitude) {} template<typename D> inline Quantity<D>& Quantity<D>::operator+=(Quantity const& right) { magnitude_ += right.magnitude_; return *this; } template<typename D> inline Quantity<D>& Quantity<D>::operator-=(Quantity const& right) { magnitude_ -= right.magnitude_; return *this; } template<typename D> inline Quantity<D>& Quantity<D>::operator*=(double const right) { magnitude_ *= right; return *this; } template<typename D> inline Quantity<D>& Quantity<D>::operator/=(double const right) { magnitude_ /= right; return *this; } // Additive group template<typename D> inline Quantity<D> Quantity<D>::operator+() const { return *this; } template<typename D> inline Quantity<D> Quantity<D>::operator-() const { return Quantity(-magnitude_); } template<typename D> inline Quantity<D> Quantity<D>::operator+(Quantity const& right) const { return Quantity(magnitude_ + right.magnitude_); } template<typename D> inline Quantity<D> Quantity<D>::operator-(Quantity const& right) const { return Quantity(magnitude_ - right.magnitude_); } // Comparison operators template<typename D> inline bool Quantity<D>::operator>(Quantity const& right) const { return magnitude_ > right.magnitude_; } template<typename D> inline bool Quantity<D>::operator<(Quantity const& right) const { return magnitude_ < right.magnitude_; } template<typename D> inline bool Quantity<D>::operator>=(Quantity const& right) const { return magnitude_ >= right.magnitude_; } template<typename D> inline bool Quantity<D>::operator<=(Quantity const& right) const { return magnitude_ <= right.magnitude_; } template<typename D> inline bool Quantity<D>::operator==(Quantity const& right) const { return magnitude_ == right.magnitude_; } template<typename D> inline bool Quantity<D>::operator!=(Quantity const& right) const { return magnitude_ != right.magnitude_; } template<typename D> void Quantity<D>::WriteToMessage( not_null<serialization::Quantity*> const message) const { message->set_dimensions(D::representation); message->set_magnitude(magnitude_); } template<typename D> Quantity<D> Quantity<D>::ReadFromMessage( serialization::Quantity const& message) { CHECK_EQ(D::representation, message.dimensions()); return Quantity(message.magnitude()); } // Multiplicative group template<typename D> inline Quantity<D> Quantity<D>::operator/(double const right) const { return Quantity(magnitude_ / right); } template<typename D> inline Quantity<D> Quantity<D>::operator*(double const right) const { return Quantity(magnitude_ * right); } template<typename LDimensions, typename RDimensions> inline Product<Quantity<LDimensions>, Quantity<RDimensions>> operator*( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right) { return Product<Quantity<LDimensions>, Quantity<RDimensions>>(left.magnitude_ * right.magnitude_); } template<typename LDimensions, typename RDimensions> inline Quotient<Quantity<LDimensions>, Quantity<RDimensions>> operator/( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right) { return Quotient<Quantity<LDimensions>, Quantity<RDimensions>>(left.magnitude_ / right.magnitude_); } template<typename RDimensions> inline Quantity<RDimensions> operator*( double const left, Quantity<RDimensions> const& right) { return Quantity<RDimensions>(left * right.magnitude_); } template<typename RDimensions> inline typename Quantity<RDimensions>::Inverse operator/( double const left, Quantity<RDimensions> const& right) { return typename Quantity<RDimensions>::Inverse(left / right.magnitude_); } template<int exponent> inline double Pow(double x) { return std::pow(x, exponent); } // Static specializations for frequently-used exponents, so that this gets // turned into multiplications at compile time. template<> inline double Pow<-3>(double x) { return 1 / (x * x * x); } template<> inline double Pow<-2>(double x) { return 1 / (x * x); } template<> inline double Pow<-1>(double x) { return 1 / x; } template<> inline double Pow<0>(double x) { return 1; } template<> inline double Pow<1>(double x) { return x; } template<> inline double Pow<2>(double x) { return x * x; } template<> inline double Pow<3>(double x) { return x * x * x; } template<int exponent, typename D> Exponentiation<Quantity<D>, exponent> Pow( Quantity<D> const& x) { return Exponentiation<Quantity<D>, exponent>( Pow<exponent>(x.magnitude_)); } inline double Abs(double const x) { return std::abs(x); } template<typename D> Quantity<D> Abs(Quantity<D> const& quantity) { return Quantity<D>(std::abs(quantity.magnitude_)); } template<typename Q> inline Q SIUnit() { return Q(1); } template<> inline double SIUnit<double>() { return 1; } inline std::string FormatUnit(std::string const& name, int const exponent) { switch (exponent) { case 0: return ""; break; case 1: return " " + name; default: return " " + name + "^" + std::to_string(exponent); } } inline std::string DebugString(double const number, int const precision) { char result[50]; #ifdef _MSC_VER unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT); sprintf_s(result, ("%+."+ std::to_string(precision) + "e").c_str(), number); _set_output_format(old_exponent_format); #else snprintf(result, sizeof(result), ("%."+ std::to_string(precision) + "e").c_str(), number); #endif return result; } template<typename D> std::string DebugString(Quantity<D> const& quantity, int const precision) { return DebugString(quantity.magnitude_, precision) + FormatUnit("m", D::Length) + FormatUnit("kg", D::Mass) + FormatUnit("s", D::Time) + FormatUnit("A", D::Current) + FormatUnit("K", D::Temperature) + FormatUnit("mol", D::Amount) + FormatUnit("cd", D::LuminousIntensity) + FormatUnit("cycle", D::Winding) + FormatUnit("rad", D::Angle) + FormatUnit("sr", D::SolidAngle); } template<typename D> std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity) { return out << DebugString(quantity); } } // namespace quantities } // namespace principia <|endoftext|>
<commit_before>/* Copyright (c) 2012 Marcello Maggioni 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, RISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <BitralContext.h> #include <iostream> #include <RegisterMemoryAddress.h> #include <CodeRegion.h> #include <cassert> #include <cstring> #undef NDEBUG //#define DEBUG using namespace Bitral; boost::uint32_t reg_var = 100; boost::uint8_t mem[100]; int main() { BitralContext b; memset(mem, 0, sizeof(mem)); assert(mem[50] == 0); Register* reg = b.addRegister(32, "A", &reg_var); //Register* reg = b.addRegister(32, "B", &reg_var2); b.setMemorySpace(mem, sizeof(mem)); CodeRegion* Region = b.createNewCodeRegion(ConstantMemoryAddress(Immediate(b, 32, 0))); Region->createMove(Immediate(b, 32, 10), reg); Region->increaseMemoryPosition(4); Region->createStore(*reg, ConstantMemoryAddress(Immediate(b,8,50))); Region->closeRegion(); CodeRegion::CodePointer Code = Region->compile(); Code(); assert(reg_var == 10); assert(mem[50] == 10); return 0; } <commit_msg>Removed stray file<commit_after><|endoftext|>
<commit_before>/* * (C) 2015-2016 Augustin Cavalier * All rights reserved. Distributed under the terms of the MIT license. */ #include "Tester.h" #include <iostream> #ifdef _WIN32 # define COLOR_RED "" # define COLOR_GREEN "" # define COLOR_RESET "" #else # define COLOR_RED "\e[97m\e[101m" # define COLOR_GREEN "\e[97m\e[42m" # define COLOR_RESET "\e[0m" #endif Tester::Tester(bool hidePassed) : fTestsPassed(0), fTestsFailed(0), fHidePassed(hidePassed) { } void Tester::beginGroup(const std::string& groupName) { if (!fHidePassed) std::cout << groupName << std::endl; fCurGroup = groupName; fGroupPrinted = false; } void Tester::endGroup() { if (!fHidePassed || fGroupPrinted) std::cout << std::endl; fCurGroup = ""; fGroupPrinted = false; } void Tester::result(bool pass, const std::string& testName) { if (pass && fHidePassed) { fTestsPassed++; return; } if (fHidePassed && !fGroupPrinted) { std::cout << fCurGroup << std::endl; fGroupPrinted = true; } if (pass) { puts(COLOR_GREEN "PASS" COLOR_RESET); fTestsPassed++; } else { puts(COLOR_RED "FAIL" COLOR_RESET); fTestsFailed++; } std::cout << ": " << testName << std::endl; } int Tester::done() { std::cout << "Finished: " << std::to_string(fTestsPassed) << " passed, " << std::to_string(fTestsFailed) << " failed." << std::endl << std::endl; return fTestsFailed; } <commit_msg>Tester: Tweak output.<commit_after>/* * (C) 2015-2016 Augustin Cavalier * All rights reserved. Distributed under the terms of the MIT license. */ #include "Tester.h" #include <iostream> #ifdef _WIN32 # define COLOR_RED "" # define COLOR_GREEN "" # define COLOR_RESET "" #else # define COLOR_RED "\e[97m\e[101m" # define COLOR_GREEN "\e[97m\e[42m" # define COLOR_RESET "\e[0m" #endif Tester::Tester(bool hidePassed) : fTestsPassed(0), fTestsFailed(0), fHidePassed(hidePassed) { } void Tester::beginGroup(const std::string& groupName) { if (!fHidePassed) std::cout << groupName << std::endl; fCurGroup = groupName; fGroupPrinted = false; } void Tester::endGroup() { if (!fHidePassed || fGroupPrinted) std::cout << std::endl; fCurGroup = ""; fGroupPrinted = false; } void Tester::result(bool pass, const std::string& testName) { if (pass && fHidePassed) { fTestsPassed++; return; } if (fHidePassed && !fGroupPrinted) { std::cout << fCurGroup << std::endl; fGroupPrinted = true; } if (pass) { puts(COLOR_GREEN "PASS" COLOR_RESET); fTestsPassed++; } else { puts(COLOR_RED "FAIL" COLOR_RESET); fTestsFailed++; } std::cout << ": " << testName << std::endl; } int Tester::done() { std::cout << "Finished: " << std::to_string(fTestsPassed) << " passed, " << std::to_string(fTestsFailed) << " failed." << std::endl; return fTestsFailed; } <|endoftext|>
<commit_before>/* * Copyright (C) 2007 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/oracle/connection.h> #include <tntdb/oracle/statement.h> #include <tntdb/oracle/error.h> #include <tntdb/result.h> #include <tntdb/statement.h> #include <cxxtools/log.h> #include <signal.h> log_define("tntdb.oracle.connection") #ifndef HAVE_SIGHANDLER_T typedef void (*sighandler_t)(int); #endif namespace tntdb { namespace oracle { namespace error { log_define("tntdb.oracle.error") void checkError(OCIError* errhp, sword ret, const char* function) { switch (ret) { case OCI_SUCCESS: break; case OCI_SUCCESS_WITH_INFO: log_warn(function << ": OCI_SUCCESS_WITH_INFO"); break; case OCI_NEED_DATA: log_warn(function << ": OCI_NEED_DATA"); throw Error(errhp, function); case OCI_NO_DATA: log_debug(function << ": OCI_NO_DATA"); throw NotFound(); case OCI_ERROR: throw Error(errhp, function); case OCI_INVALID_HANDLE: log_error("OCI_INVALID_HANDLE"); throw InvalidHandle(function); case OCI_STILL_EXECUTING: log_error("OCI_STILL_EXECUTING"); throw StillExecuting(function); case OCI_CONTINUE: log_error("OCI_CONTINUE"); throw ErrorContinue(function); } } } void Connection::checkError(sword ret, const char* function) const { error::checkError(getErrorHandle(), ret, function); } namespace { class SighandlerSaver { int signum; sighandler_t sighandler; public: explicit SighandlerSaver(int signum_) : signum(signum_) { sighandler = signal(signum, SIG_DFL); } ~SighandlerSaver() { signal(signum, sighandler); } }; } void Connection::logon(const std::string& dblink, const std::string& user, const std::string& password) { log_debug("logon \"" << dblink << "\" user=\"" << user << '"'); // workaround for OCI problem: OCI redirects SIGINT, which causes Ctrl-C to fail SighandlerSaver sighandlerSaver(SIGINT); sword ret; log_debug("create oracle environment"); ret = OCIEnvCreate(&envhp, OCI_OBJECT, 0, 0, 0, 0, 0, 0); if (ret != OCI_SUCCESS) throw Error("cannot create environment handle"); log_debug("environment handle => " << envhp); log_debug("allocate error handle"); ret = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, 0); if (ret != OCI_SUCCESS) throw Error("cannot create error handle"); log_debug("error handle => " << errhp); log_debug("allocate server handle"); ret = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, 0); checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SERVER)"); log_debug("server handle => " << srvhp); log_debug("allocate service handle"); ret = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, 0); checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SVCCTX)"); log_debug("service handle => " << svchp); log_debug("attach to server"); ret = OCIServerAttach(srvhp, errhp, reinterpret_cast<const text*>(dblink.data()), dblink.size(), 0); checkError(ret, "OCIServerAttach"); /* set attribute server context in the service context */ ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, srvhp, 0, OCI_ATTR_SERVER, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_SERVER)"); log_debug("allocate session handle"); ret = OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, (dvoid**)0); checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SESSION)"); /* set username attribute in user session handle */ log_debug("set username attribute in session handle"); ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION, reinterpret_cast<void*>(const_cast<char*>(user.data())), user.size(), OCI_ATTR_USERNAME, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_USERNAME)"); /* set password attribute in user session handle */ ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION, reinterpret_cast<void*>(const_cast<char*>(password.data())), password.size(), OCI_ATTR_PASSWORD, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_PASSWORD)"); /* start session */ log_debug("start session"); ret = OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT); checkError(ret, "OCISessionBegin"); /* set user session attrubte in the service context handle */ ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, usrhp, 0, OCI_ATTR_SESSION, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_SESSION)"); } namespace { std::string extractAttribute(std::string& value, const std::string& key) { std::string::size_type p0 = value.find(key); if (p0 == std::string::npos) return std::string(); if (p0 > 0 && value.at(p0 - 1) != ';') return std::string(); std::string::size_type p1 = value.find(';', p0); if (p1 == std::string::npos) p1 = value.size(); std::string::size_type n = p1 - p0; std::string ret(value, p0 + key.size(), n - key.size()); if (p0 > 0) value.erase(p0 - 1, n + 1); else value.erase(p0, n); return ret; } } Connection::Connection(const char* conninfo_) : envhp(0), srvhp(0), errhp(0), usrhp(0), svchp(0), transactionActive(0) { std::string conninfo(conninfo_); std::string user = extractAttribute(conninfo, "user="); std::string passwd = extractAttribute(conninfo, "passwd="); logon(conninfo, user, passwd); } Connection::~Connection() { if (envhp) { sword ret; clearStatementCache(); try { log_debug("OCISessionEnd"); ret = OCISessionEnd(svchp, errhp, usrhp, OCI_DEFAULT); checkError(ret, "OCISessionEnd"); } catch (const std::exception& e) { log_error(e.what()); } try { log_debug("OCIServerDetach"); ret = OCIServerDetach(srvhp, errhp, OCI_DEFAULT); checkError(ret, "OCIServerDetach"); } catch (const std::exception& e) { log_error(e.what()); } log_debug("OCIHandleFree(" << envhp << ')'); ret = OCIHandleFree(envhp, OCI_HTYPE_ENV); if (ret == OCI_SUCCESS) log_debug("handle released"); else log_error("OCIHandleFree failed"); } } void Connection::beginTransaction() { //log_debug("OCITransStart(" << svchp << ", " << errhp << ')'); //checkError(OCITransStart(svchp, errhp, 10, OCI_TRANS_NEW), "OCITransStart"); ++transactionActive; } void Connection::commitTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("OCITransCommit(" << srvhp << ", " << errhp << ')'); checkError(OCITransCommit(svchp, errhp, OCI_DEFAULT), "OCITransCommit"); } } void Connection::rollbackTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("OCITransRollback(" << srvhp << ", " << errhp << ')'); checkError(OCITransRollback(svchp, errhp, OCI_DEFAULT), "OCITransRollback"); } } Connection::size_type Connection::execute(const std::string& query) { return prepare(query).execute(); } tntdb::Result Connection::select(const std::string& query) { return prepare(query).select(); } Row Connection::selectRow(const std::string& query) { return prepare(query).selectRow(); } Value Connection::selectValue(const std::string& query) { return prepare(query).selectValue(); } tntdb::Statement Connection::prepare(const std::string& query) { return tntdb::Statement(new Statement(this, query)); } void Connection::clearStatementCache() { IStmtCacheConnection::clearStatementCache(); seqStmt.clear(); } bool Connection::ping() { try { checkError(OCIPing(svchp, errhp, OCI_DEFAULT), "OCIPing"); return true; } catch (const Error&) { return false; } } long Connection::lastInsertId(const std::string& name) { tntdb::Statement stmt; SeqStmtType::iterator s = seqStmt.find(name); if (s == seqStmt.end()) { // check for valid sequence name for (std::string::const_iterator it = name.begin(); it != name.end(); ++it) if (! ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || (*it >= '0' && *it <= '9') || *it == '_')) throw Error("invalid sequence name \"" + name + '"'); stmt = prepare( "select " + name + ".currval from dual"); seqStmt[name] = stmt; } else stmt = s->second; long ret; stmt.selectValue().get(ret); return ret; } } } <commit_msg>OCIPing did not work on our oracle server 10.2.0.4.0; replace with OCIServerVersion on oracle before 11<commit_after>/* * Copyright (C) 2007 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/oracle/connection.h> #include <tntdb/oracle/statement.h> #include <tntdb/oracle/error.h> #include <tntdb/result.h> #include <tntdb/statement.h> #include <cxxtools/log.h> #include <signal.h> log_define("tntdb.oracle.connection") #ifndef HAVE_SIGHANDLER_T typedef void (*sighandler_t)(int); #endif namespace tntdb { namespace oracle { namespace error { log_define("tntdb.oracle.error") void checkError(OCIError* errhp, sword ret, const char* function) { switch (ret) { case OCI_SUCCESS: break; case OCI_SUCCESS_WITH_INFO: log_warn(function << ": OCI_SUCCESS_WITH_INFO"); break; case OCI_NEED_DATA: log_warn(function << ": OCI_NEED_DATA"); throw Error(errhp, function); case OCI_NO_DATA: log_debug(function << ": OCI_NO_DATA"); throw NotFound(); case OCI_ERROR: throw Error(errhp, function); case OCI_INVALID_HANDLE: log_error("OCI_INVALID_HANDLE"); throw InvalidHandle(function); case OCI_STILL_EXECUTING: log_error("OCI_STILL_EXECUTING"); throw StillExecuting(function); case OCI_CONTINUE: log_error("OCI_CONTINUE"); throw ErrorContinue(function); } } } void Connection::checkError(sword ret, const char* function) const { error::checkError(getErrorHandle(), ret, function); } namespace { class SighandlerSaver { int signum; sighandler_t sighandler; public: explicit SighandlerSaver(int signum_) : signum(signum_) { sighandler = signal(signum, SIG_DFL); } ~SighandlerSaver() { signal(signum, sighandler); } }; } void Connection::logon(const std::string& dblink, const std::string& user, const std::string& password) { log_debug("logon \"" << dblink << "\" user=\"" << user << '"'); // workaround for OCI problem: OCI redirects SIGINT, which causes Ctrl-C to fail SighandlerSaver sighandlerSaver(SIGINT); sword ret; log_debug("create oracle environment"); ret = OCIEnvCreate(&envhp, OCI_OBJECT, 0, 0, 0, 0, 0, 0); if (ret != OCI_SUCCESS) throw Error("cannot create environment handle"); log_debug("environment handle => " << envhp); log_debug("allocate error handle"); ret = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, 0); if (ret != OCI_SUCCESS) throw Error("cannot create error handle"); log_debug("error handle => " << errhp); log_debug("allocate server handle"); ret = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, 0); checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SERVER)"); log_debug("server handle => " << srvhp); log_debug("allocate service handle"); ret = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, 0); checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SVCCTX)"); log_debug("service handle => " << svchp); log_debug("attach to server"); ret = OCIServerAttach(srvhp, errhp, reinterpret_cast<const text*>(dblink.data()), dblink.size(), 0); checkError(ret, "OCIServerAttach"); /* set attribute server context in the service context */ ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, srvhp, 0, OCI_ATTR_SERVER, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_SERVER)"); log_debug("allocate session handle"); ret = OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, (dvoid**)0); checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SESSION)"); /* set username attribute in user session handle */ log_debug("set username attribute in session handle"); ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION, reinterpret_cast<void*>(const_cast<char*>(user.data())), user.size(), OCI_ATTR_USERNAME, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_USERNAME)"); /* set password attribute in user session handle */ ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION, reinterpret_cast<void*>(const_cast<char*>(password.data())), password.size(), OCI_ATTR_PASSWORD, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_PASSWORD)"); /* start session */ log_debug("start session"); ret = OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT); checkError(ret, "OCISessionBegin"); /* set user session attrubte in the service context handle */ ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, usrhp, 0, OCI_ATTR_SESSION, errhp); checkError(ret, "OCIAttrSet(OCI_ATTR_SESSION)"); } namespace { std::string extractAttribute(std::string& value, const std::string& key) { std::string::size_type p0 = value.find(key); if (p0 == std::string::npos) return std::string(); if (p0 > 0 && value.at(p0 - 1) != ';') return std::string(); std::string::size_type p1 = value.find(';', p0); if (p1 == std::string::npos) p1 = value.size(); std::string::size_type n = p1 - p0; std::string ret(value, p0 + key.size(), n - key.size()); if (p0 > 0) value.erase(p0 - 1, n + 1); else value.erase(p0, n); return ret; } } Connection::Connection(const char* conninfo_) : envhp(0), srvhp(0), errhp(0), usrhp(0), svchp(0), transactionActive(0) { std::string conninfo(conninfo_); std::string user = extractAttribute(conninfo, "user="); std::string passwd = extractAttribute(conninfo, "passwd="); logon(conninfo, user, passwd); } Connection::~Connection() { if (envhp) { sword ret; clearStatementCache(); try { log_debug("OCISessionEnd"); ret = OCISessionEnd(svchp, errhp, usrhp, OCI_DEFAULT); checkError(ret, "OCISessionEnd"); } catch (const std::exception& e) { log_error(e.what()); } try { log_debug("OCIServerDetach"); ret = OCIServerDetach(srvhp, errhp, OCI_DEFAULT); checkError(ret, "OCIServerDetach"); } catch (const std::exception& e) { log_error(e.what()); } log_debug("OCIHandleFree(" << envhp << ')'); ret = OCIHandleFree(envhp, OCI_HTYPE_ENV); if (ret == OCI_SUCCESS) log_debug("handle released"); else log_error("OCIHandleFree failed"); } } void Connection::beginTransaction() { //log_debug("OCITransStart(" << svchp << ", " << errhp << ')'); //checkError(OCITransStart(svchp, errhp, 10, OCI_TRANS_NEW), "OCITransStart"); ++transactionActive; } void Connection::commitTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("OCITransCommit(" << srvhp << ", " << errhp << ')'); checkError(OCITransCommit(svchp, errhp, OCI_DEFAULT), "OCITransCommit"); } } void Connection::rollbackTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("OCITransRollback(" << srvhp << ", " << errhp << ')'); checkError(OCITransRollback(svchp, errhp, OCI_DEFAULT), "OCITransRollback"); } } Connection::size_type Connection::execute(const std::string& query) { return prepare(query).execute(); } tntdb::Result Connection::select(const std::string& query) { return prepare(query).select(); } Row Connection::selectRow(const std::string& query) { return prepare(query).selectRow(); } Value Connection::selectValue(const std::string& query) { return prepare(query).selectValue(); } tntdb::Statement Connection::prepare(const std::string& query) { return tntdb::Statement(new Statement(this, query)); } void Connection::clearStatementCache() { IStmtCacheConnection::clearStatementCache(); seqStmt.clear(); } bool Connection::ping() { try { // OCIPing crashed on oracle 10.2.0.4.0 #if OCI_MAJOR_VERSION >= 11 checkError(OCIPing(svchp, errhp, OCI_DEFAULT), "OCIPing"); #else char version[64]; checkError(OCIServerVersion(svchp, errhp, reinterpret_cast<text*>(version), sizeof(version), OCI_HTYPE_SVCCTX)); log_debug("oracle version " << version); #endif return true; } catch (const Error&) { return false; } } long Connection::lastInsertId(const std::string& name) { tntdb::Statement stmt; SeqStmtType::iterator s = seqStmt.find(name); if (s == seqStmt.end()) { // check for valid sequence name for (std::string::const_iterator it = name.begin(); it != name.end(); ++it) if (! ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || (*it >= '0' && *it <= '9') || *it == '_')) throw Error("invalid sequence name \"" + name + '"'); stmt = prepare( "select " + name + ".currval from dual"); seqStmt[name] = stmt; } else stmt = s->second; long ret; stmt.selectValue().get(ret); return ret; } } } <|endoftext|>
<commit_before>// // draw.cpp // solver // // Created by Nicolas Levy on 08/04/2016. // Copyright © 2016 NicolasPierreLevy. All rights reserved. // #include "solver.hpp" #include "detail/solver.hpp" #include <list> #include <fstream> #include <sstream> #include <string> #include <iostream> #include <boost/algorithm/string.hpp> std::string node_name(int lit) { std::ostringstream name; if (lit < 0) name << "\"-X" << std::abs(lit)<<"\""; else name << "X" << std::abs(lit); return name.str(); } void solver::draw(detail::clause * c, int level, int uip) { std::vector<std::string> edges; std::list<int> todo; std::ofstream graph { "conflict.dot" }; graph << "digraph conflict_graph {\n"; int current = 0; std::string dest; std::string source; std::unordered_set <int> nodes; dest = "conflict"; for (auto && l : c->litterals()) { auto lit = detail::neg(l); source = node_name(new_to_old_lit(lit)); if(m_assignment[detail::var(lit)].level == level) { todo.push_back(lit); graph << " " << source << " -> " << dest <<";\n"; } graph << " " << "conflict [color=red];\n"; } while (!todo.empty()) { current = todo.front(); todo.pop_front(); if (nodes.find(new_to_old_lit(current)) != nodes.end()) continue; auto reason = m_assignment[detail::var(current)].reason; if (reason == nullptr) continue; dest = node_name(new_to_old_lit(current)); for (auto && l : reason->litterals()) { auto lit = detail::neg(l); if (std::abs(new_to_old_lit(lit)) == std::abs(new_to_old_lit(current))) continue; source = node_name(new_to_old_lit(lit)); graph << " " << source << " -> " << dest << ";\n"; if (m_assignment[detail::var(lit)].level == level && lit != detail::neg(uip)) { todo.push_back(lit); graph << " " << source << " [color=blue];\n"; } else if (lit == detail::neg(uip)) { graph << " " << source << " [color=yellow];\n"; } else { graph << " " << source << " [color=purple];\n"; } } nodes.insert(new_to_old_lit(current)); } graph << "}\n"; } void solver::interac(detail::clause * c, int level, int uip) { std::cout << "CONFLICT: entering interactive mode" << std::endl; std::cout << "> "; std::string line; while (std::cin >> line) { boost::algorithm::trim(line); if (line == "g") { draw(c, level, uip); std::cout << "output conflict graph to conflict.dot" << std::endl; } else if (line == "c") break; else if (line == "t") { m_cdcl = cdcl_mode::NORMAL; break; } else std::cout << "unkown command `" << line << "`" << std::endl; std::cout << "> "; } } <commit_msg>Improve graph readability<commit_after>// // draw.cpp // solver // // Created by Nicolas Levy on 08/04/2016. // Copyright © 2016 NicolasPierreLevy. All rights reserved. // #include "solver.hpp" #include "detail/solver.hpp" #include <list> #include <fstream> #include <sstream> #include <string> #include <iostream> #include <boost/algorithm/string.hpp> std::string node_name(int lit) { std::ostringstream name; if (lit < 0) name << "\"-X" << std::abs(lit)<<"\""; else name << "X" << std::abs(lit); return name.str(); } void solver::draw(detail::clause * c, int level, int uip) { std::vector<std::string> edges; std::list<int> todo; std::ofstream graph { "conflict.dot" }; graph << "digraph conflict_graph {\n"; int current = 0; std::string dest; std::string source; std::unordered_set <int> nodes; dest = "conflict"; for (auto && l : c->litterals()) { auto lit = detail::neg(l); source = node_name(new_to_old_lit(lit)); if(m_assignment[detail::var(lit)].level == level) { todo.push_back(lit); graph << " " << source << " -> " << dest <<";\n"; graph << " " << source << " [style=filled, fillcolor=blue];\n"; } else { graph << " " << source << " -> " << dest <<";\n"; graph << " " << source << " [style=filled, fillcolor=purple];\n"; } graph << " " << "conflict [style=filled, fillcolor=red];\n"; } while (!todo.empty()) { current = todo.front(); todo.pop_front(); if (nodes.find(new_to_old_lit(current)) != nodes.end()) continue; auto reason = m_assignment[detail::var(current)].reason; if (reason == nullptr) continue; dest = node_name(new_to_old_lit(current)); for (auto && l : reason->litterals()) { auto lit = detail::neg(l); if (std::abs(new_to_old_lit(lit)) == std::abs(new_to_old_lit(current))) continue; source = node_name(new_to_old_lit(lit)); graph << " " << source << " -> " << dest << ";\n"; if (m_assignment[detail::var(lit)].level == level && lit != detail::neg(uip)) { todo.push_back(lit); graph << " " << source << " [style=filled, fillcolor=blue];\n"; } else if (lit == detail::neg(uip)) { graph << " " << source << " [style=filled, fillcolor=yellow];\n"; } else { graph << " " << source << " [style=filled, fillcolor=purple];\n"; } } nodes.insert(new_to_old_lit(current)); } graph << "}\n"; } void solver::interac(detail::clause * c, int level, int uip) { std::cout << "CONFLICT: entering interactive mode" << std::endl; std::cout << "> "; std::string line; while (std::cin >> line) { boost::algorithm::trim(line); if (line == "g") { draw(c, level, uip); std::cout << "output conflict graph to conflict.dot" << std::endl; } else if (line == "c") break; else if (line == "t") { m_cdcl = cdcl_mode::NORMAL; break; } else std::cout << "unkown command `" << line << "`" << std::endl; std::cout << "> "; } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include <boost/python.hpp> #include "IECore/MotionPrimitive.h" #include "IECore/bindings/MotionPrimitiveBinding.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/RunTimeTypedBinding.h" using namespace boost::python; namespace IECore { static unsigned int len( MotionPrimitive &p ) { return p.snapshots().size(); } static PrimitivePtr getItem( MotionPrimitive &p, float t ) { MotionPrimitive::SnapshotMap::const_iterator it = p.snapshots().find( t ); if( it==p.snapshots().end() ) { throw std::out_of_range( "Bad index" ); } return it->second; } static void setItem( MotionPrimitive &p, float t, const PrimitivePtr v ) { p.snapshots()[t] = v; } static bool contains( MotionPrimitive &p, float t ) { return p.snapshots().find( t )!=p.snapshots().end(); } static void delItem( MotionPrimitive &p, float t ) { MotionPrimitive::SnapshotMap::iterator it = p.snapshots().find( t ); if( it==p.snapshots().end() ) { throw std::out_of_range( "Bad index" ); } p.snapshots().erase( it ); } static boost::python::list keys( MotionPrimitive &p ) { boost::python::list result; const MotionPrimitive::SnapshotMap &s = p.snapshots(); MotionPrimitive::SnapshotMap::const_iterator it; for( it = s.begin(); it!=s.end(); it++ ) { result.append( it->first ); } return result; } static boost::python::list values( MotionPrimitive &p ) { boost::python::list result; const MotionPrimitive::SnapshotMap &s = p.snapshots(); MotionPrimitive::SnapshotMap::const_iterator it; for( it = s.begin(); it!=s.end(); it++ ) { result.append( it->second ); } return result; } void bindMotionPrimitive() { typedef class_< MotionPrimitive, MotionPrimitivePtr, bases<Renderable>, boost::noncopyable > MotionPrimitivePyClass; MotionPrimitivePyClass( "MotionPrimitive" ) .def( "__len__", &len ) .def( "__getitem__", &getItem ) .def( "__setitem__", &setItem ) .def( "__delitem__", &delItem ) .def( "__contains__", &contains ) .def( "keys", &keys ) .def( "values", &values ) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS(MotionPrimitive) ; INTRUSIVE_PTR_PATCH( MotionPrimitive, MotionPrimitivePyClass ); implicitly_convertible<MotionPrimitivePtr, RenderablePtr>(); } } <commit_msg>Corrected base class.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include <boost/python.hpp> #include "IECore/MotionPrimitive.h" #include "IECore/bindings/MotionPrimitiveBinding.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/RunTimeTypedBinding.h" using namespace boost::python; namespace IECore { static unsigned int len( MotionPrimitive &p ) { return p.snapshots().size(); } static PrimitivePtr getItem( MotionPrimitive &p, float t ) { MotionPrimitive::SnapshotMap::const_iterator it = p.snapshots().find( t ); if( it==p.snapshots().end() ) { throw std::out_of_range( "Bad index" ); } return it->second; } static void setItem( MotionPrimitive &p, float t, const PrimitivePtr v ) { p.snapshots()[t] = v; } static bool contains( MotionPrimitive &p, float t ) { return p.snapshots().find( t )!=p.snapshots().end(); } static void delItem( MotionPrimitive &p, float t ) { MotionPrimitive::SnapshotMap::iterator it = p.snapshots().find( t ); if( it==p.snapshots().end() ) { throw std::out_of_range( "Bad index" ); } p.snapshots().erase( it ); } static boost::python::list keys( MotionPrimitive &p ) { boost::python::list result; const MotionPrimitive::SnapshotMap &s = p.snapshots(); MotionPrimitive::SnapshotMap::const_iterator it; for( it = s.begin(); it!=s.end(); it++ ) { result.append( it->first ); } return result; } static boost::python::list values( MotionPrimitive &p ) { boost::python::list result; const MotionPrimitive::SnapshotMap &s = p.snapshots(); MotionPrimitive::SnapshotMap::const_iterator it; for( it = s.begin(); it!=s.end(); it++ ) { result.append( it->second ); } return result; } void bindMotionPrimitive() { typedef class_< MotionPrimitive, MotionPrimitivePtr, bases<VisibleRenderable>, boost::noncopyable > MotionPrimitivePyClass; MotionPrimitivePyClass( "MotionPrimitive" ) .def( "__len__", &len ) .def( "__getitem__", &getItem ) .def( "__setitem__", &setItem ) .def( "__delitem__", &delItem ) .def( "__contains__", &contains ) .def( "keys", &keys ) .def( "values", &values ) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS(MotionPrimitive) ; INTRUSIVE_PTR_PATCH( MotionPrimitive, MotionPrimitivePyClass ); implicitly_convertible<MotionPrimitivePtr, RenderablePtr>(); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2013, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreHoudini/ToHoudiniPointsConverter.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniPointsConverter ); ToHoudiniGeometryConverter::Description<ToHoudiniPointsConverter> ToHoudiniPointsConverter::m_description( PointsPrimitiveTypeId ); ToHoudiniPointsConverter::ToHoudiniPointsConverter( const VisibleRenderable *renderable ) : ToHoudiniGeometryConverter( renderable, "Converts an IECore::PointsPrimitive to a Houdini GU_Detail." ) { } ToHoudiniPointsConverter::~ToHoudiniPointsConverter() { } bool ToHoudiniPointsConverter::doConversion( const VisibleRenderable *renderable, GU_Detail *geo ) const { const PointsPrimitive *points = static_cast<const PointsPrimitive *>( renderable ); if ( !points ) { return false; } const IECore::V3fVectorData *positions = points->variableData<V3fVectorData>( "P" ); if ( !positions ) { // accept "position" so we can convert the results of the PDCParticleReader without having to rename things /// \todo: Consider making the ParticleReader create a P if it doesn't exist for Cortex 6. positions = points->variableData<V3fVectorData>( "position" ); } GA_Range newPoints = appendPoints( geo, points->getNumPoints() ); if ( !newPoints.isValid() || newPoints.empty() ) { return false; } transferAttribs( geo, newPoints, GA_Range() ); return true; } void ToHoudiniPointsConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const { const Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() ); if ( primitive ) { transferAttribValues( primitive, geo, points, prims, PrimitiveVariable::Vertex, PrimitiveVariable::Vertex ); } } <commit_msg>Removing code that wasn't doing anything<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2013, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreHoudini/ToHoudiniPointsConverter.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniPointsConverter ); ToHoudiniGeometryConverter::Description<ToHoudiniPointsConverter> ToHoudiniPointsConverter::m_description( PointsPrimitiveTypeId ); ToHoudiniPointsConverter::ToHoudiniPointsConverter( const VisibleRenderable *renderable ) : ToHoudiniGeometryConverter( renderable, "Converts an IECore::PointsPrimitive to a Houdini GU_Detail." ) { } ToHoudiniPointsConverter::~ToHoudiniPointsConverter() { } bool ToHoudiniPointsConverter::doConversion( const VisibleRenderable *renderable, GU_Detail *geo ) const { const PointsPrimitive *points = static_cast<const PointsPrimitive *>( renderable ); if ( !points ) { return false; } GA_Range newPoints = appendPoints( geo, points->getNumPoints() ); if ( !newPoints.isValid() || newPoints.empty() ) { return false; } transferAttribs( geo, newPoints, GA_Range() ); return true; } void ToHoudiniPointsConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const { const Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() ); if ( primitive ) { transferAttribValues( primitive, geo, points, prims, PrimitiveVariable::Vertex, PrimitiveVariable::Vertex ); } } <|endoftext|>